Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Let the owner put a Chief in charge of every department, including new ones
AdityaUmale38b213525f27
diff --git a/server/admin-activity.ts b/server/admin-activity.tsindex a223a961e4..e6abbedd35 100644--- a/server/admin-activity.ts+++ b/server/admin-activity.ts@@ -225,7 +225,7 @@ export function configChangeRows(before: unknown, after: unknown): Array<Omit<Ad/** What a bot may do, where, and who may see it; display fields (colour, unread, pins) are not audited. */export const BOT_AUDIT_FIELDS = ["approvalMode", "autoApprove", "alwaysAllow", "computer", "cloudBackend", "autoStartVps", "vpsAlias",- "cwd", "composio", "browser", "browserProfile", "mcpServers", "chiefOfStaff", "managedSections", "section",+ "cwd", "composio", "browser", "browserProfile", "mcpServers", "chiefOfStaff", "managedSections", "managesAllSections", "section","parkDirectMessages", "hidden", "modelSelection", "helperModel", "visibility",] as const;diff --git a/server/bot-overview.test.ts b/server/bot-overview.test.tsindex 6f7205f9ec..1dd64a1bd3 100644--- a/server/bot-overview.test.ts+++ b/server/bot-overview.test.ts@@ -47,6 +47,13 @@ describe("buildBotOverview", () => {expect(buildBotOverview(facts).reaches.join(" ")).not.toContain("Engineering");});+ it("says when a Chief is in charge of every department, only while it is the Chief", () => {+ const facts = baseFacts({ bot: { ...baseFacts().bot, chiefOfStaff: true, managesAllSections: true }, engine: { agentsMcp: true }, sectionPeers: 3 });+ expect(buildBotOverview(facts).reaches).toContain("In charge of every department, including new ones.");+ facts.bot.chiefOfStaff = false;+ expect(buildBotOverview(facts).reaches.join(" ")).not.toContain("every department, including new ones");+ });+it("says a bot can talk to every other bot", () => {const open = baseFacts({ bot: baseFacts().bot, engine: { agentsMcp: true }, sectionPeers: 3 });expect(buildBotOverview(open).reaches).toContain("Can talk to all 3 other bots, in any department.");diff --git a/server/bot-overview.ts b/server/bot-overview.tsindex 52ff79409e..c552ba90f6 100644--- a/server/bot-overview.ts+++ b/server/bot-overview.ts@@ -59,6 +59,7 @@ export interface OverviewFacts {| "browser"| "chiefOfStaff"| "managedSections"+ | "managesAllSections">;routines: Array<{id: string;@@ -244,7 +245,8 @@ function reachesLines(facts: OverviewFacts): string[] {const peers = facts.sectionPeers;if (facts.engine?.agentsMcp && peers > 0) lines.push(peers === 1 ? "Can talk to the other bot." : `Can talk to all ${peers} other bots, in any department.`);if (facts.bot.chiefOfStaff) lines.push("Coordinates its department as Chief of Staff.");- if (facts.bot.chiefOfStaff && facts.bot.managedSections?.length) {+ if (facts.bot.chiefOfStaff && facts.bot.managesAllSections === true) lines.push("In charge of every department, including new ones.");+ else if (facts.bot.chiefOfStaff && facts.bot.managedSections?.length) {lines.push(`Also in charge of these departments: ${facts.bot.managedSections.map(name => name || "General").join(", ")}.`);}return lines;diff --git a/server/chief-of-staff.test.ts b/server/chief-of-staff.test.tsindex fd23458643..a1392280f1 100644--- a/server/chief-of-staff.test.ts+++ b/server/chief-of-staff.test.ts@@ -86,6 +86,15 @@ describe("chiefOfStaffSystemPrompt", () => {expect(prompt).toContain("structured result");});+ it("puts every department's bots on the team of a Chief responsible for all of them", () => {+ const everywhere = bots.map(bot => bot.id === "chief" ? { ...bot, chiefOfStaff: true, managesAllSections: true } : bot);+ const prompt = chiefOfStaffSystemPrompt("chief", everywhere, true);+ expect(prompt).toContain("The owner also made you responsible for every department, including ones added later.");+ expect(prompt).toMatch(/Your team, in every department:\n(?:- .*\n)*- Scout — Travel planner \(Personal\) \[id: personal\]/);+ expect(prompt).not.toContain("Other bots you can reach, in other departments:");+ expect(chiefOfStaffSystemPrompt("chief", bots, true)).not.toContain("every department");+ });+it("is the person's assistant, does the work itself and adds a specialist without asking", () => {const prompt = chiefOfStaffSystemPrompt("chief", [{ id: "chief", name: "Atlas" }], true);diff --git a/server/chief-of-staff.ts b/server/chief-of-staff.tsindex 33987f7613..f385fd15a6 100644--- a/server/chief-of-staff.ts+++ b/server/chief-of-staff.ts@@ -59,6 +59,8 @@ export function chiefOfStaffSystemPrompt(: "Your current engine cannot contact teammates. Be honest about that limitation and ask the user to choose a delegation-compatible engine before promising coordinated work.";const isChief = !chief?.defaultBot || chief.chiefOfStaff === true;+ const responsibleFor = chief?.managesAllSections === true ? "every department, including ones added later"+ : chief?.managedSections?.length ? `these departments: ${chief.managedSections.map(s => peerName(s) || "General").join(", ")}` : "";return [isChief? person@@ -67,8 +69,8 @@ export function chiefOfStaffSystemPrompt(: chief?.defaultBot?.person? `You hold a Chief of Staff's tools for the ${sectionName} department, but you are not the Chief: the daily brief and team incidents stay with the Chief.`: `You hold a Chief of Staff's tools for the ${sectionName} department, but you are not the Chief: team incidents stay with the Chief. Keeping an eye on the person's day and their daily brief are yours.`,- chief?.managedSections?.length- ? `The owner also made you responsible for these departments: ${chief.managedSections.map(s => peerName(s) || "General").join(", ")}. You supervise their bots and may propose setup changes there. You remain the user's single point of contact. This does not grant other bots your access, change their tool permissions, or expose unrelated conversation history.`+ responsibleFor+ ? `The owner also made you responsible for ${responsibleFor}. You supervise their bots and may propose setup changes there. You remain the user's single point of contact. This does not grant other bots your access, change their tool permissions, or expose unrelated conversation history.`: "",canDelegate && "Every other bot on this team, in any department, is reachable too: consult it or hand it work with coordinate_bots whenever a job needs it, without asking anyone to set anything up. Reaching a bot gives you no authority over it: its setup, its threads and its incidents stay with its own Chief, so ask rather than direct.","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.",@@ -81,7 +83,7 @@ export function chiefOfStaffSystemPrompt(delegation,canDelegate ? "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." : "",canDelegate ? "When the user asks you to assemble or configure a team, use list_team_setup for the exact authorized teams, bot IDs and model catalog, then propose_team_setup once with all named specialists and their profile/model changes. Include new teams explicitly; the plan covers their creation and your access. Existing thread models and other bots' execution permissions stay unchanged. Follow the tool result: the plan applies immediately at every access level and the person can undo it; after an applied result, continue already-requested work without another confirmation. Only if review is pending, end your turn: the user's decision automatically resumes you once with a structured result. Report failed or cancelled results honestly. Do not ask for another yes, poll, or repeat the proposal. After successful setup, use the available coordination tools for already requested work. For explicitly requested bot deletion, use propose_bot_deletion separately and follow its applied or pending result too." : "",- person ? `Bots that report to ${person} (your team):` : chief?.managedSections?.length ? "Your team, in the departments you are responsible for:" : `Current ${sectionName} department (your team):`,+ person ? `Bots that report to ${person} (your team):` : chief?.managesAllSections === true ? "Your team, in every department:" : chief?.managedSections?.length ? "Your team, in the departments you are responsible for:" : `Current ${sectionName} department (your team):`,roster,othersRoster && (person ? "Other bots you can reach (they report to someone else):" : "Other bots you can reach, in other departments:"),othersRoster,diff --git a/server/incidents.ts b/server/incidents.tsindex 6bf38ecac2..81bb25c588 100644--- a/server/incidents.ts+++ b/server/incidents.ts@@ -13,6 +13,7 @@ export interface IncidentBot {section?: string;chiefOfStaff?: boolean;managedSections?: string[];+ managesAllSections?: boolean;createdBy?: string;reportsTo?: string;hidden?: boolean;diff --git a/server/index.test.ts b/server/index.test.tsindex bdc82787a1..f188903d88 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -4899,6 +4899,29 @@ describe("harness HTTP API", () => {body: { error: "Confirm additional department access (acknowledgePeerScope)", errorKey: "serverError.department.confirmExtra" } });});+ it("makes only a confirmed Chief responsible for every department and revokes it with the role", async () => {+ const bot = (await api("POST", "/api/bots")).body.bot;+ try {+ await api("PATCH", `/api/bots/${bot.id}`, { section: "All departments fixture" });+ expect(await api("PATCH", `/api/bots/${bot.id}`, { managesAllSections: true, acknowledgePeerScope: true }))+ .toMatchObject({ status: 400, body: { errorKey: "serverError.department.chiefResponsibility" } });+ expect(await api("PATCH", `/api/bots/${bot.id}`, { chiefOfStaff: true, managesAllSections: "yes", acknowledgePeerScope: true }))+ .toMatchObject({ status: 400 });+ expect(await api("PATCH", `/api/bots/${bot.id}`, { chiefOfStaff: true, managesAllSections: true }))+ .toMatchObject({ status: 400, body: { errorKey: "serverError.department.confirmResponsibility" } });+ const listed = async () => (await api("GET", "/api/bots")).body.bots.find((entry: { id: string }) => entry.id === bot.id);+ expect(Boolean((await listed()).chiefOfStaff)).toBe(false);+ expect((await api("PATCH", `/api/bots/${bot.id}`, { chiefOfStaff: true, managesAllSections: true, acknowledgePeerScope: true })).status).toBe(200);+ expect(await listed()).toMatchObject({ chiefOfStaff: true, managesAllSections: true });+ expect((await api("PATCH", `/api/bots/${bot.id}`, { chiefOfStaff: false })).status).toBe(200);+ expect(Boolean((await listed()).managesAllSections)).toBe(false);+ expect(await api("PATCH", `/api/bots/${bot.id}`, { managesAllSections: true, acknowledgePeerScope: true }))+ .toMatchObject({ status: 400, body: { errorKey: "serverError.department.chiefResponsibility" } });+ } finally {+ await api("DELETE", `/api/bots/${bot.id}`);+ }+ });+it("rejects a sidebar section Chief collision without changing any bot", async () => {const incumbent = (await api("POST", "/api/bots")).body.bot;const incoming = (await api("POST", "/api/bots")).body.bot;diff --git a/server/index.ts b/server/index.tsindex c895c3fb43..d90104314d 100644--- a/server/index.ts+++ b/server/index.ts@@ -1262,7 +1262,7 @@ function requestedBotFields(req: IncomingMessage, path: string): string[] {if (!body || typeof body !== "object" || Array.isArray(body)) return [];const fields = new Set(Object.keys(body));if (fields.has("autoApprove") || fields.has("approvalMode")) fields.add("autoApprove").add("approvalMode");- if (fields.has("chiefOfStaff")) fields.add("managedSections");+ if (fields.has("chiefOfStaff")) fields.add("managedSections").add("managesAllSections");return [...fields];}@@ -3034,7 +3034,7 @@ async function botOverview(bot: BotRecord, shown: { routine(routine: Routine): bconnectorTools: bot.connectorTools,browser: bot.browser,chiefOfStaff: bot.chiefOfStaff,- managedSections: bot.managedSections,+ managedSections: bot.managedSections, managesAllSections: bot.managesAllSections,},routines: routines!.listRoutines().filter((routine) => routine.botId === bot.id && shown.routine(routine))diff --git a/server/peer-roster.test.ts b/server/peer-roster.test.tsindex 69153df2b6..30be748985 100644--- a/server/peer-roster.test.ts+++ b/server/peer-roster.test.ts@@ -100,6 +100,16 @@ describe("Chief authority over additional departments", () => {expect(hasTeamAuthority({ ...chief, managedSections: [null] as unknown as string[] }, "Personal")).toBe(false);expect(hasTeamAuthority({ ...chief, managedSections: [""] }, undefined)).toBe(true);});+ it("gives a Chief made responsible for every department authority there, including new ones, and nobody else", () => {+ const everywhere = { ...self, chiefOfStaff: true, managesAllSections: true };+ expect(hasTeamAuthority(everywhere, "Finance")).toBe(true);+ expect(hasTeamAuthority(everywhere, "A department added later")).toBe(true);+ expect(hasAuthority(everywhere, fleet[4]!)).toBe(true);+ expect(hasAuthority(fleet[4]!, everywhere)).toBe(false);+ expect(hasTeamAuthority({ ...everywhere, chiefOfStaff: false }, "Finance")).toBe(false);+ expect(hasTeamAuthority({ ...everywhere, managesAllSections: false }, "Finance")).toBe(false);+ expect(hasTeamAuthority({ ...everywhere, managesAllSections: "true" as unknown as boolean }, "Finance")).toBe(false);+ });});describe("reach across departments", () => {diff --git a/server/peer-roster.ts b/server/peer-roster.tsindex 7f0e6dc147..5975e25287 100644--- a/server/peer-roster.ts+++ b/server/peer-roster.ts@@ -12,6 +12,7 @@ export interface RosterMember extends Pick<DefaultBotFields, "defaultBot"> {section?: string;chiefOfStaff?: boolean;managedSections?: string[];+ managesAllSections?: boolean;createdBy?: string;reportsTo?: string;activity?: BotActivity;@@ -27,10 +28,11 @@ export const PEER_ACCESS_HELP = "Every bot can reach every other bot, in any dep/** A title, peer id, imported persona or room membership is not a grant; invalid saved grants fail closed. */export function hasTeamAuthority(- from: Pick<RosterMember, "section" | "chiefOfStaff" | "managedSections">,+ from: Pick<RosterMember, "section" | "chiefOfStaff" | "managedSections" | "managesAllSections">,section?: string,): boolean {const target = sectionKey(section);+ if (from.chiefOfStaff === true && from.managesAllSections === true) return true;return target === sectionKey(from.section) || Boolean(from.chiefOfStaff &&Array.isArray(from.managedSections) && from.managedSections.some(value =>typeof value === "string" && sectionKey(value) === target));diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 63fce1c056..02e41c5952 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -237,7 +237,7 @@ describe("scopes", () => {it("lets a bot's maker without the admin scope say who it is and how it looks, never what it may do or whom it directs", () => {const profile = { name: "Scout", title: "Trips", soul: "Plans trips.", color: "teal", avatarCrop: "square", voice: "alloy", modelSelection: { instanceId: "claude", model: "m" } };expect(adminOnlyBotSetting(profile)).toBeNull();- for (const field of ["approvalMode", "autoApprove", "alwaysAllow", "chiefOfStaff", "managedSections", "computer", "cwd",+ for (const field of ["approvalMode", "autoApprove", "alwaysAllow", "chiefOfStaff", "managedSections", "managesAllSections", "computer", "cwd","mcpServers", "browserProfile", "toolScope", "composio", "browser", "section", "visibility", "reportsTo", "preset", "defaultBot", "installedPackage"]) {expect(adminOnlyBotSetting({ ...profile, [field]: true }), field).toBe(field);expect(botProfileSettings({ ...profile, [field]: true }), field).toEqual(profile);diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.tsindex 6791a72ee7..f616222583 100644--- a/server/routes/bot-patch.ts+++ b/server/routes/bot-patch.ts@@ -546,6 +546,7 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {error: "Auto mode on this computer requires confirming the warning first (acknowledgeLocalAuto)",});}+ const staysChief = body.chiefOfStaff === true || Boolean(existingBot?.chiefOfStaff && body.chiefOfStaff !== false);if (body.managedSections !== undefined) {const parsed = z.array(z.string().trim().max(60)).max(100).safeParse(body.managedSections);if (!parsed.success) return json(res, 400, { error: "managedSections must be a list of up to 100 department names (60 characters each)" });@@ -554,7 +555,7 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {if (newSections.some(section => section !== "" && !store.sections.includes(section))) {return json(res, 400, userError("serverError.department.createFirst"));}- if (sections.length && !(body.chiefOfStaff === true || (existingBot?.chiefOfStaff && body.chiefOfStaff !== false))) {+ if (sections.length && !staysChief) {return json(res, 400, userError("serverError.department.chiefResponsibility"));}if (newSections.length && body.acknowledgePeerScope !== true) {@@ -562,8 +563,18 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {}patch.managedSections = sections;}+ if (body.managesAllSections !== undefined) {+ if (typeof body.managesAllSections !== "boolean") return json(res, 400, { error: "managesAllSections must be true or false" });+ if (body.managesAllSections && !staysChief) {+ return json(res, 400, userError("serverError.department.chiefResponsibility"));+ }+ if (body.managesAllSections && existingBot?.managesAllSections !== true && body.acknowledgePeerScope !== true) {+ return json(res, 400, userError("serverError.department.confirmResponsibility"));+ }+ patch.managesAllSections = body.managesAllSections;+ }// Losing the role revokes its grants: no dormant authority returns if it is elected again.- if (body.chiefOfStaff === false) patch.managedSections = [];+ if (body.chiefOfStaff === false) { patch.managedSections = []; patch.managesAllSections = false; }// "everyone" (default), "admins" or { people: [...] }; members' PATCHes never get here.if (Object.hasOwn(body, "visibility")) {const parsed = parseVisibility(body.visibility);@@ -596,8 +607,9 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {if (Array.isArray(patch.managedSections) && patch.managedSections.some(section => !(existingBot?.managedSections ?? []).includes(section))) {loosened.push("managedSections");}+ if (patch.managesAllSections === true && existingBot?.managesAllSections !== true) loosened.push("managesAllSections");// A shell can forge an Origin header: new cross-team authority from local scripts only while every bot is idle.- if (loosened.includes("managedSections") && auth.kind === "loopback" && !DESKTOP_MANAGED && store.bots.some(bot => bot.busy)) {+ if ((loosened.includes("managedSections") || loosened.includes("managesAllSections")) && auth.kind === "loopback" && !DESKTOP_MANAGED && store.bots.some(bot => bot.busy)) {return json(res, 409, userError("serverError.department.stopBots"));}if (section !== undefined && sectionKey(existingBot?.section) !== sectionKey(section)) loosened.push("section");diff --git a/server/store.ts b/server/store.tsindex 478ee93708..d88833fd85 100644--- a/server/store.ts+++ b/server/store.ts@@ -434,7 +434,7 @@ export class Store {continue;}b.chiefOfStaff = false;- delete b.managedSections;+ delete b.managedSections; delete b.managesAllSections;botsMigrated = true;}for (const b of this.bots as Array<BotRecord & { peers?: unknown; approvePeerComms?: unknown }>) {@@ -1392,7 +1392,7 @@ export class Store {if (operation.fields.modelSelection) next.tasks = this.withDefaultModel(previous, operation.fields.modelSelection);nextBots[at] = next;}- if (operation.fields.chiefOfStaff === false) delete next.managedSections;+ if (operation.fields.chiefOfStaff === false) { delete next.managedSections; delete next.managesAllSections; }next.section = sectionKey(next.section) || undefined;if (operation.fields.soul !== undefined) { next.soulHash = soulHash(operation.fields.soul); next.soulDrift = false; }changed.push(next);@@ -1682,7 +1682,7 @@ export class Store {bot.hidden = false;} else {bot.chiefOfStaff = false;- delete bot.managedSections;+ delete bot.managedSections; delete bot.managesAllSections;}changed.push(bot);}diff --git a/server/team-setup-requests.ts b/server/team-setup-requests.tsindex b2f4455d7e..8809363fa2 100644--- a/server/team-setup-requests.ts+++ b/server/team-setup-requests.ts@@ -46,7 +46,7 @@ export function teamSetupRevision(bot: BotRecord, fields?: TeamSetupFields): strreturn createHash("sha256").update(JSON.stringify({...profileSnapshot(bot), section: section(bot.section), modelSelection: bot.modelSelection,hidden: Boolean(bot.hidden), chiefOfStaff: Boolean(bot.chiefOfStaff),- managedSections: bot.managedSections,+ managedSections: bot.managedSections, managesAllSections: bot.managesAllSections,approvalMode: bot.approvalMode, autoApprove: bot.autoApprove, approvalGrant: bot.approvalGrant,receipt: bot.lastTeamSetupReceipt?.requestId,})).digest("hex");diff --git a/shared/wire.ts b/shared/wire.tsindex 4afdd21810..599911e7e1 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -368,8 +368,8 @@ export interface WireBot extends DefaultBotFields, BotAccessFields {pinnedMessageId?: string;/** The coordinator for this bot's sidebar section. */chiefOfStaff?: boolean;- /** Owner-selected additional teams this Chief may coordinate. */- managedSections?: string[];+ /** Owner-selected additional teams this Chief may coordinate; managesAllSections: every department, including ones added later. */+ managedSections?: string[]; managesAllSections?: boolean;/** Team Cloud only: the lowercased email of the member who created the bot (or moved it in). */createdBy?: string;/** Team Cloud only: the lowercased email of the member the bot reports to, whose inbox its questions, approvals,diff --git a/src/components/bot-settings/ManagedTeamsSettings.tsx b/src/components/bot-settings/ManagedTeamsSettings.tsxindex c11074bd39..c2a80de31b 100644--- a/src/components/bot-settings/ManagedTeamsSettings.tsx+++ b/src/components/bot-settings/ManagedTeamsSettings.tsx@@ -2,28 +2,34 @@ import { useState } from "react";import { t } from "@/lib/i18n";export function ManagedTeamsSettings({- name, ownTeam, teams, allowed, onSave,+ name, ownTeam, teams, allowed, allowAll = false, onSave,}: {name: string;ownTeam: string;teams: string[];allowed: string[];- onSave: (teams: string[]) => void;+ allowAll?: boolean;+ onSave: (teams: string[], allTeams: boolean) => void;}) {const [selected, setSelected] = useState(allowed);+ const [all, setAll] = useState(allowAll);const choices = [...new Set([...teams, ...allowed])].filter(team => team !== ownTeam).sort();- const changed = JSON.stringify([...selected].sort()) !== JSON.stringify([...allowed].sort());+ const changed = all !== allowAll || JSON.stringify([...selected].sort()) !== JSON.stringify([...allowed].sort());return (<details className="mt-3 border-t border-hairline/40 pt-3"><summary className="cursor-pointer text-[13px] font-medium text-ink">{t("botAccess.teams.title")}</summary><p className="mt-2 text-[13px] leading-relaxed text-ink-secondary">{t("botAccess.teams.description", { name })}</p>- <fieldset className="mt-3 flex max-h-52 flex-col gap-2 overflow-y-auto">+ <label className="mt-3 flex items-center gap-2 text-[13px] font-medium text-ink">+ <input type="checkbox" className="accent-accent" checked={all} onChange={event => setAll(event.target.checked)} />+ {t("botAccess.teams.all")}+ </label>+ <fieldset disabled={all} className="mt-3 flex max-h-52 flex-col gap-2 overflow-y-auto disabled:opacity-50"><legend className="sr-only">{t("botAccess.teams.legend", { name })}</legend>{choices.map(team => (<label key={team} className="flex items-center gap-2 text-[13px] text-ink">- <input type="checkbox" className="accent-accent" checked={selected.includes(team)}+ <input type="checkbox" className="accent-accent" checked={all || selected.includes(team)}onChange={event => setSelected(current => event.target.checked? [...current, team] : current.filter(value => value !== team))} />{team === "General" || !team ? t("botAccess.teams.general") : team}@@ -31,7 +37,7 @@ export function ManagedTeamsSettings({))}{!choices.length && <p className="text-[13px] text-ink-secondary">{t("botAccess.teams.empty")}</p>}</fieldset>- <button type="button" disabled={!changed} onClick={() => onSave(selected)}+ <button type="button" disabled={!changed} onClick={() => onSave(selected, all)}className="mt-3 rounded-lg bg-accent px-3 py-1.5 text-[13px] font-medium text-white disabled:opacity-40">{t("botAccess.teams.save")}</button>diff --git a/src/components/bot-settings/PermissionsSection.test.ts b/src/components/bot-settings/PermissionsSection.test.tsindex 57b651d6c1..42a1e272b6 100644--- a/src/components/bot-settings/PermissionsSection.test.ts+++ b/src/components/bot-settings/PermissionsSection.test.ts@@ -101,6 +101,34 @@ describe("on a team", () => {});});+describe("departments a Chief is in charge of", () => {+ const chief: Bot = { ...base, chiefOfStaff: true, managedSections: ["Sales"] };+ const allBox = () => [...host.querySelectorAll("label")].find(label => label.textContent === t("botAccess.teams.all"))!.querySelector("input")!;+ const saveTeams = () => [...host.querySelectorAll("button")].find(button => button.textContent === t("botAccess.teams.save"))!;++ it("saves every department, including new ones, with the confirmation the server asks for", () => {+ render(chief, false, [{ ...base, id: "seller", name: "Seller", section: "Sales" }]);+ expect(allBox().checked).toBe(false);+ expect(saveTeams().disabled).toBe(true);+ flushSync(() => allBox().click());+ expect(host.querySelector("fieldset")!.disabled).toBe(true);+ flushSync(() => saveTeams().click());+ expect(dispatch).toHaveBeenCalledExactlyOnceWith({+ type: "updateBot", botId: "pepper", patch: { managedSections: ["Sales"], managesAllSections: true, acknowledgePeerScope: true },+ });+ });++ it("shows a saved every-department choice and can turn it off", () => {+ render({ ...chief, managesAllSections: true });+ expect(allBox().checked).toBe(true);+ flushSync(() => allBox().click());+ flushSync(() => saveTeams().click());+ expect(dispatch).toHaveBeenCalledExactlyOnceWith({+ type: "updateBot", botId: "pepper", patch: { managedSections: ["Sales"], managesAllSections: false, acknowledgePeerScope: true },+ });+ });+});+describe("PermissionsSection parts", () => {it("leaves Chief of Staff out of a page that asks only for approvals", () => {const derived = {diff --git a/src/components/bot-settings/PermissionsSection.tsx b/src/components/bot-settings/PermissionsSection.tsxindex 38d59cfe7b..eea55039ae 100644--- a/src/components/bot-settings/PermissionsSection.tsx+++ b/src/components/bot-settings/PermissionsSection.tsx@@ -96,11 +96,11 @@ export function PermissionsSection({</div><ProposalStatus bot={bot} kind="chief" />{bot.chiefOfStaff && <ManagedTeamsSettings- key={bot.id + JSON.stringify(bot.managedSections ?? [])}+ key={bot.id + JSON.stringify(bot.managedSections ?? []) + String(bot.managesAllSections === true)}name={bot.name} ownTeam={bot.section?.trim() || ""}teams={["", ...(state.sections ?? []), ...[...state.bots, ...state.groups].map(member => member.section?.trim() || "")]}- allowed={bot.managedSections ?? []}- onSave={managedSections => patch({ managedSections, acknowledgePeerScope: true })}+ allowed={bot.managedSections ?? []} allowAll={bot.managesAllSections === true}+ onSave={(managedSections, managesAllSections) => patch({ managedSections, managesAllSections, acknowledgePeerScope: true })}/>}{bot.chiefOfStaff && <ProposalStatus bot={bot} kind="owner" />}</div>}diff --git a/src/components/bot-settings/useBotSettingsDerived.ts b/src/components/bot-settings/useBotSettingsDerived.tsindex d10ed5bb3c..a23cbe5415 100644--- a/src/components/bot-settings/useBotSettingsDerived.ts+++ b/src/components/bot-settings/useBotSettingsDerived.ts@@ -37,6 +37,7 @@ export type BotPatch = Partial<| "voice"| "chiefOfStaff"| "managedSections"+ | "managesAllSections"| "composio"| "browser"| "recordBrowserSteps"diff --git a/src/lib/bot-overview-text.ts b/src/lib/bot-overview-text.tsindex de33aaeab2..604900e965 100644--- a/src/lib/bot-overview-text.ts+++ b/src/lib/bot-overview-text.ts@@ -39,6 +39,7 @@ const EXACT: Record<string, LocaleKey> = {"Can't use a computer.": "botOverview.line.noComputer","Profile proposal cards require your approval.": "botOverview.line.profileApproval","Connected apps could not be checked.": "botOverview.line.appsUnchecked",+ "In charge of every department, including new ones.": "botOverview.line.allDepartments",};const PREFERENCE: Record<string, LocaleKey> = {diff --git a/src/locales/en.json b/src/locales/en.jsonindex 00e6f7e9a7..a2403f73ad 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7061,6 +7061,7 @@"botAccess.scopes.readWriteHint": "Tool grants and sending limits still apply.","botAccess.teams.title": "Also in charge of","botAccess.teams.description": "{name} can already talk to every bot, in any department. Pick the other departments it's also in charge of as Chief of Staff: it looks after their bots, hears about their problems, and can suggest changes to how they're set up. Its own department is always included.",+ "botAccess.teams.all": "Every department, including new ones","botAccess.teams.legend": "Departments {name} is in charge of","botAccess.teams.general": "General","botAccess.teams.empty": "There are no other departments yet.",@@ -7260,6 +7261,7 @@"botOverview.line.talksToAll": "Can talk to all {count} other bots, in any department.","botOverview.line.talksToOne": "Can talk to the other bot.","botOverview.line.talksToChosen": "Talks only to the bots chosen for it.",+ "botOverview.line.allDepartments": "In charge of every department, including new ones.","botOverview.line.alsoInCharge": "Also in charge of these departments: {departments}.","botOverview.preference.auto": "Auto; availability is checked when a task starts","botOverview.preference.cloud": "cloud desktop",diff --git a/src/state/store.tsx b/src/state/store.tsxindex f1f4ab7af2..94faefbe5f 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -308,7 +308,7 @@ export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" |section?: string;pinnedMessageId?: string;chiefOfStaff?: boolean;- managedSections?: string[];+ managedSections?: string[]; managesAllSections?: boolean;createdBy?: string; reportsTo?: string;composio?: boolean;connectorTools?: Record<string, ConnectorToolGrant>;@@ -1176,7 +1176,7 @@ export function reducer(state: AppState, action: Action): AppState {if ((switchedThread || (before.awaitingThreadSnapshot && action.bot.threadId === before.threadId)) &&Array.isArray(action.bot.messages)) {// The slim deletion broadcast can beat the full snapshot; later duplicate snapshots must not overwrite newer messages.- return reducer(switching, { type: "taskSwitched", bot: { ...before, ...action.bot, computer: action.bot.computer, section: action.bot.section, toolScope: action.bot.toolScope, managedSections: action.bot.managedSections, messages: action.bot.messages, browserProfile: action.bot.browserProfile, vpsAlias: action.bot.vpsAlias, phoneApps: action.bot.phoneApps, onlyPeopleAdded: action.bot.onlyPeopleAdded } });+ return reducer(switching, { type: "taskSwitched", bot: { ...before, ...action.bot, computer: action.bot.computer, section: action.bot.section, toolScope: action.bot.toolScope, managedSections: action.bot.managedSections, managesAllSections: action.bot.managesAllSections, messages: action.bot.messages, browserProfile: action.bot.browserProfile, vpsAlias: action.bot.vpsAlias, phoneApps: action.bot.phoneApps, onlyPeopleAdded: action.bot.onlyPeopleAdded } });}const patched = updateBot(switching, action.bot.id, (b) => ({...b,@@ -1188,7 +1188,7 @@ export function reducer(state: AppState, action: Action): AppState {browserProfile: action.bot.browserProfile,computer: action.bot.computer,toolScope: action.bot.toolScope,- section: action.bot.section, managedSections: action.bot.managedSections,+ section: action.bot.section, managedSections: action.bot.managedSections, managesAllSections: action.bot.managesAllSections,vpsAlias: action.bot.vpsAlias, phoneApps: action.bot.phoneApps, onlyPeopleAdded: action.bot.onlyPeopleAdded,tasks: action.bot.tasks ? mergeTaskStamps(b.tasks, action.bot.tasks) : b.tasks,// Old approvals must never be sent to the replacement thread while its transcript loads.@@ -1737,7 +1737,7 @@ export function reducer(state: AppState, action: Action): AppState {...bot,...action.bot,computer: action.bot.computer,- toolScope: action.bot.toolScope, managedSections: action.bot.managedSections,+ toolScope: action.bot.toolScope, managedSections: action.bot.managedSections, managesAllSections: action.bot.managesAllSections,vpsAlias: action.bot.vpsAlias,messages: action.bot.messages ?? [],hasMore: action.bot.hasMore,