Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Inbox on every plan: one row, one panel, for every place
milind-soni0ea63c67f52f
diff --git a/apps/docs/content/docs/features/chat-and-teams.mdx b/apps/docs/content/docs/features/chat-and-teams.mdxindex c7aaba53a2..5e3234e5a1 100644--- a/apps/docs/content/docs/features/chat-and-teams.mdx+++ b/apps/docs/content/docs/features/chat-and-teams.mdx@@ -90,6 +90,8 @@ On a team's Cloud, everything for you arrives in one place: your chat with your**Answering is replying.** Use **Reply** on a line, give it a 👍 or 👎, or just tell your Chief ("tell Cleo Friday works"). The answer goes back where the line came from: to the bot that asked, which carries on, or to the teammate's own inbox. Only your answer goes, nothing else from your chat.+**Everyone has an Inbox.** It is the row at the top of the sidebar, with no team and no account too: questions and approvals your bots wait on, what they sent you, and routine reports, each labelled with who it is from. Answer there and the bot carries on. Each place keeps its own, so the dot on a place in the rail tells you where something waits.+**Your inbox at a glance.** In your chat with your Chief, one card keeps what needs you in view: how many things need you and how many are just for your information, the newest few with their answer buttons right there, and **Open inbox**. The whole inbox opens on the right, in three tabs: **Needs you** (questions and approvals), **For your info** (reports, mentions and messages) and **Done**. Click a line to read it in full and answer or reply; mark news done when you need nothing more from it. On a phone it opens as a sheet.**What waits on you is counted.** Your own row under People shows how many questions and approvals wait on you in your inbox, and the same number is added to the count on the app's icon and in the browser tab. It drops as soon as you settle one, wherever you do it: in your inbox, in the chat it came from, or on your phone. A message you answer in the chat it came from leaves **Needs you** too.diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 4a23d9cf7a..c905b1e20d 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -64,6 +64,18 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes t- **Never asleep, kept across restarts.** A Team Cloud refuses the Admin's sleep request (`busy: ["team"]`) and keepsevery member's session across a restart; a My Cloud revokes every session that is not its owner's at each boot.++### Off a team++Everyone has an Inbox: on a personal Cloud and in the desktop app with no account, the same row at the top of the sidebar+opens the same panel. Each place keeps its own, where its bots live, and nothing syncs; the rail's "{name}: needs you"+says which place to open. There is one person, so nothing is routed and nobody's assistant answers. An approval or a+question is the open card itself, listed from where it was asked, so one answer settles it however many surfaces show it+and whatever was waiting before an upgrade is listed. `message_person` leaves out `to`: it posts one line in its+conversation and sends one notification, and a reply is an ordinary line there. A routine's report and a failure of work+nobody watches each get a line, in `place-inbox.json`. A guest's conversation left on a Cloud reaches its owner labelled+with who asked, and its news stays out of the owner's list. See [Verifying the Inbox](verification/inbox.md).+## RulesThe team's rules live on the Admin (openmaus-cloud `docs/team-cloud.md` "Rules"): one document, `{ schema: 1, limits }`, thatdiff --git a/docs/verification/README.md b/docs/verification/README.mdindex 0e3222533e..2d0f6dcfe3 100644--- a/docs/verification/README.md+++ b/docs/verification/README.md@@ -68,6 +68,7 @@ Use only mapped, tested commands:- [Waits: tell me when, with no AI while waiting](waits.md)- [A new Cloud's first hour](first-hour.md)- [Chat widgets](widgets.md)+- [The Inbox on every plan](inbox.md)- [Reactions](reactions.md)- [Chat widgets: prompts to try with a real bot](widget-prompts.md)- [Phone web app installation and safe areas](phone-web-app.md)diff --git a/docs/verification/inbox.md b/docs/verification/inbox.mdnew file mode 100644index 0000000000..24613349ff--- /dev/null+++ b/docs/verification/inbox.md@@ -0,0 +1,19 @@+# The Inbox on every plan++`server/place-inbox.e2e.test.ts` boots this computer's server and My Cloud's with the synthetic Claude CLI, and on each:++1. An empty inbox answers with no rows, not 404.+2. A bot's approval and question, in two threads at once, are listed with count 2, each labelled with its thread.+3. An answer through the row's own conversation reaches the bot, its turn goes on and the count clears. A second answer to+ the same card is refused.+4. `message_person` arrives as one line, one row and one notification, and a reply reaches the bot.++On My Cloud it also checks that nobody connects as a guest, that a bot's shell reads nothing, and that a guest's conversation+left behind reaches the owner labelled, with its news kept away.++```sh+pnpm exec vitest run server/place-inbox.e2e.test.ts+```++The rail's count comes from `electron/place-inbox-watch.mjs`, tested in `electron/place-inbox-watch.node-test.mjs`. It never+asks a Cloud the Admin says is asleep. It has not been watched against a real sleeping Cloud.diff --git a/docs/verification/sidebar-attention.md b/docs/verification/sidebar-attention.mdindex c3036e9382..c61ceee693 100644--- a/docs/verification/sidebar-attention.md+++ b/docs/verification/sidebar-attention.md@@ -1,5 +1,8 @@# Sidebar attention popover geometry+The Inbox row replaced this menu. It opens only for a page on a server older than the page, which answers `/api/inbox` with+404 off a team, and [the fixture](../../scripts/testing/sidebar-attention-preview.tsx) shows the sidebar that way.+The Active Threads menu in the sidebar header is anchored `right-0` insidethe header's icon group, which sits 16px (`px-4`) inside the sidebar's rightedge, so the menu's width decides whether it fits: a menu wider than thediff --git a/docs/verification/threads.md b/docs/verification/threads.mdindex 7a4e9bd01e..220d099c8c 100644--- a/docs/verification/threads.md+++ b/docs/verification/threads.md@@ -89,7 +89,7 @@ switching and Stop can be exercised without a real provider or account.returns. Timed snoozes also return when due without a new server snapshot.Pinned, selected, unread, queued, and working threads remain reachable.Snooze is a display preference, not a pause or cancellation of work.-16. Open **Active Threads** while a channel is working. Its entry should name+16. Open the **Inbox** row, then **Active Threads** in its panel, while a channel is working. Its entry should namethe channel and open that channel's exact thread, not a member's directchat. Direct-chat and channel activity can appear together.17. In compact/quiet rows, idle message previews disappear but working,diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mtsindex c186fe385f..fecf876808 100644--- a/electron/cloud-rail.d.mts+++ b/electron/cloud-rail.d.mts@@ -13,7 +13,7 @@ export interface RailPlace {progress?: number;/** Waiting for its payment. */waiting?: true;- /** Something needs the person there (a payment problem on a Cloud they own). */+ /** Something needs the person there: a line in that place's inbox, or a payment problem on a Cloud they own. */attention?: true;/** A server or computer of the person's own that signed in with their account. */server?: true;@@ -70,5 +70,5 @@ export type AddCloudView =};export declare const RAIL_MIN_PLACES: number;/** main's own circles: each as the page sees it, plus the Cloud main acts on for it (never sent to a page). */-export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown; offers?: (entry: any) => boolean }): Array<RailPlace & { cloudId?: string }>;+export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown; offers?: (entry: any) => boolean; waiting?: (id: string) => boolean }): Array<RailPlace & { cloudId?: string }>;export declare function addCloudView(state: unknown, offer: import("./cloud-home.mjs").CloudOffer | null): AddCloudView;diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjsindex 8ebcb6a8d8..6d98704a57 100644--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@ -29,7 +29,7 @@ const machineProgress = machine => {/** One saved place as a circle: what it is, its colour (and who may change it from the rail) and how it is doing, from* the session's word for it. */-function circle(entry, { activeId, mine, state, offers }) {+function circle(entry, { activeId, mine, state, offers, waiting }) {const connected = state?.status === "connected" ? state : null;const listed = connected?.clouds?.find(cloud => cloud.origin === entry.origin) ?? null;const kind = entry.origin === mine || entry.home || entry.cloud ? "cloud" : entry.team ? "team" : "server";@@ -40,7 +40,7 @@ function circle(entry, { activeId, mine, state, offers }) {const color = environments.ENTRY_COLORS.includes(entry.color) ? entry.color : listed ? swatchColor(listed.color) : null;const paint = railPaint(placeLook(entry, { clouds: connected?.clouds ?? null, homeOrigin: mine }), color);return { id: entry.id, name: entry.name, color, kind, opens: true, ...(paint ? { paint } : {}), ...(entry.id === activeId ? { active: true } : {}),- ...(progress !== null ? { progress } : {}), ...(problem ? { attention: true } : {}), ...(listed?.managed === false ? serverState(listed, connected?.latestVersion ?? null) : {}),+ ...(progress !== null ? { progress } : {}), ...(problem || waiting(entry.id) ? { attention: true } : {}), ...(listed?.managed === false ? serverState(listed, connected?.latestVersion ?? null) : {}),...(kind === "cloud" && cloudState(listed) === "ended" ? { ended: true } : {}), ...(listed?.removable && kind === "cloud" ? { removable: true, cloudId: listed.id } : {}), ...(kind === "server" ? { removable: true, forget: true } : {}),...(kind === "server" && offers(entry) ? { makeHome: true } : {}) };}@@ -59,10 +59,11 @@ const unlisted = (entry, { clouds, home, mine }) => Array.isArray(clouds) && (en* checkout or its setup), never an address. My Cloud's saved place leaves once the session's list doesn't have it (removed* from the list). Fewer than RAIL_MIN_PLACES places in all, This computer counted while it is one: no rail at all, the window* as it was, unless the person has a Cloud of their own: then its one circle is the rail, for the + that buys another.- * `offers(entry)`: a server connected by hand whose menu offers Make … my home (own-home-main.mjs).- * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean }} input+ * `offers(entry)`: a server connected by hand whose menu offers Make … my home (own-home-main.mjs). `waiting(id)`: inbox lines+ * wait in that place, and the window shows another (place-inbox-watch.mjs).+ * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean, waiting?: (id: string) => boolean }} input*/-export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false }) {+export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = () => false }) {const connected = state?.status === "connected" ? state : null;const clouds = Array.isArray(connected?.clouds) ? connected.clouds : [];const order = entry => { const at = clouds.findIndex(cloud => cloud.origin === entry.origin); return at === -1 ? clouds.length : at; };@@ -70,7 +71,7 @@ export function railPlaces({ saved, home = null, mine = null, state = null, offeconst remote = saved.environments.filter(entry => entry.kind !== "local" && entry.origin && !(connected && unlisted(entry, { clouds: connected.clouds, home, mine }))).map((entry, index) => ({ entry, index })).sort((a, b) => rank(a.entry) - rank(b.entry) || order(a.entry) - order(b.entry) || a.index - b.index)- .map(({ entry }) => circle(entry, { activeId: saved.activeId, mine, state: connected, offers }));+ .map(({ entry }) => circle(entry, { activeId: saved.activeId, mine, state: connected, offers, waiting }));const making = otherOwnClouds(clouds).filter(cloud => !cloud.origin && ["checkout", "setting_up"].includes(cloud.status)).map(cloud => ({ id: `${PENDING}${cloud.id}`, name: cloud.name, color: swatchColor(cloud.color), kind: "cloud", opens: true, progress: cloudSetupProgress(cloud) ?? 0,...(cloud.status === "checkout" ? { waiting: true } : {}), cloudId: cloud.id }));@@ -81,7 +82,7 @@ export function railPlaces({ saved, home = null, mine = null, state = null, offeconst places = [...remote, ...servers, ...making];const computer = environments.savedPlace(saved, environments.LOCAL_ID), color = computer.color ?? null;const all = home ? places : [{ id: computer.id, name: computer.name, color, kind: "computer", opens: true, paint: railPaint(placeLook(computer), color),- ...(saved.activeId === environments.LOCAL_ID ? { active: true } : {}) }, ...places];+ ...(saved.activeId === environments.LOCAL_ID ? { active: true } : {}), ...(waiting(computer.id) ? { attention: true } : {}) }, ...places];return all.length < (clouds.some(ownCloud) ? 1 : RAIL_MIN_PLACES) ? [] : all;}diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjsindex 832b7cef2d..e59d40c474 100644--- a/electron/cloud-rail.node-test.mjs+++ b/electron/cloud-rail.node-test.mjs@@ -368,3 +368,11 @@ test("Remove from list on a server saved by hand: main forgets it here, by its oassert.deepEqual(await rail({ forget: async () => false }).call("workspaces:remove", "vps"), { outcome: "failed" });assert.deepEqual(await rail().call("workspaces:remove", "vps"), { outcome: "unsupported" }, "a main without forget says so");});++test("a place with inbox lines waiting says so on its circle, this computer's too; the Admin's payment problem still does", () => {+ const places = railPlaces({ saved: saved("home"), mine: HOME, state: session(), waiting: id => id === "a" || id === "local" });+ assert.equal(places.find(place => place.id === "a").attention, true);+ assert.equal(places.find(place => place.id === "local").attention, true);+ assert.equal(places.find(place => place.id === "vps").attention, undefined);+ assert.equal(railPlaces({ saved: saved("home"), mine: HOME, state: session() }).find(place => place.id === "a").attention, undefined, "with nothing to say, nothing fires");+});diff --git a/electron/main.mjs b/electron/main.mjsindex 962dc89b85..7295656f3d 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -108,7 +108,7 @@ import { installOneHome } from "./one-home-main.mjs"; import { handSaved, instalimport { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";import { createTeamProfileSeeds } from "./team-profile-seed.mjs";-import { createHomePlaces } from "./home-places.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs";+import { createHomePlaces } from "./home-places.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs";import { createWindowStateFile } from "./window-state-file.mjs";import { createEnvironmentsFile } from "./environments-file.mjs";import { createOrgLibrary } from "./org-library.mjs";@@ -2682,8 +2682,8 @@ function showHome(options) {return homeWindow.show(options).catch(error => slog(`home: ${error?.message ?? error}`));}const openOwnCloud = id => showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } });-// The rail and its + (cloud-rail.mjs): its list for this app's page and hosted Clouds' pages only, opened through switchEnvironment.-const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true }); };+const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() });+const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true }); };// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(),args: () => [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`],diff --git a/electron/place-inbox-watch.mjs b/electron/place-inbox-watch.mjsnew file mode 100644index 0000000000..b0a7a2c91a--- /dev/null+++ b/electron/place-inbox-watch.mjs@@ -0,0 +1,68 @@+// How many inbox lines wait in each place the window isn't showing, for the rail's "{name}: needs you". Each place keeps its+// own inbox and nothing syncs: main only asks each place for its count, as the signed-in person, and keeps the number.+// A Cloud the Admin says is asleep is never asked, since any request would wake it; it keeps the last number it gave.+import { BACKGROUND_HEADERS } from "./cloud-power.mjs";++export const INBOX_WATCH_MS = 120_000;+const TIMEOUT_MS = 10_000;++/**+ * @param {{+ * places(): Array<{ id: string, origin?: string | null, local?: boolean }>,+ * activeId(): string,+ * local(route: string, init?: RequestInit): Promise<Response>,+ * cloudFetch(url: string, init?: RequestInit): Promise<Response>,+ * asleep(origin: string): boolean,+ * shown(): boolean,+ * changed(): void,+ * setTimer?: typeof setInterval,+ * }} deps `places`: every saved place with its address, this computer `local`; `shown`: the window can be seen, so a rail is.+ */+export function createPlaceInboxWatch({ places, activeId, local, cloudFetch, asleep, shown, changed, setTimer = setInterval }) {+ const counts = new Map();+ let started = false, reading = null;++ async function countOf(place) {+ const signal = AbortSignal.timeout(TIMEOUT_MS);+ const response = await (place.local+ ? local("/api/inbox/count", { signal })+ : cloudFetch(`${place.origin}/api/inbox/count`, { headers: BACKGROUND_HEADERS, credentials: "include", cache: "no-store", redirect: "error", signal }));+ if (!response?.ok) return null;+ const body = await response.json().catch(() => null);+ return Number.isSafeInteger(body?.count) && body.count >= 0 ? body.count : null;+ }++ async function read() {+ const listed = places().filter((place) => place.local || (place.origin && !asleep(place.origin)));+ const before = JSON.stringify([...counts]);+ await Promise.all(listed.map(async (place) => {+ const count = await countOf(place).catch(() => undefined);+ // A place that can't say keeps its last number; one that says it has no inbox has none.+ if (count === null) counts.delete(place.id);+ else if (count !== undefined) counts.set(place.id, count);+ }));+ if (JSON.stringify([...counts]) !== before) changed();+ }++ function look() {+ if (reading || !shown()) return reading ?? Promise.resolve();+ reading = read().finally(() => { reading = null; });+ return reading;+ }++ function start() {+ if (started) return;+ started = true;+ setTimer(() => void look(), INBOX_WATCH_MS)?.unref?.();+ void look();+ }++ return {+ look,+ /** Something waits in this place, and the window is showing another one. */+ waiting(id) {+ start();+ return id !== activeId() && (counts.get(id) ?? 0) > 0;+ },+ };+}diff --git a/electron/place-inbox-watch.node-test.mjs b/electron/place-inbox-watch.node-test.mjsnew file mode 100644index 0000000000..9990cc4c2d--- /dev/null+++ b/electron/place-inbox-watch.node-test.mjs@@ -0,0 +1,89 @@+import assert from "node:assert/strict";+import test from "node:test";++import { createPlaceInboxWatch, INBOX_WATCH_MS } from "./place-inbox-watch.mjs";++const answer = (status, body) => ({ ok: status < 400, status, json: async () => body });++function setup(over = {}) {+ const asked = [], counts = { local: 0, "https://a.test": 0, "https://b.test": 0 };+ let changes = 0, tick = null;+ const watch = createPlaceInboxWatch({+ places: () => [{ id: "local", local: true }, { id: "a", origin: "https://a.test" }, { id: "b", origin: "https://b.test" }],+ activeId: () => "local",+ local: async (route) => { asked.push(["local", route]); return answer(200, { count: counts.local }); },+ cloudFetch: async (url, init) => { asked.push([url, init.headers["x-omb-background"]]); const origin = new URL(url).origin; return counts[origin] === null ? answer(404, {}) : answer(200, { count: counts[origin] }); },+ asleep: () => false, shown: () => true, changed: () => { changes += 1; },+ setTimer: (run, ms) => { tick = { run, ms }; return {}; },+ ...over,+ });+ return { watch, asked, counts, changes: () => changes, tick: () => tick };+}++test("a place with something waiting fires, and only once the window shows another", async () => {+ const f = setup();+ f.counts["https://a.test"] = 2;+ f.counts.local = 3;+ f.watch.waiting("a");+ await f.watch.look();+ assert.equal(f.watch.waiting("a"), true);+ assert.equal(f.watch.waiting("b"), false);+ assert.equal(f.watch.waiting("local"), false, "the place on screen has its own row");+ assert.equal(f.changes(), 1);+ await f.watch.look();+ assert.equal(f.changes(), 1, "the rail is told only when a number moved");+ f.counts["https://a.test"] = 0;+ await f.watch.look();+ assert.equal(f.watch.waiting("a"), false);+ assert.equal(f.changes(), 2);+});++test("asks each Cloud as background work, so asking never counts as the person using it", async () => {+ const f = setup();+ await f.watch.look();+ assert.deepEqual(f.asked.find(([url]) => url === "https://a.test/api/inbox/count"), ["https://a.test/api/inbox/count", "1"]);+ assert.deepEqual(f.asked.find(([url]) => url === "local"), ["local", "/api/inbox/count"]);+});++test("never asks a sleeping Cloud, which any request would wake; it keeps the last number", async () => {+ let asleep = false;+ const f = setup({ asleep: (origin) => asleep && origin === "https://a.test" });+ f.counts["https://a.test"] = 1;+ f.watch.waiting("a");+ await f.watch.look();+ assert.equal(f.watch.waiting("a"), true);+ asleep = true;+ f.asked.length = 0;+ f.counts["https://a.test"] = 0;+ await f.watch.look();+ assert.equal(f.asked.some(([url]) => String(url).startsWith("https://a.test")), false);+ assert.equal(f.watch.waiting("a"), true);+});++test("an older place with no inbox has nothing waiting, and one that can't be reached keeps its number", async () => {+ const failing = new Set();+ const f = setup({ cloudFetch: async (url) => { if (failing.has(url)) throw new Error("offline"); return String(url).startsWith("https://a.test") ? answer(404, {}) : answer(200, { count: 4 }); } });+ f.watch.waiting("a");+ await f.watch.look();+ assert.equal(f.watch.waiting("a"), false);+ assert.equal(f.watch.waiting("b"), true);+ failing.add("https://b.test/api/inbox/count");+ await f.watch.look();+ assert.equal(f.watch.waiting("b"), true);+});++test("a page's nonsense is no count", async () => {+ const f = setup({ cloudFetch: async () => answer(200, { count: "many" }) });+ f.watch.waiting("a");+ await f.watch.look();+ assert.equal(f.watch.waiting("a"), false);+});++test("asks nothing while the window can't be seen, and starts its clock once on the first read of the list", async () => {+ const f = setup({ shown: () => false });+ f.watch.waiting("a");+ f.watch.waiting("b");+ await f.watch.look();+ assert.deepEqual(f.asked, []);+ assert.equal(f.tick().ms, INBOX_WATCH_MS);+});diff --git a/scripts/testing/sidebar-attention-preview.tsx b/scripts/testing/sidebar-attention-preview.tsxindex c8528aed1f..e7a3ab89ee 100644--- a/scripts/testing/sidebar-attention-preview.tsx+++ b/scripts/testing/sidebar-attention-preview.tsx@@ -1,9 +1,11 @@// The sidebar attention popover geometry fixture: the real Sidebar pinned to the// ?density= before the first render, since Sidebar reads its density from-// localStorage once, at mount.+// localStorage once, at mount, as it shows on a server with no inbox, the only+// place the popover still opens.import { createRoot } from "react-dom/client";import { saveSidebarDensity } from "../../src/lib/sidebar-preferences";import { Sidebar } from "../../src/components/Sidebar";+import { setInboxSupport } from "../../src/state/inbox";import { StoreProvider } from "../../src/state/store";import { applySkin, readSkin } from "../../src/lib/skins";import "../../src/styles.css";@@ -13,6 +15,8 @@ if (density === "comfortable" || density === "icons") {saveSidebarDensity(density);}+setInboxSupport("no");+function Fixture() {return <div className="flex h-screen"><Sidebar open onClose={() => {}} />diff --git a/server/drivers/agents-catalog-wire.test.ts b/server/drivers/agents-catalog-wire.test.tsindex 2facd4026f..2f98a31fe8 100644--- a/server/drivers/agents-catalog-wire.test.ts+++ b/server/drivers/agents-catalog-wire.test.ts@@ -242,21 +242,9 @@ describe("agents proxy tools/list golden", () => {}});- it("mounts message_person only on a Team Cloud, and adds nothing else", () => {+ it("mounts message_person everywhere: every plan's bots can reach the person's Inbox", () => {const names = (wire: string) => toolsOf(wire).map((tool) => tool.name);- expect(names(wires[FULL]!).filter((tool) => tool !== "message_person")).toEqual(names(wires["skills+shared+voice+escalations+x"]!));- for (const [name, profile] of Object.entries(PROFILES)) {- expect(names(wires[name]!).includes("message_person"), name).toBe(profile.env.OMB_TEAM_PEOPLE === "1");- }- });-- it("mounts ask_for_computer only on a person's own Cloud that is lent their computer, never a Team Cloud", () => {- for (const [name, profile] of Object.entries(PROFILES)) {- expect(toolsOf(wires[name]!).some((tool) => tool.name === "ask_for_computer"), name)- .toBe(profile.env.OMB_CLOUD_HOME === "1" && profile.env.OMB_SHARED_COMPUTERS_ENABLED === "1" && profile.env.OMB_TEAM_PEOPLE !== "1");- }- const team = catalogProfileFromEnv({ ...PROFILES["skills+shared+voice+cloud-home"]!.env, OMB_TEAM_PEOPLE: "1", OMB_BOT_ID: "bot-golden" });- expect(availableTools(team).map((tool) => tool.name)).not.toContain("ask_for_computer");+ for (const name of Object.keys(PROFILES)) expect(names(wires[name]!), name).toContain("message_person");});it("ignores the switches that once picked a catalog profile", () => {diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.tsindex ba011986c3..75eddba0c9 100644--- a/server/drivers/agents-catalog.ts+++ b/server/drivers/agents-catalog.ts@@ -9,7 +9,7 @@ import { USAGE_LIMITS_TOOL_DEFINITION } from "./agents-usage-tool.ts";import { WAIT_TOOL_DEFINITIONS, WAIT_TOOL_NAMES } from "./agents-wait-tools.ts";import { COMPUTER_ASK_TOOL_DEFINITIONS, COMPUTER_ASK_TOOL_NAMES } from "./agents-computer-ask-tool.ts";import { MAUSBOT_TOOL_DEFINITIONS } from "./agents-mausbot-tools.ts";-import { PERSON_TOOL_DEFINITIONS, PERSON_TOOL_NAMES } from "./agents-person-tools.ts";+import { PERSON_TOOL_DEFINITIONS } from "./agents-person-tools.ts";import { RESEARCH_TOOL_DEFINITIONS, RESEARCH_TOOL_NAMES, X_TOOL_NAMES } from "./agents-research-tools.ts";import type { CatalogProfile } from "./agents-catalog-profile.ts";import { advertisedSchema } from "./agents-schema.ts";@@ -912,7 +912,6 @@ function catalogTools(profile: CatalogProfile) {(profile.botId === WATCHER_OPTIONS_CARD_BOT_ID || !WATCHER_TOOL_NAMES.has(tool.name)) &&(profile.memoryEnabled !== false || (tool.name !== "memory_update" && tool.name !== "memory_log")) &&(profile.escalations === true || tool.name !== "raise_escalation") &&- (profile.team === true || !PERSON_TOOL_NAMES.has(tool.name)) &&(profile.computerSelection === true || tool.name !== "select_computer") &&(profile.room !== true || !ROOM_REFUSED_TOOL_NAMES.has(tool.name)));const AUTHORING_TOOLS = profile.skillAuthoringdiff --git a/server/drivers/agents-person-tools.ts b/server/drivers/agents-person-tools.tsindex d643e4ccd6..ade16ce694 100644--- a/server/drivers/agents-person-tools.ts+++ b/server/drivers/agents-person-tools.ts@@ -1,5 +1,5 @@-// The agents catalog's message_person tool, shown only on a Team Cloud (OMB_TEAM_PEOPLE), and the internal route behind-// it (server/host/team-messages.ts), which decides where the message goes and refuses in words a bot can repeat.+// The agents catalog's message_person tool and the internal route behind it (server/host/team-messages.ts), which decides+// where the message goes and refuses in words a bot can repeat. On a team it names a person; anywhere else there is one.import type { ToolCallContext, ToolCallResult } from "./agents-call.ts";import type { Json } from "./agents-client.ts";@@ -8,8 +8,8 @@ export const PERSON_TOOL_NAMES: ReadonlySet<string> = new Set(["message_person"]export async function callPersonTool(_name: string, args: Json, context: ToolCallContext): Promise<ToolCallResult> {const to = typeof args.to === "string" ? args.to.trim() : "";const message = typeof args.message === "string" ? args.message.trim() : "";- if (!to || !message) return { text: "message_person needs to (a teammate's name or email) and message.", isError: true };- const { ok, body } = await context.client.apiResponse("/api/internal/people/message", { method: "POST", body: JSON.stringify({ to, message }) });+ if (!message) return { text: "message_person needs message.", isError: true };+ const { ok, body } = await context.client.apiResponse("/api/internal/people/message", { method: "POST", body: JSON.stringify({ ...(to ? { to } : {}), message }) });return ok ? { text: String(body.text ?? "Passed on.") } : { text: String(body.error ?? "The message could not be passed on. Try again shortly."), isError: true };}@@ -17,15 +17,15 @@ export const PERSON_TOOL_DEFINITIONS = [{name: "message_person",description:- "Pass a message to a person on this team, when someone asks you to tell them something (\"tell Bob the launch moved\"). Only your message goes, never this conversation. Someone who can see this conversation is tagged here; anyone else gets it in a new private conversation with you, and their answer can come back here.",+ "Get a message to a person's Inbox, when someone asks you to tell them something (\"tell Bob the launch moved\") or when you have news for someone who isn't watching this conversation. Only your message goes, never this conversation, and their answer comes back here. With people on a team, say who with `to`; with none, leave `to` out and it reaches the one person here.",inputSchema: {type: "object",additionalProperties: false,properties: {- to: { type: "string", maxLength: 254, description: "Their name or email address." },+ to: { type: "string", maxLength: 254, description: "Their name or email address, on a team; otherwise leave it out." },message: { type: "string", maxLength: 2000, description: "What to tell them, in your words, complete on its own." },},- required: ["to", "message"],+ required: ["message"],},},];diff --git a/server/host/person-inbox.ts b/server/host/person-inbox.tsindex a1e49edb96..df6aee0bfe 100644--- a/server/host/person-inbox.ts+++ b/server/host/person-inbox.ts@@ -5,7 +5,8 @@// Replying to a line answers it: the answer goes back to the bot that asked, which carries on, or to the teammate's own// inbox. A question that a fact the person shares with the team answers, their assistant may answer (representative.ts).// Security: a line carries only what was addressed to the person, and links its conversation only when they may read-// it. The state is ids, names and short excerpts, in person-inbox.json. Off a team nothing here exists.+// it. The state is ids, names and short excerpts, in person-inbox.json. Off a team nothing here exists: place-inbox.ts is+// the inbox there.import { readFileSync } from "node:fs";import { join } from "node:path";import { z } from "zod";diff --git a/server/host/place-inbox.test.ts b/server/host/place-inbox.test.tsnew file mode 100644index 0000000000..e029ce87e4--- /dev/null+++ b/server/host/place-inbox.test.ts@@ -0,0 +1,242 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import type { Notification } from "../../shared/notification.ts";+import type { OptionCardData } from "../../shared/wire.ts";+import type { RequestAuth } from "../request-auth.ts";+import { createPlaceInbox, PLACE_MESSAGES_HOURLY, type InboxViewer, type OpenCardRow, type PlaceInboxDeps } from "./place-inbox.ts";++const OWNER = { kind: "owner-session" } as unknown as RequestAuth;+const GUEST = { kind: "guest-session" } as unknown as RequestAuth;+const SHELL = { kind: "shell" } as unknown as RequestAuth;+const viewers = new Map<RequestAuth, InboxViewer>([[OWNER, { kind: "owner" }], [GUEST, { kind: "guest", key: "p_guest" }], [SHELL, { kind: "nobody" }]]);++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++type Said = { id: string; at: number; role: string; peerAsk?: boolean; relayed?: boolean; via?: string; text?: string; inbox?: unknown };++function setup(over: Partial<PlaceInboxDeps> = {}, dataDir = mkdtempSync(join(tmpdir(), "place-inbox-"))) {+ dirs.push(dataDir);+ let clock = 1_000;+ let serial = 0;+ const said = new Map<string, Said[]>();+ const cards: OpenCardRow[] = [];+ const sent: Notification[] = [];+ const handed = new Map<string, string>();+ const guests = new Map<string, string>();+ const bots: Record<string, { id: string; name: string; threadId: string; color: string; notifications?: boolean }> = {+ eli: { id: "eli", name: "Eli", threadId: "eli-main", color: "blue" }, mira: { id: "mira", name: "Mira", threadId: "mira-main", color: "red" },+ };+ const titles: Record<string, string> = { "eli-main": "Eli", "eli-pricing": "Pricing work", "eli-launch": "Launch work", "guest-chat": "Guest chat" };+ const listeners: Array<(change: { type: string; threadId: string }) => void> = [];+ const store = {+ bot: (id: string) => bots[id],+ botByThread: (threadId: string) => (threadId.startsWith("eli") || threadId === "guest-chat" ? bots.eli : threadId.startsWith("mira") ? bots.mira : undefined),+ taskByThread: (_botId: string, threadId: string) => (titles[threadId] ? { threadId, title: titles[threadId] } : undefined),+ groupByThread: () => undefined,+ appendMessage: (threadId: string, line: Omit<Said, "id" | "at">) => {+ const posted = { ...line, id: `m${++serial}`, at: clock };+ said.set(threadId, [...(said.get(threadId) ?? []), posted]);+ return posted;+ },+ patchTask: () => undefined, patchGroup: () => undefined,+ messagesFor: (threadId: string) => said.get(threadId) ?? [],+ onChange: (listener: (change: { type: string; threadId: string }) => void) => { listeners.push(listener); return () => undefined; },+ };+ const inbox = createPlaceInbox({+ dataDir, store: store as unknown as PlaceInboxDeps["store"], openCards: () => cards,+ viewer: (auth) => viewers.get(auth)!,+ sees: (auth, threadId) => auth === OWNER || threadId === "guest-chat",+ mayAnswer: (auth) => auth === OWNER,+ guestOf: (threadId) => guests.get(threadId) ?? null, guestName: () => "Sam",+ handedBy: (threadId) => handed.get(threadId) ?? null,+ send: (one) => sent.push(one), now: () => clock, ...over,+ });+ const ask = (threadId: string, requestId: string, card: Partial<OptionCardData> = {}, at = clock) => {+ const row = { threadId, id: `card-${requestId}`, at, fromBotId: null, card: JSON.stringify({ requestId, title: "Ask", subtitle: `Ask ${requestId}`, options: ["Yes", "No"], requestType: "question", ...card }) };+ cards.push(row);+ return row;+ };+ return { inbox, store, said, cards, sent, handed, guests, bots, listeners, ask, dataDir, tick: (ms: number) => { clock += ms; } };+}++describe("the inbox of a place that is no team's", () => {+ it("lists what was already waiting, whenever it was asked, with no copy and no notification of its own", () => {+ const f = setup();+ f.ask("eli-main", "old", { tool: "Bash", requestType: "permission" }, 1);+ f.ask("mira-main", "new");+ const { rows, threadId, botId } = f.inbox.view(OWNER);+ expect({ threadId, botId }).toEqual({ threadId: null, botId: null });+ expect(rows.map((row) => [row.id, row.kind, row.tab, row.from.name, row.origin?.threadId, row.card?.requestId])).toEqual([+ ["card-new", "ask", "needs-you", "Mira", "mira-main", "new"],+ ["card-old", "ask", "needs-you", "Eli", "eli-main", "old"],+ ]);+ expect(f.inbox.count(OWNER)).toBe(2);+ expect(f.sent).toEqual([]);+ expect(f.said.size, "nothing was copied anywhere").toBe(0);+ });++ it("drops an ask as soon as its card leaves the open cards, however it was answered", () => {+ const f = setup();+ f.ask("eli-main", "q");+ expect(f.inbox.count(OWNER)).toBe(1);+ f.cards.length = 0;+ expect(f.inbox.count(OWNER)).toBe(0);+ expect(f.inbox.view(OWNER).rows).toEqual([]);+ });++ it("leaves out offers and receipts, and a card somebody already settled", () => {+ const f = setup();+ f.ask("eli-main", "offer", { quotaSwitch: {} as never });+ f.ask("eli-main", "sent", { outboundRequest: {} as never });+ f.ask("eli-main", "auto", { autoApplied: true });+ f.ask("eli-main", "answered", { answered: "allow" });+ expect(f.inbox.view(OWNER).rows).toEqual([]);+ });++ it("says who a bot was working for, and which conversation an item came from", () => {+ const f = setup();+ f.handed.set("eli-pricing", "mira");+ f.ask("eli-pricing", "a");+ f.ask("eli-launch", "b");+ const rows = f.inbox.view(OWNER).rows;+ const of = (id: string) => rows.find((row) => row.id === id)!;+ expect(of("card-a")).toMatchObject({ workingFor: { botId: "mira", name: "Mira" }, origin: { title: "Pricing work" } });+ expect(of("card-b").workingFor).toBeUndefined();+ expect(of("card-b").origin?.title).toBe("Launch work");+ });++ it("gets a bot's message to the person once: one line, one row, one notification, and their words settle it", () => {+ const f = setup();+ const sent = f.inbox.message("eli", "eli-pricing", "The report is ready.");+ expect(sent.status).toBe(200);+ expect(f.sent.map((one) => [one.kind, one.threadId, one.body])).toEqual([["mention", "eli-pricing", "The report is ready."]]);+ const [row] = f.inbox.view(OWNER).rows;+ expect(row).toMatchObject({ kind: "message", tab: "info", unread: true, replies: true, from: { name: "Eli" }, origin: { threadId: "eli-pricing", messageId: row!.id } });+ expect(f.said.get("eli-pricing")!.map((line) => line.id)).toEqual([row!.id]);+ expect(f.inbox.count(OWNER)).toBe(1);++ f.tick(10);+ f.store.appendMessage("eli-pricing", { role: "user", relayed: true });+ expect(f.inbox.view(OWNER).rows[0]!.tab, "a line relayed from another app isn't the person's answer").toBe("info");+ f.store.appendMessage("eli-pricing", { role: "user", via: "api" });+ expect(f.inbox.view(OWNER).rows[0]!.tab, "nor one through the API").toBe("info");+ f.store.appendMessage("eli-pricing", { role: "user", text: "Thanks" });+ expect(f.inbox.view(OWNER).rows[0]!.tab).toBe("done");+ expect(f.inbox.count(OWNER)).toBe(0);+ });++ it("stops a loop of messages from one conversation, and refuses a conversation that isn't the bot's", () => {+ const f = setup();+ for (let index = 0; index < PLACE_MESSAGES_HOURLY; index++) expect(f.inbox.message("eli", "eli-main", `m${index}`).status).toBe(200);+ expect(f.inbox.message("eli", "eli-main", "one more").status).toBe(429);+ expect(f.sent).toHaveLength(PLACE_MESSAGES_HOURLY);+ expect(f.inbox.message("eli", "somewhere-else", "hi").status).toBe(403);+ expect(f.inbox.message("nobody", "eli-main", "hi").status).toBe(403);+ });++ it("counts news until it is read, and a routine's report notifies only through the notification it came with", () => {+ const f = setup();+ const note: Notification = { kind: "done", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Daily digest", body: "3 new leads" };+ expect(f.inbox.route(note, { routine: true })).toBe(note);+ expect(f.sent).toEqual([]);+ const [row] = f.inbox.view(OWNER).rows;+ expect(row).toMatchObject({ kind: "result", text: "3 new leads", tab: "info", unread: true });+ expect(row!.replies).toBeUndefined();+ expect(f.inbox.count(OWNER)).toBe(1);+ expect(f.inbox.markRead(OWNER, row!.id)).toBe(true);+ expect(f.inbox.count(OWNER)).toBe(0);+ expect(f.inbox.markDone(OWNER, row!.id)).toBe("done");+ expect(f.inbox.view(OWNER).rows[0]!.tab).toBe("done");+ });++ it("gives a line to nothing the person is sitting in front of: a chat's own finish and own failure stay out", () => {+ const f = setup();+ f.inbox.route({ kind: "done", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Done", body: "" });+ f.inbox.route({ kind: "turn-failed", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Failed", body: "" });+ f.inbox.route({ kind: "approval", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Approve", body: "" }, { routine: true });+ expect(f.inbox.view(OWNER).rows, "an approval is its card, never a second line").toEqual([]);+ f.inbox.route({ kind: "routine-failed", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Failed", body: "It broke" }, { routine: true });+ f.handed.set("eli-pricing", "mira");+ f.inbox.route({ kind: "turn-failed", botId: "eli", botName: "Eli", threadId: "eli-pricing", title: "Failed", body: "Handed work broke" });+ expect(f.inbox.view(OWNER).rows.map((row) => [row.kind, row.text])).toEqual(expect.arrayContaining([["notice", "It broke"], ["notice", "Handed work broke"]]));+ });++ it("reads an ask as seen without settling it: it still counts, and only its answer closes it", () => {+ const f = setup();+ f.ask("eli-main", "q");+ expect(f.inbox.view(OWNER).rows[0]!.unread).toBe(true);+ expect(f.inbox.markRead(OWNER, "card-q")).toBe(true);+ expect(f.inbox.view(OWNER).rows[0]!.unread).toBe(false);+ expect(f.inbox.count(OWNER)).toBe(1);+ expect(f.inbox.markDone(OWNER, "card-q")).toBe("an ask");+ expect(f.inbox.markRead(OWNER, "not-a-line")).toBe(false);+ expect(f.inbox.markDone(OWNER, "not-a-line")).toBe("unknown");+ });++ it("opening a conversation reads what waited there", () => {+ const f = setup();+ f.inbox.message("eli", "eli-main", "News");+ f.inbox.seen(OWNER, "eli-main");+ expect(f.inbox.view(OWNER).rows[0]!.unread).toBe(false);+ });++ it("forgets a deleted conversation's lines", () => {+ const f = setup();+ f.inbox.message("eli", "eli-main", "News");+ for (const listener of f.listeners) listener({ type: "thread.deleted", threadId: "eli-main" });+ expect(f.inbox.view(OWNER).rows).toEqual([]);+ });++ it("keeps its lines and what was seen across a restart", () => {+ const f = setup();+ f.ask("eli-main", "q");+ f.inbox.markRead(OWNER, "card-q");+ f.inbox.message("eli", "eli-main", "News");+ const again = setup({ openCards: () => f.cards, store: f.store as unknown as PlaceInboxDeps["store"], now: () => 2_000 }, f.dataDir);+ expect(again.inbox.view(OWNER).rows.map((row) => [row.kind, row.unread])).toEqual(expect.arrayContaining([["ask", false], ["message", true]]));+ });++ describe("on a Cloud with a guest", () => {+ function shared() {+ const f = setup();+ f.guests.set("guest-chat", "p_guest");+ f.ask("guest-chat", "theirs");+ f.ask("eli-main", "mine");+ f.inbox.message("eli", "guest-chat", "For the guest");+ f.inbox.message("eli", "eli-main", "For the owner");+ return f;+ }++ it("shows the owner a guest's ask labelled with who asked, since only they can answer it, and never the guest's news", () => {+ const f = shared();+ const rows = f.inbox.view(OWNER).rows;+ expect(rows.find((row) => row.id === "card-theirs")).toMatchObject({ askedBy: { name: "Sam" } });+ expect(rows.find((row) => row.id === "card-mine")!.askedBy).toBeUndefined();+ expect(rows.filter((row) => row.kind === "message").map((row) => row.text)).toEqual(["For the owner"]);+ });++ it("never notifies the owner about a guest's news", () => {+ const f = shared();+ expect(f.sent.map((one) => one.body)).toEqual(["For the owner"]);+ });++ it("shows a guest only their own news, none of the owner's, and no ask they can't answer", () => {+ const f = shared();+ expect(f.inbox.view(GUEST).rows.map((row) => row.text)).toEqual(["For the guest"]);+ expect(f.inbox.count(GUEST)).toBe(1);+ const ownerLine = f.inbox.view(OWNER).rows.find((row) => row.kind === "message")!.id;+ expect(f.inbox.markRead(GUEST, ownerLine), "not theirs to mark").toBe(false);+ expect(f.inbox.markDone(GUEST, ownerLine)).toBe("unknown");+ });++ it("gives nothing to a bot's shell on the Cloud", () => {+ const f = shared();+ expect(f.inbox.view(SHELL).rows).toEqual([]);+ expect(f.inbox.count(SHELL)).toBe(0);+ });+ });+});diff --git a/server/host/place-inbox.ts b/server/host/place-inbox.tsnew file mode 100644index 0000000000..9b5984ece1--- /dev/null+++ b/server/host/place-inbox.ts@@ -0,0 +1,252 @@+// The inbox of a place that is no team's: this computer, or a Cloud of one person. There is one person here, so nothing is+// copied and nothing routed. An ask is the open card itself, read where it was asked, so one tap answers the one card+// however many surfaces show it, and whatever was waiting before this inbox existed is listed. What a bot sent the person+// is a line of its conversation, and a reply there is an ordinary line of theirs.+// Security: a guest's conversation stays out of the owner's lines, and the owner's stays out of a guest's. An ask is listed+// only for someone who may answer it, so a guest's questions reach the owner labelled with who asked, never as their own.+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";++import { isPersistentQuestionCard } from "../../shared/ask-question.ts";+import type { InboxItem, InboxRow, InboxView } from "../../shared/inbox.ts";+import { liveCardKind } from "../../shared/live-approval.ts";+import type { Notification } from "../../shared/notification.ts";+import type { OptionCardData } from "../../shared/wire.ts";+import { ASK_NOTIFICATIONS } from "../ask-routing.ts";+import { writeFileAtomic } from "../atomic.ts";+import type { RequestAuth } from "../request-auth.ts";+import type { Message, Store, StoreChange } from "../store.ts";+import { clip, oneLine } from "./text-clip.ts";++export const PLACE_INBOX_FILE = "place-inbox.json";+const MAX_LINES = 2_000;+const MAX_SEEN_ASKS = 2_000;+const KEEP_MS = 30 * 24 * 60 * 60_000;+const VIEW_ROWS = 200;+const ROW_TEXT_MAX = 4_000;+const NOTICE_TEXT_MAX = 2_000;+const HOUR_MS = 60 * 60_000;+/** Messages from one conversation in an hour: enough for real news, too few for a loop to bury the person. */+export const PLACE_MESSAGES_HOURLY = 10;++const id = z.string().min(1).max(512);+const lineSchema = z.object({+ id, botId: id, threadId: id, groupId: id.optional(), kind: z.enum(["message", "result", "notice"]),+ from: z.string().max(200), workingFor: z.object({ botId: id, name: z.string().max(200) }).optional(),+ /** The guest whose conversation this is: it is theirs, not the owner's. */+ guest: id.optional(),+ text: z.string().max(NOTICE_TEXT_MAX), at: z.number(), seen: z.boolean().optional(), done: z.boolean().optional(),+});+const fileSchema = z.object({ version: z.literal(1), lines: z.array(lineSchema).max(MAX_LINES), seenAsks: z.array(id).max(MAX_SEEN_ASKS) });+type Line = z.infer<typeof lineSchema>;++/** An open card as the messages table holds it. */+export interface OpenCardRow { threadId: string; id: string; at: number; card: string | null; fromBotId: string | null }++/** Who is asking for the inbox: its owner (on a server with members, a member), a guest on someone's Cloud, or nobody it+ * belongs to (a bot's shell on a Cloud, a local service). */+export type InboxViewer = { kind: "owner" } | { kind: "guest"; key: string } | { kind: "nobody" };++export interface PlaceInboxDeps {+ dataDir: string;+ store: Pick<Store, "bot" | "botByThread" | "taskByThread" | "groupByThread" | "appendMessage" | "patchTask" | "patchGroup" | "messagesFor" | "onChange">;+ openCards(): OpenCardRow[];+ viewer(auth: RequestAuth): InboxViewer;+ sees(auth: RequestAuth, threadId: string): boolean;+ /** Whose answer counts on this card; decided where cards are answered, so a row never offers what the answer would refuse. */+ mayAnswer(auth: RequestAuth, threadId: string, requestId: string): boolean;+ /** The guest this conversation is for; null for the owner's own, and for work no guest asked for. */+ guestOf(threadId: string): string | null;+ /** The name the guest wrote under in this conversation. */+ guestName(threadId: string): string | undefined;+ /** The bot that handed this conversation's work on. */+ handedBy(threadId: string): string | null;+ /** Sends a notification as it is. */+ send(notification: Notification): void;+ now?: () => number;+}++/** Cards that wait on the person: not an offer to switch engines, a receipt, or anything settled. */+function waitsOnPerson(card: OptionCardData | null): card is OptionCardData {+ const kind = liveCardKind(card ?? undefined);+ if (!card || !kind || card.outboundRequest || card.quotaSwitch || card.teamMemoryRequest || card.autoApplied) return false;+ return kind === "review" || card.requestType === "permission" || Boolean(card.tool) || isPersistentQuestionCard(card);+}++export function createPlaceInbox(deps: PlaceInboxDeps) {+ const { store } = deps;+ const now = deps.now ?? Date.now;+ const file = join(deps.dataDir, PLACE_INBOX_FILE);+ let lines: Line[] = [];+ let seenAsks = new Set<string>();+ try {+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));+ if (parsed.success) { lines = parsed.data.lines; seenAsks = new Set(parsed.data.seenAsks); }+ else console.warn(`place inbox: ${file} is not an inbox file; starting fresh`);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`place inbox: ${file} is unreadable; starting fresh`);+ }+ const save = () => {+ lines = lines.filter((line) => now() - line.at < KEEP_MS).slice(-MAX_LINES);+ try {+ writeFileAtomic(file, `${JSON.stringify({ version: 1, lines, seenAsks: [...seenAsks].slice(-MAX_SEEN_ASKS) })}\n`, { mode: 0o600 });+ } catch (error) {+ console.warn(`place inbox: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);+ }+ };++ const workingFor = (threadId: string): { botId: string; name: string } | undefined => {+ const botId = deps.handedBy(threadId);+ const bot = botId ? store.bot(botId) : undefined;+ return bot ? { botId: bot.id, name: bot.name } : undefined;+ };++ const titleOf = (botId: string, threadId: string): string => store.groupByThread(threadId)?.name ?? store.taskByThread(botId, threadId)?.title ?? store.bot(botId)?.name ?? "";++ /** The person wrote in the conversation after a bot's message reached them: that is their answer. */+ function answeredThere(line: Line): boolean {+ if (line.kind !== "message") return false;+ const said = store.messagesFor(line.threadId);+ for (let index = said.length - 1; index >= 0 && said[index]!.at >= line.at; index--) {+ const one = said[index]!;+ if (one.role === "user" && !one.peerAsk && !one.relayed && one.via !== "api") return true;+ }+ return false;+ }++ const lineTab = (line: Line): InboxRow["tab"] => (line.done || answeredThere(line) ? "done" : "info");+ const lineFor = (auth: RequestAuth, line: Line): boolean => {+ const viewer = deps.viewer(auth);+ if (viewer.kind === "nobody" || !deps.sees(auth, line.threadId)) return false;+ return viewer.kind === "guest" ? line.guest === viewer.key : line.guest === undefined;+ };++ function askRows(auth: RequestAuth): InboxRow[] {+ if (deps.viewer(auth).kind === "nobody") return [];+ const rows = new Map<string, InboxRow>();+ for (const row of deps.openCards()) {+ let card: OptionCardData | null = null;+ try { card = row.card ? JSON.parse(row.card) as OptionCardData : null; } catch { continue; }+ if (!waitsOnPerson(card) || !deps.sees(auth, row.threadId) || !deps.mayAnswer(auth, row.threadId, card.requestId!)) continue;+ const bot = (row.fromBotId ? store.bot(row.fromBotId) : undefined) ?? store.botByThread(row.threadId);+ if (!bot) continue;+ const group = store.groupByThread(row.threadId);+ const guest = deps.guestOf(row.threadId);+ const handed = workingFor(row.threadId);+ rows.set(`${row.threadId}\u0000${card.requestId}`, {+ id: row.id, kind: "ask", tab: "needs-you", from: { name: bot.name, botId: bot.id },+ ...(handed ? { workingFor: handed } : {}), ...(guest ? { askedBy: { name: deps.guestName(row.threadId) ?? "" } } : {}),+ origin: { botId: bot.id, threadId: row.threadId, title: titleOf(bot.id, row.threadId), ...(group ? { groupId: group.id } : {}), messageId: row.id },+ text: clip(card.subtitle || card.title || "", ROW_TEXT_MAX), at: row.at, unread: !seenAsks.has(row.id), card,+ });+ }+ return [...rows.values()];+ }++ const lineRow = (line: Line): InboxRow => ({+ id: line.id, kind: line.kind, tab: lineTab(line), from: { name: line.from, botId: line.botId }, ...(line.workingFor ? { workingFor: line.workingFor } : {}),+ origin: { botId: line.botId, threadId: line.threadId, title: titleOf(line.botId, line.threadId), ...(line.groupId ? { groupId: line.groupId } : {}), messageId: line.id },+ text: clip(line.text, ROW_TEXT_MAX), at: line.at, unread: !line.seen, ...(line.kind === "message" ? { replies: true as const } : {}),+ });++ function view(auth: RequestAuth): InboxView {+ const rows = [...askRows(auth), ...lines.filter((line) => lineFor(auth, line)).map(lineRow)].sort((a, b) => b.at - a.at).slice(0, VIEW_ROWS);+ return { botId: null, threadId: null, rows, anchor: null };+ }++ function addLine(line: Line): Line {+ lines.push(line);+ save();+ return line;+ }++ const sent = new Map<string, number[]>();+ const recent = (threadId: string) => (sent.get(threadId) ?? []).filter((at) => now() - at < HOUR_MS);++ /** message_person with no team: one line in the conversation that sent it, one row, and one notification. */+ function message(botId: string, threadId: string, text: string): { status: number; text: string } {+ const bot = store.bot(botId);+ if (!bot) return { status: 403, text: "This conversation isn't one you speak in." };+ const group = store.groupByThread(threadId);+ if (bot.threadId !== threadId && !store.taskByThread(botId, threadId) && !group?.memberIds.includes(botId)) return { status: 403, text: "This conversation isn't one you speak in." };+ if (recent(threadId).length >= PLACE_MESSAGES_HOURLY) return { status: 429, text: `You have sent ${PLACE_MESSAGES_HOURLY} messages from this conversation in the last hour, the most allowed. Don't retry: put it in your reply.` };+ sent.set(threadId, [...recent(threadId), now()]);+ const handed = workingFor(threadId);+ const guest = deps.guestOf(threadId);+ const wire: InboxItem = { kind: "message", from: { name: bot.name, botId: bot.id }, replies: true };+ const posted = store.appendMessage(threadId, { role: "bot", kind: "text", text, inbox: wire, ...(group ? { from: { botId: bot.id, name: bot.name, color: bot.color } } : {}) });+ addLine({ id: posted.id, botId: bot.id, threadId, ...(group ? { groupId: group.id } : {}), kind: "message", from: bot.name.slice(0, 200), ...(handed ? { workingFor: handed } : {}),+ ...(guest ? { guest } : {}), text: clip(text, NOTICE_TEXT_MAX), at: now() });+ if (group) store.patchGroup(group.id, { unread: true });+ else store.patchTask(bot.id, threadId, { unread: true });+ if (!guest && bot.notifications !== false) {+ deps.send({ kind: "mention", botId: bot.id, botName: bot.name, threadId, title: handed ? `${bot.name}, working for ${handed.name}` : `Message from ${bot.name}`, body: oneLine(text, 200),+ ...(group ? { groupId: group.id } : {}), ...(bot.avatarUrl ? { avatarUrl: bot.avatarUrl } : {}) });+ }+ return { status: 200, text: "It is in their Inbox and they were notified. Their answer comes back here, and you carry on from it." };+ }++ /** A routine's report or a failure of work nobody is watching gets a line; the notification about it goes out as it is. */+ function route(notification: Notification, how: { routine?: boolean } = {}): Notification {+ const { kind, botId, threadId } = notification;+ const result = kind === "done" && how.routine === true;+ const notice = ASK_NOTIFICATIONS.has(kind) && kind !== "approval" && kind !== "question" && (how.routine === true || deps.handedBy(threadId) !== null);+ const bot = result || notice ? store.bot(botId) : undefined;+ if (bot) {+ const handed = workingFor(threadId);+ const guest = deps.guestOf(threadId);+ addLine({ id: crypto.randomUUID(), botId: bot.id, threadId, ...(notification.groupId ? { groupId: notification.groupId } : {}), kind: result ? "result" : "notice", from: bot.name.slice(0, 200),+ ...(handed ? { workingFor: handed } : {}), ...(guest ? { guest } : {}), text: clip(notification.body || notification.title, NOTICE_TEXT_MAX), at: now() });+ }+ return notification;+ }++ const unsubscribe = store.onChange((change: StoreChange) => {+ if (change.type !== "thread.deleted") return;+ const before = lines.length;+ lines = lines.filter((line) => line.threadId !== change.threadId);+ if (lines.length !== before) save();+ });++ return {+ view,+ message,+ route,+ /** What waits on this viewer: every open ask, and news they have not read. */+ count(auth: RequestAuth): number {+ return view(auth).rows.filter((row) => row.tab === "needs-you" || (row.tab === "info" && row.unread)).length;+ },+ markRead(auth: RequestAuth, lineId: string): boolean {+ const line = lines.find((one) => one.id === lineId && lineFor(auth, one));+ if (line) {+ if (!line.seen) { line.seen = true; save(); }+ return true;+ }+ if (!askRows(auth).some((row) => row.id === lineId)) return false;+ if (!seenAsks.has(lineId)) { seenAsks.add(lineId); save(); }+ return true;+ },+ markDone(auth: RequestAuth, lineId: string): "done" | "unknown" | "an ask" {+ const line = lines.find((one) => one.id === lineId && lineFor(auth, one));+ if (line) {+ if (!line.done) { line.done = true; line.seen = true; save(); }+ return "done";+ }+ return askRows(auth).some((row) => row.id === lineId) ? "an ask" : "unknown";+ },+ /** The person opened this conversation: what waited there for them is read. */+ seen(auth: RequestAuth, threadId: string): void {+ let changed = false;+ for (const line of lines) if (line.threadId === threadId && !line.seen && lineFor(auth, line)) { line.seen = true; changed = true; }+ if (changed) save();+ },+ stop: unsubscribe,+ };+}++export type PlaceInbox = ReturnType<typeof createPlaceInbox>;++/** The name a guest wrote under last in a conversation. */+export const guestNameIn = (lines: readonly Pick<Message, "role" | "peerAsk" | "sender">[]): string | undefined =>+ lines.findLast((line) => line.role === "user" && !line.peerAsk && line.sender?.name)?.sender?.name;diff --git a/server/host/team-messages.ts b/server/host/team-messages.tsindex b5f65e1b83..b394dde5db 100644--- a/server/host/team-messages.ts+++ b/server/host/team-messages.ts@@ -1,7 +1,8 @@// A Team Cloud's people as people a bot can name. Whatever is addressed to a teammate reaches their inbox// (person-inbox.ts): a tag of @Bob anywhere a teammate writes it, or in a bot's reply where Bob can see it, and// message_person ("tell Bob that…"), which passes one message, whose answer comes back to the conversation that asked.-// Only the message travels: a turn still reads only its own audience (audience.ts). Off a team nothing here exists.+// Only the message travels: a turn still reads only its own audience (audience.ts). Off a team there is one person, and+// place-inbox.ts is their inbox.import type { ServerResponse } from "node:http";import { z } from "zod";@@ -22,6 +23,7 @@ import type { BotRecord, GroupRecord, Message, Store, StoreChange } from "../stoimport type { TeamPeople } from "../team-people.ts";import { currentTimeZone } from "../time-zone.ts";import { loadMemory } from "../workspace.ts";+import type { PlaceInbox } from "./place-inbox.ts";import { createPersonInbox, type Delivery, type Item, type Passed, type PersonInbox, type PersonInboxDeps } from "./person-inbox.ts";import { createRepresentative, type RepresentativeDeps } from "./representative.ts";import { oneLine } from "./text-clip.ts";@@ -38,6 +40,7 @@ const PROMPT_PEOPLE = 30;const PROMPT_WAITING = 12;const bodySchema = z.object({ to: z.string().trim().min(1).max(254), message: z.string().trim().min(1).max(MESSAGE_PERSON_MAX) }).strict();+const placeBodySchema = z.object({ to: z.string().trim().max(254).optional(), message: z.string().trim().min(1).max(MESSAGE_PERSON_MAX) }).strict();type Person = { email: string; role: TeamRole; key: string; name: string; left: boolean };type Where = { bot: BotRecord; group?: GroupRecord };@@ -55,6 +58,8 @@ export interface TeamMessagesDeps {/** What one person may see, as their own session would. */sees(person: { email: string; role: TeamRole }): { bot(botId: string): boolean; thread(threadId: string): boolean };notify(notification: Notification): void;+ /** 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">> & {representative?: Omit<RepresentativeDeps, "timeZone"> & Partial<Pick<RepresentativeDeps, "timeZone">>;@@ -303,6 +308,12 @@ export function createTeamMessages(deps: TeamMessagesDeps) {async internal(ctx: MessagePersonContext): Promise<typeof PASS | void> {if (ctx.path !== MESSAGE_PERSON_PATH) return PASS;if (ctx.method !== "POST") return ctx.json(ctx.res, 405, { error: "method not allowed" });+ if (!team && deps.place) {+ const body = placeBodySchema.safeParse(await ctx.readBody());+ if (!body.success) return ctx.json(ctx.res, 400, { error: `message_person needs message (up to ${MESSAGE_PERSON_MAX} characters).` });+ const sent = deps.place.message(ctx.botId, ctx.threadId, body.data.message);+ return ctx.json(ctx.res, sent.status, sent.status === 200 ? { text: sent.text } : { error: sent.text });+ }if (!team || !deps.people) return ctx.json(ctx.res, 404, { error: "Passing a message to a person works only on a team's Cloud." });const body = bodySchema.safeParse(await ctx.readBody());if (!body.success) return ctx.json(ctx.res, 400, { error: `message_person needs to (a teammate's name or email) and message (up to ${MESSAGE_PERSON_MAX} characters).` });@@ -341,18 +352,28 @@ export function createTeamMessages(deps: TeamMessagesDeps) {if (passed.status >= 400) return Promise.reject(Object.assign(new Error(passed.error ?? "That answer can't be passed back."), { status: passed.status }));return Promise.resolve(repeated ? { queued: false, repeated: true } : { queued: false });},- /** The session's person's inbox as its panel lists it; null off a team or for someone without one. */+ /** The viewer's inbox as its panel lists it; null for someone on a team without one. */view(auth: RequestAuth): InboxView | null {+ if (!team && deps.place) return deps.place.view(auth);const me = sessionPerson(auth);return team && me ? inbox.view(me.key) : null;},- /** The session's person is done with a line of news in their inbox. */+ /** How many of the viewer's lines wait on them. */+ count(auth: RequestAuth): number | null {+ if (!team && deps.place) return deps.place.count(auth);+ const me = sessionPerson(auth);+ const view = team && me ? inbox.view(me.key) : null;+ return view ? view.rows.filter((row) => row.tab === "needs-you" || (row.tab === "info" && row.unread)).length : null;+ },+ /** The viewer is done with a line of news in their inbox. */markDone(auth: RequestAuth, id: string): ReturnType<PersonInbox["markDone"]> {+ if (!team && deps.place) return deps.place.markDone(auth, id);const me = sessionPerson(auth);return team && me ? inbox.markDone(me.key, id) : "unknown";},- /** The session's person read a line of their inbox. */+ /** The viewer read a line of their inbox. */markRead(auth: RequestAuth, id: string): boolean {+ if (!team && deps.place) return deps.place.markRead(auth, id);const me = sessionPerson(auth);return Boolean(team && me && inbox.markRead(me.key, id));},@@ -367,6 +388,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {},/** The person opened this conversation: what waited there for them is seen. */seen(auth: RequestAuth, threadId: string): void {+ if (!team) deps.place?.seen(auth, threadId);const me = sessionPerson(auth);if (me) inbox.seen(me.key, threadId);},@@ -381,10 +403,13 @@ export function createTeamMessages(deps: TeamMessagesDeps) {return waiting ? { returned: false, open: { botId: waiting.botId, threadId: waiting.threadId } } : { returned: false };},/** A notification about to go out: an ask, a failure or a routine's report routed to a person reaches their inbox. */- route: inbox.route,+ route(notification: Notification, how: { routine?: boolean } = {}): Notification | null {+ return !team && deps.place ? deps.place.route(notification, how) : inbox.route(notification, how);+ },stop(): void {unsubscribe();inbox.stop();+ deps.place?.stop();},};}diff --git a/server/index.ts b/server/index.tsindex ef2df31825..b018a32863 100644--- a/server/index.ts+++ b/server/index.ts@@ -234,7 +234,7 @@ import { createOneOnOneGoals } from "./host/one-on-one-goals.ts";import { BUILT_IN_DRIVERS } from "./drivers/builtIn.ts";import { openCodeProviderKeysAllowed, setOpenCodeProviderKeyPolicy } from "./drivers/acp/opencode-go.ts";-import { readMessageText, recallMessages, recentMessages, closeMessageSearch, closeMessageDb, chatFollowups, cancelledChatFollowup, settleChatFollowups, threadsReferencing, logNotification, lastRowAt } from "./message-db.ts";+import { openCardRows, readMessageText, recallMessages, recentMessages, closeMessageSearch, closeMessageDb, chatFollowups, cancelledChatFollowup, settleChatFollowups, threadsReferencing, logNotification, lastRowAt } from "./message-db.ts";import { briefCrossingLabel, claimRecallCrossings, recallCrossingLabel } from "./recall-disclosure.ts";import { parseSince, parseUntil, recentWork, recentWorkPrompt, turnOutcomeLine } from "./recent-work.ts";import { chiefEscalationsEnabled, NEEDS_INPUT_GATE, peerApprovalGate, RAISED_GATE } from "./escalations.ts";@@ -631,7 +631,7 @@ import { createReactionRoutes } from "./routes/reactions.ts";import { createReactions, withReactionNotes, type Reactor } from "./reactions.ts";import { createPersonReplies } from "./person-replies.ts";import { personKey, relayedPersonKey } from "./person-key.ts";-import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";+import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createPlaceInbox, guestNameIn } 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 { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts";import { createThreadRoutes } from "./routes/threads.ts";@@ -2867,7 +2867,7 @@ const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, leconst { stopThreadForPerson, stopOnTypedCommand, restartForPerson, noteTeammatesLeftRunning } = createPersonStop({store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)),-}); const teamMessages = createTeamMessages({ team: CLOUD_TEAM, dataDir: DATA_DIR, store, 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 } } });+}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, 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) => (CLOUD_PERSONAL && !cloudOwnerSession(auth) ? (auth.kind === "session" ? { kind: "guest", key: personKey(auth.session) } : { kind: "nobody" }) : auth.kind === "loopback" && auth.trust === "service" ? { kind: "nobody" } : { kind: "owner" }), 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, 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 } } });const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });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,diff --git a/server/message-db.ts b/server/message-db.tsindex cc4f71d3ce..d70fce4663 100644--- a/server/message-db.ts+++ b/server/message-db.ts@@ -559,6 +559,16 @@ export function attentionRows(since: number): AttentionRow[] {).all(since, since, since) as unknown as AttentionRow[];}+/** Every card still open, oldest first, whenever it was asked. */+export function openCardRows(): Array<{ threadId: string; id: string; at: number; card: string | null; fromBotId: string | null }> {+ return db().prepare(+ "SELECT thread_id AS threadId, id, at, json_extract(json, '$.card') AS card, json_extract(json, '$.from.botId') AS fromBotId " ++ `FROM messages INDEXED BY messages_work_at WHERE ${WORK_KINDS} AND kind = 'options' ` ++ "AND json_extract(json, '$.card.requestId') IS NOT NULL AND json_extract(json, '$.card.answered') IS NULL AND coalesce(json_extract(json, '$.card.dismissed'), 0) = 0 " ++ "AND coalesce(json_extract(json, '$.card.expired'), 0) = 0 AND json_extract(json, '$.helperIntro') IS NULL AND json_extract(json, '$.inbox') IS NULL ORDER BY at",+ ).all() as Array<{ threadId: string; id: string; at: number; card: string | null; fromBotId: string | null }>;+}+/** Successful tool calls after a time whose row mentions `word` (case-insensitive), newest last. */export function successfulCallsMentioning(since: number, word: string): Array<{ at: number; name: string; input: string | null }> {return db().prepare(diff --git a/server/place-inbox.e2e.test.ts b/server/place-inbox.e2e.test.tsnew file mode 100644index 0000000000..d849b83eb4--- /dev/null+++ b/server/place-inbox.e2e.test.ts@@ -0,0 +1,201 @@+// The Inbox with no team, end to end on both places a person's bots live (docs/team-cloud.md "Off a team"): this computer+// and My Cloud, each its own real server with a synthetic Claude CLI. A bot's approval and question are listed with the+// right count, answered through the row's own conversation, and the turn goes on; message_person arrives once and its+// reply reaches the bot. A guest's conversation left on a shared Cloud reaches the owner labelled, not as their own. It+// proves where things land, not a model's judgement.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { markLeftBehind } from "./testing/cloud-left-behind.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const ENGINE = `const dir = process.env.FAKE_CLAUDE_FIXTURE_DIR;+process.env.FAKE_CLAUDE_ROOM_PLAN = dir + "/room-plan.json";`;+const TOKEN = `ops_fake-inbox-${randomBytes(8).toString("hex")}`;++type Card = { requestId?: string; tool?: string; answered?: string };+type Row = { id: string; kind: string; tab: string; unread: boolean; replies?: true; text: string; from: { name: string; botId?: string }; workingFor?: { name: string }; askedBy?: { name: string };+ origin?: { botId: string; threadId: string; title: string }; card?: Card };+type Note = { kind: string; botId: string; threadId: string; title: string; body: string };+type Bot = { id: string; name: string; threadId: string; busy?: boolean; activity?: string };+type Call = (method: string, path: string, body?: unknown) => Promise<{ status: number; body: any }>;++let fx: CloudSendFixture;++async function until(done: () => Promise<boolean> | boolean, what: string, timeoutMs = hostTimeout(60_000)): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error(`Timed out waiting for ${what}`);+ await new Promise((resolve) => setTimeout(resolve, 150));+ }+}++function place(call: Call, home: () => string) {+ const plan: Record<string, { script: unknown[] }> = {};+ const file = () => join(home(), "room-plan.json");+ const script = (botId: string, ...entries: unknown[]) => {+ (plan[botId] ??= { script: [] }).script.push(...entries);+ writeFileSync(file(), JSON.stringify(plan));+ };+ const turns = (botId: string): Array<{ planKey?: string; threadId?: string; prompt: unknown }> => {+ const path = `${file()}.evidence.jsonl`;+ return existsSync(path) ? readFileSync(path, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)).filter((turn) => turn.botId === botId) : [];+ };+ const inbox = async () => (await call("GET", "/api/inbox")).body as { rows: Row[]; threadId: string | null };+ const count = async () => (await call("GET", "/api/inbox/count")).body.count as number;+ const listed = async () => (await inbox()).rows.filter((row) => row.tab !== "done");+ const notes = async () => ((await call("GET", "/api/notifications")).body.notifications ?? []) as Note[];+ const messages = async (threadId: string) => ((await call("GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages ?? []) as Array<{ id: string; role: string; kind: string; text?: string; at: number; card?: Card; inbox?: unknown }>;+ const bot = async (name: string) => {+ const created = await call("POST", "/api/bots", { name, modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ expect((await call("PATCH", `/api/bots/${created.body.bot.id}`, { approvalMode: "ask", applyToAllThreads: true })).status).toBe(200);+ return created.body.bot as Bot;+ };+ const thread = async (botId: string, title: string) => {+ const opened = await call("POST", `/api/bots/${botId}/tasks`, { title });+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);+ return opened.body.task.threadId as string;+ };+ const say = async (botId: string, threadId: string, text: string, more: Record<string, unknown> = {}) => {+ const sent = await call("POST", `/api/bots/${botId}/messages`, { text, threadId, ...more });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ };+ return { script, turns, inbox, count, listed, notes, messages, bot, thread, say };+}++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, cloudEngine: ENGINE, desktopEngine: ENGINE });+ writeFileSync(join(fx.root, "desktop", "room-plan.json"), "{}");+ writeFileSync(join(fx.root, "cloud", "room-plan.json"), "{}");+}, hostTimeout(180_000));++afterAll(async () => { await fx?.close(); });++describe.each([+ ["this computer", "desktop"],+ ["My Cloud", "cloud"],+] as const)("on %s", (_name, role) => {+ const here = () => place(role === "desktop" ? fx.local : fx.onCloud, () => join(fx.root, role));++ it("starts with an inbox with nothing in it, not a missing one", async () => {+ const h = here();+ expect(await h.inbox()).toMatchObject({ rows: [], threadId: null });+ expect(await h.count()).toBe(0);+ });++ it("lists a bot's approval and question with the right count and their threads, and an answer from the inbox reaches the bot, whose turn goes on", async () => {+ const h = here();+ const eli = await h.bot(`Eli ${role}`);+ const pricing = await h.thread(eli.id, "Pricing work");+ const launch = await h.thread(eli.id, "Launch work");+ h.script(eli.id,+ { key: "P1", match: ["P1-GO"], timeoutMs: 120_000, approve: { tool: "Bash", input: { command: "echo hi" } }, reply: "P1: approved and ran", replyIfDenied: "P1: denied" },+ { key: "Q1", match: ["Q1-GO"], timeoutMs: 120_000, steps: [{ server: "ogb", tool: "ask_user", arguments: { question: "Which page?", choices: ["Home", "Pricing"] }, capture: { answer: "([\\s\\S]+)" } }], reply: "Q1: going with {{answer}}" });+ const before = (await h.notes()).length;+ await h.say(eli.id, pricing, "P1-GO");+ await h.say(eli.id, launch, "Q1-GO");++ await until(async () => (await h.listed()).length === 2, "the approval and the question in the inbox");+ expect(await h.count()).toBe(2);+ const rows = await h.listed();+ const approval = rows.find((row) => row.card?.tool)!;+ const question = rows.find((row) => !row.card?.tool)!;+ expect(approval).toMatchObject({ kind: "ask", tab: "needs-you", from: { name: eli.name }, origin: { threadId: pricing, title: "Pricing work" } });+ expect(question).toMatchObject({ kind: "ask", tab: "needs-you", from: { name: eli.name }, origin: { threadId: launch, title: "Launch work" } });+ expect((await h.inbox()).threadId, "nothing was copied into a conversation of its own").toBeNull();++ const notified = (await h.notes()).slice(0, (await h.notes()).length - before);+ expect(notified.filter((note) => note.threadId === pricing && note.kind === "approval"), "one notification per item").toHaveLength(1);+ expect(notified.filter((note) => note.threadId === launch && note.kind === "question"), "one notification per item").toHaveLength(1);++ const call = role === "desktop" ? fx.local : fx.onCloud;+ const allowed = await call("POST", `/api/threads/${approval.origin!.threadId}/respond`, { requestId: approval.card!.requestId, behavior: "allow" });+ expect(allowed.status, JSON.stringify(allowed.body)).toBe(200);+ await until(async () => (await h.messages(pricing)).some((line) => line.text === "P1: approved and ran"), "the approved turn to go on");+ expect(await h.count()).toBe(1);++ const answered = await call("POST", `/api/threads/${question.origin!.threadId}/respond`, { requestId: question.card!.requestId, behavior: "answer", message: "Pricing" });+ expect(answered.status, JSON.stringify(answered.body)).toBe(200);+ await until(async () => (await h.messages(launch)).some((line) => line.text === "Q1: going with Pricing"), "the answered turn to go on");+ expect(await h.count()).toBe(0);+ expect(await h.listed()).toEqual([]);++ const again = await call("POST", `/api/threads/${question.origin!.threadId}/respond`, { requestId: question.card!.requestId, behavior: "answer", message: "Home" });+ expect(again.status, "no answer is sent twice").toBeGreaterThanOrEqual(400);+ expect((await h.messages(launch)).some((line) => line.text?.includes("going with Home"))).toBe(false);+ }, hostTimeout(180_000));++ it("gets a bot's message_person to the person once, and their reply reaches the bot", async () => {+ const h = here();+ const eli = await h.bot(`Mel ${role}`);+ const work = await h.thread(eli.id, "Background work");+ h.script(eli.id,+ { key: "M1", match: ["M1-GO"], steps: [{ server: "agents", tool: "message_person", arguments: { message: "The report is ready." } }], reply: "M1: told them" },+ { key: "M2", match: ["Send it to Ada"], reply: "M2: sending it" });+ await h.say(eli.id, work, "M1-GO");+ await until(async () => (await h.messages(work)).some((line) => line.text === "M1: told them"), "the bot's turn");+ const line = (await h.listed()).find((row) => row.kind === "message")!;+ expect(line).toMatchObject({ tab: "info", unread: true, replies: true, text: "The report is ready.", from: { name: eli.name }, origin: { threadId: work, title: "Background work" } });+ expect(await h.count()).toBe(1);+ expect((await h.notes()).filter((note) => note.threadId === work && note.body === "The report is ready."), "one notification, not one for the chat and one for the inbox").toHaveLength(1);+ expect((await h.messages(work)).filter((one) => one.text === "The report is ready."), "one line").toHaveLength(1);++ await h.say(eli.id, work, "Send it to Ada", { replyToId: line.id });+ await until(() => h.turns(eli.id).some((turn) => turn.planKey === "M2"), "the reply to reach the bot");+ await until(async () => (await h.messages(work)).some((one) => one.text === "M2: sending it"), "the bot to carry on");+ expect(await h.count()).toBe(0);+ expect((await h.inbox()).rows.find((row) => row.id === line.id)!.tab).toBe("done");+ }, hostTimeout(120_000));++ it("clears news once it is read, and keeps it listed until it is done", async () => {+ const h = here();+ const eli = await h.bot(`Nia ${role}`);+ h.script(eli.id, { key: "N1", match: ["N1-GO"], steps: [{ server: "agents", tool: "message_person", arguments: { message: "News for you." } }], reply: "N1: told them" });+ await h.say(eli.id, eli.threadId, "N1-GO");+ await until(async () => (await h.messages(eli.threadId)).some((line) => line.text === "N1: told them"), "the bot's turn");+ const call = role === "desktop" ? fx.local : fx.onCloud;+ const row = (await h.listed()).find((one) => one.text === "News for you.")!;+ expect(row.unread).toBe(true);+ expect((await call("POST", `/api/inbox/${row.id}/read`)).status).toBe(200);+ expect((await h.listed()).find((one) => one.id === row.id)).toMatchObject({ unread: false, tab: "info" });+ expect(await h.count()).toBe(0);+ expect((await call("POST", `/api/inbox/${row.id}/done`)).body.rows.find((one: Row) => one.id === row.id).tab).toBe("done");+ expect((await call("POST", "/api/inbox/not-a-line/read")).status).toBe(404);+ }, hostTimeout(120_000));+});++describe("on a Cloud someone else once used", () => {+ it("lets nobody connect as a guest, shows a bot's shell nothing, and labels a guest's ask to its owner while keeping a guest's news away", async () => {+ const h = place(fx.onCloud, () => join(fx.root, "cloud"));+ const refused = await fx.onCloud("POST", "/api/auth/pairing", { label: "Friend", scopes: ["client"] });+ expect(refused.status, "a personal Cloud takes the owner's own devices only").toBeGreaterThanOrEqual(400);++ const shell = await fetch(`${fx.cloudBase}/api/inbox`);+ const seen = shell.ok ? (await shell.json() as { rows: Row[] }).rows : [];+ expect(seen).toEqual([]);++ const zed = await h.bot("Zed");+ const theirs = await h.thread(zed.id, "Sam's work");+ const owners = await h.thread(zed.id, "My work");+ h.script(zed.id,+ { key: "G1", match: ["G1-GO"], timeoutMs: 120_000, steps: [{ server: "agents", tool: "message_person", arguments: { message: "For the guest" } }, { server: "ogb", tool: "ask_user", arguments: { question: "Guest's question?", choices: ["A", "B"] }, capture: { answer: "([\\s\\S]+)" } }], reply: "G1: {{answer}}" },+ { key: "G2", match: ["G2-GO"], timeoutMs: 120_000, steps: [{ server: "ogb", tool: "ask_user", arguments: { question: "Owner's question?", choices: ["A", "B"] }, capture: { answer: "([\\s\\S]+)" } }], reply: "G2: {{answer}}" });++ markLeftBehind(join(fx.root, "cloud", ".openmausbot"), { threadIds: [theirs] });+ await fx.relaunch({ cloud: {} });+ await h.say(zed.id, theirs, "G1-GO");+ await h.say(zed.id, owners, "G2-GO");+ await until(async () => (await h.listed()).filter((row) => row.from.name === "Zed" && row.kind === "ask").length === 2, "both asks");+ const rows = await h.listed();+ const guests = rows.find((row) => row.origin?.threadId === theirs && row.kind === "ask")!;+ const own = rows.find((row) => row.origin?.threadId === owners && row.kind === "ask")!;+ expect(guests.askedBy, "a guest's ask says it isn't the owner's").toBeDefined();+ expect(own.askedBy).toBeUndefined();+ expect((await h.messages(theirs)).some((line) => line.text === "For the guest"), "the bot did send it").toBe(true);+ expect(rows.some((row) => row.text === "For the guest"), "a guest's news isn't the owner's").toBe(false);+ expect((await h.notes()).some((note) => note.body === "For the guest")).toBe(false);+ }, hostTimeout(240_000));+});diff --git a/server/request-auth.ts b/server/request-auth.tsindex 02135d7e9c..424a5c57b8 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -405,8 +405,8 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["POST"], path: /^\/api\/presence\/active$/ },// what a bot asks of this person: their own questions and approvals only{ methods: ["GET"], path: /^\/api\/needs-you$/ },- // a Team Cloud person's own inbox: its lines, and one of them read or done; the handler serves the session's own alone- { methods: ["GET"], path: /^\/api\/inbox$/ },+ // a person's own inbox: its lines, how many wait, and one of them read or done; the handler serves the session's own alone+ { methods: ["GET"], path: /^\/api\/inbox(?:\/count)?$/ },{ methods: ["POST"], path: /^\/api\/inbox\/[\w-]+\/(?:read|done)$/ },// who a Team Cloud bot can report to, and handing over a bot the member owns: the handler checks who may{ methods: ["GET"], path: /^\/api\/team\/people$/ },diff --git a/server/routes/inbox.test.ts b/server/routes/inbox.test.tsindex fd6caa3701..e797982267 100644--- a/server/routes/inbox.test.ts+++ b/server/routes/inbox.test.ts@@ -28,6 +28,8 @@ function setup(options: Parameters<typeof teamInbox>[0] = {}) {it("answers each member with their own inbox, which a client session may read and mark", async () => {const { f, call } = setup();f.team.pass("scout", "cleo-private", "Ben", "The launch moved to Friday.");+ expect(await call("GET", "/api/inbox/count")).toMatchObject({ status: 200, body: { count: 1 } });+ expect(requiredScope("GET", "/api/inbox/count")).toBe("client");const mine = await call("GET", "/api/inbox");expect(mine).toMatchObject({ status: 200, body: { botId: "bens-chief", rows: [{ text: "The launch moved to Friday.", tab: "info", unread: true }] } });const line = mine.body.rows[0].id as string;diff --git a/server/routes/inbox.ts b/server/routes/inbox.tsindex 6955d6a3db..f69e089df7 100644--- a/server/routes/inbox.ts+++ b/server/routes/inbox.ts@@ -3,13 +3,15 @@ import type { RequestAuth } from "../request-auth.ts";import { PASS, type RouteHandler } from "./table.ts";export interface InboxRouteDeps {- /** The session's person's inbox; null off a team or for someone without one. */+ /** This viewer's inbox; null for someone on a team without one. */view(auth: RequestAuth): InboxView | null;+ /** How many of its lines wait on them; null for someone on a team without one. */+ count(auth: RequestAuth): number | null;markDone(auth: RequestAuth, id: string): "done" | "unknown" | "an ask";markRead(auth: RequestAuth, id: string): boolean;}-/** GET /api/inbox: the session's person's inbox as its panel lists it. POST /api/inbox/<line>/read and /done: one of its+/** GET /api/inbox: this viewer's inbox as its panel lists it. GET /api/inbox/count: how many of its lines wait on them. POST /api/inbox/<line>/read and /done: one of its* lines read, or news they need nothing more from; each answers with the inbox as it lists them now. */export function createInboxRoutes(deps: InboxRouteDeps): RouteHandler {return async ({ res, path, method, auth, json }) => {@@ -18,6 +20,11 @@ export function createInboxRoutes(deps: InboxRouteDeps): RouteHandler {const view = deps.view(auth);return view ? json(res, 200, view) : json(res, 404, { error: "There is no inbox here." });}+ if (path === "/api/inbox/count") {+ if (method !== "GET") return json(res, 405, { error: "method not allowed" });+ const count = deps.count(auth);+ return count === null ? json(res, 404, { error: "There is no inbox here." }) : json(res, 200, { count });+ }const m = /^\/api\/inbox\/([\w-]+)\/(read|done)$/.exec(path);if (!m) return PASS;if (method !== "POST") return json(res, 405, { error: "method not allowed" });diff --git a/shared/inbox.ts b/shared/inbox.tsindex ff55055af8..99987f3e1d 100644--- a/shared/inbox.ts+++ b/shared/inbox.ts@@ -46,6 +46,10 @@ export interface InboxRow {tab: InboxTab;from: InboxItem["from"];via?: InboxItem["via"];+ /** The bot that handed this work to the bot it is from. */+ workingFor?: { botId: string; name: string };+ /** On someone's Cloud: a guest's conversation asks this, not its owner's; `name` is empty when it isn't known. */+ askedBy?: { name: string };origin?: InboxItem["origin"];text: string;at: number;@@ -57,9 +61,10 @@ export interface InboxRow {}/** A person's inbox: where its lines live (none yet before the first arrives), and the line the inbox's card in that- * conversation sits under (the newest that needed them, else the newest). */+ * conversation sits under (the newest that needed them, else the newest). Off a team `botId` and `threadId` are null: its+ * lines stay in the conversations they came from, each answered through its `origin`. */export interface InboxView {- botId: string;+ botId: string | null;threadId: string | null;rows: InboxRow[];anchor: string | null;diff --git a/src/App.tsx b/src/App.tsxindex 8d2027286b..72861a6060 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -34,7 +34,7 @@ import { CloudSendStrip } from "@/components/CloudSendStrip";import { HomeLine } from "@/components/HomeLine";import { useTeamChats } from "@/state/team-chats";import { needsYouVersion, useTeamPeopleLoader } from "@/state/team-people";-import { inboxVersion, useInboxLoader, useInboxPanel } from "@/state/inbox";+import { inboxVersion, useInboxLoader, useInboxPanel, useInboxReady } from "@/state/inbox";import { InboxPanel } from "@/components/inbox/InboxPanel";import { PlacesRail } from "@/components/PlacesRail";import { CloudHowTo } from "@/components/CloudHowTo";@@ -73,10 +73,11 @@ import { WebPanelPage } from "@/components/WebPanelPage";function Shell({ viewer }: { viewer: WelcomeViewer | null }) {const { state, dispatch } = useStore();useTeamChats(state.config);- useTeamPeopleLoader(state.config, needsYouVersion(state.bots, state.groups, state.notifications));- const inbox = inboxVersion(state.bots);- useInboxLoader(inbox);- const inboxShown = useInboxPanel().open && inbox !== null;+ const needsYou = needsYouVersion(state.bots, state.groups, state.notifications);+ useTeamPeopleLoader(state.config, needsYou);+ useInboxLoader(`${inboxVersion(state.bots) ?? ""}|${needsYou}`);+ const inboxReady = useInboxReady();+ const inboxShown = useInboxPanel().open && inboxReady;// A Switch AI pick lands once its stopped turn's chat is idle, wherever the person is by then.useAiSwitchKeeper({ bots: state.bots, dispatch });const showThreads = useShowThreads();diff --git a/src/components/Sidebar.header-menus.test.ts b/src/components/Sidebar.header-menus.test.tsindex fe039a89a6..fe38505070 100644--- a/src/components/Sidebar.header-menus.test.ts+++ b/src/components/Sidebar.header-menus.test.ts@@ -32,7 +32,6 @@ vi.mock("./DesktopCapabilities", async () => {return { useDesktopCapabilities: () => ({ capabilities: initialDesktopCapabilities() }), windowFramed: () => false };});vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => true }));-// The Active Threads menu is an Advanced-mode control; Simple hides it.vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => true, setAdvancedMode: () => {} }));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();@@ -79,7 +78,6 @@ function press(target: unknown) {const menus = [{ name: "New or share", label: "New or share", item: "Create department" },- { name: "Active Threads", label: "Active Threads", item: "No active threads" },];const text = (tree: ReactElement<Props>[]) => tree.map((node) => Children.toArray(node.props.children).filter((child) => typeof child === "string").join(" ")).join(" ");diff --git a/src/components/Sidebar.header.test.ts b/src/components/Sidebar.header.test.tsindex 492e1d9d7b..d2c8aeaa8e 100644--- a/src/components/Sidebar.header.test.ts+++ b/src/components/Sidebar.header.test.ts@@ -56,18 +56,20 @@ afterEach(() => {describe("sidebar header", () => {const collapse = /aria-label="(Collapse sidebar to avatars|Expand sidebar)"|data-sidebar-edge-toggle/;- it.each(["comfortable", "icons"] as const)("keeps activity and add, and no button collapses or expands it, at %s density in Advanced mode", (density) => {+ it.each(["comfortable", "icons"] as const)("keeps the Inbox and add, and no button collapses or expands it, at %s density in Advanced mode", (density) => {fixture.density = density;const html = render();- expect(html).toContain('aria-label="Active Threads"');+ expect(html).toContain('aria-label="Inbox"');+ expect(html).not.toContain('aria-label="Active Threads"');expect(html).toContain('aria-label="New or share"');expect(html).not.toMatch(collapse);});- it.each(["comfortable", "icons"] as const)("keeps add, no activity menu and no collapse button in Simple mode at %s density: its edge is dragged instead", (density) => {+ it.each(["comfortable", "icons"] as const)("keeps the Inbox and add, no activity menu and no collapse button in Simple mode at %s density: its edge is dragged instead", (density) => {fixture.advanced = false;fixture.density = density;const html = render();+ expect(html).toContain('aria-label="Inbox"');expect(html).not.toContain('aria-label="Active Threads"');expect(html).toContain('aria-label="New or share"');expect(html).not.toMatch(collapse);@@ -113,7 +115,7 @@ describe("sidebar top row", () => {expect(spacer).toBeGreaterThan(slot);expect(switcher).toBeGreaterThan(spacer);expect(buttons).toBeGreaterThan(switcher);- expect(row.slice(buttons).match(/<button/g)).toHaveLength(2);+ expect(row.slice(buttons).match(/<button/g)).toHaveLength(1);const rowClasses = classesOf(row, "data-sidebar-top-row");expect(rowClasses).toEqual(expect.arrayContaining(["relative", "pl-4", "pr-2"]));expect(rowClasses).not.toContain("px-4");@@ -127,7 +129,6 @@ describe("sidebar top row", () => {expect(row).toContain('<span class="min-w-0 truncate @max-[96px]/sidebar-top:hidden">Servers</span>');expect(row).toContain("focus-visible:outline-2");expect(html).toContain('title="New or share"');- expect(row).toContain('title="Active Threads"');expect(html.match(/Switch server:/g)).toHaveLength(1);});@@ -145,7 +146,7 @@ describe("sidebar top row", () => {expect(lights).toBe(-1);expect(buttons).toBeGreaterThan(slot);expect(classesOf(row, "data-sidebar-top-buttons")).toEqual(expect.arrayContaining(["shrink-0", "pointer-events-auto"]));- expect(row.slice(buttons).match(/<button/g)).toHaveLength(2);+ expect(row.slice(buttons).match(/<button/g)).toHaveLength(1);expect(row).toMatch(/data-sidebar-search-toggle="true" aria-label="Search bots and messages" aria-expanded="false" title="Search bots and messages" class="[^"]*\bsize-\[26px\][^"]*\brounded-lg\b[^"]*\btext-ink-secondary\b/);expect(row, "no round box round either").not.toContain("bg-composer");expect(html).toMatch(/aria-label="New or share" class="[^"]*\bsize-\[26px\][^"]*\brounded-lg\b/);diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex a63333e14b..7ff2c6b73f 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -1,7 +1,7 @@import { OrganizationIdentity } from "./OrganizationIdentity";import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch } from "react";import { createPortal } from "react-dom";-import { Activity, Archive, Bot as BotIcon, Check, ChevronRight, ClipboardCopy, Crown, FolderPlus, Library, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, Phone, Pin, PinOff, Plus, Search, TextQuote, Trash2, Users, X } from "lucide-react";+import { Archive, Bot as BotIcon, Check, ChevronRight, ClipboardCopy, Crown, FolderPlus, Library, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, Phone, Pin, Plus, Search, TextQuote, Trash2, Users, X } from "lucide-react";import { api, useStore, formatTime, visibleMessages, currentTaskBot, botOpensTo, openBot, openThread, type Action, type AppState, type Bot, type BotProject, type Group, type InstanceInfo, type Message } from "@/state/store";import { approvalModeFor } from "../../shared/approval-mode";import { liveActivityLabel } from "@/lib/live-activity";@@ -40,7 +40,7 @@ import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { draggedFolder, FOLDER_DRAG_TYPE, moveFolder, placeFolder } from "@/lib/folder-order";import { folderUnreadThreadIds, markFolderRead } from "@/lib/folder-read";import { HelperThreadGroup, orderedThreadList, partitionHelperThreads, SidebarThreadRow, stampClock, threadRecency, threadRowActions, useRelativeNow, useRevealedThreadRow, useSnoozeExpiry, visibleSidebarThreads } from "./SidebarThreadRow";-import { loadSidebarAttentionPinned, saveSidebarAttentionPinned, setSidebarDensity, useSidebarDensity, usePinnedCircles, useUniversalPins, type SidebarDensity } from "@/lib/sidebar-preferences";+import { setSidebarDensity, useSidebarDensity, usePinnedCircles, useUniversalPins, type SidebarDensity } from "@/lib/sidebar-preferences";import {ATTENTION_SECTION_ID,BOT_CHATS_SECTION_ID,@@ -72,7 +72,7 @@ import { GlassBar, GlassScrollFrame, GlassScroller } from "./GlassScrollFrame";import { DesktopWorkspaceSwitcher, endCloudHowTo } from "./DesktopWorkspaceSwitcher"; import { PlaceTint } from "./PlaceTint"; import { ChromeRailToggle } from "./ChromeRailToggle";import { useCloudOwner } from "./CloudOwner";import { SidebarSectionHeader } from "./SidebarSectionHeader";-import { NeedsYouButton, OwnerPickerHost, pickOwnerOf } from "./TeamOwner"; import { SidebarPeople } from "./SidebarPeople";+import { NeedsYouButton, OwnerPickerHost, pickOwnerOf } from "./TeamOwner"; import { SidebarPeople } from "./SidebarPeople"; import { SidebarInboxRow } from "./SidebarInboxRow"; import { SidebarActiveThreads } from "./SidebarActiveThreads"; import { setAttentionPinned, useAttentionPinned } from "./inbox/attention-pinned"; import { useInboxSupport } from "@/state/inbox";import { showWhoReportsToWhom, TeamMenuItems } from "./SidebarTeamMenu";import { MENU_ITEM, MENU_SHEET } from "./menu-recipe";import { ELEVATED_CONTROL } from "./elevated";@@ -84,7 +84,7 @@ import { isSidebarToggle } from "@/lib/keyboard-shortcuts";import { SidebarRailSeparator, SimpleRailFooter } from "./SidebarSimpleRail";import { useShowThreads } from "@/lib/thread-preferences";import { useBotUnread } from "./unread-notice";-import { attentionHasRunningWork, attentionJumpAction, attentionTriggerLabel, attentionUnpinAction, AttentionThreadRows, crossBotAttentionThreads, crossBotPinnedThreads, runningRoutineRun, SidebarBotActivity, sidebarBotActivityTasks, sidebarBotStatus } from "./SidebarBotActivity";+import { attentionHasRunningWork, attentionJumpAction, attentionUnpinAction, crossBotAttentionThreads, crossBotPinnedThreads, runningRoutineRun, SidebarBotActivity, sidebarBotActivityTasks, sidebarBotStatus } from "./SidebarBotActivity";import { SidebarNoBots, SidebarTileGrid } from "./SidebarTiles";import { BotContextMenu } from "./SidebarBotMenu";export { BotContextMenu };@@ -966,13 +966,8 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {const [plusOpen, setPlusOpen] = useState(false);const plusMotion = useMenuMotion(plusOpen);const advanced = useAdvancedMode();- const [attentionOpen, setAttentionOpen] = useState(false);- const attentionMotion = useMenuMotion(attentionOpen);- const [attentionPinned, setAttentionPinnedState] = useState(() => loadSidebarAttentionPinned());- const setAttentionPinned = (pinned: boolean) => {- setAttentionPinnedState(pinned);- saveSidebarAttentionPinned(pinned);- };+ const attentionPinned = useAttentionPinned();+ const inboxSupport = useInboxSupport();const [newRoom, setNewRoom] = useState(false);const [newChatOpen, setNewChatOpen] = useState(false);const [newFolderBotId, setNewFolderBotId] = useState<string | null>(null);@@ -1025,9 +1020,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {return () => document.removeEventListener("keydown", closeOnEscape);}, [open, onClose, confirm, deletingRoom]);- const attentionMenuRef = useRef<HTMLDivElement>(null);const plusMenuRef = useRef<HTMLDivElement>(null);- usePopoverDismiss(attentionOpen, attentionMenuRef, () => setAttentionOpen(false));usePopoverDismiss(plusOpen, plusMenuRef, () => setPlusOpen(false));useEffect(() => {@@ -1313,54 +1306,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {><Search size={20} strokeWidth={1.5} /></button>}- {advanced && <div ref={attentionMenuRef} className={density === "icons" ? "relative" : "contents"}>- <button- type="button"- onClick={() => setAttentionOpen((o) => !o)}- aria-label={attentionTriggerLabel(attention.length)}- title={attentionTriggerLabel(attention.length)}- className={cn(- "relative flex items-center justify-center text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",- density === "icons" ? "size-[46px] shrink-0 rounded-xl" : phone ? "size-10 shrink-0 rounded-full border border-hairline bg-card text-ink" : "size-8 rounded-full",- )}- >- <Activity size={density === "icons" ? 20 : 18} strokeWidth={1.5} />- {attention.length > 0 && (- <span className="absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-accent px-0.5 text-[10px] font-semibold leading-4 text-ink">{attention.length > 9 ? "9+" : attention.length}</span>- )}- {attentionHasRunningWork(attention) && (- <span data-header-activity="" className="absolute bottom-0.5 right-0.5 size-1.5 rounded-full bg-success" aria-hidden="true" />- )}- </button>- {attentionMotion.shown && (- <>- <div className={cn(- "absolute top-full z-40 mt-1 overflow-hidden", MENU_SHEET,- density === "icons" ? "left-0" : "right-0",- density === "icons" ? "w-72" : "w-72 md:w-[min(288px,calc(var(--sidebar-width)_-_32px))]",- attentionMotion.className,- )} {...attentionMotion.exitProps}>- <div className="flex items-center gap-1 py-0.5 pl-2">- <span className="flex-1 text-[13px] font-medium text-ink">{t("attention.title")}</span>- <button- type="button"- onClick={() => setAttentionPinned(!attentionPinned)}- aria-label={t(attentionPinned ? "attention.unpin" : "attention.pin")}- title={t(attentionPinned ? "attention.unpin" : "attention.pin")}- className="flex size-6 items-center justify-center rounded-md text-ink-secondary hover:bg-menu-hover hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus"- >- {attentionPinned ? <PinOff size={14} /> : <Pin size={14} />}- </button>- </div>- {attention.length === 0 ? (- <div className="px-2 py-1.5 text-[13px] text-ink-secondary">{t("attention.empty")}</div>- ) : (- <AttentionThreadRows inset entries={attention} onJump={(entry) => { setAttentionOpen(false); dispatch(attentionJumpAction(entry)); }} />- )}- </div>- </>- )}- </div>}+ {advanced && inboxSupport === "no" && <SidebarActiveThreads entries={attention} icons={density === "icons"} phone={phone} dispatch={dispatch} />}{plusControl}</div>}</div>@@ -1380,6 +1326,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {/></div></div>}+ {!q && <SidebarInboxRow icons={density === "icons"} large={!advanced} running={attentionHasRunningWork(attention)} onOpened={phone ? onClose : undefined} />}{universalPins && pinnedBots.length > 0 && !simpleDesk && (<divdata-sidebar-universal-pins=""diff --git a/src/components/SidebarActiveThreads.tsx b/src/components/SidebarActiveThreads.tsxnew file mode 100644index 0000000000..abb9210561--- /dev/null+++ b/src/components/SidebarActiveThreads.tsx@@ -0,0 +1,44 @@+// For a server older than this page, which has no inbox for anyone off a team: the Active Threads button and tray.+import { Activity, Pin, PinOff } from "lucide-react";+import { useRef, useState, type Dispatch } from "react";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import type { Action } from "@/state/store";+import { setAttentionPinned, useAttentionPinned } from "./inbox/attention-pinned";+import { MENU_SHEET } from "./menu-recipe";+import { attentionHasRunningWork, attentionJumpAction, attentionTriggerLabel, AttentionThreadRows, type AttentionThread } from "./SidebarBotActivity";+import { useMenuMotion } from "./MenuMotion";+import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";++export function SidebarActiveThreads({ entries, icons, phone, dispatch }: { entries: AttentionThread[]; icons: boolean; phone: boolean; dispatch: Dispatch<Action> }) {+ const [open, setOpen] = useState(false);+ const motion = useMenuMotion(open);+ const pinned = useAttentionPinned();+ const menu = useRef<HTMLDivElement>(null);+ usePopoverDismiss(open, menu, () => setOpen(false));+ return (+ <div ref={menu} className={icons ? "relative" : "contents"}>+ <button type="button" onClick={() => setOpen((value) => !value)} aria-label={attentionTriggerLabel(entries.length)} title={attentionTriggerLabel(entries.length)}+ className={cn("relative flex items-center justify-center text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",+ icons ? "size-[46px] shrink-0 rounded-xl" : phone ? "size-10 shrink-0 rounded-full border border-hairline bg-card text-ink" : "size-8 rounded-full")}>+ <Activity size={icons ? 20 : 18} strokeWidth={1.5} />+ {entries.length > 0 && <span className="absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-accent px-0.5 text-[10px] font-semibold leading-4 text-ink">{entries.length > 9 ? "9+" : entries.length}</span>}+ {attentionHasRunningWork(entries) && <span data-header-activity="" className="absolute bottom-0.5 right-0.5 size-1.5 rounded-full bg-success" aria-hidden="true" />}+ </button>+ {motion.shown && (+ <div className={cn("absolute top-full z-40 mt-1 overflow-hidden", MENU_SHEET, icons ? "left-0 w-72" : "right-0 w-72 md:w-[min(288px,calc(var(--sidebar-width)_-_32px))]", motion.className)} {...motion.exitProps}>+ <div className="flex items-center gap-1 py-0.5 pl-2">+ <span className="flex-1 text-[13px] font-medium text-ink">{t("attention.title")}</span>+ <button type="button" onClick={() => setAttentionPinned(!pinned)} aria-label={t(pinned ? "attention.unpin" : "attention.pin")} title={t(pinned ? "attention.unpin" : "attention.pin")}+ className="flex size-6 items-center justify-center rounded-md text-ink-secondary hover:bg-menu-hover hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">+ {pinned ? <PinOff size={14} /> : <Pin size={14} />}+ </button>+ </div>+ {entries.length === 0+ ? <div className="px-2 py-1.5 text-[13px] text-ink-secondary">{t("attention.empty")}</div>+ : <AttentionThreadRows inset entries={entries} onJump={(entry) => { setOpen(false); dispatch(attentionJumpAction(entry)); }} />}+ </div>+ )}+ </div>+ );+}diff --git a/src/components/SidebarInboxRow.tsx b/src/components/SidebarInboxRow.tsxnew file mode 100644index 0000000000..4204a3cf16--- /dev/null+++ b/src/components/SidebarInboxRow.tsx@@ -0,0 +1,53 @@+// The one Inbox row at the top of the sidebar, on every plan and with no account: shaped like a bot's row, with what waits+// on the person as its count and a dot while any bot is at work. It stays when nothing waits, with no count.+import { Inbox } from "lucide-react";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { closeInbox, openInbox, useInboxPanel, useInboxSupport, useInboxView } from "@/state/inbox";+import { useTeamPeople } from "@/state/team-people";+import { inboxFixes, waitingCount } from "./inbox/inbox-view";++export function SidebarInboxRow({ icons, large, running, onOpened }: {+ icons: boolean;+ /** Simple's row, sized as its bots' rows are. */+ large: boolean;+ running: boolean;+ onOpened?: () => void;+}) {+ const support = useInboxSupport();+ const view = useInboxView();+ const team = useTeamPeople();+ const { open } = useInboxPanel();+ if (support === "no") return null;+ const count = waitingCount(view) + inboxFixes(team?.needsYou, view).length;+ const shown = count > 9 ? "9+" : String(count);+ const label = count > 0 ? t("inbox.row.count", { count }) : t("inbox.panel.title");+ const toggle = () => {+ if (open) closeInbox();+ else { openInbox(); onOpened?.(); }+ };+ const dot = running && <span data-inbox-running="" aria-hidden="true" className={cn("absolute -bottom-0.5 -right-0.5 rounded-full border-2 border-panel bg-success", icons ? "size-3" : "size-2.5")} />;+ if (icons) {+ return (+ <button type="button" data-sidebar-inbox={count} aria-label={label} title={label} aria-pressed={open} onClick={toggle}+ className={cn("relative mx-auto mb-1 flex size-[46px] shrink-0 items-center justify-center rounded-xl text-ink-secondary hover:bg-raised hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus", open && "bg-raised text-ink")}>+ <Inbox size={20} strokeWidth={1.5} aria-hidden="true" />+ {count > 0 && <span aria-hidden="true" data-inbox-count className="absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-warning px-0.5 text-[10px] font-semibold leading-4 text-panel">{shown}</span>}+ {dot}+ </button>+ );+ }+ return (+ <div className="px-2 pb-1">+ <button type="button" data-sidebar-inbox={count} aria-label={label} title={label} aria-pressed={open} onClick={toggle}+ className={cn("flex w-full min-w-0 items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none hover:bg-raised/60 focus-visible:ring-2 focus-visible:ring-accent/60", open && "bg-raised")}>+ <span className={cn("relative grid shrink-0 place-items-center rounded-full bg-raised text-ink-secondary", large ? "size-9" : "size-8")}>+ <Inbox size={large ? 18 : 16} strokeWidth={1.75} aria-hidden="true" />+ {dot}+ </span>+ <span className={cn("min-w-0 flex-1 truncate text-ink", large ? "text-[14px] font-medium leading-5" : "text-[15px] font-semibold leading-5")}>{t("inbox.panel.title")}</span>+ {count > 0 && <span aria-hidden="true" data-inbox-count className="shrink-0 rounded-full bg-warning px-1.5 text-[11px] font-semibold tabular-nums text-panel">{shown}</span>}+ </button>+ </div>+ );+}diff --git a/src/components/TeamOwner.tsx b/src/components/TeamOwner.tsxindex 1a969cffa3..a2d1e7f26f 100644--- a/src/components/TeamOwner.tsx+++ b/src/components/TeamOwner.tsx@@ -9,6 +9,7 @@ import { api, useStore, openThread, type Bot } from "@/state/store";import { useShowThreads } from "@/lib/thread-preferences";import { askingWhom, departmentOwner, ownerChanged, ownerOf, pictureOf, refreshNeedsYou, useTeamPeople, type TeamPeople, type TeamPerson } from "@/state/team-people";import type { NeedsYouItem } from "../../shared/today";+import { useInboxSupport } from "@/state/inbox";import { useHeldMenuMotion } from "./MenuMotion";import { MENU_HEADING, MENU_SHEET } from "./menu-recipe";@@ -134,11 +135,32 @@ export function NeedsYouTitle({ item, title }: { item: NeedsYouItem; title: strireturn <span className="flex w-full min-w-0 items-center gap-1.5 text-[13px] text-ink"><PersonFace person={from} size={16} /><span className="min-w-0 truncate">{title}</span></span>;}-/** On a Team Cloud: what the bots ask of this person, newest first, each one opening its conversation. */-export function NeedsYouButton({ compact = false }: { compact?: boolean }) {- const team = useTeamPeople();+/** One thing that needs this person, opening its conversation. */+export function NeedsYouLine({ item, onOpened }: { item: NeedsYouItem; onOpened?: () => void }) {const { state, dispatch } = useStore();const showThreads = useShowThreads();+ const botName = (botId: string) => state.bots.find((bot) => bot.id === botId)?.name ?? t("needsYou.aBot");+ const botId = "botId" in item ? item.botId : item.botIds[0]!;+ const title = item.kind === "message" ? t("needsYou.message", { name: item.from })+ : item.kind === "question" ? t("needsYou.asking", { bot: botName(botId) }) : t("needsYou.fix", { bot: botName(botId) });+ const text = "text" in item ? item.text : "";+ return <button type="button" role="menuitem"+ onClick={() => {+ onOpened?.();+ if (!item.threadId) return;+ openThread(dispatch, { botId, threadId: item.threadId }, state, showThreads);+ if (item.kind === "message") readConversation(state.groups, botId, item.threadId);+ }}+ className="flex w-full flex-col items-start rounded-md px-2 py-1.5 text-left hover:bg-menu-hover">+ <NeedsYouTitle item={item} title={title} />+ {text && <span className="w-full truncate text-[12px] text-ink-secondary">{text}</span>}+ </button>;+}++/** For a server older than this page, where the person has no inbox: what the bots ask of them, newest first. */+export function NeedsYouButton({ compact = false }: { compact?: boolean }) {+ const team = useTeamPeople();+ const support = useInboxSupport();const [open, setOpen] = useState(false);useEffect(() => {if (!open) return;@@ -147,9 +169,8 @@ export function NeedsYouButton({ compact = false }: { compact?: boolean }) {return () => window.removeEventListener("mousedown", onDown);}, [open]);const items = team?.needsYou ?? [];- if (!team || items.length === 0) return null;+ if (support !== "no" || !team || items.length === 0) return null;const label = t("needsYou.count", { count: items.length });- const botName = (botId: string) => state.bots.find((bot) => bot.id === botId)?.name ?? t("needsYou.aBot");return (<div data-needs-you className={cn("relative", compact ? "px-1" : "px-2 pb-1")}><button type="button" aria-expanded={open} aria-haspopup="menu" aria-label={label} title={label} onClick={() => setOpen((value) => !value)}@@ -160,23 +181,7 @@ export function NeedsYouButton({ compact = false }: { compact?: boolean }) {</button>{open && (<div role="menu" aria-label={t("needsYou.title")} className={cn("absolute left-2 right-2 top-full z-40 mt-1 max-h-[340px] overflow-y-auto", MENU_SHEET)}>- {items.map((item) => {- const botId = "botId" in item ? item.botId : item.botIds[0]!;- const title = item.kind === "message" ? t("needsYou.message", { name: item.from })- : item.kind === "question" ? t("needsYou.asking", { bot: botName(botId) }) : t("needsYou.fix", { bot: botName(botId) });- const text = "text" in item ? item.text : "";- return <button key={`${item.kind}:${item.id}`} type="button" role="menuitem"- onClick={() => {- setOpen(false);- if (!item.threadId) return;- openThread(dispatch, { botId, threadId: item.threadId }, state, showThreads);- if (item.kind === "message") readConversation(state.groups, botId, item.threadId);- }}- className="flex w-full flex-col items-start rounded-md px-2 py-1.5 text-left hover:bg-menu-hover">- <NeedsYouTitle item={item} title={title} />- {text && <span className="w-full truncate text-[12px] text-ink-secondary">{text}</span>}- </button>;- })}+ {items.map((item) => <NeedsYouLine key={`${item.kind}:${item.id}`} item={item} onOpened={() => setOpen(false)} />)}</div>)}</div>diff --git a/src/components/inbox/InboxActive.tsx b/src/components/inbox/InboxActive.tsxnew file mode 100644index 0000000000..ebba919703--- /dev/null+++ b/src/components/inbox/InboxActive.tsx@@ -0,0 +1,42 @@+// Under the inbox's lines: what else is going on, each opening where it is. What a team's person has to fix, and the+// conversations at work, with the pin that keeps them open in the sidebar.+import { Pin, PinOff } from "lucide-react";+import type { InboxView } from "../../../shared/inbox";+import { t } from "@/lib/i18n";+import { useStore } from "@/state/store";+import { useTeamPeople } from "@/state/team-people";+import { AttentionThreadRows, attentionJumpAction, crossBotAttentionThreads } from "../SidebarBotActivity";+import { NeedsYouLine } from "../TeamOwner";+import { setAttentionPinned, useAttentionPinned } from "./attention-pinned";+import { closeInbox } from "@/state/inbox";+import { inboxFixes } from "./inbox-view";++export function InboxActive({ view }: { view: InboxView | null }) {+ const { state, dispatch } = useStore();+ const team = useTeamPeople();+ const pinned = useAttentionPinned();+ const asked = new Set((view?.rows ?? []).filter((row) => row.tab === "needs-you").map((row) => row.origin?.threadId));+ const entries = crossBotAttentionThreads(state.bots, state.pendingQueued, undefined, state.groups).filter((entry) => !asked.has(entry.task.threadId));+ const fixes = inboxFixes(team?.needsYou, view);+ return (+ <>+ {fixes.length > 0 && (+ <section data-inbox-fixes className="border-t border-hairline/40 px-1.5 py-1.5">+ {fixes.map((item) => <NeedsYouLine key={`${item.kind}:${item.id}`} item={item} onOpened={closeInbox} />)}+ </section>+ )}+ {(entries.length > 0 || pinned) && (+ <section data-inbox-active aria-label={t("attention.title")} className="border-t border-hairline/40 px-1.5 py-1.5">+ <div className="flex items-center gap-1 px-2 py-0.5">+ <span className="min-w-0 flex-1 truncate text-[12px] font-medium text-ink-secondary">{t("attention.title")}</span>+ <button type="button" data-inbox-pin onClick={() => setAttentionPinned(!pinned)} aria-label={t(pinned ? "attention.unpin" : "attention.pin")} title={t(pinned ? "attention.unpin" : "attention.pin")}+ className="flex size-6 items-center justify-center rounded-md text-ink-secondary hover:bg-raised hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">+ {pinned ? <PinOff size={14} aria-hidden="true" /> : <Pin size={14} aria-hidden="true" />}+ </button>+ </div>+ <AttentionThreadRows inset entries={entries} onJump={(entry) => dispatch(attentionJumpAction(entry))} />+ </section>+ )}+ </>+ );+}diff --git a/src/components/inbox/InboxEverywhere.dom.test.ts b/src/components/inbox/InboxEverywhere.dom.test.tsnew file mode 100644index 0000000000..f9914a3fdb--- /dev/null+++ b/src/components/inbox/InboxEverywhere.dom.test.ts@@ -0,0 +1,229 @@+// @vitest-environment happy-dom+import { act, createElement, type ReactElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const server = vi.hoisted(() => ({ calls: [] as Array<{ path: string; method: string; body?: any }>, answer: null as unknown, refusal: null as null | { status: number } }));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));+vi.mock("../../state/api", () => ({+ api: vi.fn(async (path: string, init?: RequestInit) => {+ server.calls.push({ path, method: init?.method ?? "GET", ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });+ if (server.refusal) throw Object.assign(new Error("There is no inbox here."), server.refusal);+ return server.answer;+ }),+}));++import { initialState, StoreContext, type AppState, type Bot } from "@/state/store";+import { closeInbox, currentInboxPanel, openInbox, readInboxLine, refreshInbox, setInboxView } from "@/state/inbox";+import { setTeamPeople } from "@/state/team-people";+import type { InboxRow, InboxView } from "../../../shared/inbox";+import { SidebarActiveThreads } from "../SidebarActiveThreads";+import { NeedsYouButton } from "../TeamOwner";+import { SidebarInboxRow } from "../SidebarInboxRow";+import { setAttentionPinned } from "./attention-pinned";+import { InboxPanel } from "./InboxPanel";+import { senderLabel, waitingCount } from "./inbox-view";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const AT = Date.now() - 60_000;+const approval: InboxRow = {+ id: "card-a", kind: "ask", tab: "needs-you", unread: true, at: AT, from: { name: "Eli", botId: "eli" }, workingFor: { botId: "mira", name: "Mira" },+ origin: { botId: "eli", threadId: "eli-pricing", title: "Pricing work", messageId: "card-a" }, text: "Run: rm -rf ./build",+ card: { title: "Approval needed", subtitle: "Run: rm -rf ./build", options: ["Allow", "Deny"], requestId: "req-a", tool: "Bash", requestType: "permission" },+};+const question: InboxRow = {+ id: "card-q", kind: "ask", tab: "needs-you", unread: false, at: AT - 1, from: { name: "Eli", botId: "eli" },+ origin: { botId: "eli", threadId: "eli-launch", title: "Launch work", messageId: "card-q" }, text: "Which page?",+ card: { title: "A question", subtitle: "Which page?", options: ["Home", "Pricing"], requestId: "req-q", requestType: "question" },+};+const news: InboxRow = {+ id: "line-n", kind: "message", tab: "info", unread: true, replies: true, at: AT - 2, from: { name: "Noa", botId: "noa" },+ origin: { botId: "noa", threadId: "noa-main", title: "Noa", messageId: "line-n" }, text: "The report is ready.",+};+const roomNews: InboxRow = { ...news, id: "line-r", origin: { botId: "noa", threadId: "room-thread", groupId: "room", title: "Launch room", messageId: "line-r" } };+const read: InboxRow = { ...news, id: "line-read", unread: false };+const settled: InboxRow = { ...news, id: "line-done", tab: "done", unread: false };+const placeView = (rows: InboxRow[]): InboxView => ({ botId: null, threadId: null, rows, anchor: null });++let root: Root;+const dispatch = vi.fn();+const bot = (over: Partial<Bot>): Bot => ({ id: "eli", name: "Eli", threadId: "eli-main", tasks: [], ...over } as Bot);+const mount = (child: ReactElement, bots: Bot[] = []) => act(async () => {+ root.render(createElement(StoreContext.Provider,+ { value: { state: { ...initialState, bots } as AppState, dispatch, flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn() } as never }, child));+});+const click = (selector: string) => act(async () => { document.querySelector<HTMLElement>(selector)!.click(); });+const row = (props: Partial<Parameters<typeof SidebarInboxRow>[0]> = {}) => createElement(SidebarInboxRow, { icons: false, large: false, running: false, ...props });+const inboxButton = () => document.querySelector<HTMLElement>("[data-sidebar-inbox]");++beforeEach(() => {+ root = createRoot(document.body.appendChild(document.createElement("div")));+ server.calls.length = 0;+ server.refusal = null;+ server.answer = placeView([]);+ dispatch.mockClear();+ setTeamPeople(null);+ setAttentionPinned(false);+});+afterEach(() => {+ act(() => root.unmount());+ closeInbox();+ setInboxView(null);+ setTeamPeople(null);+ document.body.innerHTML = "";+ vi.useRealTimers();+});++describe("the Inbox row", () => {+ it("counts what waits on the person, not news they read or anything settled", async () => {+ setInboxView(placeView([approval, question, news, read, settled]));+ await mount(row());+ expect(document.querySelector("[data-inbox-count]")?.textContent).toBe("3");+ expect(inboxButton()!.getAttribute("aria-label")).toBe("Inbox, 3 waiting");+ expect(waitingCount(placeView([approval, question, news, read, settled]))).toBe(3);+ });++ it("stays with no count when nothing waits, and before the list arrives", async () => {+ await mount(row());+ expect(inboxButton()!.textContent).toContain("Inbox");+ expect(document.querySelector("[data-inbox-count]")).toBeNull();+ setInboxView(placeView([read, settled]));+ await mount(row());+ expect(inboxButton()!.getAttribute("aria-label")).toBe("Inbox");+ expect(document.querySelector("[data-inbox-count]")).toBeNull();+ });++ it("opens and closes the inbox, and shows a dot while a bot is at work", async () => {+ setInboxView(placeView([]));+ await mount(row({ running: true }));+ expect(document.querySelector("[data-inbox-running]")).not.toBeNull();+ await click("[data-sidebar-inbox]");+ expect(currentInboxPanel().open).toBe(true);+ await click("[data-sidebar-inbox]");+ expect(currentInboxPanel().open).toBe(false);+ await mount(row({ running: false }));+ expect(document.querySelector("[data-inbox-running]")).toBeNull();+ });++ it("is a tile with the same count among the avatars", async () => {+ setInboxView(placeView([approval]));+ await mount(row({ icons: true }));+ expect(document.querySelector("[data-inbox-count]")?.textContent).toBe("1");+ setInboxView(placeView(Array.from({ length: 12 }, (_, index) => ({ ...approval, id: `a${index}` }))));+ await mount(row({ icons: true }));+ expect(document.querySelector("[data-inbox-count]")?.textContent).toBe("9+");+ });++ it("counts what a team's person has to fix, except what the inbox lists already", async () => {+ setInboxView(placeView([question]));+ setTeamPeople({ people: [], me: null, admin: true, needsYou: [+ { kind: "signed-out", id: "s", at: AT, instanceId: "claude", botIds: ["eli"] },+ { kind: "question", id: "same", at: AT, botId: "eli", threadId: "eli-launch", text: "Which page?" },+ { kind: "question", id: "own", at: AT, botId: "eli", threadId: "eli-main", text: "In their own chat" },+ { kind: "message", id: "m", at: AT, botId: "eli", threadId: "t", from: "Ada", text: "An inbox line" },+ ] });+ await mount(row());+ expect(document.querySelector("[data-inbox-count]")?.textContent).toBe("3");+ server.answer = placeView([question]);+ openInbox();+ await mount(createElement(InboxPanel), [bot({})]);+ expect(document.querySelector("[data-inbox-fixes]")?.textContent).toContain("Eli needs a fix");+ expect(document.querySelector("[data-inbox-fixes]")?.textContent).toContain("In their own chat");+ expect(document.querySelector("[data-inbox-fixes]")?.textContent).not.toContain("Which page?");+ });+});++describe("an older server, with no inbox off a team", () => {+ beforeEach(() => { server.refusal = { status: 404 }; });++ it("falls back to the tray and Needs you it showed before, and is not asked again", async () => {+ await refreshInbox();+ await mount(createElement("div", null, row(), createElement(SidebarActiveThreads, { entries: [], icons: false, phone: false, dispatch: vi.fn() })));+ expect(inboxButton(), "no row where there is no inbox").toBeNull();+ await click('[aria-label="Active Threads"]');+ expect(document.body.textContent).toContain("No active threads");+ setTeamPeople({ people: [], me: null, admin: true, needsYou: [{ kind: "question", id: "q", at: AT, botId: "eli", threadId: "t", text: "Which?" }] });+ await mount(createElement(NeedsYouButton));+ expect(document.querySelector("[data-needs-you]"), "Needs you stays on an older team's Cloud").not.toBeNull();+ });++ it("keeps the row when the server merely can't be reached", async () => {+ server.refusal = { status: 503 };+ await refreshInbox();+ await mount(row());+ expect(inboxButton()).not.toBeNull();+ });+});++describe("a place's inbox in the panel", () => {+ const panel = async (rows: InboxRow[], bots: Bot[] = []) => {+ server.answer = placeView(rows);+ setInboxView(placeView(rows));+ openInbox();+ await mount(createElement(InboxPanel), bots);+ };++ it("labels who a line is from, who that bot worked for, and which conversation it came from", async () => {+ await panel([approval, question, news]);+ const line = (id: string) => document.querySelector(`[data-inbox-row="${id}"]`)!;+ expect(line("card-a").querySelector("[data-inbox-from]")!.textContent).toBe("Eli, working for Mira");+ expect(line("card-a").querySelector("[data-inbox-place]")!.textContent).toContain("in Pricing work");+ expect(line("card-q").querySelector("[data-inbox-from]")!.textContent).toBe("Eli");+ expect(line("card-q").querySelector("[data-inbox-place]")!.textContent).toContain("in Launch work");+ expect(senderLabel({ from: { name: "Eli" }, askedBy: { name: "Sam" } })).toBe("Eli, asked by Sam");+ expect(senderLabel({ from: { name: "Eli" }, askedBy: { name: "" } })).toBe("Eli, asked by someone else");+ });++ it("marks what waits on the person with a dot, on asks only", async () => {+ await panel([approval, news]);+ expect([...document.querySelectorAll("[data-inbox-waits]")].map((dot) => dot.closest<HTMLElement>("[data-inbox-row]")!.dataset.inboxRow)).toEqual(["card-a"]);+ });++ it("answers an ask from its row where it was asked, since there is no copy", async () => {+ await panel([approval, question]);+ await click('[data-inbox-row="card-a"] [data-inbox-action="allow"]');+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "eli-pricing", requestId: "req-a", behavior: "allow" }));+ await click('[data-inbox-row="card-q"] [data-inbox-action="close"]');+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "eli-launch", requestId: "req-q", behavior: "answer" }));+ });++ it("answers a question from the line read in full, where it was asked", async () => {+ await panel([question]);+ await act(async () => { readInboxLine("card-q"); });+ await mount(createElement(InboxPanel));+ const choice = [...document.querySelectorAll<HTMLElement>("[data-inbox-reading] button")].find((button) => button.textContent === "Pricing")!;+ await act(async () => { choice.click(); });+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "eli-launch", requestId: "req-q", behavior: "answer", message: "Pricing" }));+ });++ it("sends a reply to the conversation the message came from, in a bot's chat or a room", async () => {+ await panel([news, roomNews]);+ for (const [id, path, threadId] of [["line-n", "/api/bots/noa/messages", "noa-main"], ["line-r", "/api/groups/room/messages", "room-thread"]] as const) {+ await act(async () => { readInboxLine(id); });+ await mount(createElement(InboxPanel));+ const box = document.querySelector<HTMLTextAreaElement>("[data-inbox-reading] textarea")!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(box, "Thanks");+ box.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await act(async () => { box.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true })); });+ const send = [...document.querySelectorAll<HTMLElement>("[data-inbox-reading] footer button")].find((button) => /send/i.test(button.getAttribute("aria-label") ?? button.textContent ?? ""));+ if (!server.calls.some((call) => call.path === path)) await act(async () => { send?.click(); });+ expect(server.calls.find((call) => call.path === path), path).toMatchObject({ method: "POST", body: { text: "Thanks", threadId, replyToId: id } });+ }+ });++ it("lists the conversations at work with a jump to each and the pin, leaving out what the inbox already asks", async () => {+ const working = { threadId: "eli-work", title: "Writing the page", createdAt: 1, busy: true, activity: "working" as const };+ const asking = { threadId: "eli-pricing", title: "Pricing work", createdAt: 2, activity: "waiting-on-you" as const };+ await panel([approval], [bot({ tasks: [working, asking] as Bot["tasks"] })]);+ const section = document.querySelector<HTMLElement>("[data-inbox-active]")!;+ expect(section.textContent).toContain("Writing the page");+ expect(section.textContent).not.toContain("Pricing work");+ await act(async () => { [...section.querySelectorAll<HTMLElement>("button")].find((one) => one.textContent?.includes("Writing the page"))!.click(); });+ expect(dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "eli", threadId: "eli-work" });+ await click("[data-inbox-pin]");+ expect(document.querySelector("[data-inbox-pin]")!.getAttribute("aria-label")).toBe("Unpin");+ });+});diff --git a/src/components/inbox/InboxPanel.dom.test.ts b/src/components/inbox/InboxPanel.dom.test.tsindex 71eeaca8ff..12cc35c94d 100644--- a/src/components/inbox/InboxPanel.dom.test.ts+++ b/src/components/inbox/InboxPanel.dom.test.ts@@ -153,28 +153,25 @@ describe("answer buttons in the asking bot's colour", () => {});describe("keeping the list live", () => {- function Loader({ version }: { version: string | null }) {+ function Loader({ version }: { version: string }) {useInboxLoader(version);return null;}- it("reads the list again whenever the person's inbox task says it changed, and never off a team", async () => {+ it("reads the list again whenever what it depends on changes", async () => {const task = (inboxChangedAt?: number, openAsks?: number) => [{ id: "bens-chief", tasks: [{ threadId: "inbox", inbox: true as const, ...(inboxChangedAt ? { inboxChangedAt } : {}), ...(openAsks ? { openAsks } : {}) }] }];expect(inboxVersion([{ id: "solo", tasks: [{ threadId: "t1" }] }]), "nothing is anyone's inbox off a team").toBeNull();const first = inboxVersion(task(5, 2));expect(inboxVersion(task(6, 2))).not.toBe(first);expect(inboxVersion(task(5, 1))).not.toBe(first);- await mount(createElement(Loader, { version: first }));+ await mount(createElement(Loader, { version: first! }));await settle();const reads = () => server.calls.filter((call) => call.path === "/api/inbox").length;expect(reads()).toBe(1);- await mount(createElement(Loader, { version: first }));+ await mount(createElement(Loader, { version: first! }));await settle();expect(reads(), "the same version reads nothing").toBe(1);- await mount(createElement(Loader, { version: inboxVersion(task(6, 1)) }));- await settle();- expect(reads()).toBe(2);- await mount(createElement(Loader, { version: null }));+ await mount(createElement(Loader, { version: inboxVersion(task(6, 1))! }));await settle();expect(reads()).toBe(2);});diff --git a/src/components/inbox/InboxPanel.tsx b/src/components/inbox/InboxPanel.tsxindex e9b9e83ddb..09e33756c5 100644--- a/src/components/inbox/InboxPanel.tsx+++ b/src/components/inbox/InboxPanel.tsx@@ -1,4 +1,4 @@-// On a Team Cloud: the person's whole inbox in the right panel as one list, newest first, a dot on what waits on them,+// The person's whole inbox in the right panel as one list, newest first, a dot on what waits on them,// each line a dense row that reads in full in the panel. At phone width it is a sheet over the chat.import { useEffect, useState, type KeyboardEvent } from "react";import { createPortal } from "react-dom";@@ -7,6 +7,7 @@ import type { InboxRow } from "../../../shared/inbox";import { t } from "@/lib/i18n";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";import { closeInbox, readInboxLine, readInboxRow, useInboxPanel, useInboxView } from "@/state/inbox";+import { InboxActive } from "./InboxActive";import { InboxReading } from "./InboxReading";import { InboxRowItem } from "./InboxRow";import { listedRows } from "./inbox-view";@@ -41,10 +42,13 @@ export function InboxPanel() {</button></div>{reading && view ? <InboxReading view={view} row={reading} now={now} /> : (- <div role="list" data-inbox-list aria-label={t("inbox.panel.title")} className="min-h-0 flex-1 overflow-y-auto">- {rows.length === 0- ? <p className="px-4 py-8 text-center text-[13px] text-ink-secondary">{t("inbox.empty")}</p>- : rows.map((row) => <InboxRowItem key={row.id} row={row} now={now} onOpen={open} onAction={run} />)}+ <div className="min-h-0 flex-1 overflow-y-auto">+ <div role="list" data-inbox-list aria-label={t("inbox.panel.title")}>+ {rows.length === 0+ ? <p className="px-4 py-8 text-center text-[13px] text-ink-secondary">{t("inbox.empty")}</p>+ : rows.map((row) => <InboxRowItem key={row.id} row={row} now={now} onOpen={open} onAction={run} />)}+ </div>+ <InboxActive view={view} /></div>)}</>diff --git a/src/components/inbox/InboxReading.tsx b/src/components/inbox/InboxReading.tsxindex f98eb48556..7bc266f2bd 100644--- a/src/components/inbox/InboxReading.tsx+++ b/src/components/inbox/InboxReading.tsx@@ -13,7 +13,7 @@ import { InboxSender } from "../InboxLine";import { pendingApprovals, PendingApprovalActions, PendingApprovalPanel } from "../PendingApproval";import { QuestionCard } from "../QuestionCard";import { threadUpdatedLabel } from "../SidebarThreadRow";-import { askOf, closeResponse, subjectOf, textOf } from "./inbox-view";+import { answerThread, askOf, closeResponse, senderLabel, subjectOf, textOf } from "./inbox-view";import { accessRequestWords } from "../bot-access/access-card";import { useInboxActions } from "./use-inbox-actions";@@ -46,10 +46,11 @@ export function InboxReading({ view, row, now }: { view: InboxView; row: InboxRosetSending(false);}};- const approval = ask === "approval" && view.threadId ? pendingApprovals([asMessage(row)])[0] : undefined;+ const threadId = answerThread(view, row);+ const approval = ask === "approval" && threadId ? pendingApprovals([asMessage(row)])[0] : undefined;const canReply = !ask && row.tab === "info" && row.replies === true;return (- <article data-inbox-reading={row.id} aria-label={`${row.from.name} · ${subjectOf(row)}`} className="flex min-h-0 flex-1 flex-col">+ <article data-inbox-reading={row.id} aria-label={`${senderLabel(row)} · ${subjectOf(row)}`} className="flex min-h-0 flex-1 flex-col"><header className="flex items-start gap-2 border-b border-hairline/40 px-3 py-2.5"><button type="button" onClick={() => readInboxLine(null)} aria-label={t("inbox.action.back")} title={t("inbox.action.back")}className="flex size-7 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-raised hover:text-ink pointer-coarse:size-9">@@ -58,7 +59,7 @@ export function InboxReading({ view, row, now }: { view: InboxView; row: InboxRo<span className="mt-0.5 shrink-0" aria-hidden="true"><InboxSender from={row.from} size={28} /></span><div className="min-w-0 flex-1"><div className="flex items-baseline gap-2">- <span className="min-w-0 truncate text-[14px] font-semibold text-ink">{row.from.name}</span>+ <span className="min-w-0 truncate text-[14px] font-semibold text-ink">{senderLabel(row)}</span><span className="ml-auto shrink-0 text-[11px] tabular-nums text-ink-tertiary">{threadUpdatedLabel(row.at, now)}</span></div><div className="truncate text-[13px] text-ink">{subjectOf(row)}</div>@@ -83,11 +84,11 @@ export function InboxReading({ view, row, now }: { view: InboxView; row: InboxRo<p className="flex items-center gap-1.5 text-[13px] text-ink-secondary"><Check size={14} aria-hidden="true" />{settledLabel(row)}</p></>)}- {ask === "question" && view.threadId && <QuestionCard threadId={view.threadId} asker={asker} message={asMessage(row)} />}- {approval && view.threadId && (+ {ask === "question" && threadId && <QuestionCard threadId={threadId} asker={asker} message={asMessage(row)} />}+ {approval && threadId && (<div className={cn("rounded-[24px]", ELEVATED_CARD)}><PendingApprovalPanel pending={approval} count={1} index={0} botName={asker?.name ?? row.from.name} asker={asker}- actions={<PendingApprovalActions part="primary" tag="inbox" pending={approval} threadId={view.threadId} bot={asker} onCancelTurn={() => {}} />} />+ actions={<PendingApprovalActions part="primary" tag="inbox" pending={approval} threadId={threadId} bot={asker} onCancelTurn={() => {}} />} /></div>)}{ask === "review" && <p className="text-[13px] text-ink-secondary">{t("inbox.reviewInChat")}</p>}diff --git a/src/components/inbox/InboxRow.tsx b/src/components/inbox/InboxRow.tsxindex d3edcdb9e1..1dff0c405c 100644--- a/src/components/inbox/InboxRow.tsx+++ b/src/components/inbox/InboxRow.tsx@@ -1,5 +1,5 @@-// One line of the person's inbox as a dense row: a dot while it waits on them, the sender's face and name, the subject,-// a muted snippet and the time. An unread row is bold on a stronger ground. On hover or keyboard focus the time gives+// One line of the person's inbox as a dense row: a dot while it waits on them, the sender's face and who it is from, the+// subject and where it came from, a muted snippet and the time. An unread row is bold on a stronger ground. On hover or keyboard focus the time gives// way to the row's quick actions.import { Check, CornerUpLeft, ExternalLink, X, type LucideIcon } from "lucide-react";import type { InboxRow } from "../../../shared/inbox";@@ -8,7 +8,7 @@ import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";import { InboxSender } from "../InboxLine";import { threadUpdatedLabel } from "../SidebarThreadRow";-import { quickActions, subjectOf, textOf, type QuickAction } from "./inbox-view";+import { placeOf, quickActions, senderLabel, subjectOf, textOf, type QuickAction } from "./inbox-view";const ACTION_LOOK: Record<QuickAction, { Icon: LucideIcon; label: LocaleKey }> = {allow: { Icon: Check, label: "approval.action.allowOnce" },@@ -31,21 +31,39 @@ export function InboxRowItem({ row, now, onOpen, onAction, inCard = false }: {}) {const subject = subjectOf(row);const actions = quickActions(row);+ const sender = senderLabel(row);+ const place = placeOf(row);return (<div data-inbox-row={row.id} data-tab={row.tab} data-unread={row.unread ? "" : undefined}className={cn("group relative flex min-w-0 items-center gap-2 border-b border-hairline/20 pr-1.5 focus-within:bg-raised/70 hover:bg-raised/70",row.unread ? "bg-raised/45" : "bg-transparent", inCard && "border-b-0")}>- <button type="button" onClick={() => onOpen(row)} title={`${row.from.name} · ${subject}`}- className={cn("flex min-w-0 flex-1 items-center gap-2 py-1.5 pl-2.5 text-left text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60",+ <button type="button" onClick={() => onOpen(row)} title={[sender, subject, place].filter(Boolean).join(" · ")}+ className={cn("flex min-w-0 flex-1 gap-2 pl-2.5 text-left text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60", inCard ? "items-center py-1.5" : "items-start py-2",row.unread ? "font-semibold text-ink" : "font-normal text-ink-secondary")}>- {row.tab === "needs-you" && <span data-inbox-waits className="size-1.5 shrink-0 rounded-full bg-warning" role="img" aria-label={t("inbox.waitsOnYou")} />}+ {row.tab === "needs-you" && <span data-inbox-waits className={cn("size-1.5 shrink-0 rounded-full bg-warning", !inCard && "mt-[7px]")} role="img" aria-label={t("inbox.waitsOnYou")} />}<span className="shrink-0" aria-hidden="true"><InboxSender from={row.from} size={20} /></span>- <span className={cn("shrink-0 truncate", inCard ? "w-[7.5rem]" : "w-[5.5rem] sm:w-[6.5rem]")}>{row.from.name}</span>- <span className="flex min-w-0 flex-1 items-baseline gap-1.5">- <span className="max-w-[45%] shrink-0 truncate">{subject}</span>- <span className="min-w-0 truncate font-normal text-ink-tertiary">{textOf(row)}</span>- </span>- <span className="shrink-0 text-[11px] font-normal tabular-nums text-ink-tertiary group-focus-within:invisible group-hover:invisible">{threadUpdatedLabel(row.at, now)}</span>+ {inCard ? (+ <>+ <span className="w-[7.5rem] shrink-0 truncate">{row.from.name}</span>+ <span className="flex min-w-0 flex-1 items-baseline gap-1.5">+ <span className="max-w-[45%] shrink-0 truncate">{subject}</span>+ <span className="min-w-0 truncate font-normal text-ink-tertiary">{textOf(row)}</span>+ </span>+ <span className="shrink-0 text-[11px] font-normal tabular-nums text-ink-tertiary group-focus-within:invisible group-hover:invisible">{threadUpdatedLabel(row.at, now)}</span>+ </>+ ) : (+ <span className="min-w-0 flex-1">+ <span className="flex items-baseline gap-2">+ <span data-inbox-from className="min-w-0 flex-1 truncate">{sender}</span>+ <span className="shrink-0 text-[11px] font-normal tabular-nums text-ink-tertiary group-focus-within:invisible group-hover:invisible">{threadUpdatedLabel(row.at, now)}</span>+ </span>+ <span className="block truncate text-[12px] font-normal">+ <span>{subject}</span>+ {place && <span data-inbox-place className="text-ink-tertiary"> {place}</span>}+ <span className="text-ink-tertiary"> · {textOf(row)}</span>+ </span>+ </span>+ )}</button><span className="absolute right-1.5 top-1/2 hidden -translate-y-1/2 items-center gap-0.5 rounded-md bg-raised group-focus-within:flex group-hover:flex">{actions.map((action) => {diff --git a/src/components/inbox/attention-pinned.ts b/src/components/inbox/attention-pinned.tsnew file mode 100644index 0000000000..b895fe32d0--- /dev/null+++ b/src/components/inbox/attention-pinned.ts@@ -0,0 +1,15 @@+import { useSyncExternalStore } from "react";+import { loadSidebarAttentionPinned, saveSidebarAttentionPinned } from "@/lib/sidebar-preferences";++let pinned: boolean | null = null;+const listeners = new Set<() => void>();+const current = () => (pinned ??= loadSidebarAttentionPinned());++/** Whether Active Threads stays open in the sidebar: pinned from the inbox, unpinned there or in the sidebar. */+export const useAttentionPinned = () => useSyncExternalStore((listener) => { listeners.add(listener); return () => { listeners.delete(listener); }; }, current, current);++export function setAttentionPinned(next: boolean): void {+ pinned = next;+ saveSidebarAttentionPinned(next);+ for (const listener of listeners) listener();+}diff --git a/src/components/inbox/inbox-view.ts b/src/components/inbox/inbox-view.tsindex e947bf801e..205939c7d2 100644--- a/src/components/inbox/inbox-view.ts+++ b/src/components/inbox/inbox-view.ts@@ -1,5 +1,6 @@import { formatQuestionAnswers, questionChoices } from "../../../shared/ask-question";import type { InboxRow, InboxTab, InboxView } from "../../../shared/inbox";+import type { NeedsYouItem } from "../../../shared/today";import { liveCardKind } from "../../../shared/live-approval";import { t } from "@/lib/i18n";import { dismissResponse, type CardResponse } from "@/lib/card-answer";@@ -20,6 +21,26 @@ export function tabCounts(view: InboxView | null): Record<InboxTab, number> {return counts;}+/** What the Inbox row counts: every line waiting on the person, and news they have not read. */+export const waitingCount = (view: InboxView | null): number => (view?.rows ?? []).filter((row) => row.tab === "needs-you" || (row.tab === "info" && row.unread)).length;++/** What a team's person is told needs them beyond the inbox's lines: something to fix, or a question in their own chat. */+export const inboxFixes = (items: readonly NeedsYouItem[] | undefined, view: InboxView | null): NeedsYouItem[] =>+ (items ?? []).filter((item) => item.kind !== "message" && !(item.kind === "question" && view?.rows.some((row) => row.tab === "needs-you" && row.origin?.threadId === item.threadId)));++/** The conversation an answer to this line goes to: a team's copy, in the inbox's own, or where it was asked anywhere else. */+export const answerThread = (view: Pick<InboxView, "threadId"> | null, row: Pick<InboxRow, "origin">): string | null => view?.threadId ?? row.origin?.threadId ?? null;++/** Who a line is from, and for whom when a bot was working for another or a guest asked. */+export function senderLabel(row: Pick<InboxRow, "from" | "workingFor" | "askedBy">): string {+ const name = row.from.name;+ if (row.askedBy) return row.askedBy.name ? t("inbox.askedBy", { name, who: row.askedBy.name }) : t("inbox.askedBySomeone", { name });+ return row.workingFor ? t("inbox.workingFor", { name, other: row.workingFor.name }) : name;+}++/** The conversation a line came from, when its subject doesn't already say it. */+export const placeOf = (row: Pick<InboxRow, "kind" | "origin">): string | null => (row.kind !== "message" && row.origin?.title ? t("inbox.in", { title: row.origin.title }) : null);+/** What an ask asks: an approval, a question, or something to review where it was asked; null for anything else or an* ask already settled. */export const askOf = (row: InboxRow) => (row.kind === "ask" && row.tab === "needs-you" ? liveCardKind(row.card) : null);diff --git a/src/components/inbox/use-inbox-actions.ts b/src/components/inbox/use-inbox-actions.tsindex 926ce0c56a..3f7683a415 100644--- a/src/components/inbox/use-inbox-actions.ts+++ b/src/components/inbox/use-inbox-actions.ts@@ -4,7 +4,7 @@ import { useShowThreads } from "@/lib/thread-preferences";import { openThread, useStore } from "@/state/store";import { doneInboxRow, openInbox, readInboxRow, refreshInbox } from "@/state/inbox";import type { CardResponse } from "@/lib/card-answer";-import { closeResponse, type QuickAction } from "./inbox-view";+import { answerThread, closeResponse, type QuickAction } from "./inbox-view";/** What a row's buttons do. An ask is answered through its copy's card here, which answers the card where it was asked,* as its buttons in the chat do; a line of news is done, or opened where it came from. */@@ -13,16 +13,17 @@ export function useInboxActions(view: InboxView | null) {const showThreads = useShowThreads();const answer = useCallback((row: InboxRow, response: CardResponse, failed?: () => void) => {- if (!view?.threadId || !row.card?.requestId) return;+ const threadId = answerThread(view, row);+ if (!threadId || !row.card?.requestId) return;readInboxRow(row);- dispatch({ type: "decideRequest", threadId: view.threadId, requestId: row.card.requestId, behavior: response.behavior, ...(response.message ? { message: response.message } : {}),+ dispatch({ type: "decideRequest", threadId, requestId: row.card.requestId, behavior: response.behavior, ...(response.message ? { message: response.message } : {}),onError: () => { failed?.(); void refreshInbox(); } });}, [view, dispatch]);const openInChat = useCallback((row: InboxRow) => {readInboxRow(row);const target = row.origin ? { botId: row.origin.botId, threadId: row.origin.threadId, messageId: row.origin.messageId }- : view?.threadId ? { botId: view.botId, threadId: view.threadId, messageId: row.id } : null;+ : view?.threadId && view.botId ? { botId: view.botId, threadId: view.threadId, messageId: row.id } : null;if (!target) return;openThread(dispatch, { botId: target.botId, threadId: target.threadId }, state, showThreads);if (target.messageId) dispatch({ type: "focusMessage", threadId: target.threadId, messageId: target.messageId });diff --git a/src/locales/en.json b/src/locales/en.jsonindex e4ec13049b..04bc7fa17e 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2034,6 +2034,10 @@"sidebar.people.yourInboxWaiting": "Your inbox: waiting on you, {count}","inbox.panel.title": "Inbox","inbox.empty": "Nothing for you yet.",+ "inbox.row.count": "Inbox, {count} waiting",+ "inbox.workingFor": "{name}, working for {other}",+ "inbox.askedBy": "{name}, asked by {who}",+ "inbox.askedBySomeone": "{name}, asked by someone else","inbox.waitsOnYou": "Waits on you","inbox.card.summary": "{needs} need you · {info} for your info","inbox.card.forInfo": "{count} for your info",diff --git a/src/state/inbox.ts b/src/state/inbox.tsindex 13b3f9ba37..90d198a43d 100644--- a/src/state/inbox.ts+++ b/src/state/inbox.ts@@ -1,6 +1,6 @@-// On a Team Cloud: the person's inbox as its panel and its card in the chat show it. One copy of the server's list, read-// again whenever their inbox's task says what it lists changed, and the panel's own place (open, the line read).-// Null anywhere but a team's Cloud, where no task is anyone's inbox.+// The person's inbox as the sidebar's row, its panel and a team's card in the chat show it. One copy of the server's list,+// read again whenever what it depends on changes, and the panel's own place (open, the line read). A server older than this+// page has none off a team: it answers 404, and the sidebar falls back to what it showed before.import { useEffect, useSyncExternalStore } from "react";import type { InboxRow, InboxView } from "../../shared/inbox";import { api } from "./api";@@ -29,8 +29,16 @@ function store<T>(initial: T) {const list = store<InboxView | null>(null);export const currentInbox = list.get;export const useInboxView = (): InboxView | null => useSyncExternalStore(list.subscribe, list.get, list.get);+const hasList = () => list.get() !== null;+export const useInboxReady = (): boolean => useSyncExternalStore(list.subscribe, hasList, hasList);++export type InboxSupport = "unknown" | "yes" | "no";+const support = store<InboxSupport>("unknown");+export const useInboxSupport = (): InboxSupport => useSyncExternalStore(support.subscribe, support.get, support.get);+/** Tests and previews say what the server does. */+export const setInboxSupport = support.set;/** Tests and previews show a list of their own. */-export const setInboxView = list.set;+export const setInboxView = (view: InboxView | null): void => { list.set(view); support.set(view ? "yes" : "unknown"); };let reading: Promise<void> | null = null;let readAgain = false;@@ -41,8 +49,11 @@ export function refreshInbox(): Promise<void> {try {do {readAgain = false;- const view = await api<InboxView>("/api/inbox", { background: true }).catch(() => null);- if (view && Array.isArray(view.rows)) list.set(view);+ const view = await api<InboxView>("/api/inbox", { background: true }).catch((error: unknown) => {+ if ((error as { status?: number }).status === 404) { list.set(null); support.set("no"); }+ return null;+ });+ if (view && Array.isArray(view.rows)) { list.set(view); support.set("yes"); }} while (readAgain);} finally {reading = null;@@ -51,12 +62,17 @@ export function refreshInbox(): Promise<void> {return reading;}-/** Keeps the list in step with the person's inbox task; nothing off a team. */-export function useInboxLoader(version: string | null): void {+/** Keeps the list in step with what it depends on, and catches up when the window comes back. A server without an inbox is+ * not asked again. */+export function useInboxLoader(version: string): void {useEffect(() => {- if (version === null) { list.set(null); return; }- void refreshInbox();+ if (support.get() !== "no") void refreshInbox();}, [version]);+ useEffect(() => {+ const again = () => { if (support.get() !== "no") void refreshInbox(); };+ window.addEventListener("focus", again);+ return () => window.removeEventListener("focus", again);+ }, []);}const patchRow = (id: string, patch: Partial<InboxRow>) => {@@ -84,8 +100,10 @@ export function doneInboxRow(row: Pick<InboxRow, "id">): void {}/** A reply to a line of news that waits on one: it goes back where the line came from, as a Reply in the chat does. */-export async function replyToInboxRow(view: Pick<InboxView, "botId" | "threadId">, row: Pick<InboxRow, "id">, text: string): Promise<void> {- await api(`/api/bots/${view.botId}/messages`, { method: "POST", body: JSON.stringify({ text, threadId: view.threadId, replyToId: row.id, sendId: crypto.randomUUID() }) });+export async function replyToInboxRow(view: Pick<InboxView, "botId" | "threadId">, row: Pick<InboxRow, "id" | "origin">, text: string): Promise<void> {+ const origin = view.threadId ? null : row.origin;+ const path = origin?.groupId ? `/api/groups/${origin.groupId}/messages` : `/api/bots/${origin?.botId ?? view.botId}/messages`;+ await api(path, { method: "POST", body: JSON.stringify({ text, threadId: origin?.threadId ?? view.threadId, replyToId: row.id, sendId: crypto.randomUUID() }) });void refreshInbox();}