Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(team map): @everyone goes to the Chief, which passes it on; a stop still reaches every bot
milind-soni6aa98afc672c
diff --git a/scripts/testing/team-map-everyone-ui.e2e.test.ts b/scripts/testing/team-map-everyone-ui.e2e.test.tsnew file mode 100644index 0000000000..f1ce7cdedb--- /dev/null+++ b/scripts/testing/team-map-everyone-ui.e2e.test.ts@@ -0,0 +1,90 @@+// @everyone on the Team map, in a real page on the fake engine: the line goes to the Chief alone, a stop goes to every bot as+// its own words, and with no Chief it goes to every bot as before. Screenshots go to OMB_EVERYONE_SHOTS when it is set.+import { spawn, type ChildProcess } from "node:child_process";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { expect, it } from "vitest";+import { resolveAgentBrowserBinary } from "../../server/browser-engine.ts";+import { waitForExit } from "../../server/testing/cleanup.ts";+import { runControlOmb } from "../control-omb.ts";+import { UI_TOOLS_DIR } from "./control-omb-ui.ts";++const ROOT = fileURLToPath(new URL("../..", import.meta.url));+const binary = resolveAgentBrowserBinary({ dataDir: UI_TOOLS_DIR, env: process.env });+const enabled = Boolean(binary) || process.env.OMB_UI_E2E === "1";+if (!enabled) console.log("skipping Team map @everyone UI: set OMB_UI_E2E=1 to install the pinned browser");++type Bot = { id: string; name: string; threadId: string; chiefOfStaff?: boolean; hidden?: boolean };++(enabled ? it : it.skip)("sends @everyone to the Chief, a stop to every bot, and to everyone when there is no Chief", async () => {+ let child: ChildProcess | undefined;+ try {+ let stdout = "", stderr = "";+ let info: { ui: string; url: string };+ child = spawn(process.execPath, ["--experimental-strip-types", join(ROOT, "scripts/control-omb.ts"), "ui", "launch"], {+ cwd: ROOT, env: process.env, stdio: ["ignore", "pipe", "pipe"],+ });+ child.stdout!.on("data", chunk => { stdout += String(chunk); });+ child.stderr!.on("data", chunk => { stderr += String(chunk); });+ await expect.poll(() => {+ if (child!.exitCode !== null) throw new Error(stderr);+ try { info = JSON.parse(stdout); return Boolean(info.ui); } catch { return false; }+ }, { timeout: binary ? 180_000 : 600_000, interval: 250 }).toBe(true);+ const ui = (verb: string, ...args: string[]) => runControlOmb(["ui", verb, "--ui", info.ui, ...args]) as Promise<Record<string, any>>;+ const evaluate = async (js: string) => (await ui("eval", "--js", js)).result;+ const call = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(`${info.url}${path}`, { method, ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }) });+ expect(response.ok, `${method} ${path}`).toBe(true);+ return await response.json() as any;+ };+ const bots = async () => ((await call("GET", "/api/bots?messages=0")).bots as Bot[]).filter((bot) => !bot.hidden);+ const linesTo = async (bot: Bot) => ((await call("GET", `/api/threads/${bot.threadId}/messages`)).messages as Array<{ role: string; text?: string }>)+ .filter((message) => message.role === "user").map((message) => message.text ?? "");+ const shot = async (name: string) => { if (process.env.OMB_EVERYONE_SHOTS) await ui("screenshot", "--out", join(process.env.OMB_EVERYONE_SHOTS, `${name}.png`)); };+ const press = (label: string) => evaluate(`(() => { const target = [...document.querySelectorAll('button, a, [role=menuitem]')].find(button => button.getAttribute('aria-label') === ${JSON.stringify(label)} || button.textContent.trim() === ${JSON.stringify(label)}); target?.click(); return Boolean(target); })()`);+ const pageText = () => evaluate("document.body.innerText") as Promise<string>;++ for (const name of ["Mail", "Books", "Calendar"]) await call("POST", "/api/bots", { name });+ let chief = (await bots()).find((bot) => bot.chiefOfStaff);+ if (!chief) {+ const first = (await bots())[0]!;+ await call("PATCH", `/api/bots/${first.id}`, { chiefOfStaff: true, acknowledgePeerScope: true });+ chief = { ...first, chiefOfStaff: true };+ }+ await evaluate("location.reload(); true");+ await expect.poll(pageText, { timeout: 20_000 }).toContain("Calendar");+ if (!await press("Team map")) await press("Tools");+ await expect.poll(() => press("Team map").then(() => evaluate("Boolean(document.querySelector('textarea[aria-label=\"Message bots on the map\"]'))")), { timeout: 20_000 }).toBe(true);+ const before = new Map(await Promise.all((await bots()).map(async (bot) => [bot.id, (await linesTo(bot)).length] as const)));+ const say = async (text: string) => {+ await ui("type", "--name", "Message bots on the map", "--text", text);+ await ui("press", "--keys", "Escape");+ };+ const send = () => ui("press", "--keys", "Enter");++ // An ordinary line: the Chief gets it and says it passes it on; no other bot gets a line, so none takes a turn.+ await say("@everyone we need to fetch and send mail today");+ await expect.poll(pageText).toContain(`Goes to ${chief.name}, who passes it on to the bots it concerns`);+ await shot("everyone-before-send");+ await send();+ await expect.poll(pageText).toContain(`Sent to ${chief.name}, who passes it on`);+ await shot("everyone-sent-to-chief");+ await expect.poll(() => linesTo(chief!)).toContain("@everyone we need to fetch and send mail today");+ for (const bot of (await bots()).filter((one) => one.id !== chief!.id)) expect(await linesTo(bot), bot.name).toHaveLength(before.get(bot.id) ?? 0);++ // A stop reaches every bot at once, as its own words, so each bot's own send path stops it.+ await say("@everyone stop");+ await send();+ for (const bot of await bots()) await expect.poll(() => linesTo(bot), { message: bot.name }).toContain("stop");+ await shot("everyone-stop");++ // No Chief: everyone gets the line, as before.+ await call("PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: false });+ await evaluate("location.reload(); true");+ await expect.poll(() => press("Team map").then(() => evaluate("Boolean(document.querySelector('textarea[aria-label=\"Message bots on the map\"]'))")), { timeout: 20_000 }).toBe(true);+ await say("@everyone hello all");+ await expect.poll(pageText).not.toContain("who passes it on");+ await send();+ for (const bot of await bots()) await expect.poll(() => linesTo(bot), { message: bot.name }).toContain("@everyone hello all");+ } finally { await waitForExit(child, { signal: "SIGINT", graceMs: 30_000 }); }+}, 720_000);diff --git a/server/chief-of-staff.test.ts b/server/chief-of-staff.test.tsindex 442ca895c6..08ace61bee 100644--- a/server/chief-of-staff.test.ts+++ b/server/chief-of-staff.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { chiefOfStaffSystemPrompt, chiefTidies } from "./chief-of-staff.ts";+import { chiefOfStaffSystemPrompt, chiefTidies, EVERYONE_ON_THE_MAP } from "./chief-of-staff.ts";describe("chiefTidies", () => {const chief = { id: "chief", name: "Chief", section: "Work", chiefOfStaff: true };@@ -126,6 +126,7 @@ describe("chiefOfStaffSystemPrompt", () => {"Do the work yourself, bring in a teammate when one fits the job, and return one concise consolidated answer. Never invent a teammate's progress or result. Normal permission and approval rules still apply.","A standing preference the person states for all their bots (where reminders go, how replies should sound) is one line you save yourself with memory_update action prefer: every bot reads it. Never send it to each bot with coordinate_bots.","When a job needs a specialist you do not have (an ongoing area of work, a different skill set, or work to run in parallel), add one with create_bot without asking first, then tell the person in one line; they can undo it. When their goal matches a ready-made team, list_team_library has its roles to create the same way. Never add a bot just to look busy, or one that duplicates a teammate.",+ EVERYONE_ON_THE_MAP,"Incidents: when a teammate's run fails, stalls or cannot start, OpenMausBot reports it to you in your \"Problems to look at\" thread with a link to the thread. Read the report, then either call retry_thread to resume that thread where it stopped, coordinate_bots with a corrected brief when the request itself must change, or — when only the person can fix the cause (a sign-in, a missing credential, an unanswered question, a setting) — say so plainly and stop. Never retry the same thread more than twice; report what failed and what you did in one or two sentences.","Use list_bots or list_room_targets for the live reachable roster. Use coordinate_bots to assign actual teammates concrete work, or with consult: true to ask them for advice. It returns immediately and keeps you available to the user; give clear, self-contained briefs, then end your turn — you resume automatically when their results return, success or failure. Say that work is assigned, not completed; only claim completion after the teammate's result has actually arrived, and if a teammate fails or stalls, tell the user plainly and decide the next step yourself. Leads can coordinate their own specialists. Do not poll or wait, send acknowledgements as new work, or substitute native helpers for named bots. On return, verify the requested outcome, resolve decisions within the user's scope, request concrete corrections with rework=true when necessary, and return one consolidated answer. Consultations are advice, not proof that work or tests ran. A refusal from coordinate_bots means nothing was sent: fix what it names (usually the id — copy it from list_bots or your roster; a unique teammate name also works) and retry, and never describe a handoff the tool did not accept.","Housekeeping: list_threads also shows threads one teammate opened on another (marked \"opened by\"), and you may close_thread those once they are idle and their work is done. Threads the person started are theirs: never close them.",@@ -159,3 +160,19 @@ describe("chiefOfStaffSystemPrompt", () => {expect(prompt).not.toContain("Quill");});});++describe("an @everyone line from the Team map", () => {+ const team = [{ id: "chief", name: "Clive", chiefOfStaff: true }, { id: "mail", name: "Mail" }, { id: "books", name: "Books" }];++ it("tells the Chief it alone gets the line and passes it only to the bots it concerns", () => {+ const prompt = chiefOfStaffSystemPrompt("chief", team, true);+ expect(prompt).toContain(EVERYONE_ON_THE_MAP);+ expect(EVERYONE_ON_THE_MAP).toContain("never to all of them by default");+ });++ it("says nothing of it to a Chief that cannot hand work on, or to a MausBot that only holds the tools", () => {+ expect(chiefOfStaffSystemPrompt("chief", team, false)).not.toContain(EVERYONE_ON_THE_MAP);+ const maus = [{ id: "maus", name: "MausBot", defaultBot: { person: "[email protected]" } }, ...team.slice(1)];+ expect(chiefOfStaffSystemPrompt("maus", maus, true)).not.toContain(EVERYONE_ON_THE_MAP);+ });+});diff --git a/server/chief-of-staff.ts b/server/chief-of-staff.tsindex d80fc03872..a0b16ba974 100644--- a/server/chief-of-staff.ts+++ b/server/chief-of-staff.ts@@ -23,6 +23,10 @@ const SPECIALISTS = "When a job needs a specialist you do not have (an ongoing aconst sectionKey = (section?: string): string => section?.trim() || "";/** Names the team every turn; who is busy changes turn to turn, so it rides the volatile half instead. */+/** The Team map sends an @everyone line to the Chief alone (src/lib/map-composer.ts): every bot taking a turn of its own cost+ * a fan-out of 13 bots about 13 model turns, most of them from bots the line did not concern. */+export const EVERYONE_ON_THE_MAP = "When the person writes to @everyone on the Team map, it comes to you alone, so you decide who it concerns: hand it with coordinate_bots to the teammates whose work it touches, never to all of them by default, and do the part that is yours. If it concerns nobody else, answer it yourself.";+export function chiefOfStaffSystemPrompt(chiefId: string,bots: ChiefTeamMember[],@@ -71,6 +75,7 @@ export function chiefOfStaffSystemPrompt("Do the work yourself, bring in a teammate when one fits the job, and return one concise consolidated answer. Never invent a teammate's progress or result. Normal permission and approval rules still apply.",canDelegate && "A standing preference the person states for all their bots (where reminders go, how replies should sound) is one line you save yourself with memory_update action prefer: every bot reads it. Never send it to each bot with coordinate_bots.",canDelegate ? SPECIALISTS : "",+ canDelegate && isChief ? EVERYONE_ON_THE_MAP : "",canDelegate && isChief? "Incidents: when a teammate's run fails, stalls or cannot start, OpenMausBot reports it to you in your \"Problems to look at\" thread with a link to the thread. Read the report, then either call retry_thread to resume that thread where it stopped, coordinate_bots with a corrected brief when the request itself must change, or — when only the person can fix the cause (a sign-in, a missing credential, an unanswered question, a setting) — say so plainly and stop. Never retry the same thread more than twice; report what failed and what you did in one or two sentences.": "",diff --git a/server/index.ts b/server/index.tsindex 8104d276fa..94cf12c147 100644--- a/server/index.ts+++ b/server/index.ts@@ -312,7 +312,7 @@ import {} from "./store.ts";import * as tts from "./tts/index.ts";import { createDecider, deciderReady, describeDecider } from "./decider/index.ts"; import { createExtractor, describeHelpers } from "./extractor/index.ts";-import { decideRoomResponder } from "./decider/room-routing.ts"; import { roomRoutingInput } from "./host/room-routing-input.ts";+import { createStopLineRoutes } from "./routes/stop-line.ts"; import { decideRoomResponder } from "./decider/room-routing.ts"; import { roomRoutingInput } from "./host/room-routing-input.ts";import { createLiveSession, liveAttachUrl, liveHistoryFrom, LiveSessionError, type LiveBot, type LiveHistoryMessage } from "./live-call.ts";import { LiveCallController, LiveCallSignedOutError, type LiveSocket } from "./live-call-controller.ts";import { liveCallKey, liveSettingsFor } from "./live-settings.ts";@@ -12239,7 +12239,7 @@ let restartRequested = false;const cloudMoveRoutes = createCloudMoveRoutes();// `workspaceAccess` is assigned at boot, after this line: read it per request.-ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: () => Boolean(workspaceAccess) && entitled("admin") }));+ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: () => Boolean(workspaceAccess) && entitled("admin") })); ROUTES.push(createStopLineRoutes());const orgInstallStatuses = () => orgLibrary?.installStatuses() ?? new Map();ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses })); ROUTES.push(createWorkspaceBannerRoutes({ changed: () => broadcast({ kind: "config", ...configStatus() }) }));ROUTES.push(createSharedComputerRoutes({ enabled: lendingEnabled, computers: sharedComputers, sessionLive: (id) => sessions.isLive(id), environmentId: ENVIRONMENT_ID,diff --git a/server/request-auth.ts b/server/request-auth.tsindex 19873bf8b0..58e5b90136 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -317,6 +317,8 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["GET", "POST"], path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/file$/ },{ methods: ["GET"], path: /^\/api\/threads\/[\w-]+\/job$/ },{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/messages$/ },+ // Only says whether a line is a stop, so the Team map knows where an @everyone line goes (routes/stop-line.ts).+ { methods: ["POST"], path: /^\/api\/stop-line$/ },{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/messages\/[\w-]+\/edit$/ },{ methods: ["POST", "DELETE"], path: /^\/api\/bots\/[\w-]+\/setup-request$/ }, // Set me up: what a typed /setup could do{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/active-branch$/ },diff --git a/server/routes/stop-line.test.ts b/server/routes/stop-line.test.tsnew file mode 100644index 0000000000..4c78922041--- /dev/null+++ b/server/routes/stop-line.test.ts@@ -0,0 +1,47 @@+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, describe, expect, it } from "vitest";++import { json, readBody } from "../harness/http.ts";+import { requiredScope } from "../request-auth.ts";+import { createStopLineRoutes } from "./stop-line.ts";+import { dispatchRoutes } from "./table.ts";++const servers: Server[] = [];+afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+});++async function ask(body: unknown): Promise<{ status: number; body: any }> {+ const routes = [createStopLineRoutes()];+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET",+ auth: { kind: "loopback", scopes: ["admin", "client"] }, json, readBody });+ if (!handled) json(res, 404, { error: "not here" });+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ const response = await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}/api/stop-line`, {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });+ return { status: response.status, body: await response.json() };+}++describe("POST /api/stop-line", () => {+ it("says a line of stop words is a stop, by the rule each bot's own send path uses", async () => {+ expect((await ask({ text: "stop" })).body).toEqual({ stop: true });+ expect((await ask({ text: "stop everything now" })).body).toEqual({ stop: true });+ });++ it("says a line that asks for anything else is not one", async () => {+ expect((await ask({ text: "stop the export and send me the summary" })).body).toEqual({ stop: false });+ expect((await ask({ text: "we need to fetch mail" })).body).toEqual({ stop: false });+ expect((await ask({ text: `stop ${"now ".repeat(600)}` })).body).toEqual({ stop: false });+ });++ it("refuses a body without text, and is open to a paired device like a send", async () => {+ expect((await ask({})).status).toBe(400);+ expect(requiredScope("POST", "/api/stop-line")).toBe("client");+ expect(requiredScope("GET", "/api/stop-line")).toBe("admin");+ });+});diff --git a/server/routes/stop-line.ts b/server/routes/stop-line.tsnew file mode 100644index 0000000000..d87afc327e--- /dev/null+++ b/server/routes/stop-line.ts@@ -0,0 +1,20 @@+// Whether a line a person typed is a stop. The Team map asks before it sends an `@everyone` line: a stop goes to every bot at+// once, where each bot's own send path stops it, and anything else goes to the Chief. The rule is that send path's own+// (room-holds.ts), so the map never keeps a copy of it.+// POST /api/stop-line {text} → {stop}+import { isStopCommand } from "../room-holds.ts";+import { PASS, type RouteHandler } from "./table.ts";++/** A stop is a few words; a longer line is not one, whatever it holds. */+const TEXT_MAX = 2_000;++export function createStopLineRoutes(): RouteHandler {+ return async ({ req, res, path, method, json, readBody }) => {+ if (!(method === "POST" && path === "/api/stop-line")) return PASS;+ let body: unknown;+ try { body = await readBody(req, 8_192); } catch { return json(res, 400, { error: "expected a small JSON body" }); }+ const text = body && typeof body === "object" ? (body as { text?: unknown }).text : undefined;+ if (typeof text !== "string") return json(res, 400, { error: "text must be a string" });+ return json(res, 200, { stop: text.length <= TEXT_MAX && isStopCommand(text) });+ };+}diff --git a/src/components/MapComposer.tsx b/src/components/MapComposer.tsxindex fa977bb10a..cc8b0946d1 100644--- a/src/components/MapComposer.tsx+++ b/src/components/MapComposer.tsx@@ -4,7 +4,8 @@ import { openBot, useStore, type Bot } from "@/state/store";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { mentionChoicesForQuery, mentionQueryAt } from "@/lib/mentions";-import { mapMessageTargets, sentToSummary } from "@/lib/map-composer";+import { mapDelivery, mapMessageTargets, sentToSummary } from "@/lib/map-composer";+import { api } from "@/state/api";import { imeComposing, sendsMessage, useSendKey } from "@/lib/send-key";import { useShowThreads } from "@/lib/thread-preferences";import { MentionMenu, type MentionChoice } from "./MentionMenu";@@ -12,7 +13,8 @@ import { MentionTextarea } from "./MentionTextarea";import { useMenuMotion } from "./MenuMotion";import { randomUuid } from "@/lib/random-uuid";-/** Message bots from the Team map: tag bots, a team or @everyone; each tagged bot gets it as a normal message in its own chat. */+/** Message bots from the Team map: tag bots, a team or @everyone; each bot it goes to gets it as a normal message in its own+ * chat. @everyone goes to the Chief, which passes it on (mapDelivery). */export function MapComposer({ bots, teams, onTagged, onSent }: {bots: Bot[];teams: Array<{ key: string; name: string; count: number }>;@@ -29,11 +31,13 @@ export function MapComposer({ bots, teams, onTagged, onSent }: {const [caret, setCaret] = useState(0);const [dismissedAt, setDismissedAt] = useState<number | null>(null);const [highlight, setHighlight] = useState(0);- const [sent, setSent] = useState<{ botIds: string[]; expanded: boolean } | null>(null);+ const [sent, setSent] = useState<{ botIds: string[]; expanded: boolean; chiefId?: string } | null>(null);const visible = useMemo(() => bots.filter((bot) => !bot.hidden), [bots]);const targets = useMemo(() => mapMessageTargets(text, visible, teams), [text, visible, teams]);- const targetKey = targets.botIds.join(",");+ // Before sending, a line is taken for what it says; only the server knows a stop when it sees one.+ const preview = useMemo(() => mapDelivery(targets, visible, false), [targets, visible]);+ const targetKey = preview.botIds.join(",");useEffect(() => { onTagged(targetKey ? targetKey.split(",") : []); }, [targetKey, onTagged]);useEffect(() => () => onTagged([]), [onTagged]);@@ -68,27 +72,36 @@ export function MapComposer({ bots, teams, onTagged, onSent }: {};const canSend = text.trim().length > 0 && targets.botIds.length > 0;- const send = () => {+ const send = async () => {if (!canSend) return;const message = text.trim();- for (const botId of targets.botIds) dispatch({ type: "send", botId, text: message, sendId: randomUuid() });- onSent(targets.botIds);- setSent({ botIds: targets.botIds, expanded: false });+ const typed = targets;setText("");setCaret(0);setDismissedAt(null);+ // A stop must reach every bot: when the server can't say, the line goes to every bot as it always did.+ const stop = preview.chief+ ? await api<{ stop?: unknown }>("/api/stop-line", { method: "POST", body: JSON.stringify({ text: typed.words }) }).then((answer) => answer.stop === true, () => null)+ : false;+ const delivery = stop === null ? { botIds: typed.botIds } : mapDelivery(typed, visible, stop);+ for (const botId of delivery.botIds) dispatch({ type: "send", botId, text: delivery.text || message, sendId: randomUuid() });+ onSent(delivery.botIds);+ setSent({ botIds: delivery.botIds, expanded: false, ...(delivery.chief ? { chiefId: delivery.chief.id } : {}) });};- const names = (sent?.botIds ?? []).flatMap((id) => visible.find((bot) => bot.id === id) ?? []);+ const chief = sent?.chiefId ? visible.find((bot) => bot.id === sent.chiefId) : undefined;+ const names = (sent?.botIds ?? []).filter((id) => id !== chief?.id).flatMap((id) => visible.find((bot) => bot.id === id) ?? []);const summary = sentToSummary(names.map((bot) => bot.name));const shownNames = sent?.expanded ? names : names.slice(0, summary.names.length);- const hint = text.trim() && !targets.botIds.length ? t("mapComposer.tagHint") : null;+ const hint = text.trim() && !targets.botIds.length ? t("mapComposer.tagHint")+ : preview.chief ? t("mapComposer.willSendViaChief", { name: preview.chief.name }) : null;return <><div className="pointer-events-none absolute inset-x-0 bottom-5 z-30 flex justify-center px-4"><div className="pointer-events-auto w-full max-w-[620px]">- {sent && names.length > 0 && <p role="status" className="mb-2 flex flex-wrap items-center gap-x-1 gap-y-0.5 rounded-xl bg-panel/95 px-3 py-1.5 text-[12px] text-ink-secondary shadow-sm ring-1 ring-hairline/50">- <span>{t("mapComposer.sentTo")}</span>+ {sent && (chief || names.length > 0) && <p role="status" className="mb-2 flex flex-wrap items-center gap-x-1 gap-y-0.5 rounded-xl bg-panel/95 px-3 py-1.5 text-[12px] text-ink-secondary shadow-sm ring-1 ring-hairline/50">+ {chief && <span>{t("mapComposer.sentViaChief", { name: chief.name })}{names.length > 0 ? " ·" : ""}</span>}+ {names.length > 0 && <span>{t("mapComposer.sentTo")}</span>}{shownNames.map((bot, index) => <span key={bot.id}><button className="font-medium text-ink underline-offset-2 hover:underline" onClick={() => openBot(dispatch, bot, showThreads)}>{bot.name}</button>{index < shownNames.length - 1 ? "," : ""}@@ -116,16 +129,16 @@ export function MapComposer({ bots, teams, onTagged, onSent }: {if (event.key === "Enter" || event.key === "Tab") { event.preventDefault(); pick(choices[highlight]); return; }if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setDismissedAt(mention?.start ?? null); return; }}- if (sendsMessage(event.nativeEvent, sendKey)) { event.preventDefault(); send(); }+ if (sendsMessage(event.nativeEvent, sendKey)) { event.preventDefault(); void send(); }}} />- <button onClick={send} disabled={!canSend} aria-label={t("mapComposer.send")}- title={!canSend ? t("mapComposer.tagHint") : targets.botIds.length === 1 ? t("mapComposer.sendToOne") : t("mapComposer.sendTo", { count: targets.botIds.length })}+ <button onClick={() => void send()} disabled={!canSend} aria-label={t("mapComposer.send")}+ title={!canSend ? t("mapComposer.tagHint") : preview.botIds.length === 1 ? t("mapComposer.sendToOne") : t("mapComposer.sendTo", { count: preview.botIds.length })}className={cn("mb-0.5 flex size-8 shrink-0 items-center justify-center rounded-full text-white transition-opacity", canSend ? "bg-accent hover:brightness-110" : "bg-ink-secondary/30")}><ArrowUp size={16} /></button></div>{(hint || targets.botIds.length > 0) && <p className="mt-1.5 px-3 text-[11px] text-ink-secondary">- {hint ?? (targets.botIds.length === 1 ? t("mapComposer.willSendOne") : t("mapComposer.willSend", { count: targets.botIds.length }))}+ {hint ?? (preview.botIds.length === 1 ? t("mapComposer.willSendOne") : t("mapComposer.willSend", { count: preview.botIds.length }))}</p>}</div></div>diff --git a/src/lib/map-composer.test.ts b/src/lib/map-composer.test.tsindex e486cbf6db..0524fcfb18 100644--- a/src/lib/map-composer.test.ts+++ b/src/lib/map-composer.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { mapMessageTargets, sentToSummary } from "./map-composer";+import { everyoneChief, mapDelivery, mapMessageTargets, sentToSummary } from "./map-composer";const bots = [{ id: "maya", name: "Maya Chen", section: "Research" },@@ -38,7 +38,7 @@ describe("Team map message targets", () => {});it("finds nobody in a message without a tag", () => {- expect(mapMessageTargets("start your task", bots, teams)).toEqual({ botIds: [], tags: [], unknown: [] });+ expect(mapMessageTargets("start your task", bots, teams)).toEqual({ botIds: [], tags: [], unknown: [], words: "start your task" });});it("summarises who a message went to", () => {@@ -47,3 +47,46 @@ describe("Team map message targets", () => {expect(sentToSummary(["Ana", "Ben", "Cy", "Dee", "Eve"])).toEqual({ names: ["Ana", "Ben"], more: 3 });});});++describe("Team map delivery", () => {+ const team = [+ { id: "chief", name: "Clive", chiefOfStaff: true },+ { id: "design-chief", name: "Dana", section: "Design", chiefOfStaff: true },+ ...bots,+ ];+ const targets = (text: string, roster = team) => mapMessageTargets(text, roster, teams);++ it("sends @everyone to the team's Chief alone, which passes it on", () => {+ expect(mapDelivery(targets("@everyone we need mail today"), team, false)).toEqual({ botIds: ["chief"], chief: team[0] });+ });++ it("still sends to a bot or team named directly, after the Chief", () => {+ expect(mapDelivery(targets("@everyone mail, and @Nora Lind check the inbox"), team, false).botIds).toEqual(["chief", "nora"]);+ expect(mapDelivery(targets("@Research @everyone status?"), team, false).botIds).toEqual(["chief", "maya", "theo"]);+ });++ it("sends a stop to every bot, as its own words, so each bot stops at once", () => {+ const stop = mapDelivery(targets("@everyone stop now"), team, true);+ expect(stop.botIds).toEqual(targets("@everyone").botIds);+ expect(stop.text).toBe("stop now");+ expect(stop.chief).toBeUndefined();+ });++ it("sends to everyone as before when there is no Chief, and leaves lines without @everyone alone", () => {+ expect(mapDelivery(targets("@everyone hello", bots), bots, false)).toEqual({ botIds: ["maya", "theo", "theodora", "nora", "solo"] });+ expect(mapDelivery(targets("@Design start"), team, false)).toEqual({ botIds: ["design-chief", "theodora", "nora"] });+ expect(mapDelivery(targets("@Theo stop"), team, true)).toEqual({ botIds: ["theo"] });+ });++ it("prefers the Chief over the whole team to a department's, and never a hidden one", () => {+ expect(everyoneChief(team)?.id).toBe("chief");+ expect(everyoneChief(team.slice(1))?.id).toBe("design-chief");+ expect(everyoneChief([{ id: "x", name: "X", chiefOfStaff: true, hidden: true }, ...bots])).toBeUndefined();+ });++ it("takes only the tags out of the words", () => {+ expect(targets("@everyone alles stoppen").words).toBe("alles stoppen");+ expect(targets("Bitte @Theo und @Design: stop").words).toBe("Bitte und : stop");+ expect(targets("mail [email protected]").words).toBe("mail [email protected]");+ });+});diff --git a/src/lib/map-composer.ts b/src/lib/map-composer.tsindex 53f2358917..b4c41ce1ac 100644--- a/src/lib/map-composer.ts+++ b/src/lib/map-composer.ts@@ -5,6 +5,7 @@ export interface MapComposerBot {name: string;section?: string;hidden?: boolean;+ chiefOfStaff?: boolean;}export interface MapComposerTeam {@@ -23,6 +24,8 @@ export function mapMessageTargets(text: string, bots: readonly MapComposerBot[],botIds: string[];tags: MapTag[];unknown: string[];+ /** The message without the tags that matched: what it says, with who it is for taken out. */+ words: string;} {const visible = bots.filter((bot) => !bot.hidden && bot.name.trim());const names = [@@ -35,6 +38,7 @@ export function mapMessageTargets(text: string, bots: readonly MapComposerBot[],].sort((a, b) => b.name.length - a.name.length);const tags: MapTag[] = [];const unknown: string[] = [];+ const spans: Array<[number, number]> = [];let at = -1;while ((at = text.indexOf("@", at + 1)) !== -1) {if (!isMentionBoundary(text, at)) continue;@@ -43,13 +47,37 @@ export function mapMessageTargets(text: string, bots: readonly MapComposerBot[],&& !isMentionNameContinuation(rest.slice(name.length)));if (match) {tags.push(match.tag);+ spans.push([at, at + 1 + match.name.length]);at += match.name.length;continue;}const word = /^[\p{L}\p{N}\p{M}_.-]+/u.exec(rest)?.[0];if (word) unknown.push(word);}- return { botIds: [...new Set(tags.flatMap((tag) => tag.botIds))], tags, unknown };+ const words = spans.reduceRight((rest, [from, to]) => rest.slice(0, from) + rest.slice(to), text).replace(/\s+/g, " ").trim();+ return { botIds: [...new Set(tags.flatMap((tag) => tag.botIds))], tags, unknown, words };+}++/** Who a message from the Team map is delivered to. `@everyone` goes to the team's Chief alone, which hands it to the bots it+ * concerns, so a bot it doesn't concern takes no turn. A stop goes to every bot, as its own words without the tags, so each+ * bot's own send path stops it at once. A bot or team named directly always gets it. With no Chief, everyone gets it. */+export function mapDelivery(targets: ReturnType<typeof mapMessageTargets>, bots: readonly MapComposerBot[], stop: boolean): {+ botIds: string[];+ text?: string;+ chief?: MapComposerBot;+} {+ if (!targets.tags.some((tag) => tag.kind === "everyone")) return { botIds: targets.botIds };+ if (stop) return { botIds: targets.botIds, text: targets.words };+ const chief = everyoneChief(bots);+ if (!chief) return { botIds: targets.botIds };+ const named = targets.tags.filter((tag) => tag.kind !== "everyone").flatMap((tag) => tag.botIds);+ return { botIds: [...new Set([chief.id, ...named])], chief };+}++/** The Chief an `@everyone` line goes to: the one over the whole team before a department's own. */+export function everyoneChief<T extends MapComposerBot>(bots: readonly T[]): T | undefined {+ const chiefs = bots.filter((bot) => bot.chiefOfStaff && !bot.hidden);+ return chiefs.find((bot) => !bot.section?.trim()) ?? chiefs[0];}/** "Maya, Theo and 18 more": the first names, then a count. */diff --git a/src/locales/en.json b/src/locales/en.jsonindex 7686f3f943..c04c330263 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -5928,6 +5928,8 @@"mapComposer.sendTo": "Send to {count} tagged bots","mapComposer.willSendOne": "Goes to 1 tagged bot, in its own chat","mapComposer.willSend": "Goes to {count} tagged bots, each in its own chat",+ "mapComposer.willSendViaChief": "Goes to {name}, who passes it on to the bots it concerns",+ "mapComposer.sentViaChief": "Sent to {name}, who passes it on","mapComposer.sentTo": "Sent to","mapComposer.andMore": "and {count} more","team.instructionsPlaceholder": "Goals\n- Ship the Windows onboarding refresh\n\nDecisions\n- Keep customer data local\n\nPreferences\n- Use concise weekly updates",diff --git a/src/locales/it.json b/src/locales/it.jsonindex f336bdf68f..7c4ec5ac04 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -5125,6 +5125,8 @@"mapComposer.sendTo": "Invia a {count} bot menzionati","mapComposer.willSendOne": "Va a 1 bot menzionato, nella sua chat","mapComposer.willSend": "Va a {count} bot menzionati, ognuno nella propria chat",+ "mapComposer.willSendViaChief": "Va a {name}, che lo passa ai bot che riguarda",+ "mapComposer.sentViaChief": "Inviato a {name}, che lo passa avanti","mapComposer.sentTo": "Inviato a","mapComposer.andMore": "e altri {count}","team.instructionsPlaceholder": "Obiettivi\n- Consegna l'aggiornamento della prima configurazione per Windows\n\nDecisioni\n- Tieni i dati dei clienti in locale\n\nPreferenze\n- Usa aggiornamenti settimanali concisi",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 3c6fe3bc2d..882a9a6139 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -5350,6 +5350,8 @@"mapComposer.sendTo": "指定した {count} 体のボットに送信","mapComposer.willSendOne": "指定した 1 体のボットに、そのボットのチャットで送信されます","mapComposer.willSend": "指定した {count} 体のボットに、それぞれのチャットで送信されます",+ "mapComposer.willSendViaChief": "{name} に届き、関係するボットに引き継がれます",+ "mapComposer.sentViaChief": "{name} に送信しました。関係するボットに引き継がれます","mapComposer.sentTo": "送信先","mapComposer.andMore": "ほか {count} 体","team.instructionsPlaceholder": "目標\n- Windowsオンボーディングの刷新をリリースする\n\n決定事項\n- 顧客データはローカルに保持する\n\n方針\n- 週次の更新は簡潔にまとめる",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex 14a9767c40..56ac7bf329 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -5689,6 +5689,8 @@"mapComposer.sendTo": "태그한 봇 {count}개에게 보내기","mapComposer.willSendOne": "태그한 봇 1개에게 그 봇의 채팅으로 가요","mapComposer.willSend": "태그한 봇 {count}개에게 각자의 채팅으로 가요",+ "mapComposer.willSendViaChief": "{name}에게 가고, 관련된 봇에게 전달돼요",+ "mapComposer.sentViaChief": "{name}에게 보냈어요. 관련된 봇에게 전달해요","mapComposer.sentTo": "보낸 대상","mapComposer.andMore": "외 {count}개","team.instructionsPlaceholder": "목표\n- Windows 온보딩 개편 출시\n\n결정 사항\n- 고객 데이터는 로컬에 보관\n\n선호\n- 주간 업데이트는 간결하게",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex e99002faec..1344b0ca0b 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -5266,6 +5266,8 @@"mapComposer.sendTo": "Wyślij do oznaczonych botów: {count}","mapComposer.willSendOne": "Trafi do 1 oznaczonego bota, w jego własnym czacie","mapComposer.willSend": "Trafi do oznaczonych botów: {count}, każdy w swoim czacie",+ "mapComposer.willSendViaChief": "Trafi do: {name}, a stamtąd do botów, których dotyczy",+ "mapComposer.sentViaChief": "Wysłano do: {name}, a stamtąd dalej","mapComposer.sentTo": "Wysłano do","mapComposer.andMore": "i {count} więcej","team.instructionsPlaceholder": "Cele\n- Wdrożyć odświeżenie pierwszych kroków w Windows\n\nDecyzje\n- Dane klientów pozostają lokalnie\n\nPreferencje\n- Zwięzłe cotygodniowe aktualizacje",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 36f21208ea..7eb63a52d2 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -5319,6 +5319,8 @@"mapComposer.sendTo": "Отправить {count} отмеченным ботам","mapComposer.willSendOne": "Дойдёт до 1 отмеченного бота в его чате","mapComposer.willSend": "Дойдёт до {count} отмеченных ботов, каждому в отдельный чат",+ "mapComposer.willSendViaChief": "Уйдёт к {name}, а дальше — к ботам, которых это касается",+ "mapComposer.sentViaChief": "Отправлено {name}, дальше — к нужным ботам","mapComposer.sentTo": "Отправлено","mapComposer.andMore": "и ещё {count}","team.instructionsPlaceholder": "Цели\n- Выпустить обновление онбординга для Windows\n\nРешения\n- Данные клиентов храним локально\n\nПредпочтения\n- Краткие еженедельные отчёты",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 4eec79bd03..33613732c3 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -20719,7 +20719,9 @@"server.browser.stoppedWaiting": "0c6d8041de6e6077f9be0ddaddeebe4457e29a1231de7aa6a8b9288704e5ccb2","composer.queued.capacityStarter": "b04ed386a880964a1438f12746471df1a3f2dd4894ca97dcb3fbd22b1834da88","composer.queued.seePlans": "d989893356eeff0f22804648f79ee465c509800917fe8d64ec31ab5aa6557220",- "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f"+ "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f",+ "mapComposer.willSendViaChief": "002eb9ef4efe4459e760b645a541b65592a3c706eb9f1fe606bd88a601270f92",+ "mapComposer.sentViaChief": "d041c2b20ba17c607f7195d1a40a4dfbac05e9749aa2471de3341e70d7f0aae1"},"pt-br": {"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",@@ -34427,7 +34429,9 @@"server.browser.stoppedWaiting": "0c6d8041de6e6077f9be0ddaddeebe4457e29a1231de7aa6a8b9288704e5ccb2","composer.queued.capacityStarter": "b04ed386a880964a1438f12746471df1a3f2dd4894ca97dcb3fbd22b1834da88","composer.queued.seePlans": "d989893356eeff0f22804648f79ee465c509800917fe8d64ec31ab5aa6557220",- "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f"+ "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f",+ "mapComposer.willSendViaChief": "002eb9ef4efe4459e760b645a541b65592a3c706eb9f1fe606bd88a601270f92",+ "mapComposer.sentViaChief": "d041c2b20ba17c607f7195d1a40a4dfbac05e9749aa2471de3341e70d7f0aae1"},"zh-tw": {"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",@@ -59201,7 +59205,9 @@"server.browser.stoppedWaiting": "0c6d8041de6e6077f9be0ddaddeebe4457e29a1231de7aa6a8b9288704e5ccb2","composer.queued.capacityStarter": "b04ed386a880964a1438f12746471df1a3f2dd4894ca97dcb3fbd22b1834da88","composer.queued.seePlans": "d989893356eeff0f22804648f79ee465c509800917fe8d64ec31ab5aa6557220",- "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f"+ "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f",+ "mapComposer.willSendViaChief": "002eb9ef4efe4459e760b645a541b65592a3c706eb9f1fe606bd88a601270f92",+ "mapComposer.sentViaChief": "d041c2b20ba17c607f7195d1a40a4dfbac05e9749aa2471de3341e70d7f0aae1"},"ru": {"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",@@ -65786,7 +65792,9 @@"server.browser.stoppedWaiting": "0c6d8041de6e6077f9be0ddaddeebe4457e29a1231de7aa6a8b9288704e5ccb2","composer.queued.capacityStarter": "b04ed386a880964a1438f12746471df1a3f2dd4894ca97dcb3fbd22b1834da88","composer.queued.seePlans": "d989893356eeff0f22804648f79ee465c509800917fe8d64ec31ab5aa6557220",- "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f"+ "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f",+ "mapComposer.willSendViaChief": "002eb9ef4efe4459e760b645a541b65592a3c706eb9f1fe606bd88a601270f92",+ "mapComposer.sentViaChief": "d041c2b20ba17c607f7195d1a40a4dfbac05e9749aa2471de3341e70d7f0aae1"},"it": {"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",@@ -72169,7 +72177,9 @@"server.browser.stoppedWaiting": "0c6d8041de6e6077f9be0ddaddeebe4457e29a1231de7aa6a8b9288704e5ccb2","composer.queued.capacityStarter": "b04ed386a880964a1438f12746471df1a3f2dd4894ca97dcb3fbd22b1834da88","composer.queued.seePlans": "d989893356eeff0f22804648f79ee465c509800917fe8d64ec31ab5aa6557220",- "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f"+ "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f",+ "mapComposer.willSendViaChief": "002eb9ef4efe4459e760b645a541b65592a3c706eb9f1fe606bd88a601270f92",+ "mapComposer.sentViaChief": "d041c2b20ba17c607f7195d1a40a4dfbac05e9749aa2471de3341e70d7f0aae1"},"ko": {"connectedWorkspaces.localTitle": "7d6deafeab011d734c3fdd1bfd6f69544fbb746a004019269bdb48544b01164b",@@ -79277,7 +79287,9 @@"server.browser.stoppedWaiting": "0c6d8041de6e6077f9be0ddaddeebe4457e29a1231de7aa6a8b9288704e5ccb2","composer.queued.capacityStarter": "b04ed386a880964a1438f12746471df1a3f2dd4894ca97dcb3fbd22b1834da88","composer.queued.seePlans": "d989893356eeff0f22804648f79ee465c509800917fe8d64ec31ab5aa6557220",- "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f"+ "settings.threads.starter": "8837e4531b35bb772dcbdd6067cf3a494bca815a6620e7319bd01d9af0e1574f",+ "mapComposer.willSendViaChief": "002eb9ef4efe4459e760b645a541b65592a3c706eb9f1fe606bd88a601270f92",+ "mapComposer.sentViaChief": "d041c2b20ba17c607f7195d1a40a4dfbac05e9749aa2471de3341e70d7f0aae1"}}}diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 27f7877297..b60e7a0d52 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -5853,6 +5853,8 @@"mapComposer.sendTo": "发送给 {count} 个标记的机器人","mapComposer.willSendOne": "会发送给 1 个标记的机器人,在它自己的聊天中","mapComposer.willSend": "会发送给 {count} 个标记的机器人,各自在独立的聊天中",+ "mapComposer.willSendViaChief": "发送给 {name},由它转给相关的机器人",+ "mapComposer.sentViaChief": "已发送给 {name},由它转交","mapComposer.sentTo": "已发送给","mapComposer.andMore": "以及另外 {count} 个","team.instructionsPlaceholder": "目标\n- 完成 Windows 新手指引改版\n\n决策\n- 客户数据保留在本地\n\n偏好\n- 每周简报保持简洁",