Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team train: the six remaining team changes, merged once (#5248)
Milind Soni9d6678adcaf6
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 82fd150b5b..73786c8ec5 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -32,8 +32,8 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes tthe team (or are removed), your private chats and everything only yours there are deleted, never handed to an admin(below). The Owner's export of the team's machine (the workspace backup, `OMB_CLOUD_EXPORT_ONLY`) leaves them out too(`server/workspace-backup-team-private.ts`): no private conversation, none of its work folders or files only it used, no- member's memory layer, no member's own MausBot, their inbox or anything under `people/`. Restoring such an export gives a- team back everything but those.+ routine that lives in one nor any run that names one, no member's memory layer, no member's own MausBot, their inbox+ or anything under `people/`. Restoring such an export gives a team back everything but those.- **The order of bots.** Each User's list of bots is in their own order (`bot-orders.json`): their reorder (`PUT/api/bots/order`, any level, Can view included) changes only their list and reaches only their streams. Whoever hasnever ordered theirs sees the team's order, which an Owner's or Admin's reorder sets: an admin's order is the team's,@@ -88,8 +88,8 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes twith no conversation named (a phone) it is the person's own. Every Chrome runs in its own box (below).- **Phones.** Settings → *Open on your phone* (and *Connect your phone* in the account menu) shows a code made for theperson signed in. The phone app scans it as any `/pair#code=` link and gets that person's session: their address,- their role, their chats, never another member's. The phone stays signed in while the person's app keeps checking in- with the Admin (it does so while the team is open in it) and ends within the hour after the last check. Under the code,+ their role, their chats, never another member's. The phone stays signed in while it is used: the Cloud's roster check+ (below, "Signed in without a desktop") asks the Admin about its person, as the desktop's re-pairing always did. Under the code,*Paired devices* lists the phones those codes opened as *device · member* (`GET /api/team/phones`): a member sees theirown, the Super admin and Admins every member's. **Remove** (`DELETE /api/team/phones/<id>`, the same rule) signs thatphone out at once and closes its open streams; the app windows the Admin signs in are not listed there.@@ -104,6 +104,40 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes tsession across a restart; a My Cloud revokes every session that is not its owner's at each boot.+- **In a browser, with nothing installed.** The join page's Open <team> (and a User's team home on MausBot Cloud) signs the+ browser in here as that person, at their role: the Admin's browser sign-in with their member claim, "Open Acme as+ <address>" and one Continue (`/pair#signin=`, BrowserSignInPage). The browser is the same app, at phone width too.+ When its session ends, the sign-in page offers "Open Acme with MausBot Cloud": the person's team page there, which their+ signed-in session told this browser (`/api/auth/session` `teamSignIn`, kept in the browser); never told before sign-in.+ With the team's rule turning remote access off, a User's browser sign-in is refused (`remote_access_off`) and their open+ browsers sign out with their phones (`closeMemberBrowsers`); an Owner's and an Admin's stay, since their admin pages+ open in a browser and the rule is theirs to change.+- **The first screen.** A User's first time in the team (TeamWelcome): "Welcome to Acme", who invited them (the Admin's+ `member.invitedBy`, named from the people list), who else is in it with their pictures, the bots shared with them with one+ line each, the privacy sentence (said here, so the first private chat doesn't say it again) and one action, Start a chat+ with the first bot they can chat with. Shown once per person, in the app or a browser: kept in+ `people/<person>/welcome.json` (`GET /api/me` `welcome: { invitedBy, welcomedAt, hints }`, `PUT /api/me/welcome {+ welcomed: true }`). Admins get the Cloud's own welcome; on a team its own record (shown, done, hidden:+ `TEAM_PERSONAL_HINTS`) is each person's too, kept in the same file, so one admin finishing it ends it for nobody else+ (the Owner also keeps what the team's record said before). The Owner's last step offers Invite people, the team's People+ page on MausBot Cloud.++### Signed in without a desktop++Every 5 minutes (give or take a minute) the Team Cloud asks the Admin about everyone with a team session used in the last+hour (`server/cloud-team-roster.ts`): `POST <Admin>/api/cloud/machines/team-member { v: 1, emails }`, at most 50, signed+with the bootstrap secret in its own context (`teamRosterSignature`). The answer is each address's role now, or null.++- **Someone removed, or whose role changed**, is signed out at that check, within about 6 minutes, even without the Admin's+ `member-left` (which ends their sessions at once). A role in the answer never upgrades a session: the old role's ends.+- **A session in use** ends no sooner than an hour after its last use while the Admin keeps finding its person in the team+ (`vouchMember`: a phone's `memberCheckedAt`, anyone else's `vouchedAt`), so a browser or a phone stays signed in with no+ desktop.+- **An unused session** still ends within the hour of its last use (at most an hour after it opened, if never used),+ however much the same person uses another device: only a session itself used within the hour is ever kept.+- No answer, a refusal or an older Admin (404) changes nothing, and a deleted team's Cloud is told nothing (404). A+ script's token and a move-in sign-in end as they were made to.+### Off a teamEveryone has an Inbox: on a personal Cloud and in the desktop app with no account, the same row at the top of the sidebar@@ -297,19 +331,24 @@ The Admin signs the usual pairing body with two more fields:The session carries `teamRole` and `membershipAuthority: "team"`: the sign-in list never revalidates or revokes it, and`/api/auth/session` answers `team: { id, name, role }`.-**Membership lives on the Admin.** No roster read exists, so the machine checks membership at each pairing, which the-Admin signs only for a current member. A team session therefore ends within the hour of its pairing-(`TEAM_SESSION_MAX_MS`), however much it is used, and the app pairs again; a removed member's next pairing is refused by-the Admin (404). A session is also kept only across a clean restart.+**Membership lives on the Admin.** The machine checks membership at each pairing, which the Admin signs only for a current+member, and through its roster check ("Signed in without a desktop"). A team session therefore ends within the hour of the+Admin's last word about its member and within the hour of its own last use (`TEAM_SESSION_MAX_MS`); a removed member's next+pairing is refused by the Admin (404).+A session is also kept only across a clean restart.++`member.invitedBy` (optional): who invited this member, by address. Kept for their welcome the first time it is said;+a member's own request never sets it.**When someone leaves.** The Admin tells the machine when a member is removed or leaves: `POST/api/cloud/team/member-left` with `{ "email": "<address>" }`, signed with its body like the sleep request (400`invalid_member` for a bad address; only on a Team Cloud). The machine then deletes what was that person's alone and-answers `{ ok, chats, layers, sessions, files, browsers, bots }`: every session and phone of theirs and any open code of-theirs end at once; their own MausBot is deleted as the app deletes a bot, with its chats and notes (`bots`, its chats-counted in `chats`), and should they join again they get a new one; their private chats with every bot are deleted as-the app deletes a conversation (messages, notifications, follow-ups, a running turn stopped first), with the uploaded-files only those chats used and every file they uploaded that nothing uses (a file they took off a message before+answers `{ ok, chats, layers, sessions, files, browsers, bots, routines, routinesHandedOver, botsHandedBack }`: every+session and phone of theirs and any open code of theirs end at once; their own MausBot is deleted as the app deletes a+bot, with its chats and notes (`bots`, its chats counted in `chats`), and should they join again they get a new one;+their private chats with every bot are deleted as the app deletes a conversation (messages, notifications, follow-ups,+a running turn stopped first), with the routines that live in them (`routines`, below "Routines"), the uploaded files+only those chats and routines used and every file they uploaded that nothing uses (a file they took off a message beforesending goes at once: `DELETE /api/attachments/<name>`, its uploader only, while nothing uses it); their memorylayers (`workspaces/<bot>--member-<person>`, their journal and search index); their "About you" and profile(`people/<person>/`); their own connections, keys and MCP sign-ins; and their own browser of every bot and shared@@ -317,6 +356,16 @@ profile. Nothing of it is handed to an admin. Each conversation keeps its starterecord that still names it (a usage trace, an activity row) stays theirs and no admin reads it there. An export of theirown chats before they go is not built.+What they did for the team stays, without them. A routine they wrote for a shared place (a bot, a group chat) keeps+running as the routine of whoever looks after its bot now, or nobody's when nobody does, whose asks go to the Admins+(`routinesHandedOver`); one that reported into a chat of theirs gets a chat of its new owner's. Each is one admin+activity row, *Handed a routine over*, naming the routine and its new owner. They come off every bot's sharing+(`access.people` and `visibility`, an `@domain` entry kept) and "Looked after by": a bot they looked after, by+`reportsTo` or as its creator, is nobody's and falls to the Admins (`botsHandedBack`); a Chief that would then be its+department's second gives up its crown. So joining again restores nothing: they start as a new member. One more row,+*Left the team*, names who left and when, with `botsHandedBack` and `routinesHandedOver` and nothing of what was+theirs alone.+**A member's own code (their phone).** `POST /api/team/phone-pairing` (any team session, Member included) makes a pairingcode carrying the caller's `member` claim (address, role, the role's scopes) and the time the Admin last vouched forthem; on a Team Cloud `POST /api/auth/pairing` does the same for an admin session, so no team session makes a bare@@ -334,7 +383,7 @@ Everything stored on a Team Cloud carries an audience (`server/audience.ts`):|---|---|---|| `team` | everyone who sees the bot | a bot's main chat, its own folder (`workspaces/<bot>`: MEMORY.md, memory/, skills), team files, routines nobody opened || `room:<id>` | whoever sees the room | the room's threads, `workspaces/<bot>--room-<id>` |-| `member:<person>` | that person only (never an Admin) | the conversations they opened (`thread-starters.json`), `workspaces/<bot>--member-<person>`, their uploads, `people/<person>/about.json` |+| `member:<person>` | that person only (never an Admin) | the conversations they opened (`thread-starters.json`), `workspaces/<bot>--member-<person>`, their uploads, `people/<person>/about.json`, the routines that live in their private chats (below, "Routines") |**A turn reads only inputs whose audience includes everyone who will see its answer, and writes only into its ownaudience.** `mayRead(input, turn)` is true for the team's things and for the turn's own audience, nothing else.@@ -419,6 +468,30 @@ On a My Cloud and on a desktop there is one person: every audience is the team'severy browser keeps its old name and Chrome its old launcher, every engine keeps the server's HOME, and nothing herechanges what those do.+## Routines++A routine lives where it was made or where it reports (`server/routine-home.ts`). One for a member's own MausBot, or that+names someone's private chat (the chat a bot made it in, `sourceThreadId`, or the one it reports into,+`resultsThreadId`), is that person's alone, as the chat is: no other member and no Admin, the Super admin included, sees+it or learns of it, in `GET /api/routines`, the `routine` and `routine.run` frames, a bot's overview, the Today counts, a+team export or backup, the Owner's whole-machine export, or a bot's `trigger_info` and `trigger` tools in any other+conversation; naming it by id (to change, run or delete it) answers 404 *no such routine*, and a file only such a+routine carries is refused as one that does not exist. Every other routine is its place's (the bot's shared chat, or a+group chat): whoever sees that place sees it, without the id of a conversation they may not read.++**Its results follow where it lives** (`server/host/team-routines.ts`). A private routine's runs open their+conversations as its person and report into a chat of theirs. A routine of a shared place opens its runs as the team,+whoever made it or runs it (the schedule, its writer or an Admin), and reports into the shared chat or into a results+chat of its own that everyone who reads the place reads; its asks go to whoever looks after the bot, or the Admins. The+routine form on a team offers two places: **Just me** (`resultsThreadId: "just-me"`, the person's own private chat with+the bot, or a new one named for the routine) and **Shared chat** (the bot's main chat); anyone who can chat with the bot+may choose either, and an older app's "The bot's main thread" (`null`) is the shared place's own results chat. A routine+that reports into a chat whose audience is not its own, such as one made before this for the shared chat whose results+chat was opened privately for its writer, gets a results chat of its own place at its next run; the old chat stays+where it is, unchanged. The chat a routine opened for its own results does not make it anyone's until they write in it.+The routine picker lists only the bots the person can chat with and never a teammate's own MausBot, which takes no+routine from anyone else (404 *no such bot*).+## The shared chat's nameA team bot's main chat is called *"Shared chat"* on every person's copy (`WireTask.sharedChat`), whatever its stored title,@@ -459,15 +532,26 @@ private chat goes to that person instead), and it retries their threads and chanchat with it is their inbox (below). A crowned bot nobody owns stays its department's Chief, as on any other server.The app offers no crown on a team, so this is reached only through the API (`PATCH /api/bots/<id>` with `chiefOfStaff`).-**A member's MausBot is not crowned.** It is theirs alone, and the audience rule below keeps a bot only one person sees-from reaching a bot everyone sees (`sameAudience`), so today it cannot hand work to the team's shared bots.+**A person's MausBot hands work to the bots they can use.** A member's MausBot is not crowned and has no authority over any+bot, but from a chat private to its person, with their own request behind the turn, it can hand work to any team bot that+person may chat with, at their level (`server/host/personal-reach.ts`): the receiving bot reads it as `[From @MausBot (bot)+· assignment … for Mira · on their behalf at your level]`. The work runs in that bot's own private chat with the person,+exactly as if they had opened it themselves: it is created private to them before anyone's app hears of it, reads and+writes their layer, and comes back whole to the chat they asked in. Nothing of it reaches the bot's shared chat, a room,+the team's notes, another member or an admin, in lists, counts, search, notifications or streams. It never widens what the+person could do: a bot they cannot see is never named to their MausBot (by name or id it is refused exactly like a bot that+does not exist, and it is never counted), and a bot they can only view is refused. A routine, a relayed line, an event, a+guest and another person's words can't use this, and it can answer a waiting question only in that person's own chats.+The same holds for an Owner's or Admin's MausBot, which reaches every bot but other people's MausBots. Nothing reaches a+person's MausBot from outside it: no other bot is told of it.**Every bot reaches every bot.** Departments are folders, not walls. Any bot can ask, hand work to or @mention anyother bot on the team, in any department, someone's Chief included, with nothing to set up (`canReach` in`server/peer-roster.ts`). Each bot's roster lists them all, its own department first; a Chief's lists its own teamfirst and everyone else as reachable. Reaching a bot gives no authority over it: supervision, incidents, the inbox,setup changes and automations follow ownership and departments as above (`hasAuthority`, `canManage`). Only two-things narrow reach: archived bots, and the audience rule below (a bot shared with different people). A turn in someone's+things narrow reach: archived bots, and the audience rule below (a bot shared with different people; a person's own MausBot is the+one exception, above). A turn in someone'sprivate chat may ask any bot, and the work it hands on stays in that person's audience; it never hands work into a roomor posts in one.@@ -496,8 +580,8 @@ listed.|---|---|| No access | Nothing: the bot is not listed for them, and every route naming it, its conversations, its rooms, routines and files answers 404 as for one that does not exist || Can view | See the bot, its main chat and the conversations shared with them (rooms, their own earlier chats), read only; open them and mark them read |-| Can chat | Also write to it, start their own conversations, answer its cards, react, stop it, write in its rooms, run its routines and make routines for it (and change or delete their own) |-| Can edit | Also change its instructions, profile and model, which of the team's connected apps and MCP servers it uses, any of its routines, its sharing, and approve a card that changes the bot itself (instructions, model, skills, team, triggers) |+| Can chat | Also write to it, start their own conversations, answer its cards, react, stop a run they asked for (or one no person asked for; below, "Whoever asked owns the run"), write in its rooms, run its routines and make routines for it (and change or delete their own) |+| Can edit | Also change its instructions, profile and model, which of the team's connected apps and MCP servers it uses, any of its routines but those in someone else's private chat, its sharing, and approve a card that changes the bot itself (instructions, model, skills, team, triggers) |Can edit never reaches what only an admin sets on any bot: what it may do on its computer (approval level, alwaysallow, folders), where it runs, its department, whom it answers to or directs, connecting an app or making a webhook.@@ -547,6 +631,44 @@ allow, folders), where it runs, its department, whom it answers to or directs, cNot now changes nothing and tells nobody; they can ask again. The card is a set-answer question card(`card.accessRequest`), shown in each person's language, and its answer is always its own option.+## Whoever asked owns the run++In a conversation more than one person reads (a bot's shared chats, a conversation opened from one, a group chat), a+run belongs to the person whose own request it answers (`server/host/run-owner.ts`, the one place that decides):++- **Someone else's line waits its turn.** Sent while Priya's request runs, Tom's line never reaches her run, never stops+ it and never cuts it short to be answered first: it waits in the queue and runs after hers, as its own turn, with his+ name on it. The send answers `{ queued: true, queueId }`. Lines from different people never join one turn; a run of+ one person's lines does, as before. Priya adding to her own request is steered into it and, after a step has run a+ minute with her line unread, answered first (`server/host/person-first.ts`), exactly as in a private chat; her own+ line goes ahead of anyone else's waiting.+- **Everyone there sees the queue.** Each waiting line carries its writer (`BotQueuedMessages[…].sender`) and the+ conversation, while it works, the person whose request runs (`WireTask.askedBy`). The app's working line reads+ "Working on Priya's request", with one quiet line under it, "Next: Tom's request" ("…, then 2 more" when more wait);+ someone whose own message waits also sees its words there ("Yours: …") with a small remove control, which nobody else+ sees; that chat shows no queue above the composer. A person is named as the People list names them: their name, or+ for an address the part before the @ ("Dev's request" for [email protected]).+ Only its writer removes a waiting line (`DELETE+ /api/bots/<bot>/queue/<id>`; a line no person wrote, an Owner or Admin), and waiting lines join the running request+ (`…/steer`) only when every one is the asker's own and the asker adds them; otherwise 403 in plain words.+- **Only the asker, or an Owner or Admin, stops it.** Stop (`POST /api/bots/<bot>/interrupt`, a group chat's+ `/api/groups/<id>/interrupt`, a typed "stop", a guarded request's `/interrupt`) from anyone else answers 403 with+ `code: "stop_not_yours"` and *"Only Priya or an admin can stop this."*; their "@Scout stop" in a group chat is an+ ordinary line there. Stop stays the only interrupt. The app shows Stop, and Retry on a stopped request, only to the+ asker and to Owners and Admins (and to everyone for a run no person asked for). The stopped row records who pressed+ Stop (`WireMessage.stoppedBy`): it reads "Maya stopped this." to everyone else and "You stopped this." to Maya.+- **Who asked, for what is not a person's line** (read from the records the provenance labels come from, never from+ model text). A routine, a webhook and an app's event never run in a person's conversation: each runs in its own and+ leaves one report line, held while a turn runs and written before the queue behind it moves+ ([automation-reports.md](verification/automation-reports.md)); none steers or stops anyone's run. Work a bot hands on+ for a person (`[… · on their behalf at your level]`) is that person's run. A line sent through the API, one another+ app relays, a bot's message and its report (*information only*) are nobody's request: they wait like anyone else's+ line, a run they start is nobody's and anyone who may chat stops it, and a person's line waits behind such a run only+ until it ends, ahead of any bot or app line still waiting.++A private chat, a personal install and a My Cloud have one person: none of this applies there, and an older app, which+reads neither field, simply shows no names on the queue.+## A team with no AIUntil someone connects an AI, a bot has nothing to answer with. A Send from a User comes back as `409` with `code: "no_ai"`:@@ -698,9 +820,33 @@ A private chat shows none of it. Nothing says when someone was last here, and noapp 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.+## When you are away++A member who has no live stream on the team (no app or phone open on it) is away, and three things reach them by one+email, which the Admin sends (openmaus-cloud docs/team-cloud.md "When you are away"): a teammate or bot mentioned them+or passed them a message; a question, approval or sign-in waits on their answer (routed to them, or in their own private+chat) for at least 5 minutes; work they asked for in a shared chat or group chat, or a routine's report routed to them,+finished or failed. The first thing opens a 10-minute window and everything in it goes in one email; finished work is+left out when a question or mention from the same conversation is in it, and is told once per conversation per stretch+away. At least 30 minutes between two emails, at most 6 a day, and never the same thing twice. Coming back before it+goes, answering, or opening the line drops it. `server/host/team-away.ts` decides; `team-away-events.ts` says what is+worth one; "away" is one function (`here`) so presence can replace it.++What leaves the machine is `POST /api/cloud/machines/team-away`, signed with the bootstrap secret (`omb-team-away-v1`):+`{ v: 1, notices: [{ id, to, language?, items: [{ kind: "mention" | "waiting" | "finished" | "failed", key, who?, place?,+routine?, private? }], more? }], prefs?: [{ to, on }] }`. `key` is a SHA-256 of what it is about; `who` a teammate's or+bot's name; `place` a group chat's or the bot's name. Never a message's words, a title or an id. From someone's private+chat an item names no bot and no place (`private: true`; a teammate who wrote to you is named). Each person turns these+off with "Email me when I'm away" under Settings → General (a row of Account in Simple, in Profile in Advanced; `GET`/`PUT+/api/me/away-emails`, kept in `people/<person>/away-emails.json`, which leaving deletes) or with the email's stop link; the+Admin's answer lists who is off, and the switch follows. An older Admin's 404 pauses asking for an hour. The email's button+opens the team's page on the Cloud site (`/cloud/team/<id>`), not a chat. Nothing of this runs off a team.## What is not closed here+- **A group chat's waiting lines.** A group chat queues every line while it works, and only the asker or an admin stops+ it, but its queue is still shown only to each line's own writer.+- **Saved logins per member.** A login saved from a sign-in card is the team's (an Admin saves it, for every bot in theteam); per-member saved logins are not built. Sign-ins a member makes in their own browser stay in it (above).- **The new browser engine and temporary browsers in a box.** The new engine (`browserEngine.engine: "chrome"`, off by@@ -708,8 +854,8 @@ On a My Cloud and on a desktop there is one person: no People list, no presence,into it is not reachable from its box.- **Per-member engine sign-ins.** Every audience's engine signs in as the team (its key through the broker, or theteam'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 the- hour, and nothing is deleted.+- **Removal without `member-left`.** Without the Admin's `member-left` request (above), removal takes effect at the next+ roster check (about 6 minutes), and nothing is deleted, handed over or taken off a bot.- **Someone invited who never opened the team.** The machine first learns of a member at their first pairing, so untilthen they are in no People list, and nothing says they joined (`team.people`): the Admin sends no roster and no"joined" of its own.@@ -720,9 +866,24 @@ On a My Cloud and on a desktop there is one person: no People list, no presence,- **An engine that replaces its sign-in file by renaming.** Inside a box the rename is refused (the team's file is boundthere); an engine that does not then write in place keeps a refreshed token for that process only.- **What a bot keeps per bot, not per audience.** Its data sheet, the skills it stages and its own profile are the bot's- (the team's), whichever chat wrote them; so are a routine's definition and schedule (its runs and results are the- conversation's). The Owner's whole-machine export leaves every member's private chats out (above), the Owner's own too: an- export is the team's, never anyone's alone.+ (the team's), whichever chat wrote them; a routine is its place's (above, "Routines"). The Owner's whole-machine+ export leaves every member's private chats out (above), the Owner's own too: an export is the team's, never anyone's+ alone.- **Own apps with the team's own Composio project.** A member's own apps always use OpenMausBot's connected-appsservice, even when the team connected a Composio project key of its own; an app that needs the project's own authconfig can't be connected by each person.++## The desktop app and a team it was invited to++- **`openmausbot://team/<team id>`** (the join page's Open in the MausBot app; `electron/team-join.mjs`): the id only. Main+ opens the team as the verified session lists it: signed in as the same address it reads the session again at once and+ opens the team; signed out it starts its own browser sign-in and opens the team once signed in; signed in as someone+ the team isn't listed for, main's own dialog says so and offers to sign in with another address (Add another account:+ the one in use stays signed in). A link left waiting is dropped after 30 minutes. `openmausbot://cloud` is unchanged.+- **Landing** (`landing` in the Admin's session: no Cloud of the account's own, invited into a team): the window moves to the+ team only on a sign-in this app just saw, the first on this device (`team-landing.json` keeps the accounts signed in here+ and the teams opened here), with no place of the person's own on screen (My Cloud, a remembered place); then once. Any+ other time, the team is in the rail and the window stays. No plan is pushed meanwhile: no trial card, no Start free trial+ in Settings (`cloudPlanView` `invited`).+- A sign-in the link started that finishes as an address the team isn't listed for says so, with the way to sign in with+ the other address, never nothing.diff --git a/docs/verification/chat-turns.md b/docs/verification/chat-turns.mdindex 51da65a139..f3150f0602 100644--- a/docs/verification/chat-turns.md+++ b/docs/verification/chat-turns.md@@ -274,6 +274,20 @@ was stopped 1.5 s after the steered question, and the fake engine answered thequestion in the next turn. With the steered message's watch removed, thequestion stayed unanswered for 30 s and the test failed.+## Several people in one shared chat++```sh+pnpm exec vitest run server/cloud-team-asker-owns.e2e.test.ts server/host/run-owner.test.ts src/components/SharedQueueLine.test.ts+```++On a Team Cloud, whoever asked owns the run ([team-cloud.md](../team-cloud.md#whoever-asked-owns-the-run)). The+e2e test pairs an Owner and three members, holds Priya's request in the same scripted CI poll, and checks with+`OMB_PERSON_FIRST_MS=1500`: Tom's line is queued (never steered, never cut short to be answered first) and runs after+hers as his own turn; everyone sees the waiting lines with their writers, in order; only a line's writer removes it+and nobody joins someone else's run; Tom's Stop and typed stop answer 403 "Only Priya or an admin can stop this.",+while Priya and the Owner stop it; Priya's own addition is steered and answered first, in the shared chat and in her+private chat; and a routine run started mid-run leaves its report between her answer and Tom's line.+## Threads of one bot at the same timeDifferent threads of one bot run at once. A saved `threads.maxConcurrentPerBot` sets how many. With none saved, a Clouddiff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mtsindex 00a19b0e99..c967a6e149 100644--- a/electron/cloud-account.d.mts+++ b/electron/cloud-account.d.mts@@ -24,6 +24,9 @@ export interface CloudAccountState {machine?: import("./cloud-home.mjs").CloudMachine;/** Connected: the teams this account is in, each with its Cloud; absent while it is in none. */teams?: import("./cloud-home.mjs").CloudTeam[];+ /** Connected, with no Cloud of the account's own: the team it was invited into, which opens first, before any plan is+ * offered (the Admin's `landing`). */+ landing?: { teamId: string };/** Connected to an Admin that lists every Cloud of the person's (contract v1 `clouds`): each of them, My Cloud first.* Absent from an older Admin, whose `machine` and `teams` say everything. */clouds?: import("./cloud-list.mjs").CloudListEntry[];diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjsindex 820dd96a14..cdb70be9ca 100644--- a/electron/cloud-account.mjs+++ b/electron/cloud-account.mjs@@ -1,5 +1,5 @@import { createManagedDesktopStore, retryDelay, unreadableRecord } from "./managed-desktop.mjs";-import { CLOUD_MACHINE_CONNECTABLE, cloudUnreachableText, parseCloudCredit, parseCloudOffer, parseCloudPurchase, parseCloudSummary, parseCloudTeams, parseCloudRoom, parseCloudTrial, parseCloudUsage, parsePairingGrant, parsePublicOffer, withoutTrial } from "./cloud-home.mjs";+import { CLOUD_MACHINE_CONNECTABLE, cloudUnreachableText, parseCloudCredit, parseCloudLanding, parseCloudOffer, parseCloudPurchase, parseCloudSummary, parseCloudTeams, parseCloudRoom, parseCloudTrial, parseCloudUsage, parsePairingGrant, parsePublicOffer, withoutTrial } from "./cloud-home.mjs";import { CLOUD_ID, CLOUD_SWATCHES, cleanCloudListName, ORGANIZATION_BLOCKS, otherOwnClouds, ownCloud, parseCloudList, parseCloudRenewal, parseOrganizations, releaseVersion } from "./cloud-list.mjs";import { planTeam, teamPlan } from "./cloud-team-plan.mjs";import { cleanCode, cleanEmail, parseSignInStart, SIGN_IN_START, SIGN_IN_TRIES, SIGN_IN_VERIFY, signInIdentity, startFailure, verifyFailure } from "./cloud-signin.mjs";@@ -261,7 +261,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNthrow Object.assign(new Error("Cloud identity changed."), { status: 401, code: "invalid_token" });}const access = entitlement(result.entitlement);- const machine = parseCloudSummary(result.cloud), teams = parseCloudTeams(result.teams);+ const machine = parseCloudSummary(result.cloud), teams = parseCloudTeams(result.teams), landing = parseCloudLanding(result.landing, teams);const purchase = parseCloudPurchase(result.cloud?.purchase);const trial = parseCloudTrial(result.cloud?.trial), credit = parseCloudCredit(result.cloud?.credit), offer = parseCloudOffer(result.offer);const usage = access.status === "active" ? parseCloudUsage(result.cloud?.usage) : null, room = usage ? parseCloudRoom(result.cloud?.room) : null;@@ -294,7 +294,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNelse if (adding && adding.cloudId === null && waitingCloud) adding = { ...adding, cloudId: waitingCloud.id, name: waitingCloud.name, color: waitingCloud.color, tier: waitingCloud.tier ?? adding.tier };verifiedUntil = Math.min(grant.expiresAt, now() + STEADY_MS,access.status === "active" && access.expiresAt !== null ? access.expiresAt : Infinity);- publish({ ...view("connected"), entitlement: access, ...(machine ? { machine } : {}), ...(teams.length ? { teams } : {}), ...(purchase ? { purchase } : {}),+ publish({ ...view("connected"), entitlement: access, ...(machine ? { machine } : {}), ...(teams.length ? { teams } : {}), ...(landing ? { landing } : {}), ...(purchase ? { purchase } : {}),...(trial ? { trial } : {}), ...(credit ? { credit } : {}), ...(offer ? { offer } : {}), ...(usage ? { usage } : {}), ...(room ? { room } : {}), ...(renewingCloud ? { renewal } : {}),...(clouds ? { clouds, addCloud: more } : {}), ...(organizations ? { organizations } : {}), ...(latest ? { latestVersion: latest } : {}), verifiedAt: now(), verifiedUntil });const planCloud = teamPlan(value) ? planTeam(value)?.machine ?? null : machine;diff --git a/electron/cloud-home.d.mts b/electron/cloud-home.d.mtsindex f7b4855fb0..dcf02fee15 100644--- a/electron/cloud-home.d.mts+++ b/electron/cloud-home.d.mts@@ -137,6 +137,7 @@ export declare const CLOUD_TEAM_ROLES: readonly CloudTeamRole[];/** owner → Super admin, admin → Admin, member → User, in `t`'s language (English by default). */export declare function teamRoleLabel(role: string | null | undefined, t?: (key: string, params?: Record<string, unknown>) => string): string;export declare function parseCloudTeams(input: unknown): CloudTeam[];+export declare function parseCloudLanding(input: unknown, teams: readonly CloudTeam[]): { teamId: string } | null;export declare function cloudUnreachableCause(state: unknown, origin?: string | null): "host" | "no_answer" | null;export declare function cloudUnreachableText(state: unknown, origin?: string | null, t?: (key: string, params?: Record<string, string | number>) => string): string | null;export declare function parseCloudPurchase(input: unknown): CloudPurchase | null;diff --git a/electron/cloud-home.mjs b/electron/cloud-home.mjsindex a3f0bd8758..267b28f6e8 100644--- a/electron/cloud-home.mjs+++ b/electron/cloud-home.mjs@@ -317,6 +317,13 @@ export function parseCloudTeams(input) {return teams;}+/** The session's `landing` (additive): the team an account with no Cloud of its own was invited into, only while the session+ * lists that team. Null otherwise. */+export function parseCloudLanding(input, teams) {+ const teamId = record(input) && typeof input.teamId === "string" ? input.teamId : null;+ return teamId && teams.some((team) => team.id === teamId) ? { teamId } : null;+}+export function parsePairingGrant(input, origin, now) {if (!input || typeof input !== "object" || input.cloudContractVersion !== 1 || input.origin !== origin) return null;if (typeof input.code !== "string" || !CODE.test(input.code)) return null;diff --git a/electron/home-places.mjs b/electron/home-places.mjsindex 2a9b152eed..c17e1f4f42 100644--- a/electron/home-places.mjs+++ b/electron/home-places.mjs@@ -19,11 +19,13 @@ const KINDS = Object.freeze(["team", "cloud", "profile", "server"]);* persist(state: unknown): void,* makeId(): string,* homeOrigin(): string | null,+ * synced?(state: any): void,* log?(line: string): void,* }} deps `store`: this app's home-place.json (`{ team }` or `{ cloud }`); `environments()` / `persist()`: the saved- * places and their file; `homeOrigin()`: My Cloud's verified origin, the place the window falls back to.+ * places and their file; `homeOrigin()`: My Cloud's verified origin, the place the window falls back to. `synced(state)`: each sign-in state as it+ * comes, after the places follow it (a team the person just joined opens from there: team-join-main.mjs).*/-export function createHomePlaces({ store, environments: read, persist, makeId, homeOrigin, log = () => {} }) {+export function createHomePlaces({ store, environments: read, persist, makeId, homeOrigin, synced = () => {}, log = () => {} }) {let cached = null;const pending = [];/** One kind of place at most: the first of KINDS the record names. */@@ -81,6 +83,9 @@ export function createHomePlaces({ store, environments: read, persist, makeId, h* (one it no longer lists is gone; a team with its name for the line), in the colours the Admin keeps for them;* anything else changes nothing. An Admin that lists no Clouds leaves the Cloud places as they were. */sync(state) {+ try { places.follow(state); } finally { synced(state); }+ },+ follow(state) {if (state?.status !== "connected") return;const teams = Array.isArray(state.teams) ? state.teams : [];const { state: withTeams, left } = environments.reconcileTeams(read(), teams, makeId, homeOrigin());diff --git a/electron/main.mjs b/electron/main.mjsindex 4e5d546f79..a3a150b9bb 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -103,7 +103,7 @@ import { createDesktopText, DESKTOP_PORTS, jsonFile, registerDesktopPrefs, relabimport { createDesktopIncludedX } from "./included-x.mjs"; import { createDesktopIncludedPages } from "./included-pages.mjs";import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createCloudPowerGate, isCloudHomeEntry, myCloudOrigin, rememberedCloudHome, savedCloudHomeOrigin, signInCloudSession, withCloudHome } from "./cloud-home.mjs";import { installCloudFiles } from "./cloud-sync-main.mjs";-import { createCloudEntry } from "./cloud-entry.mjs";+import { createCloudEntry } from "./cloud-entry.mjs"; import { installTeamJoin } from "./team-join-main.mjs";import { createLendingTarget } from "./lending-target.mjs"; import { createOpenAtLogin, installOpenAtLogin } from "./open-at-login.mjs";import { cleanWorkspaceDir, createCleanWorkspace, profilesDir } from "./clean-workspace.mjs"; import { createLocalProfiles, createProfileRegistry } from "./local-profiles.mjs"; import { installOneHome } from "./one-home-main.mjs"; import { handSaved, installOwnHome } from "./own-home-main.mjs"; import { reopenSavedServer, serverOpens } from "./saved-server.mjs"; import { installTwoPlacesMain } from "./two-places-main.mjs";import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";@@ -152,7 +152,7 @@ const cloudEntry = createCloudEntry({return delivered;},});-cloudEntry.fromLaunch(process.argv);+cloudEntry.fromLaunch(process.argv); const teamLinks = installTeamJoin({ argv: process.argv, account: () => (app.isPackaged && !desktopRemoteAccess ? ensureCloudAccount() : null), addAccount: () => accountRing()?.addBrowser() ?? Promise.resolve(), openTeam: team => workspaceMenuAction(async () => { homeWindow.cancel(); await showHome({ place: { team: team.id, name: team.name } }); }), confirm: async (message, detail, button) => (await dialog.showMessageBox({ type: "question", buttons: [button, nativeT("native.common.cancel")], defaultId: 0, cancelId: 1, message, detail })).response === 0, t: (key, params) => nativeT(key, params), reveal: () => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); }, store: jsonFile(path.join(app.getPath("userData"), "team-landing.json")), ownPlace: () => Boolean(homeWindow.cloudOrigin()) || Boolean(homePlaces.remembered()), log: line => slog(line) });let pendingPackageInstallUrl = pendingOrganizationEntry ? null : packageUrlFromCommandLine(process.argv);let pendingChatLink = pendingOrganizationEntry ? null : chatLinkFromCommandLine(process.argv);let organizationEntryReady = false;@@ -243,7 +243,7 @@ function queueChatLink(rawLink) {}app.on("open-url", (event, url) => {- if (!queueOrganizationEntry(url) && !cloudEntry.fromUrl(url) && !queuePackageInstall(url) && !queueChatLink(url)) return;+ if (!teamLinks.fromUrl(url) && !queueOrganizationEntry(url) && !cloudEntry.fromUrl(url) && !queuePackageInstall(url) && !queueChatLink(url)) return;event.preventDefault();});@@ -252,7 +252,7 @@ app.on("second-instance", (_event, commandLine) => {queueOrganizationEntry("openmausbot://organization");return;}- if (cloudEntry.fromArgs(commandLine)) return;+ if (cloudEntry.fromArgs(commandLine)) return; if (teamLinks.fromArgs(commandLine)) return;const packageUrl = packageUrlFromCommandLine(commandLine);if (packageUrl) pendingPackageInstallUrl = packageUrl;const chatLink = chatLinkFromCommandLine(commandLine);@@ -2613,14 +2613,14 @@ const localServerRequest = (route, init = {}) => (serverProc && serverReady ? feconst teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.-const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, log: slog });+const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, synced: state => teamLinks.changed(state), log: slog });const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,window: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null), ensureWindow: () => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); },localOrigin: rendererOrigin, cookieFetch: (...args) => session.defaultSession.fetch(...args), power: cloudPower, splash: () => startupScreen, lastInput: oneHome.lastInput, rehomed: () => talk.homeChanged(), log: slog, t: nativeT,hosts: () => session.defaultSession, readyStore: jsonFile(path.join(app.getPath("userData"), "cloud-ready.json")), ownMove: () => ownHome?.underWay() ?? null,remembered: homePlaces.remembered, remember: homePlaces.remember, left: homePlaces.left, drop: homePlaces.drop,publish: view => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("home:state-changed", view); },- go: (url, origin, place) => { if (place?.kind === "team" || place?.kind === "own") { activatePlace(place); if (place.kind === "team") teamProfileSeeds.opened(place.origin); } else if (origin) activateCloud(origin); else if (activeEnvironment(environmentsState)) persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(url, true); },+ go: (url, origin, place) => { if (place?.kind === "team" || place?.kind === "own") { activatePlace(place); if (place.kind === "team") { teamProfileSeeds.opened(place.origin); teamLinks.opened(place.id); } } else if (origin) activateCloud(origin); else if (activeEnvironment(environmentsState)) persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(url, true); },reopen: (place, still) => reopenSavedServer(place, { still, saved: () => environmentsState.environments.filter(handSaved), fetch: (...args) => session.defaultSession.fetch(...args), opened: async (entry) => { homePlaces.remember(null); persistEnvironments(withActive(environmentsState, entry.id)); return navigateMainWindow(activeOrigin(), true); } }),showLocal: leaving => { if (!mainWindow || mainWindow.isDestroyed()) return createWindow(); if (!leaving) return; persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); } });installHomeWindowIpc({ ipcMain, homeWindow, cloudPage: cloudPageAsking });@@ -3067,7 +3067,7 @@ app.whenReady().then(async () => {// A cold-start action owns its first navigation; a default load started first would be aborted by it.const deliveredOrganizationEntry = await deliverOrganizationEntry();const deliveredCloudEntry = await cloudEntry.ready();- if (!hiddenStart && !restoredOrganizationEntry && !deliveredOrganizationEntry && !deliveredCloudEntry) await showStartPlace();+ if (!hiddenStart && !restoredOrganizationEntry && !deliveredOrganizationEntry && !deliveredCloudEntry) await showStartPlace(); void cloudAccountRestored().then(() => teamLinks.ready());// Reconcile incomplete setup and resume interrupted sign-out only once the local app is usable.if (hostedAccount) void hostedAccount.restore().catch(() => {});// Registering from an unreadable store would mint a second installation identity.diff --git a/electron/team-join-main.mjs b/electron/team-join-main.mjsnew file mode 100644index 0000000000..fee204e7e3--- /dev/null+++ b/electron/team-join-main.mjs@@ -0,0 +1,28 @@+// Main's side of a team the person joined (team-join.mjs): the team link from a launch, a URL or a second instance, and the+// landing of an invited person's first sign-in, with main's own dialog for the account that isn't in the team.+import { createTeamJoin, createTeamLanding, takeTeamLink, teamIdFromLink } from "./team-join.mjs";++/**+ * @param {{+ * argv: string[],+ * account(): any, addAccount(): Promise<unknown>, openTeam(team: { id: string, name: string }): Promise<unknown>,+ * confirm(message: string, detail: string, button: string): Promise<boolean>, t(key: string, params?: Record<string, string>): string,+ * reveal(): void, store: { read(): unknown, write(value: unknown): void }, ownPlace(): boolean, log(line: string): void,+ * }} deps `confirm`: main's own question dialog, true for `button`.+ */+export function installTeamJoin({ argv, account, addAccount, openTeam, confirm, t, reveal, store, ownPlace, log }) {+ const join = createTeamJoin({ account, addAccount, open: openTeam, reveal, log,+ ask: ({ email }) => confirm(t("native.teamLink.otherTitle"), t("native.teamLink.otherDetail", { email }), t("native.teamLink.signIn")) });+ const landing = createTeamLanding({ store, open: openTeam, ownPlace, log });+ const launched = takeTeamLink(argv);+ if (launched) join.request(launched, { launch: true });+ return {+ /** An `openmausbot://team/…` URL (macOS open-url): handled, true; anything else is left to the other handlers. */+ fromUrl(url) { const id = teamIdFromLink(url); return id ? join.request(id) : false; },+ /** A second instance's command line (Windows, Linux). */+ fromArgs(commandLine) { const id = takeTeamLink(commandLine); return id ? join.request(id) : false; },+ changed(state) { join.changed(state); landing.changed(state); },+ opened: (teamId) => landing.opened(teamId),+ ready: () => join.ready(),+ };+}diff --git a/electron/team-join.mjs b/electron/team-join.mjsnew file mode 100644index 0000000000..a5aad86612--- /dev/null+++ b/electron/team-join.mjs@@ -0,0 +1,151 @@+// openmausbot://team/<team id>: the join page's Open in the MausBot app, after someone joined a team in their browser. An+// action, not a credential: it names a team by its id only, and the team is opened only as the Admin's verified session lists+// it for whoever is signed in here. Signed out, it starts this app's own browser sign-in (its device code never leaves main);+// signed in as someone the team isn't listed for, it says so and offers to sign in with another address. Another app that+// catches the link learns a team id and can do nothing with it.+export const TEAM_LINK_PREFIX = "openmausbot://team/";+/** The Admin's team ids. */+const TEAM_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;+/** A link opened and waiting on a sign-in finishes it within this long, or is dropped. */+export const TEAM_JOIN_WAIT_MS = 30 * 60_000;++/** The team a link names, or null for anything but exactly `openmausbot://team/<team id>`. */+export function teamIdFromLink(value) {+ if (typeof value !== "string" || !value.startsWith(TEAM_LINK_PREFIX)) return null;+ const id = value.slice(TEAM_LINK_PREFIX.length);+ return TEAM_ID.test(id) ? id : null;+}++/** The last team link on a command line (a launch or a second instance on Windows and Linux), taken out so a relaunch+ * doesn't open it again. */+export function takeTeamLink(argv) {+ let found = null;+ for (let index = argv.length - 1; index >= 0; index--) {+ const id = teamIdFromLink(argv[index]);+ if (!id) continue;+ found ??= id;+ argv.splice(index, 1);+ }+ return found;+}++const listed = (state, teamId) => (state?.status === "connected" && Array.isArray(state.teams) ? state.teams.find((team) => team?.id === teamId) ?? null : null);++/**+ * @param {{+ * account(): { state(): any, refresh(): Promise<any>, begin(): Promise<any>, signInAgain(): Promise<any> } | null,+ * addAccount(): Promise<unknown>,+ * open(team: { id: string, name: string }): Promise<unknown>,+ * ask(question: { kind: "other-account", email: string }): Promise<boolean>,+ * reveal(): void,+ * now?(): number,+ * log?(line: string): void,+ * }} deps `account()`: the MausBot Cloud sign-in, null where this app can't have one (a build run from source, or connected+ * to another computer). `addAccount()`: Add another account's browser sign-in, which keeps the one in use waiting.+ * `open(team)`: the team's Cloud in the window, as the rail opens it. `ask`: main's own dialog, never a page's.+ */+export function createTeamJoin({ account, addAccount, open, ask, reveal, now = Date.now, log = () => {} }) {+ let wanted = null, ready = false, asking = false;+ const fresh = () => (wanted && now() < wanted.until ? wanted : (wanted = null));+ async function openIfListed(state) {+ const want = fresh();+ const team = want ? listed(state, want.teamId) : null;+ if (!team) return false;+ wanted = null;+ await open({ id: team.id, name: team.name });+ return true;+ }+ async function deliver() {+ const want = fresh(), client = account();+ if (!ready || !want || !client) return false;+ let state = client.state();+ if (state?.status === "signed-out" && state.message === "restoring") return false;+ if (state?.status === "signed-out") { log("team link: signing in to open the team"); want.begun = true; await client.begin(); return true; }+ if (state?.status === "reauth-required") { want.begun = true; await client.signInAgain(); return true; }+ if (state?.status === "connecting") return true;+ // Joined a moment ago: the list is read again now, not at the next minute's check.+ state = await client.refresh().catch(() => client.state());+ if (await openIfListed(state)) return true;+ return askOther(want, state);+ }+ /** Signed in, and the team isn't listed for this account: said once, with the way to sign in with the other address. */+ async function askOther(want, state) {+ if (state?.status !== "connected" || want.asked || asking) return false;+ want.asked = true;+ asking = true;+ try {+ const email = state.account?.email ?? "";+ if (await ask({ kind: "other-account", email })) await addAccount();+ else if (wanted === want) wanted = null;+ } finally { asking = false; }+ return true;+ }+ return {+ /** A link arrived: the team it names opens once someone it is listed for is signed in here. `launch`: the link this app+ * was started with, which waits for `ready` without showing anything yet. */+ request(teamId, { launch = false } = {}) {+ if (!TEAM_ID.test(teamId ?? "")) return false;+ wanted = { teamId, until: now() + TEAM_JOIN_WAIT_MS };+ if (launch) return true;+ reveal();+ void deliver().catch((error) => log(`team link: ${error?.message ?? error}`));+ return true;+ },+ /** The app can show a window and has read its sign-in: a link from the launch goes now. */+ ready() {+ ready = true;+ return deliver().catch((error) => { log(`team link: ${error?.message ?? error}`); return false; });+ },+ /** The sign-in changed (a sign-in finished, another account became the one in use): the waiting team opens once listed. */+ changed(state) {+ const want = fresh();+ if (!want) return;+ void openIfListed(state).then((opened) => {+ // The sign-in this link started finished as an account the team isn't listed for: say so, never just nothing.+ if (!opened && want.begun && state?.status === "connected") { want.begun = false; return askOther(want, state); }+ }).catch((error) => log(`team link: ${error?.message ?? error}`));+ },+ pending: () => fresh()?.teamId ?? null,+ };+}++/**+ * The team an invited person's account lands in (the session's `landing`: no Cloud of their own, invited into a team). The+ * window moves there only on a sign-in this app just saw, the first on this device, with no place of the person's own in+ * use; then once. Any other time the team is in the rail and the window stays where it is.+ * @param {{ store: { read(): unknown, write(value: unknown): void }, open(team: { id: string, name: string }): Promise<unknown>,+ * ownPlace(): boolean, log?(line: string): void }} deps `store`: team-landing.json, the accounts signed in here before and the+ * teams already opened here. `ownPlace()`: My Cloud or another place of the person's own is what the window shows.+ */+export function createTeamLanding({ store, open, ownPlace, log = () => {} }) {+ const MAX = 50, ACCOUNT = /^[\w-]{1,128}$/;+ let signingIn = false;+ const kept = () => {+ try {+ const value = store.read();+ return { teams: Array.isArray(value?.teams) ? value.teams.filter((id) => TEAM_ID.test(id)) : [], accounts: Array.isArray(value?.accounts) ? value.accounts.filter((id) => ACCOUNT.test(id)) : [] };+ } catch { return { teams: [], accounts: [] }; }+ };+ const save = (next) => { try { store.write(next); } catch (error) { log(`team landing: could not keep it (${error?.message ?? error})`); } };+ const mark = (teamId) => {+ const now = kept();+ if (TEAM_ID.test(teamId ?? "") && !now.teams.includes(teamId)) save({ ...now, teams: [...now.teams, teamId].slice(-MAX) });+ };+ return {+ changed(state) {+ if (state?.status === "connecting" || (state?.status === "signed-out" && state.message !== "restoring")) { signingIn = true; return; }+ if (state?.status !== "connected" || !state.account?.id) return;+ const justSignedIn = signingIn, before = kept();+ signingIn = false;+ if (!before.accounts.includes(state.account.id)) save({ ...before, accounts: [...before.accounts, state.account.id].slice(-MAX) });+ const teamId = state.landing?.teamId;+ if (!justSignedIn || before.accounts.length || !teamId || before.teams.includes(teamId) || ownPlace()) return;+ const team = listed(state, teamId);+ if (!team) return;+ mark(teamId);+ void Promise.resolve().then(() => open({ id: team.id, name: team.name })).catch((error) => log(`team landing: ${error?.message ?? error}`));+ },+ /** The window went to this team, by any way: it is no landing any more. */+ opened: mark,+ };+}diff --git a/electron/team-join.node-test.mjs b/electron/team-join.node-test.mjsnew file mode 100644index 0000000000..bb9f86afe9--- /dev/null+++ b/electron/team-join.node-test.mjs@@ -0,0 +1,194 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createTeamJoin, createTeamLanding, takeTeamLink, TEAM_JOIN_WAIT_MS, teamIdFromLink } from "./team-join.mjs";+import { isCloudDeepLink } from "./cloud-entry.mjs";+import { chatLinkFrom } from "./chat-link.mjs";++const ACME = "0f8b6a3e-1c2d-4e5f-8a9b-0c1d2e3f4a5b", OTHER = "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d";+const LINK = `openmausbot://team/${ACME}`;++test("a team link names a team by its id and nothing else; anything more is no link", () => {+ assert.equal(teamIdFromLink(LINK), ACME);+ for (const value of [null, undefined, 42, "", `${LINK}/`, `${LINK}?code=ABCDE`, `${LINK}#token=x`, "openmausbot://team/", "openmausbot://team/acme",+ `openmausbot://team/${ACME.toUpperCase()}`, `OPENMAUSBOT://team/${ACME}`, `openmausbot://teams/${ACME}`, `https://evil.example/openmausbot://team/${ACME}`, ` ${LINK}`]) {+ assert.equal(teamIdFromLink(value), null, String(value));+ }+ // Older handlers leave it alone, and it is no Cloud or chat link.+ assert.equal(isCloudDeepLink(LINK), false);+ assert.equal(chatLinkFrom(LINK), null);+});++test("a launch's team link is taken out of the command line, so a relaunch doesn't open it again", () => {+ const argv = ["/Applications/MausBot", "--flag", LINK, "openmausbot://cloud"];+ assert.equal(takeTeamLink(argv), ACME);+ assert.deepEqual(argv, ["/Applications/MausBot", "--flag", "openmausbot://cloud"]);+ assert.equal(takeTeamLink(argv), null);+});++/** The sign-in as main keeps it: its state, and what a refresh, a begin and a sign-in again do. */+function harness(initial, { afterRefresh = initial, answer = true, now = () => 1_000 } = {}) {+ const calls = [];+ let current = initial;+ const client = {+ state: () => current,+ refresh: async () => { calls.push("refresh"); current = afterRefresh; return current; },+ begin: async () => { calls.push("begin"); current = { status: "connecting" }; return current; },+ signInAgain: async () => { calls.push("signInAgain"); return current; },+ };+ const join = createTeamJoin({ account: () => client, now,+ addAccount: async () => { calls.push("addAccount"); },+ open: async (team) => { calls.push(["open", team]); },+ ask: async (question) => { calls.push(["ask", question]); return answer; },+ reveal: () => calls.push("reveal") });+ return { join, calls, set: (state) => { current = state; } };+}+const connected = (teams, email = "[email protected]") => ({ status: "connected", account: { id: "u1", email }, teams });+const settle = () => new Promise((resolve) => setImmediate(resolve));++test("signed in as the same address: the team list is read again at once and the team opens", async () => {+ const h = harness(connected([]), { afterRefresh: connected([{ id: ACME, name: "Acme", role: "member" }]) });+ await h.join.ready();+ assert.equal(h.join.request(ACME), true);+ await settle();+ assert.deepEqual(h.calls, ["reveal", "refresh", ["open", { id: ACME, name: "Acme" }]]);+ assert.equal(h.join.pending(), null);+});++test("signed out: the app's own browser sign-in starts, and the team opens once the sign-in lists it", async () => {+ const h = harness({ status: "signed-out" });+ await h.join.ready();+ h.join.request(ACME);+ await settle();+ assert.deepEqual(h.calls, ["reveal", "begin"]);+ h.join.changed(connected([{ id: ACME, name: "Acme", role: "admin" }]));+ await settle();+ assert.deepEqual(h.calls.at(-1), ["open", { id: ACME, name: "Acme" }]);+});++test("signed in as another address: it says so once, and offers to sign in with the other one, keeping this one", async () => {+ const h = harness(connected([], "[email protected]"));+ await h.join.ready();+ h.join.request(ACME);+ await settle();+ assert.deepEqual(h.calls, ["reveal", "refresh", ["ask", { kind: "other-account", email: "[email protected]" }], "addAccount"]);+ // The added account becomes the one in use, listing the team: it opens.+ h.join.changed(connected([{ id: ACME, name: "Acme", role: "member" }], "[email protected]"));+ await settle();+ assert.deepEqual(h.calls.at(-1), ["open", { id: ACME, name: "Acme" }]);+ // Cancel drops the link: nothing opens later by surprise.+ const declined = harness(connected([], "[email protected]"), { answer: false });+ await declined.join.ready();+ declined.join.request(ACME);+ await settle();+ assert.equal(declined.join.pending(), null);+});++test("a link from the launch waits for the app to be ready, shows nothing before, and a link left waiting ends after half an hour", async () => {+ let clock = 1_000;+ const h = harness({ status: "signed-out", message: "restoring" }, { now: () => clock });+ h.join.request(ACME, { launch: true });+ await settle();+ assert.deepEqual(h.calls, []);+ h.set({ status: "signed-out" });+ await h.join.ready();+ assert.deepEqual(h.calls, ["begin"]);+ clock += TEAM_JOIN_WAIT_MS;+ h.join.changed(connected([{ id: ACME, name: "Acme", role: "member" }]));+ await settle();+ assert.deepEqual(h.calls, ["begin"]);+});++test("an invited person's team opens first only on a sign-in just made, the first on this device, with no place of their own in use; once", async () => {+ const make = (initial = null, own = false) => {+ let kept = initial;+ const opened = [];+ const landing = createTeamLanding({ store: { read: () => kept, write: (value) => { kept = value; } }, open: async (team) => { opened.push(team.id); }, ownPlace: () => own });+ return { landing, opened, kept: () => kept };+ };+ const state = { ...connected([{ id: ACME, name: "Acme", role: "member" }]), landing: { teamId: ACME } };+ // A fresh install: the sign-in, then the team.+ const fresh = make();+ fresh.landing.changed({ status: "signed-out" });+ fresh.landing.changed({ status: "connecting" });+ fresh.landing.changed(state);+ fresh.landing.changed({ status: "signed-out" });+ fresh.landing.changed(state);+ await settle();+ assert.deepEqual(fresh.opened, [ACME]);+ assert.deepEqual(fresh.kept(), { teams: [ACME], accounts: ["u1"] });+ // Already signed in when the app started (a session read, not a sign-in): the team is in the rail, the window stays.+ const restored = make();+ restored.landing.changed({ status: "signed-out", message: "restoring" });+ restored.landing.changed(state);+ await settle();+ assert.deepEqual(restored.opened, []);+ // A sign-in on a device another account used before, or with My Cloud on screen: no move either.+ const used = make({ teams: [], accounts: ["someone-else"] });+ used.landing.changed({ status: "connecting" }); used.landing.changed(state);+ const own = make(null, true);+ own.landing.changed({ status: "connecting" }); own.landing.changed(state);+ // A team the session doesn't list is never a landing.+ const unlisted = make();+ unlisted.landing.changed({ status: "connecting" }); unlisted.landing.changed({ ...state, teams: [] });+ await settle();+ assert.deepEqual([used.opened, own.opened, unlisted.opened], [[], [], []]);+});++test("the link's own sign-in finishing as an address the team isn't listed for says so, instead of nothing", async () => {+ const h = harness({ status: "signed-out" });+ await h.join.ready();+ h.join.request(ACME);+ await settle();+ h.join.changed(connected([], "[email protected]"));+ await settle();+ assert.deepEqual(h.calls.slice(-2), [["ask", { kind: "other-account", email: "[email protected]" }], "addAccount"]);+});++test("the session's landing is read only for a team the same session lists", async () => {+ const { parseCloudLanding } = await import("./cloud-home.mjs");+ const teams = [{ id: ACME, name: "Acme", role: "member", machine: null }];+ assert.deepEqual(parseCloudLanding({ teamId: ACME }, teams), { teamId: ACME });+ assert.equal(parseCloudLanding({ teamId: OTHER }, teams), null);+ for (const value of [null, undefined, {}, { teamId: 3 }, "x"]) assert.equal(parseCloudLanding(value, teams), null);+});++test("main's wiring: a team URL or command line is taken, anything else is left to the other handlers, and main's own dialog asks", async () => {+ const { installTeamJoin } = await import("./team-join-main.mjs");+ const asked = [];+ let state = connected([], "[email protected]");+ const client = { state: () => state, refresh: async () => state, begin: async () => state, signInAgain: async () => state };+ const argv = ["/app", LINK];+ const links = installTeamJoin({ argv, account: () => client, addAccount: async () => {}, openTeam: async () => {}, t: (key, params) => `${key}${params ? JSON.stringify(params) : ""}`,+ confirm: async (message, detail, button) => { asked.push([message, detail, button]); return false; }, reveal: () => {}, store: { read: () => null, write: () => {} }, ownPlace: () => false, log: () => {} });+ assert.deepEqual(argv, ["/app"]);+ assert.equal(links.fromUrl("openmausbot://cloud"), false);+ assert.equal(links.fromArgs(["/app", "openmausbot://cloud"]), false);+ await links.ready();+ await settle();+ assert.deepEqual(asked, [["native.teamLink.otherTitle", 'native.teamLink.otherDetail{"email":"[email protected]"}', "native.teamLink.signIn"]]);+ state = connected([{ id: ACME, name: "Acme", role: "member" }]);+ assert.equal(links.fromUrl(LINK), true);+});++test("main makes the team link's wiring before most of main exists: nothing it is given is read until later, so the app starts", async () => {+ const { readFileSync } = await import("node:fs");+ const main = readFileSync(new URL("./main.mjs", import.meta.url), "utf8");+ const at = main.indexOf("installTeamJoin({");+ assert.ok(at > 0);+ // The call's own arguments, to its closing brace.+ let depth = 0, end = at + "installTeamJoin(".length;+ for (; end < main.length; end++) { const c = main[end]; if ("({[".includes(c)) depth++; else if (")}]".includes(c) && --depth === 0) break; }+ const args = main.slice(at + "installTeamJoin({".length, end);+ // Split into its top-level `key: value` pairs.+ const pairs = []; let start = 0; depth = 0;+ for (let i = 0; i <= args.length; i++) { const c = args[i]; if (c && "({[".includes(c)) depth++; else if (c && ")}]".includes(c)) depth--; else if ((c === "," && depth === 0) || i === args.length) { pairs.push(args.slice(start, i).trim()); start = i + 1; } }+ const imported = new Set([...main.matchAll(/^import \{([^}]*)\}/gm)].flatMap((match) => match[1].split(",").map((name) => name.trim().split(/\s+as\s+/).pop())));+ const before = main.slice(0, at);+ for (const pair of pairs.filter(Boolean)) {+ const value = pair.slice(pair.indexOf(":") + 1).trim();+ if (/^(async\s+)?(\([^)]*\)|[\w$]+)\s*=>/.test(value)) continue;+ const head = /^([A-Za-z_$][\w$]*)/.exec(value)?.[1];+ if (!head || ["process", "path", "app"].includes(head)) continue;+ assert.ok(imported.has(head) || new RegExp(`(?:const|let|var|function)\\s+${head}\\b`).test(before), `${pair.split(":")[0]}: ${head} is read before main declares it`);+ }+});diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex f65eeec603..4ce5fe225c 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -77,11 +77,15 @@ export const VITEST_SUBSETS = {"server/cloud-send-store.e2e.test.ts","server/cloud-send.e2e.test.ts","server/cloud-sync.e2e.test.ts",+ "server/cloud-team-asker-owns.e2e.test.ts",+ "server/cloud-team-away.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-connections.e2e.test.ts","server/cloud-team-engine-homes.e2e.test.ts","server/cloud-team-gateway-mcp.e2e.test.ts","server/cloud-team-inbox.e2e.test.ts",+ "server/cloud-team-mausbot-reach.e2e.test.ts",+ "server/cloud-team-new-chat-private.e2e.test.ts","server/cloud-team-open-reach.e2e.test.ts","server/cloud-team-owners.e2e.test.ts","server/cloud-team-people.e2e.test.ts",@@ -92,6 +96,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts","server/cloud-team-requests.e2e.test.ts",+ "server/cloud-team-routines.e2e.test.ts","server/cloud-team-setup-request.e2e.test.ts","server/cloud-team.e2e.test.ts","server/host/brief-words.test.ts",@@ -109,6 +114,7 @@ export const VITEST_SUBSETS = {"server/shared-computers.e2e.test.ts","server/shared-computers.gate.test.ts","server/team-move.e2e.test.ts",+ "server/team-welcome.e2e.test.ts","server/use-my-mac.e2e.test.ts","server/workspace-banner.e2e.test.ts","scripts/server-locale-plugin.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 8dfbb11b0c..cd147f913b 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -214,11 +214,15 @@ describe("CI outputs", () => {"server/cloud-send-store.e2e.test.ts","server/cloud-send.e2e.test.ts","server/cloud-sync.e2e.test.ts",+ "server/cloud-team-asker-owns.e2e.test.ts",+ "server/cloud-team-away.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-connections.e2e.test.ts","server/cloud-team-engine-homes.e2e.test.ts","server/cloud-team-gateway-mcp.e2e.test.ts","server/cloud-team-inbox.e2e.test.ts",+ "server/cloud-team-mausbot-reach.e2e.test.ts",+ "server/cloud-team-new-chat-private.e2e.test.ts","server/cloud-team-open-reach.e2e.test.ts","server/cloud-team-owners.e2e.test.ts","server/cloud-team-people.e2e.test.ts",@@ -229,6 +233,7 @@ describe("CI outputs", () => {"server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts","server/cloud-team-requests.e2e.test.ts",+ "server/cloud-team-routines.e2e.test.ts","server/cloud-team-setup-request.e2e.test.ts","server/cloud-team.e2e.test.ts","server/host/brief-words.test.ts",@@ -246,6 +251,7 @@ describe("CI outputs", () => {"server/shared-computers.e2e.test.ts","server/shared-computers.gate.test.ts","server/team-move.e2e.test.ts",+ "server/team-welcome.e2e.test.ts","server/use-my-mac.e2e.test.ts","server/workspace-banner.e2e.test.ts","scripts/server-locale-plugin.test.ts",diff --git a/server/app-trigger-host.ts b/server/app-trigger-host.tsindex 02cdc5ed6b..991e1183ce 100644--- a/server/app-trigger-host.ts+++ b/server/app-trigger-host.ts@@ -10,7 +10,7 @@ import { AppTriggerRequestService, type AppTriggerRequestStore } from "./app-triimport { AppTriggerError, AppTriggerManager, type AppTriggerPatch } from "./app-triggers.ts";import type { RosterMember } from "./peer-roster.ts";import type { RequestAuth } from "./request-auth.ts";-import type { RoutineManager } from "./routines.ts";+import type { Routine, RoutineManager } from "./routines.ts";import { PASS, type RouteContext, type RouteHandler } from "./routes/table.ts";import { listTriggers, triggerTarget } from "./trigger-tools.ts";import { addressFor } from "./webhook-address.ts";@@ -50,6 +50,8 @@ export interface InternalTriggerContext {/** A run a webhook or app event started, or work one handed on. */outsideDriven: () => boolean;canCommit: () => boolean;+ /** Whether this turn may know of the routine: on a Team Cloud one that lives in someone's private chat only in theirs. */+ routineShown?: (routine: Routine) => boolean;}const GUEST_REFUSAL = "Only the Cloud's owner can make a bot watch their connected apps. Tell the person to ask from their own conversation.";@@ -177,7 +179,7 @@ export function createAppTriggerHost(deps: AppTriggerHostDeps) {if ("error" in target) return json(res, target.status, { error: target.error });const ownerId = target.forBot?.botId ?? context.from.id;const listing = listTriggers({- botId: ownerId, triggerId: url.searchParams.get("triggerId") ?? undefined, routines: deps.routines().listRoutines(),+ botId: ownerId, triggerId: url.searchParams.get("triggerId") ?? undefined, routines: deps.routines().listRoutines().filter((routine) => context.routineShown?.(routine) ?? true),webhooks: deps.webhooks.list(), appTriggers: manager.list(), runs: deps.routines().listRuns(), timeZone: deps.timeZone(), now: Date.now(),});const shown = listing.trigger;diff --git a/server/automation-destinations.test.ts b/server/automation-destinations.test.tsindex 22c0e52b3a..b07fe28803 100644--- a/server/automation-destinations.test.ts+++ b/server/automation-destinations.test.ts@@ -11,7 +11,7 @@ function world(writer: string, cloud = true, earlier: Array<{ webhookId: string;let made = 0;const store = {bot: () => ({ id: "bot" }),- createTask: (_botId: string, title: string) => { const task = { threadId: `made-${++made}`, title }; tasks.set(task.threadId, task); return task; },+ createTask: (_botId: string, title: string, ...rest: unknown[]) => { const task = { threadId: `made-${++made}`, title }; tasks.set(task.threadId, task); (rest[6] as ((made: { threadId: string }) => void) | undefined)?.(task); return task; },messagesFor: () => [],taskByThread: (_botId: string, threadId: string) => tasks.get(threadId),} as unknown as AutomationDestinationDeps["store"];diff --git a/server/automation-destinations.ts b/server/automation-destinations.tsindex 5e663aacfd..d523017612 100644--- a/server/automation-destinations.ts+++ b/server/automation-destinations.ts@@ -13,7 +13,7 @@ export interface AutomationDestinationDeps {cloud: {owner: string;/** Who a routine's chat counts as opened by. */- opener(routineId: string): string;+ opener(routineId: string, routine?: Routine): string;reportFromOthers(line: Message): boolean;opened(threadId: string, person: string): void;/** This chat holds what an outside event's run reported. */@@ -21,16 +21,20 @@ export interface AutomationDestinationDeps {} | null;}-function legacyResultsThread(routineName: string, task: TaskRecord): boolean {+function legacyResultsThread(routineName: string, task: Pick<TaskRecord, "title">): boolean {return task.title.endsWith(" · Results") || task.title === threadTitleFrom(`${routineName} · Results`);}+/** The chat a routine opened for its own results, which no person has written in. */+export function isOwnResultsChat(routineName: string, task: Pick<TaskRecord, "title" | "askedAt">): boolean {+ return legacyResultsThread(routineName, task) && task.askedAt === undefined;+}+export function createAutomationDestinations(deps: AutomationDestinationDeps) {const { store, cloud } = deps;const chatOfItsOwn = (botId: string, name: string, person?: string) => {- const threadId = store.createTask(botId, `${name} · Results`, false)?.threadId;- if (threadId && person) cloud?.opened(threadId, person);- return threadId;+ return store.createTask(botId, `${name} · Results`, false, undefined, undefined, undefined, undefined, undefined,+ person ? (created) => cloud?.opened(created.threadId, person) : undefined)?.threadId;};return {/** The chat of its own an outside event's run reports into on a Cloud: never the person's, and never a wait's, which reports to the chat that set it. */@@ -40,7 +44,7 @@ export function createAutomationDestinations(deps: AutomationDestinationDeps) {},routine(routine: Routine, forceNew: boolean): { threadId: string; main?: true } | undefined {const bot = store.bot(routine.botId);- const opener = cloud?.opener(routine.id);+ const opener = cloud?.opener(routine.id, routine);// A routine outside work wrote reports nowhere a person already works, whatever chat it names.const chosen = !forceNew && opener !== CLOUD_OUTSIDE_KEY && routine.resultsThreadId && bot && !bot.hidden ? store.taskByThread(bot.id, routine.resultsThreadId) : undefined;const main = bot && !bot.hidden ? deps.mainThread(bot.id) : undefined;diff --git a/server/bot-api-host.ts b/server/bot-api-host.tsindex ca8e8e8824..c84f13905f 100644--- a/server/bot-api-host.ts+++ b/server/bot-api-host.ts@@ -151,12 +151,11 @@ export function createBotApiHost(deps: BotApiHostDeps) {let opened = false;if (threadId === undefined) {// Asks from the start, with none of the bot's saved allowances: nothing may answer an approval for an outside caller.- const task = store.createTask(botId, message.slice(0, 80), false, undefined, undefined, "ask");+ const task = store.createTask(botId, message.slice(0, 80), false, undefined, undefined, "ask", undefined, undefined, (created) => deps.opened?.(created.threadId));if (!task) fail(404, "no such bot");threadId = task.threadId;opened = true;store.patchTask(botId, threadId, { botApi: true, outside: true });- deps.opened?.(threadId);}const receivedAt = Date.now();const userMessage = store.appendMessage(threadId, { role: "user", kind: "text", text: message, via: "api" });diff --git a/server/bot-owners.test.ts b/server/bot-owners.test.tsnew file mode 100644index 0000000000..8185a16591--- /dev/null+++ b/server/bot-owners.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";++import type { BotAccess } from "../shared/bot-access.ts";+import { forgetMember } from "./bot-owners.ts";+import type { BotRecord } from "./store.ts";++const BOB = "[email protected]";++function storeOf(bots: Array<Partial<BotRecord> & { id: string }>) {+ const list = bots as BotRecord[];+ return {+ get bots() { return list; },+ bot: (id: string) => list.find((bot) => bot.id === id) ?? null,+ patchBot: (id: string, patch: Partial<BotRecord>) => { const bot = list.find((one) => one.id === id)!; Object.assign(bot, patch); return bot; },+ };+}++describe("forgetMember", () => {+ it("takes a member who left off every bot's sharing and Looked after by, and their bots fall to the Admins", () => {+ const store = storeOf([+ { id: "ledger", reportsTo: BOB, createdBy: "[email protected]", access: { everyone: "none", people: { [BOB]: "chat", "[email protected]": "chat" } }, visibility: { people: [BOB, "[email protected]"] } },+ { id: "made", createdBy: BOB },+ { id: "listed", visibility: { people: [BOB, "@acme.test"] } },+ { id: "scout", createdBy: "[email protected]", reportsTo: "[email protected]" },+ { id: "mausbot", defaultBot: { person: BOB }, reportsTo: BOB },+ ]);+ const shared: Array<[string, BotAccess]> = [];+ const handedBack = forgetMember(store, "[email protected]", (bot, access) => { shared.push([bot.id, access]); store.patchBot(bot.id, { access }); });+ expect(handedBack.map((bot) => bot.id)).toEqual(["ledger", "made"]);+ expect(store.bot("ledger")).toMatchObject({ reportsTo: undefined, createdBy: undefined });+ expect(store.bot("made")?.createdBy).toBeUndefined();+ expect(store.bot("scout")).toMatchObject({ reportsTo: "[email protected]", createdBy: "[email protected]" });+ expect(store.bot("mausbot")?.reportsTo).toBe(BOB);+ expect(shared).toEqual([+ ["ledger", { everyone: "none", people: { "[email protected]": "chat" } }],+ ["listed", { everyone: "none", people: { "@acme.test": "chat" } }],+ ]);+ });++ it("uncrowns a Chief that would be a second one in its department once nobody owns it", () => {+ const store = storeOf([+ { id: "dept-chief", section: "Sales", chiefOfStaff: true },+ { id: "bobs-chief", section: "Sales", chiefOfStaff: true, reportsTo: BOB },+ ]);+ forgetMember(store, BOB, () => {});+ expect(store.bot("bobs-chief")).toMatchObject({ chiefOfStaff: false, reportsTo: undefined });+ expect(store.bot("dept-chief")?.chiefOfStaff).toBe(true);+ });+});diff --git a/server/bot-owners.ts b/server/bot-owners.tsindex dc198b785e..f6730a61fb 100644--- a/server/bot-owners.ts+++ b/server/bot-owners.ts@@ -35,3 +35,36 @@ export function setCreatedBy(store: Owners, botId: string, email: string): voidconst bot = store.bot(botId);if (bot && !bot.createdBy) store.patchBot(botId, { createdBy: ownerEmail(email) });}++/** A member who left a Team Cloud: no bot is shared with them by name or looked after by them any more, so joining again+ * restores nothing. A bot they looked after is nobody's, whose asks go to the Admins; a Chief that would then be a second+ * one in its department gives up its crown. `share` writes a bot's sharing (and its visibility with it). The bots they+ * looked after. */+export function forgetMember(store: Owners, email: string, share: (bot: BotRecord, access: BotAccess) => void): BotRecord[] {+ const address = ownerEmail(email);+ const handedBack: BotRecord[] = [];+ for (const bot of store.bots) {+ if (bot.defaultBot?.person) continue;+ const looked = botOwner(bot) === address;+ const named = bot.reportsTo === address || bot.createdBy === address;+ const shared = accessOf(bot);+ const added = Object.hasOwn(shared.people, address);+ if (!looked && !named && !added) continue;+ let current = bot;+ if (looked || named) {+ const patch: Partial<BotRecord> = {+ ...(looked || bot.reportsTo === address ? { reportsTo: undefined } : {}),+ ...(looked || bot.createdBy === address ? { createdBy: undefined } : {}),+ };+ if (bot.chiefOfStaff && chiefConflict(store.bots.map((other) => (other.id === bot.id ? { ...other, ...patch } : other)))) patch.chiefOfStaff = false;+ current = store.patchBot(bot.id, patch) ?? bot;+ if (looked) handedBack.push(current);+ }+ if (added || (looked && bot.access !== undefined) || (looked && typeof bot.visibility === "object")) {+ const people = { ...shared.people };+ delete people[address];+ share(current, { everyone: shared.everyone, people });+ }+ }+ return handedBack;+}diff --git a/server/bot-visibility.ts b/server/bot-visibility.tsindex 0ea12a79d2..f657b058da 100644--- a/server/bot-visibility.ts+++ b/server/bot-visibility.ts@@ -19,8 +19,12 @@ export interface ThreadAudiences {person: string | null;/** A bot's conversation as this person has read it: its unread mark and read line their own (host/room-reads.ts). */ownTask?<T extends { threadId: string; unread?: boolean; lastReadMessageId?: string }>(task: T): T;+ /** The person whose private chat a routine lives in (routine-home.ts), else null. */+ routineHome?(routine: RoutineRef): string | null;}+export type RoutineRef = { botId?: unknown; groupId?: unknown; name?: unknown; sourceThreadId?: unknown; resultsThreadId?: unknown };+/** `all`: every bot and room. On a Team Cloud an admin session is `all` with its address, and still sees only the* conversations its person may (audience.ts): its own private chats, never another person's. */export type Viewer = { kind: "all"; email?: string } | { kind: "member"; email?: string };@@ -295,6 +299,12 @@ export class VisibleSet {return all.filter((section) => shown.has(key(section)));}+ /** A routine that lives in someone's private chat is theirs alone on a Team Cloud: no other member and no admin. */+ routineShown(routine: RoutineRef): boolean {+ const home = this.audiences?.routineHome?.(routine) ?? null;+ return home === null || home === this.audiences!.person;+ }+/** Refused only when everything referencing it is hidden; an unreferenced one (a member's own upload) is served, its name is random. */attachment(name: string, threadsReferencing: (name: string) => readonly string[]): boolean {if (this.everything) return true;@@ -563,7 +573,9 @@ export function frameForMember(payload: Record<string, unknown>, ctx: FrameConte}case "routine": {const routine = field("routine");- return routineVisible(routine, visible) ? payload : undefined;+ if (!routineVisible(routine, visible)) return undefined;+ const shown = routineForViewer(routine, visible);+ return shown === routine ? payload : { ...payload, routine: shown };}case "routine.run": {const run = field("run");@@ -620,12 +632,24 @@ export function webhookVisible(value: { botId?: unknown; groupId?: unknown }, vireturn typeof value.groupId !== "string" || !value.groupId || visible.group(value.groupId);}-export function routineVisible(value: { botId?: unknown; groupId?: unknown }, visible: VisibleSet): boolean {+export function routineVisible(value: RoutineRef, visible: VisibleSet): boolean {if (visible.everything) return true;+ if (!visible.routineShown(value)) return false;if (typeof value.groupId === "string" && value.groupId) return visible.group(value.groupId);return typeof value.botId === "string" && visible.bot(value.botId);}+/** A routine as one person is sent it: without the id of a conversation they may not read (the chat a teammate's+ * routine opened for its results). The same object when nothing is left out. */+export function routineForViewer<T extends { sourceThreadId?: unknown; resultsThreadId?: unknown }>(routine: T, visible: VisibleSet): T {+ if (!visible.filtersThreads) return routine;+ const hidden = (["sourceThreadId", "resultsThreadId"] as const).filter((key) => typeof routine[key] === "string" && visible.hides(routine[key] as string));+ if (!hidden.length) return routine;+ const shown = { ...routine };+ for (const key of hidden) delete shown[key];+ return shown;+}+/** A run's prompt and output are its conversation's words: on a Team Cloud a run that went into someone's private chat* is theirs alone. */export function routineRunVisible(run: { botId?: unknown; groupId?: unknown; threadId?: unknown; resultsThreadId?: unknown; sourceThreadId?: unknown }, visible: VisibleSet): boolean {diff --git a/server/channel-queue.ts b/server/channel-queue.tsindex 9226ef8c48..8e9087fade 100644--- a/server/channel-queue.ts+++ b/server/channel-queue.ts@@ -98,6 +98,15 @@ export function queuedChannelMessage(return entry.items.find((item) => item.sendId === sendId) ?? null;}+/** The waiting line under that id, and the conversation it waits in. */+export function channelQueueItem(groupId: string, queueId: string): { threadId: string; item: ChannelQueueItem } | null {+ for (const [threadId, entry] of queues) {+ const item = entry.groupId === groupId ? entry.items.find((candidate) => candidate.id === queueId) : undefined;+ if (item) return { threadId, item };+ }+ return null;+}+export function cancelChannelMessage(groupId: string, queueId: string): boolean {for (const [threadId, entry] of queues) {if (entry.groupId !== groupId) continue;diff --git a/server/chief-of-staff.ts b/server/chief-of-staff.tsindex 21e38ff47d..33987f7613 100644--- a/server/chief-of-staff.ts+++ b/server/chief-of-staff.ts@@ -31,13 +31,14 @@ export function chiefOfStaffSystemPrompt(chiefId: string,bots: ChiefTeamMember[],canDelegate: boolean,+ also?: (bot: ChiefTeamMember) => boolean,): string {const chief = bots.find((bot) => bot.id === chiefId);const chiefSection = sectionKey(chief?.section);const sectionName = peerName(chiefSection) || "General";const owner = chief ? botOwner(chief) : null;const person = owner ? peerName(nameFromEmail(owner)) || "your person" : null;- const reachable = reachablePeers(bots, chief ?? { id: chiefId, name: "" });+ const reachable = reachablePeers(bots, chief ?? { id: chiefId, name: "" }, also);const team = chief ? reachable.filter((bot) => hasAuthority(chief, bot)) : reachable;const others = chief ? reachable.filter((bot) => !hasAuthority(chief, bot)) : [];const roster = renderRoster(team, {diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.tsindex 78e57b6806..3015d2f127 100644--- a/server/cloud-home.test.ts+++ b/server/cloud-home.test.ts@@ -847,3 +847,30 @@ it("a My Cloud refuses a team claim: it is one person's", () => {expect(f.mint(f.sign(JSON.stringify({ team: { id: "team-1" } })))).toEqual({ status: 400, body: { error: "not_a_team" } });expect(f.sessions.openPairings()).toHaveLength(0);});++it("a Team Cloud with remote access turned off refuses a User's browser sign-in, keeps an Owner's and an Admin's, and every app pairing", () => {+ const root = directory();+ let off = true, counter = 0;+ const now = 1_800_000_000_000;+ const sessions = new SessionRegistry({ file: join(root, "sessions.json"), now: () => now });+ const pairing = createCloudPairing({ secret, sessions, team: { id: "team-1", name: "Acme" }, memberBrowserOff: () => off, now: () => now });+ const mint = (claims: Record<string, unknown>) => {+ const body = JSON.stringify({ label: "Web browser", ttlSeconds: 120, ...claims });+ const timestamp = String(Math.floor(now / 1000)), nonce = `nonce-${String(++counter).padStart(12, "0")}`;+ return pairing.handle({ timestamp, nonce, signature: `v1=${cloudPairingSignature(secret, timestamp, nonce, body)}`, body: Buffer.from(body), source: "203.0.113.9" });+ };+ const browser = (email: string, role: string) => mint({ purpose: "browser", owner: email, member: { email, role } });+ expect(browser("[email protected]", "member")).toEqual({ status: 403, body: { error: "remote_access_off" } });+ expect(browser("[email protected]", "admin").status).toBe(200);+ expect(browser("[email protected]", "owner").status).toBe(200);+ expect(mint({ member: { email: "[email protected]", role: "member" } }).status, "the app's pairing stays: it is how the team reaches its Cloud").toBe(200);+ off = false;+ expect(browser("[email protected]", "member").status).toBe(200);+ // Turned off again: the User's open browser signs out, the admins' stay.+ const ada = sessions.exchange({ code: (browser("[email protected]", "member").body.credential as string), browser: true, label: "", source: "s" });+ const ben = sessions.exchange({ code: (browser("[email protected]", "admin").body.credential as string), browser: true, label: "", source: "s" });+ expect(ada.ok && ben.ok).toBe(true);+ expect(sessions.closeMemberBrowsers()).toBe(1);+ expect(sessions.list().map((session) => session.email)).toEqual(expect.arrayContaining(["[email protected]"]));+ expect(sessions.list().map((session) => session.email)).not.toContain("[email protected]");+});diff --git a/server/cloud-home.ts b/server/cloud-home.tsindex f1b8418dfd..83e6a4ff34 100644--- a/server/cloud-home.ts+++ b/server/cloud-home.ts@@ -10,7 +10,7 @@ import { join } from "node:path";import type { Surface } from "../shared/wire.ts";import { writeFileAtomic } from "./atomic.ts";import { hostedWorkspaceConfigured } from "./enterprise.ts";-import { parseMemberClaim, teamRoleScopes, type CloudTeam } from "./cloud-team.ts";+import { parseMemberClaim, teamMemberEmail, teamRoleScopes, type CloudTeam } from "./cloud-team.ts";import { isLoopbackHost } from "./request-auth.ts";import { formatPairingCode, type SessionRegistry } from "./sessions.ts";@@ -180,7 +180,7 @@ export function createCloudRequestVerifier(options: { secret: string; now?: () =}export interface CloudPairingResult {- status: 200 | 400 | 401 | 429 | 503;+ status: 200 | 400 | 401 | 403 | 429 | 503;body: Record<string, unknown>;}@@ -191,6 +191,11 @@ export function createCloudPairing(options: {sessions: PairingSessions;/** The team this machine serves: then every pairing body must carry the Admin's `member` claim. */team?: CloudTeam | null;+ /** The team's rule turned remote access off: a User's browser sign-in is refused (an Owner's and an Admin's stay: the+ * rule is theirs to change, and their admin pages open in a browser). */+ memberBrowserOff?: () => boolean;+ /** The claim's `member.invitedBy` (additive): who invited this member, for their welcome (team-welcome.ts). */+ invited?: (member: string, by: string) => void;now?: () => number;}) {const { sessions } = options;@@ -213,6 +218,7 @@ export function createCloudPairing(options: {const claim = options.team ? parseMemberClaim(parsed as Record<string, unknown>, options.team) : null;if (claim && !claim.ok) return { status: 400, body: { error: claim.error } };const member = claim?.ok ? claim.member : null;+ const invitedBy = member ? teamMemberEmail((parsed as { member?: { invitedBy?: unknown } }).member?.invitedBy) : null;// oxlint-disable-next-line no-control-regexif (label !== undefined && (typeof label !== "string" || label.length > 80 || /[\x00-\x1f\x7f]/.test(label))) return { status: 400, body: { error: "invalid_label" } };if (ttlSeconds !== undefined && (!Number.isSafeInteger(ttlSeconds) || (ttlSeconds as number) < 1)) return { status: 400, body: { error: "invalid_ttl" } };@@ -222,8 +228,12 @@ export function createCloudPairing(options: {if ((browser || owner !== undefined) && (typeof owner !== "string" || owner.length > 254 || !OWNER_EMAIL.test(owner))) {return { status: 400, body: { error: "invalid_owner" } };}+ if (browser && member?.role === "member" && options.memberBrowserOff?.()) return { status: 403, body: { error: "remote_access_off" } };const ttl = Math.min((ttlSeconds as number | undefined) ?? CLOUD_PAIRING_DEFAULT_TTL_S, browser ? CLOUD_BROWSER_SIGN_IN_MAX_TTL_S : CLOUD_PAIRING_MAX_TTL_S);if (member) sessions.revokeMember(member.email, member.role);+ if (member && invitedBy && invitedBy !== member.email) {+ try { options.invited?.(member.email, invitedBy); } catch { /* the welcome names nobody; the pairing goes on */ }+ }const opened = sessions.openPairing({scopes: member ? teamRoleScopes(member.role) : ["admin", "client"],label: typeof label === "string" && label.trim() ? label.trim() : "MausBot Cloud",diff --git a/server/cloud-team-asker-owns.e2e.test.ts b/server/cloud-team-asker-owns.e2e.test.tsnew file mode 100644index 0000000000..145c5a4398--- /dev/null+++ b/server/cloud-team-asker-owns.e2e.test.ts@@ -0,0 +1,242 @@+// Whoever asked owns the run, on a Team Cloud's shared chat. Priya's request holds in a long tool call (a CI poll) while+// Tom and Sam write in the same chat: their lines wait their turn, in a queue everyone sees, and each runs after hers as+// its own turn; neither steers nor stops her run, and only Priya or an admin can stop it. Priya adding to her own run, and+// her private chat, behave as on a one-person server. Disposable homes and the synthetic Claude CLI; nothing leaves this+// machine.+import { randomBytes } from "node:crypto";+import { rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, afterEach, 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 ENGINE = `process.env.FAKE_CLAUDE_TOOL_CALLS_FILE = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/tool-calls.json";+process.env.FAKE_CLAUDE_RELEASE = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/release";+process.env.FAKE_CLAUDE_MARKER_REPLIES = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/markers.json";`;+const POLL = { name: "Bash", input: { command: "gh run watch 42" }, hold: true };+const [PRIYA_ASK, TOM_ASK, SAM_ASK, PRIYA_MORE] = ["Watch CI for PR 42", "What is due on Friday?", "Book the room for Monday", "Is the PR up yet?"];+/** A resumed turn's prompt can carry earlier lines too, and the fake engine answers the first marker it finds: newest asks first. */+const ANSWERS: Record<string, string> = {+ [PRIYA_MORE]: "Yes, PR 42 is up.",+ [SAM_ASK]: "Booked the room for Monday.",+ [TOM_ASK]: "The invoice run is due on Friday.",+ "Check this week's pay runs.": "This week's pay runs are fine.",+ [PRIYA_ASK]: "CI for PR 42 is green.",+};++type Row = { id: string; role: string; kind: string; text?: string; steered?: boolean; sender?: { name: string; id?: string }; tool?: { name: string }; stoppedBy?: { name: string; id?: string } };+type Queued = { queueId: string; text: string; sender?: { name: string; id?: string } };++let fx: CloudSendFixture, team: CloudTeamFixture;+let ada = "", priya = "", tom = "", sam = "", dev = "";+let botId = "", shared = "";++const home = (name: string) => join(team.home, name);+const transcript = async (token: string, threadId = shared) =>+ ((await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages ?? []) as Row[];+const queue = async (token: string, threadId = shared) =>+ (((await team.as(token, "GET", "/api/bots?messages=0")).body.botQueuedMessages ?? {}) as Record<string, Queued[]>)[threadId] ?? [];+const busy = async (threadId = shared, token = ada) => {+ const bot = ((await team.as(token, "GET", "/api/bots?messages=0")).body.bots as Array<{ id: string; busy?: boolean; tasks?: Array<{ threadId: string; busy?: boolean }> }>).find((one) => one.id === botId);+ return Boolean(bot?.tasks?.find((task) => task.threadId === threadId)?.busy ?? (threadId === shared && bot?.busy));+};+const answered = async (text: string, threadId = shared, token = ada) => (await transcript(token, threadId)).some((row) => row.role === "bot" && row.kind === "text" && row.text?.includes(text));+const personFirstStops = async (threadId = shared, token = ada) => (await transcript(token, threadId)).filter((row) => row.kind === "activity" && (row.tool?.name ?? "").endsWith("to answer you first")).length;+const send = (token: string, text: string, threadId = shared) => team.as(token, "POST", `/api/bots/${botId}/messages`, { text, threadId });++/** Priya's request starts and holds in its CI poll; later turns call no tool. */+async function priyaRuns(threadId = shared) {+ rmSync(home("release"), { force: true });+ writeFileSync(home("tool-calls.json"), JSON.stringify([POLL]));+ const polls = async () => (await transcript(priya, threadId)).filter((row) => row.kind === "activity" && JSON.stringify(row.tool ?? {}).includes("gh run watch 42")).length;+ const before = await polls();+ const sent = await send(priya, PRIYA_ASK, threadId);+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await expect.poll(polls, { timeout: hostTimeout(30_000), interval: 100 }).toBe(before + 1);+ writeFileSync(home("tool-calls.json"), "[]");+}+async function release(threadId = shared, token = ada) {+ writeFileSync(home("release"), "");+ await expect.poll(async () => !(await busy(threadId, token)) && (await queue(token, threadId)).length === 0, { timeout: hostTimeout(60_000), interval: 100 }).toBe(true);+}+/** Longer than the person-first wait (OMB_PERSON_FIRST_MS below), so a stop it would make has happened. */+const pastPersonFirst = () => new Promise((resolve) => setTimeout(resolve, 3_000));++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-asker-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-asker", name: "Acme", engine: ENGINE,+ env: { OMB_BOT_BOX: "0", OMB_PERSON_FIRST_MS: "1500" } } });+ team = fx.team!;+ writeFileSync(home("markers.json"), JSON.stringify(ANSWERS));+ writeFileSync(home("tool-calls.json"), "[]");+ ada = (await team.pair({ email: "[email protected]", role: "owner" })).token!;+ priya = (await team.pair({ email: "[email protected]", role: "member" })).token!;+ tom = (await team.pair({ email: "[email protected]", role: "member" })).token!;+ sam = (await team.pair({ email: "[email protected]", role: "member" })).token!;+ dev = (await team.pair({ email: "[email protected]", role: "member" })).token!;+ for (const [token, name] of [[ada, "Ada"], [priya, "Priya"], [tom, "Tom"], [sam, "Sam"]]) {+ expect((await team.as(token, "PUT", "/api/me", { name })).status).toBe(200);+ }+ const created = await team.as(ada, "POST", "/api/bots", { name: "Scout" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ botId = created.body.bot.id;+ shared = created.body.bot.threadId;+}, hostTimeout(120_000));++/** Whatever a test left holding (a stopped run's CI poll, a waiting line) ends before the next one starts. */+afterEach(async () => {+ writeFileSync(home("release"), "");+ writeFileSync(home("tool-calls.json"), "[]");+ await expect.poll(async () => !(await busy()) && (await queue(ada)).length === 0, { timeout: hostTimeout(60_000), interval: 100 }).toBe(true);+}, hostTimeout(90_000));++afterAll(async () => {+ await fx?.close();+});++it("Tom's line during Priya's run waits its turn: it never reaches her run, nor stops it, and runs after as Tom's own turn", async () => {+ await priyaRuns();+ const stopsBefore = await personFirstStops();+ const sent = await send(tom, TOM_ASK);+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ expect(sent.body.steered).toBeUndefined();+ expect(sent.body.queued).toBe(true);+ for (const viewer of [ada, priya, tom]) {+ expect((await queue(viewer)).map((item) => [item.text, item.sender?.name])).toEqual([[TOM_ASK, "Tom"]]);+ }+ await pastPersonFirst();+ expect(await busy()).toBe(true);+ expect(await personFirstStops()).toBe(stopsBefore);++ await release();+ const rows = await transcript(priya);+ const priyaAnswer = rows.findIndex((row) => row.role === "bot" && row.text?.includes(ANSWERS[PRIYA_ASK]));+ const tomLine = rows.findIndex((row) => row.role === "user" && row.text === TOM_ASK);+ const tomAnswer = rows.findIndex((row) => row.role === "bot" && row.text?.includes(ANSWERS[TOM_ASK]));+ expect(priyaAnswer).toBeGreaterThan(-1);+ expect(rows[priyaAnswer].text, "Priya's run never read Tom's words").not.toContain(TOM_ASK);+ expect(priyaAnswer).toBeLessThan(tomLine);+ expect(tomLine).toBeLessThan(tomAnswer);+ expect(rows[tomLine].steered).toBeUndefined();+ expect(rows[tomLine].sender?.name).toBe("Tom");+}, hostTimeout(120_000));++it("only Priya or an admin can stop her run: Tom's Stop and typed stop are refused in words", async () => {+ await priyaRuns();+ const pressed = await team.as(tom, "POST", `/api/bots/${botId}/interrupt`, { threadId: shared });+ expect(pressed.status, JSON.stringify(pressed.body)).toBe(403);+ expect(pressed.body.error).toBe("Only Priya or an admin can stop this.");+ const typed = await send(tom, "stop");+ expect(typed.status, JSON.stringify(typed.body)).toBe(403);+ expect(typed.body.error).toBe("Only Priya or an admin can stop this.");+ expect(await busy()).toBe(true);++ const answersBefore = (await transcript(ada)).filter((row) => row.role === "bot" && row.text?.includes(ANSWERS[PRIYA_ASK])).length;+ const admin = await team.as(ada, "POST", `/api/bots/${botId}/interrupt`, { threadId: shared });+ expect(admin.status, JSON.stringify(admin.body)).toBe(200);+ await expect.poll(() => busy(), { timeout: hostTimeout(30_000), interval: 100 }).toBe(false);+ expect((await transcript(ada)).filter((row) => row.role === "bot" && row.text?.includes(ANSWERS[PRIYA_ASK])).length, "her run ended unanswered").toBe(answersBefore);+ await expect.poll(async () => (await transcript(priya)).findLast((row) => row.kind === "activity" && row.tool?.name.startsWith("stopped:"))?.stoppedBy?.name,+ { timeout: hostTimeout(10_000), interval: 100 }).toBe("Ada");+}, hostTimeout(120_000));++it("Priya can stop her own run", async () => {+ await priyaRuns();+ const own = await team.as(priya, "POST", `/api/bots/${botId}/interrupt`, { threadId: shared });+ expect(own.status, JSON.stringify(own.body)).toBe(200);+ await expect.poll(() => busy(), { timeout: hostTimeout(30_000), interval: 100 }).toBe(false);+ await expect.poll(async () => (await transcript(tom)).findLast((row) => row.kind === "activity" && row.tool?.name.startsWith("stopped:"))?.stoppedBy?.name,+ { timeout: hostTimeout(10_000), interval: 100 }).toBe("Priya");+}, hostTimeout(120_000));++it("Priya adding to her own run in the shared chat is steered into it, and person-first still answers her first", async () => {+ await priyaRuns();+ const stopsBefore = await personFirstStops();+ const more = await send(priya, PRIYA_MORE);+ expect(more.status, JSON.stringify(more.body)).toBe(202);+ expect(more.body.steered).toBe(true);+ await expect.poll(() => personFirstStops(), { timeout: hostTimeout(30_000), interval: 100 }).toBeGreaterThan(stopsBefore);+ await expect.poll(() => answered(ANSWERS[PRIYA_MORE]), { timeout: hostTimeout(30_000), interval: 100 }).toBe(true);+ await expect.poll(() => busy(), { timeout: hostTimeout(30_000), interval: 100 }).toBe(false);+}, hostTimeout(120_000));++it("three people: everyone sees whose lines wait, in order; each removes only their own; nobody else's waits steer her run", async () => {+ await priyaRuns();+ const stopsBefore = await personFirstStops();+ expect((await send(tom, TOM_ASK)).body.queued).toBe(true);+ expect((await send(sam, SAM_ASK)).body.queued).toBe(true);+ const waiting = await queue(priya);+ expect(waiting.map((item) => item.sender?.name)).toEqual(["Tom", "Sam"]);+ expect((await queue(sam)).map((item) => item.sender?.name)).toEqual(["Tom", "Sam"]);+ const [tomQueued, samQueued] = waiting;++ const notHis = await team.as(sam, "DELETE", `/api/bots/${botId}/queue/${tomQueued.queueId}`, { threadId: shared });+ expect(notHis.status, JSON.stringify(notHis.body)).toBe(403);+ const steerIn = await team.as(tom, "POST", `/api/bots/${botId}/queue/${tomQueued.queueId}/steer`, { threadId: shared });+ expect(steerIn.status, JSON.stringify(steerIn.body)).toBe(403);+ const priyaSteers = await team.as(priya, "POST", `/api/bots/${botId}/queue/${tomQueued.queueId}/steer`, { threadId: shared });+ expect(priyaSteers.status, JSON.stringify(priyaSteers.body)).toBe(403);+ const own = await team.as(sam, "DELETE", `/api/bots/${botId}/queue/${samQueued.queueId}`, { threadId: shared });+ expect(own.status, JSON.stringify(own.body)).toBe(200);+ expect((await queue(tom)).map((item) => item.sender?.name)).toEqual(["Tom"]);++ await pastPersonFirst();+ expect(await personFirstStops()).toBe(stopsBefore);+ await release();+ expect(await answered(ANSWERS[TOM_ASK])).toBe(true);+ expect((await transcript(ada)).some((row) => row.role === "user" && row.text === SAM_ASK)).toBe(false);+}, hostTimeout(120_000));++it("her private chat is unchanged: her line is steered into her run and answered first", async () => {+ const opened = await team.as(priya, "POST", `/api/bots/${botId}/tasks`, { title: "Mine" });+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);+ const mine = opened.body.task.threadId as string;+ await priyaRuns(mine);+ const more = await send(priya, PRIYA_MORE, mine);+ expect(more.body.steered).toBe(true);+ await expect.poll(() => personFirstStops(mine, priya), { timeout: hostTimeout(30_000), interval: 100 }).toBe(1);+ await expect.poll(() => answered(ANSWERS[PRIYA_MORE], mine, priya), { timeout: hostTimeout(30_000), interval: 100 }).toBe(true);+ await expect.poll(() => busy(mine, priya), { timeout: hostTimeout(30_000), interval: 100 }).toBe(false);+}, hostTimeout(120_000));++it("a routine run started mid-run neither steers nor stops her run, and Tom's line still runs after", async () => {+ const routine = await team.as(ada, "POST", "/api/routines", { name: "Pay check", prompt: "Check this week's pay runs.", botId,+ schedule: { type: "interval", everyMinutes: 1440, anchorAt: Date.now() + 86_400_000 } });+ expect(routine.status, JSON.stringify(routine.body)).toBe(201);+ await priyaRuns();+ const stopsBefore = await personFirstStops();+ expect((await send(tom, TOM_ASK)).body.queued).toBe(true);+ const ran = await team.as(ada, "POST", `/api/routines/${routine.body.routine.id}/run`);+ expect(ran.status, JSON.stringify(ran.body)).toBe(201);+ await pastPersonFirst();+ expect(await busy()).toBe(true);+ expect(await personFirstStops()).toBe(stopsBefore);++ await release();+ await expect.poll(() => answered(ANSWERS[TOM_ASK]), { timeout: hostTimeout(60_000), interval: 100 }).toBe(true);+ const results = (ran.body.run.resultsThreadId as string | undefined) ?? shared;+ await expect.poll(() => answered("This week's pay runs are fine.", results), { timeout: hostTimeout(60_000), interval: 100 }).toBe(true);+ const rows = await transcript(ada);+ const last = (text: string) => rows.findLastIndex((row) => row.text?.includes(text));+ expect(rows[last(ANSWERS[PRIYA_ASK])].text, "the routine never reached her run").not.toContain("pay runs");+ expect(last(ANSWERS[PRIYA_ASK])).toBeLessThan(last(TOM_ASK));+ expect(last(TOM_ASK)).toBeLessThan(last(ANSWERS[TOM_ASK]));+ expect(rows.some((row) => row.role === "user" && row.text?.includes("pay runs")), "the routine ran in its own conversation").toBe(false);+}, hostTimeout(180_000));++it("a person with no name set is named as the People list names them, in the queue and in the refusal", async () => {+ await priyaRuns();+ expect((await send(dev, TOM_ASK)).body.queued).toBe(true);+ expect((await queue(priya)).map((item) => item.sender?.name)).toEqual(["Dev"]);+ await release();+ writeFileSync(home("tool-calls.json"), JSON.stringify([POLL]));+ rmSync(home("release"), { force: true });+ expect((await send(dev, SAM_ASK)).status).toBe(202);+ await expect.poll(() => busy(), { timeout: hostTimeout(30_000), interval: 100 }).toBe(true);+ const refused = await team.as(tom, "POST", `/api/bots/${botId}/interrupt`, { threadId: shared });+ expect(refused.status, JSON.stringify(refused.body)).toBe(403);+ expect(refused.body.error).toBe("Only Dev or an admin can stop this.");+ const task = ((await team.as(tom, "GET", "/api/bots?messages=0")).body.bots as Array<{ id: string; tasks?: Array<{ threadId: string; askedBy?: { name: string } }> }>)+ .find((one) => one.id === botId)?.tasks?.find((one) => one.threadId === shared);+ expect(task?.askedBy?.name).toBe("Dev");+}, hostTimeout(120_000));diff --git a/server/cloud-team-away.e2e.test.ts b/server/cloud-team-away.e2e.test.tsnew file mode 100644index 0000000000..13b4a219da--- /dev/null+++ b/server/cloud-team-away.e2e.test.ts@@ -0,0 +1,126 @@+// "When you are away" end to end on a Team Cloud (docs/team-cloud.md): a stand-in Admin records what the Cloud asks it to+// email. Acme's Owner Cleo and a member Ben, a synthetic Claude CLI; a person with a live stream is here, anyone else is+// away. It proves what leaves the machine (names and hashes, never the words) and when, not how the Admin sends it.+// Disposable homes; nothing leaves this machine.+import { existsSync, rmSync, writeFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { TEAM_AWAY_ADMIN_PATH, type AwayRequest } from "./host/team-away.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const CLEO = { email: "[email protected]", role: "owner" as const };+const BEN = { email: "[email protected]", role: "member" as const };+const WINDOW_MS = 10_000;+const ENGINE = `process.env.FAKE_CLAUDE_DUMP = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/dump.json";+process.env.FAKE_CLAUDE_REPLY_FILE = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/reply.txt";`;++type Bot = { id: string; name: string; threadId: string; mainThreadId?: string; busy?: boolean; activity?: string };+const asked: { raw: string; body: AwayRequest; signed: boolean }[] = [];+let adminServer: Server, fx: CloudSendFixture, team: CloudTeamFixture;+let cleo = "", ben = "", scout: Bot;+const streams = new Map<string, AbortController>();++const notices = () => asked.flatMap((request) => request.body.notices);+const file = (name: string) => join(team.home, name);+const bots = async (token: string) => (await team.as(token, "GET", "/api/bots")).body.bots as Bot[];+async function until(done: () => Promise<boolean> | boolean, timeoutMs = 60_000): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error("timed out waiting");+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+}+async function turn(token: string, threadId: string, text: string, reply = "Done.") {+ writeFileSync(file("reply.txt"), reply);+ rmSync(file("dump.json"), { force: true });+ const sent = await team.as(token, "POST", `/api/bots/${scout.id}/messages`, { text, threadId });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await until(() => existsSync(file("dump.json")));+ await until(async () => (await bots(cleo)).every((bot) => !bot.busy && bot.activity !== "working")+ && ((await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages as { role: string; text?: string }[]).some((row) => row.role === "bot" && row.text === reply));+}+async function here(name: string, token: string) {+ const abort = new AbortController();+ streams.set(name, abort);+ const response = await fetch(`${team.base}/api/events`, { headers: { ...fx.edge, authorization: `Bearer ${token}` }, signal: abort.signal });+ void response.body!.pipeTo(new WritableStream()).catch(() => {});+ await new Promise((resolve) => setTimeout(resolve, 300));+}+function away(name: string) { streams.get(name)?.abort(); streams.delete(name); }++beforeAll(async () => {+ adminServer = createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {+ res.setHeader("content-type", "application/json");+ if (req.url !== TEAM_AWAY_ADMIN_PATH) { res.writeHead(404); res.end(JSON.stringify({ error: "Not found." })); return; }+ const raw = Buffer.concat(chunks).toString("utf8"), body = JSON.parse(raw) as AwayRequest;+ const headers = req.headers as Record<string, string>;+ asked.push({ raw, body, signed: /^v1=[\w-]{43}$/.test(headers["x-omb-cloud-signature"] ?? "") && headers["x-omb-cloud-machine"] === "0d9e8f7a-6b5c-4d3e-9f8a-7b6c5d4e3f2a" });+ res.writeHead(200);+ res.end(JSON.stringify({ v: 1, results: body.notices.map(({ id }) => ({ id, state: "sent" })) }));+ });+ });+ await new Promise<void>((resolve) => adminServer.listen(0, "127.0.0.1", resolve));+ fx = await launchCloudSendFixture({ onePasswordToken: "ops_fake-away", team: { id: "team-acme-1", name: "Acme", engine: ENGINE, env: {+ OMB_BOT_BOX: "0", FIXTURE_ADMIN_STAND_IN: `http://127.0.0.1:${(adminServer.address() as AddressInfo).port}`, OMB_TEAM_AWAY_WINDOW_MS: String(WINDOW_MS),+ } } });+ team = fx.team!;+ cleo = (await team.pair(CLEO)).token!;+ ben = (await team.pair(BEN)).token!;+ await bots(ben);+ const created = await team.as(cleo, "POST", "/api/bots", { name: "Scout" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ scout = created.body.bot as Bot;+}, hostTimeout(180_000));++afterAll(async () => {+ for (const abort of streams.values()) abort.abort();+ await fx?.close();+ await new Promise((resolve) => adminServer?.close(resolve));+});++it("Ben is away: Cleo's @Ben in Scout's shared chat asks for one email naming Cleo and Scout, never the words", async () => {+ await here("cleo", cleo);+ await turn(cleo, scout.mainThreadId ?? scout.threadId, "@Ben can you check the Globex numbers before Friday?");+ await until(() => notices().length === 1, 40_000);+ expect(asked.every((request) => request.signed)).toBe(true);+ expect(notices()).toEqual([{ id: expect.stringMatching(/^n_[\w-]{22}$/), to: BEN.email, items: [{ kind: "mention", key: expect.stringMatching(/^[0-9a-f]{64}$/), who: "Cleo", place: "Scout" }] }]);+ expect(asked.map((request) => request.raw).join("")).not.toMatch(/Globex|numbers|Friday/);+ await new Promise((resolve) => setTimeout(resolve, WINDOW_MS * 2));+ expect(notices().filter((notice) => notice.to === CLEO.email), "Cleo was here when her request finished").toEqual([]);+}, hostTimeout(120_000));++it("Cleo is away: Ben's @Cleo from his own private chat says only that Ben wrote; her shared request finishing is in the same email", async () => {+ away("cleo");+ const own = await team.as(ben, "POST", `/api/bots/${scout.id}/tasks`, { title: "Ben and Scout" });+ expect(own.status, JSON.stringify(own.body)).toBe(201);+ await turn(ben, own.body.task.threadId as string, "@Cleo I am interviewing at Globex on Thursday, keep it quiet", "Noted.");+ await turn(cleo, scout.mainThreadId ?? scout.threadId, "Summarise the week for the board", "Here is the week.");+ await until(() => notices().some((notice) => notice.to === CLEO.email), 40_000);+ const [toCleo, ...more] = notices().filter((notice) => notice.to === CLEO.email);+ expect(more).toEqual([]);+ expect(toCleo).toEqual({ id: expect.stringMatching(/^n_[\w-]{22}$/), to: CLEO.email, items: [+ { kind: "mention", key: expect.stringMatching(/^[0-9a-f]{64}$/), who: "Ben", private: true },+ { kind: "finished", key: expect.stringMatching(/^[0-9a-f]{64}$/), who: "Scout" },+ ] });+ expect(asked.map((request) => request.raw).join("")).not.toMatch(/Globex|interviewing|Ben and Scout|Summarise|board/);+}, hostTimeout(120_000));++it("someone who is here gets nothing, and the switch in their profile reaches the Admin", async () => {+ await here("ben", ben);+ const before = notices().length;+ await turn(cleo, scout.mainThreadId ?? scout.threadId, "@Ben one more thing", "Sure.");+ await new Promise((resolve) => setTimeout(resolve, WINDOW_MS * 2));+ expect(notices().slice(before).filter((notice) => notice.to === BEN.email)).toEqual([]);++ expect((await team.as(ben, "GET", "/api/me/away-emails")).body).toEqual({ on: true });+ expect((await team.as(ben, "PUT", "/api/me/away-emails", { on: false })).body).toEqual({ on: false });+ await until(() => asked.some((request) => request.body.prefs?.some((pref) => pref.to === BEN.email && !pref.on)), 10_000);+ expect((await team.as(ben, "GET", "/api/me/away-emails")).body).toEqual({ on: false });+}, hostTimeout(120_000));diff --git a/server/cloud-team-mausbot-reach.e2e.test.ts b/server/cloud-team-mausbot-reach.e2e.test.tsnew file mode 100644index 0000000000..32a026ef8f--- /dev/null+++ b/server/cloud-team-mausbot-reach.e2e.test.ts@@ -0,0 +1,293 @@+// A person's own MausBot hands work to the team's shared bots, on a Team Cloud with the synthetic Claude CLI. Mira (a+// User) asks her MausBot; the work runs in Sales' own private chat with her, at her level, and its result comes back whole+// to her private chat. Ben (a User) and Ada (an Admin) see none of it: not by id, not in lists, counts, search,+// notifications, streams, Sales' shared chat or its notes. A bot Mira cannot see is never named to her MausBot, a bot she+// can only view refuses work, and a turn her own request isn't behind hands nothing on. The engine plays a script through+// the real agents tools, so this proves the routes and what each person can see, not a model's judgement.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";+import { afterAll, beforeAll, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { personKey } from "./person-key.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const ADA = { email: "[email protected]", role: "admin" as const };+const MIRA = { email: "[email protected]", role: "member" as const };+const BEN = { email: "[email protected]", role: "member" as const };+const ENGINE = `process.env.FAKE_CLAUDE_ROOM_PLAN = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/plan.json";`;+const miraKey = personKey({ id: "", email: MIRA.email });+const SECRET = "Zebrafinch42";+const PRIVATE_NOTE = `Mira's commission is ${SECRET}`;+const ASK = `HAND-TO-SALES: pull the Q3 numbers for my commission review (${SECRET})`;++type Task = { threadId: string; title: string; private?: true };+type Bot = { id: string; name: string; threadId: string; mainThreadId: string; approvalMode?: string; unread?: boolean; defaultBot?: { person?: string }; tasks?: Task[] };+type Step = { step?: { tool?: string; arguments?: Record<string, unknown> }; response?: { error?: unknown; result?: { isError?: boolean; content?: Array<{ text: string }> } } };+type Turn = { botId: string; threadId: string; system: string; prompt: unknown; evidence: Step[]; planKey?: string };+type Line = { id: string; role: string; text?: string };++let fx: CloudSendFixture, team: CloudTeamFixture;+let ada = "", mira = "", ben = "";+let sales: Bot, archive: Bot, payroll: Bot, counsel: Bot, mausbot: Bot, mine = "";+let room = "";++const planPath = () => join(team.home, "plan.json");+const dataDir = (...rest: string[]) => join(team.home, ".openmausbot", ...rest);+const turns = (): Turn[] => existsSync(`${planPath()}.evidence.jsonl`)+ ? readFileSync(`${planPath()}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line) as Turn) : [];+const turn = (key: string): Turn => { const found = turns().find((one) => one.planKey === key); if (!found) throw new Error(`no turn ${key}`); return found; };+const sent = (one: Turn): string => { const content = (one.prompt as { message?: { content?: unknown } }).message?.content; return typeof content === "string" ? content : JSON.stringify(content); };+const stepText = (entry: Step | undefined): string => JSON.stringify(entry?.response?.result?.content ?? entry?.response?.error ?? "");+const steps = (one: Turn) => one.evidence.filter((entry) => entry.step);+const refused = (key: string) => { const step = steps(turn(key))[0]!; expect(step.response?.result?.isError, `${key}: ${stepText(step)}`).toBe(true); return stepText(step); };+const lines = async (token: string, threadId: string) => ((await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages ?? []) as Line[];+const status = async (token: string, threadId: string) => (await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=1`)).status;+const botsOf = async (token: string) => (await team.as(token, "GET", "/api/bots?messages=0")).body.bots as Bot[];+const settled = async () => (await Promise.all([ada, mira, ben].map(botsOf))).flat().every((one) => !(one as { busy?: boolean }).busy+ && !((one.tasks ?? []) as Array<{ busy?: boolean; waitingForTeammates?: boolean }>).some((task) => task.busy || task.waitingForTeammates));+async function say(text: string, threadId = mine, token = mira, bot: Bot = mausbot) {+ await expect.poll(settled, { timeout: 30_000 }).toBe(true);+ const posted = await team.as(token, "POST", `/api/bots/${bot.id}/messages`, { text, threadId });+ expect(posted.status, JSON.stringify(posted.body)).toBe(202);+}+const ran = (key: string) => expect.poll(() => turns().some((one) => one.planKey === key), { timeout: 60_000 }).toBe(true);+const handOn = (key: string, match: string, target: string, more: Record<string, unknown> = {}, expectError = false) => ({+ key, match: [match], reply: `${key} done`,+ steps: [{ arguments: { bot_ids: [target], message: `${key}: pull the numbers for Mira`, reason: "Mira asked", ...more }, ...(expectError ? { expectError: true } : {}) }],+});+async function workRows(): Promise<Array<Record<string, unknown>>> {+ const db = new DatabaseSync(dataDir("runtime.db"), { readOnly: true });+ try { return db.prepare("select * from assignments").all() as Array<Record<string, unknown>>; } finally { db.close(); }+}+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 expect.poll(() => text.includes("\"hello\""), { timeout: 10_000 }).toBe(true);+ return { text: () => text, close: async () => { controller.abort(); await done; } };+}++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-7", name: "Acme", engine: ENGINE } });+ team = fx.team!;+ ada = (await team.pair(ADA)).token!;+ mira = (await team.pair(MIRA)).token!;+ ben = (await team.pair(BEN)).token!;+ for (const [token, name] of [[ada, "Ada"], [mira, "Mira"], [ben, "Ben"]] as const) expect((await team.as(token, "PUT", "/api/me", { name })).status).toBe(200);+ const create = async (name: string) => {+ const created = await team.as(ada, "POST", "/api/bots", { name, title: name });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ return created.body.bot as Bot;+ };+ const share = async (bot: Bot, access: { everyone: string; people: Record<string, string> }) =>+ expect((await team.as(ada, "PUT", `/api/bots/${bot.id}/access`, access)).status).toBe(200);+ sales = await create("Sales");+ archive = await create("Archive");+ payroll = await create("Payroll");+ counsel = await create("Counsel");+ await share(archive, { everyone: "view", people: {} });+ await share(payroll, { everyone: "none", people: { [BEN.email]: "chat" } });+ mausbot = (await botsOf(mira)).find((bot) => bot.defaultBot?.person === MIRA.email)!;+ expect(mausbot, "every member has their own MausBot").toBeDefined();+ const chat = await team.as(mira, "POST", `/api/bots/${mausbot.id}/tasks`, { title: "Mine" });+ expect(chat.status, JSON.stringify(chat.body)).toBe(201);+ mine = chat.body.task.threadId as string;+ const made = await team.as(ada, "POST", "/api/groups", { name: "All hands", memberIds: [sales.id] });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ room = (made.body.group as { id: string }).id;+ writeFileSync(planPath(), JSON.stringify({+ [mausbot.id]: { script: [+ { key: "M-LIST", match: ["WHO-CAN-YOU-REACH"], reply: "Listed.", steps: [{ tool: "list_bots", arguments: {} }] },+ { key: "M-SALES", match: ["HAND-TO-SALES"], reply: "Asked Sales.", steps: [{ arguments: { bot_ids: ["Sales"], message: ASK, reason: "Mira asked" } }] },+ { key: "M-RESUMED", repeat: true, match: ["report on assignment"], reply: "M-RESUMED done" },+ handOn("M-VIEW", "HAND-TO-ARCHIVE", "Archive", {}, true),+ handOn("M-HIDDEN-NAME", "HAND-TO-PAYROLL-NAME", "Payroll", {}, true),+ handOn("M-UNKNOWN-NAME", "HAND-TO-NOBODY-NAME", "Quokka", {}, true),+ { key: "M-HIDDEN-ID", match: ["HAND-TO-PAYROLL-ID"], reply: "done", steps: [{ arguments: { bot_ids: [payroll.id], message: "Pull the payroll", reason: "Mira asked" }, expectError: true }] },+ { key: "M-UNKNOWN-ID", match: ["HAND-TO-NOBODY-ID"], reply: "done", steps: [{ arguments: { bot_ids: ["bot_doesnotexist0"], message: "Pull the payroll", reason: "Mira asked" }, expectError: true }] },+ handOn("M-ROOM", "HAND-INTO-ROOM", "Sales", { group_id: room }, true),+ handOn("M-MAIN", "HAND-TO-MAIN-THREAD", "Sales", { thread: sales.threadId }, true),+ handOn("M-FROM-MAIN", "FROM-MY-MAIN-CHAT", "Sales"),+ handOn("M-RELAYED", "RELAYED-LINE", "Sales", {}, true),+ handOn("M-ROUTINE", "ROUTINE-LINE", "Sales", {}, true),+ ] },+ [sales.id]: { script: [+ { key: "S-FROM-MAIN", match: ["M-FROM-MAIN"], reply: "Sales: done from her main chat." },+ { key: "S-WORK", match: ["HAND-TO-SALES"], reply: `Sales: Q3 was 120k. Noted ${SECRET}.`, steps: [+ { tool: "memory_update", arguments: { action: "append", text: PRIVATE_NOTE } },+ { tool: "propose_team_memory", arguments: { kind: "decision", name: "Commission", detail: PRIVATE_NOTE }, expectError: true },+ { tool: "post_to_room", arguments: { group_id: room, message: PRIVATE_NOTE }, expectError: true },+ ] },+ ] },+ [counsel.id]: { script: [+ { key: "C-ASKS", match: ["BEN-ASKS-COUNSEL"], reply: "NEEDS INPUT: What is the password for the contract portal?" },+ { key: "C-CARRIES", repeat: true, match: ["FORGED-ANSWER"], reply: "C-CARRIES: carried on" },+ ] },+ }));+}, hostTimeout(120_000));++afterAll(async () => {+ await fx?.close();+});++it("lists only the shared bots Mira may chat with, in its roster and in list_bots, and nothing of the rest", async () => {+ await say("WHO-CAN-YOU-REACH");+ await ran("M-LIST");+ const listed = turn("M-LIST");+ expect(listed.system).toContain("Sales");+ expect(listed.system).toContain("private chat with this person");+ for (const hidden of ["Payroll", payroll.id, "Archive", archive.id]) expect(listed.system).not.toContain(hidden);+ const names = stepText(steps(listed)[0]);+ expect(names).toContain(sales.id);+ expect(names).toContain(counsel.id);+ for (const hidden of ["Payroll", payroll.id, archive.id]) expect(names).not.toContain(hidden);+}, hostTimeout(90_000));++it("hands work to Sales privately: the result comes back to Mira whole, and Ben and the Admin see nothing of it anywhere", async () => {+ const before = Object.fromEntries(await Promise.all([["ada", ada], ["ben", ben]].map(async ([who, token]) => [who, (await botsOf(token!)).find((bot) => bot.id === sales.id)!.unread])));+ const streams = { ada: await listen(ada), ben: await listen(ben) };+ const miraStream = await listen(mira);+ await say(ASK);+ await ran("M-RESUMED");+ await expect.poll(async () => (await lines(mira, mine)).some((line) => line.text === "M-RESUMED done"), { timeout: 60_000 }).toBe(true);+ await expect.poll(settled, { timeout: 30_000 }).toBe(true);++ const work = turn("S-WORK");+ expect(sent(work)).toMatch(/\[From @MausBot \(bot\) · assignment \S+ for Mira · on their behalf at your level\]/);+ expect(sent(turn("M-RESUMED")), "her result comes back whole: this is her own chat").toContain("Q3 was 120k");+ const seen = (await botsOf(mira)).find((bot) => bot.id === sales.id)!.tasks!.find((task) => task.threadId === work.threadId)!;+ expect(seen, "Sales' chat with Mira is listed for her").toBeDefined();+ expect(seen.private).toBe(true);+ expect(await status(mira, work.threadId)).toBe(200);+ expect(JSON.stringify(miraStream.text())).toContain(work.threadId);++ for (const [who, token] of [["ada", ada], ["ben", ben]] as const) {+ expect(await status(token, work.threadId), who).toBe(404);+ expect(await status(token, mine), who).toBe(404);+ const salesCopy = (await botsOf(token)).find((bot) => bot.id === sales.id)!;+ expect(salesCopy.tasks!.map((task) => task.threadId), who).not.toContain(work.threadId);+ expect(salesCopy.unread, `${who}: Sales' unread mark`).toBe(before[who]);+ expect(JSON.stringify(await lines(token, sales.threadId)), `${who}: Sales' shared chat`).not.toContain(SECRET);+ for (const route of ["/api/bots", `/api/search?q=${SECRET}`, "/api/notifications", "/api/today", "/api/needs-you", "/api/inbox", `/api/bots/${sales.id}/memory/mine`, `/api/bots/${sales.id}/activity`]) {+ const answer = await team.as(token, "GET", route);+ expect(answer.status, `${who}: ${route}`).toBeLessThan(500);+ expect(JSON.stringify(answer.body), `${who}: ${route}`).not.toContain(SECRET);+ expect(JSON.stringify(answer.body), `${who}: ${route}`).not.toContain(work.threadId);+ }+ expect(streams[who].text(), `${who}: event stream`).not.toContain(SECRET);+ expect(streams[who].text(), `${who}: event stream`).not.toContain(work.threadId);+ }+ for (const stream of [...Object.values(streams), miraStream]) await stream.close();++ // Sales could not take it into a room or the team's notes, and its note landed in Mira's layer alone.+ const [noted, teamMemory, roomPost] = steps(work);+ expect(noted!.response?.result?.isError).toBeFalsy();+ expect(teamMemory!.response?.result?.isError).toBe(true);+ expect(roomPost!.response?.result?.isError).toBe(true);+ expect(readFileSync(dataDir("workspaces", `${sales.id}--member-${miraKey}`, "MEMORY.md"), "utf8")).toContain(PRIVATE_NOTE);+ const teamNotes = dataDir("workspaces", sales.id, "MEMORY.md");+ expect(existsSync(teamNotes) ? readFileSync(teamNotes, "utf8") : "").not.toContain(SECRET);+ expect(existsSync(dataDir("workspaces", `${sales.id}--member-${personKey({ id: "", email: BEN.email })}`, "MEMORY.md"))).toBe(false);++ // The work acts for her and nobody else.+ const handed = JSON.parse(readFileSync(dataDir("handed-people.json"), "utf8")) as { work: Record<string, { person: string }> };+ const row = (await workRows()).find((one) => one.assignee_thread_id === work.threadId)!;+ expect(handed.work[String(row.id)]?.person).toBe(miraKey);+}, hostTimeout(180_000));++it("a bot Mira cannot see is refused exactly like one that does not exist, by name and by id, and runs nothing", async () => {+ for (const [text, key] of [["HAND-TO-PAYROLL-NAME", "M-HIDDEN-NAME"], ["HAND-TO-NOBODY-NAME", "M-UNKNOWN-NAME"], ["HAND-TO-PAYROLL-ID", "M-HIDDEN-ID"], ["HAND-TO-NOBODY-ID", "M-UNKNOWN-ID"]] as const) {+ await say(text);+ await ran(key);+ }+ const byName = refused("M-HIDDEN-NAME"), unknownName = refused("M-UNKNOWN-NAME");+ expect(byName.replaceAll("Payroll", "X")).toBe(unknownName.replaceAll("Quokka", "X"));+ const byId = refused("M-HIDDEN-ID"), unknownId = refused("M-UNKNOWN-ID");+ expect(byId.replaceAll(payroll.id, "X")).toBe(unknownId.replaceAll("bot_doesnotexist0", "X"));+ for (const said of [byName, byId]) for (const leak of ["Ben", "Ada", "looks after", "admin"]) expect(said).not.toContain(leak);+ expect(byId).not.toContain("Payroll");+ expect(turns().filter((one) => one.botId === payroll.id)).toEqual([]);+}, hostTimeout(150_000));++it("a bot Mira can only view refuses work, and says so plainly", async () => {+ await say("HAND-TO-ARCHIVE");+ await ran("M-VIEW");+ expect(refused("M-VIEW")).toContain("view only");+ expect(turns().filter((one) => one.botId === archive.id)).toEqual([]);+}, hostTimeout(90_000));++it("never into a room, nor into Sales' shared chat", async () => {+ for (const [text, key] of [["HAND-INTO-ROOM", "M-ROOM"], ["HAND-TO-MAIN-THREAD", "M-MAIN"]] as const) {+ await say(text);+ await ran(key);+ refused(key);+ }+ expect(JSON.stringify(await lines(ada, sales.threadId))).not.toContain("pull the numbers for Mira");+}, hostTimeout(120_000));++it("works from her MausBot's main chat too, which is hers alone", async () => {+ const main = (await botsOf(mira)).find((bot) => bot.id === mausbot.id)!.mainThreadId;+ expect(main).toBeTruthy();+ await say("FROM-MY-MAIN-CHAT", main);+ await ran("S-FROM-MAIN");+ const work = turn("S-FROM-MAIN");+ expect(await status(mira, work.threadId)).toBe(200);+ expect(await status(ada, work.threadId)).toBe(404);+ expect(await status(ben, work.threadId)).toBe(404);+}, hostTimeout(90_000));++it("a line another app relays into her private chat hands nothing on", async () => {+ await expect.poll(settled, { timeout: 30_000 }).toBe(true);+ const leaf = (await team.as(mira, "GET", `/api/threads/${mine}/messages?limit=1`)).body.activeLeafId ?? null;+ const mode = (await botsOf(mira)).find((bot) => bot.id === mausbot.id)!.approvalMode ?? "ask";+ const relayed = await fetch(`${team.base}/api/bots/${mausbot.id}/messages/guarded`, {+ method: "POST", headers: { "content-type": "application/json" },+ body: JSON.stringify({ threadId: mine, sendId: "slackjob_mausbot_reach_1", text: "RELAYED-LINE", expectedActiveLeafId: leaf, expectedApprovalMode: mode, onBehalfOf: { email: MIRA.email, name: "Mira" } }),+ });+ expect(relayed.status, await relayed.clone().text()).toBe(202);+ await ran("M-RELAYED");+ refused("M-RELAYED");+ expect(turns().filter((one) => one.botId === sales.id && sent(one).includes("M-RELAYED"))).toEqual([]);+}, hostTimeout(90_000));++it("her routine, with nobody behind it, hands nothing on", async () => {+ await expect.poll(settled, { timeout: 30_000 }).toBe(true);+ const created = await team.as(mira, "POST", "/api/routines", { name: "Nightly", prompt: "ROUTINE-LINE", botId: mausbot.id, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ expect((await team.as(mira, "POST", `/api/routines/${created.body.routine.id}/run`)).status).toBe(201);+ await ran("M-ROUTINE");+ refused("M-ROUTINE");+ expect(turns().filter((one) => one.botId === sales.id && sent(one).includes("M-ROUTINE"))).toEqual([]);+}, hostTimeout(90_000));++it("cannot answer a question waiting in Ben's private work, even knowing its id", async () => {+ await expect.poll(settled, { timeout: 30_000 }).toBe(true);+ const bensMausbot = (await botsOf(ben)).find((bot) => bot.defaultBot?.person === BEN.email)!;+ const bensChat = (await team.as(ben, "POST", `/api/bots/${bensMausbot.id}/tasks`, { title: "Mine" })).body.task.threadId as string;+ const plan = JSON.parse(readFileSync(planPath(), "utf8"));+ plan[bensMausbot.id] = { script: [{ key: "B-ASKS", match: ["BEN-HANDS-ON"], reply: "Asking.", steps: [{ arguments: { bot_ids: ["Counsel"], message: "BEN-ASKS-COUNSEL", reason: "Ben asked" } }] }, { key: "B-RESUMED", repeat: true, match: ["on assignment"], reply: "B-RESUMED done" }] };+ writeFileSync(planPath(), JSON.stringify(plan));+ await say("BEN-HANDS-ON", bensChat, ben, bensMausbot);+ await ran("C-ASKS");+ await expect.poll(async () => (await workRows()).some((row) => row.status === "needs_input"), { timeout: 60_000 }).toBe(true);+ const waiting = (await workRows()).find((row) => row.status === "needs_input")!;++ const later = JSON.parse(readFileSync(planPath(), "utf8"));+ later[mausbot.id].script.push({ key: "M-ANSWERS", match: ["ANSWER-BENS-QUESTION"], reply: "M-ANSWERS done",+ steps: [{ arguments: { bot_ids: ["Counsel"], message: "FORGED-ANSWER contract B", reason: "Mira answers", answers: String(waiting.id) }, expectError: true }] });+ writeFileSync(planPath(), JSON.stringify(later));+ await expect.poll(async () => (await workRows()).find((row) => row.id === waiting.id)?.status, { timeout: 30_000 }).toBe("needs_input");+ const posted = await team.as(mira, "POST", `/api/bots/${mausbot.id}/messages`, { text: "ANSWER-BENS-QUESTION", threadId: mine });+ expect(posted.status, JSON.stringify(posted.body)).toBe(202);+ await ran("M-ANSWERS");+ refused("M-ANSWERS");+ expect((await workRows()).find((row) => row.id === waiting.id)!.status).toBe("needs_input");+ expect(turns().some((one) => one.planKey === "C-CARRIES")).toBe(false);+}, hostTimeout(180_000));diff --git a/server/cloud-team-new-chat-private.e2e.test.ts b/server/cloud-team-new-chat-private.e2e.test.tsnew file mode 100644index 0000000000..1fb51ce46b--- /dev/null+++ b/server/cloud-team-new-chat-private.e2e.test.ts@@ -0,0 +1,97 @@+// A conversation a person opens on a Team Cloud is private to them from its first frame: another member and an admin,+// listening on their streams while it is made, never get its id or its title in any frame, live or replayed, and their+// copy of the bot (its threads, their labels, its main chat) does not change at all. A new member's own MausBot is theirs+// from its first frame too: nobody else is ever sent its main chat.+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 ADA = { email: "[email protected]", role: "admin" as const };+const CLEO = { email: "[email protected]", role: "member" as const };+const MIRA = { email: "[email protected]", role: "member" as const };+const BEN = { email: "[email protected]", role: "member" as const };+const TITLE = "Kumquat salary talks";++type Task = { threadId: string; title: string; sharedChat?: true; private?: true };+type Bot = { id: string; threadId: string; mainThreadId?: string; unread?: boolean; defaultBot?: { person?: string }; tasks?: Task[] };++let fx: CloudSendFixture, team: CloudTeamFixture;+let ada = "", mira = "", ben = "";+let scout: Bot;++async function listen(token: string, headers: Record<string, string> = {}) {+ const controller = new AbortController();+ const stream = await fetch(`${team.base}/api/events`, { headers: { ...fx.edge, authorization: `Bearer ${token}`, accept: "text/event-stream", ...headers }, 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 expect.poll(() => text.includes("\"hello\""), { timeout: 10_000 }).toBe(true);+ return { text: () => text, cursor: /"cursor":"([^"]+)"/.exec(text)![1]!, close: async () => { controller.abort(); await done; } };+}+const view = (bot: Bot) => ({ threadId: bot.threadId, mainThreadId: bot.mainThreadId, unread: bot.unread, tasks: bot.tasks!.map(({ threadId, title, sharedChat }) => ({ threadId, title, sharedChat })) });+const botFrames = (text: string, botId: string): Bot[] => text.split("\n").filter((line) => line.startsWith("data: ")).map((line) => JSON.parse(line.slice(6)) as { kind: string; bot?: Bot })+ .flatMap((frame) => (frame.kind === "bot" && frame.bot?.id === botId ? [frame.bot] : []));+const scoutOf = async (token: string) => ((await team.as(token, "GET", "/api/bots?messages=0")).body.bots as Bot[]).find((bot) => bot.id === scout.id)!;++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-8", name: "Acme" } });+ team = fx.team!;+ ada = (await team.pair(ADA)).token!;+ mira = (await team.pair(MIRA)).token!;+ ben = (await team.pair(BEN)).token!;+ const created = await team.as(ada, "POST", "/api/bots", { name: "Scout" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ scout = created.body.bot as Bot;+}, hostTimeout(120_000));++afterAll(async () => {+ await fx?.close();+});++it("never shows another member or an admin a conversation someone opens, from its first frame on", async () => {+ const before = { ada: view(await scoutOf(ada)), ben: view(await scoutOf(ben)) };+ const shared = before.ada.mainThreadId!;+ expect(before.ada.tasks.find((task) => task.threadId === shared)?.sharedChat).toBe(true);+ const streams = { ada: await listen(ada), ben: await listen(ben) };+ const own = await listen(mira);+ const opened = await team.as(mira, "POST", `/api/bots/${scout.id}/tasks`, { title: TITLE });+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);+ const threadId = opened.body.task.threadId as string;+ await expect.poll(() => own.text().includes(threadId), { timeout: 10_000 }).toBe(true);+ expect((await scoutOf(mira)).tasks!.find((task) => task.threadId === threadId)?.title).toBe(TITLE);++ for (const [who, token] of [["ada", ada], ["ben", ben]] as const) {+ expect(streams[who].text(), `${who}: live stream`).not.toContain(threadId);+ expect(streams[who].text(), `${who}: live stream`).not.toContain(TITLE);+ const replayed = await listen(token, { "last-event-id": streams[who].cursor });+ expect(replayed.text(), `${who}: replayed stream`).not.toContain(threadId);+ expect(replayed.text(), `${who}: replayed stream`).not.toContain(TITLE);+ await replayed.close();+ expect(view(await scoutOf(token)), `${who}: their copy of Scout`).toEqual(before[who]);+ for (const frame of botFrames(streams[who].text(), scout.id)) {+ expect(frame.mainThreadId, `${who}: a bot frame's main chat`).toBe(shared);+ expect(frame.tasks?.filter((task) => task.sharedChat).map((task) => task.threadId), `${who}: a bot frame's Shared chat`).toEqual([shared]);+ }+ expect(JSON.stringify((await team.as(token, "GET", "/api/bots")).body), `${who}: /api/bots`).not.toContain(TITLE);+ }+ for (const stream of [...Object.values(streams), own]) await stream.close();+}, hostTimeout(90_000));++it("never sends anyone else a new member's own MausBot's main chat, from its first frame on", async () => {+ const streams = { ada: await listen(ada), ben: await listen(ben) };+ const cleo = (await team.pair(CLEO)).token!;+ const own = await expect.poll(async () => ((await team.as(cleo, "GET", "/api/bots?messages=0")).body.bots as Bot[]).find((bot) => bot.defaultBot?.person === CLEO.email), { timeout: 20_000 })+ .toBeTruthy().then(async () => ((await team.as(cleo, "GET", "/api/bots?messages=0")).body.bots as Bot[]).find((bot) => bot.defaultBot?.person === CLEO.email)!);+ const main = own.mainThreadId ?? own.threadId;+ expect(own.tasks!.map((task) => task.threadId)).toContain(main);+ for (const [who, token] of [["ada", ada], ["ben", ben]] as const) {+ expect(streams[who].text(), `${who}: live stream`).not.toContain(main);+ expect(JSON.stringify((await team.as(token, "GET", "/api/bots?messages=0")).body), `${who}: /api/bots`).not.toContain(main);+ expect((await team.as(token, "GET", `/api/threads/${main}/messages?limit=1`)).status, `${who}: opening it`).toBe(404);+ }+ for (const stream of Object.values(streams)) await stream.close();+}, hostTimeout(90_000));diff --git a/server/cloud-team-policy.ts b/server/cloud-team-policy.tsindex 9a650b4f3e..647254d17e 100644--- a/server/cloud-team-policy.ts+++ b/server/cloud-team-policy.ts@@ -275,7 +275,7 @@ export function startTeamPolicyClient(options: TeamPolicyClientOptions): TeamPollet cloudTeam: TeamPolicyClient | null = null;/** A Team Cloud only; a My Cloud has no team, no rules and no fetch. */-export function startCloudTeamPolicy(input: { cloudHome: CloudHomeConfig | null; dataDir: string; managed: ManagedDesktopPolicy; sessions: Pick<SessionRegistry, "closeMemberPhones"> }): void {+export function startCloudTeamPolicy(input: { cloudHome: CloudHomeConfig | null; dataDir: string; managed: ManagedDesktopPolicy; sessions: Pick<SessionRegistry, "closeMemberPhones" | "closeMemberBrowsers"> }): void {const { cloudHome, managed, sessions } = input;if (!cloudHome?.team || cloudTeam) return;cloudTeam = startTeamPolicyClient({@@ -283,7 +283,7 @@ export function startCloudTeamPolicy(input: { cloudHome: CloudHomeConfig | null;log: (line) => console.log(`team cloud: ${line}`),apply: (policy) => {managed.apply(policy);- if (policy && !policy.remoteAccess) sessions.closeMemberPhones();+ if (policy && !policy.remoteAccess) { sessions.closeMemberPhones(); sessions.closeMemberBrowsers(); }},});const client = cloudTeam;diff --git a/server/cloud-team-roster.test.ts b/server/cloud-team-roster.test.tsnew file mode 100644index 0000000000..bb1d53e1fc--- /dev/null+++ b/server/cloud-team-roster.test.ts@@ -0,0 +1,166 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { startTeamRoster, TEAM_ROSTER_ADMIN_PATH, teamRosterSignature } from "./cloud-team-roster.ts";+import { SessionRegistry } from "./sessions.ts";++const HOUR = 60 * 60_000, MINUTE = 60_000;+const ADA = { email: "[email protected]", role: "member" as const };+const ADMIN = "https://cloud.example.test";+const SECRET = "s".repeat(43);++let dir: string, clock: number, registry: SessionRegistry;+beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "omb-team-roster-"));+ clock = Date.UTC(2026, 10, 10, 9);+ registry = new SessionRegistry({ file: join(dir, "sessions.json"), now: () => clock });+});+afterEach(() => { registry.close(); rmSync(dir, { recursive: true, force: true }); });++/** A browser sign-in the Admin signed for a member (the join page's Open, a User's team home). */+function browserSession(member: { email: string; role: "owner" | "admin" | "member" } = ADA) {+ const { credential } = registry.openPairing({ scopes: ["client"], member, browser: true, owner: member.email });+ const paired = registry.exchange({ code: credential, browser: true, label: "Safari on Mac", source: "b" });+ if (!paired.ok) throw new Error(paired.error);+ return paired.token;+}+/** A code the member made from that session, redeemed by their phone. */+function phoneSession(token: string) {+ const session = registry.authenticate(token)!;+ const { code } = registry.openPairing({ scopes: ["client"], member: { email: session.email!, role: session.teamRole! }, memberCheckedAt: session.createdAt });+ const paired = registry.exchange({ code, label: "Ada's phone", source: "p" });+ if (!paired.ok) throw new Error(paired.error);+ return paired.token;+}++/** The Admin as the Team Cloud meets it: checks the signature, answers each address's role from `roster`. */+function admin(roster: Record<string, string | null>, options: { status?: number; down?: boolean } = {}) {+ const asked: string[][] = [];+ const fetchImpl = (async (url: string, init: RequestInit) => {+ if (options.down) throw new TypeError("fetch failed");+ expect(url).toBe(`${ADMIN}${TEAM_ROSTER_ADMIN_PATH}`);+ const headers = init.headers as Record<string, string>, body = String(init.body);+ expect(headers["x-omb-cloud-signature"]).toBe(`v1=${teamRosterSignature(SECRET, "cm-home", headers["x-omb-cloud-timestamp"]!, headers["x-omb-cloud-nonce"]!, body)}`);+ const emails = (JSON.parse(body) as { emails: string[] }).emails;+ asked.push(emails);+ if (options.status) return Response.json({ error: "no" }, { status: options.status });+ return Response.json({ members: Object.fromEntries(emails.map((email) => [email, roster[email] ?? null])) });+ }) as unknown as typeof fetch;+ const roster_ = startTeamRoster({ machineId: "cm-home", adminOrigin: ADMIN, secret: SECRET, sessions: registry, fetchImpl, now: () => clock,+ setTimer: () => ({}), clearTimer: () => {} });+ return { check: roster_.check, asked };+}++describe("a Team Cloud's roster check", () => {+ it("signs as openmaus-cloud's server/cloud-team-roster.ts does", () => {+ // The same vector is pinned in openmaus-cloud tests/cloud-team-join.test.ts.+ expect(teamRosterSignature(SECRET, "cm-test-home", "1792670400", "nonce-nonce-nonce-1", '{"v":1,"emails":["[email protected]"]}')).toBe("WvlpjOna5b6fkOkqkNZgLdv0c913uLp8ufS_2gFEI3Y");+ });++ it("keeps a member's browser and phone signed in while they use them, with no desktop pairing again, and across a restart", async () => {+ const browser = browserSession(), phone = phoneSession(browser);+ const started = clock;+ const { check, asked } = admin({ [ADA.email]: "member" });+ // Used through the first hour: each check keeps both another hour from their last use.+ for (let minute = 5; minute <= 55; minute += 5) {+ clock = started + minute * MINUTE;+ registry.authenticate(browser); registry.authenticate(phone);+ await check();+ }+ expect(asked.every((emails) => emails.length === 1 && emails[0] === ADA.email)).toBe(true);+ expect(registry.authenticate(browser)?.expiresAt).toBeGreaterThan(started + HOUR);+ registry.close();+ registry = new SessionRegistry({ file: join(dir, "sessions.json"), now: () => clock });+ clock = started + HOUR + 10 * MINUTE;+ expect(registry.authenticate(browser), "past the first hour, kept by the Admin's word").not.toBeNull();+ expect(registry.authenticate(phone)).not.toBeNull();+ });++ it("one person, two sessions, one left idle (a shared computer): the idle one ends within the hour of its last use, the one in use is kept", async () => {+ const idle = browserSession(), active = browserSession();+ const opened = clock;+ const { check } = admin({ [ADA.email]: "member" });+ for (let minute = 5; minute <= 120; minute += 5) {+ clock = opened + minute * MINUTE;+ registry.authenticate(active);+ await check();+ }+ clock = opened + HOUR;+ expect(registry.authenticate(idle), "never used after it opened: it ends at its hour").toBeNull();+ clock = opened + 2 * HOUR;+ expect(registry.authenticate(active)).not.toBeNull();+ // The active one, left alone now: it too ends within the hour of its last use.+ const lastUse = clock;+ for (let minute = 5; minute <= 65; minute += 5) { clock = lastUse + minute * MINUTE; await check(); }+ expect(registry.authenticate(active)).toBeNull();+ });++ it("asks nothing about a session nobody used in the last hour, and lets it end", async () => {+ const browser = browserSession();+ const { check, asked } = admin({ [ADA.email]: "member" });+ // Used once, then kept by the checks while that use is within the hour; never past an hour from it.+ clock += 2 * MINUTE;+ registry.authenticate(browser);+ const used = clock;+ clock = used + 30 * MINUTE;+ await check();+ expect(asked).toEqual([[ADA.email]]);+ const end = registry.list()[0]!.expiresAt;+ expect(end).toBeLessThanOrEqual(used + HOUR);+ asked.length = 0;+ clock = used + HOUR + 1;+ await check();+ expect(asked, "its last use is over an hour ago: not asked about").toEqual([]);+ expect(registry.list()).toEqual([]);+ });++ it("signs someone out at the next check when the Admin no longer lists them, ends sessions at a role they no longer have, and never upgrades one", async () => {+ const ada = browserSession(), ben = browserSession({ email: "[email protected]", role: "admin" }), cleo = browserSession({ email: "[email protected]", role: "member" });+ const { check } = admin({ [ADA.email]: null, "[email protected]": "member", "[email protected]": "admin" });+ clock += 5 * MINUTE;+ registry.authenticate(ada); registry.authenticate(ben); registry.authenticate(cleo);+ await check();+ expect(registry.authenticate(ada), "removed: out at the first check, not when the session nears its end").toBeNull();+ expect(registry.authenticate(ben), "an Admin made a User: their admin session ends").toBeNull();+ expect(registry.authenticate(cleo), "a User made an Admin: the member session ends rather than gaining admin").toBeNull();+ expect(registry.list().some((session) => session.scopes.includes("admin"))).toBe(false);+ });++ it("never keeps a script's token or a move-in sign-in alive", async () => {+ const issued = registry.issueMoveIn({ label: "Moving a bot in", email: ADA.email, teamRole: "member", bot: "bot-1" });+ const before = registry.list().find((session) => session.id === issued.session.id)!.expiresAt;+ const { check, asked } = admin({ [ADA.email]: "member" });+ clock += 5 * MINUTE;+ registry.authenticate(issued.token);+ await check();+ expect(asked).toEqual([]);+ expect(registry.list().find((session) => session.id === issued.session.id)?.expiresAt).toBe(before);+ });++ it("no answer, a refusal or an older Admin changes nothing: sessions end within the hour, as before", async () => {+ for (const options of [{ down: true }, { status: 404 }, { status: 401 }, { status: 503 }]) {+ const browser = browserSession(), opened = clock;+ const { check } = admin({ [ADA.email]: "member" }, options);+ clock += 45 * MINUTE;+ registry.authenticate(browser);+ await check();+ expect(registry.authenticate(browser)?.expiresAt).toBe(opened + HOUR);+ clock = opened + HOUR;+ expect(registry.authenticate(browser)).toBeNull();+ }+ });+});++describe("why a session ended", () => {+ it("remembers, by digest, the sessions of someone no longer in the team; a role change or an ended session is no such thing", async () => {+ const ada = browserSession(), ben = browserSession({ email: "[email protected]", role: "admin" });+ registry.revokeMember(ADA.email);+ registry.revokeMember("[email protected]", "member");+ expect(registry.leftTeam(ada)).toBe(true);+ expect(registry.leftTeam(ben)).toBe(false);+ expect(registry.leftTeam("omb_sess_" + "y".repeat(43))).toBe(false);+ clock += 25 * HOUR;+ expect(registry.leftTeam(ada), "said for a day").toBe(false);+ });+});diff --git a/server/cloud-team-roster.ts b/server/cloud-team-roster.tsnew file mode 100644index 0000000000..c8e0719bab--- /dev/null+++ b/server/cloud-team-roster.ts@@ -0,0 +1,127 @@+// A Team Cloud's roster check: every 5 minutes it asks the Admin, signed with its bootstrap secret, whether the people+// whose sessions were used in the last hour are still in the team, and at which role (openmaus-cloud docs/team-cloud.md "A+// session that lives without a desktop"). A member found at their role keeps each session they use until an hour after its+// last use, so a browser or a phone stays signed in with no desktop re-pairing; anyone the Admin no longer lists is signed+// out at once, at the next check.+// Security invariants: membership is the Admin's word only, read fresh, about this Cloud's own team. No answer changes+// nothing, so a session still ends within the hour of the last word, as every team session did before.+import { createHash, createHmac, randomBytes } from "node:crypto";+import { z } from "zod";+import type { CloudHomeConfig } from "./cloud-home.ts";+import { isTeamRole } from "./cloud-team.ts";+import type { SessionRegistry } from "./sessions.ts";++/** On the Admin; must match openmaus-cloud's TEAM_ROSTER_MACHINE_PATH. */+export const TEAM_ROSTER_ADMIN_PATH = "/api/cloud/machines/team-member";+export const TEAM_ROSTER_EVERY_MS = 5 * 60_000;+/** The Admin's own limit on one ask. */+export const TEAM_ROSTER_MAX = 50;+const FETCH_TIMEOUT_MS = 15_000, ANSWER_MAX_BYTES = 64 * 1024;++/** Must match openmaus-cloud's teamRosterSignature: a context of its own, so no other signed request reads as one. */+export function teamRosterSignature(secret: string, machineId: string, timestamp: string, nonce: string, body: string): string {+ const bodyHash = createHash("sha256").update(body).digest("base64url");+ return createHmac("sha256", secret).update(`omb-team-roster-v1\n${machineId}\n${timestamp}\n${nonce}\n${bodyHash}`).digest("base64url");+}++const answerSchema = z.object({ members: z.record(z.string(), z.unknown()) });++interface Timer { unref?(): unknown }++export interface TeamRosterOptions {+ machineId: string;+ adminOrigin: string;+ secret: string;+ sessions: Pick<SessionRegistry, "membersToVouch" | "vouchMember" | "revokeMember">;+ fetchImpl?: typeof fetch;+ log?: (line: string) => void;+ now?: () => number;+ random?: () => number;+ setTimer?: (run: () => void, ms: number) => Timer;+ clearTimer?: (timer: Timer) => void;+}++export interface TeamRoster {+ /** One check now; it never rejects. */+ check(): Promise<void>;+ stop(): void;+}++export function startTeamRoster(options: TeamRosterOptions): TeamRoster {+ const now = options.now ?? Date.now, log = options.log ?? (() => {}), random = options.random ?? Math.random;+ const fetcher = options.fetchImpl ?? globalThis.fetch;+ const setTimer = options.setTimer ?? ((run, ms) => setTimeout(run, ms));+ const clearTimer = options.clearTimer ?? ((timer) => clearTimeout(timer as ReturnType<typeof setTimeout>));+ let timer: Timer | null = null, stopped = false, running: Promise<void> | null = null;++ const ask = async (): Promise<void> => {+ const emails = options.sessions.membersToVouch(TEAM_ROSTER_MAX);+ if (!emails.length) return;+ const body = JSON.stringify({ v: 1, emails });+ const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");+ let response: Response;+ try {+ response = await fetcher(`${options.adminOrigin}${TEAM_ROSTER_ADMIN_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), headers: {+ accept: "application/json", "content-type": "application/json", "x-omb-cloud-machine": options.machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,+ "x-omb-cloud-signature": `v1=${teamRosterSignature(options.secret, options.machineId, timestamp, nonce, body)}`,+ } });+ } catch (error) {+ log(`team roster: the Admin can't be reached (${error instanceof Error ? error.name : "error"}); sessions end at their hour`);+ return;+ }+ const json = /^application\/json\b/i.test(response.headers.get("content-type") ?? "");+ if (response.status !== 200 || !json) {+ await response.body?.cancel().catch(() => {});+ // 404: an Admin from before the roster check. Sessions end at their hour, as they always did.+ if (response.status !== 404) log(`team roster: the Admin answered HTTP ${response.status}; sessions end at their hour`);+ return;+ }+ const text = await response.text().catch(() => "");+ let parsed: z.ZodSafeParseResult<z.infer<typeof answerSchema>>;+ try { parsed = text.length > ANSWER_MAX_BYTES ? answerSchema.safeParse(null) : answerSchema.safeParse(JSON.parse(text)); } catch { parsed = answerSchema.safeParse(null); }+ if (!parsed.success) { log("team roster: the Admin's answer can't be read"); return; }+ let left = 0;+ for (const email of emails) {+ if (!Object.hasOwn(parsed.data.members, email)) continue;+ const role = parsed.data.members[email];+ if (role === null) left += options.sessions.revokeMember(email);+ else if (isTeamRole(role)) options.sessions.vouchMember(email, role);+ }+ if (left) log(`team roster: ${left} session(s) ended for people no longer in the team`);+ };++ const schedule = () => {+ if (stopped) return;+ timer = setTimer(() => { timer = null; void check().finally(schedule); }, Math.round(TEAM_ROSTER_EVERY_MS * (1 + 0.2 * random())));+ timer.unref?.();+ };+ const check = (): Promise<void> => {+ if (stopped) return Promise.resolve();+ running ??= ask().catch((error: unknown) => log(`team roster: ${error instanceof Error ? error.message : String(error)}`)).finally(() => { running = null; });+ return running;+ };+ schedule();+ return {+ check,+ stop() {+ stopped = true;+ if (timer) clearTimer(timer);+ timer = null;+ },+ };+}++let cloudTeam: TeamRoster | null = null;++/** A Team Cloud only: a My Cloud is one person's, and its sessions are its owner's. */+export function startCloudTeamRoster(input: { cloudHome: CloudHomeConfig | null; sessions: TeamRosterOptions["sessions"] }): void {+ const { cloudHome } = input;+ if (!cloudHome?.team || cloudTeam) return;+ cloudTeam = startTeamRoster({ machineId: cloudHome.machineId, adminOrigin: cloudHome.adminOrigin, secret: cloudHome.bootstrapSecret, sessions: input.sessions,+ log: (line) => console.log(`team cloud: ${line}`) });+}++export function stopCloudTeamRoster(): void {+ cloudTeam?.stop();+ cloudTeam = null;+}diff --git a/server/cloud-team-routines.e2e.test.ts b/server/cloud-team-routines.e2e.test.tsnew file mode 100644index 0000000000..cefb5ec57e--- /dev/null+++ b/server/cloud-team-routines.e2e.test.ts@@ -0,0 +1,284 @@+// A routine is where it lives (docs/team-cloud.md "Routines"). A real Team Cloud (OMB_CLOUD_ROLE=team) with the Owner,+// an Admin and two members, Bob and Ben: a routine Bob makes from his private chat, or points at it, is his alone in+// every list, stream, file, export and bot tool, and its runs land in his audience; one he makes for the shared chat+// stays the team's. When Bob leaves, his private routines go with his chats, the shared ones he wrote are handed to whoever+// looks after their bot (the Admins when nobody does), he is taken off every bot's sharing and "Looked after by", and+// the admins' Activity says so in counts. The engine is the synthetic Claude CLI.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { CLOUD_NOBODY_KEY } from "./cloud-sharing.ts";+import { personKey } from "./person-key.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const OWNER = { email: "[email protected]", role: "owner" as const };+const ADMIN = { email: "[email protected]", role: "admin" as const };+const BOB = { email: "[email protected]", role: "member" as const };+const BEN = { email: "[email protected]", role: "member" as const };+const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "base64");+const LATER = { type: "interval", everyMinutes: 1440, anchorAt: Date.now() + 86_400_000 };+type Routine = { id: string; name: string; enabled: boolean };+type Run = { id: string; routineId: string; status: string; threadId?: string; resultsThreadId?: string };+type Bot = { id: string; name: string; threadId: string; mainThreadId: string };++let fx: CloudSendFixture, team: CloudTeamFixture;+let owner = "", admin = "", bob = "", ben = "";+let scout: Bot, ledger: Bot;+let bobThread = "", benThread = "", fileName = "";+let kumquat = "", quince = "", standup = "", tally = "", digest = "", justMe = "", mausbotRoutine = "";++const dataDir = (...rest: string[]) => join(team.home, ".openmausbot", ...rest);+const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms));+async function until(done: () => Promise<boolean> | boolean, timeoutMs = 60_000): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error("timed out waiting");+ await sleep(100);+ }+}+const raw = (token: string, path: string) => fetch(`${team.base}${path}`, { headers: { ...fx.edge, authorization: `Bearer ${token}` } });+const routinesOf = async (token: string) => (await team.as(token, "GET", "/api/routines")).body as { routines: Routine[]; runs: Run[] };+const botsOf = async (token: string) => (await team.as(token, "GET", "/api/bots")).body.bots as Array<Bot & { tasks: Array<{ threadId: string }>; reportsTo?: string; access?: { people: Record<string, string> } }>;+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);+ return { text: () => text, close: async () => { controller.abort(); await done; } };+}+/** A bot's own trigger tools, as its turn in that conversation calls them. */+async function tools(botId: string, threadId: string) {+ const token = await team.capability(botId, threadId);+ const call = (path: string, body?: unknown) => fetch(`${team.base}${path}`, { method: body === undefined ? "GET" : "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ return {+ list: async () => (await (await call(`/api/internal/triggers?fromBotId=${botId}`)).json()) as { triggers?: Array<{ id: string; name: string }> },+ change: (action: string, triggerId: string) => call("/api/internal/trigger-requests", { fromBotId: botId, fromThreadId: threadId, action, triggerId }),+ create: (name: string, instructions: string) => call("/api/internal/trigger-requests", { fromBotId: botId, fromThreadId: threadId, action: "create", kind: "schedule",+ routine: { name, instructions, schedule: { type: "weekly", time: "09:00", weekdays: ["monday"] } } }),+ };+}+async function runToEnd(token: string, routineId: string): Promise<Run> {+ const ran = await team.as(token, "POST", `/api/routines/${routineId}/run`);+ expect(ran.status, JSON.stringify(ran.body)).toBe(201);+ let run: Run | undefined;+ await until(async () => {+ run = (await routinesOf(token)).runs.find((candidate) => candidate.id === ran.body.run.id);+ return Boolean(run && ["completed", "failed"].includes(run.status));+ }, 90_000);+ return run!;+}+const writers = () => (JSON.parse(readFileSync(dataDir("lending-routines.json"), "utf8")) as { writers?: Record<string, string> }).writers ?? {};++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-1", name: "Acme" } });+ team = fx.team!;+ owner = (await team.pair(OWNER)).token!;+ admin = (await team.pair(ADMIN)).token!;+ bob = (await team.pair(BOB)).token!;+ ben = (await team.pair(BEN)).token!;+ scout = (await team.as(owner, "POST", "/api/bots", { name: "Scout" })).body.bot;+ bobThread = (await team.as(bob, "POST", `/api/bots/${scout.id}/tasks`, { title: "Bob's plans" })).body.task.threadId;+ benThread = (await team.as(ben, "POST", `/api/bots/${scout.id}/tasks`, { title: "Ben's notes" })).body.task.threadId;+ const upload = await fetch(`${team.base}/api/attachments`, { method: "POST", headers: { ...fx.edge, authorization: `Bearer ${bob}`, "content-type": "image/png" }, body: PNG });+ expect(upload.status).toBe(201);+ const uploaded = ((await upload.json()) as { path: string }).path;+ fileName = uploaded.split(/[\\/]/).pop()!;+ // From the Automations page, reporting into his private chat, with a file.+ const made = await team.as(bob, "POST", "/api/routines", { name: "Kumquat follow-up", prompt: "Ask Kumquat Labs about my offer", botId: scout.id, schedule: LATER,+ resultsThreadId: bobThread, attachments: [{ id: "offer", kind: "image", name: "offer.png", path: uploaded, size: PNG.length }] });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ kumquat = made.body.routine.id;+ // The bot makes one in his private chat, as its trigger tool does.+ const proposed = await (await tools(scout.id, bobThread)).create("Quince reminder", "Remind Bob about the quince jam interview");+ expect(proposed.status).toBe(201);+ quince = ((await proposed.json()) as { result: { resultId: string } }).result.resultId;+ // One from the Automations page for the bot itself ("The bot's main thread"), which everyone who sees the bot sees.+ const shared = await team.as(bob, "POST", "/api/routines", { name: "Shared standup", prompt: "Post the standup summary", botId: scout.id, schedule: LATER, resultsThreadId: null });+ expect(shared.status, JSON.stringify(shared.body)).toBe(201);+ standup = shared.body.routine.id;+ // Ledger: only Bob and Ben added, and Bob looks after it.+ ledger = (await team.as(owner, "POST", "/api/bots", { name: "Ledger" })).body.bot;+ expect((await team.as(owner, "PUT", `/api/bots/${ledger.id}/access`, { everyone: "none", people: { [BOB.email]: "chat", [BEN.email]: "chat" } })).status).toBe(200);+ expect((await team.as(owner, "PUT", `/api/bots/${ledger.id}/reports-to`, { email: BOB.email })).status).toBe(200);+ const tallied = await team.as(bob, "POST", "/api/routines", { name: "Ledger tally", prompt: "Add up the week", botId: ledger.id, schedule: LATER, resultsThreadId: null });+ expect(tallied.status, JSON.stringify(tallied.body)).toBe(201);+ tally = tallied.body.routine.id;+}, hostTimeout(240_000));++afterAll(async () => {+ await fx?.close();+});++it("Bob's private routines are his: listed, changed and run by him, and a bot sees them only in his chat", async () => {+ const mine = await routinesOf(bob);+ expect(mine.routines.map((routine) => routine.id)).toEqual(expect.arrayContaining([kumquat, quince, standup, tally]));+ expect((await raw(bob, `/api/attachments/${fileName}`)).status).toBe(200);+ expect((await team.as(bob, "PATCH", `/api/routines/${kumquat}`, { name: "Kumquat follow-up" })).status).toBe(200);+ const inHisChat = (await (await tools(scout.id, bobThread)).list()).triggers!.map((trigger) => trigger.id);+ expect(inHisChat).toEqual(expect.arrayContaining([kumquat, quince, standup]));+}, hostTimeout(60_000));++it("nobody else sees, opens, changes, runs or fetches the file of Bob's private routines: not Ben, not an Admin, not the Owner", async () => {+ for (const [who, token] of [["Ben", ben], ["Admin", admin], ["Owner", owner]] as const) {+ const label = (what: string) => `${who}: ${what}`;+ for (const route of ["/api/routines", `/api/bots/${scout.id}/overview`, "/api/today"]) {+ const answer = JSON.stringify((await team.as(token, "GET", route)).body);+ expect(answer, label(route)).not.toContain("Kumquat");+ expect(answer, label(route)).not.toContain("Quince");+ expect(answer, label(route)).not.toContain(bobThread);+ expect(answer, label(route)).not.toContain(fileName);+ }+ const listed = (await routinesOf(token)).routines;+ expect(listed.map((routine) => routine.id), label("list")).toContain(standup);+ const shared = listed.find((routine) => routine.id === standup) as { resultsThreadId?: string } | undefined;+ expect((await team.as(token, "GET", `/api/threads/${shared?.resultsThreadId}/messages`)).status, label("the chat it reports to is the team's")).toBe(200);+ expect((await raw(token, `/api/attachments/${fileName}`)).status, label("file")).toBe(404);+ for (const id of [kumquat, quince]) {+ expect((await team.as(token, "PATCH", `/api/routines/${id}`, { enabled: false })).status, label("PATCH")).toBe(404);+ expect((await team.as(token, "POST", `/api/routines/${id}/run`)).status, label("run")).toBe(404);+ expect((await team.as(token, "DELETE", `/api/routines/${id}`)).status, label("DELETE")).toBe(404);+ }+ }+ for (const token of [owner, admin]) {+ const backup = await team.as(token, "POST", "/api/teams/export", { format: "backup" });+ expect(backup.status).toBe(200);+ expect(JSON.stringify(backup.body)).not.toContain("Kumquat");+ expect(JSON.stringify(backup.body)).not.toContain("Quince");+ }+ // A bot's tools in any other conversation neither list them nor reach them by id.+ for (const threadId of [benThread, scout.mainThreadId]) {+ const bot = await tools(scout.id, threadId);+ const ids = (await bot.list()).triggers!.map((trigger) => trigger.id);+ expect(ids).toContain(standup);+ expect(ids).not.toContain(kumquat);+ expect(ids).not.toContain(quince);+ for (const id of [kumquat, quince]) expect((await bot.change("pause", id)).status).toBe(404);+ }+ expect((await routinesOf(bob)).routines.filter((routine) => [kumquat, quince].includes(routine.id)).map((routine) => routine.enabled)).toEqual([true, true]);+}, hostTimeout(90_000));++it("never streams Bob's private routine to Ben or an Admin, while Bob's stream has it", async () => {+ const benStream = await listen(ben), adminStream = await listen(admin), bobStream = await listen(bob);+ expect((await team.as(bob, "PATCH", `/api/routines/${kumquat}`, { prompt: "Ask Kumquat Labs about the salary" })).status).toBe(200);+ await until(() => bobStream.text().includes("about the salary"), 10_000);+ await sleep(500);+ for (const [who, stream] of [["Ben", benStream], ["Admin", adminStream]] as const) {+ expect(stream.text(), who).not.toContain("Kumquat");+ expect(stream.text(), who).not.toContain(bobThread);+ }+ for (const stream of [benStream, adminStream, bobStream]) await stream.close();+}, hostTimeout(60_000));++it("a run of the routine the bot made in Bob's chat works and lands in his audience, never a chat the team reads", async () => {+ const run = await runToEnd(bob, quince);+ expect(run.status).toBe("completed");+ const where = [run.threadId, run.resultsThreadId].filter((id): id is string => Boolean(id));+ expect(where.length).toBeGreaterThan(0);+ for (const threadId of where) expect((await team.as(bob, "GET", `/api/threads/${threadId}/messages`)).status).toBe(200);+ expect(JSON.stringify((await team.as(bob, "GET", `/api/threads/${run.threadId}/messages`)).body)).toContain("quince jam");+ for (const token of [ben, admin, owner]) {+ const tasks = (await botsOf(token)).find((bot) => bot.id === scout.id)!.tasks.map((task) => task.threadId);+ for (const threadId of where) {+ expect(tasks).not.toContain(threadId);+ expect((await team.as(token, "GET", `/api/threads/${threadId}/messages`)).status).toBe(404);+ }+ expect(JSON.stringify((await routinesOf(token)).runs)).not.toContain(run.id);+ }+}, hostTimeout(120_000));++it("a member's routine for the shared chat lands where everyone reads it, run by the schedule or by an admin; Just me stays theirs", async () => {+ const soon = await team.as(bob, "POST", "/api/routines", { name: "Team digest", prompt: "Post the team digest", botId: scout.id, schedule: { type: "once", at: Date.now() + 2_000 }, resultsThreadId: scout.mainThreadId });+ expect(soon.status, JSON.stringify(soon.body)).toBe(201);+ digest = soon.body.routine.id;+ let scheduled: Run | undefined;+ await until(async () => {+ scheduled = (await routinesOf(ben)).runs.find((run) => run.routineId === digest && ["completed", "failed"].includes(run.status));+ return Boolean(scheduled);+ }, 90_000);+ expect(scheduled).toMatchObject({ status: "completed", resultsThreadId: scout.mainThreadId });+ const byAdmin = await runToEnd(admin, digest);+ expect(byAdmin.status).toBe("completed");+ for (const run of [scheduled!, byAdmin]) {+ for (const token of [ben, admin, owner, bob]) {+ const read = await team.as(token, "GET", `/api/threads/${run.threadId}/messages`);+ expect(read.status, "its run is the team's to read").toBe(200);+ expect(JSON.stringify(read.body)).toContain("Post the team digest");+ expect((await team.as(token, "GET", `/api/threads/${scout.mainThreadId}/messages`)).status).toBe(200);+ }+ }+ // Just me: Bob's own private chat with the bot, and the routine and its run are his alone.+ const mine = await team.as(bob, "POST", "/api/routines", { name: "Pay rise", prompt: "Draft my pay rise case", botId: scout.id, schedule: LATER, resultsThreadId: "just-me" });+ expect(mine.status, JSON.stringify(mine.body)).toBe(201);+ justMe = mine.body.routine.id;+ expect(mine.body.routine.resultsThreadId).toBe(bobThread);+ const ran = await runToEnd(bob, justMe);+ expect((await team.as(bob, "GET", `/api/threads/${ran.threadId}/messages`)).status).toBe(200);+ for (const token of [ben, admin, owner]) {+ expect((await routinesOf(token)).routines.map((routine) => routine.id)).not.toContain(justMe);+ expect((await team.as(token, "GET", `/api/threads/${ran.threadId}/messages`)).status).toBe(404);+ }+ // A teammate's own MausBot takes no routine from anyone else, and one Bob sets up for his is his alone.+ const bobsMausBot = (await botsOf(bob)).find((bot) => bot.name === "MausBot")!;+ expect((await team.as(owner, "POST", "/api/routines", { name: "Peek", prompt: "x", botId: bobsMausBot.id, schedule: LATER })).status).toBe(404);+ const own = await team.as(bob, "POST", "/api/routines", { name: "Bee check", prompt: "Check the bees", botId: bobsMausBot.id, schedule: LATER });+ expect(own.status, JSON.stringify(own.body)).toBe(201);+ mausbotRoutine = own.body.routine.id;+ for (const token of [admin, owner]) expect((await routinesOf(token)).routines.map((routine) => routine.id)).not.toContain(mausbotRoutine);+}, hostTimeout(180_000));++it("when Bob leaves, his private routines go and the shared ones he wrote are handed over and keep running", async () => {+ const left = await team.signed("POST", "/api/cloud/team/member-left", { email: BOB.email });+ expect(left.status, JSON.stringify(left.body)).toBe(200);+ expect(left.body).toMatchObject({ ok: true, routines: 4, routinesHandedOver: 3 });+ const stored = readFileSync(dataDir("routines.json"), "utf8");+ expect(stored).not.toContain("Kumquat");+ expect(stored).not.toContain("Quince");+ expect(existsSync(dataDir("attachments", fileName)), "the file only his routine used goes with it").toBe(false);+ // The shared ones keep running, now the bot's owner's, or nobody's (the Admins') when he looked after the bot himself.+ expect((await routinesOf(owner)).routines.map((routine) => routine.id)).toEqual(expect.arrayContaining([standup, tally]));+ expect(writers()[standup]).toBe(personKey({ id: "", email: OWNER.email }));+ expect(writers()[tally]).toBe(CLOUD_NOBODY_KEY);+ const run = await runToEnd(owner, standup);+ expect(run.status).toBe("completed");+ expect((await team.as(owner, "GET", `/api/threads/${run.threadId}/messages`)).status, "its run is the owner's now, not a gone person's").toBe(200);+ expect((await team.as(owner, "GET", `/api/threads/${run.resultsThreadId}/messages`)).status, "and so is the chat it reports into").toBe(200);+ const tallied = await runToEnd(admin, tally);+ expect(tallied.status).toBe("completed");+ expect((await team.as(admin, "GET", `/api/threads/${tallied.threadId}/messages`)).status, "nobody's run: the team's").toBe(200);+ // Admin activity says each was handed over, and nothing from a private chat.+ type Entry = { action: string; target?: { kind: string; id?: string; name?: string }; after?: Record<string, unknown> };+ let entries: Entry[] = [];+ await until(async () => {+ entries = (await team.as(admin, "GET", "/api/admin-activity?what=all")).body.entries as Entry[];+ return entries.filter((entry) => entry.action === "routine.handover").length >= 2;+ }, 10_000);+ expect(entries.filter((entry) => entry.action === "routine.handover").map((entry) => [entry.target?.name, entry.after?.owner]).sort()).toEqual([["Ledger tally", null], ["Shared standup", OWNER.email], ["Team digest", OWNER.email]]);+ const activity = JSON.stringify(entries);+ for (const secret of ["Kumquat", "Quince", "quince", bobThread]) expect(activity).not.toContain(secret);+}, hostTimeout(240_000));++it("Bob is off every bot when he leaves, Activity says so in counts, and joining again restores nothing", async () => {+ const ledgerNow = (await botsOf(owner)).find((bot) => bot.id === ledger.id)!;+ expect(JSON.stringify(ledgerNow)).not.toContain(BOB.email);+ expect(ledgerNow.reportsTo).toBeUndefined();+ expect(ledgerNow.access?.people, "the Owner kept editing it when she handed it to Bob").toEqual({ [OWNER.email]: "edit", [BEN.email]: "chat" });+ type Entry = { action: string; at: string; target?: { kind: string; name?: string }; after?: Record<string, unknown> };+ let entries: Entry[] = [];+ await until(async () => {+ entries = (await team.as(admin, "GET", "/api/admin-activity?what=people")).body.entries as Entry[];+ return entries.some((entry) => entry.action === "member.left");+ }, 10_000);+ expect(entries.filter((entry) => entry.action === "member.left")).toEqual([+ expect.objectContaining({ at: expect.any(String), target: { kind: "person", name: BOB.email }, after: { botsHandedBack: 1, routinesHandedOver: 3 } }),+ ]);+ for (const secret of ["Kumquat", "Quince", bobThread]) expect(JSON.stringify(entries)).not.toContain(secret);+ const again = (await team.pair(BOB)).token!;+ expect((await botsOf(again)).map((bot) => bot.id), "Ledger was shared with him by name").not.toContain(ledger.id);+ expect((await routinesOf(again)).routines.map((routine) => routine.id)).not.toContain(kumquat);+}, hostTimeout(60_000));diff --git a/server/default-bot.test.ts b/server/default-bot.test.tsindex d04969059c..58ea3dafeb 100644--- a/server/default-bot.test.ts+++ b/server/default-bot.test.ts@@ -46,7 +46,7 @@ describe("MausBot, every person's helper", () => {expect(intros(again, maus)).toHaveLength(1);});- it("leaves a Team Cloud member's MausBot uncrowned: it reaches no bot everyone sees, so a crown would promise work it can't hand on", () => {+ it("leaves a Team Cloud member's MausBot uncrowned: only its person's own requests reach a bot everyone sees, and it manages none", () => {const store = new Store(selection);store.seedIfEmpty({ defaultBot: false });const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: "[email protected]", team: "Acme" })!;diff --git a/server/default-bot.ts b/server/default-bot.tsindex f264728c49..b7754ee988 100644--- a/server/default-bot.ts+++ b/server/default-bot.ts@@ -93,14 +93,14 @@ function introduce(store: DefaultBotStore, bot: BotRecord, team?: string | null)export type DefaultBotIntro = (bot: BotRecord) => Omit<Message, "id" | "at">;/** A new MausBot, with its intro as its first message. On a Team Cloud it is its member's alone. */-export function createDefaultBot(store: DefaultBotStore, options: { person?: string; team?: string | null; chief?: (id: string) => void; intro?: DefaultBotIntro } = {}): BotRecord {+export function createDefaultBot(store: DefaultBotStore, options: { person?: string; team?: string | null; chief?: (id: string) => void; intro?: DefaultBotIntro; opened?: (bot: BotRecord) => void } = {}): BotRecord {const person = options.person?.trim().toLowerCase() ?? "";const taken = new Set(person ? [] : store.bots.map((bot) => bot.name.trim().toLowerCase()));const created = store.createBot({name: takeImportName(DEFAULT_BOT_NAME, taken),color: DEFAULT_BOT_COLOR,...(person ? { visibility: { people: [person] } } : {}),- }, { seedMessages: false });+ }, { seedMessages: false, beforeShown: (made) => options.opened?.({ ...made, defaultBot: person ? { person } : {} }) });options.chief?.(created.id);const bot = store.patchBot(created.id, { defaultBot: person ? { person } : {} }) ?? created;store.appendMessage(bot.threadId, options.intro?.(bot) ?? helperIntroMessage(bot, options.team));@@ -111,7 +111,8 @@ export function createDefaultBot(store: DefaultBotStore, options: { person?: str* install's own adopted, or a new one. A MausBot that is gone is never made again. Two marked ones keep the oldest. A* place with no Chief of Staff at all gets MausBot as its Chief, so someone keeps an eye on the day; one that has a* Chief keeps it. */-export function ensureDefaultBot(store: DefaultBotStore, options: { dataDir: string; person?: string; team?: string | null }): BotRecord | null {+/** `opened`: a new one, before anyone is told of it, so its person's main chat is theirs from its first frame. */+export function ensureDefaultBot(store: DefaultBotStore, options: { dataDir: string; person?: string; team?: string | null; opened?: (bot: BotRecord) => void }): BotRecord | null {const person = options.person?.trim().toLowerCase() ?? "";const marked = store.bots.filter((bot) => bot.defaultBot && defaultBotPerson(bot) === person).sort((a, b) => a.createdAt - b.createdAt);@@ -129,7 +130,7 @@ export function ensureDefaultBot(store: DefaultBotStore, options: { dataDir: strchief?.(bot.id);introduce(store, bot, options.team);} else {- bot = createDefaultBot(store, { person, team: options.team, chief });+ bot = createDefaultBot(store, { person, team: options.team, chief, opened: options.opened });}remember(options.dataDir, person, bot.id);return bot;diff --git a/server/direct-send.ts b/server/direct-send.tsindex 5b473adf5b..2cffa8e103 100644--- a/server/direct-send.ts+++ b/server/direct-send.ts@@ -22,6 +22,8 @@ export interface DirectSendInput {followUp?: FollowUp;/** Bot ids the person picked from the @ list. */mentions?: string[];+ /** The sender is the team's Owner or an Admin, so a typed stop may end someone else's run. */+ admin?: boolean;}export type DirectSendReceipt =diff --git a/server/host/chief-notices.ts b/server/host/chief-notices.tsindex 21269442c4..fec6808ae8 100644--- a/server/host/chief-notices.ts+++ b/server/host/chief-notices.ts@@ -157,7 +157,8 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {if (!chief || !reachesChief(chief, bot, threadId)) return tellThePerson();const notices = store.tasks(chief.id).find((candidate) => (candidate.title === input.title || (input.title === INCIDENTS_THREAD_TITLE && candidate.title === OLD_INCIDENTS_THREAD_TITLE)) && !candidate.archivedAt &&(!routing || routing.startedBy(candidate.threadId) === (person ?? undefined)))- ?? store.createTask(chief.id, input.title, false, undefined, { botId: chief.id, name: chief.name, at: Date.now() });+ ?? store.createTask(chief.id, input.title, false, undefined, { botId: chief.id, name: chief.name, at: Date.now() }, undefined, undefined, undefined,+ routing && person ? (created) => routing.open(created.threadId, person) : undefined);if (!notices || notices.threadId === threadId) return tellThePerson();if (routing && person && routing.startedBy(notices.threadId) === undefined) routing.open(notices.threadId, person);store.appendMessage(notices.threadId, {diff --git a/server/host/cloud-signed-host.ts b/server/host/cloud-signed-host.tsindex 1cb4cb5aaf..ec166fbe43 100644--- a/server/host/cloud-signed-host.ts+++ b/server/host/cloud-signed-host.ts@@ -18,6 +18,10 @@ export interface CloudSignedHostDeps {box: () => BoxReport;/** A Team Cloud's shared connections and AI for its admins; used only when the home is a Team Cloud. */teamAdmin?: { summary(): Promise<TeamAdminSummary> };+ /** A Team Cloud's pairing claim said who invited this member: kept for their welcome (team-welcome.ts). */+ invited?: (member: string, by: string) => void;+ /** The team's rule turned remote access off: no browser sign-in for a User. */+ memberBrowserOff?: () => boolean;/** A Team Cloud's member left (the Admin's signed request): delete what was theirs alone. */memberLeft?: (email: string) => Promise<Record<string, unknown>>;/** A Team Cloud's rules changed on the Admin (its signed nudge): fetch them now. */@@ -32,7 +36,7 @@ export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth:const cloudHealth = deps.cloudHome ? createCloudHealth({ ...deps.health, box: deps.box }) : null;const cloudSigned = deps.cloudHome && cloudHealth? createCloudSignedRoutes({ secret: deps.cloudHome.bootstrapSecret, sessions: deps.sessions, team: deps.cloudHome.team, health: cloudHealth, power: deps.power, box: deps.box,- ...(deps.cloudHome.team && deps.teamAdmin ? { teamAdmin: deps.teamAdmin } : {}),+ ...(deps.cloudHome.team && deps.teamAdmin ? { teamAdmin: deps.teamAdmin } : {}), ...(deps.cloudHome.team && deps.invited ? { invited: deps.invited } : {}), ...(deps.cloudHome.team && deps.memberBrowserOff ? { memberBrowserOff: deps.memberBrowserOff } : {}),...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.cloudHome.team && deps.policyChanged ? { policyChanged: deps.policyChanged } : {}), ...(deps.plan ? { plan: deps.plan } : {}), ...(deps.planTier ? { planTier: deps.planTier } : {}) }): null;return { cloudHealth, cloudSigned };diff --git a/server/host/person-first.ts b/server/host/person-first.tsindex 80a72495f2..2c8eb1af6e 100644--- a/server/host/person-first.ts+++ b/server/host/person-first.ts@@ -2,8 +2,10 @@// turn or waits in the queue, and the engine reads a steered message only once the tool call it is in returns: a command// that polls CI can keep it unread for ten minutes. So once a tool call has run PERSON_FIRST_MS while the person's message// waits unanswered, the turn is stopped and the message runs next, ahead of anything else queued in that chat. Only a-// person's own message does this: rooms, routines, teammates and apps wait their turn. A turn waiting on the person (a-// question, a sign-in) or on a computer is never stopped this way.+// person's own message does this: rooms, routines, teammates and apps wait their turn. Where several people write (a Team+// Cloud's shared chat), only the person whose request runs does it; anyone else's line waits in the queue+// and never reaches this. A turn waiting on the person (a question, a sign-in) or on a computer is+// never stopped this way.import type { RuntimeEvent } from "../contracts.ts";import { conversationLanguage, serverLine } from "../server-lines.ts";diff --git a/server/host/person-inbox.ts b/server/host/person-inbox.tsindex 9fa48ee3b4..bced48b721 100644--- a/server/host/person-inbox.ts+++ b/server/host/person-inbox.ts@@ -117,6 +117,8 @@ export interface PersonInboxDeps {ensureOwnBot?(email: string): void;/** What waits on this inbox's person may have changed: its bot goes out to them again. */changed?(threadId: string): void;+ /** A line reached a person's inbox. */+ delivered?(item: Item, delivery: Delivery): void;now?: () => number;}@@ -165,9 +167,8 @@ export function createPersonInbox(deps: PersonInboxDeps) {let threadId = standing?.threadId;if (standing?.brief) store.patchTask(bot.id, standing.threadId, { title: INBOX_TITLE });else if (!standing) {- const created = store.createTask(bot.id, INBOX_TITLE, false);+ const created = store.createTask(bot.id, INBOX_TITLE, false, undefined, undefined, undefined, undefined, undefined, (task) => deps.starters.set(task.threadId, person));if (!created) return null;- deps.starters.set(created.threadId, person);threadId = created.threadId;}homes[person] = { botId: bot.id, threadId: threadId! };@@ -302,6 +303,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {};items.push(item);save();+ deps.delivered?.(item, delivery);mark(at.threadId);store.patchTask(at.bot.id, at.threadId, { unread: true });if (delivery.representable && deps.representative) void represent(item, delivery, at.bot);diff --git a/server/host/person-stop.ts b/server/host/person-stop.tsindex 27b18dec08..13d7def0e7 100644--- a/server/host/person-stop.ts+++ b/server/host/person-stop.ts@@ -6,6 +6,8 @@ import type { RoutineManager } from "../routines.ts";import { serverLine } from "../server-lines.ts";import type { Message, Store } from "../store.ts";import type { UsageTrigger } from "../usage-ledger.ts";+import type { ResolvedSender } from "../../shared/wire.ts";+import type { Actor } from "./run-owner.ts";export interface PersonStopDeps {store: Pick<Store, "appendMessage" | "bot" | "botByThread" | "groupByThread" | "taskByThread" | "tasks">;@@ -16,7 +18,7 @@ export interface PersonStopDeps {stopping(botId: string, threadId: string): () => void;clearUnattended(threadId: string): void;/** Remembers that the person stopped the turn running in this thread, so it ends as their stop. */- markStopped(threadId: string): void;+ markStopped(threadId: string, by?: ResolvedSender): void;/** Ends a goal running in this one-on-one chat, so the interrupted turn is its last. */stopGoal(threadId: string): void;/** A turn runs, or teammates are at work, for this thread. */@@ -24,6 +26,8 @@ export interface PersonStopDeps {/** The bot waits for the person's answer here: a parked question or an open card. */asking(threadId: string): boolean;language(threadId: string): string | undefined;+ /** Where several people write, the sentence someone who may not stop this thread's run reads. */+ stopRefusal?(threadId: string, by: Actor): string | null;}export interface TypedStop {@@ -38,19 +42,21 @@ export interface TypedStop {busy: boolean;/** The rest of the person's message row, as the busy branch would have recorded it. */row: Pick<Message, "replyToId" | "sendId" | "sender" | "via" | "callId">;+ /** Who typed it. */+ by?: Actor;}export function createPersonStop(deps: PersonStopDeps) {const { store } = deps;- async function stopThreadForPerson(botId: string, threadId: string): Promise<void> {+ async function stopThreadForPerson(botId: string, threadId: string, by?: ResolvedSender): Promise<void> {const routines = deps.routines();const routine = routines?.activeBotRunForBot(botId);const free = deps.stopping(botId, threadId);if (routine?.threadId === threadId) await routines!.cancelRun(routine.id);else {deps.handoffs().stoppedByPerson(threadId);- deps.markStopped(threadId);+ deps.markStopped(threadId, by);deps.stopGoal(threadId);await deps.interruptDirectThread(botId, threadId);}@@ -65,10 +71,13 @@ export function createPersonStop(deps: PersonStopDeps) {if (input.fromApp || (trigger.kind !== "user" && trigger.kind !== "owner") || !isStopCommand(text, store.bot(botId)?.name)) return null;const everyone = addressesEveryone(text);if (!busy && !everyone && (input.row.via || deps.asking(threadId) || !deps.working(botId, threadId))) return null;+ const refusal = (id: string) => deps.stopRefusal?.(id, input.by ?? { admin: false }) ?? null;+ const refused = everyone ? null : refusal(threadId);+ if (refused) throw Object.assign(new Error(refused), { status: 403, code: "stop_not_yours" });if (input.personPresent) deps.clearUnattended(threadId);const message = store.appendMessage(threadId, { role: "user", kind: "text", text, ...input.row });- const stopping = (everyone ? store.tasks(botId).map((task) => task.threadId) : [threadId]).filter((id) => (id === threadId && busy) || deps.working(botId, id));- for (const id of stopping) await stopThreadForPerson(botId, id);+ const stopping = (everyone ? store.tasks(botId).map((task) => task.threadId) : [threadId]).filter((id) => ((id === threadId && busy) || deps.working(botId, id)) && refusal(id) === null);+ for (const id of stopping) await stopThreadForPerson(botId, id, input.row.sender);if (!stopping.length) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: serverLine(deps.language(threadId), "server.stop.nothingRunning"), ok: true } });return { ok: true as const, threadId, message };}diff --git a/server/host/personal-reach.test.ts b/server/host/personal-reach.test.tsnew file mode 100644index 0000000000..28f68da4c8--- /dev/null+++ b/server/host/personal-reach.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from "vitest";++import type { BotAccessLevel } from "../../shared/bot-access.ts";+import { resolveTeammate, unreachableTeammate, type RosterMember } from "../peer-roster.ts";+import { createPersonalReach } from "./personal-reach.ts";++const MIRA = "[email protected]";+const key = (email: string) => `p_${email.replace(/\W/g, "").padEnd(22, "x").slice(0, 22)}`;+const mausbot: RosterMember = { id: "maus", name: "MausBot", defaultBot: { person: MIRA }, visibility: { people: [MIRA] } };+const bensMausbot: RosterMember = { id: "ben-maus", name: "MausBot", defaultBot: { person: "[email protected]" }, visibility: { people: ["[email protected]"] } };+const sales: RosterMember = { id: "sales", name: "Sales" };+const archive: RosterMember = { id: "archive", name: "Archive" };+const payroll: RosterMember = { id: "payroll", name: "Payroll", visibility: { people: ["[email protected]"] } };+const gone: RosterMember = { id: "gone", name: "Gone", hidden: true };+const bots = [mausbot, bensMausbot, sales, archive, payroll, gone];+const levels: Record<string, BotAccessLevel> = { sales: "chat", archive: "view", payroll: "none", gone: "chat", "ben-maus": "edit" };+const privateTo: Record<string, string | null> = { mine: key(MIRA), bens: key("[email protected]"), shared: null };++function world(acting: string | null = key(MIRA), behind = true) {+ return createPersonalReach({+ privateTo: (threadId) => privateTo[threadId] ?? null,+ personKey: key,+ level: (bot) => levels[bot.id] ?? "none",+ personBehind: () => behind,+ actingFor: () => acting,+ });+}++describe("a person's own MausBot reaching the team's bots", () => {+ it("reaches only the bots its person may chat with, from a chat private to them", () => {+ expect(world().peers(bots, mausbot, "mine").map((bot) => bot.id)).toEqual(["sales"]);+ expect(world().reaches(mausbot, sales, "shared")).toBe(false);+ expect(world().reaches(mausbot, sales, "bens")).toBe(false);+ expect(world().reaches(sales, archive, "mine"), "any other bot keeps the audience rule").toBe(false);+ });++ it("lists nothing, and hands nothing on, when its person's own request is not behind the turn", () => {+ expect(world(key(MIRA), false).peers(bots, mausbot, "mine")).toEqual([]);+ expect(world(null).handOnProblem(mausbot, sales, "mine", "turn")).toMatch(/routine, an event or a line another app passed on/);+ expect(world().handOnProblem(mausbot, sales, "mine", "turn")).toBeUndefined();+ });++ it("never names a bot its person cannot see, nor another person's MausBot", () => {+ for (const hidden of [payroll, bensMausbot]) {+ expect(world().hides(mausbot, hidden)).toBe(true);+ expect(world().refusal(mausbot, hidden, "mine")).toBe(`No bot with id "${hidden.id}" — call list_bots and copy the exact id from the result`);+ expect(unreachableTeammate(bots, mausbot, hidden.name, (bot) => world().hides(mausbot, bot))?.id).not.toBe(hidden.id);+ }+ const wider = (reach = world()) => ({ reaches: (bot: RosterMember) => reach.listed(mausbot, bot, "mine"), hides: (bot: RosterMember) => reach.hides(mausbot, bot), refusal: (bot: RosterMember) => reach.refusal(mausbot, bot, "mine") });+ const unknown = resolveTeammate(bots, mausbot, "Nobody", undefined, undefined, wider());+ expect(resolveTeammate(bots, mausbot, "Payroll", undefined, undefined, wider())).toEqual({ error: (unknown as { error: string }).error.replaceAll("Nobody", "Payroll") });+ expect(resolveTeammate(bots, mausbot, "payroll", undefined, undefined, wider())).not.toEqual({ id: "payroll", byName: false });+ expect(resolveTeammate(bots, mausbot, "Sales", undefined, undefined, wider())).toEqual({ id: "sales", byName: true });+ });++ it("refuses a bot its person can only view, and says so", () => {+ expect(world().reaches(mausbot, archive, "mine")).toBe(false);+ expect(world().refusal(mausbot, archive, "mine")).toMatch(/view only/);+ });++ it("carries placed work only in a thread private to the same person, traced to their request", () => {+ const placed = (threadId: string, kind: "user" | "outside" = "user") => ({ id: "as_1", threadId, origin: kind === "user" ? { kind, request: "pull Q3" } as const : { kind } as const });+ expect(world().carries(mausbot, sales, "mine", placed("mine"))).toBe(true);+ expect(world().carries(mausbot, sales, "mine", placed("shared"))).toBe(false);+ expect(world().carries(mausbot, sales, "mine", placed("bens"))).toBe(false);+ expect(world().carries(mausbot, sales, "mine", placed("mine", "outside"))).toBe(false);+ });++ it("hands on only in its person's own name, and leaves every other hand-off to the usual rules", () => {+ expect(() => world().checkHandOn(mausbot, sales, "mine", key(MIRA))).not.toThrow();+ expect(() => world().checkHandOn(mausbot, sales, "mine", key(MIRA), { threadId: "mine" })).not.toThrow();+ expect(() => world().checkHandOn(mausbot, sales, "mine", key("[email protected]"))).toThrow(/person's own chats/);+ expect(() => world().checkHandOn(mausbot, sales, "mine", key(MIRA), { threadId: "bens" })).toThrow(/person's own chats/);+ expect(() => world().checkHandOn(mausbot, sales, "mine", key(MIRA), {})).toThrow(/person's own chats/);+ expect(() => world().checkHandOn(mausbot, archive, "mine", key("[email protected]"))).not.toThrow();+ expect(() => world().checkHandOn(sales, archive, "mine", key("[email protected]"))).not.toThrow();+ });++ it("answers a waiting question only in its person's own chats", () => {+ expect(world().mayAnswerIn("mine", "mine")).toBe(true);+ expect(world().mayAnswerIn("mine", "bens")).toBe(false);+ expect(world().mayAnswerIn("shared", "shared")).toBe(false);+ });+});diff --git a/server/host/personal-reach.ts b/server/host/personal-reach.tsnew file mode 100644index 0000000000..9898558516--- /dev/null+++ b/server/host/personal-reach.ts@@ -0,0 +1,104 @@+// Security invariant: a Team Cloud person's own MausBot reaches past its audience (bot-visibility.ts sameAudience) only+// to the team bots that person may chat with, only from a chat private to them, and only with their own request behind+// the turn. The work opens in a thread private to that same person, so nothing of it reaches a shared chat, a room, the+// team's notes, another member or an admin. It never widens what the person could do themselves: a bot they cannot see+// is never named to it, a bot they can only view is refused, and reaching a bot grants no authority over it.+import { atLeast, type BotAccessLevel } from "../../shared/bot-access.ts";+import { defaultBotPerson } from "../../shared/default-bot.ts";+import type { HandoffView } from "../coordinator.ts";+import { canReach, peerName, reachablePeers, type RosterMember } from "../peer-roster.ts";++export interface PersonalReachDeps {+ /** The person key a conversation is private to; null for a shared chat, a room and anywhere off a team. */+ privateTo(threadId: string): string | null;+ personKey(email: string): string;+ /** What this person may do with the bot, as their own session would. */+ level(bot: RosterMember, email: string): BotAccessLevel;+ /** No routine, webhook, relay or guest drives this conversation now. */+ personBehind(botId: string, threadId: string): boolean;+ /** The person key this turn acts for (acting-person.ts), or null. */+ actingFor(threadId: string, generation: string): string | null;+}++type Placed = Pick<HandoffView, "threadId"> & Partial<Pick<HandoffView, "id" | "origin">>;++export const unknownBot = (id: string) => `No bot with id "${peerName(id)}" — call list_bots and copy the exact id from the result`;++export function createPersonalReach(deps: PersonalReachDeps) {+ const ownerOf = (from: RosterMember): string | null => defaultBotPerson(from) || null;+ /** The MausBot's person, when this conversation is private to them. */+ const chatPerson = (from: RosterMember, threadId: string): string | null => {+ const email = ownerOf(from);+ return email && deps.privateTo(threadId) === deps.personKey(email) ? email : null;+ };+ const usable = (from: RosterMember, target: RosterMember, email: string): boolean =>+ from.id !== target.id && !target.hidden && !target.defaultBot && atLeast(deps.level(target, email), "chat");++ /** A bot this MausBot's person cannot see, or another person's MausBot: never named to it, in any of its chats. */+ const hides = (from: RosterMember, target: RosterMember): boolean => {+ const email = ownerOf(from);+ return email !== null && from.id !== target.id && (Boolean(target.defaultBot) || deps.level(target, email) === "none");+ };+ const reaches = (from: RosterMember, target: RosterMember, threadId: string): boolean => {+ const email = chatPerson(from, threadId);+ return email !== null && usable(from, target, email);+ };+ const notBehind = (target: RosterMember) =>+ `Only this person's own request, asked in this chat, can hand work to ${peerName(target.name)}; a routine, an event or a line another app passed on cannot, so nothing was sent.`;+ const listed = (from: RosterMember, target: RosterMember, threadId: string): boolean =>+ reaches(from, target, threadId) && deps.personBehind(from.id, threadId);++ /** May this hand-off answer a question waiting in `answerThreadId`: only one in the same person's own chats. */+ const mayAnswerIn = (fromThreadId: string, answerThreadId: string | undefined): boolean => {+ const person = deps.privateTo(fromThreadId);+ return person !== null && answerThreadId !== undefined && deps.privateTo(answerThreadId) === person;+ };++ return {+ hides,+ reaches,+ listed,+ peers<T extends RosterMember>(bots: readonly T[], from: RosterMember, threadId: string): T[] {+ return reachablePeers(bots, from, (bot) => listed(from, bot, threadId));+ },+ /** Before anything is sent: only the person's own request may hand work on this way. */+ handOnProblem(from: RosterMember, target: RosterMember, threadId: string, generation: string): string | undefined {+ if (canReach(from, target) || !reaches(from, target, threadId) || deps.actingFor(threadId, generation) === deps.privateTo(threadId)) return undefined;+ return notBehind(target);+ },+ /** Checked whenever the work is sent, starts or reports back. Once placed, the work must run in a thread private to+ * the same person and trace to their request; before that it may only be offered where the person is behind it. */+ carries(from: RosterMember, target: RosterMember, fromThreadId: string, node: Placed): boolean {+ if (node.id === undefined) return listed(from, target, fromThreadId);+ return reaches(from, target, fromThreadId) && deps.privateTo(node.threadId) === deps.privateTo(fromThreadId) && node.origin?.kind === "user";+ },+ /** Why this MausBot cannot reach the bot, when its person decides it; null leaves the usual refusal. */+ refusal(from: RosterMember, target: RosterMember, threadId: string): string | null {+ const email = ownerOf(from);+ if (!email) return null;+ if (hides(from, target)) return unknownBot(target.id);+ const name = peerName(target.name);+ if (!atLeast(deps.level(target, email), "chat")) {+ return `${name} is shared with this person to view only, so it can't be given work and nothing was sent. Tell them in one plain sentence: "You can view ${name}, not chat with it."`;+ }+ if (!chatPerson(from, threadId)) return `${name} can be given work only from this person's own private chats, and this chat is not one of them, so nothing was sent.`;+ return reaches(from, target, threadId) ? notBehind(target) : null;+ },+ mayAnswerIn,+ /** A hand-off to a bot outside a room that goes by this reach must open for the person whose chat this is, and may+ * answer a question only in that person's own chats; anything else throws, so nothing is sent. */+ checkHandOn(from: RosterMember, target: RosterMember, fromThreadId: string, opener: string | undefined, answering?: { threadId?: string }): void {+ if (canReach(from, target) || !reaches(from, target, fromThreadId)) return;+ if (opener !== deps.privateTo(fromThreadId) || (answering && !mayAnswerIn(fromThreadId, answering.threadId))) {+ throw new Error("This stays in the person's own chats, and that is not one of them, so nothing was sent.");+ }+ },+ /** For the system prompt, in a chat where this MausBot reaches beyond its audience. */+ prompt(from: RosterMember, threadId: string, peers: readonly RosterMember[]): string {+ if (!chatPerson(from, threadId) || !peers.some((peer) => reaches(from, peer, threadId))) return "";+ return " The team bots in your roster are the ones this person may chat with. Work you hand one runs in that bot's own private chat with this person, which only they can see, and its result comes back here. You have no say over those bots' setup. A bot that isn't listed is not one this person can use: say only that you can't reach it.";+ },+ };+}++export type PersonalReach = ReturnType<typeof createPersonalReach>;diff --git a/server/host/refused-handoffs.ts b/server/host/refused-handoffs.tsindex 5b8e4b2dce..f0697955dc 100644--- a/server/host/refused-handoffs.ts+++ b/server/host/refused-handoffs.ts@@ -9,6 +9,8 @@ type Refused = { target: RosterMember; from: RosterMember };export interface RefusedHandoffDeps {bots(): readonly RosterMember[];+ /** A bot `from` may never be told of (personal-reach.ts hides). */+ hides?(from: RosterMember, target: RosterMember): boolean;/** The run this conversation is, when it is one. */runOf(threadId: string): { routineId: string; botId: string } | undefined;/** The person key of who wrote this routine; absent off a Cloud and for a routine nobody wrote. */@@ -39,7 +41,7 @@ export function createRefusedHandoffs(deps: RefusedHandoffDeps) {if (!deps.runOf(threadId)) return;const seen = refused.get(threadId) ?? new Map<string, Refused>();for (const raw of named) {- const target = status >= 400 ? unreachableTeammate(deps.bots(), from, raw) : null;+ const target = status >= 400 ? unreachableTeammate(deps.bots(), from, raw, (bot) => deps.hides?.(from, bot) === true) : null;if (target) seen.set(target.id, { target, from });if (status < 400) for (const [id, was] of seen) if (namesTeammate(was.target, raw)) seen.delete(id);}diff --git a/server/host/room-access.ts b/server/host/room-access.tsindex 5fcdf8d740..cf4a690cbd 100644--- a/server/host/room-access.ts+++ b/server/host/room-access.ts@@ -1,12 +1,15 @@import type { HandoffView, RoomAddress } from "../coordinator.ts";import { peerAllowed, reachRefusal, type LookedAfterBy } from "../peer-roster.ts";-import type { GroupRecord, Store } from "../store.ts";+import type { BotRecord, GroupRecord, Store } from "../store.ts";+import type { PersonalReach } from "./personal-reach.ts";export interface RoomAccessDeps {store: Store;/** The person a conversation is private to on a Team Cloud; null elsewhere. */privateTo?(threadId: string): string | null;lookedAfterBy?: LookedAfterBy;+ /** A person's own MausBot reaching the bots they may chat with (personal-reach.ts). */+ personalReach?(): Pick<PersonalReach, "carries" | "refusal">;}/** Security: what is said in a Team Cloud member's private chat never reaches a room. */@@ -24,7 +27,13 @@ export type RoomTalksVerdict =const NOT_A_MEMBER = "The addressed agent isn't a member of this room; work sent to it again goes to it directly, in a thread of its own";const LEFT_THE_ROOM = "The addressed agent is no longer a member of this room, so its room job stopped; work sent to it again goes to it directly, in a thread of its own";-export function createRoomAccess({ store, privateTo = () => null, lookedAfterBy }: RoomAccessDeps) {+export function createRoomAccess({ store, privateTo = () => null, lookedAfterBy, personalReach }: RoomAccessDeps) {+ function reachProblem(from: BotRecord, bot: BotRecord, parent: Pick<HandoffView, "threadId">, node: Pick<HandoffView, "threadId"> & Partial<Pick<HandoffView, "id" | "origin">>): string | undefined {+ if (peerAllowed(from, bot)) return undefined;+ const personal = personalReach?.();+ if (personal?.carries(from, bot, parent.threadId, node)) return undefined;+ return personal?.refusal(from, bot, parent.threadId) ?? reachRefusal(from, bot, lookedAfterBy)!;+ }function roomRootProblem(node: Pick<HandoffView, "groupId" | "threadId" | "botId">): string | undefined {const group = node.groupId ? store.group(node.groupId) : undefined;const bot = store.bot(node.botId);@@ -33,7 +42,7 @@ export function createRoomAccess({ store, privateTo = () => null, lookedAfterByif (!group.memberIds.includes(bot.id)) return "The addressed agent is no longer a member of this room";return undefined;}- function roomHandoffProblem(node: Pick<HandoffView, "groupId" | "threadId" | "botId"> & Partial<Pick<HandoffView, "kind">>, parent?: Pick<HandoffView, "groupId" | "threadId" | "botId">): string | undefined {+ function roomHandoffProblem(node: Pick<HandoffView, "groupId" | "threadId" | "botId"> & Partial<Pick<HandoffView, "kind" | "id" | "origin">>, parent?: Pick<HandoffView, "groupId" | "threadId" | "botId">): string | undefined {const group = node.groupId ? store.group(node.groupId) : undefined;const bot = store.bot(node.botId);if (!bot || bot.hidden) return "The addressed agent no longer exists";@@ -52,7 +61,10 @@ export function createRoomAccess({ store, privateTo = () => null, lookedAfterByif (!from || from.hidden || (parent.groupId ? !source || !source.memberIds.includes(from.id) || !store.groupTaskByThread(source.id, parent.threadId) : !store.taskByThread(from.id, parent.threadId))) return "Source membership or task was removed";if (source && group && source.id === group.id && parent.threadId !== node.threadId) return "Same-room work must stay in the originating conversation";// A bot's own thread (start_thread's report_back) is no teammate: its teammate list never names itself.- if (!(from.id === bot.id && !node.groupId) && !peerAllowed(from, bot)) return reachRefusal(from, bot, lookedAfterBy)!;+ if (!(from.id === bot.id && !node.groupId)) {+ const refused = reachProblem(from, bot, parent, node);+ if (refused) return refused;+ }}}diff --git a/server/host/run-owner.test.ts b/server/host/run-owner.test.tsnew file mode 100644index 0000000000..e0cf553aa8--- /dev/null+++ b/server/host/run-owner.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from "vitest";++import type { RequestAuth } from "../request-auth.ts";+import { arrivalDecision, createRunOwners, mayJoinRun, mayRemoveQueued, mayStop, routeRunOwners, type RunOwnersDeps } from "./run-owner.ts";++const PRIYA = "p_priyapriyapriyapriyapr";+const TOM = "p_tomtomtomtomtomtomtomt";+const priya = { person: PRIYA, name: "Priya" };++describe("the rule", () => {+ it("lets only the asker's own line reach the run where several people write", () => {+ expect(arrivalDecision({ shared: true, asker: priya, from: PRIYA })).toBe("as-today");+ expect(arrivalDecision({ shared: true, asker: priya, from: TOM })).toBe("queue");+ expect(arrivalDecision({ shared: true, asker: priya })).toBe("queue");+ expect(arrivalDecision({ shared: true, asker: null, from: TOM })).toBe("queue");+ });++ it("changes nothing in a private chat or with one person", () => {+ expect(arrivalDecision({ shared: false, asker: priya, from: TOM })).toBe("as-today");+ expect(arrivalDecision({ shared: false, asker: null })).toBe("as-today");+ expect(mayStop({ shared: false, asker: priya, by: { person: TOM, admin: false } })).toBe(true);+ expect(mayRemoveQueued({ shared: false, sender: { name: "Priya", id: PRIYA }, by: { person: TOM, admin: false } })).toBe(true);+ expect(mayJoinRun({ shared: false, asker: priya, senders: [{ name: "Tom", id: TOM }], by: { person: TOM, admin: false } })).toBe(true);+ });++ it("lets the asker or an admin stop a person's run, and anyone who may chat stop a run no person asked for", () => {+ expect(mayStop({ shared: true, asker: priya, by: { person: PRIYA, admin: false } })).toBe(true);+ expect(mayStop({ shared: true, asker: priya, by: { person: TOM, admin: false } })).toBe(false);+ expect(mayStop({ shared: true, asker: priya, by: { admin: false } })).toBe(false);+ expect(mayStop({ shared: true, asker: priya, by: { person: TOM, admin: true } })).toBe(true);+ expect(mayStop({ shared: true, asker: null, by: { person: TOM, admin: false } })).toBe(true);+ });++ it("leaves a waiting line to its writer, and one no person wrote to an admin", () => {+ expect(mayRemoveQueued({ shared: true, sender: { name: "Tom", id: TOM }, by: { person: TOM, admin: false } })).toBe(true);+ expect(mayRemoveQueued({ shared: true, sender: { name: "Tom", id: TOM }, by: { person: PRIYA, admin: true } })).toBe(false);+ expect(mayRemoveQueued({ shared: true, sender: { name: "Slack" }, by: { person: TOM, admin: false } })).toBe(false);+ expect(mayRemoveQueued({ shared: true, by: { person: TOM, admin: true } })).toBe(true);+ });++ it("joins waiting lines to the run only when the asker adds their own", () => {+ expect(mayJoinRun({ shared: true, asker: priya, senders: [{ name: "Priya", id: PRIYA }], by: { person: PRIYA, admin: false } })).toBe(true);+ expect(mayJoinRun({ shared: true, asker: priya, senders: [{ name: "Priya", id: PRIYA }, { name: "Tom", id: TOM }], by: { person: PRIYA, admin: false } })).toBe(false);+ expect(mayJoinRun({ shared: true, asker: priya, senders: [{ name: "Tom", id: TOM }], by: { person: TOM, admin: false } })).toBe(false);+ expect(mayJoinRun({ shared: true, asker: null, senders: [{ name: "Tom", id: TOM }], by: { person: TOM, admin: true } })).toBe(false);+ });+});++describe("who asked", () => {+ const lines = [+ { id: "m1", role: "user", kind: "text", sender: { name: "Priya", id: PRIYA } },+ { id: "m2", role: "user", kind: "text", sender: { name: "Slack" }, relayed: true },+ { id: "m3", role: "user", kind: "text", sender: { name: "Scout" }, peerAsk: { botId: "b" } },+ { id: "m4", role: "user", kind: "text", sender: { name: "Tom", id: TOM }, via: "api" },+ ];+ const owners = (request: ReturnType<RunOwnersDeps["directRequest"]>, room?: string) => createRunOwners({+ shared: () => true, directRequest: () => request, roomRequestMessageId: () => room, isRoom: () => room !== undefined,+ messages: () => lines, personName: (person) => (person === TOM ? "Tom" : undefined), language: () => undefined,+ });++ it("is the person whose own line the run answers", () => {+ expect(owners({ messageId: "m1" }).asker("t")).toEqual(priya);+ expect(owners(undefined, "m1").asker("t")).toEqual(priya);+ });++ it("is nobody for a relayed line, a bot's ask, an API line, a routine or webhook run, and a stopped run", () => {+ for (const messageId of ["m2", "m3", "m4"]) expect(owners({ messageId }).asker("t")).toBeNull();+ expect(owners({ messageId: "m1", automation: { kind: "schedule" } }).asker("t")).toBeNull();+ expect(owners({ messageId: "m1", stopped: true }).asker("t")).toBeNull();+ expect(owners({ origin: { kind: "outside" } }).asker("t")).toBeNull();+ });++ it("is the person work handed on runs for", () => {+ expect(owners({ origin: { kind: "user", request: "check the stock", person: TOM } }).asker("t")).toEqual({ person: TOM, name: "Tom" });+ });++ it("names a person with no name set as the People list does", () => {+ const dev = createRunOwners({ shared: () => true, directRequest: () => ({ messageId: "d1" }), roomRequestMessageId: () => undefined, isRoom: () => false,+ messages: () => [{ id: "d1", role: "user", kind: "text", sender: { name: "[email protected]", id: TOM } }], personName: () => "[email protected]", language: () => undefined });+ expect(dev.stopRefusal("t", { person: PRIYA, admin: false })).toBe("Only Dev or an admin can stop this.");+ expect(dev.askedBy({ threadId: "t", busy: true })).toEqual({ askedBy: { name: "Dev", id: TOM } });+ expect(dev.shownSender("t", { name: "[email protected]", id: TOM })).toEqual({ name: "Dev", id: TOM });+ });++ it("names the asker in the refusal", () => {+ expect(owners({ messageId: "m1" }).stopRefusal("t", { person: TOM, admin: false })).toBe("Only Priya or an admin can stop this.");+ expect(owners({ messageId: "m1" }).stopRefusal("t", { person: PRIYA, admin: false })).toBeNull();+ });+});++describe("a route built without the rule", () => {+ it("refuses nothing and sees no admin, as on a server one person uses", () => {+ const owners = routeRunOwners(undefined, undefined);+ const auth = { kind: "loopback" } as RequestAuth;+ expect(owners.admin(auth)).toBe(false);+ expect(owners.stopRefusal(auth, "t")).toBeNull();+ expect(owners.removeRefusal(auth, "t", { name: "Tom", id: TOM })).toBeNull();+ expect(owners.joinRefusal(auth, "t", [{ name: "Tom", id: TOM }])).toBeNull();+ });+});diff --git a/server/host/run-owner.ts b/server/host/run-owner.tsnew file mode 100644index 0000000000..4fdc87b040--- /dev/null+++ b/server/host/run-owner.ts@@ -0,0 +1,146 @@+// Whoever asked owns the run, in a conversation more than one person reads on a Team Cloud (a bot's shared chats and the+// conversations opened from them, a group chat). A line from anyone else (a teammate, an app, the API, another bot) never+// steers the run, never stops it and never cuts it short to be answered first: it waits in the queue, which everyone+// there sees, and runs after as its own turn. Only the asker, or an Owner or Admin, stops it. A run no person asked for (a+// bot's own work, an app's or the API's line) is nobody's: anyone who may chat there stops it, and a person's line waits+// only until it ends. A private chat, a personal install and a My Cloud have one person, so nothing here applies there.+import type { ResolvedSender, WireTask } from "../../shared/wire.ts";+import type { RequestAuth } from "../request-auth.ts";+import { shownPersonName } from "../../shared/bot-owner.ts";+import type { WorkOrigin } from "../peer-provenance.ts";+import { serverLine } from "../server-lines.ts";++const PERSON = /^p_[\w-]{22}$/;++/** The person whose own request a run answers, or null when no person asked for it. */+export type RunAsker = { person: string; name: string } | null;++/** Who acts: their person key when they are a signed-in person, and whether they are the team's Owner or an Admin. */+export interface Actor {+ person?: string;+ admin: boolean;+}++export type ArrivalDecision = "as-today" | "queue";++export function runActorOf(auth: RequestAuth, personOf: (auth: RequestAuth & { kind: "session" }) => string): Actor {+ return auth.kind === "session" ? { person: personOf(auth), admin: auth.scopes.includes("admin") } : { admin: false };+}++/** A new line `from` a person (absent: not a person's own line) in a conversation whose run `asker` owns. */+export function arrivalDecision(input: { shared: boolean; asker: RunAsker; from?: string }): ArrivalDecision {+ if (!input.shared) return "as-today";+ return input.asker !== null && input.from !== undefined && input.from === input.asker.person ? "as-today" : "queue";+}++export function mayStop(input: { shared: boolean; asker: RunAsker; by: Actor }): boolean {+ const { shared, asker, by } = input;+ return !shared || asker === null || by.admin || by.person === asker.person;+}++/** A waiting line is its writer's to remove; one no person wrote, an Owner's or Admin's. */+export function mayRemoveQueued(input: { shared: boolean; sender?: ResolvedSender; by: Actor }): boolean {+ const { shared, sender, by } = input;+ if (!shared) return true;+ const writer = sender?.id && PERSON.test(sender.id) ? sender.id : undefined;+ return writer ? writer === by.person : by.admin;+}++/** Waiting lines join the running turn only when every one is the asker's own and the asker adds them. */+export function mayJoinRun(input: { shared: boolean; asker: RunAsker; senders: ReadonlyArray<ResolvedSender | undefined>; by: Actor }): boolean {+ const { shared, asker, senders, by } = input;+ if (!shared) return true;+ return asker !== null && by.person === asker.person && senders.every((sender) => sender?.id === asker.person);+}++type Line = { id: string; role: string; kind: string; peerAsk?: unknown; relayed?: boolean; aside?: boolean; via?: string; sender?: ResolvedSender };++/** A person's own line, as the server recorded it: never a bot's, a relay's, an aside or one sent through the API. */+function linePerson(line: Line | undefined): RunAsker {+ if (!line || line.role !== "user" || line.kind !== "text" || line.peerAsk || line.relayed || line.aside || line.via === "api") return null;+ const person = line.sender?.id;+ return person && PERSON.test(person) ? { person, name: line.sender!.name } : null;+}++export interface RunOwnersDeps {+ /** More than one person reads this conversation: a Team Cloud conversation that is not someone's private one. */+ shared(threadId: string): boolean;+ /** The one-on-one conversation's running request (index.ts directRequestOwners). */+ directRequest(threadId: string): { messageId?: string; stopped?: boolean; automation?: unknown; origin?: WorkOrigin } | undefined;+ /** The person's line the group chat's live run answers, if one does. */+ roomRequestMessageId(threadId: string): string | undefined;+ isRoom(threadId: string): boolean;+ messages(threadId: string): readonly Line[];+ personName(person: string): string | undefined;+ language(threadId: string): string | undefined;+}++export function createRunOwners(deps: RunOwnersDeps) {+ const lineAsker = (threadId: string, messageId: string | undefined): RunAsker =>+ messageId ? linePerson(deps.messages(threadId).find((line) => line.id === messageId)) : null;++ const named = (owner: RunAsker): RunAsker => owner && { person: owner.person, name: shownPersonName(deps.personName(owner.person) ?? owner.name) };++ /** A routine, a webhook or an app's event runs nobody's request; work handed on for a person runs theirs. */+ const asker = (threadId: string): RunAsker => named(askerOf(threadId));+ const askerOf = (threadId: string): RunAsker => {+ if (deps.isRoom(threadId)) return lineAsker(threadId, deps.roomRequestMessageId(threadId));+ const request = deps.directRequest(threadId);+ if (!request || request.stopped || request.automation !== undefined) return null;+ const own = lineAsker(threadId, request.messageId);+ if (own) return own;+ const handedFor = request.origin?.kind === "user" ? request.origin.person : undefined;+ return handedFor ? { person: handedFor, name: handedFor } : null;+ };++ return {+ shared: deps.shared,+ asker,+ /** A waiting line's writer as the chat names them, where several people write; nothing elsewhere. */+ shownSender(threadId: string, sender: ResolvedSender): ResolvedSender | undefined {+ return deps.shared(threadId) ? { ...sender, name: shownPersonName((sender.id && deps.personName(sender.id)) || sender.name) } : undefined;+ },+ /** The conversation's wire field naming whose request runs, while it works where several people write. */+ askedBy(task: { threadId: string; busy?: boolean }): Pick<WireTask, "askedBy"> {+ const owner = task.busy && deps.shared(task.threadId) ? asker(task.threadId) : null;+ return owner ? { askedBy: { name: owner.name, id: owner.person } } : {};+ },+ /** A new line while this conversation's run goes on: as today, or into the queue behind it. */+ arrival(threadId: string, sender: ResolvedSender | undefined, ownLine: boolean): ArrivalDecision {+ if (!deps.shared(threadId)) return "as-today";+ return arrivalDecision({ shared: true, asker: asker(threadId), from: ownLine ? sender?.id : undefined });+ },+ /** The sentence someone who may not stop this conversation's run reads, or null when they may. */+ stopRefusal(threadId: string, by: Actor): string | null {+ const shared = deps.shared(threadId);+ const owner = shared ? asker(threadId) : null;+ return mayStop({ shared, asker: owner, by }) ? null : serverLine(deps.language(threadId), "server.runOwner.onlyAskerStops", { name: owner!.name });+ },+ /** Where several read, the running request's asker: their own line added to it goes ahead of everyone else's waiting+ * lines, as it does in a private chat. */+ askerFirst(threadId: string): string | undefined {+ return deps.shared(threadId) ? asker(threadId)?.person : undefined;+ },+ removeRefusal(threadId: string, sender: ResolvedSender | undefined, by: Actor): string | null {+ return mayRemoveQueued({ shared: deps.shared(threadId), sender, by }) ? null : serverLine(deps.language(threadId), "server.runOwner.notYourQueued");+ },+ joinRefusal(threadId: string, senders: ReadonlyArray<ResolvedSender | undefined>, by: Actor): string | null {+ const shared = deps.shared(threadId);+ return mayJoinRun({ shared, asker: shared ? asker(threadId) : null, senders, by }) ? null : serverLine(deps.language(threadId), "server.runOwner.waitsItsTurn");+ },+ };+}++export type RunOwners = ReturnType<typeof createRunOwners>;++/** The rule as a route asks it, by the request's sign-in. A route built without it (a server one person uses, or a+ * route's own test) refuses nothing and sees no admin, so nothing changes there. */+export function routeRunOwners(owners: Pick<RunOwners, "stopRefusal" | "removeRefusal" | "joinRefusal"> | undefined, actorOf: ((auth: RequestAuth) => Actor) | undefined) {+ const by = (auth: RequestAuth): Actor => actorOf?.(auth) ?? { admin: false };+ return {+ admin: (auth: RequestAuth) => by(auth).admin,+ stopRefusal: (auth: RequestAuth, threadId: string) => owners?.stopRefusal(threadId, by(auth)) ?? null,+ removeRefusal: (auth: RequestAuth, threadId: string, sender: ResolvedSender | undefined) => owners?.removeRefusal(threadId, sender, by(auth)) ?? null,+ joinRefusal: (auth: RequestAuth, threadId: string, senders: ReadonlyArray<ResolvedSender | undefined>) => owners?.joinRefusal(threadId, senders, by(auth)) ?? null,+ };+}diff --git a/server/host/team-away-events.test.ts b/server/host/team-away-events.test.tsnew file mode 100644index 0000000000..5371054cc4--- /dev/null+++ b/server/host/team-away-events.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it } from "vitest";+import type { Notification } from "../../shared/notification.ts";+import type { Audience } from "../audience.ts";+import type { AwayEvent } from "./team-away.ts";+import type { Message } from "../store.ts";+import type { Delivery, Item } from "./person-inbox.ts";+import { createTeamAwayEvents } from "./team-away-events.ts";++const MAYA = "p_mayamayamayamayamayama", BEN = "p_benbenbenbenbenbenbenb";+const audiences: Record<string, Audience> = { shared: "team", room: "room:g1", mayas: `member:${MAYA}`, bens: `member:${BEN}`, inbox: `member:${MAYA}` };++function world(messages: Record<string, Partial<Message>[]> = {}, unread?: (person: string, threadId: string, groupId?: string) => boolean) {+ const events: AwayEvent[] = [];+ let unseen: { id: string }[] = [{ id: "line-1" }];+ const events_ = createTeamAwayEvents({+ audienceOf: (threadId) => audiences[threadId] ?? "team",+ store: {+ bot: (id: string) => (id === "scout" ? { id, name: "Scout" } : id === "sales" ? { id, name: "Sales" } : undefined),+ groupByThread: (threadId: string) => (threadId === "room" ? { id: "g1", name: "Q3 launch" } : undefined),+ activePath: (threadId: string) => (messages[threadId] ?? []) as Message[],+ messagesFor: (threadId: string) => (messages[threadId] ?? []) as Message[],+ } as never,+ unseen: () => unseen,+ ...(unread ? { unread } : {}),+ noticed: (event) => events.push(event),+ });+ return { events, ...events_, setUnseen: (next: { id: string }[]) => { unseen = next; } };+}++const item = (over: Partial<Item> = {}): Item => ({ id: "line-1", person: MAYA, botId: "mausbot", threadId: "inbox", kind: "message", from: "Ben", text: "secret words", at: 1, ...over });+const delivery = (over: Partial<Delivery>): Delivery => ({ kind: "message", from: { name: "Ben", email: "[email protected]" }, text: "the words: never sent", title: "Ben mentioned you in Scout", notify: "mention", ...over });+const plain = (event: AwayEvent) => ({ ...event, still: undefined });++describe("what of a Team Cloud is worth an away email", () => {+ it("a teammate's mention in a shared chat: who and where, never the words", () => {+ const { events, delivered, setUnseen } = world();+ delivered(item(), delivery({ origin: { botId: "scout", threadId: "shared", messageId: "m1" } }));+ expect(events.map(plain)).toEqual([{ person: MAYA, about: "inbox:line-1", thread: "shared", still: undefined, item: { kind: "mention", who: "Ben", place: "Scout" } }]);+ expect(JSON.stringify(events)).not.toContain("words");+ expect(events[0]!.still!()).toBe(true);+ setUnseen([]);+ expect(events[0]!.still!()).toBe(false);+ });++ it("a mention in a group chat names the group chat", () => {+ const { events, delivered } = world();+ delivered(item(), delivery({ origin: { botId: "scout", threadId: "room", groupId: "g1" } }));+ expect(events[0]!.item).toEqual({ kind: "mention", who: "Ben", place: "Q3 launch" });+ });++ it("from someone's private chat: only that a teammate wrote, no bot, no place; a bot's is not emailed", () => {+ const { events, delivered } = world();+ delivered(item(), delivery({ origin: { botId: "scout", threadId: "bens" } }));+ delivered(item({ id: "line-2" }), delivery({ from: { name: "Scout", botId: "scout" }, origin: { botId: "scout", threadId: "bens" } }));+ expect(events.map((event) => event.item)).toEqual([{ kind: "mention", who: "Ben", private: true }]);+ });++ it("a question routed to the bot's owner names the bot; one from a private chat names nothing", () => {+ const { events, delivered } = world();+ const card = { requestId: "r1", question: "Which plan?" } as never;+ delivered(item(), delivery({ kind: "ask", from: { name: "Sales", botId: "sales" }, notify: "question", card, origin: { botId: "sales", threadId: "shared" } }));+ delivered(item({ id: "line-2" }), delivery({ kind: "ask", from: { name: "Sales", botId: "sales" }, notify: "approval", card: { requestId: "r2" } as never, origin: { botId: "sales", threadId: "mayas" } }));+ expect(events.map((event) => [event.about, event.item])).toEqual([+ ["ask:shared:r1", { kind: "waiting", who: "Sales" }],+ ["ask:mayas:r2", { kind: "waiting", private: true }],+ ]);+ });++ it("a routine's report and failure, once per conversation; an assistant's answer and other news are not emailed", () => {+ const { events, delivered } = world();+ delivered(item(), delivery({ kind: "result", from: { name: "Scout", botId: "scout" }, notify: "done", origin: { botId: "scout", threadId: "shared" } }));+ delivered(item({ id: "line-2" }), delivery({ kind: "notice", from: { name: "Scout", botId: "scout" }, notify: "routine-failed", origin: { botId: "scout", threadId: "mayas" } }));+ delivered(item({ id: "line-3" }), delivery({ assistant: true, origin: { botId: "scout", threadId: "shared" } }));+ delivered(item({ id: "line-4" }), delivery({ kind: "notice", from: { name: "Scout", botId: "scout" }, notify: "incident", origin: { botId: "scout", threadId: "shared" } }));+ expect(events.map((event) => [event.conversation, event.item])).toEqual([+ ["shared", { kind: "finished", who: "Scout", routine: true }],+ ["mayas", { kind: "failed", private: true, routine: true }],+ ]);+ });++ const note = (over: Partial<Notification>): Notification => ({ kind: "question", botId: "scout", botName: "Scout", threadId: "mayas", title: "Scout asks", body: "Which plan, the blue one?", ...over });++ it("a question in the person's own private chat: a bot waits, nothing more, while its card is open", () => {+ const card = { id: "c", role: "bot", kind: "options", card: { requestId: "r9", title: "Which plan?", options: [] } } as unknown as Partial<Message>;+ const { events, notified } = world({ mayas: [card] });+ notified(note({}), note({}));+ expect(events.map(plain)).toEqual([{ person: MAYA, about: "ask:mayas:r9", thread: "mayas", still: undefined, item: { kind: "waiting", private: true } }]);+ expect(events[0]!.still!()).toBe(true);+ (card.card as { answered?: string }).answered = "blue";+ expect(events[0]!.still!()).toBe(false);+ });++ it("work asked for in a shared place finished or failed: told to whoever asked last", () => {+ const asked = { shared: [{ id: "u1", role: "user", sender: { id: BEN, name: "Ben" } }], room: [{ id: "u2", role: "user", sender: { id: MAYA, name: "Maya" } }] } as Record<string, Partial<Message>[]>;+ const { events, notified } = world(asked);+ notified(note({ kind: "done", threadId: "shared" }), note({ kind: "done", threadId: "shared" }));+ notified(note({ kind: "turn-failed", threadId: "room", groupId: "g1" }), note({ kind: "turn-failed", threadId: "room", groupId: "g1" }));+ expect(events.map((event) => [event.person, event.about, event.conversation, event.item])).toEqual([+ [BEN, "done:shared:u1", "shared", { kind: "finished", who: "Scout" }],+ [MAYA, "turn-failed:room:u2", "room", { kind: "failed", who: "Scout", place: "Q3 launch" }],+ ]);+ });++ it("drops finished work once that person, not someone else, has read the conversation past the reply", () => {+ const read = new Set<string>();+ const asked = { room: [{ id: "u2", role: "user", sender: { id: MAYA, name: "Maya" } }] } as Record<string, Partial<Message>[]>;+ const { events, notified } = world(asked, (person, threadId, groupId) => !read.has(`${person}:${threadId}:${groupId}`));+ notified(note({ kind: "done", threadId: "room", groupId: "g1" }), note({ kind: "done", threadId: "room", groupId: "g1" }));+ read.add(`${BEN}:room:g1`);+ expect(events[0]!.still!()).toBe(true);+ read.add(`${MAYA}:room:g1`);+ expect(events[0]!.still!()).toBe(false);+ });++ it("nothing from a private chat's finished work, a routine's own run, or what the inbox already took", () => {+ const { events, notified } = world({ mayas: [{ id: "u1", role: "user", sender: { id: MAYA, name: "Maya" } }] });+ notified(note({ kind: "done" }), note({ kind: "done" }));+ notified(note({ kind: "done", threadId: "shared" }), note({ kind: "done", threadId: "shared" }), { routine: true });+ notified(note({}), { ...note({}), forPerson: MAYA });+ notified(note({}), null);+ expect(events).toEqual([]);+ });+});diff --git a/server/host/team-away-events.ts b/server/host/team-away-events.tsnew file mode 100644index 0000000000..9829253f8f--- /dev/null+++ b/server/host/team-away-events.ts@@ -0,0 +1,85 @@+// What, of what reaches a Team Cloud person, is worth an email while they are away (team-away.ts), and the+// names that email may carry. Security invariant: a private chat's event names no bot and no place, and nothing here+// reads a message's words.+import { liveCardKind } from "../../shared/live-approval.ts";+import type { Notification, NotifyKind } from "../../shared/notification.ts";+import { audienceMember, type Audience } from "../audience.ts";+import type { AwayEvent, AwayKind } from "./team-away.ts";+import type { Store } from "../store.ts";+import type { Delivery, Item } from "./person-inbox.ts";++const WAITING: ReadonlySet<NotifyKind> = new Set(["approval", "question", "sign-in", "secret"]);+const INBOX_KINDS: Partial<Record<NotifyKind, { kind: AwayKind; routine?: true }>> = {+ approval: { kind: "waiting" }, question: { kind: "waiting" }, "sign-in": { kind: "waiting" }, secret: { kind: "waiting" },+ mention: { kind: "mention" }, done: { kind: "finished", routine: true }, "routine-failed": { kind: "failed", routine: true },+};++export interface TeamAwayEventsDeps {+ audienceOf(threadId: string): Audience;+ store: Pick<Store, "bot" | "groupByThread" | "activePath" | "messagesFor">;+ /** The lines in this person's inbox they have not opened and that still wait on them. */+ unseen(person: string): readonly { id: string }[];+ /** A bot replied in this shared conversation after where this person has read it up to. */+ unread?(person: string, threadId: string, groupId?: string): boolean;+ noticed(event: AwayEvent): void;+}++export function createTeamAwayEvents(deps: TeamAwayEventsDeps) {+ const shared = (threadId: string) => audienceMember(deps.audienceOf(threadId)) === null;+ const groupName = (threadId: string, groupId?: string) => (groupId ? deps.store.groupByThread(threadId)?.name : undefined);+ const openCard = (threadId: string, requestId?: string) => deps.store.messagesFor(threadId)+ .findLast((message) => !message.inbox && liveCardKind(message.card) !== null && (!requestId || message.card?.requestId === requestId));++ /** A line reached a person's inbox. */+ function delivered(item: Item, delivery: Delivery): void {+ const mapped = INBOX_KINDS[delivery.notify];+ if (!mapped || delivery.assistant) return;+ const origin = delivery.origin;+ const open = origin ? shared(origin.threadId) : false;+ const still = () => deps.unseen(item.person).some((one) => one.id === item.id);+ const about = mapped.kind === "waiting" && origin && delivery.card?.requestId ? `ask:${origin.threadId}:${delivery.card.requestId}` : `inbox:${item.id}`;+ const conversation = mapped.routine && origin ? origin.threadId : undefined;+ const thread = !mapped.routine && origin ? origin.threadId : undefined;+ const base = { person: item.person, about, still, ...(conversation ? { conversation } : {}), ...(thread ? { thread } : {}) };+ if (!open) {+ if (mapped.kind === "mention") {+ if (delivery.from.email) deps.noticed({ ...base, item: { kind: "mention", who: delivery.from.name, private: true } });+ return;+ }+ deps.noticed({ ...base, item: { kind: mapped.kind, private: true, ...(mapped.routine ? { routine: true } : {}) } });+ return;+ }+ const place = groupName(origin!.threadId, origin!.groupId) ?? deps.store.bot(origin!.botId)?.name;+ const named = place && place !== delivery.from.name ? { place } : {};+ deps.noticed({ ...base, item: { kind: mapped.kind, who: delivery.from.name, ...named, ...(mapped.routine ? { routine: true } : {}) } });+ }++ /** A notification went out as it is, past the inbox: a question in the person's own private chat, or a reply to what+ * someone asked in a shared place. */+ function notified(original: Notification, routed: Notification | null, how: { routine?: boolean } = {}): void {+ if (!routed || routed.forPerson || original.forPerson || how.routine) return;+ const { threadId } = original;+ const own = audienceMember(deps.audienceOf(threadId));+ if (WAITING.has(original.kind)) {+ const card = own ? openCard(threadId) : undefined;+ const requestId = card?.card?.requestId;+ if (!own || !requestId) return;+ deps.noticed({ person: own, item: { kind: "waiting", private: true }, about: `ask:${threadId}:${requestId}`, thread: threadId, still: () => openCard(threadId, requestId) !== undefined });+ return;+ }+ if ((original.kind !== "done" && original.kind !== "turn-failed") || own) return;+ const asked = deps.store.activePath(threadId).findLast((message) => message.role === "user" && !message.peerAsk && message.sender?.id);+ const person = asked?.sender?.id;+ if (!asked || !person) return;+ const group = groupName(threadId, original.groupId), { groupId } = original;+ deps.noticed({+ person, about: `${original.kind}:${threadId}:${asked.id}`, conversation: threadId,+ ...(deps.unread ? { still: () => deps.unread!(person, threadId, groupId) } : {}),+ item: { kind: original.kind === "done" ? "finished" : "failed", who: original.botName, ...(group ? { place: group } : {}) },+ });+ }++ return { delivered, notified };+}++export type TeamAwayEvents = ReturnType<typeof createTeamAwayEvents>;diff --git a/server/host/team-away-host.ts b/server/host/team-away-host.tsnew file mode 100644index 0000000000..ab0b410d96--- /dev/null+++ b/server/host/team-away-host.ts@@ -0,0 +1,56 @@+// The Team Cloud's "when you are away" emails, put together: the client that asks the Admin (team-away.ts) and what of the+// inbox and the notifications is worth one (team-away-events.ts). Off a team every hook does nothing.+import type { Notification } from "../../shared/notification.ts";+import type { Audience } from "../audience.ts";+import type { CloudHomeConfig } from "../cloud-home.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import { PASS, type RouteHandler } from "../routes/table.ts";+import type { SessionRecord } from "../sessions.ts";+import type { Store } from "../store.ts";+import type { Delivery, Item } from "./person-inbox.ts";+import { createTeamAway } from "./team-away.ts";+import { roomUnreadFor, threadReadKey } from "./room-reads.ts";+import { createTeamAwayEvents } from "./team-away-events.ts";++export interface TeamAwayHostDeps {+ cloudHome: CloudHomeConfig | null;+ dataDir: string;+ /** Whether this person has the team open now: the one place that decides "away". */+ here(person: string): boolean;+ people(): readonly { email: string; leftAt?: number | string }[];+ language(person: string): string | undefined;+ audienceOf(threadId: string): Audience;+ store: Pick<Store, "bot" | "groupByThread" | "activePath" | "messagesFor">;+ unseen(person: string): readonly { id: string }[];+ /** Where this person has read a shared conversation (a group chat's id, or `threadReadKey`) up to (room-reads.ts). */+ readUpTo(key: string, person: string): string | undefined;+ session(auth: RequestAuth): SessionRecord | null;+}++export interface TeamAwayHost {+ /** A line reached a person's inbox (person-inbox.ts `delivered`). */+ delivered(item: Item, delivery: Delivery): void;+ /** A notification went out, as `notify` had it and as the inbox routed it. */+ notified(original: Notification | null, routed: Notification | null, how?: { routine?: boolean }): void;+ /** `GET`/`PUT /api/me/away-emails`. */+ routes: RouteHandler;+}++export function createTeamAwayHost(deps: TeamAwayHostDeps): TeamAwayHost {+ const home = deps.cloudHome;+ if (!home?.team) return { delivered: () => {}, notified: () => {}, routes: (async () => PASS) as RouteHandler };+ const windowMs = Number(process.env.OMB_TEAM_AWAY_WINDOW_MS);+ const away = createTeamAway({+ here: deps.here, language: deps.language, dataDir: deps.dataDir, adminOrigin: home.adminOrigin, machineId: home.machineId, secret: home.bootstrapSecret,+ member: (person) => deps.people().find((one) => one.leftAt === undefined && personKey({ id: "", email: one.email }) === person),+ log: (line) => console.log(`team cloud: ${line}`), ...(windowMs > 0 ? { windowMs } : {}),+ });+ const events = createTeamAwayEvents({ audienceOf: deps.audienceOf, store: deps.store, unseen: deps.unseen, noticed: away.noticed,+ unread: (person, threadId, groupId) => roomUnreadFor(deps.store.activePath(threadId), deps.readUpTo(groupId ?? threadReadKey(threadId), person), true) });+ return {+ delivered: events.delivered,+ notified: (original, routed, how) => { if (original) events.notified(original, routed, how); },+ routes: away.routes(deps.session),+ };+}diff --git a/server/host/team-away.test.ts b/server/host/team-away.test.tsnew file mode 100644index 0000000000..95335bf071--- /dev/null+++ b/server/host/team-away.test.ts@@ -0,0 +1,240 @@+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { AWAY_DAILY_MAX, AWAY_EMAILS_FILE, AWAY_EMAILS_PATH, AWAY_GAP_MS, AWAY_WINDOW_MS, awayKey, createTeamAway, TEAM_AWAY_ADMIN_PATH, teamAwaySignature, type AwayRequest, type TeamAway } from "./team-away.ts";+import { json } from "../harness/http.ts";+import { personKey } from "../person-key.ts";+import { PASS } from "../routes/table.ts";++const MAYA = "[email protected]", BEN = "[email protected]";+const maya = personKey({ id: "", email: MAYA });+const SECRET = "s".repeat(43), MACHINE = "cm-team-home";++const dirs: string[] = [], aways: TeamAway[] = [];+afterEach(() => { for (const away of aways.splice(0)) away.stop(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++type Answer = (request: AwayRequest) => Response | Promise<Response>;+const ok: Answer = (request) => Response.json({ v: 1, results: request.notices.map(({ id }) => ({ id, state: "sent" })) });++function world(options: { answer?: Answer; here?: Set<string>; members?: string[] } = {}) {+ const dataDir = mkdtempSync(join(tmpdir(), "omb-team-away-"));+ dirs.push(dataDir);+ let clock = Date.UTC(2026, 10, 10, 9, 0, 0);+ const here = options.here ?? new Set<string>();+ const members = new Map((options.members ?? [MAYA, BEN]).map((email) => [personKey({ id: "", email }), { email }]));+ const timers: { run: () => void; at: number; unref(): void }[] = [];+ const requests: { body: AwayRequest; headers: Record<string, string>; url: string; raw: string }[] = [];+ const away = createTeamAway({+ here: (person) => here.has(person), member: (person) => members.get(person), language: (person) => (person === maya ? "de" : undefined),+ dataDir, adminOrigin: "https://cloud.example.test", machineId: MACHINE, secret: SECRET, now: () => clock,+ setTimer: (run, ms) => { const timer = { run, at: clock + ms, unref() {} }; timers.push(timer); return timer; },+ clearTimer: (timer) => { const index = timers.indexOf(timer as never); if (index >= 0) timers.splice(index, 1); },+ fetchImpl: (async (url: string, init: RequestInit) => {+ const raw = String(init.body), body = JSON.parse(raw) as AwayRequest;+ requests.push({ body, headers: init.headers as Record<string, string>, url, raw });+ return (options.answer ?? ok)(body);+ }) as typeof fetch,+ });+ aways.push(away);+ /** Moves the clock and runs every timer that falls due, in order. */+ const advance = async (ms: number) => {+ const until = clock + ms;+ for (;;) {+ const next = timers.filter((timer) => timer.at <= until).sort((a, b) => a.at - b.at)[0];+ if (!next) break;+ timers.splice(timers.indexOf(next), 1);+ clock = Math.max(clock, next.at);+ next.run();+ await new Promise((resolve) => setTimeout(resolve, 0));+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ clock = until;+ };+ const notices = () => requests.flatMap((request) => request.body.notices);+ return { away, dataDir, here, members, requests, notices, advance, setClock: (at: number) => { clock = at; }, clock: () => clock };+}++const mention = (person = maya, about = "inbox:line-1") => ({ person, about, item: { kind: "mention" as const, who: "Ben", place: "Sales" } });++describe("the away email a Team Cloud asks the Admin for", () => {+ it("sends exactly the names and a hash, signed, after the window", async () => {+ const { away, advance, requests, clock } = world();+ away.noticed(mention());+ await advance(AWAY_WINDOW_MS - 1);+ expect(requests).toHaveLength(0);+ await advance(1);+ expect(requests).toHaveLength(1);+ const [request] = requests;+ expect(request!.url).toBe(`https://cloud.example.test${TEAM_AWAY_ADMIN_PATH}`);+ expect(request!.body).toEqual({+ v: 1,+ notices: [{ id: expect.stringMatching(/^n_[\w-]{22}$/), to: MAYA, language: "de", items: [{ kind: "mention", key: awayKey("inbox:line-1"), who: "Ben", place: "Sales" }] }],+ });+ expect(Object.keys(request!.body.notices[0]!).sort()).toEqual(["id", "items", "language", "to"]);+ expect(awayKey("inbox:line-1")).toMatch(/^[0-9a-f]{64}$/);+ const headers = request!.headers;+ expect(headers["x-omb-cloud-machine"]).toBe(MACHINE);+ expect(headers["x-omb-cloud-timestamp"]).toBe(String(Math.floor(clock() / 1000)));+ expect(headers["x-omb-cloud-signature"]).toBe(`v1=${teamAwaySignature(SECRET, MACHINE, headers["x-omb-cloud-timestamp"]!, headers["x-omb-cloud-nonce"]!, request!.raw)}`);+ });++ it("signs the way the Admin checks (a fixed vector both repositories test)", () => {+ expect(teamAwaySignature("secret-of-the-home", "cm-acme", "1762765200", "nonce-0123456789abcdef", '{"v":1,"notices":[]}'))+ .toBe("wXx8Ty3f-Z1Ag0DrNs80GxPT4KwAZ6RoIzrRF139vAI");+ });++ it("puts what happens within the window in one email, the question first", async () => {+ const { away, advance, notices } = world();+ away.noticed(mention());+ await advance(60_000);+ away.noticed({ person: maya, about: "ask:t1:r1", item: { kind: "waiting", who: "Sales" } });+ await advance(60_000);+ away.noticed({ person: maya, about: "done:t2:l1", conversation: "t2", item: { kind: "finished", who: "Scout", place: "Q3 launch" } });+ await advance(AWAY_WINDOW_MS);+ expect(notices()).toHaveLength(1);+ expect(notices()[0]!.items.map((item) => item.kind)).toEqual(["waiting", "mention", "finished"]);+ });++ it("leaves finished work out when a question or a mention from that conversation is already in the email", async () => {+ const { away, advance, notices } = world();+ away.noticed({ person: maya, about: "ask:t1:r1", thread: "t1", item: { kind: "waiting", who: "Scout" } });+ away.noticed({ person: maya, about: "done:t1:l1", conversation: "t1", item: { kind: "finished", who: "Scout" } });+ away.noticed({ person: maya, about: "done:t2:l1", conversation: "t2", item: { kind: "finished", who: "Sales" } });+ await advance(AWAY_WINDOW_MS);+ expect(notices()[0]!.items.map((item) => [item.kind, item.who])).toEqual([["waiting", "Scout"], ["finished", "Sales"]]);+ });++ it("keeps a question that arrived late in the window for the next email", async () => {+ const { away, advance, notices } = world();+ away.noticed(mention());+ await advance(AWAY_WINDOW_MS - 60_000);+ away.noticed({ person: maya, about: "ask:t1:r1", item: { kind: "waiting", private: true } });+ await advance(60_000);+ expect(notices().map((notice) => notice.items.map((item) => item.kind))).toEqual([["mention"]]);+ await advance(AWAY_GAP_MS);+ expect(notices().map((notice) => notice.items.map((item) => item.kind))).toEqual([["mention"], ["waiting"]]);+ });++ it("sends nothing to someone who is here, or who came back before it went", async () => {+ const { away, advance, here, requests } = world();+ here.add(maya);+ away.noticed(mention());+ expect(away.pendingFor(maya)).toEqual([]);+ here.delete(maya);+ away.noticed(mention(maya, "inbox:line-2"));+ here.add(maya);+ await advance(AWAY_WINDOW_MS);+ expect(requests).toHaveLength(0);+ });++ it("drops what was answered or seen before it went", async () => {+ const { away, advance, notices } = world();+ let open = true;+ away.noticed({ ...mention(), still: () => open });+ away.noticed({ person: maya, about: "ask:t1:r1", item: { kind: "waiting", private: true }, still: () => true });+ open = false;+ await advance(AWAY_WINDOW_MS);+ expect(notices()[0]!.items.map((item) => item.kind)).toEqual(["waiting"]);+ });++ it("never asks about the same thing twice", async () => {+ const { away, advance, notices } = world();+ away.noticed(mention());+ away.noticed(mention());+ await advance(AWAY_WINDOW_MS);+ away.noticed(mention());+ await advance(AWAY_GAP_MS + AWAY_WINDOW_MS);+ expect(notices()).toHaveLength(1);+ expect(notices()[0]!.items).toHaveLength(1);+ });++ it("tells of finished work once per conversation for a stretch away, and again after they came back", async () => {+ const { away, advance, notices, here } = world();+ const done = (line: string) => ({ person: maya, about: `done:t1:${line}`, conversation: "t1", item: { kind: "finished" as const, who: "Scout" } });+ away.noticed(done("l1"));+ away.noticed(done("l2"));+ await advance(AWAY_WINDOW_MS);+ away.noticed(done("l3"));+ await advance(AWAY_GAP_MS + AWAY_WINDOW_MS);+ expect(notices()).toHaveLength(1);+ here.add(maya);+ away.noticed(done("l4"));+ here.delete(maya);+ away.noticed(done("l5"));+ await advance(AWAY_WINDOW_MS);+ expect(notices()).toHaveLength(2);+ });++ it("waits the gap between two emails and stops at the daily cap", async () => {+ const { away, advance, notices } = world();+ for (let index = 0; index < AWAY_DAILY_MAX + 2; index++) {+ away.noticed(mention(maya, `inbox:line-${index}`));+ await advance(AWAY_GAP_MS + AWAY_WINDOW_MS);+ }+ expect(notices()).toHaveLength(AWAY_DAILY_MAX);+ });++ it("asks nothing for someone who left or was never in", async () => {+ const { away, advance, requests } = world({ members: [BEN] });+ away.noticed(mention(maya));+ await advance(AWAY_WINDOW_MS);+ expect(requests).toHaveLength(0);+ });++ it("tries a failed send again as the same email, and drops it when an older Admin doesn't know the route", async () => {+ let calls = 0;+ const { away, advance, notices } = world({ answer: (request) => (++calls === 1 ? new Response("down", { status: 503 }) : ok(request)) });+ away.noticed(mention());+ await advance(AWAY_WINDOW_MS + 60_000);+ expect(notices()).toHaveLength(2);+ expect(notices()[1]!.id).toBe(notices()[0]!.id);++ const older = world({ answer: () => Response.json({ error: "Not found." }, { status: 404 }) });+ older.away.noticed(mention());+ await older.advance(AWAY_WINDOW_MS);+ older.away.noticed(mention(maya, "inbox:line-9"));+ await older.advance(AWAY_GAP_MS + AWAY_WINDOW_MS);+ expect(older.requests).toHaveLength(1);+ });+});++describe("the person's own switch", () => {+ const session = (email: string) => ({ id: "s1", email }) as never;+ async function call(away: TeamAway, method: string, email: string | null, body?: unknown) {+ const answer: { status?: number; body?: unknown } = {};+ const res = { setHeader() {}, writeHead(status: number) { answer.status = status; }, end(text: string) { answer.body = JSON.parse(text); }, headersSent: false } as never;+ const route = away.routes(() => (email ? session(email) : null));+ const out = await route({ req: {} as never, res, url: new URL(`http://x${AWAY_EMAILS_PATH}`), path: AWAY_EMAILS_PATH, method, auth: {} as never, json, readBody: (async () => body) as never });+ return out === PASS ? null : answer;+ }++ it("is on by default; off stops every email and reaches the Admin", async () => {+ const { away, advance, requests, dataDir } = world();+ expect(await call(away, "GET", MAYA)).toEqual({ status: 200, body: { on: true } });+ expect(await call(away, "PUT", MAYA, { on: false })).toEqual({ status: 200, body: { on: false } });+ away.noticed(mention());+ await advance(AWAY_WINDOW_MS);+ const synced = requests.filter((request) => request.body.prefs);+ expect(synced.map((request) => request.body)).toEqual([{ v: 1, notices: [], prefs: [{ to: MAYA, on: false }] }]);+ expect(requests.flatMap((request) => request.body.notices)).toEqual([]);+ expect(JSON.parse(readFileSync(join(dataDir, "people", maya, AWAY_EMAILS_FILE), "utf8"))).toEqual({ version: 1, on: false, synced: true });+ expect(await call(away, "PUT", MAYA, { on: true })).toEqual({ status: 200, body: { on: true } });+ await advance(5_000);+ expect(existsSync(join(dataDir, "people", maya, AWAY_EMAILS_FILE))).toBe(false);+ });++ it("follows a stop link: the Admin's off turns the switch off here", async () => {+ const { away, advance } = world({ answer: (request) => Response.json({ v: 1, results: request.notices.map(({ id }) => ({ id, state: "off" })), off: [MAYA] }) });+ away.noticed(mention());+ await advance(AWAY_WINDOW_MS);+ expect(await call(away, "GET", MAYA)).toEqual({ status: 200, body: { on: false } });+ expect(await call(away, "GET", BEN)).toEqual({ status: 200, body: { on: true } });+ });++ it("is refused without a team sign-in, and takes only true or false", async () => {+ const { away } = world();+ expect((await call(away, "GET", null))?.status).toBe(403);+ expect((await call(away, "PUT", MAYA, { on: "no" }))?.status).toBe(400);+ });+});diff --git a/server/host/team-away.ts b/server/host/team-away.tsnew file mode 100644index 0000000000..beb603b953--- /dev/null+++ b/server/host/team-away.ts@@ -0,0 +1,343 @@+// A Team Cloud tells people what happened while they were away: a teammate mentioned them, a bot waits on their answer,+// work they asked for finished. The Admin owns their addresses and sends the email (openmaus-cloud docs/team-cloud.md+// "When you are away"); this machine decides what is worth one and asks for it with a signed call.+// Security invariants: what leaves here is names and opaque hashes, never a message's words, a conversation's title or+// an id; an item from someone's private chat names no bot and no place. The Admin checks every address against the+// team's own roster itself.+import { createHash, createHmac, randomBytes } from "node:crypto";+import { mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";+import { writeFileAtomic } from "../atomic.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import { PASS, type RouteHandler } from "../routes/table.ts";+import type { SessionRecord } from "../sessions.ts";++/** On the Admin; must match openmaus-cloud's TEAM_AWAY_MACHINE_PATH. */+export const TEAM_AWAY_ADMIN_PATH = "/api/cloud/machines/team-away";+/** The person's own switch: `GET` → `{ on }`, `PUT { on }` → `{ on }`. A Team Cloud session only. */+export const AWAY_EMAILS_PATH = "/api/me/away-emails";+/** The first thing that happens while someone is away opens a window; what happens in it goes in the same email. */+export const AWAY_WINDOW_MS = 10 * 60_000;+/** A question waits at least this long unanswered before an email tells of it. */+export const AWAY_ASK_MIN_MS = 5 * 60_000;+export const AWAY_GAP_MS = 30 * 60_000;+export const AWAY_DAILY_MAX = 6;+/** Finished work is told once per conversation for a stretch of absence; a stretch this long ends by itself. */+export const AWAY_STRETCH_MS = 12 * 60 * 60_000;+export const AWAY_ITEMS_MAX = 10;+export const AWAY_EMAILS_FILE = "away-emails.json";+const DAY_MS = 24 * 60 * 60_000;+const KEYS_KEEP_MS = 7 * DAY_MS;+const KEYS_MAX = 5_000;+const RETRY_MS = [60_000, 5 * 60_000];+const UNAVAILABLE_MS = 60 * 60_000;+const REFRESH_GAP_MS = 60_000;+const FETCH_TIMEOUT_MS = 15_000;+const ANSWER_MAX_BYTES = 64 * 1024;+const PERSON = /^p_[\w-]{22}$/u;++export type AwayKind = "mention" | "waiting" | "finished" | "failed";++/** One line of an away email, exactly as the Admin receives it. */+export interface AwayItem {+ kind: AwayKind;+ /** 64 hex digits: the SHA-256 of what it is about here, so the same thing is never emailed twice. */+ key: string;+ /** The teammate or bot who did it. On a private item only a teammate who wrote to the person. */+ who?: string;+ /** A shared place's name: the group chat's, or the bot's whose shared chat it is. Never on a private item. */+ place?: string;+ routine?: true;+ /** It happened in someone's private chat: the email says only what kind of thing it was. */+ private?: true;+}+/** One email for one person. `id` makes a retry the same email. */+export interface AwayNotice { id: string; to: string; language?: string; items: AwayItem[]; more?: number }+/** `POST /api/cloud/machines/team-away`, signed with the bootstrap secret (`teamAwaySignature`). `prefs` carries the+ * person's own switch, changed in the app, until the Admin has it. */+export interface AwayRequest { v: 1; notices: AwayNotice[]; prefs?: { to: string; on: boolean }[] }++const answerSchema = z.object({+ v: z.literal(1),+ results: z.array(z.object({ id: z.string(), state: z.string() })).max(50),+ off: z.array(z.string().max(320)).max(1_000).optional(),+});++/** Must match openmaus-cloud's teamAwaySignature. */+export function teamAwaySignature(secret: string, machineId: string, timestamp: string, nonce: string, body: string): string {+ const bodyHash = createHash("sha256").update(body).digest("base64url");+ return createHmac("sha256", secret).update(`omb-team-away-v1\n${machineId}\n${timestamp}\n${nonce}\n${bodyHash}`).digest("base64url");+}++export const awayKey = (about: string): string => createHash("sha256").update(`omb-team-away\n${about}`).digest("hex");++/** Something that happened for one person. `about` is what makes it the same thing twice; only its hash leaves. */+export interface AwayEvent {+ person: string;+ item: Omit<AwayItem, "key">;+ about: string;+ /** Finished work: its conversation, told once per stretch of absence, and left out of an email that already has a+ * question or a mention from there. */+ conversation?: string;+ /** A question or a mention: the conversation it came from. */+ thread?: string;+ /** Asked again when the email goes: false once it was answered, seen or closed. */+ still?: () => boolean;+}++interface Pending { key: string; at: number; item: AwayItem; conversation?: string; thread?: string; still?: () => boolean }+interface Timer { unref?(): unknown }++export interface TeamAwayDeps {+ /** Whether the person has the team open now. The one place that decides "away". */+ here(person: string): boolean;+ /** A current member by person key; undefined for someone who left or was never in. */+ member(person: string): { email: string } | undefined;+ /** The language their app shows, when the server knows it. */+ language(person: string): string | undefined;+ dataDir: string;+ adminOrigin: string;+ machineId: string;+ secret: string;+ fetchImpl?: typeof fetch;+ log?: (line: string) => void;+ now?: () => number;+ setTimer?: (run: () => void, ms: number) => Timer;+ clearTimer?: (timer: Timer) => void;+ /** AWAY_WINDOW_MS unless a fixture shortens it; a question's wait shortens with it. */+ windowMs?: number;+}++const prefSchema = z.object({ version: z.literal(1), on: z.boolean(), synced: z.boolean() });+type Pref = z.infer<typeof prefSchema>;++export function createTeamAway(deps: TeamAwayDeps) {+ const now = deps.now ?? Date.now, log = deps.log ?? (() => {});+ const fetcher = deps.fetchImpl ?? globalThis.fetch;+ const setTimer = deps.setTimer ?? ((run, ms) => setTimeout(run, ms));+ const clearTimer = deps.clearTimer ?? ((timer) => clearTimeout(timer as ReturnType<typeof setTimeout>));+ const windowMs = deps.windowMs ?? AWAY_WINDOW_MS, askMinMs = Math.min(AWAY_ASK_MIN_MS, windowMs / 2);+ const pending = new Map<string, Pending[]>();+ const timers = new Map<string, Timer>();+ const sentKeys = new Map<string, number>();+ const sentAt = new Map<string, number[]>();+ const stretches = new Map<string, { since: number; told: Set<string> }>();+ const retries = new Map<string, { notice: AwayNotice; items: Pending[]; tries: number }>();+ let unavailableUntil = 0, stopped = false, lastRefresh = 0;+ let syncTimer: Timer | null = null;++ const prefPath = (person: string) => join(deps.dataDir, "people", person, AWAY_EMAILS_FILE);+ const readPref = (person: string): Pref | null => {+ if (!PERSON.test(person)) return null;+ try {+ const parsed = prefSchema.safeParse(JSON.parse(readFileSync(prefPath(person), "utf8")));+ return parsed.success ? parsed.data : null;+ } catch { return null; }+ };+ const writePref = (person: string, pref: Pref | null) => {+ if (!PERSON.test(person)) return;+ try {+ if (!pref || (pref.on && pref.synced)) { rmSync(prefPath(person), { force: true }); return; }+ mkdirSync(join(deps.dataDir, "people", person), { recursive: true, mode: 0o700 });+ writeFileAtomic(prefPath(person), `${JSON.stringify(pref)}\n`, { mode: 0o600 });+ } catch (error) {+ log(`away emails: could not keep a switch: ${(error as NodeJS.ErrnoException).code ?? "error"}`);+ }+ };+ const isOn = (person: string) => readPref(person)?.on ?? true;+ const unsynced = (): { person: string; to: string; on: boolean }[] => {+ let people: string[] = [];+ try { people = readdirSync(join(deps.dataDir, "people")).filter((one) => PERSON.test(one)); } catch { return []; }+ return people.flatMap((person) => {+ const pref = readPref(person), member = pref && !pref.synced ? deps.member(person) : undefined;+ return pref && member ? [{ person, to: member.email, on: pref.on }] : [];+ });+ };++ const here = (person: string): boolean => {+ try { return deps.here(person); } catch { return true; }+ };+ const forget = (person: string) => {+ const timer = timers.get(person);+ if (timer) clearTimer(timer);+ timers.delete(person);+ pending.delete(person);+ retries.delete(person);+ stretches.delete(person);+ };+ const stretchOf = (person: string) => {+ const known = stretches.get(person);+ if (known && now() - known.since < AWAY_STRETCH_MS) return known;+ const fresh = { since: now(), told: new Set<string>() };+ stretches.set(person, fresh);+ return fresh;+ };+ const recentSends = (person: string) => (sentAt.get(person) ?? []).filter((at) => now() - at < DAY_MS);+ const remember = (keys: string[]) => {+ for (const [key, at] of sentKeys) if (now() - at >= KEYS_KEEP_MS) sentKeys.delete(key);+ for (const key of keys) sentKeys.set(key, now());+ while (sentKeys.size > KEYS_MAX) sentKeys.delete(sentKeys.keys().next().value!);+ };++ const schedule = (person: string, at?: number) => {+ if (stopped || timers.has(person)) return;+ const queue = pending.get(person) ?? [];+ const retry = retries.get(person);+ if (!queue.length && !retry) return;+ const last = recentSends(person).at(-1);+ const due = at ?? Math.max(Math.min(...queue.map((one) => one.at)) + windowMs, last !== undefined ? last + AWAY_GAP_MS : 0);+ const timer = setTimer(() => { timers.delete(person); void flush(person); }, Math.max(0, due - now()));+ timer.unref?.();+ timers.set(person, timer);+ };++ function noticed(event: AwayEvent): void {+ const { person } = event;+ if (stopped || !deps.member(person)) return;+ if (here(person)) { forget(person); return; }+ if (!isOn(person)) return;+ const key = awayKey(event.about);+ const queue = pending.get(person) ?? [];+ if (sentKeys.has(key) || queue.some((one) => one.key === key)) return;+ if (event.conversation && (stretchOf(person).told.has(event.conversation) || queue.some((one) => one.conversation === event.conversation))) return;+ queue.push({ key, at: now(), item: { ...event.item, key }, ...(event.conversation ? { conversation: event.conversation } : {}), ...(event.thread ? { thread: event.thread } : {}), ...(event.still ? { still: event.still } : {}) });+ pending.set(person, queue);+ schedule(person);+ }++ const signedPost = async (request: AwayRequest): Promise<{ status: number; answer: z.infer<typeof answerSchema> | null }> => {+ const body = JSON.stringify(request);+ const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");+ const response = await fetcher(`${deps.adminOrigin}${TEAM_AWAY_ADMIN_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), headers: {+ accept: "application/json", "content-type": "application/json", "x-omb-cloud-machine": deps.machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,+ "x-omb-cloud-signature": `v1=${teamAwaySignature(deps.secret, deps.machineId, timestamp, nonce, body)}`,+ } });+ const json = /^application\/json\b/i.test(response.headers.get("content-type") ?? "");+ if (response.status !== 200 || !json) { await response.body?.cancel().catch(() => {}); return { status: response.status, answer: null }; }+ const text = await response.text().catch(() => "");+ let parsed: unknown = null;+ try { parsed = text.length > ANSWER_MAX_BYTES ? null : JSON.parse(text); } catch { parsed = null; }+ const answer = answerSchema.safeParse(parsed);+ return { status: answer.success ? 200 : 502, answer: answer.success ? answer.data : null };+ };++ /** One call: what is to send, the switches not yet told, and what the Admin says is off. */+ const call = async (notices: AwayNotice[]): Promise<{ status: number; states: Map<string, string> }> => {+ const prefs = unsynced();+ if (now() < unavailableUntil) return { status: 404, states: new Map() };+ let result: Awaited<ReturnType<typeof signedPost>>;+ try {+ result = await signedPost({ v: 1, notices, ...(prefs.length ? { prefs: prefs.map(({ to, on }) => ({ to, on })) } : {}) });+ } catch (error) {+ log(`away emails: the Admin can't be reached (${error instanceof Error ? error.name : "error"})`);+ return { status: 0, states: new Map() };+ }+ if (result.status === 404) { unavailableUntil = now() + UNAVAILABLE_MS; return { status: 404, states: new Map() }; }+ if (!result.answer) { log(`away emails: the Admin answered HTTP ${result.status}`); return { status: result.status, states: new Map() }; }+ for (const { person, on } of prefs) {+ const pref = readPref(person);+ if (pref && pref.on === on && !pref.synced) writePref(person, { version: 1, on, synced: true });+ }+ for (const address of result.answer.off ?? []) {+ const person = personKey({ id: "", email: address });+ if (deps.member(person) && readPref(person)?.synced !== false) writePref(person, { version: 1, on: false, synced: true });+ }+ return { status: 200, states: new Map(result.answer.results.map(({ id, state }) => [id, state])) };+ };++ async function flush(person: string): Promise<void> {+ if (stopped) return;+ const member = deps.member(person);+ if (!member || here(person) || !isOn(person)) { forget(person); return; }+ const retry = retries.get(person);+ let notice: AwayNotice, items: Pending[], tries: number;+ if (retry) {+ retries.delete(person);+ ({ notice, items, tries } = retry);+ } else {+ const queue = pending.get(person) ?? [];+ const ready = queue.filter((one) => now() - one.at >= (one.item.kind === "waiting" ? askMinMs : 0));+ pending.set(person, queue.filter((one) => !ready.includes(one)));+ items = ready.filter((one) => !sentKeys.has(one.key) && (one.still?.() ?? true));+ tries = 0;+ if (!items.length || recentSends(person).length >= AWAY_DAILY_MAX) { schedule(person); return; }+ const covered = new Set(items.flatMap((one) => (one.thread ? [one.thread] : [])));+ const ranked = items.filter((one) => !one.conversation || !covered.has(one.conversation)).sort((a, b) => RANK[a.item.kind] - RANK[b.item.kind] || a.at - b.at);+ const language = deps.language(person);+ notice = { id: `n_${randomBytes(16).toString("base64url")}`, to: member.email, ...(language ? { language } : {}), items: ranked.slice(0, AWAY_ITEMS_MAX).map((one) => one.item),+ ...(ranked.length > AWAY_ITEMS_MAX ? { more: ranked.length - AWAY_ITEMS_MAX } : {}) };+ }+ const { status, states } = await call([notice]);+ if (stopped) return;+ const state = states.get(notice.id);+ if (status === 200 && state) {+ remember(items.map((one) => one.key));+ if (state === "sent") {+ sentAt.set(person, [...recentSends(person), now()]);+ const stretch = stretchOf(person);+ for (const one of items) if (one.conversation) stretch.told.add(one.conversation);+ }+ if (state === "off") writePref(person, { version: 1, on: false, synced: true });+ } else if ((status === 0 || status >= 500) && tries < RETRY_MS.length) {+ retries.set(person, { notice, items, tries: tries + 1 });+ schedule(person, now() + RETRY_MS[tries]!);+ return;+ }+ schedule(person);+ }++ const syncSoon = () => {+ if (stopped || syncTimer) return;+ syncTimer = setTimer(() => { syncTimer = null; void call([]); }, 2_000);+ syncTimer.unref?.();+ };++ const routes: (session: (auth: RequestAuth) => SessionRecord | null) => RouteHandler = (session) => async ({ req, res, path, method, auth, json, readBody }) => {+ if (path !== AWAY_EMAILS_PATH) return PASS;+ const signedIn = session(auth);+ if (!signedIn?.email) return json(res, 403, { error: "Sign in to this team to choose your emails." });+ const person = personKey(signedIn);+ if (method === "GET") {+ if (now() - lastRefresh >= REFRESH_GAP_MS) {+ lastRefresh = now();+ await Promise.race([call([]), new Promise((resolve) => { const timer = setTimer(() => resolve(null), 3_000); timer.unref?.(); })]);+ }+ return json(res, 200, { on: isOn(person) });+ }+ if (method !== "PUT") return json(res, 405, { error: "method not allowed" });+ const body = await readBody(req, 1024);+ const on = body && typeof body === "object" ? (body as { on?: unknown }).on : undefined;+ if (typeof on !== "boolean") return json(res, 400, { error: "send { on: true } or { on: false }" });+ writePref(person, { version: 1, on, synced: false });+ if (!on) forget(person);+ syncSoon();+ return json(res, 200, { on });+ };++ return {+ noticed,+ routes,+ /** Runs every person's timer now, as if each were due. */+ async runTimers(): Promise<void> {+ for (const person of new Set([...pending.keys(), ...retries.keys()])) {+ const timer = timers.get(person);+ if (timer) clearTimer(timer);+ timers.delete(person);+ await flush(person);+ }+ },+ pendingFor: (person: string): readonly AwayItem[] => (pending.get(person) ?? []).map((one) => one.item),+ stop(): void {+ stopped = true;+ for (const timer of timers.values()) clearTimer(timer);+ timers.clear();+ if (syncTimer) clearTimer(syncTimer);+ },+ };+}++const RANK: Record<AwayKind, number> = { waiting: 0, mention: 1, failed: 2, finished: 3 };++export type TeamAway = ReturnType<typeof createTeamAway>;diff --git a/server/host/team-join-host.ts b/server/host/team-join-host.tsnew file mode 100644index 0000000000..ac2957aed3--- /dev/null+++ b/server/host/team-join-host.ts@@ -0,0 +1,19 @@+// What a Team Cloud tells one signed-in person about joining it (openmaus-cloud docs/team-cloud.md "Getting an invited+// person in"): their own welcome record inside the onboarding record, and their team page on MausBot Cloud, where they open+// the team in a browser again. Told to a signed-in session only, never before sign-in.+import { personalHints } from "../../shared/cloud-hints.ts";+import type { CloudHomeConfig } from "../cloud-home.ts";+import { personKey } from "../person-key.ts";+import type { SessionRecord } from "../sessions.ts";+import type { TeamWelcomeStore } from "../team-welcome.ts";++/** The onboarding record this person reads on a team: the welcome's own hints are theirs (shared/cloud-hints.ts). */+export function teamOnboarding<T extends { hintsSeen: string[] }>(onboarding: T, session: SessionRecord | null | undefined, welcome: Pick<TeamWelcomeStore, "read">): T {+ return { ...onboarding, hintsSeen: personalHints(onboarding.hintsSeen, session ? welcome.read(personKey(session)).hints : [], session?.teamRole === "owner") };+}++/** `/api/auth/session`'s `teamSignIn` for a team session: the person's team page on MausBot Cloud. An address, nothing that+ * signs anyone in; the app keeps it so a page whose session ended can offer the way back. */+export function teamSignInFor(cloudHome: CloudHomeConfig | null, session: Pick<SessionRecord, "membershipAuthority">): { teamSignIn: string } | Record<string, never> {+ return cloudHome?.team && session.membershipAuthority === "team" ? { teamSignIn: `${cloudHome.adminOrigin}/cloud/team/${encodeURIComponent(cloudHome.team.id)}` } : {};+}diff --git a/server/host/team-member-left.test.ts b/server/host/team-member-left.test.tsindex 5ddccdcca8..3c0d9885fd 100644--- a/server/host/team-member-left.test.ts+++ b/server/host/team-member-left.test.ts@@ -23,6 +23,9 @@ function fixture() {const deleted: string[] = [];const deletedBots: string[] = [];const working = new Set<string>();+ const routines: Array<{ id: string; name: string; botId: string; home: string | null; writer: string | undefined; files: string[] }> = [];+ const handed: Array<[string, string, string | null]> = [];+ const rows: unknown[] = [];const deps: TeamMemberLeftDeps = {dataDir,store: { get bots() { return bots; }, messagesFor: (threadId) => messages.get(threadId) ?? [] },@@ -48,12 +51,39 @@ function fixture() {deleteAttachment: (file) => deleted.push(file),eraseBrowsers: async () => true,forgetConnections: () => {},+ routines: () => routines,+ deleteRoutine: (id) => { routines.splice(routines.findIndex((routine) => routine.id === id), 1); },+ handRoutine: (id, left, to) => { handed.push([id, left, to]); },+ forgetOnBots: () => 0,+ ownerOf: (botId) => (botId === "scout" ? "[email protected]" : botId === "ledger" ? BOB : null),+ record: (row) => { rows.push(row); },};const file = (n: number) => { writeFileSync(join(attachments, name(n)), "x"); return name(n); };- return { dataDir, attachments, messages, bots, deleted, deletedBots, working, deps, file };+ return { dataDir, attachments, messages, bots, deleted, deletedBots, working, deps, file, routines, handed, rows };}describe("createTeamMemberLeft", () => {+ it("deletes the routines in their private chats with the files only those used, and hands the shared ones they wrote over", async () => {+ const fx = fixture();+ const own = fx.file(1), shared = fx.file(2);+ fx.routines.push(+ { id: "kumquat", name: "Kumquat", botId: "scout", home: bob, writer: undefined, files: [own] },+ { id: "standup", name: "Standup", botId: "scout", home: null, writer: bob, files: [shared] },+ { id: "tally", name: "Tally", botId: "ledger", home: null, writer: bob, files: [] },+ { id: "theirs", name: "Theirs", botId: "scout", home: null, writer: "p_someone_else_entirely", files: [] },+ );+ const result = await createTeamMemberLeft({ ...fx.deps, openedBy: () => [] })(BOB);+ expect(fx.routines.map((routine) => routine.id)).toEqual(["standup", "tally", "theirs"]);+ expect(fx.handed).toEqual([["standup", bob, personKey({ id: "", email: "[email protected]" })], ["tally", bob, null]]);+ expect(fx.rows).toEqual([+ { category: "bot", action: "routine.handover", target: { kind: "routine", id: "standup", name: "Standup" }, after: { owner: "[email protected]" } },+ { category: "bot", action: "routine.handover", target: { kind: "routine", id: "tally", name: "Tally" }, after: { owner: null } },+ { category: "people", action: "member.left", target: { kind: "person", name: BOB }, after: { botsHandedBack: 0, routinesHandedOver: 2 } },+ ]);+ expect(fx.deleted).toEqual([own]);+ expect(result).toMatchObject({ routines: 1, routinesHandedOver: 2 });+ });+it("deletes the departing member's own MausBot with its chats, and counts them", async () => {const fx = fixture();fx.messages.set("mausbot-main", [{ role: "user", text: "LC-L2-MAIN-9081" }]);diff --git a/server/host/team-member-left.ts b/server/host/team-member-left.tsindex b2cc3a5c6e..4c6e3b878d 100644--- a/server/host/team-member-left.ts+++ b/server/host/team-member-left.ts@@ -1,9 +1,13 @@// When a person leaves a Team Cloud (an admin removes them, or they leave), what was theirs alone goes with them: their// own MausBot with its chats and notes, their private chats with every bot (messages, notifications, the files only-// those chats used, and the files they uploaded and never sent), their memory layers, their+// those chats used, and the files they uploaded and never sent), the routines that live in those chats, their memory+// layers, their// engine home (its transcripts), their "About you", their own connections, their own browsers, and every session and-// phone of theirs. Nothing of it is handed to an admin. The Admin tells this machine with a signed request-// (`POST /api/cloud/team/member-left`, cloud-signed.ts).+// phone of theirs. Nothing of it is handed to an admin. A routine they wrote for a shared place keeps running, as the+// routine of whoever looks after its bot now (the Admins when nobody does), and admin activity says it was handed over.+// They come off every bot's sharing and "Looked after by" (what they looked after falls to the Admins), so joining again+// restores nothing, and one admin activity row says who left, in counts. The Admin tells this machine with a signed+// request (`POST /api/cloud/team/member-left`, cloud-signed.ts).//// Each conversation keeps its starter (thread-starters.json, a hash): what other records still name it (a decision's// row, a usage trace) stays someone else's, so no admin ever reads it there either.@@ -11,6 +15,7 @@ import { existsSync, readdirSync, rmSync } from "node:fs";import { basename, join } from "node:path";import { defaultBotPerson, type DefaultBotFields } from "../../shared/default-bot.ts";+import type { AdminActionRow } from "../admin-activity.ts";import { memberAudience, type Audience } from "../audience.ts";import { forgetDefaultBot } from "../default-bot.ts";import { audienceHome } from "../engine-homes/layout.ts";@@ -49,9 +54,22 @@ export interface TeamMemberLeftDeps {eraseBrowsers(audience: Audience): Promise<boolean>;/** Their own connections, keys and MCP sign-ins (team-connections.ts). */forgetConnections(person: string): void;+ /** Every routine: `home` is the person whose private chat it lives in (routine-home.ts), `writer` who last wrote it,+ * `files` the attachments/ names it carries. */+ routines(): ReadonlyArray<{ id: string; name: string; botId: string; home: string | null; writer: string | undefined; files: readonly string[] }>;+ deleteRoutine(id: string): void;+ /** The routine runs as `to`'s from now on (a person key), or nobody's, whose asks go to the Admins (null); it stops+ * reporting into a chat of `left`, the person who left. */+ handRoutine(id: string, left: string, to: string | null): void;+ /** Takes the address off every bot's sharing and "Looked after by"; how many bots they looked after. */+ forgetOnBots(email: string): number;+ /** Who looks after the bot (an address), else null. */+ ownerOf(botId: string): string | null;+ /** One row of the team's admin activity. */+ record(row: Omit<AdminActionRow, "at" | "actor">): void;}-export type TeamMemberLeftResult = { chats: number; layers: number; sessions: number; files: number; browsers: boolean; bots: number; botsKept: number };+export type TeamMemberLeftResult = { chats: number; layers: number; sessions: number; files: number; browsers: boolean; bots: number; botsKept: number; routines: number; routinesHandedOver: number; botsHandedBack: number };export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string) => Promise<TeamMemberLeftResult> {const workspaces = join(deps.dataDir, "workspaces");@@ -61,15 +79,27 @@ export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string)if (!PERSON.test(person)) throw new Error("not a person key");// First, so nothing of theirs is opened, written or streamed while it goes.const sessions = deps.revokeSessions(email);+ const address = email.trim().toLowerCase();+ const botsHandedBack = deps.forgetOnBots(address);+ // Before their chats go: which routine lives in one is read from those chats.+ const everyRoutine = deps.routines();+ const ownRoutines = everyRoutine.filter((routine) => routine.home === person);+ const written = everyRoutine.filter((routine) => routine.home === null && routine.writer === person);+ for (const routine of written) {+ const owner = deps.ownerOf(routine.botId);+ const to = owner && owner !== address ? owner : null;+ deps.handRoutine(routine.id, person, to === null ? null : personKey({ id: "", email: to }));+ deps.record({ category: "bot", action: "routine.handover", target: { kind: "routine", id: routine.id, name: routine.name }, after: { owner: to } });+ }+ for (const routine of ownRoutines) deps.deleteRoutine(routine.id);const mine = new Set(deps.openedBy(person).filter((threadId) => deps.privateTo(threadId) === person));let chats = 0;- const files = new Set<string>(memberUploads(deps.dataDir, person));+ const files = new Set<string>([...memberUploads(deps.dataDir, person), ...ownRoutines.flatMap((routine) => routine.files)]);const noteFiles = (threadId: string) => {for (const match of JSON.stringify(deps.store.messagesFor(threadId)).matchAll(ATTACHMENT)) files.add(match[1]!);};let bots = 0;let botsKept = 0;- const address = email.trim().toLowerCase();for (const bot of deps.store.bots.filter((candidate) => candidate.defaultBot && defaultBotPerson(candidate) === address)) {const threads = (bot.tasks ?? []).map((task) => task.threadId);threads.forEach(noteFiles);@@ -91,11 +121,13 @@ export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string)}chats += deps.deleteTasks(bot.id, threads)?.deleted.length ?? 0;}- // A file only their chats used, or that they never sent, goes too; one a bot's picture or another conversation uses stays.+ // A file only their chats or private routines used, or that they never sent, goes too; one a bot's picture, another+ // conversation or a routine that stays uses stays.+ const routineFiles = new Set(deps.routines().flatMap((routine) => routine.files));let removed = 0;for (const name of files) {const url = `/api/attachments/${name}`;- if (name.includes("..") || !existsSync(join(attachments, name)) || deps.threadsReferencing(name).length || deps.store.bots.some((bot) => bot.avatarUrl === url)) continue;+ if (name.includes("..") || !existsSync(join(attachments, name)) || routineFiles.has(name) || deps.threadsReferencing(name).length || deps.store.bots.some((bot) => bot.avatarUrl === url)) continue;deps.deleteAttachment(basename(name));removed++;}@@ -113,6 +145,8 @@ export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string)rmSync(audienceHome(deps.dataDir, memberAudience(person)), { recursive: true, force: true });deps.forgetConnections(person);const browsers = await deps.eraseBrowsers(memberAudience(person)).catch(() => false);- return { chats, layers, sessions, files: removed, browsers, bots, botsKept };+ // Counts of shared things only: nothing here says what was theirs alone.+ deps.record({ category: "people", action: "member.left", target: { kind: "person", name: address }, after: { botsHandedBack, routinesHandedOver: written.length } });+ return { chats, layers, sessions, files: removed, browsers, bots, botsKept, routines: ownRoutines.length, routinesHandedOver: written.length, botsHandedBack };};}diff --git a/server/host/team-messages.ts b/server/host/team-messages.tsindex 0e0667307b..6cee916820 100644--- a/server/host/team-messages.ts+++ b/server/host/team-messages.ts@@ -67,7 +67,7 @@ export interface TeamMessagesDeps {/** The inbox of a place that is no team's. */place?: PlaceInbox | null;/** What the inbox needs from the server: whose asks are whose, hand-offs, a bot carrying on, the assistant's reads. */- inbox: Pick<PersonInboxDeps, "askedPerson" | "handedFrom" | "continueTurn"> & Partial<Pick<PersonInboxDeps, "notes" | "ensureOwnBot" | "changed">> & {+ inbox: Pick<PersonInboxDeps, "askedPerson" | "handedFrom" | "continueTurn"> & Partial<Pick<PersonInboxDeps, "notes" | "ensureOwnBot" | "changed" | "delivered">> & {representative?: Omit<RepresentativeDeps, "timeZone"> & Partial<Pick<RepresentativeDeps, "timeZone">>;};now?: () => number;diff --git a/server/host/team-owners.ts b/server/host/team-owners.tsindex 76d8cc94ec..30664cc792 100644--- a/server/host/team-owners.ts+++ b/server/host/team-owners.ts@@ -61,9 +61,9 @@ export function createTeamOwners(deps: TeamOwnersDeps) {left(email: string): void {people?.left(email);},- /** Bots moved in before owners were recorded report to whoever moved them. */+ /** Bots moved in before owners were recorded report to whoever moved them, unless they left. */backfill(moveIns: Record<string, { email?: string }>): void {- for (const [botId, move] of Object.entries(moveIns)) if (move.email) setCreatedBy(deps.store(), botId, move.email);+ for (const [botId, move] of Object.entries(moveIns)) if (move.email && !people?.gone(move.email)) setCreatedBy(deps.store(), botId, move.email);},};}diff --git a/server/host/team-routines.test.ts b/server/host/team-routines.test.tsnew file mode 100644index 0000000000..ec9ad9b26a--- /dev/null+++ b/server/host/team-routines.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from "vitest";++import { RESULTS_JUST_ME } from "../../shared/routines.ts";+import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "../cloud-sharing.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import type { Routine } from "../routines.ts";+import { createTeamRoutines, type TeamRoutinesDeps } from "./team-routines.ts";++const BOB = "[email protected]", bob = personKey({ id: "", email: BOB });+const OLIVE = "[email protected]", olive = personKey({ id: "", email: OLIVE });+const session = (email: string) => ({ kind: "session", scopes: ["client"], session: { id: `s-${email}`, email } }) as unknown as RequestAuth;++function fixture(team = true) {+ const starters = new Map<string, string>([["bob-chat", bob], ["bob-old-results", bob]]);+ const tasks = [+ { threadId: "main", title: "Scout" },+ { threadId: "bob-old-results", title: "Standup · Results" },+ { threadId: "bob-chat", title: "Bob's plans" },+ ];+ const writers = new Map<string, string>();+ const opened: Array<[string, string, string]> = [];+ const deps: TeamRoutinesDeps = {+ team,+ privateTo: (threadId) => starters.get(threadId) ?? null,+ task: (_botId, threadId) => tasks.find((task) => task.threadId === threadId),+ ownBot: (botId) => (botId === "bobs-mausbot" ? bob : null),+ routines: () => null,+ authors: { forget: () => {}, wrote: (id, person) => { writers.set(id, person); }, writer: (id) => writers.get(id), remove: () => {} },+ withWriter: (_writer, work) => work(),+ tasks: () => tasks,+ openChat: (botId, title, person) => { opened.push([botId, title, person]); starters.set("new-chat", person); return "new-chat"; },+ threadRefusal: () => "On this Cloud you can only change conversations you started.",+ };+ return { host: createTeamRoutines(deps), writers, opened, tasks };+}+const routine = (fields: Partial<Routine>) => ({ id: "r1", name: "Standup", botId: "scout", ...fields }) as Routine;++describe("createTeamRoutines", () => {+ it("opens a shared routine's chats as the team, whoever wrote it, and a private one's as its person", () => {+ const { host, writers } = fixture();+ writers.set("r1", bob);+ expect(host.opener(routine({}))).toBe(CLOUD_NOBODY_KEY);+ expect(host.opener(routine({ resultsThreadId: "main" }))).toBe(CLOUD_NOBODY_KEY);+ expect(host.opener(routine({ sourceThreadId: "bob-chat" }))).toBe(bob);+ expect(host.opener(routine({ botId: "bobs-mausbot" }))).toBe(bob);+ writers.set("r1", CLOUD_OUTSIDE_KEY);+ expect(host.opener(routine({}))).toBe(CLOUD_OUTSIDE_KEY);+ expect(fixture(false).host.opener(routine({}))).toBeNull();+ });++ it("moves results that sit outside where the routine lives, a shared one's old private results chat included", () => {+ const { host } = fixture();+ expect(host.reportsElsewhere(routine({ resultsThreadId: "bob-old-results" })), "a shared routine, its writer's old chat").toBe(true);+ expect(host.reportsElsewhere(routine({ resultsThreadId: "main" }))).toBe(false);+ expect(host.reportsElsewhere(routine({ sourceThreadId: "bob-chat", resultsThreadId: "main" })), "a private one into the shared chat").toBe(true);+ expect(host.reportsElsewhere(routine({ resultsThreadId: "bob-chat" }))).toBe(false);+ expect(fixture(false).host.reportsElsewhere(routine({ resultsThreadId: "bob-old-results" }))).toBe(false);+ });++ it("lets a member point results at any chat they read, refuses another person's MausBot, and keeps the Cloud's rule off a team", () => {+ const { host } = fixture();+ expect(host.bodyRefusal(session(BOB), { botId: "scout", resultsThreadId: "main" })).toBeNull();+ expect(host.bodyRefusal(session(OLIVE), { botId: "bobs-mausbot", name: "x" })).toEqual({ status: 404, error: "no such bot" });+ expect(host.bodyRefusal(session(BOB), { botId: "bobs-mausbot", name: "x" })).toBeNull();+ expect(fixture(false).host.bodyRefusal(session(BOB), { resultsThreadId: "main" })?.status).toBe(403);+ });++ it("makes Just me the person's own private chat with the bot, or a new one", () => {+ const { host, opened, tasks } = fixture();+ expect(host.justMe(session(BOB), { botId: "scout", name: "Kumquat", resultsThreadId: RESULTS_JUST_ME })).toMatchObject({ resultsThreadId: "bob-chat" });+ expect(host.justMe(session(OLIVE), { botId: "scout", name: "Kumquat", resultsThreadId: RESULTS_JUST_ME })).toMatchObject({ resultsThreadId: "new-chat" });+ expect(opened).toEqual([["scout", "Kumquat", olive]]);+ tasks.splice(2, 1);+ expect(host.justMe(session(BOB), { botId: "scout", name: "Standup", resultsThreadId: RESULTS_JUST_ME }), "never the chat a routine opened for itself").toMatchObject({ resultsThreadId: "new-chat" });+ const plain = { botId: "scout", resultsThreadId: "main" };+ expect(host.justMe(session(BOB), plain)).toBe(plain);+ });+});diff --git a/server/host/team-routines.ts b/server/host/team-routines.tsnew file mode 100644index 0000000000..f6ad039277--- /dev/null+++ b/server/host/team-routines.ts@@ -0,0 +1,106 @@+// A Team Cloud's routines and the audience rule (docs/team-cloud.md "Routines"): the person whose private chat a routine+// lives in (routine-home.ts), whether a bot's turn may know of it, who its runs and results chats are opened as (its+// person's for a private one, the team's for one of a shared place, whoever made it), what a person may point it at,+// and what happens to a leaver's routines (team-member-left.ts). Off a team every answer here is the plain one.+import { basename } from "node:path";++import { RESULTS_JUST_ME } from "../../shared/routines.ts";+import { isOwnResultsChat } from "../automation-destinations.ts";+import type { createCloudRoutineAuthors } from "../cloud-lending.ts";+import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "../cloud-sharing.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import { routineHome, type RoutineHomeDeps, type RoutinePlace } from "../routine-home.ts";+import type { Routine, RoutineManager } from "../routines.ts";+import type { TaskRecord } from "../store.ts";+import type { TeamMemberLeftDeps } from "./team-member-left.ts";++export const NO_SUCH_TRIGGER = "No trigger with that id belongs to this bot. Call trigger_info without trigger_id to see its ids.";++export interface TeamRoutinesDeps extends RoutineHomeDeps {+ team: boolean;+ /** index.ts's routines, made after this host. */+ routines(): Pick<RoutineManager, "listRoutines" | "update" | "removeForBot"> | null;+ authors: Pick<ReturnType<typeof createCloudRoutineAuthors>, "forget" | "wrote" | "writer" | "remove"> | null;+ /** Runs `work` with `writer` as whoever opens the chats it makes (index.ts's withRoutineWriter). */+ withWriter<T>(writer: string, work: () => T): T;+ tasks(botId: string): ReadonlyArray<Pick<TaskRecord, "threadId" | "title" | "askedAt" | "routineRunId">>;+ /** A new conversation with the bot, opened by (private to) this person. */+ openChat(botId: string, title: string, person: string): string | undefined;+ /** Off a team: why this session may not point a routine's results at this conversation (a Cloud home's rule). */+ threadRefusal(auth: RequestAuth, threadId: string): string | null;+}++export function createTeamRoutines(deps: TeamRoutinesDeps) {+ /** The person whose private chat a routine lives in on a Team Cloud; null anywhere else. */+ const home = (routine: RoutinePlace): string | null => (deps.team ? routineHome(routine, deps) : null);+ /** A turn's bot tools reach a private routine only in its person's own conversations. */+ const inTurn = (routine: RoutinePlace, threadId: string): boolean => {+ const person = home(routine);+ return person === null || person === deps.privateTo(threadId);+ };+ /** A routine whose writer left runs as `to`'s (a person key; null: nobody's, whose asks go to the Admins), and stops+ * reporting into a chat of the person who left. */+ const hand = (id: string, left: string, to: string | null): void => {+ const writer = to ?? CLOUD_NOBODY_KEY;+ deps.authors?.forget(id);+ deps.authors?.wrote(id, writer);+ const routine = deps.routines()?.listRoutines().find((candidate) => candidate.id === id);+ if (routine?.resultsThreadId && deps.privateTo(routine.resultsThreadId) === left) deps.withWriter(writer, () => deps.routines()!.update(id, { resultsThreadId: null }));+ };+ const field = (body: unknown, key: "botId" | "resultsThreadId" | "name"): unknown => (body && typeof body === "object" ? (body as Record<string, unknown>)[key] : undefined);+ return {+ home,+ inTurn,+ /** On a team, who a routine's chats are opened as: its person for a private one; the team (nobody, or outside work)+ * for one of a shared place, whoever made it, so everyone who reads that place reads its runs. Null off a team. */+ opener(routine: RoutinePlace & { id: string }): string | null {+ if (!deps.team) return null;+ return home(routine) ?? (deps.authors?.writer(routine.id) === CLOUD_OUTSIDE_KEY ? CLOUD_OUTSIDE_KEY : CLOUD_NOBODY_KEY);+ },+ /** A routine's results follow where it lives: one reporting into a chat whose audience is not its own (a private+ * routine's into a shared chat, or a shared one's into the chat it once opened privately for its writer) gets a new+ * results chat of its own audience at its next run. */+ reportsElsewhere(routine: Routine): boolean {+ return deps.team && Boolean(routine.resultsThreadId) && deps.privateTo(routine.resultsThreadId!) !== home(routine);+ },+ /** Why this routine body is refused: on a team, another person's own MausBot is no bot of theirs (any chat they read+ * may take its results; the visibility gate refuses another person's); off a team, the Cloud's rule for results. */+ bodyRefusal(auth: RequestAuth, body: unknown): { status: number; error: string } | null {+ const botId = field(body, "botId"), results = field(body, "resultsThreadId");+ if (!deps.team) {+ const refused = typeof results === "string" ? deps.threadRefusal(auth, results) : null;+ return refused ? { status: 403, error: refused } : null;+ }+ const own = typeof botId === "string" ? deps.ownBot?.(botId) : null;+ return own && (auth.kind !== "session" || own !== personKey(auth.session)) ? { status: 404, error: "no such bot" } : null;+ },+ /** "Just me" made concrete: the person's own private chat with the bot, else a new one named for the routine. */+ justMe<T>(auth: RequestAuth, body: T, routineId?: string): T {+ if (!deps.team || auth.kind !== "session" || field(body, "resultsThreadId") !== RESULTS_JUST_ME) return body;+ const person = personKey(auth.session);+ const existing = routineId ? deps.routines()?.listRoutines().find((routine) => routine.id === routineId) : undefined;+ const botId = typeof field(body, "botId") === "string" ? field(body, "botId") as string : existing?.botId;+ if (!botId) return body;+ const name = typeof field(body, "name") === "string" ? field(body, "name") as string : existing?.name ?? "Routine";+ const mine = deps.tasks(botId).find((task) => !task.routineRunId && deps.privateTo(task.threadId) === person && !isOwnResultsChat(name, task));+ const threadId = mine?.threadId ?? deps.openChat(botId, name, person);+ return threadId ? { ...body, resultsThreadId: threadId } : body;+ },+ /** Why a bot's change to a trigger by id is refused in this conversation: one that lives in someone else's private chat. */+ hiddenTrigger(request: { kind: string; proposal?: { routineId?: string } }, threadId: string): string | null {+ const id = request.kind === "schedule" ? request.proposal?.routineId : undefined;+ const named = id ? deps.routines()?.listRoutines().find((routine) => routine.id === id) : undefined;+ return named && !inTurn(named, threadId) ? NO_SUCH_TRIGGER : null;+ },+ /** The leave clean-up's part in routines. */+ leaving: {+ routines: () => (deps.routines()?.listRoutines() ?? []).map((routine) => ({ id: routine.id, name: routine.name, botId: routine.botId, home: home(routine),+ writer: deps.authors?.writer(routine.id), files: (routine.attachments ?? []).map((file) => basename(file.path)) })),+ deleteRoutine: (id: string) => { const routine = deps.routines()?.listRoutines().find((candidate) => candidate.id === id); if (routine) { deps.routines()!.removeForBot(routine.botId, id); deps.authors?.remove(id); } },+ handRoutine: hand,+ } satisfies Pick<TeamMemberLeftDeps, "routines" | "deleteRoutine" | "handRoutine">,+ };+}++export type TeamRoutines = ReturnType<typeof createTeamRoutines>;diff --git a/server/host/visibility-host.ts b/server/host/visibility-host.tsindex f6c5b43e31..7dc4ae88af 100644--- a/server/host/visibility-host.ts+++ b/server/host/visibility-host.ts@@ -2,6 +2,8 @@// room or conversation change), the one check every request naming a bot, conversation, room, routine or file passes, and// the per-conversation filter a list uses. On a Team Cloud an admin is a viewer with a person too: every bot and room, but// only their own private chats (audience.ts).+import { basename } from "node:path";+import { audienceEquals, narrowestAudience, roomFeeds, routineRunVisible, routineVisible, SEES_EVERYTHING, VisibleSet, type PathSubject, type ThreadAudiences, type ThreadOwner, type Viewer } from "../bot-visibility.ts";import type { RequestAuth } from "../request-auth.ts";import type { RoutineManager } from "../routines.ts";@@ -70,6 +72,14 @@ export function createVisibilityHost(deps: VisibilityHostDeps) {return threads;}+ /** On a Team Cloud a file a routine carries is refused when only routines hidden from the viewer use it and no+ * conversation they read does. */+ function routineFileShown(name: string, visible: VisibleSet): boolean {+ if (!visible.filtersThreads) return true;+ const users = (deps.routines()?.listRoutines() ?? []).filter((routine) => routine.attachments?.some((file) => basename(file.path) === name));+ return !users.length || users.some((routine) => routineVisible(routine, visible)) || threadsUsingAttachment(name).some((threadId) => visible.thread(threadId));+ }+/** The one visibility check every member request naming a subject passes through (a team's admin's too). */function subjectVisible(subject: PathSubject, visible: VisibleSet): boolean {switch (subject.kind) {@@ -88,7 +98,7 @@ export function createVisibilityHost(deps: VisibilityHostDeps) {return !run || routineRunVisible(run, visible);}case "attachment":- return visible.attachment(subject.name, threadsUsingAttachment);+ return visible.attachment(subject.name, threadsUsingAttachment) && routineFileShown(subject.name, visible);}}diff --git a/server/index.ts b/server/index.tsindex c6c5ccb198..7be7f9289b 100644--- a/server/index.ts+++ b/server/index.ts@@ -272,7 +272,7 @@ import { EventBus } from "./harness/bus.ts";import { ENGINE_LIST_REUSE_MS, engineMemory, enginesByUse, ProviderRegistry } from "./harness/registry.ts"; import { afterFirstEngineRead, holdUntilFirstEngineRead } from "./first-engine-read.ts";import { ManagedDesktopProviders } from "./managed-desktop.ts";import { mainThread, wasOldestThread } from "./main-thread.ts";-import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } from "./managed-policy.ts"; import { nudgeCloudTeamPolicy, remoteAccessPaths, startCloudTeamPolicy, stopCloudTeamPolicy } from "./cloud-team-policy.ts";+import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } from "./managed-policy.ts"; import { nudgeCloudTeamPolicy, remoteAccessPaths, startCloudTeamPolicy, stopCloudTeamPolicy } from "./cloud-team-policy.ts"; import { startCloudTeamRoster, stopCloudTeamRoster } from "./cloud-team-roster.ts"; import { createTeamWelcomeStore } from "./team-welcome.ts"; import { teamOnboarding, teamSignInFor } from "./host/team-join-host.ts";import { hostedModelPolicy, HOSTED_MODEL_POLICY_HEADER } from "./hosted-models.ts";import { CLOUD_HOME_SECRET_KEYS, CLOUD_IGNORED_KEYS, cloudHomeConfiguration, cloudHomeOffersPlace, cloudHomePlaceRefusal, firstCloudTurnPatch } from "./cloud-home.ts";import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { attachmentsForBox } from "./box-attachments.ts"; import { brokerPath } from "./bot-box/broker-probe.ts";@@ -300,7 +300,7 @@ import { createLiveApprovalMode } from "./host/live-approval.ts";import { CONSENT_RULE, continuedOrigin, escapeNotes, labelledLine, OUTSIDE, peerLineText, peerProvenanceNote, reportNote, requestWorkOrigin, type WorkOrigin } from "./peer-provenance.ts"; import { lineNote, PROVENANCE_PROMPT } from "./provenance-label.ts"; import { openRoomThread } from "./host/room-new-thread.ts"; import { createLineLabels } from "./host/line-labels.ts";import { decideRoomPost, emptyRoomPostBudget, type RoomPostAttempt, type RoomPostBudget } from "./room-post-budget.ts";import { messagePages, pageSize, slimMessage } from "./host/message-pages.ts";-import { coordinateResultMessage, createAsksActingPerson, createTeammatePrompts } from "./host/teammate-prompts.ts"; import { createMausBotOwnChat } from "./host/mausbot-own-chat.ts"; import { moveMemoryLayer } from "./memory-move.ts";+import { coordinateResultMessage, createAsksActingPerson, createTeammatePrompts } from "./host/teammate-prompts.ts"; import { createPersonalReach } from "./host/personal-reach.ts"; import { createMausBotOwnChat } from "./host/mausbot-own-chat.ts"; import { moveMemoryLayer } from "./memory-move.ts";import { createQueuedReason } from "./host/queued-reason.ts";import { ReplayBuffer } from "./host/sse-replay.ts";import {@@ -427,7 +427,7 @@ import { ComputerIdleTimer } from "./computer-idle.ts";import { CLOUD_COMPUTER_DID_NOT_START, CLOUD_COMPUTER_START_BUDGET_MS, CLOUD_COMPUTER_STARTING, createCloudComputerPower } from "./host/cloud-computer-power.ts";import { LocalVmLease, LocalVmLeasePool } from "./local-vm-lease.ts";import { LocalVmSeatPool, type LocalVmSeatHolder } from "./local-vm-seat-pool.ts";-import { createLoopGuard, loopGuardSettings } from "./host/loop-guard.ts"; import { createPersonFirst } from "./host/person-first.ts";+import { createLoopGuard, loopGuardSettings } from "./host/loop-guard.ts"; import { createPersonFirst } from "./host/person-first.ts"; import { createRunOwners, runActorOf } from "./host/run-owner.ts";import { claudeUserSkillsEnabled, settingsTurnFields } from "./turn-settings.ts";import { addHeldSecretScrubber, redactSecretsInText, scrubHeldSecrets } from "./redact.ts";import * as vps from "./vps-computer.ts";@@ -454,7 +454,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 { createTeamPresenceHost } from "./host/team-presence-host.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 { createTeamRoutines } from "./host/team-routines.ts"; import { botOwner } from "../shared/bot-owner.ts"; import { forgetMember } from "./bot-owners.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 { createTeamPresenceHost } from "./host/team-presence-host.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";@@ -564,7 +564,7 @@ import {noteSeen,notFoundFor,pathSubject,- routineRunVisible, routineVisible,+ routineForViewer, routineRunVisible, routineVisible,sameAudience,VisibleSet,type FrameContext,@@ -634,7 +634,7 @@ import { createReactions, withReactionNotes, type Reactor } from "./reactions.tsimport { createPersonReplies } from "./person-replies.ts";import { personKey, relayedPersonKey } from "./person-key.ts";import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";-import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";+import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";import { createThreadRoutes } from "./routes/threads.ts";@@ -956,7 +956,7 @@ let cloudHome: ReturnType<typeof settleCloudHome> | null = null; const teamHostserverProfile: { read: () => cfg.profile, clear: () => { adminActorScope.exit(() => saveConfig({ profile: { name: "", email: "", aboutMe: "", avatarUrl: "" } })); Object.assign(cfg, loadConfig()); } } });const teamOwners = createTeamOwners({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store: () => store, audienceOf: (threadId) => teamHost.audienceOf(threadId), starters: threadStarters }); const mausbotOwnChat = createMausBotOwnChat({ bots: () => store.bots, starters: threadStarters, personKey: (email) => personKey({ id: "", email }), moveNotes: (from, to, person) => moveMemoryLayer(from, to, personLanguages.forLine(person)) });const personRooms = createPersonRooms({ reads: CLOUD_TEAM ? createRoomReads(DATA_DIR, (person) => { botOrders?.forgetPerson(person); forgetNotificationReader(person); }) : null, store: () => store, newestMessageId: (threadId) => readCursor(threadId).lastReadMessageId, publicGroupState, broadcast, shared: (threadId) => teamHost.privateTo(threadId) === null, wireBot: (botId) => { const bot = store.bot(botId); return bot ? wireBot(bot) : null; } });-const botOrders = CLOUD_TEAM ? createPersonBotOrder(DATA_DIR) : null;+const botOrders = CLOUD_TEAM ? createPersonBotOrder(DATA_DIR) : null; const teamRoutines = createTeamRoutines({ team: Boolean(CLOUD_TEAM), privateTo: teamHost.privateTo, task: (botId, threadId) => store.taskByThread(botId, threadId), routines: () => routines, authors: cloudRoutineAuthors, withWriter: withRoutineWriter, ownBot: (botId) => { const person = store.bot(botId)?.defaultBot?.person; return person ? personKey({ id: "", email: person }) : null; }, tasks: (botId) => store.tasks(botId), threadRefusal: cloudThreadRefusal, openChat: (botId, title, person) => { const threadId = store.createTask(botId, title, false)?.threadId; if (threadId) threadStarters.set(threadId, person); return threadId; } });function actorKey(auth: RequestAuth & { kind: "session" }): string {return CLOUD_OWNER_KEY && auth.scopes.includes("admin") ? CLOUD_OWNER_KEY : personKey(auth.session);@@ -999,6 +999,7 @@ function cloudOwnerApplied(action: string, routineId: string | undefined, wasOwnfunction routineOpener(routineId: string): string {if (routineWriterInFlight) return routineWriterInFlight;const routine = routines?.listRoutines().find((candidate) => candidate.id === routineId);+ const team = routine ? teamRoutines.opener(routine) : null; if (team) return team;if (routine && CLOUD_OWNER_KEY && cloudRoutineAuthors?.authored(routineId, routine)) return CLOUD_OWNER_KEY;const writer = cloudRoutineAuthors?.writer(routineId);if (writer && CLOUD_OWNER_KEY && writer === CLOUD_OWNER_KEY) return CLOUD_OWNER_KEY;@@ -1136,7 +1137,7 @@ async function answeringCardAs(auth: RequestAuth, threadId: string, requestId: s}const { viewerFor, threadOwner, visibleTo, forgetVisibility, threadShown, subjectVisible, hiddenRoutineTarget, roomFeedsBot, settleRoomFloor } = createVisibilityHost({ store: () => store, routines: () => routines,- team: Boolean(CLOUD_TEAM), audiencesFor: (viewer) => { const audiences = teamHost.audiencesFor(viewer), person = audiences?.person; return audiences && person ? { ...audiences, ownTask: (task) => personRooms.taskForPerson(task, person) } : audiences; }, threadsReferencing }); if (CLOUD_TEAM) hideOthersSyncFolders(() => store.bots, threadShown); const notificationListed = notificationListedFor(threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined, CLOUD_TEAM ? (auth) => (auth.kind === "session" ? personKey(auth.session) : null) : undefined); const botAccess = createBotAccessHost({ visibleFor: (auth) => visibleTo(viewerFor(auth)), store: () => store, routines: () => routines, threadOwner, routineWriter: (id) => cloudRoutineAuthors?.writer(id) }), { levelOf } = botAccess; const accessRequests = createAccessRequests({ team: CLOUD_TEAM, store: () => store, people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, inbox: () => teamMessages.inbox, visibleTo, levelOf, writeAccess: (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access), record: (row, by) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: by, email: by } }) });+ team: Boolean(CLOUD_TEAM), audiencesFor: (viewer) => { const audiences = teamHost.audiencesFor(viewer), person = audiences?.person; return audiences && person ? { ...audiences, routineHome: teamRoutines.home, ownTask: (task) => personRooms.taskForPerson(task, person) } : audiences && { ...audiences, routineHome: teamRoutines.home }; }, threadsReferencing }); if (CLOUD_TEAM) hideOthersSyncFolders(() => store.bots, threadShown); const notificationListed = notificationListedFor(threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined, CLOUD_TEAM ? (auth) => (auth.kind === "session" ? personKey(auth.session) : null) : undefined); const botAccess = createBotAccessHost({ visibleFor: (auth) => visibleTo(viewerFor(auth)), store: () => store, routines: () => routines, threadOwner, routineWriter: (id) => cloudRoutineAuthors?.writer(id) }), { levelOf } = botAccess; const accessRequests = createAccessRequests({ team: CLOUD_TEAM, store: () => store, people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, inbox: () => teamMessages.inbox, visibleTo, levelOf, writeAccess: (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access), record: (row, by) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: by, email: by } }) });function recentWorkFilter(threadId: string): { include?: (threadId: string) => boolean; privateThread?: (threadId: string) => boolean } {const include = CLOUD_TEAM ? (id: string) => teamHost.readableFrom(threadId)(id) && outsideLineage.mayReach(id, threadId) : CLOUD_HOME ? cloudOwnerOnlyThread : () => true; return { include: (id) => !botApiThread(id) && include(id), ...(CLOUD_TEAM ? { privateThread: (id: string) => teamHost.privateTo(id) !== null } : {}) };@@ -2809,17 +2810,17 @@ const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusalForBot,ownerPerson: cloudProvenOwnerPerson, cardAnswerer: cloudCardAnswerer, activeRoutineRun: activeRoutineRunForThread, ownerStartedRun: (runId) => ownerStartedRoutineRuns.has(runId),routineRunIsOwners: cloudRoutineRunIsOwners, routines: () => routines, routineAuthors: cloudRoutineAuthors, lentPlatform: () => sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform,memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true, lifts: () => lendingLifts, handedSince: (threadId, since) => handedInSince(coordinator.all(), threadId, since) });-const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) }); const lendingLifts = lendingMemory ? createLendingLifts({ store, stopped: (threadId) => directRequestOwners.get(threadId)?.stopped === true, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn, notify, language: (threadId) => threadLanguage(threadId), device: () => deviceWord(sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform), decide: (row) => appendDecision(DATA_DIR, row), words: changedWords, ownersAnswer: (card) => cloudProvenOwnerPerson(cloudCardAnswerer(card)), memory: { info: (botId) => lendingMemory.reviewInfo(botId), accept: (botId, token) => lendingMemory.review(botId, foreignTurnRunning(botId), token).ok } }) : null;+const teamAway = createTeamAwayHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, here: (person) => [...sseClients].some((client) => client.ask.person === person), people: () => teamOwners.people?.everyone() ?? [], language: personLanguages.forLine, audienceOf: teamHost.audienceOf, store, unseen: (person) => teamMessages.inbox.unseen(person), readUpTo: (key, person) => personRooms.reads?.readUpTo(key, person), session: (auth) => (auth.kind === "session" ? auth.session : null) }); const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) }); const lendingLifts = lendingMemory ? createLendingLifts({ store, stopped: (threadId) => directRequestOwners.get(threadId)?.stopped === true, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn, notify, language: (threadId) => threadLanguage(threadId), device: () => deviceWord(sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform), decide: (row) => appendDecision(DATA_DIR, row), words: changedWords, ownersAnswer: (card) => cloudProvenOwnerPerson(cloudCardAnswerer(card)), memory: { info: (botId) => lendingMemory.reviewInfo(botId), accept: (botId, token) => lendingMemory.review(botId, foreignTurnRunning(botId), token).ok } }) : null;const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, lending: sharedComputers, principal: CLOUD_HOME_LENDER, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn,refusal: (turn) => sharedComputerPrincipal(turn) ? null : cloudLendingRefusalForBot(turn) ?? "This conversation can't use your computer.", request: (threadId) => directRequestOwners.get(threadId), active: (turn) => internalCapabilityIsActive(turn as InternalCapability) }) : null;const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersonStop({store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, stopping: (botId, threadId) => idleThreads.stopping(botId, threadId), clearUnattended,- stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)), working: (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId), asking: (threadId) => coordinator.awaitingAnswer(threadId) || Boolean(openPersonCard(threadId)), language: threadLanguage,-}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });+ stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId, by) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId), by), working: (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId), asking: (threadId) => coordinator.awaitingAnswer(threadId) || Boolean(openPersonCard(threadId)), language: threadLanguage, stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by),+}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, delivered: (item, delivery) => teamAway.delivered(item, delivery), changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null, opened: (made) => void mausbotOwnChat.claim(made) }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });-const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });+const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,log: line => console.warn(line) });@@ -2837,7 +2838,7 @@ const phones = createPhones({active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const botLimit = createBotLimit({ starter: () => cloudPlanTier.starter(), bots: () => store.bots }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, botName: (botId) => store.bot(botId)?.name, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.-const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,+const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });@@ -2904,7 +2905,7 @@ const wireTask = (task: TaskRecord, botModel: ModelSelection, awaiting = threads// Snoozes heal on read against the server clock; the 0 sentinel ("until new activity") survives reads.const { snoozedUntil, ...base } = toWireTask(task, botModel);const keepWarm = cacheKeepWarmStatus(task.threadId);- const coordinated = { ...base, waitingForTeammates: awaiting.has(task.threadId) && !task.busy, ...(keepWarm ? { cacheKeepWarm: keepWarm } : {}), ...(teamHost.ownTurn(task.threadId) ? { private: true as const } : {}), ...teamMessages.inbox.wire(task.threadId) };+ const coordinated = { ...base, waitingForTeammates: awaiting.has(task.threadId) && !task.busy, ...(keepWarm ? { cacheKeepWarm: keepWarm } : {}), ...(teamHost.ownTurn(task.threadId) ? { private: true as const } : {}), ...teamMessages.inbox.wire(task.threadId), ...runOwners.askedBy(task) };const asleep = snoozedUntil === 0 || (snoozedUntil !== undefined && snoozedUntil > Date.now());return asleep ? { ...coordinated, snoozedUntil } : coordinated;};@@ -3004,7 +3005,7 @@ function previewSystemPrompt(bot: BotRecord) {};}-async function botOverview(bot: BotRecord): Promise<BotOverview> {+async function botOverview(bot: BotRecord, shown: { routine(routine: Routine): boolean; run(run: RoutineRun): boolean } = { routine: () => true, run: () => true }): Promise<BotOverview> {const connectedApps = await connectedAppsFacts(composio.configured(cfg),composio.connectorAvailability(cfg),@@ -3034,7 +3035,7 @@ async function botOverview(bot: BotRecord): Promise<BotOverview> {managedSections: bot.managedSections,},routines: routines!.listRoutines()- .filter((routine) => routine.botId === bot.id)+ .filter((routine) => routine.botId === bot.id && shown.routine(routine)).map((routine) => ({id: routine.id,name: routine.name,@@ -3043,7 +3044,7 @@ async function botOverview(bot: BotRecord): Promise<BotOverview> {nextRunAt: routine.nextRunAt,})),runs: routines!.listRuns()- .filter((run) => run.botId === bot.id)+ .filter((run) => run.botId === bot.id && shown.run(run)).map((run) => ({routineId: run.routineId,status: run.status,@@ -3508,7 +3509,7 @@ const publicBot = (bot: NonNullable<ReturnType<typeof store.bot>>) => {const wired = wireBot(bot), tasks = store.tasks(bot.id);return { ...wired, ...messagePage(bot.threadId, DEFAULT_PAGE), tasks: tasks === bot.tasks && wired.tasks ? wired.tasks : tasks.map((task) => wireTask(task, bot.modelSelection)) };};-const publicBotQueuedMessages = () => queuedSteerSnapshot((botId, threadId) => Boolean(store.taskByThread(botId, threadId)), waitWords.queued);+const publicBotQueuedMessages = () => queuedSteerSnapshot((botId, threadId) => Boolean(store.taskByThread(botId, threadId)), waitWords.queued, runOwners.shownSender);type GroupTurnOperation = {id: string;@@ -3750,7 +3751,7 @@ const channelTaskBlocked = (group: GroupRecord) =>// Load coordination state before registering store listeners or recovering routines: recovery can emit room changes synchronously.const groupQueues = new Map<string, Promise<void>>();-const { roomRootProblem, roomHandoffProblem, roomHandoffTarget, roomSetupPending, roomTalks, laneRoomThread } = createRoomAccess({ store, privateTo: (threadId) => teamHost.privateTo(threadId), lookedAfterBy: (bot) => (CLOUD_TEAM ? lookedAfterBy(bot, teamHost.personName) : null) });+const personalReach = createPersonalReach({ privateTo: (threadId) => teamHost.privateTo(threadId), personKey: (email) => personKey({ id: "", email }), personBehind: (botId, threadId) => teammatePrompts.personBehind(botId, threadId), actingFor: (threadId, generation) => actingPeople.requester(threadId, generation), level: (bot, email) => { const role = (teamOwners.people?.list() ?? []).find((one) => one.email === email)?.role; return visibleTo(role === "owner" || role === "admin" ? { kind: "all", email } : { kind: "member", email }).level(bot.id); } }); const { roomRootProblem, roomHandoffProblem, roomHandoffTarget, roomSetupPending, roomTalks, laneRoomThread } = createRoomAccess({ store, privateTo: (threadId) => teamHost.privateTo(threadId), personalReach: () => personalReach, lookedAfterBy: (bot) => (CLOUD_TEAM ? lookedAfterBy(bot, teamHost.personName) : null) });const roomJobs = createRoomJobs({ store, coordinator: { all: () => coordinator.all() }, cfg, laneRoomThread,operations: groupId => groupTurnOperations.get(groupId) ?? [], speakerOf: threadId => groupSpeakers.get(threadId)?.botId });@@ -4952,7 +4953,7 @@ const QUIET_TURN_NEWS: ReadonlySet<Notification["kind"]> = new Set(["done", "turfunction notify(notification: Notification | null, how?: { routine?: boolean }) {if (notification && QUIET_TURN_NEWS.has(notification.kind) && quietTurnThreads.has(notification.threadId)) return;- const routed = notification && teamMessages.route(notification, how); if (routed) broadcast({ kind: "notify", notification: logNotification(routed) });+ const routed = notification && teamMessages.route(notification, how); if (routed) broadcast({ kind: "notify", notification: logNotification(routed) }); teamAway.notified(notification, routed, how);}const roomTurnLevels = createRoomTurnLevels();@@ -6380,7 +6381,7 @@ bus.subscribe((event: RuntimeEvent) => {const byPerson = personStops.stopped(event.threadId, turnId);if (!byPerson) lastReply.delete(event.threadId);stoppedTurns.set(event.threadId, turnId ?? liveTurnByThread.get(event.threadId));- const row = stoppedTurnRow(store.messagesFor(event.threadId), turnId, byPerson);+ const row = stoppedTurnRow(store.messagesFor(event.threadId), turnId, byPerson, personStops.stopper(event.threadId));if (row) pushMessage(row);};const pushAssistantText = (text: string, turnId: string | undefined) => {@@ -7105,7 +7106,7 @@ const repeats = createLoopGuard({bus.subscribe((event: RuntimeEvent) => { if (!shouldIgnoreProviderEvent(event)) repeats.onEvent(event); });const personFirst = createPersonFirst({ firstMs: Number(process.env.OMB_PERSON_FIRST_MS) || undefined, waiting: (threadId) => watchdog.waiting(threadId) || activeRoutineRunForThread(threadId) !== null,stop: async (threadId, line) => { const bot = store.botByThread(threadId); if (!bot) return; store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: line, ok: true } }); turnStops.stopping(threadId, liveTurnByThread.get(threadId), line); await interruptDirectThread(bot.id, threadId, line); } });-bus.subscribe((event: RuntimeEvent) => { if (!shouldIgnoreProviderEvent(event)) personFirst.onEvent(event); });+bus.subscribe((event: RuntimeEvent) => { if (!shouldIgnoreProviderEvent(event)) personFirst.onEvent(event); }); const runOwners = createRunOwners({ shared: (threadId) => CLOUD_TEAM !== null && audienceMember(teamHost.audienceOf(threadId)) === null, directRequest: (threadId) => directRequestOwners.get(threadId), roomRequestMessageId: (threadId) => [...(groupTurnOperations.get(store.groupByThread(threadId)?.id ?? "") ?? [])].find((operation) => operation.threadId === threadId && !operation.cancelled && operation.requestMessageId)?.requestMessageId, isRoom: (threadId) => Boolean(store.groupByThread(threadId)), messages: (threadId) => store.messagesFor(threadId), personName: (person) => teamHost.personName(person), language: threadLanguage }), runActor = (auth: RequestAuth) => runActorOf(auth, actorKey);// A first reply that never comes gets one notice with a way out (server/first-reply-rescue.ts), on listeners of their own.const firstReplyRescue = createFirstReplyRescue({ store, botForThread, speaker: (threadId) => groupSpeakers.get(threadId), runningEngine: (threadId) => runningTurnEngines.get(threadId)?.instanceId,engineName: (instanceId) => engineName(instanceId), quiet: (threadId) => isInternalTurn(threadId) || activeRoutineRunForThread(threadId) !== null,@@ -7208,7 +7209,7 @@ async function acceptDirectSend(input: DirectSendInput,guardedStart?: (currentAtStart: BotRecord) => Promise<DirectSendReceipt>,): Promise<DirectSendReceipt> {- const { botId, threadId, text, sendId, replyTo, sender, trigger, via, callId, dataContext, personPresent, app, followUp, mentions } = input;+ const { botId, threadId, text, sendId, replyTo, sender, trigger, via, callId, dataContext, personPresent, app, followUp, mentions, admin } = input;const refused = directSendRefusal(botId, threadId);if (refused) throw refused;return sendSequencer.run(@@ -7259,10 +7260,10 @@ async function acceptDirectSend(if (guardedStart) return guardedStart(currentAtStart);- const typedStop = await stopOnTypedCommand({ botId, threadId, text, trigger, personPresent, fromApp: Boolean(app), busy: currentAtStart.busy === true, row: { replyToId: replyTo?.id, sendId, sender, ...spokenLineFields(via, callId) } });+ const typedStop = await stopOnTypedCommand({ botId, threadId, text, trigger, personPresent, fromApp: Boolean(app), busy: currentAtStart.busy === true, row: { replyToId: replyTo?.id, sendId, sender, ...spokenLineFields(via, callId) }, by: { ...(sender?.id ? { person: sender.id } : {}), admin: admin === true } });if (typedStop) return typedStop;if (currentAtStart.busy) {- const personsOwn = personPresent && !app && (trigger.kind === "user" || trigger.kind === "owner"), queuedPrompt = (app?.context ?? "") + personPrompt(threadId, sender, promptWithReply(promptWithDataContext(text, dataContext), replyTo, userNameFor(threadId)));+ const personsOwn = personPresent && !app && (trigger.kind === "user" || trigger.kind === "owner"), queuedPrompt = (app?.context ?? "") + personPrompt(threadId, sender, promptWithReply(promptWithDataContext(text, dataContext), replyTo, userNameFor(threadId))); if (runOwners.arrival(threadId, sender, personPresent && Boolean(sender?.id)) === "queue") return { ok: true as const, queued: true as const, threadId, queueId: queueSteeredMessage(currentAtStart.id, threadId, text, { replyToId: replyTo?.id, sendId, dataContext, fromApp: app?.fromApp, mentions, prompt: queuedPrompt, sender, trigger, via, callId, first: personPresent && Boolean(sender?.id) }).id };const instance = runningTurnInstance(currentAtStart, threadId);let steered: SteerOutcome = "refused";const steerInput = extractTurnImages(text);@@ -7314,7 +7315,7 @@ async function acceptDirectSend(store.setTaskAskedAt(botId, threadId, message.at);handoffs.steered(threadId, steerTarget, instance?.instanceId, message.id);signInSettle.answerInChat(botId, threadId);- if (personsOwn) personFirst.wait(threadId, { requeue: (note) => void queueSteeredMessage(current.id, threadId, text, { prompt: note ? `${queuedPrompt}\n\n${note}` : queuedPrompt, rowId: message.id, first: true, queuedAt: message.at, replyToId: replyTo?.id, dataContext, sender, trigger, via, callId, mentions }) });+ if (personsOwn) personFirst.wait(threadId, { requeue: (note) => void queueSteeredMessage(current.id, threadId, text, { prompt: note ? `${queuedPrompt}\n\n${note}` : queuedPrompt, rowId: message.id, first: true, queuedAt: message.at, replyToId: replyTo?.id, dataContext, sender, trigger, via, callId, mentions, aheadOfOthers: runOwners.askerFirst(threadId) }) });return { ok: true as const, steered: true as const, threadId, message };}if (!current.busy) {@@ -7329,7 +7330,7 @@ async function acceptDirectSend(trigger,via,callId,- first: personsOwn || chose === "restart",+ first: personsOwn || chose === "restart", aheadOfOthers: runOwners.askerFirst(threadId),});if (personsOwn && !chose) personFirst.wait(threadId, {});if (chose === "restart") await restartForPerson(botId, threadId, trigger);@@ -8255,7 +8256,7 @@ async function beginTurn(else vpsUnavailableNote = ` This bot's VPS computer is unavailable this turn (${autoVpsProblem}), so no computer is mounted. Work that needs no screen can go ahead. If the request needs the VPS desktop, do not claim to have used it: say it is unavailable${hint ? ` and what the person can do: ${hint}` : "."}`;}// One reachability rule: a bot is never told about a peer that coordinate_bots would refuse.- const sectionPeers = reachablePeers(store.bots, bot);+ const sectionPeers = personalReach.peers(store.bots, bot, threadId);if (agentsMounted) {integrations.agents = agentsIntegration(bot.id, threadId, commsDepth, skillAuthoring, dispatchClaimId, opts?.coordination?.id, worksInWorkspace, opts?.automationSource !== undefined);}@@ -8267,11 +8268,11 @@ async function beginTurn(? mentionedBots(withoutPersonTags(providerText, [...personTagNames(cfg.profile?.name), ...teamMessages.people().flatMap((one) => one.tags)],store.bots.filter((one) => !one.hidden).map((one) => one.name)), sectionPeers, opts?.mentions): [];- const coordinationPrompt = chiefLevel(bot)- ? chiefOfStaffSystemPrompt(bot.id, store.bots, Boolean(integrations.agents))+ const coordinationPrompt = (chiefLevel(bot)+ ? chiefOfStaffSystemPrompt(bot.id, store.bots, Boolean(integrations.agents), (peer) => personalReach.listed(bot, peer, threadId)): integrations.agents && sectionPeers.length > 0? peerRosterSystemPrompt(sectionPeers, bot)- : "";+ : "") + (integrations.agents ? personalReach.prompt(bot, threadId, sectionPeers) : "");const credentialPrompt = integrations.agents ? CREDENTIAL_PROMPT + savedSecretsPrompt(botLogins.secretNamesFor(bot.id)) + THREADS_PROMPT + WIDGET_PROMPT : "";const routinePrompt = integrations.agents ? TRIGGER_PROMPT : "";const profilePrompt = integrations.agents ? PROFILE_PROMPT : "";@@ -8769,7 +8770,7 @@ const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failoverreturn Boolean(checked?.ok && store.switchTaskModel(botId, threadId, checked.selection, false, false, { ...hostedModels?.resetTask(to, checked.selection), rewound: true }));} });const automationDestinations = createAutomationDestinations({ store, mainThread: botMainThread, runs: () => routines?.listRuns() ?? [],- cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: routineOpener, reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person), outside: (threadId) => outsideLineage.mark(threadId) } : null });+ cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: (id, routine) => (routine && teamRoutines.opener(routine)) || routineOpener(id), reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person), outside: (threadId) => outsideLineage.mark(threadId) } : null });const routineModelChecks: RoutineModelChecks = { check: (raw) => checkedModelSelection(raw), bot: (botId) => store.bot(botId), engineSwitchNeedsAsk };routines = new RoutineManager({emit: broadcast, limitResetAt: (engine) => limitClock.resetAt(engine), checks: proactive.checks,@@ -8797,11 +8798,9 @@ routines = new RoutineManager({return groupIsWorking(group) || coordinator.busy ? "busy" : "ready";},createTask: (botId, title, run) => {- const task = store.createTask(botId, title, false, undefined, undefined, undefined, routineThreadModel(run && routines?.listRoutines().find((routine) => routine.id === run.routineId), routineModelChecks));// On a Cloud home the routine's writer opens a run's conversation; a webhook run is the owner's, but its payload never reaches the lent Mac.- if (task && CLOUD_HOME && run) {- threadStarters.set(task.threadId, run.triggerSource === "webhook" ? CLOUD_OWNER_KEY! : routineOpener(run.routineId));- }+ const task = store.createTask(botId, title, false, undefined, undefined, undefined, routineThreadModel(run && routines?.listRoutines().find((routine) => routine.id === run.routineId), routineModelChecks), undefined,+ CLOUD_HOME && run ? (created) => threadStarters.set(created.threadId, run.triggerSource === "webhook" ? CLOUD_OWNER_KEY! : routineOpener(run.routineId)) : undefined);if (task && run?.triggerSource === "webhook") outsideLineage.mark(task.threadId);return task;},@@ -8819,7 +8818,7 @@ routines = new RoutineManager({const task = store.taskByThread(botId, threadId);return Boolean(bot && !bot.hidden && task && !task.routineRunId);},- resolveResultsThread: (routine, forceNew) => automationDestinations.routine(routine, forceNew),+ resolveResultsThread: (routine, forceNew) => automationDestinations.routine(routine, forceNew || teamRoutines.reportsElsewhere(routine)),eventResultsThread: (event) => automationDestinations.event(event),frozenResultsThread: (botId, threadId) => wasOldestThread(store.tasks(botId), threadId) && !cloudGuestOpened(threadId),discardResultsThread: (botId, threadId) => {@@ -11810,7 +11809,8 @@ function configStatus() {/** `session`: who is asking. On a Team Cloud the profile is theirs alone, never the server's. */function configForAccess(status: ReturnType<typeof configStatus>, admin: boolean, session?: SessionRecord | null) {const profile: MemberProfile = CLOUD_TEAM ? (session ? teamHost.memberProfile(session) : NOBODY_PROFILE) : status.profile;- if (admin) return CLOUD_TEAM ? { ...status, profile } : status;+ const onboarding = CLOUD_TEAM ? teamOnboarding(status.onboarding, session, teamWelcome) : status.onboarding;+ if (admin) return CLOUD_TEAM ? { ...status, profile, onboarding } : status;// Client sessions get configured-or-not only: no SSH alias, email, browser partition id or sign-in list.return {...withoutKeyHints(status),@@ -11818,7 +11818,7 @@ function configForAccess(status: ReturnType<typeof configStatus>, admin: booleansignIn: { admins: [], members: [] }, live: liveSettingsForClient(status.live), everyBotRules: undefined,vps: { configured: status.vps.configured, sshAlias: "" },opencodeGo: { configured: status.opencodeGo.configured, providerKeys: [] },- profile: CLOUD_TEAM ? profile : { name: profile.name, email: "", ...(profile.avatarUrl ? { avatarUrl: profile.avatarUrl } : {}) },+ ...(CLOUD_TEAM ? { onboarding } : {}), profile: CLOUD_TEAM ? profile : { name: profile.name, email: "", ...(profile.avatarUrl ? { avatarUrl: profile.avatarUrl } : {}) },browserProfiles: status.browserProfiles.map((profile) => Object.fromEntries(Object.entries(profile).filter(([key]) => key !== "partitionId"))),};}@@ -12097,7 +12097,7 @@ ROUTES.push(createBotMessageRoutes({routines: () => routines,fromPhone: phones.fromPhone, notePhoneSend: phones.noteSend,desktopManaged: DESKTOP_MANAGED, cloudHome: Boolean(CLOUD_HOME), DirectSendRefused,- acceptDirectSend, directSendRefusal, startTurn, usageTriggerFor, messageSender, cloudGuestSendRefusal, cloudThreadRefusal, resolveAccessRequest: (threadId, requestId, behavior, message) => lendingLifts?.resolve(threadId, requestId, behavior) ?? accessRequests.resolve(threadId, requestId, behavior, message), relayRefusal: CLOUD_TEAM ? (bot, email) => relayedSendRefusal(bot, email, Boolean(email && teamOwners.people?.list().some((one) => one.email === email && one.role !== "member"))) : undefined,+ acceptDirectSend, directSendRefusal, startTurn, usageTriggerFor, messageSender, cloudGuestSendRefusal, cloudThreadRefusal, runOwners, runActor, resolveAccessRequest: (threadId, requestId, behavior, message) => lendingLifts?.resolve(threadId, requestId, behavior) ?? accessRequests.resolve(threadId, requestId, behavior, message), relayRefusal: CLOUD_TEAM ? (bot, email) => relayedSendRefusal(bot, email, Boolean(email && teamOwners.people?.list().some((one) => one.email === email && one.role !== "member"))) : undefined,noAiRefusal: noAiNotice.refusal, cardAnswerRefusal, commandRememberRefusal, requestBehavior, requestedTaskBot, botForThread, threadBusy,botAtThreadCapacity, parksBehindCoordination, activeGroupTurnForBot, runningTurnInstance, engineSteersImages, resolveReplyTarget,turnSelection, policyModelRefusal, clearUnattended, drainQueuedSends, answeringCardAs, resolveAndSendTrust, resolveAndSendTeamSetup, resolveAndSendMcp,@@ -12126,7 +12126,7 @@ ROUTES.push(createThreadRoutes({companionMutationToken: () => companionMutationToken,cliOwnerToken: () => cliOwnerToken,pageSize, messagePage, messageWindow, publicBotQueuedMessages, publicGroupState, wireBot,- botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => { const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name }); if (own) void mausbotOwnChat.claim(own); return own; } : undefined,+ botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => { const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name, opened: (made) => void mausbotOwnChat.claim(made) }); if (own) void mausbotOwnChat.claim(own); return own; } : undefined,uploads: uploadsFor(createUploadOwners(DATA_DIR), Boolean(CLOUD_TEAM)),attachmentInUse: (name) => threadsReferencing(name).length > 0 || store.bots.some((bot) => bot.avatarUrl === `/api/attachments/${name}`),keptAttachments: CLOUD_TEAM ? undefined : () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles,@@ -12201,7 +12201,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(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) }),+ROUTES.push(teamPresence.routes, createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) }));ROUTES.push(createRoomHoldRoutes({group: (id) => store.group(id),@@ -12223,7 +12223,7 @@ ROUTES.push(createGroupRoutes({groupFor: personRooms.groupForAuth,}));ROUTES.push(createChannelRoutes({- store, threadRead: teamMessages.seen,+ store, threadRead: teamMessages.seen, runOwners, runActor,personMarkRoom: personRooms.personMarkRoom,groupFor: personRooms.groupForAuth,cfg,@@ -12298,7 +12298,7 @@ const taskRoutes = createTaskRoutes({revokeInternalCapabilitiesForThread,stagedSkillCleanupsForThread,rejectDeletedThreadSkillStages,-}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { teamConnections.forgetPerson(person); connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); } }) : null;+}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { teamConnections.forgetPerson(person); connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null;ROUTES.push(createTeamRoutes({store,cfg,@@ -12312,7 +12312,7 @@ ROUTES.push(createTeamRoutes({defaultSelection,defaultsPresetFor,packageImportDeps,- starterNotes, threadShown,+ starterNotes, threadShown, routineShown: (auth) => (routine) => routineVisible(routine, visibleTo(viewerFor(auth))),...skillExport(skillsHost),}));ROUTES.push(createBrowserSiteRoutes({@@ -12380,7 +12380,7 @@ const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persicomputerProviderConfigTransitions, managedBoatOwners, providerOperationConflict, perBotLocalVmCountForModeChange,checkedModelSelection, policyModelRefusal, browserSessionSpec, configStatus,configForAccess: (status, auth) => configForAccess(status as ReturnType<typeof configStatus>, auth.scopes.includes("admin"), auth.kind === "session" ? auth.session : null),- ...(CLOUD_TEAM ? { ownProfile: (auth: RequestAuth, profile: { name?: string; avatarUrl?: string; aboutMe?: string }) => auth.kind === "session" ? (teamHost.saveMemberProfile(auth.session, profile), true) : false } : {}),+ ...(CLOUD_TEAM ? { ownProfile: (auth: RequestAuth, profile: { name?: string; avatarUrl?: string; aboutMe?: string }) => auth.kind === "session" ? (teamHost.saveMemberProfile(auth.session, profile), true) : false, ownHints: (auth: RequestAuth, hints: string[]) => auth.kind === "session" ? (teamWelcome.save(personKey(auth.session), { hints }), true) : false } : {}),resyncOpenCodeProviderKeys, revokeEngineCapabilities, reloadProviders, broadcast, drainQueuedSends, postiz,}));ROUTES.push(createInstanceRoutes({@@ -12473,7 +12473,7 @@ const liveCalls = new LiveCallController({trigger: usageTriggerFor(auth),via: "call",callId,- personPresent: true,+ personPresent: true, admin: runActor(auth).admin,});if ("queued" in receipt) return { kind: "queued", queueId: receipt.queueId };return { kind: receipt.steered ? "steered" : "started", messageId: receipt.message.id };@@ -12621,7 +12621,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (browser && body?.preview === true) {// Shown before the person continues; redeems nothing.const preview = sessions.previewBrowserSignIn(code);- return preview ? json(res, 200, preview) : json(res, 401, userError("serverError.pair.linkExpired"));+ return preview ? json(res, 200, { ...preview, ...(CLOUD_TEAM ? { team: CLOUD_TEAM.name } : {}) }) : json(res, 401, userError("serverError.pair.linkExpired"));}if (browser && !wantsCookie) return json(res, 400, { error: "a browser sign-in sets this browser's cookie; send cookie: true" });const result = sessions.exchange({ code, label, attemptId, browser, source: requestSource(req), fallbackLabel: labelFromUserAgent(req.headers["user-agent"]) });@@ -12741,7 +12741,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {...(auth.session.email ? { email: auth.session.email } : {}),...(auth.session.owner ? { owner: auth.session.owner } : {}),...(HOSTED_WORKSPACE ? { hosted: true } : {}),- ...(CLOUD_HOME ? { cloudHome: true } : {}), ...(ownHome.owner(auth) ? { own: true, ...(ownerLends() ? { lending: OWNER_LENDING } : {}) } : {}), ...(teamHost.sessionInfo(auth.session) ? { team: teamHost.sessionInfo(auth.session), openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),+ ...(CLOUD_HOME ? { cloudHome: true } : {}), ...teamSignInFor(CLOUD_HOME, auth.session), ...(ownHome.owner(auth) ? { own: true, ...(ownerLends() ? { lending: OWNER_LENDING } : {}) } : {}), ...(teamHost.sessionInfo(auth.session) ? { team: teamHost.sessionInfo(auth.session), openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),...(CLOUD_PERSONAL && !cloudOwnerSession(auth) ? { cloudGuest: true, openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),...(reactorFor(auth).by !== "user" ? { reactor: reactorFor(auth).by } : {}),},@@ -13207,7 +13207,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}if (method === "GET" && path === "/api/internal/agents") {const sender = internalSender;- const bots = reachablePeers(store.bots, sender)+ const bots = personalReach.peers(store.bots, sender, internalCapability.threadId).map((b) => {const status = peerStatus(b.activity, b.busy);return {@@ -13338,7 +13338,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}return json(res, 200, { rooms: rooms.slice(0, 50), unpostable: unpostable.slice(0, 50) });}- const triggerContext = { from: internalSender, threadId: internalCapability.threadId, ownsThread: (botId: string, threadId: string) => Boolean(connectorThread(botId, threadId)), guestDriven: cloudGuestDriven(internalCapability.threadId), outsideDriven: () => outsideDrivenThread(internalCapability.threadId), canCommit: () => internalCapabilityIsActive(internalCapability) };+ const triggerContext = { from: internalSender, threadId: internalCapability.threadId, ownsThread: (botId: string, threadId: string) => Boolean(connectorThread(botId, threadId)), guestDriven: cloudGuestDriven(internalCapability.threadId), outsideDriven: () => outsideDrivenThread(internalCapability.threadId), canCommit: () => internalCapabilityIsActive(internalCapability), routineShown: (routine: Routine) => teamRoutines.inTurn(routine, internalCapability.threadId) };if (await dispatchRoutes([appTriggers.internalRoutes(triggerContext)], { req, res, url, path, method, auth, json, readBody })) return;if (method === "POST" && path === "/api/internal/trigger-requests") {const from = internalSender;@@ -13347,6 +13347,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (!owner) return json(res, 403, { error: "source conversation does not belong to sender" });const request = parseTriggerRequest(await readInternalBody(), (id) => routines!.listRoutines().some((routine) => routine.id === id) ? "schedule" : appTriggers.isApp(id) ? "app" : "webhook");if (!request.ok) return json(res, 400, { error: request.error });+ const hiddenTrigger = teamRoutines.hiddenTrigger(request, fromThreadId); if (hiddenTrigger) return json(res, 404, { error: hiddenTrigger });const target = triggerTarget(from, request.forBotId, (id) => store.bot(id));if ("error" in target) return json(res, target.status, { error: target.error });const forBot = target.forBot;@@ -13713,7 +13714,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (destination && destination.id !== source?.id && !outsideLineage.mayReach(address.threadId, destination.threadId)) return refuse(403, OUTSIDE_STAYS_HERE);const botIds: string[] = [];for (const raw of call.botIds) {- const resolved = resolveTeammate(store.bots, internalSender, raw, placesElsewhere.explain, (bot) => (CLOUD_TEAM ? lookedAfterBy(bot, teamHost.personName) : null));+ const resolved = resolveTeammate(store.bots, internalSender, raw, placesElsewhere.explain, (bot) => (CLOUD_TEAM ? lookedAfterBy(bot, teamHost.personName) : null), { reaches: (bot) => personalReach.listed(internalSender, bot, address.threadId), hides: (bot) => personalReach.hides(internalSender, bot), refusal: (bot) => personalReach.refusal(internalSender, bot, address.threadId) });if ("error" in resolved) return refuse(403, resolved.error);botIds.push(resolved.id);}@@ -13734,7 +13735,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {target.botId === internalSender.id && !toSelf ? "Choose a teammate, not yourself": !addressed ? `No bot with id "${target.botId}" — call list_bots and copy the exact id from the result`: addressed.hidden ? `The bot with id "${target.botId}" is no longer available — call list_bots for the ones you can reach`- : roomHandoffProblem(target, address);+ : roomHandoffProblem(target, address) ?? personalReach.handOnProblem(internalSender, addressed, address.threadId, internalCapability.generation);if (eligibility) return refuse(403, eligibility);}const requestBatchKey = destination ? randomUUID() : undefined, handOnFor = CLOUD_TEAM ? teamConnections.handOnFor(internalCapability.threadId, internalCapability.generation) : null;@@ -13759,7 +13760,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const recipient = store.bot(target.botId);if (!recipient) throw new Error("The recipient no longer exists");// Work a person's request hands on opens in the receiving bot's chat with them when it may use their own apps.- const opener = (room ? null : handOnFor) ?? openerFrom(address.threadId);+ const opener = (room ? null : handOnFor) ?? openerFrom(address.threadId); if (!room) personalReach.checkHandOn(internalSender, recipient, address.threadId, opener, call.answers ? { threadId: coordinator.node(call.answers)?.threadId } : undefined);// A Chief answers, for the person, the question a teammate it manages waits on in a thread the Chief did not open.let lends = mode === "work" && handsOnLending(internalCapability); const forPerson = EXTERNAL || room || fresh || call.answers || mode !== "work" || call.thread === "standing" || !teammatePrompts.actsForPerson(internalSender, internalCapability.threadId) || !canManage(internalSender, recipient) || !threadReadableFrom(internalCapability.threadId)(call.thread) || !asksActingPerson(internalCapability.threadId, store.groupByThread(internalCapability.threadId) ? internalCapability.generation : undefined)(call.thread, recipient.id) ? undefined : await questionRouting.answerForPerson({ lends, sender: internalSender, senderThreadId: address.threadId, target: recipient, threadId: call.thread, message: call.message });if (forPerson) { if (forPerson.outcome === "failed") refused.push(forPerson.detail); else answeredForPerson.add(forPerson); receipts.push(forPerson); continue; }@@ -13774,10 +13775,10 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (lane?.created) createdThread = lane.threadId;if (lane) delegatedLevel.apply(internalSender, internalCapability.threadId, internalCapability.roomHandoffId ?? generation, recipient, lane.threadId);if (!room) {- const opened = { botId: internalSender.id, name: internalSender.name, threadId: address.threadId, at: Date.now(), ...(lends ? { forOwner: true as const } : {}) };+ const opened = { botId: internalSender.id, name: internalSender.name, threadId: address.threadId, at: Date.now(), ...(lends ? { forOwner: true as const } : {}) }, startedFor = (created: { threadId: string }) => threadStarters.set(created.threadId, opener);const task = continued ?? (fresh- ? store.createTask(target.botId, call.title ?? (call.message.replace(/\s+/g, " ").trim().slice(0, 60) || `From ${internalSender.name}`), false, call.projectId, opened, call.ownThread?.approvalMode, call.ownThread?.modelSelection, folder.cwd)- : store.createTask(target.botId, `@${internalSender.name} · work`, false, undefined, { ...opened, kind: "work" }, undefined, undefined, folder.cwd));+ ? store.createTask(target.botId, call.title ?? (call.message.replace(/\s+/g, " ").trim().slice(0, 60) || `From ${internalSender.name}`), false, call.projectId, opened, call.ownThread?.approvalMode, call.ownThread?.modelSelection, folder.cwd, startedFor)+ : store.createTask(target.botId, `@${internalSender.name} · work`, false, undefined, { ...opened, kind: "work" }, undefined, undefined, folder.cwd, startedFor));if (!task) throw new Error("The recipient no longer exists");target.threadId = task.threadId;if (!continued) createdThread = task.threadId;@@ -13854,7 +13855,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {});// Only this conversation's own tree; a row of another conversation is refused.const owned = (a: Row) => coordinator.node(a.rootId)?.threadId === fromThreadId;- const reachable = (a: Row) => { const target = store.bot(a.assignee.botId); return !target || target.id === internalSender.id || canReach(internalSender, target); };+ const reachable = (a: Row) => { const target = store.bot(a.assignee.botId); return !target || target.id === internalSender.id || canReach(internalSender, target) || personalReach.reaches(internalSender, target, fromThreadId); };if (!id) {const outstanding = coordinator.outstandingFor(fromThreadId).flatMap(n => { const row = coordinator.status(n.id)?.assignment; return row && reachable(row) ? [shape(row)] : []; });return json(res, 200, { outstanding });@@ -13923,7 +13924,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {.map(b => ({ id: b!.id, name: b!.name, title: b!.title, busy: b!.busy })),})).filter(g => g.members.length);return json(res, 200, { currentRoom: source ? { id: source.id, name: source.name, workingFolder: source.cwd || null } : null,- bots: reachablePeers(store.bots, internalSender).map(bot => ({ id: bot.id, name: bot.name, title: bot.title, section: bot.section, busy: bot.busy })),+ bots: personalReach.peers(store.bots, internalSender, internalCapability.threadId).map(bot => ({ id: bot.id, name: bot.name, title: bot.title, section: bot.section, busy: bot.busy })),rooms, note: "Each bot uses its own environment and permissions. Files are not transferred: pass absolute paths only when accessible to the recipient, otherwise pass the content." });}if (method === "POST" && path === "/api/internal/retry-thread") {@@ -14104,9 +14105,9 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (body.reportBack === true) { if (owner.group) return json(res, 400, { error: "report_back works only from your own conversation, not a room. Leave it out; the thread's result then stays in that thread." });const result = await coordinateBots({ botIds: [from.id], message, rework: false, thread: "new", reply: "resume", consult: false, title, projectId, ownThread: inherited }), receipt = (result.body.receipts as PeerDeliveryReceipt[] | undefined)?.[0];return json(res, result.status === 200 ? 201 : result.status, { ...result.body, self: true, reportBack: true, title, botId: from.id, botName: from.name, threadId: receipt?.threadId, requestId: receipt?.requestId }); }- const task = store.createTask(from.id, title, false, projectId, { botId: from.id, name: from.name, at: Date.now() }, inherited.approvalMode, inherited.modelSelection);+ const task = store.createTask(from.id, title, false, projectId, { botId: from.id, name: from.name, at: Date.now() }, inherited.approvalMode, inherited.modelSelection, undefined,+ (created) => threadStarters.set(created.threadId, (CLOUD_TEAM ? teamConnections.handOnFor(internalCapability.threadId, internalCapability.generation) : null) ?? openerFrom(fromThreadId)));if (!task) return json(res, 500, { error: "couldn't create that thread" });- threadStarters.set(task.threadId, (CLOUD_TEAM ? teamConnections.handOnFor(internalCapability.threadId, internalCapability.generation) : null) ?? openerFrom(fromThreadId));internalCapability.openedThreads += 1;const chip: Omit<Message, "id" | "at"> = {role: "bot",@@ -14642,22 +14643,19 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (path === "/api/routines" && method === "GET") {return json(res, 200, {- routines: routines!.listRoutines().filter((routine) => routineVisible(routine, visible)),+ routines: routines!.listRoutines().filter((routine) => routineVisible(routine, visible)).map((routine) => routineForViewer(routine, visible)),runs: routineRunsFor((from, to) => routines!.listRuns(from, to), url.searchParams).filter((run) => routineRunVisible(run, visible)),});}- const routineResultsRefusal = (body: unknown): string | null =>- body && typeof body === "object" && typeof (body as { resultsThreadId?: unknown }).resultsThreadId === "string"- ? cloudThreadRefusal(auth, (body as { resultsThreadId: string }).resultsThreadId) : null;const routineBodyRefusal = (body: unknown, existing?: Routine): { status: number; error: string } | null => {- const hidden = hiddenRoutineTarget(body, visible), notYours = routineResultsRefusal(body);- return hidden ? { status: 404, error: hidden } : notYours ? { status: 403, error: notYours } : routineModelRefusal(body, routineModelChecks, existing);+ const hidden = hiddenRoutineTarget(body, visible), notYours = teamRoutines.bodyRefusal(auth, body);+ return hidden ? { status: 404, error: hidden } : notYours ?? routineModelRefusal(body, routineModelChecks, existing);};if (path === "/api/routines" && method === "POST") {const body = await readBody(req);const refused = routineBodyRefusal(body); if (refused) return json(res, refused.status, { error: refused.error });const writer = auth.kind === "session" ? actorKey(auth) : CLOUD_NOBODY_KEY;- const routine = withRoutineWriter(writer, () => routines!.create(body));+ const routine = withRoutineWriter(writer, () => routines!.create(teamRoutines.justMe(auth, body)));if (cloudRoutineAuthors && cloudOwnerSession(auth)) cloudRoutineAuthors.record(routine.id, routine);cloudRoutineAuthors?.wrote(routine.id, writer);if (ownerOrAdmin(auth)) phones.routineAuthors?.record(routine.id, routine);@@ -14688,7 +14686,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {: previous === CLOUD_OUTSIDE_KEY && !(body && typeof body === "object" && "prompt" in body) ? previous: auth.kind === "session" && (!cloudOwnerSession(auth) || (CLOUD_TEAM && previous === CLOUD_OUTSIDE_KEY)) ? actorKey(auth): previous && !cloudOwnerPerson(previous) ? previous : CLOUD_NOBODY_KEY;- const routine = withRoutineWriter(writer, () => routines!.update(routineMatch![1], body));+ const routine = withRoutineWriter(writer, () => routines!.update(routineMatch![1], teamRoutines.justMe(auth, body, routineMatch![1])));// Anyone else's edit, of any field, makes the routine no longer the owner's until the owner rewrites it; off a Cloud home the same for the desktop owner's phones.if (routine) phones.routineEdited(auth, routine, wasOwners || Boolean(body && typeof body === "object" && "prompt" in body));if (routine && cloudRoutineAuthors) {@@ -14918,7 +14916,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (m && method === "GET") {const bot = store.bot(m[1]);if (!bot) return json(res, 404, { error: "no such bot" });- return json(res, 200, await botOverview(bot));+ return json(res, 200, await botOverview(bot, { routine: (routine) => routineVisible(routine, visible), run: (run) => routineRunVisible(run, visible) }));}m = path.match(/^\/api\/bots\/([\w-]+)\/history$/);@@ -15019,10 +15017,10 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (snapshot.phase === "untracked" || !owner || owner.messageId !== snapshot.messageId) {return json(res, 409, { error: "This continuation cannot be safely stopped from this interface", code: "guarded_request_untracked" });}- if (snapshot.phase === "settled") throw requestConflict("This request has already settled");+ if (snapshot.phase === "settled") throw requestConflict("This request has already settled"); const notYours = runOwners.stopRefusal(threadId, runActor(auth)); if (notYours) return json(res, 403, { error: notYours, code: "stop_not_yours" });// No await between comparing the exact lease and revoking it.owner.stopped = true;- handoffs.stoppedByPerson(threadId); personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId));+ handoffs.stoppedByPerson(threadId); personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId), messageSender(auth));const free = idleThreads.stopping(m[1], threadId); await interruptDirectThread(m[1], threadId); free();return json(res, 200, { ok: true, outcome: "stopped" });}@@ -15438,7 +15436,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATAserver.listen(PORT, listenHost(server), async () => {companyRuntimeReady(); cloudHealth?.speed.ready();console.log(`openmausbot server on http://127.0.0.1:${PORT}`);- personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });+ personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); startCloudTeamRoster({ cloudHome: CLOUD_HOME, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); });followupsReady = true; engineUpdates.start();drainQueuedSends();@@ -15501,7 +15499,7 @@ const gracefulShutdown = createGracefulShutdown({if (workspaceAccessTimer) clearInterval(workspaceAccessTimer);// Invalidate turn bearers before any cleanup reaches an await: child MCP processes and the listener may outlive it.revokeAllInternalCapabilities();- sharedComputers.close(); deviceLinks.close(); stopCloudTeamPolicy();+ sharedComputers.close(); deviceLinks.close(); stopCloudTeamPolicy(); stopCloudTeamRoster();phones.close();sharedComputerControl.close();browserLive.closeAll();diff --git a/server/peer-roster.ts b/server/peer-roster.tsindex 22035cfbe0..7f0e6dc147 100644--- a/server/peer-roster.ts+++ b/server/peer-roster.ts@@ -112,10 +112,10 @@ export function reachRefusal(from: RosterMember, target: RosterMember, lookedAft/** What a bot is told about its team can never be wider than what the comms endpoints allow. Its own department comes* first, then the others by name, so a capped roster keeps the nearest teammates. */-export function reachablePeers<T extends RosterMember>(bots: readonly T[], from: RosterMember): T[] {+export function reachablePeers<T extends RosterMember>(bots: readonly T[], from: RosterMember, also?: (bot: T) => boolean): T[] {const own = sectionKey(from.section);const department = (bot: T) => (sectionKey(bot.section) === own ? "" : ` ${sectionKey(bot.section).toLowerCase()}`);- return bots.filter(bot => canReach(from, bot)).sort((a, b) => {+ return bots.filter(bot => canReach(from, bot) || also?.(bot)).sort((a, b) => {const [left, right] = [department(a), department(b)];return left < right ? -1 : left > right ? 1 : 0;});@@ -131,10 +131,22 @@ export function namesTeammate(target: Pick<RosterMember, "id" | "name">, raw: streturn target.id === wanted || foldedName(target.name) === foldedName(wanted) || looseName(target.name) === looseName(wanted);}-/** The teammate `raw` names when `from` may not reach it. A person's own MausBot is never named to anyone else. */-export function unreachableTeammate<T extends RosterMember>(bots: readonly T[], from: RosterMember, raw: string): T | null {+/** Their audiences alone would let `from` reach `target`, whatever its own list of peers says. */+export const reachesInAudience = (from: RosterMember, target: RosterMember): boolean => sameAudience(from.visibility, target.visibility);++/** The teammate `raw` names when `from` may not reach it. A person's own MausBot is never named to anyone else, nor a bot+ * `hides` keeps from `from`. */+export function unreachableTeammate<T extends RosterMember>(bots: readonly T[], from: RosterMember, raw: string, hides?: (bot: T) => boolean): T | null {const target = bots.find((bot) => bot.id === raw.trim()) ?? bots.find((bot) => namesTeammate(bot, raw));- return target && target.id !== from.id && !target.hidden && !target.defaultBot && !canReach(from, target) ? target : null;+ return target && target.id !== from.id && !target.hidden && !target.defaultBot && !canReach(from, target) && !hides?.(target) ? target : null;+}++/** Reach past `from`'s audience that someone else decides (server/host/personal-reach.ts): the bots it adds, the bots+ * `from` may never be told of, and its own words for a refusal. */+export interface WiderReach<T extends RosterMember> {+ reaches(bot: T): boolean;+ hides(bot: T): boolean;+ refusal(bot: T): string | null;}/** A name resolves only inside reachablePeers, so it can never reach a bot its id could not. `elsewhere(name)`: why no bot@@ -145,14 +157,15 @@ export function resolveTeammate<T extends RosterMember>(raw: string,elsewhere: (name: string) => { where: string } | { hint: string } | null = () => null,lookedAfterBy?: LookedAfterBy,+ wider?: WiderReach<T>,): { id: string; byName: boolean } | { error: string } {const wanted = raw.trim();- if (bots.some(bot => bot.id === wanted)) return { id: wanted, byName: false };+ if (bots.some(bot => bot.id === wanted && !wider?.hides(bot))) return { id: wanted, byName: false };const fold = foldedName, loose = looseName;const name = fold(wanted);const shown = peerName(wanted) || wanted;if (!name) return { error: `No bot with id "${shown}" — call list_bots and copy the exact id from the result` };- const reachable = reachablePeers(bots, from);+ const reachable = reachablePeers(bots, from, wider?.reaches);const matches = reachable.filter(bot => fold(bot.name) === name);if (matches.length === 1) return { id: matches[0]!.id, byName: true };if (matches.length > 1) {@@ -160,9 +173,9 @@ export function resolveTeammate<T extends RosterMember>(}const near = reachable.filter(bot => loose(bot.name) === loose(wanted));if (near.length === 1) return { id: near[0]!.id, byName: true };- const apart = bots.find(bot => bot.id !== from.id && !bot.hidden && !bot.defaultBot && !sameAudience(from.visibility, bot.visibility) && (fold(bot.name) === name || loose(bot.name) === loose(wanted)));- if (apart) return { error: reachRefusal(from, apart, lookedAfterBy)! };- const away = bots.some(bot => fold(bot.name) === name || loose(bot.name) === loose(wanted)) ? null : elsewhere(wanted);+ const apart = bots.find(bot => bot.id !== from.id && !bot.hidden && !bot.defaultBot && !wider?.hides(bot) && !sameAudience(from.visibility, bot.visibility) && (fold(bot.name) === name || loose(bot.name) === loose(wanted)));+ if (apart) return { error: wider?.refusal(apart) ?? reachRefusal(from, apart, lookedAfterBy)! };+ const away = bots.some(bot => !wider?.hides(bot) && (fold(bot.name) === name || loose(bot.name) === loose(wanted))) ? null : elsewhere(wanted);if (away && "where" in away) return { error: away.where };return { error: `No bot with id or name "${shown}" — call list_bots and copy the exact id from the result.${teammateChoices(reachable)}${away ? ` ${away.hint}` : ""} ${PEER_ACCESS_HELP}` };}diff --git a/server/person-stops.test.ts b/server/person-stops.test.tsindex 94ea9450bf..53dbf016ec 100644--- a/server/person-stops.test.ts+++ b/server/person-stops.test.ts@@ -45,6 +45,21 @@ describe("PersonStops", () => {});});+describe("who stopped it", () => {+ it("keeps who pressed Stop until the turn's end, and names them on the stopped row", () => {+ const stops = new PersonStops();+ const maya = { name: "Maya", id: "p_maya" };+ stops.stop("t", "turn-1", false, maya);+ expect(stops.stopper("t")).toEqual(maya);+ expect(stoppedTurnRow([], "turn-1", true, stops.stopper("t"))?.stoppedBy).toEqual(maya);+ expect(stoppedTurnRow([], "turn-1", false, maya)).not.toHaveProperty("stoppedBy");+ stops.turnEnded("t", "turn-1");+ expect(stops.stopper("t")).toBeUndefined();+ stops.stop("t", "turn-2", false);+ expect(stops.stopper("t")).toBeUndefined();+ });+});+describe("LiveTurns", () => {const frame = (type: string, turnId: string, threadId = "t1") => ({ type, turnId, threadId }) as never;diff --git a/server/person-stops.ts b/server/person-stops.tsindex 0c9f7ee867..0c1db35fd9 100644--- a/server/person-stops.ts+++ b/server/person-stops.ts@@ -2,16 +2,25 @@// turn they stopped; a Stop that names a turn already over (the second click of a double click) reaches nothing,// so it can never land on the queued message that started next.import { isStoppedTurnName, PERSON_STOPPED_TURN_NAME, STOPPED_TURN_NAME } from "../shared/client-cancel.ts";+import type { ResolvedSender } from "../shared/wire.ts";import type { Message } from "./store.ts";export class PersonStops {readonly #byThread = new Map<string, string | undefined>();+ readonly #by = new Map<string, ResolvedSender>();/** The person pressed Stop on the thread's live turn; `turnId` is undefined while that turn is still being* dispatched. A Stop that found nothing running or dispatching is no stop of anything. */- stop(threadId: string, turnId: string | undefined, dispatching: boolean): void {+ stop(threadId: string, turnId: string | undefined, dispatching: boolean, by?: ResolvedSender): void {if (turnId === undefined && !dispatching) return;this.#byThread.set(threadId, turnId);+ if (by) this.#by.set(threadId, by);+ else this.#by.delete(threadId);+ }++ /** Who pressed that Stop, where several people use the server. */+ stopper(threadId: string): ResolvedSender | undefined {+ return this.#byThread.has(threadId) ? this.#by.get(threadId) : undefined;}stopped(threadId: string, turnId: string | undefined): boolean {@@ -23,14 +32,19 @@ export class PersonStops {/** A turn started: a mark for any other turn on the thread is over (even if that turn's end was lost), and a mark* made during a dispatch is dropped at this start too, since it named no turn. */turnStarted(threadId: string, turnId: string | undefined): void {- if (this.#byThread.has(threadId) && this.#byThread.get(threadId) !== turnId) this.#byThread.delete(threadId);+ if (this.#byThread.has(threadId) && this.#byThread.get(threadId) !== turnId) this.#forget(threadId);}/** A turn ended: its own stop goes, and so does one pressed during a dispatch; another turn's end leaves it be. */turnEnded(threadId: string, turnId: string | undefined): void {if (!this.#byThread.has(threadId)) return;const stopped = this.#byThread.get(threadId);- if (stopped === undefined || stopped === turnId) this.#byThread.delete(threadId);+ if (stopped === undefined || stopped === turnId) this.#forget(threadId);+ }++ #forget(threadId: string): void {+ this.#byThread.delete(threadId);+ this.#by.delete(threadId);}}@@ -45,11 +59,12 @@ export function stoppedTurnRow(messages: readonly Message[],turnId: string | undefined,byPerson: boolean,+ by?: ResolvedSender,): Omit<Message, "id" | "at"> | null {for (let i = messages.length - 1; i >= 0; i -= 1) {const message = messages[i]!;if (message.role === "user") break;if (message.kind === "activity" && isStoppedTurnName(message.tool?.name ?? "") && message.turnId === turnId) return null;}- return { role: "bot", kind: "activity", tool: { name: byPerson ? PERSON_STOPPED_TURN_NAME : STOPPED_TURN_NAME, ok: true }, turnId };+ return { role: "bot", kind: "activity", tool: { name: byPerson ? PERSON_STOPPED_TURN_NAME : STOPPED_TURN_NAME, ok: true }, turnId, ...(byPerson && by ? { stoppedBy: by } : {}) };}diff --git a/server/request-auth.ts b/server/request-auth.tsindex 3bb15b070c..2046dfc5b3 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -1,5 +1,6 @@// Loopback requests (Host and Origin both loopback) or paired sessions (bearer, cookie, stream ticket); a session swaps the loopback rule for same-origin (CSRF) and a scope check.// Browsers never get loopback trust: a page a bot opens is a browser on this machine too.+import { TEAM_LEFT_REFUSAL } from "../shared/cloud-hints.ts";import type { IncomingMessage } from "node:http";import { timingSafeEqual } from "node:crypto";import { isIP } from "node:net";@@ -418,6 +419,10 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["GET"], path: /^\/api\/config$/ },// a person's own "About you" on a Team Cloud{ methods: ["GET", "PUT"], path: /^\/api\/me$/ },+ // whether the person saw their own welcome to the team, and its steps they finished (team-welcome.ts)+ { methods: ["PUT"], path: /^\/api\/me\/welcome$/ },+ // their own "Email me when I'm away" switch on a Team Cloud+ { methods: ["GET", "PUT"], path: /^\/api\/me\/away-emails$/ },// what a bot remembers about the signed-in person on a Team Cloud: their own layer only (routes/bot-memory.ts ownLayer){ methods: ["GET"], path: /^\/api\/bots\/[\w-]+\/memory\/mine$/ },{ methods: ["GET", "PUT", "DELETE"], path: /^\/api\/bots\/[\w-]+\/memory\/mine\/file$/ },@@ -623,6 +628,8 @@ export function resolveRequestAuth(req: IncomingMessage, options: ResolveOptions// A removed member's invalid credential must not fall back to loopback owner.if (via) {+ const presented = via === "bearer" ? bearer : via === "cookie" ? cookie : null;+ if (presented && options.sessions.leftTeam(presented)) return deny(401, TEAM_LEFT_REFUSAL);return deny(401, "unauthorized: this session has expired or was revoked; pair this device again");}diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 310c9ec666..8f5d9f002a 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -29,7 +29,8 @@ import type { RequestAuth } from "../request-auth.ts";import type { RoutineManager } from "../routines.ts";import { acceptedSendMatch, parseSendId } from "../send-idempotency.ts";import type { DirectSendInput, DirectSendReceipt } from "../direct-send.ts";-import { cancelSteeredMessage, holdSteeredQueue, queuedSteeredMessage, restoreHeldSteeredQueue, settleHeldSteeredQueue } from "../steer-queue.ts";+import { cancelSteeredMessage, holdSteeredQueue, queuedSteerSender, queuedSteeredMessage, restoreHeldSteeredQueue, settleHeldSteeredQueue } from "../steer-queue.ts";+import { routeRunOwners, type Actor, type RunOwners } from "../host/run-owner.ts";import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";import { extractSteerImages } from "../turn-images.ts";import { followupFacts, helperFollowup, helperFollowupBody, mayFollowUp } from "../helper-followup.ts";@@ -108,7 +109,10 @@ export interface BotMessageRouteDeps {decidedFor?: { id: string; name: string }, always?: boolean, rememberCommand?: boolean,): Promise<RequestOutcome>;deliverLateQuestionAnswer(auth: RequestAuth, threadId: string, requestId: string, answer: string, cardMessage: Message, owner: BotRecord): Promise<{ queued: boolean }>;- stopThreadForPerson(botId: string, threadId: string): Promise<void>;+ stopThreadForPerson(botId: string, threadId: string, by?: ResolvedSender): Promise<void>;+ /** Whoever asked owns the run, where several people write. */+ runOwners?: Pick<RunOwners, "stopRefusal" | "removeRefusal" | "joinRefusal">;+ runActor?(auth: RequestAuth): Actor;cancelDirectTurnDispatch(botId: string, expectedThreadId?: string): unknown;revokeInternalCapabilitiesForThread(threadId: string): void;cancelGroupTurnOperations(groupId: string, threadId: string): void;@@ -170,7 +174,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerresolveAndSendRoutine, resolveAndSendProfile, resolveAndSendModel, resolveSkillRequest, sendSkillResolution, answerRequest,deliverLateQuestionAnswer, stopThreadForPerson, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread,cancelGroupTurnOperations, closeOpenApprovals, harnessCardOutcome, pressRecords, serverPress, relayedReaction, answeredIn, fromPhone, notePhoneSend, goals,- } = deps;+ } = deps; const owners = routeRunOwners(deps.runOwners, deps.runActor);const pinnedClientThread = pinnedClientThreadGuard(store);/** Security: a bot's own shell must never approve its own card, so a local request counts only from the desktop app, or* from a browser while every bot is idle. */@@ -336,7 +340,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlertry {const receipt = await acceptDirectSend({botId: bot.id, threadId, text, sendId, replyTo, sender, trigger, dataContext, ...(app ? { app } : {}),- personPresent, ...(followUp ? { followUp } : {}),+ personPresent, admin: owners.admin(auth), ...(followUp ? { followUp } : {}),...(mentions?.length && !press && !appSent ? { mentions } : {}),}, guardedStart);press?.settle("queueId" in receipt ? receipt.queueId : undefined);@@ -358,6 +362,9 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerrequirePinnedClientThread(m[1], body?.threadId);const bot = requestedTaskBot(m[1], body?.threadId);const queueId = m[2];+ const waiting = queuedSteerSender(bot.id, bot.threadId, queueId);+ const notYours = waiting && owners.removeRefusal(auth, bot.threadId, waiting.sender);+ if (notYours) return json(res, 403, { error: notYours, code: "queued_not_yours" });if (!cancelSteeredMessage(bot.id, queueId, bot.threadId)) {return json(res, 404, { error: "no such queued message" });}@@ -374,6 +381,11 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler// Hold the whole queue atomically: a racing settle drains it or this request steers it, never both.const held = holdSteeredQueue(bot.id, bot.threadId, m[2]);if (!held) return json(res, 404, { error: "no such queued message" });+ const waitsItsTurn = owners.joinRefusal(auth, bot.threadId, held.items.map((item) => item.sender));+ if (waitsItsTurn) {+ restoreHeldSteeredQueue(held);+ return json(res, 403, { error: waitsItsTurn, code: "waits_its_turn" });+ }const currentAtStart = store.projectBotForTask(bot.id, bot.threadId);const instance = currentAtStart?.busy ? runningTurnInstance(currentAtStart, bot.threadId) : undefined;const engineCanSteer = Boolean(currentAtStart?.busy && instance?.adapter.capabilities.queueing && instance.adapter.steer);@@ -757,9 +769,15 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerif (body.turnId !== undefined && (!turnId || turnId.length > 200)) {return json(res, 400, { error: "turnId must name a turn" });}+ const stopRefused = (threadId: string): boolean => {+ const refusal = owners.stopRefusal(auth, threadId);+ if (refusal) json(res, 403, { error: refusal, code: "stop_not_yours" });+ return refusal !== null;+ };if (typeof expectedThreadId === "string" && store.taskByThread(bot.id, expectedThreadId)) {if (!stopReachesLiveTurn(turnId, liveTurn(expectedThreadId))) return json(res, 200, { ok: true, outcome: "already-stopped" });- await stopThreadForPerson(bot.id, expectedThreadId);+ if (stopRefused(expectedThreadId)) return;+ await stopThreadForPerson(bot.id, expectedThreadId, messageSender(auth));return json(res, 200, { ok: true });}const directClaim = directTurnDispatchClaims.get(bot.threadId);@@ -781,6 +799,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerif (expectedThreadId !== undefined && busyGroup.threadId !== expectedThreadId) {return json(res, 409, userError("serverError.chat.busyInRoom", { room: busyGroup.group.name }));}+ if (stopRefused(busyGroup.threadId)) return;cancelGroupTurnOperations(busyGroup.group.id, busyGroup.threadId);revokeInternalCapabilitiesForThread(busyGroup.threadId);await instance?.adapter.interruptTurn(busyGroup.threadId).catch(() => {});@@ -796,7 +815,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerreturn json(res, 409, { error: "the bot switched tasks before it could be interrupted" });}if (!stopReachesLiveTurn(turnId, liveTurn(expectedThreadId ?? bot.threadId))) return json(res, 200, { ok: true, outcome: "already-stopped" });- await stopThreadForPerson(bot.id, expectedThreadId ?? bot.threadId);+ if (stopRefused(expectedThreadId ?? bot.threadId)) return;+ await stopThreadForPerson(bot.id, expectedThreadId ?? bot.threadId, messageSender(auth));return json(res, 200, { ok: true });}return PASS;diff --git a/server/routes/channels.ts b/server/routes/channels.tsindex 802672862e..d23c60369f 100644--- a/server/routes/channels.ts+++ b/server/routes/channels.ts@@ -1,8 +1,10 @@import { z } from "zod";+import { routeRunOwners, type Actor, type RunOwners } from "../host/run-owner.ts";import type { ResolvedSender, WireGroup } from "../../shared/wire.ts";import { admit } from "../admission.ts";import {cancelChannelMessage,+ channelQueueItem,headChannelGroup,holdChannelQueue,queueChannelMessage,@@ -39,6 +41,9 @@ import { readThreadNotifications, type NotificationListed } from "./notificationexport type MessagePage = { messages: Array<Message | Record<string, unknown>>; hasMore?: boolean; activeLeafId: string | null };export interface ChannelRouteDeps {+ /** Whoever asked owns the run, where several people write. */+ runOwners?: Pick<RunOwners, "stopRefusal" | "removeRefusal" | "joinRefusal">;+ runActor?(auth: RequestAuth): Actor;store: Pick<Store,| "group" | "groupTaskByThread" | "bot" | "switchGroupTask" | "patchGroupTask" | "patchGroup" | "messagesFor" | "groupTasks" | "deleteGroupTasks" | "deleteGroup"| "createGroupTask" | "appendMessage">;@@ -109,7 +114,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {resolveReplyTarget, runningTurnInstance, startGroupTurn, engineSteersImages, applyRoomHoldsFromMessage, cancelGroupTurnOperations,drainQueuedChannelSends, clearTurnDigestState, closeOpenApprovals, revokeInternalCapabilitiesForThread,stagedSkillCleanupsForThread, rejectDeletedThreadSkillStages,- } = deps;+ } = deps; const owners = routeRunOwners(deps.runOwners, deps.runActor);const DESKTOP_MANAGED = deps.desktopManaged;const deleteRefusal = (auth: RequestAuth, groupId: string, threadId: string): { status: 403 | 404 | 409; error: string } | null => {if (phoneSecretSubmissions.hasThread(threadId)) {@@ -400,7 +405,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {? sameNameRefusalForBots(text, members, mentions, current.name, "sent"): sameNameRefusal(text, members, mentions, conversationLanguage(threadId));if (sameName) throw Object.assign(new Error(sameName), { status: 409 });- if (channelMode === "chat") applyRoomHoldsFromMessage(current.id, text, mentions);+ if (channelMode === "chat" && !owners.stopRefusal(auth, threadId)) applyRoomHoldsFromMessage(current.id, text, mentions);const threadWorking = groupThreadIsWorking(current.id, threadId);const decision = admit("room", {}, { roomWorking: threadWorking, threadWorking });if (decision.action === "queue") {@@ -425,6 +430,9 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (m && method === "DELETE") {const group = store.group(m[1]);if (!group) return json(res, 404, { error: "no such group" });+ const waiting = channelQueueItem(group.id, m[2]);+ const notYours = waiting && owners.removeRefusal(auth, waiting.threadId, waiting.item.sender);+ if (notYours) return json(res, 403, { error: notYours, code: "queued_not_yours" });if (!cancelChannelMessage(group.id, m[2])) {return json(res, 404, { error: "no such queued message" });}@@ -463,6 +471,11 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (!held) return json(res, 404, { error: "no such queued message" });const headGroup = headChannelGroup(held.items);const [head] = headGroup;+ const waitsItsTurn = owners.joinRefusal(auth, targetThreadId, headGroup.map((item) => item.sender));+ if (waitsItsTurn) {+ restoreHeldChannelQueue(held);+ return json(res, 403, { error: waitsItsTurn, code: "waits_its_turn" });+ }const steerInput = extractSteerImages(headGroup.map((item) => item.text));const decision = admit("room-steer", {speakerPresent: Boolean(speaker),@@ -603,6 +616,8 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {instance: busy ? runningTurnInstance(busy, threadId) : undefined,};});+ const refusal = targetThreadIds.map((threadId) => owners.stopRefusal(auth, threadId)).find(Boolean);+ if (refusal) return json(res, 403, { error: refusal, code: "stop_not_yours" });// Abort every queued operation before the first provider round trip, so none begins while Stop awaits.for (const { threadId } of interruptTargets) cancelGroupTurnOperations(group.id, threadId);for (const { threadId, instance } of interruptTargets) {diff --git a/server/routes/cloud-signed.ts b/server/routes/cloud-signed.tsindex 3c490f6942..071bcf4f0d 100644--- a/server/routes/cloud-signed.ts+++ b/server/routes/cloud-signed.ts@@ -34,6 +34,10 @@ export function createCloudSignedRoutes(deps: {sessions: Pick<SessionRegistry, "openPairing" | "revokeMember" | "attemptAllowed" | "noteFailure" | "clearFailures">;/** A Team Cloud: every pairing body must carry the Admin's member claim (cloud-team.ts). */team?: CloudTeam | null;+ /** A pairing's `member.invitedBy`: who invited that member (team-welcome.ts); absent on a My Cloud. */+ invited?: (member: string, by: string) => void;+ /** The team's rule turned remote access off: no browser sign-in for a User. */+ memberBrowserOff?: () => boolean;health: Pick<CloudHealth, "report">;/** The home's power once the server listens (null before, and on a server that is not a Cloud home). */power?: () => Pick<CloudPower, "report" | "prepareSleep"> | null;@@ -51,7 +55,7 @@ export function createCloudSignedRoutes(deps: {planTier?: ((tier: string) => void) | null;now?: () => number;}) {- const pairing = createCloudPairing({ secret: deps.secret, sessions: deps.sessions, team: deps.team ?? null, now: deps.now });+ const pairing = createCloudPairing({ secret: deps.secret, sessions: deps.sessions, team: deps.team ?? null, ...(deps.invited ? { invited: deps.invited } : {}), ...(deps.memberBrowserOff ? { memberBrowserOff: deps.memberBrowserOff } : {}), now: deps.now });const healthRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });const powerReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });const sleepRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });diff --git a/server/routes/config.ts b/server/routes/config.tsindex 23d84fc554..853180f865 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -27,6 +27,7 @@ import {import type { InstanceConfigMap, ModelSelection } from "../contracts.ts";import type { RequestAuth } from "../request-auth.ts";import { parseConfigPatchForPerson } from "../decider/config-errors.ts";+import { TEAM_PERSONAL_HINTS } from "../../shared/cloud-hints.ts";import { DECIDER_KEY_ERROR, deciderIncludedHere, deciderPatchKey, deciderSavePatch, deciderSharedKeyUsable, type Decider } from "../decider/index.ts";import type { ProviderRegistry } from "../harness/registry.ts";import { HOSTED_PROVIDER_SETTINGS_ERROR } from "../hosted-models.ts";@@ -97,6 +98,9 @@ export interface ConfigRouteDeps {/** A Team Cloud only: Settings → Profile saves the signed-in person's own profile, never the server's. False: nobody* signed in to save it for. */ownProfile?(auth: RequestAuth, profile: { name?: string; avatarUrl?: string; aboutMe?: string }): boolean;+ /** On a Team Cloud: the welcome's own hints (TEAM_PERSONAL_HINTS) go to this person's record, never the team's; false+ * for a caller with no team session. */+ ownHints?(auth: RequestAuth, hints: string[]): boolean;resyncOpenCodeProviderKeys(): void;revokeEngineCapabilities(engines: ReadonlySet<string>): void;reloadProviders(before: Record<string, unknown>): Promise<void>;@@ -113,7 +117,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy, localVmImageBusy, localVmModeChangeBusy,providerConfigBusy, computerProviderConfigTransitions, managedBoatOwners, providerOperationConflict,perBotLocalVmCountForModeChange, checkedModelSelection, policyModelRefusal, browserSessionSpec, configStatus,- configForAccess, resyncOpenCodeProviderKeys, revokeEngineCapabilities, reloadProviders, broadcast, drainQueuedSends, ownProfile, postiz,+ configForAccess, resyncOpenCodeProviderKeys, revokeEngineCapabilities, reloadProviders, broadcast, drainQueuedSends, ownProfile, ownHints, postiz,} = deps;return async ({ req, res, url, path, method, auth, json, readBody }) => {// API keys are never echoed back: booleans only.@@ -134,6 +138,14 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {return json(res, 200, configForAccess(configStatus(), auth));}}+ if (patch.onboarding?.hintsSeen && ownHints) {+ const mine = patch.onboarding.hintsSeen.filter((hint) => TEAM_PERSONAL_HINTS.has(hint));+ if (mine.length && ownHints(auth, mine)) {+ // The team's record keeps what it had of these; only this person's changes.+ const kept = (cfg.onboarding?.hintsSeen ?? []).filter((hint) => TEAM_PERSONAL_HINTS.has(hint));+ patch.onboarding = { ...patch.onboarding, hintsSeen: [...new Set([...patch.onboarding.hintsSeen.filter((hint) => !TEAM_PERSONAL_HINTS.has(hint)), ...kept])] };+ }+ }if (CLOUD_HOME && (patch.signIn?.admins?.length || patch.signIn?.members?.length)) {return json(res, 403, { ...userError("serverError.cloud.personal"), code: "cloud_personal" });}diff --git a/server/routes/me.ts b/server/routes/me.tsindex a6e02fde8a..6e108e8291 100644--- a/server/routes/me.ts+++ b/server/routes/me.ts@@ -5,13 +5,17 @@ import { botAvatarUrlSchema } from "../../shared/bot-avatar.ts";import type { CloudTeam } from "../cloud-team.ts";import type { MemberProfile, MemberProfilePatch } from "../host/cloud-team-host.ts";import { ABOUT_ME_MAX, PERSON_NAME_MAX, type SeedField } from "../people-about.ts";+import { personKey } from "../person-key.ts";import type { RequestAuth } from "../request-auth.ts";+import { WELCOME_HINT, type TeamWelcomeStore } from "../team-welcome.ts";import type { SessionRecord } from "../sessions.ts";import { PASS, type RouteHandler } from "./table.ts";export interface MeRouteDeps {team: CloudTeam | null;session(auth: RequestAuth): SessionRecord | null;+ /** The person's own welcome to the team (team-welcome.ts): who invited them, whether they saw it, its steps they finished. */+ welcome: Pick<TeamWelcomeStore, "read" | "save">;profile(session: SessionRecord): MemberProfile;save(session: SessionRecord, patch: MemberProfilePatch): MemberProfile;/** `fillEmpty`: the desktop app's one-time seed from the person's own computer (seedMemberProfile). */@@ -23,12 +27,24 @@ export interface MeRouteDeps {export function createMeRoutes(deps: MeRouteDeps): RouteHandler {return async ({ req, res, path, method, auth, json, readBody }) => {- if (path !== "/api/me") return PASS;+ if (path !== "/api/me" && path !== "/api/me/welcome") return PASS;if (!deps.team) return json(res, 404, { error: "not found" });const session = deps.session(auth);if (!session) return json(res, 403, { error: "Sign in to this team to have a profile." });const team = { id: deps.team.id, name: deps.team.name };- if (method === "GET") return json(res, 200, { team, ...deps.profile(session), seeded: deps.seeded(session) });+ if (path === "/api/me/welcome") {+ // PUT { welcomed?: true, hints?: [id] }: this person saw their welcome, or finished some of its steps. Theirs alone.+ if (method !== "PUT") return json(res, 405, { error: "method not allowed" });+ const body = await readBody(req, 8 * 1024);+ const given = body && typeof body === "object" && !Array.isArray(body) ? body as Record<string, unknown> : {};+ if (given.welcomed !== undefined && given.welcomed !== true) return json(res, 400, { error: "welcomed is true or absent" });+ if (given.hints !== undefined && (!Array.isArray(given.hints) || given.hints.length > 16 || !given.hints.every((hint) => typeof hint === "string" && WELCOME_HINT.test(hint)))) {+ return json(res, 400, { error: "hints are at most 16 step ids" });+ }+ if (given.welcomed === undefined && given.hints === undefined) return json(res, 400, { error: "send { welcomed: true } or { hints }" });+ return json(res, 200, { welcome: deps.welcome.save(personKey(session), { ...(given.welcomed ? { welcomed: true as const } : {}), ...(given.hints ? { hints: given.hints as string[] } : {}) }) });+ }+ if (method === "GET") return json(res, 200, { team, ...deps.profile(session), seeded: deps.seeded(session), welcome: deps.welcome.read(personKey(session)) });if (method !== "PUT") return json(res, 405, { error: "method not allowed" });const body = await readBody(req, 64 * 1024);const given = body && typeof body === "object" && !Array.isArray(body) ? body as Record<string, unknown> : {};diff --git a/server/routes/tasks.ts b/server/routes/tasks.tsindex 7b8f58fb5c..66bc0d0b94 100644--- a/server/routes/tasks.ts+++ b/server/routes/tasks.ts@@ -195,10 +195,10 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTaif (body.projectId !== undefined && (typeof body.projectId !== "string" || !store.project(bot.id, body.projectId))) {return json(res, 400, { error: "projectId must belong to this bot" });}- const task = store.createTask(bot.id, typeof body.title === "string" ? body.title : undefined, body.select !== false, body.projectId, undefined, body.approvalMode, undefined, cwd);+ // Who opened it decides who may answer its cards on a shared workspace, and on a team who sees it at all.+ const task = store.createTask(bot.id, typeof body.title === "string" ? body.title : undefined, body.select !== false, body.projectId, undefined, body.approvalMode, undefined, cwd,+ auth.kind === "session" ? (created) => threadStarters.set(created.threadId, actorKey(auth)) : undefined);if (!task) return json(res, 500, { error: "couldn't create that task" });- // Who opened it decides who may answer its cards on a shared workspace.- if (auth.kind === "session") threadStarters.set(task.threadId, actorKey(auth));return json(res, 201, { bot: publicBot(store.bot(bot.id)!), task: wireTask(task, store.bot(bot.id)!.modelSelection) });}m = path.match(/^\/api\/bots\/([\w-]+)\/tasks\/delete$/);diff --git a/server/routes/teams.ts b/server/routes/teams.tsindex 46ff42b7ca..317bffc02c 100644--- a/server/routes/teams.ts+++ b/server/routes/teams.ts@@ -26,7 +26,7 @@ import {import { readPublishedLibrary, writePublishedLibrary, type DefaultsPreset } from "../presets.ts";import { scoutProject, suggestTeam } from "../project-scout.ts";import { readPublishedTeam, writePublishedTeam } from "../published-teams.ts";-import type { RoutineManager } from "../routines.ts";+import type { Routine, RoutineManager } from "../routines.ts";import { readSectionContext } from "../section-context.ts";import { sectionKey, type BotRecord, type GroupRecord, type Store } from "../store.ts";import { createTeamBackup, importTeamBackup } from "../team-backup.ts";@@ -58,9 +58,16 @@ export interface TeamRouteDeps {| { ok: false; error: string; available: string[] };/** On a Team Cloud: false for someone else's private chat, which a team backup never carries. */threadShown?(auth: RequestAuth): (threadId: string) => boolean;+ /** On a Team Cloud: false for a routine that lives in someone else's private chat, which no export carries. */+ routineShown?(auth: RequestAuth): (routine: Routine) => boolean;}export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {+ const routinesFor = (auth: RequestAuth): Routine[] => {+ const all = deps.routines()!.listRoutines();+ const shown = deps.routineShown?.(auth);+ return shown ? all.filter(shown) : all;+ };const {store, cfg, broadcast, publicBot, publicGroupState, groupWithThread, defaultSelection, defaultsPresetFor,packageImportDeps, starterNotes, checkedExportSkillNames, collectExportSkills, collectTeamSkills,@@ -125,7 +132,7 @@ export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {authorName: profileName,bots: store.bots,groups: store.groups,- routines: routines!.listRoutines(),+ routines: routinesFor(auth),brief: readSectionContext(team)?.text,published: readPublishedTeam(team),skillsByBot: skills.skillsByBot,@@ -160,7 +167,7 @@ export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {if ((body.format === "backup" ? store.bots.length : memberIds.length) === 0) return json(res, 400, { error: "Create a bot before exporting your team" });try {if (body.format === "backup") {- return json(res, 200, createTeamBackup(store, routines!.listRoutines(), name, deps.threadShown?.(auth)));+ return json(res, 200, createTeamBackup(store, routinesFor(auth), name, deps.threadShown?.(auth)));}if (body.format === "package") {const selectedBots = store.bots.filter((bot) => !bot.hidden);@@ -171,7 +178,7 @@ export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {authorName: profileName,bots: selectedBots,groups: store.groups,- routines: routines!.listRoutines(),+ routines: routinesFor(auth),skillsByBot: collectExportSkills(selectedBots, skillNames.names),});return json(res, 200, {diff --git a/server/routine-home.test.ts b/server/routine-home.test.tsnew file mode 100644index 0000000000..c305c38013--- /dev/null+++ b/server/routine-home.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from "vitest";++import { routineHome } from "./routine-home.ts";++const PRIVATE: Record<string, string> = { "bob-chat": "p_bob", "bob-results": "p_bob", "ben-chat": "p_ben" };+const TASKS: Record<string, { title: string; askedAt?: number }> = {+ "bob-chat": { title: "Bob's plans" },+ "bob-results": { title: "Standup · Results" },+ "main": { title: "Shared chat" },+};+const deps = { privateTo: (threadId: string) => PRIVATE[threadId] ?? null, task: (_botId: string, threadId: string) => TASKS[threadId] };++describe("routineHome", () => {+ it("is the person whose private chat it was made in, whatever it reports to", () => {+ expect(routineHome({ botId: "scout", sourceThreadId: "bob-chat", resultsThreadId: "main" }, deps)).toBe("p_bob");+ });++ it("is the person whose private chat it reports into", () => {+ expect(routineHome({ botId: "scout", name: "Kumquat", resultsThreadId: "bob-chat" }, deps)).toBe("p_bob");+ });++ it("is nobody's for one made in a shared chat, or reporting into the chat it opened for itself", () => {+ expect(routineHome({ botId: "scout", sourceThreadId: "main" }, deps)).toBeNull();+ expect(routineHome({ botId: "scout", name: "Standup", resultsThreadId: "bob-results" }, deps)).toBeNull();+ expect(routineHome({ botId: "scout", name: "Standup" }, deps)).toBeNull();+ });++ it("is the person's once they have written in the chat it opened for itself", () => {+ TASKS["bob-results"]!.askedAt = 1;+ try {+ expect(routineHome({ botId: "scout", name: "Standup", resultsThreadId: "bob-results" }, deps)).toBe("p_bob");+ } finally {+ delete TASKS["bob-results"]!.askedAt;+ }+ });+});diff --git a/server/routine-home.ts b/server/routine-home.tsnew file mode 100644index 0000000000..227c0895d5--- /dev/null+++ b/server/routine-home.ts@@ -0,0 +1,37 @@+// Where a routine lives on a Team Cloud (docs/team-cloud.md "Routines"). One for a member's own MausBot, or that names+// someone's private chat (the chat it was made in or the one it reports into), is that person's alone, as the chat is;+// any other routine is its place's (the bot's, or its group chat's). The chat a routine opened for its own results is+// not a place the person chose, so it does not make the routine theirs.+import { isOwnResultsChat } from "./automation-destinations.ts";+import type { TaskRecord } from "./store.ts";++export interface RoutinePlace {+ botId?: unknown;+ name?: unknown;+ sourceThreadId?: unknown;+ resultsThreadId?: unknown;+}++export interface RoutineHomeDeps {+ /** The person a conversation is private to, else null (audience.ts). */+ privateTo(threadId: string): string | null;+ task(botId: string, threadId: string): Pick<TaskRecord, "title" | "askedAt"> | null | undefined;+ /** The person whose own MausBot this is, else null. */+ ownBot?(botId: string): string | null;+}++const id = (value: unknown): string | null => (typeof value === "string" && value ? value : null);++/** The person whose private chat the routine lives in; null for one of a shared place, and anywhere off a team. */+export function routineHome(routine: RoutinePlace, deps: RoutineHomeDeps): string | null {+ const own = typeof routine.botId === "string" ? deps.ownBot?.(routine.botId) : null;+ if (own) return own;+ const source = id(routine.sourceThreadId);+ const made = source ? deps.privateTo(source) : null;+ if (made) return made;+ const results = id(routine.resultsThreadId);+ if (!results) return null;+ const task = typeof routine.botId === "string" ? deps.task(routine.botId, results) : null;+ if (task && isOwnResultsChat(typeof routine.name === "string" ? routine.name : "", task)) return null;+ return deps.privateTo(results);+}diff --git a/server/routines.ts b/server/routines.tsindex 77e3a39e3e..d20e885dff 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -665,21 +665,21 @@ export class RoutineManager {return true;}- /** A deleted bot's schedules go with it: each is removed, its unfinished runs stop, and its run history is dropped. */- removeForBot(botId: string) {- for (const routine of this.routines.filter((candidate) => candidate.botId === botId)) this.remove(routine.id);+ /** A deleted bot's schedules go with it, or with `routineId` that one only (one person's alone, gone as they leave a team): each is removed, its unfinished runs stop, and its run history is dropped. */+ removeForBot(botId: string, routineId?: string) {+ for (const routine of this.routines.filter((candidate) => candidate.botId === botId && (routineId === undefined || candidate.id === routineId))) this.remove(routine.id);for (const run of this.runs) {- if (run.botId !== botId || !["queued", "running", "waiting"].includes(run.status)) continue;+ if (run.botId !== botId || (routineId !== undefined && run.routineId !== routineId) || !["queued", "running", "waiting"].includes(run.status)) continue;run.status = "cancelled";if (run.target === "room-goal") run.goalStatus = "stopped";run.attention = undefined;run.finishedAt = this.now();- run.error = "The assigned bot was deleted";+ run.error = routineId === undefined ? "The assigned bot was deleted" : "The routine was deleted";this.emitRun(run);if (run.threadId && run.target === "room-goal") void this.options.interruptGoal?.(run.groupId, run.threadId).catch(() => {});else if (run.threadId) void this.options.interruptTurn?.(run.botId, run.threadId).catch(() => {});}- const kept = this.runs.filter((run) => run.botId !== botId);+ const kept = this.runs.filter((run) => run.botId !== botId || (routineId !== undefined && run.routineId !== routineId));if (kept.length !== this.runs.length) this.commitMutation(() => { this.runs = kept; });}diff --git a/server/sessions.ts b/server/sessions.tsindex 7c4993d836..3b769afcb1 100644--- a/server/sessions.ts+++ b/server/sessions.ts@@ -33,6 +33,8 @@ export const SESSION_TTL_MS = daysMs(process.env.OMB_SESSION_TTL_DAYS, 30);/** OMB_SESSION_MAX_DAYS (default 180): renewal never passes this, so a stolen cookie has a bounded life. */export const SESSION_MAX_AGE_MS = daysMs(process.env.OMB_SESSION_MAX_DAYS, 180);export const SESSION_RENEW_WHEN_LEFT_MS = SESSION_TTL_MS / 2;+/** A team session the roster check keeps alive was used within this long. */+const TEAM_ACTIVE_MS = 60 * 60_000;export function cookieMaxAgeSeconds(session: { expiresAt: number }, now = Date.now()): number {return Math.max(1, Math.floor((session.expiresAt - now) / 1000));@@ -75,6 +77,9 @@ const sessionSchema = z.object({/** A team session opened with a code its member made (their phone): when the Admin last vouched for that member. The* session ends within the hour of it; each new Admin-signed pairing of the same member, in the same role, moves it. */memberCheckedAt: z.number().optional(),+ /** A team session the Admin's roster check (cloud-team-roster.ts) last found its member in the team, at this role: it ends+ * within the hour of that, so a browser or app in use stays signed in with no new pairing. */+ vouchedAt: z.number().optional(),/** A browser sign-in (PairingCode `browser`): accepted only as its browser's cookie, never as a bearer token. */cookieOnly: z.literal(true).optional(),owner: z.string().max(254).optional(),@@ -499,6 +504,41 @@ export class SessionRegistry {}}+ /** The team members the roster check asks about: those with a session used within the last hour (never a script's token+ * or a move-in sign-in, which end as they were made to). At most `max` people, the soonest to end first. */+ membersToVouch(max: number): string[] {+ this.prune();+ const now = this.now(), soonest = new Map<string, number>();+ for (const session of this.sessions) {+ if (!this.vouchable(session, now)) continue;+ soonest.set(session.email!, Math.min(soonest.get(session.email!) ?? Infinity, session.expiresAt));+ }+ return [...soonest].sort((a, b) => a[1] - b[1]).slice(0, max).map(([email]) => email);+ }++ /** A team session the roster check may keep: live, used within the last hour, and not a token or a move-in sign-in. */+ private vouchable(session: SessionRecord, now: number): boolean {+ return session.membershipAuthority === "team" && Boolean(session.email) && !session.token && !session.moveIn+ && session.expiresAt > now && now - session.lastSeenAt <= TEAM_ACTIVE_MS;+ }++ /** The Admin's roster check found this member in the team at `role` just now. Their sessions at another role end (a role+ * change the Admin's own pairing didn't reach; never an upgrade). Each of their sessions at that role that was used within+ * the hour, phones included, ends no later than an hour after its last use: an idle one, left on another computer, still+ * ends on schedule however much the person uses another device. */+ vouchMember(email: string, role: TeamRole): void {+ const address = email.trim().toLowerCase(), now = this.now();+ this.revokeMember(address, role);+ let changed = false;+ for (const session of this.sessions) {+ if (session.email !== address || session.teamRole !== role || !this.vouchable(session, now)) continue;+ if (session.memberCheckedAt !== undefined) session.memberCheckedAt = now; else session.vouchedAt = now;+ const next = Math.min(teamSessionExpiresAt(now, Math.min(now + SESSION_TTL_MS, session.createdAt + SESSION_MAX_AGE_MS)), session.lastSeenAt + TEAM_ACTIVE_MS);+ if (next > session.expiresAt) { session.expiresAt = next; changed = true; }+ }+ if (changed) this.persist();+ }+issue(input: { label: string; scopes: Scope[]; userId?: string; email?: string }): { token: string; session: PublicSession } {return this.issueAccount(input);}@@ -642,7 +682,7 @@ export class SessionRegistry {if (!record || record.expiresAt <= now || record.token) return false;if (record.expiresAt - now > SESSION_RENEW_WHEN_LEFT_MS) return false;const proposed = Math.min(now + SESSION_TTL_MS, record.createdAt + SESSION_MAX_AGE_MS);- const next = record.membershipAuthority === "team" ? teamSessionExpiresAt(record.memberCheckedAt ?? record.createdAt, proposed) : proposed;+ const next = record.membershipAuthority === "team" ? teamSessionExpiresAt(Math.max(record.memberCheckedAt ?? record.createdAt, record.vouchedAt ?? 0), proposed) : proposed;if (next <= record.expiresAt) return false;record.expiresAt = next;record.lastSeenAt = now;@@ -673,11 +713,35 @@ export class SessionRegistry {return this.memberPhones().filter((phone) => this.revoke(phone.id)).length;}+ /** The credentials of a person no longer in the team, for a day, by digest only (memory, never stored): their page can say+ * why it was signed out. */+ private readonly left = new Map<string, number>();+ private noteLeft(address: string): void {+ const now = this.now();+ for (const [hash, until] of this.left) if (until <= now) this.left.delete(hash);+ for (const session of this.sessions) {+ if (session.membershipAuthority === "team" && session.email?.toLowerCase() === address && this.left.size < 5_000) this.left.set(session.tokenHash, now + 86_400_000);+ }+ }+ /** Whether this credential's session ended because its person is no longer in the team. */+ leftTeam(token: string): boolean {+ const until = this.left.get(sha256(token));+ return until !== undefined && until > this.now();+ }++ /** Remote access turned off on a Team Cloud: every User's browser sign-in signs out. An Owner's and an Admin's stay. */+ closeMemberBrowsers(): number {+ this.prune();+ return this.sessions.filter((session) => session.membershipAuthority === "team" && session.cookieOnly && session.teamRole === "member").map((session) => session.id)+ .filter((id) => this.revoke(id)).length;+ }+/** A person who left a Team Cloud: every session of theirs (app windows, phones) ends now, and no open code of theirs* can open another. With `keepRole` (the Admin vouched for them at that role), only those at another role end. Returns* how many sessions ended. */revokeMember(email: string, keepRole?: TeamRole): number {const address = email.trim().toLowerCase();+ if (keepRole === undefined) this.noteLeft(address);this.pairings = this.pairings.filter((pairing) => pairing.member?.email.toLowerCase() !== address || pairing.member.role === keepRole);const ended = this.sessions.filter((session) => session.membershipAuthority === "team" && session.email?.toLowerCase() === address && (keepRole === undefined || session.teamRole !== keepRole));for (const session of ended) this.revoke(session.id);diff --git a/server/steer-queue.test.ts b/server/steer-queue.test.tsindex a6d968c617..8a37cb7b9c 100644--- a/server/steer-queue.test.ts+++ b/server/steer-queue.test.ts@@ -280,6 +280,21 @@ describe("steer-queue module", () => {expect(store.messages.map((message) => message.text)).toEqual(["first words", "second words"]);});+ it("where several people write, runs each person's lines as their own turn, the asker's own addition first, and names each chip", () => {+ const bot = fakeBot("bot-several", "thread-several", true);+ const store = fakeStore([bot]);+ const run = vi.fn();+ const tom = { name: "Tom", id: "p_tom" }, priya = { name: "Priya", id: "p_priya" };+ queueSteeredMessage(bot.id, bot.threadId, "what is due", { sender: tom, first: true });+ queueSteeredMessage(bot.id, bot.threadId, "and the PR", { sender: priya, first: true, aheadOfOthers: "p_priya" });+ expect(queuedSteerSnapshot((id) => id === bot.id, undefined, (_threadId, sender) => sender)[bot.threadId]!.map((chip) => chip.sender?.name)).toEqual(["Priya", "Tom"]);+ expect(queuedSteerSnapshot((id) => id === bot.id)[bot.threadId]!.some((chip) => "sender" in chip)).toBe(false);+ bot.busy = false;+ drainSteeredMessages(store, run);+ drainSteeredMessages(store, run);+ expect(run.mock.calls.map((call) => [call[2], call[6].sender?.name])).toEqual([["and the PR", "Priya"], ["what is due", "Tom"]]);+ });+it("drains one call's spoken lines as one turn, and the next call's as its own", () => {const bot = fakeBot("bot-call-groups", "thread-call-groups", true);const store = fakeStore([bot]);diff --git a/server/steer-queue.ts b/server/steer-queue.tsindex 4736ee5d9c..8acd8e211e 100644--- a/server/steer-queue.ts+++ b/server/steer-queue.ts@@ -84,13 +84,15 @@ const changed = () => {}};-/** Public pending chips only: never expose provider prompts or reply context. */-export function queuedSteerSnapshot(ownsThread: (botId: string, threadId: string) => boolean, whyHeld: (threadId: string, reason: SteerQueueReason | undefined) => string | undefined = () => undefined):- BotQueuedMessages {+/** Public pending chips only: never expose provider prompts or reply context. `shownSender`: where several people write,+ * whose each chip is. */+export function queuedSteerSnapshot(ownsThread: (botId: string, threadId: string) => boolean, whyHeld: (threadId: string, reason: SteerQueueReason | undefined) => string | undefined = () => undefined,+ shownSender: (threadId: string, sender: ResolvedSender) => ResolvedSender | undefined = () => undefined): BotQueuedMessages {return Object.fromEntries([...queues].filter(([threadId, entry]) => ownsThread(entry.botId, threadId)).map(([threadId, entry]) => [threadId, entry.items.filter((item) => !item.rowId).map((item) => ({queueId: item.messageId, text: item.text, ...(item.reason ? { reason: item.reason, why: whyHeld(threadId, item.reason) } : {}),+ ...(item.sender && shownSender(threadId, item.sender) ? { sender: shownSender(threadId, item.sender) } : {}),}))]));}@@ -107,7 +109,7 @@ export function queueSteeredMessage(botId: string,threadId: string,text: string,- options: { prompt?: string; replyToId?: string; sendId?: string; dataContext?: Message["dataContext"]; reason?: SteerQueueReason; unattended?: boolean; peerAsk?: Message["peerAsk"]; origin?: WorkOrigin; sender?: ResolvedSender; trigger?: UsageTrigger; callId?: string; via?: "call"; reaction?: string; fromApp?: Message["fromApp"]; relay?: Message["relay"]; rowId?: string; first?: boolean; queuedAt?: number; mentions?: string[] } = {},+ options: { prompt?: string; replyToId?: string; sendId?: string; dataContext?: Message["dataContext"]; reason?: SteerQueueReason; unattended?: boolean; peerAsk?: Message["peerAsk"]; origin?: WorkOrigin; sender?: ResolvedSender; trigger?: UsageTrigger; callId?: string; via?: "call"; reaction?: string; fromApp?: Message["fromApp"]; relay?: Message["relay"]; rowId?: string; first?: boolean; queuedAt?: number; mentions?: string[]; aheadOfOthers?: string } = {},): QueuedSteer {const id = newId();const entry = queues.get(threadId) ?? { botId, items: [] };@@ -134,8 +136,10 @@ export function queueSteeredMessage(...(options.mentions?.length ? { mentions: options.mentions } : {}),};saveChatFollowup({ id, kind: "bot", ownerId: botId, threadId, payload: item });- // `first`: ahead of everything queued but the person's own messages sent before it.- const ahead = options.first ? entry.items.findIndex((other) => other.peerAsk !== undefined || other.unattended === true || other.queuedAt > item.queuedAt) : -1;+ // `first`: ahead of everything queued but the person's own messages sent before it; with `aheadOfOthers` (the person+ // whose request runs, where several people write), ahead of everyone else's too.+ const ahead = options.first ? entry.items.findIndex((other) => other.peerAsk !== undefined || other.unattended === true || other.queuedAt > item.queuedAt+ || (options.aheadOfOthers !== undefined && other.sender?.id !== options.aheadOfOthers)) : -1;if (ahead < 0) entry.items.push(item);else entry.items.splice(ahead, 0, item);queues.set(threadId, entry);@@ -267,6 +271,13 @@ export function queuedSteeredMessage(return item ? { id: item.messageId, text: item.text, replyToId: item.replyToId, ...(item.reason ? { reason: item.reason } : {}) } : null;}+/** Whose waiting line this is, or null when nothing waits under that id. */+export function queuedSteerSender(botId: string, threadId: string, queueId: string): { sender?: ResolvedSender } | null {+ const item = queues.get(threadId)?.botId === botId ? queues.get(threadId)!.items.find((candidate) => candidate.messageId === queueId) : undefined;+ if (!item) return null;+ return item.sender ? { sender: item.sender } : {};+}+export function cancelSteeredMessage(botId: string, messageId: string, expectedThreadId?: string): boolean {for (const [threadId, entry] of queues) {if (entry.botId !== botId || (expectedThreadId !== undefined && threadId !== expectedThreadId)) continue;diff --git a/server/store.ts b/server/store.tsindex 635ec00224..d1ae676e6c 100644--- a/server/store.ts+++ b/server/store.ts@@ -1297,7 +1297,7 @@ export class Store {>> = {},opts: {- seedMessages?: boolean; id?: string; threadId?: string;+ seedMessages?: boolean; id?: string; threadId?: string; beforeShown?: (bot: BotRecord) => void;} = {},): BotRecord {const toolScope = parseToolScope(profile.toolScope);@@ -1348,7 +1348,7 @@ export class Store {console.warn(`[bot-folder] could not write SOUL.md mirror for ${bot.id}: ${(e as Error).message}`);}// Before its transcript: clients need the bot/thread mapping to place either message.- this.emit({ type: "bot", botId: bot.id });+ opts.beforeShown?.(bot); this.emit({ type: "bot", botId: bot.id });if (opts.seedMessages !== false) {this.appendMessage(bot.threadId, initialGreetingMessage(name, this.initialLanguage, !bot.soul?.trim() && !bot.description.trim(), this.personName()));}@@ -2156,7 +2156,7 @@ export class Store {}createTask(botId: string, title?: string, activate = true, projectId?: string, openedBy?: TaskOpenedBy, approvalMode?: "ask" | "full",- modelSelection?: ModelSelection, cwd?: string): TaskRecord | null {+ modelSelection?: ModelSelection, cwd?: string, beforeShown?: (task: TaskRecord) => void): TaskRecord | null {const bot = this.bot(botId);if (!bot) return null;if (projectId !== undefined && !this.project(botId, projectId)) return null;@@ -2165,7 +2165,7 @@ export class Store {bot.tasks = [task, ...(bot.tasks ?? [])];if (activate) this.mirrorActiveTask(bot, task);});- this.emit({ type: "bot", botId });+ beforeShown?.(task); this.emit({ type: "bot", botId });return task;}diff --git a/server/team-move.e2e.test.ts b/server/team-move.e2e.test.tsindex 21edab0452..32946eabe0 100644--- a/server/team-move.e2e.test.ts+++ b/server/team-move.e2e.test.ts@@ -80,7 +80,7 @@ function watchRoutine(id: string) {const done = (async () => {while (!stop) {try {- const [mine, theirs] = await Promise.all([fx.onCloud("GET", "/api/routines"), onTeam("olive")("GET", "/api/routines")]);+ const [mine, theirs] = await Promise.all([fx.onCloud("GET", "/api/routines"), onTeam("ada")("GET", "/api/routines")]);const find = (body: any) => (body?.routines as Array<{ id: string; enabled: boolean }> | undefined)?.find((routine) => routine.id === id)?.enabled ?? null;seen.push({ mine: find(mine.body), theirs: find(theirs.body) });} catch {}@@ -114,7 +114,7 @@ it("moves Scout with its two chats, its routine and its files; its notes about Afx.beforeTeamJournalWrite = null;expect(phaseOf(scout.bot.id)?.phase).toBe("check");const routineOn = async (side: CloudSendFixture["onCloud"]) => ((await side("GET", "/api/routines")).body.routines as Array<{ id: string; enabled: boolean }>).find((routine) => routine.id === scout.routine)?.enabled;- expect([await routineOn(fx.onCloud), await routineOn(onTeam("olive"))], "off on both sides until the switch").toEqual([false, false]);+ expect([await routineOn(fx.onCloud), await routineOn(onTeam("ada"))], "off on both sides until the switch").toEqual([false, false]);expect(fx.teamMove.view()?.phase).toBe("moving");await fx.teamMove.kick();await watch.stop();@@ -143,10 +143,13 @@ it("moves Scout with its two chats, its routine and its files; its notes about Aexpect(carried).toMatchObject({ enabled: true, botId: scout.bot.id });expect(carried.resultsThreadId).not.toBe((there as { mainThreadId?: string }).mainThreadId);expect(there.tasks?.find((task) => task.threadId === carried.resultsThreadId)?.private, "its results conversation came with it, as Ada's").toBe(true);- // It reports into Ada's own conversation there, never the team's main chat.- const ran = await onTeam("olive")("POST", `/api/routines/${scout.routine}/run`);+ // It reports into Ada's own conversation there, never the team's main chat, so it is hers alone: the Owner neither+ // sees it nor runs it.+ expect(((await onTeam("olive")("GET", "/api/routines")).body.routines as Array<{ id: string }>).some((routine) => routine.id === scout.routine)).toBe(false);+ expect((await onTeam("olive")("POST", `/api/routines/${scout.routine}/run`)).status).toBe(404);+ const ran = await onTeam("ada")("POST", `/api/routines/${scout.routine}/run`);expect(ran.status, JSON.stringify(ran.body)).toBeLessThan(300);- // Its run is Ada's: she sees it, and the Owner who started it never reads what it said.+ // Its run is Ada's: she sees it, and nobody else reads what it said.await expect.poll(async () => ((await onTeam("ada")("GET", "/api/routines")).body.runs as Array<{ routineId: string; status: string }>).some((run) => run.routineId === scout.routine && run.status === "completed"), { timeout: 60_000, interval: 200 }).toBe(true);const report = ((await onTeam("ada")("GET", "/api/routines")).body.runs as Array<{ routineId: string; threadId?: string; resultsThreadId?: string }>).find((run) => run.routineId === scout.routine)!;@@ -224,7 +227,7 @@ it("a move cut short, by the app killed while My Cloud holds the bot and by a drexpect(new Set(ids).size).toBe(ids.length);expect(ids).toEqual((await rows(fx.onCloud, threadId)).map((row) => row.id));}- const routines = ((await onTeam("olive")("GET", "/api/routines")).body.routines as Array<{ id: string; enabled: boolean }>).filter((routine) => routine.id === quill.routine);+ const routines = ((await onTeam("ada")("GET", "/api/routines")).body.routines as Array<{ id: string; enabled: boolean }>).filter((routine) => routine.id === quill.routine);expect(routines).toEqual([expect.objectContaining({ enabled: true })]);expect(watch.seen.some((sample) => sample.mine && sample.theirs), JSON.stringify(watch.seen)).toBe(false);}, hostTimeout(300_000));diff --git a/server/team-small-fixes.e2e.test.ts b/server/team-small-fixes.e2e.test.tsindex d29f31712a..08d0bb8c85 100644--- a/server/team-small-fixes.e2e.test.ts+++ b/server/team-small-fixes.e2e.test.ts@@ -228,7 +228,7 @@ it("a question left for a day is said in the person's own inbox chat, once the cconst reporter = await create({ name: "Reporter", title: "Reports", section: "Support", reportsTo: MIRA.email });expect((await team.as(ada, "PATCH", `/api/bots/${reporter.id}`, { approvalMode: "ask" })).status).toBe(200);const bots = async () => (await team.as(mira, "GET", "/api/bots")).body.bots as Array<Bot & { defaultBot?: unknown; tasks?: Array<{ threadId: string; inbox?: true; openAsks?: number }> }>;- // A User's own MausBot: no crown and no Chief's powers, and it cannot reach a bot shared with everyone.+ // A User's own MausBot: no crown and no Chief's powers.const own = (await bots()).find((bot) => bot.defaultBot) as Bot & { chiefOfStaff?: boolean };expect(MIRA.role).toBe("member");expect(own.chiefOfStaff).toBeFalsy();diff --git a/server/team-welcome.e2e.test.ts b/server/team-welcome.e2e.test.tsnew file mode 100644index 0000000000..3749272242--- /dev/null+++ b/server/team-welcome.e2e.test.ts@@ -0,0 +1,98 @@+// A real Team Cloud (OMB_CLOUD_ROLE=team): each person's first screen is theirs alone. Who invited them comes from the+// Admin's signed claim only; whether they saw it, and the steps they finished, are kept per person, never team-wide.+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";+import { TEAM_LEFT_REFUSAL } from "../shared/cloud-hints.ts";++const ADA = { email: "[email protected]", role: "owner" as const };+const BOB = { email: "[email protected]", role: "admin" as const };+const CLEO = { email: "[email protected]", role: "member" as const };++let fx: CloudSendFixture, team: CloudTeamFixture;++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-welcome-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-1", name: "Acme" } });+ team = fx.team!;+}, hostTimeout(120_000));++afterAll(async () => {+ await fx?.close();+}, hostTimeout(60_000));++type Welcome = { invitedBy: string | null; welcomedAt: number | null; hints: string[] };+const welcomeOf = async (token: string) => (await team.as(token, "GET", "/api/me")).body.welcome as Welcome;++it("names who invited a member as the Admin signed it, never as the member says it; the Owner's names nobody", async () => {+ const ada = (await team.pair(ADA)).token!;+ expect(await welcomeOf(ada)).toEqual({ invitedBy: null, welcomedAt: null, hints: [] });+ const cleo = (await team.pair({ ...CLEO, invitedBy: "[email protected]" } as never)).token!;+ expect((await welcomeOf(cleo)).invitedBy).toBe("[email protected]");+ // A later pairing that says someone else keeps the first: it is who invited them.+ const again = (await team.pair({ ...CLEO, invitedBy: "[email protected]" } as never)).token!;+ expect((await welcomeOf(again)).invitedBy).toBe("[email protected]");+ // Nothing a member sends changes it.+ expect((await team.as(cleo, "PUT", "/api/me/welcome", { invitedBy: "[email protected]", welcomed: true })).status).toBe(200);+ expect((await welcomeOf(cleo)).invitedBy).toBe("[email protected]");+});++it("keeps whether each person saw the welcome, and the steps they finished, for that person alone", async () => {+ const bob = (await team.pair(BOB)).token!, ada = (await team.pair(ADA)).token!;+ const saved = await team.as(bob, "PUT", "/api/me/welcome", { welcomed: true, hints: ["cloud-welcome-done"] });+ expect(saved.status, JSON.stringify(saved.body)).toBe(200);+ expect(saved.body.welcome).toMatchObject({ hints: ["cloud-welcome-done"] });+ expect((await welcomeOf(bob)).welcomedAt).toEqual(expect.any(Number));+ expect(await welcomeOf(ada), "one admin's welcome ends nobody else's").toMatchObject({ welcomedAt: null, hints: [] });+ expect((await team.as(bob, "PUT", "/api/me/welcome", { hints: ["Not a step!"] })).status).toBe(400);+ expect((await team.as(bob, "PUT", "/api/me/welcome", { welcomed: false })).status).toBe(400);+ expect((await team.as(bob, "PUT", "/api/me/welcome", {})).status).toBe(400);+});++it("the Cloud's own welcome for admins: one admin finishing it ends it for that admin alone; its steps stay the team's", async () => {+ const ada = (await team.pair(ADA)).token!, bob = (await team.pair(BOB)).token!;+ const hints = async (token: string) => ((await team.as(token, "GET", "/api/config")).body.onboarding as { hintsSeen: string[] }).hintsSeen;+ const saved = await team.as(bob, "PUT", "/api/config", { onboarding: { hintsSeen: ["cloud-welcome-shown", "cloud-welcome-engine", "cloud-welcome-done"] } });+ expect(saved.status, JSON.stringify(saved.body)).toBe(200);+ expect(await hints(bob)).toEqual(expect.arrayContaining(["cloud-welcome-shown", "cloud-welcome-engine", "cloud-welcome-done"]));+ const adas = await hints(ada);+ expect(adas, "a step is a fact about the team's Cloud").toContain("cloud-welcome-engine");+ expect(adas).not.toContain("cloud-welcome-done");+ expect(adas).not.toContain("cloud-welcome-shown");+});++it("tells a signed-in member, never anyone before sign-in, where their team page on MausBot Cloud is", async () => {+ const cleo = (await team.pair(CLEO)).token!;+ expect((await team.as(cleo, "GET", "/api/auth/session")).body.teamSignIn).toMatch(/\/cloud\/team\/team-acme-1$/);+ const descriptor = await (await fetch(`${team.base}/.well-known/openmausbot/environment`, { headers: fx.edge })).json() as Record<string, unknown>;+ expect(JSON.stringify(descriptor)).not.toContain("/cloud/team/");+});++it("the welcome's one action, a chat with a bot, is the person's own private chat: the new conversation is marked private on the wire at once", async () => {+ const ada = (await team.pair(ADA)).token!, cleo = (await team.pair(CLEO)).token!;+ const made = await team.as(ada, "POST", "/api/bots", { name: "Research", description: "Briefs before a call." });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ const botId = made.body.bot.id as string;+ const opened = await team.as(cleo, "POST", `/api/bots/${botId}/tasks`, {});+ expect(opened.status, JSON.stringify(opened.body)).toBeLessThan(300);+ const threadId = opened.body.task.threadId as string;+ expect(threadId).not.toBe(made.body.bot.mainThreadId);+ expect(opened.body.bot.threadId).toBe(threadId);+ expect((opened.body.bot.tasks as Array<{ threadId: string; private?: boolean }>).find((task) => task.threadId === threadId)?.private).toBe(true);+});++it("a User's copy of a team bot carries what the welcome's one line reads, and a removed person's page is told why", async () => {+ const ada = (await team.pair(ADA)).token!;+ const made = await team.as(ada, "POST", "/api/bots", { name: "Seedling" });+ await team.as(ada, "PATCH", `/api/bots/${made.body.bot.id}`, { soul: "You look after the team's plants." });+ const dee = (await team.pair({ email: "[email protected]", role: "member" })).token!;+ const copy = ((await team.as(dee, "GET", "/api/bots?messages=0")).body.bots as Array<{ id: string; soul?: string }>).find((bot) => bot.id === made.body.bot.id);+ expect(copy?.soul).toBe("You look after the team's plants.");+ expect((await team.signed("POST", "/api/cloud/team/member-left", { email: "[email protected]" })).status).toBe(200);+ const after = await team.as(dee, "GET", "/api/auth/session");+ expect(after.status).toBe(401);+ expect(after.body.error).toBe(TEAM_LEFT_REFUSAL);+ // A session that simply ended says what it always said.+ const expired = await team.as("omb_sess_" + "x".repeat(43), "GET", "/api/auth/session");+ expect(expired.body.error).not.toBe(TEAM_LEFT_REFUSAL);+});diff --git a/server/team-welcome.ts b/server/team-welcome.tsnew file mode 100644index 0000000000..56bb76d442--- /dev/null+++ b/server/team-welcome.ts@@ -0,0 +1,72 @@+// A person's first screen on a Team Cloud, kept for that person alone (people/<person>/welcome.json): who invited them (the+// Admin's signed claim, `member.invitedBy`), when they saw the welcome, and which of the welcome's steps they finished. Each+// is that person's own, so one admin finishing the welcome ends it for nobody else. A member who leaves takes it with them+// (people/<person>/ goes whole), and no backup carries it.+import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";+import { writeFileAtomic } from "./atomic.ts";+import { teamMemberEmail } from "./cloud-team.ts";++const PERSON = /^p_[\w-]{22}$/;+/** A welcome step's id, as the app's onboarding hints are written. */+export const WELCOME_HINT = /^[a-z0-9][a-z0-9-]{0,63}$/;+const MAX_HINTS = 64;+const record = z.object({+ version: z.literal(1),+ invitedBy: z.string().max(254).optional(),+ welcomedAt: z.number().int().positive().optional(),+ hints: z.array(z.string().regex(WELCOME_HINT)).max(MAX_HINTS).optional(),+});++export interface TeamWelcome {+ /** Who invited them, by address, as the Admin said it; null when it never did (an older Admin, or the Owner). */+ invitedBy: string | null;+ /** When they saw their welcome; null until they have. */+ welcomedAt: number | null;+ /** The welcome steps they finished, theirs alone. */+ hints: string[];+}++export interface TeamWelcomeStore {+ read(person: string): TeamWelcome;+ /** The Admin's claim at a pairing: kept the first time it is said, never over an earlier one. */+ invited(person: string, by: string): void;+ /** `welcomed`: they saw it now (kept the first time). `hints`: more finished steps. */+ save(person: string, change: { welcomed?: true; hints?: readonly string[] }, now?: number): TeamWelcome;+}++export function createTeamWelcomeStore(dataDir: string): TeamWelcomeStore {+ const file = (person: string) => {+ if (!PERSON.test(person)) throw new Error("not a person key");+ return join(dataDir, "people", person, "welcome.json");+ };+ const load = (person: string): z.infer<typeof record> => {+ try {+ const path = file(person);+ return existsSync(path) ? record.parse(JSON.parse(readFileSync(path, "utf8"))) : { version: 1 };+ } catch {+ return { version: 1 };+ }+ };+ const write = (person: string, next: z.infer<typeof record>) => {+ mkdirSync(join(dataDir, "people", person), { recursive: true, mode: 0o700 });+ writeFileAtomic(file(person), `${JSON.stringify(next)}\n`, { mode: 0o600 });+ };+ const view = (kept: z.infer<typeof record>): TeamWelcome => ({ invitedBy: kept.invitedBy ?? null, welcomedAt: kept.welcomedAt ?? null, hints: kept.hints ?? [] });+ return {+ read: (person) => view(load(person)),+ invited(person, by) {+ const address = teamMemberEmail(by), kept = load(person);+ if (!address || kept.invitedBy) return;+ write(person, { ...kept, invitedBy: address });+ },+ save(person, change, now = Date.now()) {+ const kept = load(person);+ const hints = [...new Set([...(kept.hints ?? []), ...(change.hints ?? []).filter((hint) => WELCOME_HINT.test(hint))])].slice(0, MAX_HINTS);+ const next = { ...kept, ...(change.welcomed && !kept.welcomedAt ? { welcomedAt: now } : {}), ...(hints.length ? { hints } : {}) };+ if (JSON.stringify(next) !== JSON.stringify(kept)) write(person, next);+ return view(next);+ },+ };+}diff --git a/server/testing/team-inbox-fixture.ts b/server/testing/team-inbox-fixture.tsindex d51b899159..b3d69b5df9 100644--- a/server/testing/team-inbox-fixture.ts+++ b/server/testing/team-inbox-fixture.ts@@ -53,9 +53,10 @@ export function teamInbox(options: { team?: boolean; representative?: TeamMessaggroupByThread: (threadId: string) => groups.find((group) => group.threadId === threadId),tasks: (botId: string) => bots.find((bot) => bot.id === botId)?.tasks ?? [],taskByThread: (botId: string, threadId: string) => bots.find((bot) => bot.id === botId)?.tasks.find((task) => task.threadId === threadId),- createTask: (botId: string, title: string) => {+ createTask: (botId: string, title: string, ...rest: unknown[]) => {const task = { threadId: `made-${++made}`, title };bots.find((bot) => bot.id === botId)!.tasks.push(task);+ (rest[6] as ((made: { threadId: string }) => void) | undefined)?.(task);return task;},appendMessage: (threadId: string, message: Omit<Message, "id" | "at">) => {diff --git a/server/workspace-backup-team-private.test.ts b/server/workspace-backup-team-private.test.tsindex f8d7095636..d858a550db 100644--- a/server/workspace-backup-team-private.test.ts+++ b/server/workspace-backup-team-private.test.ts@@ -9,7 +9,7 @@ import { openRuntimeStore } from "./runtime/store.ts";import type { Assignment } from "./runtime/types.ts";import { createWorkspaceBackupSnapshot, stagedWorkspaceData, stageWorkspaceBackup } from "./workspace-backup.ts";import { ensureMemoryIndex } from "./message-db-memory-index.ts";-import { omittedAsTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts";+import { omittedAsTeamPrivate, routinesWithoutTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts";const BOB = "p_bobbobbobbobbobbobbob1";const PASSWORD = "correct horse battery staple";@@ -108,6 +108,22 @@ describe("what a Team Cloud's export leaves out (the private sentence: not the Oexpect(withoutTeamPrivate([{ id: "bot", tasks: [{ threadId: "main" }, { threadId: "bob-chat" }] }, { id: "bobs-own", tasks: [] }], privacy)).toEqual([{ id: "bot", tasks: [{ threadId: "main" }] }]);});+ it("leaves out the routines that live in a member's private chat and every run that names one", () => {+ const privacy = { threads: new Set(["bob-chat", "bob-results", "bob-run"]), bots: new Set(["bobs-own"]), attachments: new Set<string>() };+ const bots = [{ id: "bot", tasks: [{ threadId: "main", title: "Scout" }, { threadId: "bob-chat", title: "Bob's" }, { threadId: "bob-results", title: "Standup · Results" }] }];+ const routines = { routines: [+ { id: "made-there", botId: "bot", name: "Kumquat", sourceThreadId: "bob-chat" },+ { id: "reports-there", botId: "bot", name: "Quince", resultsThreadId: "bob-chat" },+ { id: "standup", botId: "bot", name: "Standup", resultsThreadId: "bob-results" },+ { id: "own-bot", botId: "bobs-own", name: "Mine" },+ ], runs: [+ { id: "r1", routineId: "made-there", threadId: "other" },+ { id: "r2", routineId: "standup", threadId: "bob-run" },+ { id: "r3", routineId: "standup", threadId: "team-run" },+ ], ownerNotices: [] };+ expect(routinesWithoutTeamPrivate(routines, bots, privacy)).toEqual({ routines: [routines.routines[2]], runs: [routines.runs[2]], ownerNotices: [] });+ });+it("strips the private conversations' rows from the snapshot databases and rebuilds them, so no freed page keeps their words", () => {const root = directory();teamData(root);diff --git a/server/workspace-backup-team-private.ts b/server/workspace-backup-team-private.tsindex e157f864c3..36b6bf2326 100644--- a/server/workspace-backup-team-private.ts+++ b/server/workspace-backup-team-private.ts@@ -6,6 +6,7 @@ import { DatabaseSync } from "node:sqlite";import { isLayerId, layerAudience } from "./audience.ts";import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";+import { routineHome } from "./routine-home.ts";const PERSON = /^p_[\w-]{22}$/;const MARKERS: ReadonlySet<string> = new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]);@@ -73,6 +74,22 @@ export function withoutTeamPrivate(bots: unknown, privacy: TeamPrivacy): unknown: bot));}+/** routines.json without the routines that live in a member's private chat (routine-home.ts) and without any run that+ * names a private conversation: a run carries its prompt and what it wrote. `bots` is bots.json, as stored. */+export function routinesWithoutTeamPrivate(value: unknown, bots: unknown, privacy: TeamPrivacy): unknown {+ if (!record(value)) return value;+ const tasks = new Map<string, { title: string; askedAt?: number }>();+ for (const bot of rows(bots)) for (const task of rows(bot.tasks)) {+ if (typeof task.threadId === "string" && typeof task.title === "string") tasks.set(task.threadId, { title: task.title, ...(typeof task.askedAt === "number" ? { askedAt: task.askedAt } : {}) });+ }+ const privateTo = (threadId: string) => (privacy.threads.has(threadId) ? threadId : null);+ const names = (row: Row, keys: readonly string[]) => keys.some((key) => typeof row[key] === "string" && privacy.threads.has(row[key] as string));+ const routines = rows(value.routines).filter((routine) => !privacy.bots.has(String(routine.botId)) && routineHome(routine, { privateTo, task: (_bot, threadId) => tasks.get(threadId) }) === null);+ const kept = new Set(routines.map((routine) => routine.id));+ const runs = rows(value.runs).filter((run) => kept.has(run.routineId) && !names(run, ["threadId", "resultsThreadId", "sourceThreadId", "executionThreadId"]));+ return { ...value, ...(Array.isArray(value.routines) ? { routines } : {}), ...(Array.isArray(value.runs) ? { runs } : {}) };+}+function chunks(ids: readonly string[]): string[][] {const out: string[][] = [];for (let at = 0; at < ids.length; at += IN_CHUNK) out.push(ids.slice(at, at + IN_CHUNK));diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex c20216f93d..e2a3f6cc56 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -15,7 +15,7 @@ import { userErrorFields, userErrorThrown } from "./user-errors.ts";import { WORKSPACE_BACKUP_CLIENT_KEYS } from "../shared/workspace-backup-client.ts";import { INSTRUCTION_FILE, restorePaths, validRelative } from "./workspace-backup-paths.ts";import { ephemeralWorkspaceTokenPath, excludedWorkspaceAuthPath, liveDataEnginePath, managedTaskSkillLink, portableWorkspaceConfig, redownloadedOrgLibraryPath, restoredWorkspaceConfig } from "./workspace-backup-policy.ts";-import { omittedAsTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts";+import { omittedAsTeamPrivate, routinesWithoutTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts";import type { WorkspaceBackupClientState, WorkspaceBackupPrivateMetadata, WorkspaceBackupSummary, WorkspaceLeftBehind } from "../shared/workspace-backup.ts";export type { WorkspaceBackupSummary, WorkspaceBackupPrivateMetadata } from "../shared/workspace-backup.ts";@@ -389,10 +389,11 @@ export async function createWorkspaceBackupSnapshot(dataDir: string, options: Crwalk(source, path, [...chain, source]);} else if (stat.isFile()) {let copied: { size: number; mode: number; sha256: string };- if (path === "config.json" || path === "webhooks.json" || (privacy && path === "bots.json")) {+ if (path === "config.json" || path === "webhooks.json" || (privacy && (path === "bots.json" || path === "routines.json"))) {const value = privateJson(source);if (path === "config.json") writeJson(destination, portableWorkspaceConfig(value));else if (path === "bots.json") writeJson(destination, withoutTeamPrivate(value, privacy!));+ else if (path === "routines.json") writeJson(destination, routinesWithoutTeamPrivate(value, privateJson(join(root, "bots.json")), privacy!));else {if (!record(value)) throw new Error("Invalid webhook definitions in workspace backup.");if (Array.isArray(value.webhooks)) for (const webhook of value.webhooks) if (record(webhook)) { delete webhook.secretHash; delete webhook.sealedSecret; }diff --git a/shared/bot-owner.ts b/shared/bot-owner.tsindex 8d2437e006..c0a4c11f53 100644--- a/shared/bot-owner.ts+++ b/shared/bot-owner.ts@@ -43,6 +43,12 @@ export function withOneChief<T extends OwnedBot & { id: string }>(bots: readonlyreturn bots.map((bot) => (bot.id === chief.id || !bot.chiefOfStaff || chiefScope(bot) !== scope ? bot : { ...bot, chiefOfStaff: false }));}+/** A person as the People list names them: their name, or for an address, the part before the @ as below. */+export function shownPersonName(name: string): string {+ const trimmed = name.trim();+ return trimmed.includes("@") ? nameFromEmail(trimmed) : trimmed;+}+/** A member's name until their profile has one: the address before the @, capitalised. */export function nameFromEmail(email: string): string {const local = email.split("@")[0]?.replace(/[._-]+/g, " ").trim() || email;diff --git a/shared/cloud-hints.ts b/shared/cloud-hints.tsindex 362d2cf64a..d0733e6a3f 100644--- a/shared/cloud-hints.ts+++ b/shared/cloud-hints.ts@@ -1,2 +1,18 @@/** The onboarding hint a Cloud's welcome records when it is done: the app opens on the Chief's chat from then on. */export const CLOUD_WELCOME_DONE = "cloud-welcome-done";++/** A team session that ended because its person is no longer in the team (removed, or they left): the session read says so,+ * and the page says "You're no longer in <team>." instead of offering a sign-in that can't work. */+export const TEAM_LEFT_REFUSAL = "unauthorized: you are no longer in this team";++/** On a Team Cloud, the welcome's own record (shown, done, hidden) is each person's: one admin finishing it ends it for+ * nobody else. Its steps (an AI connected, files) stay the team's, since they are facts about the team's Cloud. */+export const TEAM_PERSONAL_HINTS: ReadonlySet<string> = new Set(["cloud-welcome-shown", CLOUD_WELCOME_DONE, "cloud-setup-hidden"]);++/**+ * The onboarding record one person on a team reads: the team's, without the welcome's own hints, plus theirs. The Owner+ * also keeps what the team's record already said, which was theirs before the record was per person.+ */+export function personalHints(teamHints: readonly string[], own: readonly string[], owner: boolean): string[] {+ return [...new Set([...teamHints.filter((hint) => owner || !TEAM_PERSONAL_HINTS.has(hint)), ...own.filter((hint) => TEAM_PERSONAL_HINTS.has(hint))])];+}diff --git a/shared/routines.ts b/shared/routines.tsindex e1e8c6d38a..cf01c5cea4 100644--- a/shared/routines.ts+++ b/shared/routines.ts@@ -249,6 +249,10 @@ export interface RoutineInput {access?: RoutineAccess | null;deliver?: RoutineDelivery | null;attachments?: RoutineContextAttachment[];- /** Omission preserves routing; null resets it to the bot's main thread. */+ /** Omission preserves routing; null resets it to the bot's main thread (on a Team Cloud, a results chat everyone who+ * sees the bot reads); RESULTS_JUST_ME, on a Team Cloud only, the person's own private chat with the bot. */resultsThreadId?: string | null;}++/** On a Team Cloud, "Just me": the routine reports into the person's own private chat with the bot, theirs alone. */+export const RESULTS_JUST_ME = "just-me";diff --git a/shared/wire.ts b/shared/wire.tsindex 6890d9111b..8482da3bc9 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -155,6 +155,7 @@ export interface WireTask extends InboxTask {/** Set when a bot, not a person, opened this thread. */ openedBy?: TaskOpenedBy;/** On a team's server: one person's conversation, seen by them alone (never by another member or an admin). */private?: true;+ /** Team Cloud, where several people write, while it works: whose request runs (they or an Owner or Admin stop it). */ askedBy?: ResolvedSender;/** Set by close_thread; absent while the thread is open. */closedBy?: TaskClosedBy;archivedAt?: number;@@ -530,7 +531,7 @@ export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCard* one. Absent reads as the profile name. */sender?: ResolvedSender;/** Provider turn that produced this message. */- turnId?: string;+ turnId?: string; /** A stopped row where several people use the server: who pressed Stop. */ stoppedBy?: ResolvedSender;/** Server-proven originating user message, including supported harness* continuations. Absent means external clients must not infer ownership. */requestMessageId?: string;@@ -923,9 +924,9 @@ export interface RoomHeldMessage {* turn (which runs one at a time per bot). */export type SteerQueueReason = "capacity" | "group-turn";-/** Pending steer-queue chips, as `queuedSteerSnapshot` emits them and the- * `bot.queued` frame carries them: threadId → queued items. */-export type BotQueuedMessages = Record<string, Array<{ queueId: string; text: string; reason?: SteerQueueReason; /** The reason in plain words, shown as it is. */ why?: string }>>;+/** Pending steer-queue chips, as `queuedSteerSnapshot` emits them and the `bot.queued` frame carries them: threadId → queued items. */+export type BotQueuedMessages = Record<string, Array<{ queueId: string; text: string; reason?: SteerQueueReason; /** The reason in plain words, shown as it is. */ why?: string;+ /** Team Cloud, where several people write: whose line waits; only they remove it, and it runs after as their own turn. */ sender?: ResolvedSender }>>;/** Skills library browse surface: one row per library entry, with the bots* currently assigned to it. Version is null for locally imported skills. */diff --git a/src/App.tsx b/src/App.tsxindex 96751a7435..1858271a81 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -52,6 +52,8 @@ import { CloudIntent } from "@/components/CloudIntent";import { cloudIntentDue, cloudIntentShown, useCloudIntent } from "@/lib/cloud-intent";import { CloudSetup } from "@/components/CloudSetup";import { CloudWelcome } from "@/components/cloud-welcome/CloudWelcome";+import { TeamWelcome } from "@/components/TeamWelcome";+import { teamWelcomeDue, useTeamWelcomeRecord } from "@/lib/team-welcome";import { WelcomeKeeper } from "@/components/cloud-welcome/WelcomeKeeper";import { EmptyChatShell } from "@/components/onboarding/EmptyChatShell";import { cloudFirstRun, cloudWelcomeVisible, useCloudWelcome } from "@/lib/cloud-welcome";@@ -170,6 +172,9 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {const welcomeOnScreen = cloudWelcomeVisible({ viewer, connected: state.connected, enginesKnown: state.instances.length > 0, onboarding: state.config?.onboarding }, welcome)&& state.activeView === "chat" && !(!remoteClient && localVmWorkspaceBotId);const firstRun = cloudFirstRun({ welcome: welcomeOnScreen, intent: cloudAsk, signIn: cloudSignIn || cloudJobWaiting });+ const team = state.config?.team ?? null;+ const teamWelcomeRecord = useTeamWelcomeRecord(team && viewer?.canSave === false ? team.id : null);+ const teamWelcomeOn = teamWelcomeDue({ team, canSave: viewer?.canSave, record: teamWelcomeRecord }) && state.activeView === "chat";useEffect(() => {const onKey = (e: KeyboardEvent) => {@@ -376,6 +381,8 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {onClose={() => setLocalVmWorkspaceBotId(null)}onOpenComputer={openComputerFromWorkspace}/>+ ) : teamWelcomeOn && team ? (+ <TeamWelcome team={team} invitedBy={teamWelcomeRecord?.invitedBy ?? null} />) : firstRun === "welcome" ? (<CloudWelcome />) : firstRun === "intent" ? (diff --git a/src/components/AwayEmailsSetting.test.ts b/src/components/AwayEmailsSetting.test.tsnew file mode 100644index 0000000000..474a043b50--- /dev/null+++ b/src/components/AwayEmailsSetting.test.ts@@ -0,0 +1,40 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({ team: true, on: true, calls: [] as { path: string; init?: { method?: string; body?: string } }[] }));+vi.mock("@/state/store", () => ({+ useStore: () => ({ state: { config: fixture.team ? { team: { id: "t1", name: "Acme" } } : {} } }),+ api: async (path: string, init?: { method?: string; body?: string }) => {+ fixture.calls.push({ path, ...(init ? { init } : {}) });+ if (init?.method === "PUT") fixture.on = (JSON.parse(init.body!) as { on: boolean }).on;+ return { on: fixture.on };+ },+}));+const { AwayEmailsSetting } = await import("./AwayEmailsSetting");++let container: HTMLDivElement, root: Root;+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ fixture.team = true; fixture.on = true; fixture.calls = [];+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); });++it("shows the person's own switch on a team, on by default, and turns it off with one click", async () => {+ await act(async () => { root.render(createElement(AwayEmailsSetting, { row: true })); });+ const toggle = container.querySelector<HTMLButtonElement>('[role="switch"]')!;+ expect(container.textContent).toContain("Email me when I'm away");+ expect(toggle.getAttribute("aria-checked")).toBe("true");+ await act(async () => { toggle.click(); });+ expect(fixture.calls.at(-1)).toEqual({ path: "/api/me/away-emails", init: expect.objectContaining({ method: "PUT", body: JSON.stringify({ on: false }) }) });+ expect(toggle.getAttribute("aria-checked")).toBe("false");+});++it("shows nothing and asks nothing off a team", async () => {+ fixture.team = false;+ await act(async () => { root.render(createElement(AwayEmailsSetting, { row: true })); });+ expect(container.innerHTML).toBe("");+ expect(fixture.calls).toEqual([]);+});diff --git a/src/components/AwayEmailsSetting.tsx b/src/components/AwayEmailsSetting.tsxnew file mode 100644index 0000000000..daa10780cc--- /dev/null+++ b/src/components/AwayEmailsSetting.tsx@@ -0,0 +1,37 @@+import { useEffect, useId, useState } from "react";+import { api, useStore } from "@/state/store";+import { t } from "@/lib/i18n";+import { Switch } from "./SettingsPrimitives";++/** Settings → General on a Team Cloud (a row of Account, or in Profile): the person's own "Email me when I'm away"+ * (GET/PUT /api/me/away-emails). Nothing off a team. */+export function AwayEmailsSetting({ row = false }: { row?: boolean }) {+ const team = Boolean(useStore().state.config?.team);+ const [on, setOn] = useState<boolean | null>(null);+ const [failed, setFailed] = useState(false);+ const label = useId();+ useEffect(() => {+ if (!team) return;+ let active = true;+ void api<{ on: boolean }>("/api/me/away-emails", { timeoutMs: 10_000 }).then((answer) => { if (active) setOn(answer.on); }, () => {});+ return () => { active = false; };+ }, [team]);+ const change = (next: boolean) => {+ const before = on;+ setOn(next);+ setFailed(false);+ void api<{ on: boolean }>("/api/me/away-emails", { method: "PUT", body: JSON.stringify({ on: next }), timeoutMs: 10_000 })+ .then((answer) => setOn(answer.on), () => { setOn(before); setFailed(true); });+ };+ if (!team || on === null) return null;+ return (+ <div className={row ? "flex flex-col gap-1 px-4 py-[13px]" : "flex flex-col gap-1"}>+ <div className="flex items-center justify-between gap-3">+ <span id={label} className="text-[14px] text-ink">{t("settings.profile.awayEmails")}</span>+ <Switch aria-labelledby={label} checked={on} onClick={() => change(!on)} />+ </div>+ <div className="text-[12px] text-ink-secondary">{t("settings.profile.awayEmailsHelp")}</div>+ {failed && <div role="alert" className="text-[12px] text-danger">{t("settings.profile.awayEmailsError")}</div>}+ </div>+ );+}diff --git a/src/components/CancelledTurnRow.tsx b/src/components/CancelledTurnRow.tsxindex 99ced929e3..dbed2aad4a 100644--- a/src/components/CancelledTurnRow.tsx+++ b/src/components/CancelledTurnRow.tsx@@ -1,12 +1,22 @@import { RefreshCw } from "lucide-react";import { t } from "@/lib/i18n";+import { useReactor } from "@/lib/cloud-guest";+import { shownPersonName } from "../../shared/bot-owner";import { PERSON_STOPPED_TURN_NAME } from "../../shared/client-cancel";+import type { ResolvedSender } from "../../shared/wire";-/** A stopped turn, never an error. `name` is the row's tool name: a turn the person stopped says so. */-export function CancelledTurnRow({ onRetry, name }: { onRetry?: () => void; name?: string }) {+/** What a stopped row says: who stopped it when that was someone else, "You stopped this." to whoever did. */+export function stoppedWords(name: string | undefined, stoppedBy: ResolvedSender | undefined, viewer: string): string {+ if (name !== PERSON_STOPPED_TURN_NAME) return t("chat.turnStopped");+ return stoppedBy?.id && stoppedBy.id !== viewer ? t("chat.turnStoppedBy", { name: shownPersonName(stoppedBy.name) }) : t("chat.turnStoppedByYou");+}++/** A stopped turn, never an error. `name` is the row's tool name: a turn a person stopped says so, and who. */+export function CancelledTurnRow({ onRetry, name, stoppedBy }: { onRetry?: () => void; name?: string; stoppedBy?: ResolvedSender }) {+ const viewer = useReactor();return (<div role="status" className="flex w-fit max-w-full flex-wrap items-center gap-2 text-[13px] text-ink-secondary">- <span>{t(name === PERSON_STOPPED_TURN_NAME ? "chat.turnStoppedByYou" : "chat.turnStopped")}</span>+ <span>{stoppedWords(name, stoppedBy, viewer)}</span>{onRetry && (<buttontype="button"diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 91f5ca0539..5d627b8769 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -95,7 +95,7 @@ import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffimport { 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";+import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine"; import { ownChatStarted } from "@/state/team-chats";import { useChatFindRequests } from "@/lib/chat-find";import { CitationSelectionToolbar, SentCitations } from "./CitationUI";import { SpeakButton } from "./SpeakButton";@@ -130,7 +130,7 @@ import { PinnedBanner } from "./ChatPinnedBanner";import { highlightCitationSource } from "@/lib/citations-dom";import { useCanWriteIn, useReactor } from "@/lib/cloud-guest";import { formattedReplyWidth, isFormattedReply, splitReplyBlocks } from "@/lib/formatted-reply";-import { otherSpeaker } from "@/lib/own-profile";+import { otherSpeaker } from "@/lib/own-profile"; import { useSharedRun } from "./SharedQueueLine";import { latestFailure, latestReply, type TranscriptSnapshot } from "@/lib/transcript-announcer";import { pendingApprovals } from "./PendingApproval";import { TranscriptAnnouncer } from "./TranscriptAnnouncer";@@ -724,7 +724,7 @@ const MessagesList = memo(function MessagesList({if (isCancelledTranscriptRow(m)) {return (<CancelledTurnRow- onRetry={m.id === lookups.retryableId && canRetryLast ? onRegenerate : undefined} name={m.tool?.name}+ onRetry={m.id === lookups.retryableId && canRetryLast ? onRegenerate : undefined} name={m.tool?.name} stoppedBy={m.stoppedBy}/>);}@@ -913,7 +913,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {() => ({ botId: bot.id, threadId: bot.threadId, botName: bot.name, botColor: bot.color, voiceId: bot.voice, tts, localVoice, hasMore, bots, mentionPeers, mentionPerson: { profileName: state.config?.profile?.name }, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, conversational: isConversational(bot.replyStyle), simple: !advanced, canReact: canWrite !== false, openedAt, speakerViewer }),[bot.id, bot.threadId, bot.name, bot.color, bot.voice, tts, localVoice, hasMore, bots, mentionPeers, state.config?.profile?.name, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, bot.replyStyle, advanced, canWrite, openedAt, speakerViewer],);- const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && currentTask?.private === true, ownHelper = Boolean(team) && !privateChat && Boolean(bot.defaultBot?.person), sharedChat = Boolean(team) && !privateChat && !ownHelper;+ const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && (currentTask?.private === true || ownChatStarted(bot.threadId)), ownHelper = Boolean(team) && !privateChat && Boolean(bot.defaultBot?.person), sharedChat = Boolean(team) && !privateChat && !ownHelper;const [editingId, setEditingId] = useState<string | null>(null);useEffect(() => setEditingId(null), [bot.id, bot.threadId]);@@ -968,7 +968,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {}, 520);}, [lastMessage?.id, lastMessage?.role, lastMessage?.kind]);const teammatesWorking = !advanced && !bot.busy && Boolean(bot.waitingForTeammates);- const presenceVisible = waiting || popping !== null || teammatesWorking;+ const presenceVisible = waiting || popping !== null || teammatesWorking, sharedRun = useSharedRun(bot, advanced);const lastShownRow = windowedMessages.findLast((message) => !quietRow(message, showToolCalls));const presenceUnderBubble = Boolean(lastShownRow && isBotTextRow(lastShownRow, bot.id));const announcement = useMemo((): TranscriptSnapshot => {@@ -1196,7 +1196,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {editingId={editingId}lastBotTextId={lastBotTextId}emergingId={popping}- canRetryLast={!bot.busy && Boolean(lastUserMessage)}+ canRetryLast={!bot.busy && Boolean(lastUserMessage) && sharedRun.mayAct(lastUserMessage?.sender)}engine={state.instances.find((i) => i.instanceId === bot.modelSelection.instanceId)}unreadDividerId={unreadDivider.messageId}unreadDividerFading={unreadDivider.fading}@@ -1239,14 +1239,14 @@ export function ChatView({ bot: profile }: { bot: Bot }) {}simple={!advanced}className={cn(!advanced && presenceUnderBubble && SIMPLE_STACKED)}- label={teammatesWorking ? t("chat.teammatesWorking") : undefined}+ label={teammatesWorking ? t("chat.teammatesWorking") : sharedRun.label}visible={presenceVisible}{...now}phrases={teammatesWorking ? undefined : now.phrases}seed={`${bot.id}:${bot.threadId ?? ""}:${busySince ?? ""}`}answering={popping !== null}since={busySince}- />+ />{presenceVisible && sharedRun.line}</div></div>diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex 75fe2f5d31..3218b03e3a 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -31,7 +31,7 @@ import {type ComposerSendSnapshot,type FailedComposerSend,} from "@/lib/drafts";-import { DEVS_CHOICE, MentionMenu, teammateChoices, type MentionChoice } from "./MentionMenu"; import { useTeammates } from "@/state/team-people"; import { hiddenFromSidebar, useViewerEmail } from "@/lib/default-bot";+import { DEVS_CHOICE, MentionMenu, teammateChoices, type MentionChoice } from "./MentionMenu"; import { useTeammates } from "@/state/team-people"; import { hiddenFromSidebar, useViewerEmail } from "@/lib/default-bot"; import { useMayAct } from "./SharedQueueLine";import { SlashCommandMenu } from "./SlashCommandMenu";import { MentionTextarea } from "./MentionTextarea";import { ComposerAttachments, pathForFile } from "./ComposerAttachments";@@ -403,8 +403,9 @@ export function Composer({requestAnimationFrame(() => { inputRef.current?.focus(); inputRef.current?.setSelectionRange(learn.length, learn.length); });};- const pendingCount = (state.pendingQueued[threadId] ?? []).length;- const queuedMessages = state.pendingQueued[threadId] ?? [];+ const sharedChat = Boolean(state.config?.team && !group && profile?.tasks?.some((task) => task.threadId === threadId && !task.private));+ const queuedMessages = sharedChat ? [] : state.pendingQueued[threadId] ?? [];+ const pendingCount = queuedMessages.length;const canSteerQueued = composerCanSteerQueuedMessages(busy,locked,@@ -502,7 +503,8 @@ export function Composer({const media = useLiveMedia();const callTarget = group?.id ?? bot?.id;const calling = callTarget !== undefined && (onCall === callTarget || (isLiveCallRunning(media.phase) && media.botId === callTarget));- const stoppable = busy || Boolean(!group && bot?.waitingForTeammates);+ const mayAct = useMayAct(), mayStop = !sharedChat || mayAct(profile?.tasks?.find((task) => task.threadId === threadId)?.askedBy);+ const stoppable = (busy || Boolean(!group && bot?.waitingForTeammates)) && mayStop;// Simple mode's round button is the call, Send while there is text, and Stop while the bot works.const stopInSlot = simpleDock && stoppable && !locked && !hasContent && !calling;const callShown = !simpleDock || (!hasContent && !stopInSlot);@@ -924,7 +926,7 @@ export function Composer({)}/><div data-composer-actions className={cn("flex items-center", simpleDock ? "gap-2" : "gap-1", !singleRow && !simpleDock && "@max-[30rem]/composer:ml-auto", stacked && "ml-auto")}>- {(simpleDock ? stoppable : busy) && !locked && (+ {(simpleDock ? stoppable : busy && mayStop) && !locked && (<buttononClick={interruptTurn}aria-label={t("chat.stopTurn")}diff --git a/src/components/MausBotWelcome.tsx b/src/components/MausBotWelcome.tsxindex 4379605371..15f53ad6aa 100644--- a/src/components/MausBotWelcome.tsx+++ b/src/components/MausBotWelcome.tsx@@ -1,4 +1,5 @@import { useEffect, useRef, useState, type DragEvent } from "react";+import { teamWelcomeShownThisLaunch } from "@/lib/team-welcome";import { createPortal } from "react-dom";import { BookOpen, Crown, Pencil, Sparkles, Wand2 } from "lucide-react";@@ -44,6 +45,10 @@ export function mausBotWelcomeDue(input: { bot: Pick<Bot, "welcomed" | "hidden">return Boolean(input.bot && !input.bot.welcomed && !input.bot.hidden && !input.onboardingDue && !input.welcomeOpen && !input.tourOpen);}+/** On a team the team's welcome introduced things, and a run under way is never interrupted by the card. */+export const teamQuiet = (state: { config?: { team?: unknown } | null; bots: ReadonlyArray<{ busy?: boolean }> }): boolean =>+ Boolean(state.config?.team) && (teamWelcomeShownThisLaunch() || state.bots.some((candidate) => candidate.busy));+/** MausBot's first-launch card is due now (mausBotWelcomeDue), and, like the Cloud Pro popup and the product-updates* question, waits for the first reply (unknown until the bots load), for a launch after the one whose welcome finished, and* for a launch the notices queue has not already used. The notices queue asks this too, so the card goes first. */@@ -57,7 +62,7 @@ export function useMausBotWelcomeDue(viewer: WelcomeViewer | null): { bot: Bot |hosted: viewer.hosted, canSave: viewer.canSave, cloudHome: viewer.cloudHome,});const due = Boolean(state.config) && mausBotWelcomeDue({ bot, onboardingDue, welcomeOpen: state.welcomeOpen, tourOpen: touring })- && firstReplyPending(state) === false && !welcomeFinishedThisLaunch() && launchDialogShown() !== "notices";+ && firstReplyPending(state) === false && !welcomeFinishedThisLaunch() && launchDialogShown() !== "notices" && !teamQuiet(state);return { bot, due };}diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex 841a2b67a7..41f56bcd1a 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -51,6 +51,7 @@ import { ChatWidthRow, FontRow, SidebarToolsLayoutRow } from "./AppearanceSelectimport { RoomTurnTimeoutSettings } from "./RoomTurnTimeoutSettings";import { McpCallTimeoutSettings } from "./McpCallTimeoutSettings";import { ProfileFields } from "./ProfileSettings";+import { AwayEmailsSetting } from "./AwayEmailsSetting";import { ThreadConcurrencySettings } from "./ThreadConcurrencySettings";import { AutomaticRecoverySettings } from "./AutomaticRecoverySettings";import { ThreadCleanupSettings } from "./ThreadCleanupSettings";@@ -356,6 +357,7 @@ export function SettingsModal() {<CloudUsageSettings /><Card title={t("settings.profile.title")} subtitle={t("settings.profile.sharedSubtitle")}><ProfileFields />+ <AwayEmailsSetting /></Card><LanguageRow />diff --git a/src/components/SettingsSimplePages.tsx b/src/components/SettingsSimplePages.tsxindex 7489bed875..6b547a8c4f 100644--- a/src/components/SettingsSimplePages.tsx+++ b/src/components/SettingsSimplePages.tsx@@ -32,6 +32,7 @@ import { PlaceLookRows } from "./PlaceLookCard";import { ChromeRailRow } from "./ChromeRailToggle";import { WindowFrameRow } from "./WindowFrameRow";import { ProfileSummaryRow } from "./ProfileSettings";+import { AwayEmailsSetting } from "./AwayEmailsSetting";import { ImportSettings } from "./ImportSettings";import { NotificationRows } from "./NotificationSettingsRows";import { useServerUpdateItem } from "./SidebarProfileMenu";@@ -69,6 +70,7 @@ export function SimpleGeneralPage({ has, peopleOpen, onLooks, onMore }: { has: H<SettingsGroup label={t("settings.group.account")} block="general"><SettingsRows>{has("general") && <ProfileSummaryRow />}+ {has("general") && <AwayEmailsSetting row />}{has("general") && <CloudPlanRow place="account" />}{has("people") && <div data-settings-block="people" className="scroll-mt-4"><PeopleSection simple startOpen={peopleOpen} /></div>}</SettingsRows>diff --git a/src/components/SharedQueueLine.test.ts b/src/components/SharedQueueLine.test.tsnew file mode 100644index 0000000000..841898e0e8--- /dev/null+++ b/src/components/SharedQueueLine.test.ts@@ -0,0 +1,63 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";++import { SharedQueueLine, mayActOn, nextLine, workingForLabel } from "./SharedQueueLine";+import { stoppedWords } from "./CancelledTurnRow";+import { PERSON_STOPPED_TURN_NAME, STOPPED_TURN_NAME } from "../../shared/client-cancel";++const priya = { name: "Priya", id: "p_priya" }, tom = { name: "Tom", id: "p_tom" }, sam = { name: "Sam", id: "p_sam" };+const line = (waiting: Array<{ queueId: string; text: string; sender?: { name: string; id?: string } }>, viewer: string) =>+ renderToStaticMarkup(createElement(SharedQueueLine, { waiting, viewer, onRemove: () => {} }));++describe("the shared chat's quiet queue line", () => {+ it("says whose request runs", () => {+ expect(workingForLabel(priya, "p_tom")).toBe("Working on Priya's request");+ expect(workingForLabel(priya, "p_priya")).toBe("Working on your request");+ expect(workingForLabel(undefined, "p_tom")).toBeUndefined();+ });++ it("names only what runs next, and how many more wait", () => {+ const w = (queueId: string, sender: { name: string; id: string }) => ({ queueId, text: "", sender });+ expect(nextLine([], "p_priya")).toBeNull();+ expect(nextLine([w("q1", tom)], "p_priya")).toBe("Next: Tom's request");+ expect(nextLine([w("q1", tom), w("q2", sam), w("q3", priya)], "p_priya")).toBe("Next: Tom's request, then 2 more");+ expect(nextLine([w("q1", tom)], "p_tom")).toBe("Next: your request");+ expect(nextLine([w("q1", tom), w("q2", sam)], "p_tom")).toBe("Next: your request, then 1 more");+ });++ it("shows the writer their own waiting words with its remove control, and nobody else those words", () => {+ const waiting = [{ queueId: "q1", text: "What is due?", sender: tom }, { queueId: "q2", text: "Book the room", sender: sam }];+ const priyaSees = line(waiting, "p_priya");+ expect(priyaSees).not.toContain("Remove your waiting message");+ expect(priyaSees).not.toContain("What is due?");+ expect(priyaSees).not.toContain("Book the room");+ const samSees = line(waiting, "p_sam");+ expect(samSees).toContain("Remove your waiting message");+ expect(samSees).toContain("Yours: Book the room");+ expect(samSees).not.toContain("What is due?");+ expect(line([], "p_sam")).toBe("");+ });++ it("names a person with no name set as the People list does", () => {+ expect(nextLine([{ queueId: "q1", text: "", sender: { name: "[email protected]", id: "p_dev" } }], "p_priya")).toBe("Next: Dev's request");+ expect(workingForLabel({ name: "[email protected]", id: "p_mary" }, "p_tom")).toBe("Working on Mary Ann Lee's request");+ });++ it("lets only the asker, an admin, or anyone for a run no person asked for, stop or retry", () => {+ expect(mayActOn(priya, "p_priya", false)).toBe(true);+ expect(mayActOn(priya, "p_tom", false)).toBe(false);+ expect(mayActOn(priya, "p_tom", true)).toBe(true);+ expect(mayActOn(undefined, "p_tom", false)).toBe(true);+ expect(mayActOn({ name: "Slack" }, "p_tom", false)).toBe(true);+ });++ it("says who stopped a run: their name to everyone else, you to them", () => {+ const maya = { name: "Maya Shah", id: "p_maya" };+ expect(stoppedWords(PERSON_STOPPED_TURN_NAME, maya, "p_priya")).toBe("Maya Shah stopped this.");+ expect(stoppedWords(PERSON_STOPPED_TURN_NAME, maya, "p_maya")).toBe("You stopped this.");+ expect(stoppedWords(PERSON_STOPPED_TURN_NAME, { name: "[email protected]", id: "p_dev" }, "p_priya")).toBe("Dev stopped this.");+ expect(stoppedWords(PERSON_STOPPED_TURN_NAME, undefined, "user")).toBe("You stopped this.");+ expect(stoppedWords(STOPPED_TURN_NAME, maya, "p_priya")).toBe("Stopped");+ });+});diff --git a/src/components/SharedQueueLine.tsx b/src/components/SharedQueueLine.tsxnew file mode 100644index 0000000000..d22ec64afa--- /dev/null+++ b/src/components/SharedQueueLine.tsx@@ -0,0 +1,89 @@+import { X } from "lucide-react";+import type { ReactNode } from "react";++import { shownPersonName } from "../../shared/bot-owner";+import type { ResolvedSender } from "../../shared/wire";+import { useReactor } from "@/lib/cloud-guest";+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { useStore, type Bot } from "@/state/store";++type Waiting = { queueId: string; text: string; sender?: ResolvedSender };++/** The working line's lead in a conversation several people write in: whose request runs. */+export function workingForLabel(askedBy: ResolvedSender | undefined, viewer: string): string | undefined {+ if (!askedBy) return undefined;+ return askedBy.id === viewer ? t("chat.queue.workingForYou") : t("chat.queue.workingFor", { name: shownPersonName(askedBy.name) });+}++/** "Next: Tom's request, then 2 more", or null when nothing waits. */+export function nextLine(waiting: readonly Waiting[], viewer: string): string | null {+ const [head] = waiting;+ if (!head) return null;+ const mine = head.sender?.id === viewer;+ const name = shownPersonName(head.sender?.name ?? "");+ const more = waiting.length - 1;+ if (more > 0) return mine ? t("chat.queue.nextYoursMore", { count: more }) : t("chat.queue.nextMore", { name, count: more });+ return mine ? t("chat.queue.nextYours") : t("chat.queue.next", { name });+}++/** Where several people write, whether the viewer may stop or retry what `asker` asked: their own, a run no person+ * asked for, or any as an Owner or Admin (shown while that is still unknown; the server refuses the rest). */+export function mayActOn(asker: ResolvedSender | undefined, viewer: string, admin: boolean | null): boolean {+ return !asker?.id || asker.id === viewer || admin !== false;+}++export function useMayAct(): (asker: ResolvedSender | undefined) => boolean {+ const viewer = useReactor();+ const admin = useOwnerOrAdmin();+ return (asker) => mayActOn(asker, viewer, admin);+}++/** One quiet line under the working line: what runs next. The viewer's own waiting message shows to them alone, with+ * its remove control. */+export function SharedQueueLine({ waiting, viewer, onRemove, className }: {+ waiting: readonly Waiting[];+ viewer: string;+ onRemove: (queueId: string) => void;+ className?: string;+}) {+ const line = nextLine(waiting, viewer);+ if (!line) return null;+ const own = waiting.find((item) => item.sender?.id === viewer);+ return (+ <div className={cn("flex min-w-0 flex-col text-[12px] text-ink-tertiary", className)} data-shared-queue>+ <span className="truncate">{line}</span>+ {own && (+ <span className="flex min-w-0 items-center gap-1">+ <span dir="auto" className="truncate">{t("chat.queue.yoursWaiting", { text: own.text })}</span>+ <button+ type="button"+ onClick={() => onRemove(own.queueId)}+ aria-label={t("chat.queue.removeYours")}+ title={t("chat.queue.removeYours")}+ className="flex size-5 shrink-0 items-center justify-center rounded text-ink-tertiary outline-none hover:bg-raised-hover hover:text-ink focus-visible:ring-2 focus-visible:ring-accent/60"+ >+ <X size={12} aria-hidden="true" />+ </button>+ </span>+ )}+ </div>+ );+}++/** In a Team Cloud conversation several people write in: the working line's lead, the quiet line under it, and whether+ * the viewer may act on a request someone made. */+export function useSharedRun(bot: Bot, advanced: boolean): { label?: string; line: ReactNode; mayAct: (asker: ResolvedSender | undefined) => boolean } {+ const { state, dispatch } = useStore();+ const viewer = useReactor();+ const mayAct = useMayAct();+ const task = state.config?.team ? bot.tasks?.find((one) => one.threadId === bot.threadId && !one.private) : undefined;+ if (!task) return { line: null, mayAct: () => true };+ return {+ label: workingForLabel(task.askedBy, viewer),+ line: <SharedQueueLine waiting={state.pendingQueued[bot.threadId] ?? []} viewer={viewer} className={advanced ? "ps-11" : "ps-12"}+ onRemove={(queueId) => dispatch({ type: "cancelQueued", botId: bot.id, threadId: bot.threadId, queueId })} />,+ mayAct,+ };+}diff --git a/src/components/StatusActivityRow.tsx b/src/components/StatusActivityRow.tsxindex 9f6f2c0f5a..807f186c8b 100644--- a/src/components/StatusActivityRow.tsx+++ b/src/components/StatusActivityRow.tsx@@ -12,7 +12,7 @@ export function StatusActivityRow({ message }: { message: Message }) {const { dispatch } = useStore();const status = statusActivity(message);if (!status) return null;- if (status.kind === "stopped") return <CancelledTurnRow name={message.tool?.name} />;+ if (status.kind === "stopped") return <CancelledTurnRow name={message.tool?.name} stoppedBy={message.stoppedBy} />;if (message.tool?.rescue) return <FirstReplyRescueRow rescue={message.tool.rescue} text={status.text} at={message.at} />;const Icon = status.kind === "recovery" ? RefreshCw : Info;// A notice that signing in fixes (an AI signed out) opens the place to sign in again.diff --git a/src/components/TeamPrivateChatsLine.tsx b/src/components/TeamPrivateChatsLine.tsxindex 33d19841ca..ea4f00ef3c 100644--- a/src/components/TeamPrivateChatsLine.tsx+++ b/src/components/TeamPrivateChatsLine.tsx@@ -16,6 +16,11 @@ export function teamPrivateChatsLineDue(teamId: string, storage: Pick<Storage, "}}+/** The team's welcome said it: the first private chat doesn't say it again. */+export function markTeamPrivateChatsLineSaid(teamId: string, storage: Pick<Storage, "getItem" | "setItem"> | null = typeof localStorage === "undefined" ? null : localStorage): void {+ try { if (storage && !storage.getItem(SEEN_KEY(teamId))) storage.setItem(SEEN_KEY(teamId), String(Date.now())); } catch {}+}+/** In every private chat with a team's bot, beside its name: who can see it. */export function TeamPrivateHeader() {return <ChatHeadAudience icon={<Lock size={12} aria-hidden="true" className="shrink-0" />} label={t("team.privateHeader")} data-chathead-private="" />;diff --git a/src/components/TeamWelcome.test.ts b/src/components/TeamWelcome.test.tsnew file mode 100644index 0000000000..c35fe0be49--- /dev/null+++ b/src/components/TeamWelcome.test.ts@@ -0,0 +1,145 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { setLocale } from "@/lib/i18n";++const fixture = vi.hoisted(() => ({ state: {} as any, dispatch: vi.fn(), api: vi.fn(), people: null as any }));+vi.mock("@/state/store", async (original) => ({+ ...await original<typeof import("@/state/store")>(),+ useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }),+ api: fixture.api,+}));+vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => true }));+vi.mock("@/state/team-people", async (original) => ({ ...await original<typeof import("@/state/team-people")>(), useTeamPeople: () => fixture.people }));+import { TeamWelcome } from "./TeamWelcome";+import { teamPrivateChatsLineDue } from "./TeamPrivateChatsLine";+import { finishTeamWelcome, markTeamWelcomeShown, parseTeamWelcome, resetTeamWelcome, teamWelcomeDue, teamWelcomeView, WELCOME_USE_MS } from "@/lib/team-welcome";+import { teamQuiet } from "./MausBotWelcome";++const ACME = { id: "team-acme", name: "Acme" };+const people = [+ { email: "[email protected]", name: "Sam", role: "member", you: true as const },+ { email: "[email protected]", name: "Ada Lovelace", role: "owner", pictureUrl: "/api/team/people/p_a/picture?v=1" },+ { email: "[email protected]", name: "", role: "admin" },+];+const bot = (id: string, name: string, extra: Record<string, unknown> = {}) => ({ id, name, title: "", description: "", tasks: [], threadId: `${id}-main`, mainThreadId: `${id}-main`, avatarCrop: "mascot", ...extra });+const bots = [+ bot("mine", "MausBot", { defaultBot: { person: "[email protected]" } }),+ bot("payroll", "Payroll", { description: "Runs payroll every month.\nAsk it anything about pay.", yourAccess: "view" }),+ bot("support", "Support", { title: "Answers customers" }),+ bot("old", "Old", { hidden: true }),+];++let container: HTMLDivElement, root: Root;+beforeEach(() => {+ const stored = new Map<string, string>();+ vi.stubGlobal("localStorage", { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => { stored.set(key, value); }, removeItem: (key: string) => { stored.delete(key); } });+ setLocale("en");+ resetTeamWelcome();+ fixture.dispatch.mockReset(); fixture.api.mockReset().mockResolvedValue({});+ fixture.state = { bots, groups: [], config: { team: ACME } };+ fixture.people = { people, me: people[0], admin: false, needsYou: [] };+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);+});+afterEach(() => { root.unmount(); container.remove(); });+const render = (invitedBy: string | null = "[email protected]") => flushSync(() => root.render(createElement(TeamWelcome, { team: ACME, invitedBy })));++describe("a new member's first screen in a team", () => {+ it("names the team and who invited them, shows who else is in it and the bots shared with them, says the privacy rule once, and offers one chat", () => {+ render();+ expect(container.querySelector("h1")?.textContent).toBe("Welcome to Acme");+ expect(container.querySelector("[data-team-welcome-invited]")?.textContent).toBe("Ada Lovelace invited you to Acme.");+ expect([...container.querySelectorAll("[data-team-welcome-person] span.truncate")].map((row) => row.textContent)).toEqual(["Ada Lovelace", "[email protected]"]);+ expect(container.querySelector('[data-team-welcome-person="[email protected]"] img')?.getAttribute("src")).toBe("/api/team/people/p_a/picture?v=1");+ // Their own MausBot isn't shared with them, and a hidden bot isn't shown; one line each.+ expect([...container.querySelectorAll("[data-team-welcome-bot]")].map((row) => row.textContent)).toEqual(["PayrollRuns payroll every month.", "SupportAnswers customers"]);+ expect(container.querySelectorAll("[data-team-private-chats]")).toHaveLength(1);+ expect(container.querySelector("[data-team-private-chats]")?.textContent).toBe("Your chats in Acme are private. Only you can see them: not other members, not Acme's admins.");+ expect(teamPrivateChatsLineDue(ACME.id, localStorage), "the first private chat won't say it again").toBe(false);+ // A bot they can only view is not the first chat.+ const buttons = [...container.querySelectorAll("button")].map((button) => button.textContent);+ expect(buttons).toEqual(["Start a chat with Support", "Not now"]);+ });++ it("the one action opens a chat with that bot and keeps the welcome seen, for this person, on the team's Cloud", async () => {+ render();+ flushSync(() => [...container.querySelectorAll("button")].find((button) => button.textContent === "Start a chat with Support")!.click());+ expect(fixture.api).toHaveBeenCalledWith("/api/me/welcome", { method: "PUT", body: JSON.stringify({ welcomed: true }), timeoutMs: 10_000 });+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "showChat" });+ expect(fixture.dispatch.mock.calls.some(([action]) => action.type === "select" && action.id === "support" || action.botId === "support")).toBe(true);+ });++ it("an older Admin that never said who invited them, or nobody else and no bots yet: still plain, with one way on", () => {+ fixture.people = { people: [people[0]], me: people[0], admin: false, needsYou: [] };+ fixture.state = { ...fixture.state, bots: [bots[0]] };+ render(null);+ expect(container.querySelector("[data-team-welcome-invited]")?.textContent).toBe("You’re in Acme now.");+ expect(container.querySelector("[data-team-welcome-person]")).toBeNull();+ expect(container.textContent).toContain("No bots are shared with you in Acme yet. Your own MausBot is in the sidebar.");+ expect([...container.querySelectorAll("button")].map((button) => button.textContent)).toEqual(["Look around"]);+ });+});++describe("when it shows", () => {+ it("only to a User of a team who hasn't seen it, once their record is read; an Admin has the Cloud's own welcome", () => {+ const fresh = { invitedBy: null, welcomedAt: null, hints: [] };+ expect(teamWelcomeDue({ team: ACME, canSave: false, record: fresh })).toBe(true);+ expect(teamWelcomeDue({ team: ACME, canSave: false, record: { ...fresh, welcomedAt: 1 } })).toBe(false);+ expect(teamWelcomeDue({ team: ACME, canSave: false, record: undefined }), "not yet read").toBe(false);+ expect(teamWelcomeDue({ team: ACME, canSave: false, record: null }), "a Team Cloud too old to keep one").toBe(false);+ expect(teamWelcomeDue({ team: ACME, canSave: true, record: fresh })).toBe(false);+ expect(teamWelcomeDue({ team: null, canSave: false, record: fresh })).toBe(false);+ });++ it("reads the record as the server keeps it, and nothing else", () => {+ expect(parseTeamWelcome({ invitedBy: "[email protected]", welcomedAt: 5, hints: ["a", 3] })).toEqual({ invitedBy: "[email protected]", welcomedAt: 5, hints: ["a"] });+ expect(parseTeamWelcome({ invitedBy: "nobody", welcomedAt: -1 })).toEqual({ invitedBy: null, welcomedAt: null, hints: [] });+ expect(parseTeamWelcome(undefined)).toBeNull();+ });++ it("an inviter not on the people list yet is named by their address; a long team shows a few and how many more", () => {+ const many = Array.from({ length: 9 }, (_, index) => ({ email: `p${index}@acme.test`, name: `P${index}`, role: "member" }));+ const view = teamWelcomeView({ invitedBy: "[email protected]", people: many, bots: [] });+ expect(view.inviter).toEqual({ email: "[email protected]", name: "", role: "member" });+ expect([view.people.length, view.morePeople]).toEqual([6, 3]);+ expect(view.first).toBeNull();+ });++ it("seen here goes at once, even when the team's Cloud can't save it now", async () => {+ fixture.api.mockRejectedValue(new Error("offline"));+ await finishTeamWelcome(ACME.id);+ expect(fixture.api).toHaveBeenCalledTimes(1);+ });+});++describe("its manners", () => {+ it("puts focus on the one action, not a ring on the heading, and a bot with no description gets a quiet line from what its copy carries", () => {+ fixture.state = { ...fixture.state, bots: [...bots, bot("seed", "Seedling", { soul: "# Seedling\n\nYou look after the team's plants." })] };+ render();+ expect(document.activeElement?.textContent).toBe("Start a chat with Support");+ expect(container.querySelector("h1")?.getAttribute("tabindex")).toBeNull();+ expect(container.querySelector('[data-team-welcome-bot="seed"]')?.textContent).toBe("SeedlingYou look after the team's plants.");+ const view = teamWelcomeView({ invitedBy: null, people: [], bots: [bot("bare", "Bare"), bot("soul", "Soul", { soul: "\n> You answer questions about pay.\n" })] });+ expect(view.bots.map((entry) => entry.line)).toEqual(["", "You answer questions about pay."]);+ });++ it("counts as using the team while it is on screen and the page is visible", () => {+ vi.useFakeTimers();+ try {+ render();+ fixture.api.mockClear();+ vi.advanceTimersByTime(WELCOME_USE_MS);+ expect(fixture.api).toHaveBeenCalledWith("/api/me", expect.objectContaining({ background: true }));+ } finally { vi.useRealTimers(); }+ });++ it("MausBot's own card doesn't interrupt a team's first run: not after the team's welcome in this launch, never over a run", () => {+ expect(teamQuiet({ config: { team: ACME }, bots: [{ busy: true }] })).toBe(true);+ expect(teamQuiet({ config: { team: ACME }, bots: [{ busy: false }] })).toBe(false);+ markTeamWelcomeShown();+ expect(teamQuiet({ config: { team: ACME }, bots: [] })).toBe(true);+ expect(teamQuiet({ config: {}, bots: [{ busy: true }] }), "off a team as before").toBe(false);+ });+});diff --git a/src/components/TeamWelcome.tsx b/src/components/TeamWelcome.tsxnew file mode 100644index 0000000000..ce72f913db--- /dev/null+++ b/src/components/TeamWelcome.tsx@@ -0,0 +1,85 @@+import { useEffect, useRef } from "react";+import { Lock } from "lucide-react";+import { WindowDragStrip } from "@/components/DesktopCapabilities";+import { PRIMARY, QUIET } from "@/components/cloud-welcome/parts";+import { PersonFace } from "@/components/TeamOwner";+import { markTeamPrivateChatsLineSaid } from "@/components/TeamPrivateChatsLine";+import { BotAvatar } from "@/components/Avatar";+import { t } from "@/lib/i18n";+import { finishTeamWelcome, markTeamWelcomeShown, teamWelcomeView, WELCOME_USE_MS } from "@/lib/team-welcome";+import { useShowThreads } from "@/lib/thread-preferences";+import { api, openBot, useStore } from "@/state/store";+import { useTeamPeople } from "@/state/team-people";++/**+ * A User's first screen in a team, once: the team by its name and who invited them, who else is in it, the bots shared with+ * them, the one privacy rule, and one thing to do, a chat with a bot. Seen is kept on the team's Cloud for this person alone+ * (PUT /api/me/welcome), so it shows once whichever device they open first, in the app or a browser.+ */+export function TeamWelcome({ team, invitedBy }: { team: { id: string; name: string }; invitedBy: string | null }) {+ const { state, dispatch } = useStore();+ const showThreads = useShowThreads();+ const people = useTeamPeople();+ const view = teamWelcomeView({ invitedBy, people: people?.people ?? [], bots: state.bots });+ const action = useRef<HTMLButtonElement>(null);+ useEffect(() => {+ action.current?.focus({ preventScroll: true });+ markTeamPrivateChatsLineSaid(team.id);+ markTeamWelcomeShown();+ }, [team.id]);+ // Reading this page is using the team, as any screen is: while it is in front of them, the session hears from them.+ useEffect(() => {+ const timer = setInterval(() => { if (document.visibilityState === "visible") void api("/api/me", { timeoutMs: 10_000, background: true }).catch(() => {}); }, WELCOME_USE_MS);+ return () => clearInterval(timer);+ }, []);+ const done = () => { void finishTeamWelcome(team.id); };+ const start = () => {+ done();+ dispatch({ type: "showChat" });+ const bot = state.bots.find((candidate) => candidate.id === view.first?.id);+ if (bot) openBot(dispatch, bot, showThreads);+ };+ const inviter = view.inviter ? view.inviter.name.trim() || view.inviter.email : null;+ return <main data-team-welcome className="relative flex h-full min-w-0 flex-1 flex-col overflow-y-auto bg-app">+ <WindowDragStrip />+ <div className="mx-auto flex w-full max-w-[560px] flex-col gap-6 px-5 pb-12 pt-10 max-md:pt-14">+ <header className="flex flex-col gap-1.5">+ <h1 className="text-[22px] font-semibold tracking-[-0.015em] text-ink [text-wrap:balance]">{t("teamWelcome.title", { team: team.name })}</h1>+ <p data-team-welcome-invited className="text-[14px] leading-relaxed text-ink-secondary">+ {inviter ? t("teamWelcome.invited", { person: inviter, team: team.name }) : t("teamWelcome.invitedNobody", { team: team.name })}+ </p>+ </header>+ {view.people.length > 0 && <section aria-labelledby="team-welcome-people" className="flex flex-col gap-2">+ <h2 id="team-welcome-people" className="text-[13px] font-medium text-ink-secondary">{t("teamWelcome.people", { team: team.name })}</h2>+ <ul className="flex flex-wrap gap-x-4 gap-y-2">+ {view.people.map((person) => <li key={person.email} data-team-welcome-person={person.email} className="flex min-w-0 items-center gap-2 text-[14px] text-ink">+ <PersonFace person={{ ...person, name: person.name.trim() || person.email }} size={24} /><span className="truncate">{person.name.trim() || person.email}</span>+ </li>)}+ {view.morePeople > 0 && <li className="text-[14px] text-ink-secondary">{t("teamWelcome.more", { count: view.morePeople })}</li>}+ </ul>+ </section>}+ <section aria-labelledby="team-welcome-bots" className="flex flex-col gap-2">+ <h2 id="team-welcome-bots" className="text-[13px] font-medium text-ink-secondary">{t("teamWelcome.bots")}</h2>+ {view.bots.length ? <ul className="flex flex-col gap-2">+ {view.bots.map((bot) => {+ const full = state.bots.find((candidate) => candidate.id === bot.id);+ return <li key={bot.id} data-team-welcome-bot={bot.id} className="flex min-w-0 items-start gap-3 rounded-xl border border-hairline/50 bg-card/50 p-3">+ {full && <BotAvatar bot={full} size={28} />}+ <span className="min-w-0"><span className="block truncate text-[14px] font-medium text-ink">{bot.name}</span>+ {bot.line && <span className="block truncate text-[13px] text-ink-secondary">{bot.line}</span>}</span>+ </li>;+ })}+ {view.moreBots > 0 && <li className="text-[13px] text-ink-secondary">{t("teamWelcome.moreBots", { count: view.moreBots })}</li>}+ </ul> : <p className="text-[14px] text-ink-secondary">{t("teamWelcome.noBots", { team: team.name })}</p>}+ </section>+ <p data-team-private-chats className="flex items-start gap-2 text-[13px] leading-relaxed text-ink-secondary">+ <Lock size={14} aria-hidden="true" className="mt-0.5 shrink-0" />{t("team.privateChats", { team: team.name })}+ </p>+ <div className="flex flex-wrap items-center gap-2">+ {view.first ? <button ref={action} type="button" className={PRIMARY} onClick={start}>{t("teamWelcome.start", { bot: view.first.name })}</button>+ : <button ref={action} type="button" className={PRIMARY} onClick={done}>{t("teamWelcome.look")}</button>}+ {view.first && <button type="button" className={QUIET} onClick={done}>{t("teamWelcome.later")}</button>}+ </div>+ </div>+ </main>;+}diff --git a/src/components/TriggersPage.tsx b/src/components/TriggersPage.tsxindex 19144c523f..e4fb7e9397 100644--- a/src/components/TriggersPage.tsx+++ b/src/components/TriggersPage.tsx@@ -21,6 +21,7 @@ import { RoutineEditor } from "./RoutineCalendarPage";import { Select } from "./Select";import { Switch } from "./SettingsPrimitives";import { WebhookEditor } from "./WebhookTrigger";+import { schedulableBots, useTeamPeople } from "@/state/team-people";/** The bot filter earns its place only on a long list shared by several bots. */const FILTER_FROM = 9;@@ -41,6 +42,7 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpeconst [editing, setEditing] = useState<{ kind: SetUpKind; id?: string; botId?: string } | null>(null);const routinesOnly = window.ogb?.remoteClient?.active === true;const visibleBots = state.bots.filter((bot) => !bot.hidden);+ const team = useTeamPeople();const botName = (botId: string) => state.bots.find((bot) => bot.id === botId)?.name ?? t("routines.unavailableBot");useEffect(() => {@@ -161,7 +163,7 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe{newText !== null && (<NewAutomation initialText={newText} onClose={() => setNewText(null)} onSetUpYourself={(kind, botId) => { setNewText(null); setEditing({ kind, botId }); }} />)}- {editing?.kind === "schedule" && (editRoutine || !editing.id) && <RoutineEditor routine={editRoutine} bots={visibleBots} initialBotId={editing.botId} plain onClose={() => setEditing(null)} />}+ {editing?.kind === "schedule" && (editRoutine || !editing.id) && <RoutineEditor routine={editRoutine} bots={schedulableBots(visibleBots, team, editRoutine?.botId)} initialBotId={editing.botId} plain onClose={() => setEditing(null)} />}{editing?.kind === "webhook" && (editWebhook || !editing.id) && (<WebhookEditor webhook={editWebhook} bots={visibleBots} initialBotId={editing.botId} onClose={() => setEditing(null)} onCredential={(credential, id) => { saveWebhookCredential(webhookCredentialStore(), id, credential); setOpenId(id); }} />)}diff --git a/src/components/TurnPresence.tsx b/src/components/TurnPresence.tsxindex 7d7a071caa..bc70cbcb1d 100644--- a/src/components/TurnPresence.tsx+++ b/src/components/TurnPresence.tsx@@ -165,7 +165,7 @@ export function TurnPresence({<span id={statusId} className="flex min-w-0 items-baseline gap-x-1.5 text-[14px] leading-[22px] text-ink-tertiary" data-turn-status><span className="turn-phrase turn-phrase-quiet relative grid min-w-0" title={hover} data-turn-now={now ? "" : undefined}>{now ? (- <ShimmerPhrase key={`in:${current}`} text={current} className={cn("truncate", previous !== null && "turn-phrase-in")} />+ <ShimmerPhrase key={`in:${current}`} text={label ? `${label} · ${current}` : current} className={cn("truncate", previous !== null && "turn-phrase-in")} />) : (<span>{label ?? t("chat.typing")}</span>)}diff --git a/src/components/automations/AutomationsCalendar.tsx b/src/components/automations/AutomationsCalendar.tsxindex adb4080091..7b252eab56 100644--- a/src/components/automations/AutomationsCalendar.tsx+++ b/src/components/automations/AutomationsCalendar.tsx@@ -12,6 +12,7 @@ import { automationsFrom, automationStatus } from "@/lib/automations";import type { RoutineRun } from "@/lib/routines";import { api, useStore } from "@/state/store";import { useRoutineRunsFrom } from "@/state/older-routine-runs";+import { schedulableBots, useTeamPeople } from "@/state/team-people";import { CalendarGrid, EventDetails, EventEditor, QuickComposer, type CalendarEventItem, type EventKind, type EventSeed } from "../RoutineCalendarPage";import type { ResetDrop } from "../routines/LimitResetMarkers";@@ -34,6 +35,7 @@ export function AutomationsCalendar({ botFilter, department = "all", selectedAutconst [selected, setSelected] = useState<CalendarEventItem | null>(null);const [error, setError] = useState("");const visibleBots = state.bots.filter((bot) => !bot.hidden);+ const routineBots = schedulableBots(visibleBots, useTeamPeople(), editor?.botIds[0]);const rangeStart = days === 7 ? startOfWeek(anchor) : startOfDay(anchor);const rangeEnd = addDays(rangeStart, days);useRoutineRunsFrom(rangeStart);@@ -157,8 +159,8 @@ export function AutomationsCalendar({ botFilter, department = "all", selectedAut</div>)}</div>- {quick && <><div className="fixed inset-0 z-40 bg-black/25" onMouseDown={() => setQuick(null)} /><QuickComposer seed={quick} bots={visibleBots} routinesOnly={routinesOnly} onClose={() => setQuick(null)} onMore={(seed) => { setQuick(null); setEditor(seed); }} onSavedRoutine={(routine) => dispatch({ type: "routinePatched", routine })} onSavedCall={upsertCall} /></>}- {editor && <EventEditor seed={editor} bots={visibleBots} routinesOnly={routinesOnly} onClose={() => setEditor(null)} onSavedCall={upsertCall} />}+ {quick && <><div className="fixed inset-0 z-40 bg-black/25" onMouseDown={() => setQuick(null)} /><QuickComposer seed={quick} bots={routineBots} routinesOnly={routinesOnly} onClose={() => setQuick(null)} onMore={(seed) => { setQuick(null); setEditor(seed); }} onSavedRoutine={(routine) => dispatch({ type: "routinePatched", routine })} onSavedCall={upsertCall} /></>}+ {editor && <EventEditor seed={editor} bots={routineBots} routinesOnly={routinesOnly} onClose={() => setEditor(null)} onSavedCall={upsertCall} />}</div>);}diff --git a/src/components/cloud-welcome/CloudWelcome.test.ts b/src/components/cloud-welcome/CloudWelcome.test.tsindex 416509b033..2e21e2caa6 100644--- a/src/components/cloud-welcome/CloudWelcome.test.ts+++ b/src/components/cloud-welcome/CloudWelcome.test.ts@@ -300,8 +300,9 @@ describe("CloudWelcome", () => {(window.ogb as Record<string, unknown>).cloudPlan = { state: vi.fn() };fixture.state.config.team = { id: "t-acme", name: "Acme" };render();- await vi.waitFor(() => expect(text()).toContain("Welcome to Studio Cloud"));- expect(host.querySelector('[data-welcome-files="folders"]')?.textContent).toContain(desktopText);+ // On a team the welcome is the team's, by its name: never "My Cloud" or the Cloud's address.+ await vi.waitFor(() => expect(text()).toContain("Welcome to Acme"));+ expect(host.querySelector('[data-welcome-files="folders"]')?.textContent).toContain(desktopText.replace("Studio Cloud", "Acme"));});it("files and apps open Connected apps, then it is ready and says hi to the Chief of Staff", async () => {diff --git a/src/components/cloud-welcome/CloudWelcome.tsx b/src/components/cloud-welcome/CloudWelcome.tsxindex b693c0e048..e05096a72e 100644--- a/src/components/cloud-welcome/CloudWelcome.tsx+++ b/src/components/cloud-welcome/CloudWelcome.tsx@@ -18,6 +18,8 @@ import type { LocaleKey } from "@/locales";import type { CloudSendNotice } from "../../../electron/cloud-send.mjs";import { openBot, useStore } from "@/state/store";import { useCloudName } from "./parts";+import { teamPeoplePage } from "@/components/SidebarPeople";+import { useTeamPeople } from "@/state/team-people";import { WelcomeBring, type BringOutcome } from "./WelcomeBring";import { WelcomeDone, WelcomeEngine, WelcomeFiles } from "./WelcomeSteps";@@ -63,6 +65,7 @@ export function CloudWelcome() {const { state, dispatch } = useStore();const showThreads = useShowThreads();const welcome = useCloudWelcome();+ const people = useTeamPeople();const record = withEarlyHints(state.config?.onboarding, welcome.early);const name = useCloudName();const [view, setView] = useState<WelcomeView>(() => requestedView(takeWelcomeRequest()) ?? welcomeView(record));@@ -160,7 +163,7 @@ export function CloudWelcome() {onFinish={finishBring} />;} else if (view === "engine") content = <WelcomeEngine name={name} headingRef={heading} onFinish={() => finish("engine")} />;else if (view === "files") content = <WelcomeFiles name={name} headingRef={heading} onFinish={() => finish("files")} />;- else content = <WelcomeDone name={name} bot={bot} headingRef={heading} onSayHi={sayHi} onJob={giveJob} />;+ else content = <WelcomeDone name={name} bot={bot} headingRef={heading} onSayHi={sayHi} onJob={giveJob} invite={people?.me?.role === "owner" ? teamPeoplePage(state.config?.team) : null} />;return <main data-cloud-welcome={view} className="@container/welcome relative flex h-full min-w-0 flex-1 flex-col bg-app"><WindowDragStrip />diff --git a/src/components/cloud-welcome/WelcomeBring.test.ts b/src/components/cloud-welcome/WelcomeBring.test.tsindex 38386f6a83..1d82e1ad6d 100644--- a/src/components/cloud-welcome/WelcomeBring.test.ts+++ b/src/components/cloud-welcome/WelcomeBring.test.ts@@ -9,7 +9,7 @@ const bring = (team: boolean) => renderToStaticMarkup(createElement(WelcomeBringdescribe("the first setup step's promise", () => {it("on a Team Cloud, never says the bots on this computer come here by themselves", () => {const html = bring(true);- expect(html).toContain("Your own bots stay on your computer. Acme starts with bots of its own that everyone in the team can use.");+ expect(html).toContain("Acme is your team’s: its bots are shared with everyone in Acme, and your own bots stay where they are.");expect(html).not.toContain("come here by themselves");});diff --git a/src/components/cloud-welcome/WelcomeBring.tsx b/src/components/cloud-welcome/WelcomeBring.tsxindex 222237af8f..998d5e2ba1 100644--- a/src/components/cloud-welcome/WelcomeBring.tsx+++ b/src/components/cloud-welcome/WelcomeBring.tsx@@ -67,7 +67,7 @@ export function WelcomeBring({ name, desktop, older = false, cloudHasWork, sent</>: <button type="button" className={PRIMARY} onClick={() => onFinish("skipped")}>{t("onboarding.continue")}</button>;return <section aria-labelledby="cloud-welcome-step" data-welcome-step="bring" className="flex flex-col gap-5">- <StepHeading headingRef={headingRef} title={t("cloudWelcome.bring.title", { name })} sub={t(team ? "cloudWelcome.bring.subTeam" : "cloudWelcome.bring.sub", { name })} />+ <StepHeading headingRef={headingRef} title={t("cloudWelcome.bring.title", { name })} sub={t(team ? "cloudWelcome.bring.subTeamShared" : "cloudWelcome.bring.sub", { name })} />{older && <p role="note" data-bring-update className="text-[13px] leading-relaxed text-ink">{t("cloudWelcome.bring.update")}</p>}{team && desktop && <BringMyCloud />}{cloudHasWorkdiff --git a/src/components/cloud-welcome/WelcomeSteps.tsx b/src/components/cloud-welcome/WelcomeSteps.tsxindex 85cd749306..81b8516c4d 100644--- a/src/components/cloud-welcome/WelcomeSteps.tsx+++ b/src/components/cloud-welcome/WelcomeSteps.tsx@@ -87,14 +87,21 @@ export function WelcomeFiles({ name, headingRef, onFinish }: { name: string; hea</section>;}-export function WelcomeDone({ name, bot, headingRef, onSayHi, onJob }: {+export function WelcomeDone({ name, bot, headingRef, onSayHi, onJob, invite = null }: {name: string; bot: Bot | null; headingRef: Ref<HTMLHeadingElement>; onSayHi: () => void; onJob: () => void;+ /** The team's People page on MausBot Cloud, for its Owner: the last step is bringing people in. */+ invite?: string | null;}) {return <section aria-labelledby="cloud-welcome-step" data-welcome-step="done" className="flex flex-col items-start gap-4"><span aria-hidden="true" className="check-in flex size-[42px] items-center justify-center rounded-full bg-success"><Check size={22} strokeWidth={2.5} /></span><StepHeading headingRef={headingRef} title={t("cloudWelcome.done.title", { name })} sub={t("cloudWelcome.done.body")} />+ {invite && <div data-welcome-invite className="flex w-full max-w-[520px] flex-col items-start gap-2 rounded-2xl border border-hairline/50 bg-card/50 p-4">+ <p className="text-[14px] font-medium text-ink">{t("cloudWelcome.invite.title", { name })}</p>+ <p className="text-[13px] leading-relaxed text-ink-secondary">{t("cloudWelcome.invite.body", { name })}</p>+ <a href={invite} target="_blank" rel="noreferrer" className={SECONDARY}>{t("cloudWelcome.invite.action")}</a>+ </div>}<Footer><button type="button" className={PRIMARY} onClick={onSayHi}>{bot?.chiefOfStaff || !bot ? t("cloudWelcome.done.chief") : t("cloudWelcome.done.bot", { name: bot.name })}diff --git a/src/components/cloud-welcome/parts.tsx b/src/components/cloud-welcome/parts.tsxindex 7ecc1391c9..79ceaa8ab6 100644--- a/src/components/cloud-welcome/parts.tsx+++ b/src/components/cloud-welcome/parts.tsx@@ -2,6 +2,7 @@ import { useEffect, useState, type ReactNode, type Ref } from "react";import type { LucideIcon } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";+import { useStore } from "@/state/store";export const PRIMARY = "ui-button ui-button-primary min-h-9 px-4 text-[14px]";export const SECONDARY = "ui-button min-h-9 px-4 text-[14px]";@@ -35,6 +36,7 @@ export function Footer({ children, className }: { children: ReactNode; className/** The name this app keeps for the server open in the window; My Cloud wherever the app has none. */export function useCloudName(): string {+ const team = useStore().state.config?.team?.name?.trim();const bridge = window.ogb?.workspaces;const [name, setName] = useState<string | null>(null);useEffect(() => {@@ -44,5 +46,5 @@ export function useCloudName(): string {}).catch(() => {});return () => { alive = false; };}, [bridge]);- return name ?? t("cloudSetup.myCloud");+ return team || (name ?? t("cloudSetup.myCloud"));}diff --git a/src/components/routines/ResultsDestination.test.ts b/src/components/routines/ResultsDestination.test.tsindex 8b05f5fbfc..a173610850 100644--- a/src/components/routines/ResultsDestination.test.ts+++ b/src/components/routines/ResultsDestination.test.ts@@ -36,4 +36,15 @@ describe("routine result destination", () => {expect(html).toContain("Thread unavailable");expect(html).toContain('value="deleted-or-foreign" disabled="" selected=""');});++ it("on a team offers only Just me and the shared chat, and picks the shared chat by its id", () => {+ const team = { ...bot, mainThreadId: "main", tasks: [...bot.tasks!, { threadId: "mine", title: "Bob's plans", private: true }] } as Bot;+ const html = renderToStaticMarkup(createElement(ResultsDestination, { bot: team, value: null, team: true, onChange: vi.fn() }));+ expect(html).toContain('value="shared" selected=""');+ expect(html).toContain(">Just me<");+ expect(html).toContain(">Shared chat<");+ expect(html).not.toContain("Fleet health");+ expect(renderToStaticMarkup(createElement(ResultsDestination, { bot: team, value: "mine", team: true, onChange: vi.fn() }))).toContain('value="me" selected=""');+ expect(renderToStaticMarkup(createElement(ResultsDestination, { bot: team, value: "just-me", team: true, onChange: vi.fn() }))).toContain('value="me" selected=""');+ });});diff --git a/src/components/routines/ResultsDestination.tsx b/src/components/routines/ResultsDestination.tsxindex 4b7c0577b6..84e0ea09ff 100644--- a/src/components/routines/ResultsDestination.tsx+++ b/src/components/routines/ResultsDestination.tsx@@ -1,15 +1,20 @@import { useId } from "react";+import { RESULTS_JUST_ME } from "../../../shared/routines";import { t } from "@/lib/i18n";import type { Bot } from "@/state/store";+import { useTeamPeople } from "@/state/team-people";import { Select } from "../Select";-export function ResultsDestination({ bot, value, allowCurrent = false, onChange }: {+export function ResultsDestination({ bot, value, allowCurrent = false, team, onChange }: {bot?: Bot;value: string | null | undefined;allowCurrent?: boolean;+ /** A Team Cloud, where the routine reports to the person alone or to the bot's shared chat; read from the app when unset. */+ team?: boolean;onChange: (threadId: string | null | undefined) => void;}) {- const id = useId();+ const id = useId(), people = useTeamPeople();+ if (team ?? people !== null) return <TeamResultsDestination id={id} bot={bot} value={value} allowCurrent={allowCurrent} onChange={onChange} />;const tasks = (bot?.tasks ?? []).filter((task) => !task.routineRunId);const selectedMissing = typeof value === "string" && !tasks.some((task) => task.threadId === value);const groups = [...(bot?.projects ?? []), { id: "", name: t("folder.none") }];@@ -30,3 +35,20 @@ export function ResultsDestination({ bot, value, allowCurrent = false, onChange<p id={`${id}-help`} className="text-[11px] leading-relaxed text-ink-secondary">{t("routines.results.mainHelp")}</p></div>;}++function TeamResultsDestination({ id, bot, value, allowCurrent, onChange }: {+ id: string; bot?: Bot; value: string | null | undefined; allowCurrent: boolean; onChange: (threadId: string | null | undefined) => void;+}) {+ const ownChat = typeof value === "string" && Boolean(bot?.tasks?.some((task) => task.threadId === value && task.private === true));+ const selected = value === undefined && allowCurrent ? "current" : value === RESULTS_JUST_ME || ownChat ? "me" : "shared";+ return <div className="min-w-0 space-y-1.5">+ <label htmlFor={id} className="block text-[12px] font-medium text-ink">{t("routines.results.label")}</label>+ <Select className="w-full" id={id} aria-describedby={`${id}-help`} disabled={!bot} value={selected}+ onChange={(event) => onChange(event.target.value === "current" ? undefined : event.target.value === "me" ? (ownChat ? value : RESULTS_JUST_ME) : bot?.mainThreadId ?? null)}>+ {selected === "current" && <option value="current">{t("routines.results.keep")}</option>}+ <option value="me">{t("routines.results.justMe")}</option>+ <option value="shared">{t("task.sharedChat")}</option>+ </Select>+ <p id={`${id}-help`} className="text-[11px] leading-relaxed text-ink-secondary">{t("routines.results.teamHelp")}</p>+ </div>;+}diff --git a/src/lib/cloud-plan.test.ts b/src/lib/cloud-plan.test.tsindex eda73e6934..0ed7cbe50b 100644--- a/src/lib/cloud-plan.test.ts+++ b/src/lib/cloud-plan.test.ts@@ -446,3 +446,13 @@ describe("why a step of the dialog ended without going on", () => {expect(cloudAddView(free, OFFER, { ...at, conflict: true })).toMatchObject({ kind: "offer", notice: "preparing" });});});++describe("an invited person with no Cloud of their own", () => {+ it("is offered no plan before their team: no trial card, no Start free trial in Settings", () => {+ const account = { status: "connected", account: { id: "u", email: "[email protected]" }, deviceId: "d", expiresAt: 1, entitlement: { plan: "free", status: "inactive", expiresAt: null, version: 1 },+ teams: [{ id: "t", name: "Acme", role: "member", machine: null }], landing: { teamId: "t" } } as never;+ expect(cloudPlanView(account)).toEqual({ kind: "free", invited: true });+ expect(buyOfferAllowed(cloudPlanView(account))).toBe(false);+ expect(buyOfferAllowed(cloudPlanView({ ...(account as object), landing: undefined } as never))).toBe(true);+ });+});diff --git a/src/lib/cloud-plan.ts b/src/lib/cloud-plan.tsindex 937fb75761..70985bb3fc 100644--- a/src/lib/cloud-plan.ts+++ b/src/lib/cloud-plan.ts@@ -19,7 +19,7 @@ export type CloudPlanView =| { kind: "signed-out" }| { kind: "removed" }| { kind: "connecting" }- | { kind: "free" }+ | { kind: "free"; invited?: true }| { kind: "paid"; label: string; checking: boolean; trial?: true }| { kind: "attention"; label: string | null }| { kind: "purchase"; label: string | null; paidAt?: number }@@ -42,11 +42,12 @@ export function cloudPlanView(account: CloudAccountState | null | undefined): Cl}if (entitlement?.plan === "pro") return { kind: "attention", label: cloudPlanLabel(entitlement.tier) };if (account.machine) return { kind: "attention", label: null };- return { kind: "free" };+ // Invited into a team, with no Cloud of their own: their team comes first, and no plan is pushed at them.+ return account.landing ? { kind: "free", invited: true } : { kind: "free" };}export function buyOfferAllowed(view: CloudPlanView): boolean {- return view.kind === "signed-out" || view.kind === "free";+ return view.kind === "signed-out" || (view.kind === "free" && !view.invited);}/** What the X research card offers someone whose server has no plan credential yet: a paying desktop is still connectingdiff --git a/src/lib/session.ts b/src/lib/session.tsindex 96a54f8801..d87dea0fb8 100644--- a/src/lib/session.ts+++ b/src/lib/session.ts@@ -14,7 +14,7 @@ export interface TeamSession { id: string; name: string; role: string }export type SessionState =| { kind: "loopback"; trust?: "service" }- | { kind: "session"; id: string; label: string; email?: string; scopes: string[]; expiresAt: number; cloudGuest?: true; openedThreads?: string[]; reactor?: string; team?: TeamSession }+ | { kind: "session"; id: string; label: string; email?: string; scopes: string[]; expiresAt: number; cloudGuest?: true; openedThreads?: string[]; reactor?: string; team?: TeamSession; teamSignIn?: string }| { kind: "unauthenticated"; error: string }| { kind: "unreachable"; error: string };@@ -31,6 +31,16 @@ export function profileForSession(profile: SessionProfile | undefined, sessionStreturn profile?.email?.trim().toLowerCase() === email.trim().toLowerCase() ? profile : { email };}+const TEAM_SIGN_IN_KEY = "omb.team-sign-in";+/** A team session's page on MausBot Cloud, kept by this browser for this server, so the page its session ended on can offer+ * the way back. Nothing that signs anyone in: an address the signed-in session was told. */+export function rememberTeamSignIn(url: string | undefined): void {+ try { if (url) globalThis.localStorage?.setItem(TEAM_SIGN_IN_KEY, url); } catch {}+}+export function rememberedTeamSignIn(): string | null {+ try { return globalThis.localStorage?.getItem(TEAM_SIGN_IN_KEY) ?? null; } catch { return null; }+}+export async function readSessionState(fetchImpl: typeof fetch = fetch): Promise<SessionState> {let res: Response;try {@@ -53,6 +63,7 @@ export async function readSessionState(fetchImpl: typeof fetch = fetch): Promisescopes: Array.isArray(record.scopes) ? record.scopes.filter((s): s is string => typeof s === "string") : [],expiresAt: typeof record.expiresAt === "number" ? record.expiresAt : 0,...(typeof record.reactor === "string" ? { reactor: record.reactor } : {}),+ ...(typeof record.teamSignIn === "string" ? { teamSignIn: record.teamSignIn } : {}),...(teamSessionOf(record.team) ? { team: teamSessionOf(record.team)!, openedThreads: Array.isArray(record.openedThreads) ? record.openedThreads.filter((id): id is string => typeof id === "string") : [] } : {}),...(record.cloudGuest === true ? {cloudGuest: true as const,@@ -143,7 +154,7 @@ export async function pairWithCode(return { ok: false, error: refusalText(body, res) };}-export async function previewBrowserSignIn(credential: string, fetchImpl: typeof fetch = fetch): Promise<{ owner: string } | null> {+export async function previewBrowserSignIn(credential: string, fetchImpl: typeof fetch = fetch): Promise<{ owner: string; team?: string } | null> {try {const res = await fetchImpl("/api/auth/pair", {method: "POST",@@ -151,8 +162,9 @@ export async function previewBrowserSignIn(credential: string, fetchImpl: typeofheaders: { "content-type": "application/json" },body: JSON.stringify({ code: credential, browser: true, preview: true }),});- const owner: unknown = Reflect.get(Object(await res.json().catch(() => ({}))), "owner");- return res.ok && typeof owner === "string" && owner ? { owner } : null;+ const body = Object(await res.json().catch(() => ({})));+ const owner: unknown = Reflect.get(body, "owner"), team: unknown = Reflect.get(body, "team");+ return res.ok && typeof owner === "string" && owner ? { owner, ...(typeof team === "string" && team.trim() ? { team: team.trim() } : {}) } : null;} catch {return null;}diff --git a/src/lib/team-welcome.ts b/src/lib/team-welcome.tsnew file mode 100644index 0000000000..8f511c3562--- /dev/null+++ b/src/lib/team-welcome.ts@@ -0,0 +1,84 @@+import { useEffect, useSyncExternalStore } from "react";+import { api } from "@/state/store";+import type { TeamPerson } from "@/state/team-people";++/** A person's own welcome to a team (server/team-welcome.ts), from GET /api/me. */+export interface TeamWelcomeRecord { invitedBy: string | null; welcomedAt: number | null; hints: string[] }++export function parseTeamWelcome(value: unknown): TeamWelcomeRecord | null {+ const record = value && typeof value === "object" ? value as Record<string, unknown> : null;+ if (!record) return null;+ const invitedBy = typeof record.invitedBy === "string" && record.invitedBy.includes("@") ? record.invitedBy : null;+ const welcomedAt = typeof record.welcomedAt === "number" && record.welcomedAt > 0 ? record.welcomedAt : null;+ const hints = Array.isArray(record.hints) ? record.hints.filter((hint): hint is string => typeof hint === "string") : [];+ return { invitedBy, welcomedAt, hints };+}++/** Per team: undefined while it is read, null where the server keeps none (an older Team Cloud, or no team). */+let kept: { teamId: string; record: TeamWelcomeRecord | null | undefined } | null = null;+const listeners = new Set<() => void>();+const publish = (next: typeof kept) => { kept = next; for (const listener of listeners) listener(); };+const asked = new Set<string>();++function ask(teamId: string) {+ if (asked.has(teamId)) return;+ asked.add(teamId);+ void api<{ welcome?: unknown }>("/api/me", { timeoutMs: 10_000, background: true })+ .then((me) => publish({ teamId, record: parseTeamWelcome(me.welcome) }))+ .catch(() => publish({ teamId, record: null }));+}++/** This person's welcome on the team on screen; undefined until read, null off a team or on a Team Cloud too old to keep one. */+export function useTeamWelcomeRecord(teamId: string | null): TeamWelcomeRecord | null | undefined {+ useEffect(() => { if (teamId) ask(teamId); }, [teamId]);+ const current = useSyncExternalStore((listener) => { listeners.add(listener); return () => listeners.delete(listener); }, () => kept, () => kept);+ if (!teamId) return null;+ return current?.teamId === teamId ? current.record : undefined;+}++/** They saw it: kept on the server for them alone, and gone from this screen at once (even when the save fails: it comes+ * back on another device, never twice here). */+export async function finishTeamWelcome(teamId: string): Promise<void> {+ const record = kept?.teamId === teamId ? kept.record : null;+ publish({ teamId, record: { invitedBy: record?.invitedBy ?? null, hints: record?.hints ?? [], welcomedAt: Date.now() } });+ await api("/api/me/welcome", { method: "PUT", body: JSON.stringify({ welcomed: true }), timeoutMs: 10_000 }).catch(() => {});+}++/** The welcome counts as using the team: one quiet read this often while it is on screen and the page is visible. */+export const WELCOME_USE_MS = 5 * 60_000;+let shownThisLaunch = false;+/** The team's own welcome was on screen in this launch: nothing else introduces itself over the first run that follows. */+export function markTeamWelcomeShown(): void { shownThisLaunch = true; }+export const teamWelcomeShownThisLaunch = () => shownThisLaunch;++/** Only for tests: the record is module state. */+export function resetTeamWelcome(): void { asked.clear(); shownThisLaunch = false; publish(null); }++/** A User's first time in the team: they have a record and haven't seen it. An Admin has the Cloud's own welcome. */+export function teamWelcomeDue(input: { team: { id: string } | null | undefined; canSave: boolean | undefined; record: TeamWelcomeRecord | null | undefined }): boolean {+ return Boolean(input.team) && input.canSave === false && Boolean(input.record) && input.record!.welcomedAt === null;+}++interface WelcomeBot { id: string; name: string; title?: string; description?: string; soul?: string; hidden?: boolean; defaultBot?: { person?: string } | null; yourAccess?: string }+/** One line about a bot: its description, else its title, else the first line of its instructions when this copy carries+ * them (a quiet fallback); else none. */+const firstLine = (text: string | undefined, name = "") => (text ?? "").split("\n").map((line) => line.replace(/^[#>*\-\s]+/, "").trim()).find((line) => line && line !== name) ?? "";+export const WELCOME_PEOPLE = 6, WELCOME_BOTS = 4;++/**+ * What the welcome shows: who invited them (from the people list, else their address), everyone else in the team (a few,+ * and how many more), and the bots shared with them, each with one line; the first one they can chat with is the one+ * action. Their own MausBot is theirs, not shared, and a bot they can only view can't be the first chat.+ */+export function teamWelcomeView(input: { invitedBy: string | null; people: readonly TeamPerson[]; bots: readonly WelcomeBot[] }) {+ const inviter = input.invitedBy ? input.people.find((person) => person.email === input.invitedBy) ?? { email: input.invitedBy, name: "", role: "member" } : null;+ const others = input.people.filter((person) => !person.you);+ const shared = input.bots.filter((bot) => !bot.hidden && !bot.defaultBot?.person);+ const line = (bot: WelcomeBot) => (firstLine(bot.description) || bot.title?.trim() || firstLine(bot.soul, bot.name)).slice(0, 140);+ return {+ inviter,+ people: others.slice(0, WELCOME_PEOPLE), morePeople: Math.max(0, others.length - WELCOME_PEOPLE),+ bots: shared.slice(0, WELCOME_BOTS).map((bot) => ({ id: bot.id, name: bot.name, line: line(bot) })), moreBots: Math.max(0, shared.length - WELCOME_BOTS),+ first: shared.find((bot) => bot.yourAccess !== "view") ?? null,+ };+}diff --git a/src/locales/de.json b/src/locales/de.jsonindex 00ec653f4d..e114e59f99 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -3011,6 +3011,9 @@"server.routines.cron.nthWeekend.last": "Monatlich am letzten {weekday} um {time}","server.personFirst.stoppedSeconds": "Ein Schritt, der seit {seconds} s lief, wurde gestoppt, um dir zuerst zu antworten","server.personFirst.stoppedMinutes": "Ein Schritt, der seit {minutes} min lief, wurde gestoppt, um dir zuerst zu antworten",+ "server.runOwner.onlyAskerStops": "Nur {name} oder ein Admin kann das stoppen.",+ "server.runOwner.notYourQueued": "Nur die Person, die diese Nachricht geschickt hat, kann sie entfernen.",+ "server.runOwner.waitsItsTurn": "Diese Nachricht wartet, bis sie dran ist, und läuft nach der Anfrage, die gerade läuft.","server.routines.held.planCancelled": "Deine Routinen sind pausiert, weil der Tarif gekündigt wurde. Damit eine bis zum Ende des Tarifs weiterläuft, schalte sie unter Routines wieder ein.","server.routines.held.noEngine": "Deine Routinen sind pausiert: Keines deiner KI-Konten ist hier noch angemeldet. Sie schalten sich von selbst wieder ein, wenn du dich erneut anmeldest.","server.routines.held.noConnections": "Deine Routinen sind pausiert: Alle verbundenen Apps und MCP-Server wurden entfernt. Sie schalten sich wieder ein, wenn du eine App oder einen MCP-Server verbindest oder eine Routine unter Routines wieder einschaltest.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 79b825b46a..8be16df278 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1592,6 +1592,7 @@"cloudWelcome.bring.title": "What should {name} start with?","cloudWelcome.bring.sub": "Bots on your computer come here by themselves from the {app} app.","cloudWelcome.bring.subTeam": "Your own bots stay on your computer. {name} starts with bots of its own that everyone in the team can use.",+ "cloudWelcome.bring.subTeamShared": "{name} is your team’s: its bots are shared with everyone in {name}, and your own bots stay where they are.","cloudWelcome.bring.fresh": "Start fresh","cloudWelcome.bring.freshHint": "Pick a ready-made team from the library, or start with one bot and build your own.","cloudWelcome.bring.chooseTeam": "Choose a team",@@ -1627,6 +1628,9 @@"cloudWelcome.files.appsHint": "Gmail, Slack, Notion and more. Connections are per Cloud, so connect them here.","cloudWelcome.files.appsAction": "Connect apps","cloudWelcome.files.finish": "Finish",+ "cloudWelcome.invite.title": "Invite people to {name}",+ "cloudWelcome.invite.body": "{name} is better with your team in it. Invite them by email on MausBot Cloud: they can open it in their browser right away.",+ "cloudWelcome.invite.action": "Invite people","cloudWelcome.done.title": "{name} is ready","cloudWelcome.done.body": "Your bots now run 24/7. Close your laptop whenever you like.","cloudWelcome.done.chief": "Say hi to your Chief of Staff",@@ -1716,6 +1720,9 @@"settings.profile.avatar.tooLargeDimensions": "The photo must be no larger than 8192 × 8192 pixels.","settings.profile.aboutMe": "About me","settings.profile.aboutMeHelp": "Shared with every bot in private and group chats. Saved automatically.",+ "settings.profile.awayEmails": "Email me when I'm away",+ "settings.profile.awayEmailsHelp": "One email when a teammate mentions you, a bot is waiting on your answer, or work you asked for finishes while you're not in the app. It never includes what anyone wrote.",+ "settings.profile.awayEmailsError": "That didn't save. Try again.","settings.profile.everyBotRules": "Rules for every bot","settings.profile.everyBotRulesPlaceholder": "Every bot follows these. A bot's own instructions win where they differ.","settings.profile.saving": "Saving…",@@ -2518,6 +2525,7 @@"chat.retry": "Retry","chat.turnStopped": "Stopped","chat.turnStoppedByYou": "You stopped this.",+ "chat.turnStoppedBy": "{name} stopped this.","chat.rescue.waiting": "{bot} hasn't heard back from {ai} yet.","chat.rescue.over": "{bot} didn't hear back from {ai}.","chat.rescue.switchAi": "Switch AI",@@ -2751,6 +2759,14 @@"chat.activity.thinking": "Thinking","chat.activity.working": "Working","chat.typing": "Typing…",+ "chat.queue.workingFor": "Working on {name}'s request",+ "chat.queue.workingForYou": "Working on your request",+ "chat.queue.next": "Next: {name}'s request",+ "chat.queue.nextYours": "Next: your request",+ "chat.queue.nextMore": "Next: {name}'s request, then {count} more",+ "chat.queue.nextYoursMore": "Next: your request, then {count} more",+ "chat.queue.removeYours": "Remove your waiting message",+ "chat.queue.yoursWaiting": "Yours: {text}","chat.teammatesWorking": "Teammates working","chat.friendly.thinking": "Thinking it through","chat.friendly.mulling": "Mulling it over",@@ -4237,6 +4253,8 @@"activity.action.access.allow": "Let someone chat with a bot","activity.action.access.decline": "Turned down a request to chat with a bot","activity.action.owner.update": "Changed who a bot reports to",+ "activity.action.routine.handover": "Handed a routine over",+ "activity.action.member.left": "Left the team","activity.action.room.audience-reset": "Widened who can see a room","activity.action.webhook.create": "Created a webhook","activity.action.webhook.update": "Changed a webhook",@@ -5437,6 +5455,8 @@"routines.results.missing": "A thread that no longer exists","routines.results.main": "The bot's main thread","routines.results.mainHelp": "Each run starts with fresh context. Dated results collect here, in the bot's main thread unless you choose another; full execution details stay in Run logs.",+ "routines.results.justMe": "Just me",+ "routines.results.teamHelp": "Just me: only you see what it reports. Shared chat: everyone who can use the bot sees it.","routines.runNow": "Run now","routines.starting": "Starting…","routines.pause": "Pause",@@ -7485,6 +7505,17 @@"mcp.apps.title": "Show its apps in chat","mcp.apps.desc": "When one of its tools has an app, the app opens in the chat.","mcp.apps.toggleAria": "Show apps from {name} in chat",+ "teamWelcome.title": "Welcome to {team}",+ "teamWelcome.invited": "{person} invited you to {team}.",+ "teamWelcome.invitedNobody": "You’re in {team} now.",+ "teamWelcome.people": "Who’s in {team}",+ "teamWelcome.more": "and {count} more",+ "teamWelcome.bots": "Bots shared with you",+ "teamWelcome.moreBots": "and {count} more in the sidebar",+ "teamWelcome.noBots": "No bots are shared with you in {team} yet. Your own MausBot is in the sidebar.",+ "teamWelcome.start": "Start a chat with {bot}",+ "teamWelcome.look": "Look around",+ "teamWelcome.later": "Not now","team.privateChats": "Your chats in {team} are private. Only you can see them: not other members, not {team}'s admins.","team.privateHeader": "Private · only you","team.sharedHeader": "Shared · everyone in {team} can see",@@ -8801,6 +8832,7 @@"pair.connect": "Connect","pair.useEmail": "Sign in with email","pair.browser.title": "Signing in to {owner}’s Cloud",+ "pair.browser.teamTitle": "Open {team} as {owner}","pair.browser.notYou": "Not your email? Close this tab.","pair.continue": "Continue","pair.fromLink": "From the link",@@ -9434,6 +9466,8 @@"routines.event.resizeSeries": "Resize this entire recurring series?","chat.mermaid.failed": "Diagram could not be rendered: {error}","pair.myCloud": "My Cloud",+ "pair.team.open": "Open {team} with MausBot Cloud",+ "pair.team.openHint": "You sign in there with your email, then come straight back here.","pair.signInTo": "Sign in to {name}","pair.connectTo": "Connect to {name}","shortcuts.toggle-sidebar": "Collapse or expand the sidebar",@@ -9703,6 +9737,9 @@"chat.notice.memoryReclaimedTaskDetail": "Ran out of room, so I stopped this task to keep everything else running. ({detail})","server.personFirst.stoppedSeconds": "Stopped a step that had run for {seconds} s, to answer you first","server.personFirst.stoppedMinutes": "Stopped a step that had run for {minutes} min, to answer you first",+ "server.runOwner.onlyAskerStops": "Only {name} or an admin can stop this.",+ "server.runOwner.notYourQueued": "Only the person who sent this message can remove it.",+ "server.runOwner.waitsItsTurn": "This message waits its turn and runs after the request that is running now.","server.routines.held.planCancelled": "Your routines are paused because the plan was cancelled. To keep one running until the plan ends, turn it back on in Routines.","server.routines.held.noEngine": "Your routines are paused: none of your AI accounts is signed in here any more. They turn back on by themselves when you sign in again.","server.routines.held.noConnections": "Your routines are paused: every connected app and MCP server was removed. They turn back on when you connect one, or turn one back on in Routines.",@@ -9783,6 +9820,9 @@"native.html.tooLarge": "This page is too large to open (2 MB)","native.accounts.moving": "This computer's bots are moving to the Cloud. Try again once that's done.","native.accounts.myComputer": "My computer",+ "native.teamLink.otherTitle": "This team isn’t on the account signed in here",+ "native.teamLink.otherDetail": "MausBot is signed in as {email}. If you joined the team with another address, sign in with that one. {email} stays signed in too.",+ "native.teamLink.signIn": "Sign in with another address","server.outside.routineFromBefore": "This routine was made before this update. Open it and save it once to run it with full access.","server.outside.routineFromOutside": "A webhook's run made or changed this routine, so it runs without full access. Open it and save it once to run it with full access.","server.outside.conversationFromBefore": "This conversation is from before My Cloud was only yours, so this bot works in it without a shell. Start a new conversation to use it fully.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 1cd2cf8b8b..d7daf535db 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -1593,6 +1593,9 @@"settings.profile.avatar.tooLargeDimensions": "A foto precisa ter no máximo 8.192 × 8.192 pixels.","settings.profile.aboutMe": "Sobre mim","settings.profile.aboutMeHelp": "Compartilhado com todos os bots em conversas privadas e em grupo. Salvo automaticamente.",+ "settings.profile.awayEmails": "Me envie um e-mail quando eu estiver fora",+ "settings.profile.awayEmailsHelp": "Um e-mail quando um colega mencionar você, um bot estiver esperando sua resposta ou um trabalho que você pediu terminar enquanto você não está no app. Ele nunca inclui o que alguém escreveu.",+ "settings.profile.awayEmailsError": "Não foi salvo. Tente novamente.","settings.profile.everyBotRules": "Regras para todos os bots","settings.profile.everyBotRulesPlaceholder": "Todos os bots seguem estas regras. Quando divergem, valem as instruções do próprio bot.","settings.profile.saving": "Salvando…",@@ -2389,6 +2392,7 @@"chat.retry": "Tentar novamente","chat.turnStopped": "Sessão interrompida","chat.turnStoppedByYou": "Você interrompeu esta sessão.",+ "chat.turnStoppedBy": "{name} interrompeu esta sessão.","chat.rescue.waiting": "{bot} ainda não recebeu uma resposta de {ai}.","chat.rescue.over": "{bot} não recebeu uma resposta de {ai}.","chat.rescue.switchAi": "Trocar de IA",@@ -2621,6 +2625,14 @@"chat.voiceNote.transcript": "Transcrição","chat.activity.thinking": "Pensando","chat.activity.working": "Trabalhando",+ "chat.queue.workingFor": "Trabalhando no pedido de {name}",+ "chat.queue.workingForYou": "Trabalhando no seu pedido",+ "chat.queue.next": "A seguir: pedido de {name}",+ "chat.queue.nextYours": "A seguir: seu pedido",+ "chat.queue.nextMore": "A seguir: pedido de {name}, depois mais {count}",+ "chat.queue.nextYoursMore": "A seguir: seu pedido, depois mais {count}",+ "chat.queue.removeYours": "Remover sua mensagem da fila",+ "chat.queue.yoursWaiting": "Sua: {text}","chat.typing": "Digitando…","chat.teammatesWorking": "Colegas trabalhando","chat.friendly.thinking": "Pensando no assunto",@@ -4087,6 +4099,8 @@"activity.action.access.allow": "Permitiu que alguém conversasse com um bot","activity.action.access.decline": "Recusou um pedido para conversar com um bot","activity.action.owner.update": "Alterou a quem um bot responde",+ "activity.action.routine.handover": "Passou uma rotina adiante",+ "activity.action.member.left": "Saiu da equipe","activity.action.room.audience-reset": "Ampliou a visibilidade de um grupo","activity.action.webhook.create": "Criou um webhook","activity.action.webhook.update": "Alterou um webhook",@@ -5167,6 +5181,8 @@"routines.results.missing": "Uma conversa que não existe mais","routines.results.main": "A conversa principal do bot","routines.results.mainHelp": "Cada execução começa com contexto novo. Os resultados, com as datas, ficam aqui na conversa principal do bot, a menos que você escolha outra. Os detalhes completos da execução ficam em “Registros”.",+ "routines.results.justMe": "Só eu",+ "routines.results.teamHelp": "Só eu: só você vê o que ela relata. Conversa compartilhada: todos que podem usar o bot veem.","routines.runNow": "Rodar agora","routines.starting": "Iniciando…","routines.pause": "Pausar",@@ -9673,6 +9689,9 @@"chat.notice.memoryReclaimedBrowserDetail": "Faltou memória, então fechei o navegador para manter o restante funcionando. ({detail})","chat.notice.memoryReclaimedTaskDetail": "Faltou memória, então interrompi esta tarefa para manter o restante funcionando. ({detail})","server.personFirst.stoppedSeconds": "Interrompi um passo que já durava {seconds} s para responder a você primeiro",+ "server.runOwner.onlyAskerStops": "Só {name} ou um administrador pode interromper isto.",+ "server.runOwner.notYourQueued": "Só quem enviou esta mensagem pode removê-la.",+ "server.runOwner.waitsItsTurn": "Esta mensagem espera a vez dela e roda depois do pedido em andamento.","server.personFirst.stoppedMinutes": "Interrompi um passo que já durava {minutes} min para responder a você primeiro","server.routines.held.planCancelled": "Suas rotinas estão pausadas porque o plano foi cancelado. Para manter uma delas rodando até o fim do plano, ligue-a novamente em “Rotinas”.","server.routines.held.noEngine": "Suas rotinas estão pausadas: nenhuma das suas contas de IA continua conectada aqui. O app liga as rotinas automaticamente quando você entrar novamente.",@@ -9980,5 +9999,26 @@"phone.code.typeIntro": "Abra o app do {app} e digite este código de pareamento.","phone.signIn.emailCode": "Código de login do seu e-mail","settings.simple.account.noNameHint": "Ainda não definido",- "settings.simple.account.yourName": "Seu nome"+ "settings.simple.account.yourName": "Seu nome",+ "cloudWelcome.bring.subTeamShared": "{name} é da sua equipe: os bots são compartilhados com todos em {name}, e seus próprios bots ficam onde estão.",+ "cloudWelcome.invite.title": "Convidar pessoas para {name}",+ "cloudWelcome.invite.body": "{name} fica melhor com sua equipe. Convide as pessoas por e-mail no MausBot Cloud: elas podem abrir no navegador na hora.",+ "cloudWelcome.invite.action": "Convidar pessoas",+ "teamWelcome.title": "Boas-vindas a {team}",+ "teamWelcome.invited": "{person} convidou você para {team}.",+ "teamWelcome.invitedNobody": "Agora você faz parte de {team}.",+ "teamWelcome.people": "Quem está em {team}",+ "teamWelcome.more": "e mais {count}",+ "teamWelcome.bots": "Bots compartilhados com você",+ "teamWelcome.moreBots": "e mais {count} na barra lateral",+ "teamWelcome.noBots": "Ainda não há bots compartilhados com você em {team}. Seu MausBot está na barra lateral.",+ "teamWelcome.start": "Conversar com {bot}",+ "teamWelcome.look": "Explorar",+ "teamWelcome.later": "Agora não",+ "pair.browser.teamTitle": "Abrir {team} como {owner}",+ "pair.team.open": "Abrir {team} com o MausBot Cloud",+ "pair.team.openHint": "Você entra lá com seu e-mail e volta direto para cá.",+ "native.teamLink.otherTitle": "Esta equipe não está na conta conectada aqui",+ "native.teamLink.otherDetail": "O MausBot está conectado como {email}. Se você entrou na equipe com outro endereço, entre com ele. {email} continua conectado também.",+ "native.teamLink.signIn": "Entrar com outro endereço"}diff --git a/src/main.tsx b/src/main.tsxindex 50a8cd99a4..bf12293989 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -1,7 +1,7 @@import { StrictMode } from "react";import { createRoot } from "react-dom/client";import {- previewBrowserSignIn, readSessionState, takeBrowserSignInFromLocation, takePairingCodeFromLocation, takeInvitedEmailFromLocation,+ previewBrowserSignIn, readSessionState, rememberTeamSignIn, takeBrowserSignInFromLocation, takePairingCodeFromLocation, takeInvitedEmailFromLocation,} from "./lib/session";import { bootstrapBrand, productName } from "./lib/brand";import { t } from "./lib/i18n";@@ -12,7 +12,8 @@ import { applyFont, readFont } from "./lib/fonts";import { applySoftwareRendering } from "./lib/software-rendering";import { settleInterfaceMode } from "./lib/new-look";import { BrowserSignInPage } from "./pair/BrowserSignInPage";-import { PairPage } from "./pair/PairPage";+import { PairPage, TeamLeftPage } from "./pair/PairPage";+import { TEAM_LEFT_REFUSAL } from "../shared/cloud-hints";import { HomeScreen, SignedOutAtHome } from "./components/HomeScreen";import { PageBoundary } from "./components/PageBoundary";import { endedBeforeReload, forgetEndedSession } from "./lib/session-ended";@@ -32,6 +33,10 @@ const PAGES_WITHOUT_THE_APP = new Set(["/home", "/pair", "/desktop-viewer"]);const loadApp = () => import("./App").catch((error: unknown) => ({ default: (): never => { throw error; } }));const appPage = PAGES_WITHOUT_THE_APP.has(location.pathname) ? null : loadApp();+/** A team's name as its server describes itself to anyone (the descriptor's label), null when it can't say. */+const teamName = () => fetch("/.well-known/openmausbot/environment").then((res) => res.json() as Promise<{ label?: unknown; capabilities?: { cloudTeam?: unknown } }>)+ .then((descriptor) => (descriptor.capabilities?.cloudTeam === true && typeof descriptor.label === "string" ? descriptor.label : null), () => null);+async function chooseRoot(): Promise<React.ReactNode> {const home = window.ogb?.home;if (location.pathname === "/home" && home) return <HomeScreen bridge={home} manage={window.ogb?.cloudPlan?.manage} />;@@ -40,17 +45,19 @@ async function chooseRoot(): Promise<React.ReactNode> {if (signIn) {const preview = await previewBrowserSignIn(signIn);await pageLanguage;- return preview ? <BrowserSignInPage credential={signIn} owner={preview.owner} /> : <PairPage initialCode={null} reason={t("pair.browser.signInFailed")} />;+ return preview ? <BrowserSignInPage credential={signIn} owner={preview.owner} team={preview.team} /> : <PairPage initialCode={null} reason={t("pair.browser.signInFailed")} />;}return <PairPage initialCode={takePairingCodeFromLocation()} initialEmail={takeInvitedEmailFromLocation()} />;}const session = await readSessionState();if (session.kind === "unauthenticated") {await pageLanguage;+ if (session.error === TEAM_LEFT_REFUSAL) return <TeamLeftPage team={await teamName()} />;const pair = <PairPage initialCode={null} reason={endedBeforeReload() ? t("pair.sessionEnded") : session.error} />;return home ? <SignedOutAtHome bridge={home} fallback={pair} /> : pair;}forgetEndedSession();+ if (session.kind === "session") rememberTeamSignIn(session.teamSignIn);if (session.kind === "loopback" && session.trust === "service") {await pageLanguage;return <PairPage initialCode={null} reason={t("pair.serviceTrust")} />;diff --git a/src/pair/BrowserSignInPage.tsx b/src/pair/BrowserSignInPage.tsxindex 925d7afcd7..2332b855f2 100644--- a/src/pair/BrowserSignInPage.tsx+++ b/src/pair/BrowserSignInPage.tsx@@ -4,7 +4,7 @@ import { newAttemptId, signInWithBrowserGrant } from "../lib/session";import { t } from "../lib/i18n";/** Nothing is redeemed until the person continues, so a sent link never signs this browser in unseen; the credential is never shown. */-export function BrowserSignInPage({ credential, owner }: { credential: string; owner: string }) {+export function BrowserSignInPage({ credential, owner, team }: { credential: string; owner: string; team?: string }) {const [attemptId] = useState(() => newAttemptId());const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);@@ -24,7 +24,7 @@ export function BrowserSignInPage({ credential, owner }: { credential: string; oreturn (<main className="flex min-h-screen items-center justify-center bg-app px-6 text-ink"><div className="w-full max-w-[420px]">- <h1 className="text-[20px] font-semibold">{t("pair.browser.title", { owner })}</h1>+ <h1 className="text-[20px] font-semibold">{team ? t("pair.browser.teamTitle", { team, owner }) : t("pair.browser.title", { owner })}</h1><p className="mt-1.5 text-[14px] text-ink-secondary">{t("pair.browser.notYou")}</p>{error ? <p role="alert" className="mt-3 text-[13px] text-danger">{error}</p> : null}<button type="button" onClick={() => void continueSignIn()} disabled={busy}diff --git a/src/pair/PairPage.test.ts b/src/pair/PairPage.test.tsindex 1c0030859b..35b6140ee2 100644--- a/src/pair/PairPage.test.ts+++ b/src/pair/PairPage.test.ts@@ -6,8 +6,9 @@ const f = vi.hoisted(() => ({ effects: [] as EffectCallback[], pair: vi.fn() }))vi.mock("react", async original => ({ ...await original<typeof import("react")>(), useEffect: (effect: EffectCallback) => { f.effects.push(effect); } }));vi.mock("../lib/session", async original => ({ ...await original<typeof import("../lib/session")>(), pairWithCode: f.pair, readSessionState: vi.fn().mockResolvedValue({ kind: "unauthenticated", error: "" }) }));vi.mock("../components/DesktopWorkspaceSwitcher", () => ({ DesktopWorkspaceSwitcher: () => null }));-import { codeProblem, codeReady, openInAppLink, PairPage, pairIntro, pairsAutomatically, pairTitle, unencryptedPublic } from "./PairPage";+import { codeProblem, codeReady, openInAppLink, PairPage, pairIntro, pairsAutomatically, pairTitle, TeamLeftPage, teamPage, unencryptedPublic } from "./PairPage";import en from "../locales/en.json";+import type { EnvironmentDescriptor } from "../lib/session";const code = "ABCD-EFGH-JK23";const render = (initialCode: string | null) => { f.effects = []; return renderToStaticMarkup(createElement(PairPage, { initialCode })); };@@ -100,3 +101,18 @@ it("asks for the code first, with email sign-in as a link below, and says how toexpect(html).toContain("npx openmausbot pair");expect(html.indexOf("<form")).toBeLessThan(html.indexOf(en["pair.code"]));});++it("a team's Cloud whose session ended offers the way back through MausBot Cloud, as the signed-in session told this browser, and only to an https page", () => {+ const team = { environmentId: "e", label: "Acme", platform: "linux", version: "1", capabilities: { remoteSessions: true as const, cloudHome: true as const, cloudTeam: true as const } } as unknown as EnvironmentDescriptor;+ expect(teamPage(team, "https://cloud.openmausbot.com/cloud/team/t1")).toBe("https://cloud.openmausbot.com/cloud/team/t1");+ expect(teamPage(team, null), "never told before sign-in").toBeNull();+ for (const bad of ["javascript:alert(1)", "http://evil.example/cloud", "https://u:[email protected]/x", "https://cloud.example/x#signin=1", "nope"]) expect(teamPage(team, bad)).toBeNull();+ expect(teamPage({ ...team, capabilities: { remoteSessions: true, cloudHome: true } } as unknown as EnvironmentDescriptor, "https://cloud.openmausbot.com/cloud/team/t1"), "a My Cloud has no team page").toBeNull();+ expect(en["pair.team.open"].replace("{team}", "Acme")).toBe("Open Acme with MausBot Cloud");+});++it("a team's page whose person is no longer in the team says so in one sentence, with nothing to sign in to", () => {+ const html = renderToStaticMarkup(createElement(TeamLeftPage, { team: "Acme" }));+ expect(html).toContain("You're no longer in Acme.");+ expect(html).not.toMatch(/<(input|button|a) /);+});diff --git a/src/pair/PairPage.tsx b/src/pair/PairPage.tsxindex 6e640d6cde..d1372c720e 100644--- a/src/pair/PairPage.tsx+++ b/src/pair/PairPage.tsx@@ -9,6 +9,7 @@ import {pairWithCode,readSessionState,reasonWorthShowing,+ rememberedTeamSignIn,startEmailSignIn,verifyEmailSignIn,type EnvironmentDescriptor,@@ -57,12 +58,30 @@ export function unencryptedPublic(where: { protocol: string; hostname: string })return where.protocol === "http:" && !isPrivateHost(where.hostname);}+/** A team's Cloud: the person's team page on MausBot Cloud, as their signed-in session told this browser (never before+ * sign-in), where they open it again. Only an https page (or a loopback fixture's). */+export function teamPage(environment: EnvironmentDescriptor | null, remembered: string | null = rememberedTeamSignIn()): string | null {+ if (!environment?.capabilities.cloudTeam || typeof remembered !== "string") return null;+ try {+ const url = new URL(remembered);+ const loopback = url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);+ return (url.protocol === "https:" || loopback) && !url.username && !url.password && !url.hash ? url.href : null;+ } catch { return null; }+}+export function pairTitle(environment: EnvironmentDescriptor | null, mode: "email" | "code" | null): string {if (environment?.capabilities.cloudTeam) return environment.label;if (environment?.capabilities.cloudHome) return t("pair.myCloud");return t(mode === "email" ? "pair.signInTo" : "pair.connectTo", { name: environment?.label ?? t("pair.thisOpenMausBot", { app: productName() }) });}+/** A team's page whose session ended because its person is no longer in the team: one sentence, nothing that can't work. */+export function TeamLeftPage({ team }: { team: string | null }) {+ return <main data-team-left className="flex min-h-screen items-center justify-center bg-app px-6 text-ink">+ <p role="status" className="max-w-[420px] text-[16px]">{t("homeLine.left", { name: team ?? t("pair.thisOpenMausBot", { app: productName() }) })}</p>+ </main>;+}+export function PairPage({ initialCode, initialEmail = null, reason }: { initialCode: string | null; initialEmail?: string | null; reason?: string }) {const [code, setCode] = useState(initialCode ?? "");const [label, setLabel] = useState(defaultDeviceLabel());@@ -159,6 +178,10 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial</p>{reasonWorthShowing(reason) && !connected ? <p className="mt-3 text-[13px] text-ink-secondary">{reasonWorthShowing(reason)}</p> : null}{error && cloudHome && initialCode ? <p className="mt-3 text-[13px] text-ink-secondary">{t("pair.expired", { app: productName(), open: t("cloudHome.connect"), section: t("settings.section.cloudAccount") })}</p> : null}+ {!connected && teamPage(environment) ? <div data-team-sign-in className="mt-4 flex flex-col items-start gap-1.5">+ <a href={teamPage(environment)!} className="rounded-md bg-accent px-4 py-2 text-[14px] font-medium text-accent-ink">{t("pair.team.open", { team: environment!.label })}</a>+ <p className="text-[13px] text-ink-secondary">{t("pair.team.openHint")}</p>+ </div> : null}</>}{opening ? null : connected ? (<p className="mt-4 text-[14px]">diff --git a/src/state/store.tsx b/src/state/store.tsxindex f68d5a903a..c7e17b7b22 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -11,7 +11,7 @@ import {type ReactNode,} from "react";import { flushSync } from "react-dom";-import type { BotMovedTo, BotVisibility, CardAnswerer, CloudBackend, ConnectorToolGrant, EffortLevel, InstalledPackageMetadata, LiveCallState, ServerFrame, GroupThreadUsage, SteerQueueReason, WireBot, WireGroup, WireTask, OptionCardData as WireOptionCard } from "../../shared/wire"; import type { InstanceEndpointInfo } from "../../shared/claude-endpoint";+import type { BotMovedTo, BotVisibility, CardAnswerer, CloudBackend, ConnectorToolGrant, EffortLevel, InstalledPackageMetadata, LiveCallState, ServerFrame, GroupThreadUsage, ResolvedSender, SteerQueueReason, WireBot, WireGroup, WireTask, OptionCardData as WireOptionCard } from "../../shared/wire"; import type { InstanceEndpointInfo } from "../../shared/claude-endpoint";import { movesThreadToTop } from "../../shared/wire"; import type { DefaultBotFields } from "../../shared/default-bot";import { reorderStable } from "../../shared/bot-order";import { withOneChief } from "../../shared/bot-owner";@@ -117,7 +117,7 @@ export type SecretRequestCardData = Omit<import("../../shared/wire").SecretRequeexport type ComputerControlState = { held: boolean; helpReason: string | null; help?: import("../../shared/wire").ComputerHelpRef | null };-export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "sender" | "setupSuggestion" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "bugReport" | "engineCompaction"> {+export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "sender" | "setupSuggestion" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "bugReport" | "engineCompaction" | "stoppedBy"> {id: string;role: "bot" | "user";kind: "text" | "options" | "activity" | "screen" | "connector" | "secret" | "signin" | "routine.run" | "goal.run" | "digest" | "compaction" | "call" | "widget" | "app";@@ -215,7 +215,7 @@ export interface ModelSelection {variant?: string;}-export interface Task extends Pick<WireTask, "private" | "setupRequest" | "inbox" | "openAsks"> {+export interface Task extends Pick<WireTask, "private" | "setupRequest" | "inbox" | "openAsks" | "askedBy"> {waitingForTeammates?: boolean; sharedChat?: true;threadId: string;routineRunId?: string;@@ -617,7 +617,7 @@ export interface AppState {nonce: number;kind: Exclude<MausMotion, "none">;} | null;- pendingQueued: Record<string, Array<{ queueId: string; text: string; reason?: SteerQueueReason }>>;+ pendingQueued: Record<string, Array<{ queueId: string; text: string; reason?: SteerQueueReason; sender?: ResolvedSender }>>;consumedQueueIds: Record<string, true>;backgroundThreadEvents: Record<string, Array<Extract<Action, { type: "messageAdded" | "messagePatched" | "threadActive" | "optimisticMessageRemoved" }>>>;loadingOlder: Record<string, true>;diff --git a/src/state/team-chats.ts b/src/state/team-chats.tsindex cf1e7a3f46..0aebd27e62 100644--- a/src/state/team-chats.ts+++ b/src/state/team-chats.ts@@ -31,6 +31,10 @@ export function rememberOwnChat(teamId: string, threadId: string) {if (current?.teamId === teamId && !current.opened?.includes(threadId)) current = { ...current, opened: [...(current.opened ?? []), threadId] };}+/** A conversation this person started on a team (the session's list, and one this page just made before its task arrives):+ * theirs alone, so it is never shown as the shared chat. */+export const ownChatStarted = (threadId: string | undefined) => Boolean(threadId && current?.opened?.includes(threadId));+/** A person's own conversation: private, open, and opened by a person (not a routine's report or a bot's thread). */const ownKind = (task: TaskLike) => task.private === true && !task.routineRunId && !task.openedBy && !task.archivedAt && !task.closedBy;const newest = (tasks: TaskLike[]) => [...tasks].sort((a, b) => (b.updatedAt ?? b.createdAt ?? 0) - (a.updatedAt ?? a.createdAt ?? 0))[0];diff --git a/src/state/team-people.test.ts b/src/state/team-people.test.tsnew file mode 100644index 0000000000..4f373d3fc8--- /dev/null+++ b/src/state/team-people.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vitest";++import { schedulableBots } from "./team-people";++const OLIVE = { email: "[email protected]", name: "Olive", role: "owner", you: true as const };+const bots = [+ { id: "scout", yourAccess: "edit" },+ { id: "payroll", yourAccess: "view" },+ { id: "olives-mausbot", defaultBot: { person: "[email protected]" }, yourAccess: "edit" },+ { id: "bobs-mausbot", defaultBot: { person: "[email protected]" }, yourAccess: "edit" },+ { id: "archived", hidden: true, yourAccess: "edit" },+];++describe("schedulableBots", () => {+ it("on a team lists only the bots the person can chat with, their own MausBot and no teammate's", () => {+ expect(schedulableBots(bots, { me: OLIVE }).map((bot) => bot.id)).toEqual(["scout", "olives-mausbot"]);+ });++ it("keeps the bot a routine being changed already has", () => {+ expect(schedulableBots(bots, { me: OLIVE }, "payroll").map((bot) => bot.id)).toEqual(["scout", "payroll", "olives-mausbot"]);+ });++ it("off a team lists every bot shown", () => {+ expect(schedulableBots(bots, null).map((bot) => bot.id)).toEqual(["scout", "payroll", "olives-mausbot", "bobs-mausbot"]);+ });+});diff --git a/src/state/team-people.ts b/src/state/team-people.tsindex 2516f21965..cd8ec00348 100644--- a/src/state/team-people.ts+++ b/src/state/team-people.ts@@ -76,6 +76,14 @@ export function teamBotName(bot: { name: string; defaultBot?: { person?: stringreturn `${bot.name} · ${owner?.name || nameFromEmail(person)}`;}+/** The bots a person may set a routine up for: on a team only the ones they can chat with, never a teammate's own+ * MausBot (`keep`: the bot a routine being changed already has); anywhere else every bot shown. */+export function schedulableBots<T extends { id: string; hidden?: boolean; yourAccess?: string; defaultBot?: { person?: string } }>(bots: readonly T[], team: Pick<TeamPeople, "me"> | null, keep?: string): T[] {+ const me = team?.me?.email.toLowerCase();+ return bots.filter((bot) => bot.id === keep || (!bot.hidden && (!team || ((bot.yourAccess === undefined || bot.yourAccess === "chat" || bot.yourAccess === "edit")+ && (!bot.defaultBot?.person || bot.defaultBot.person.trim().toLowerCase() === me)))));+}+export function mayChangeOwner(bot: { createdBy?: string; reportsTo?: string; defaultBot?: { person?: string } }, team: TeamPeople | null): boolean {return Boolean(team && !bot.defaultBot?.person && (team.admin || (team.me && botOwner(bot) === team.me.email)));}