Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Add an Access tab to Set for all bots in this department
Azad Jagtap7da3e6320fed
diff --git a/scripts/verify-team-bot-access.ts b/scripts/verify-team-bot-access.tsindex db4bb5195b..84833fd9c4 100644--- a/scripts/verify-team-bot-access.ts+++ b/scripts/verify-team-bot-access.ts@@ -112,7 +112,7 @@ try {return answer.body;};const payroll = (await as("ada", "POST", "/api/bots", { name: "Payroll", title: "Answers pay questions", color: "teal" })).bot as { id: string; threadId: string };- await as("ada", "POST", "/api/bots", { name: "Helpdesk", title: "IT questions", color: "blue" });+ const helpdesk = (await as("ada", "POST", "/api/bots", { name: "Helpdesk", title: "IT questions", color: "blue" })).bot as { id: string };if (before) await as("ada", "PATCH", `/api/bots/${payroll.id}`, { visibility: { people: [PEOPLE.bob.email, PEOPLE.cara.email, PEOPLE.dan.email] } });else await as("ada", "PUT", `/api/bots/${payroll.id}/access`, { everyone: "none", people: { [PEOPLE.bob.email]: "view", [PEOPLE.cara.email]: "chat", [PEOPLE.dan.email]: "edit" } });await as("ada", "POST", `/api/bots/${payroll.id}/messages`, { text: "When does payroll run this month?" });@@ -225,6 +225,29 @@ try {await openPayroll();await page.until("!document.querySelector('[data-testid=view-only-composer]') && Boolean(document.querySelector('textarea'))", "Bob's composer");} },+ { name: "department-access-preview", who: "ada", query: "mode=simple", act: async () => {+ for (const id of [payroll.id, helpdesk.id]) await as("ada", "PATCH", `/api/bots/${id}`, { section: "Finance" });+ await page.click('[aria-label="Actions for Finance department"]', "Finance's menu");+ await page.until(`(() => { const item = [...document.querySelectorAll('[role=menuitem]')].find((entry) => entry.textContent.includes("Set for all bots")); item?.click(); return Boolean(item); })()`, "Set for all bots");+ await page.until(`(() => { const tab = [...document.querySelectorAll('[data-testid=team-settings-dialog] [role=tab]')].find((entry) => entry.textContent.trim() === "Access"); tab?.click(); return Boolean(tab); })()`, "the Access tab");+ const pick = (label: string, value: string) => page.evaluate(`(() => { const field = document.querySelector('[data-testid=team-settings-dialog] select[aria-label="${label}"]'); field.value = ${JSON.stringify(value)}; field.dispatchEvent(new Event("change", { bubbles: true })); return true; })()`);+ await pick("Everyone in Acme", "view");+ await pick("A person", PEOPLE.eve.email);+ await page.until("Boolean(document.querySelector('[data-testid=team-settings-rows]'))", "the preview");+ } },+ { name: "department-access-applied", who: "ada", query: "mode=simple", act: async () => {+ for (const id of [payroll.id, helpdesk.id]) await as("ada", "PATCH", `/api/bots/${id}`, { section: "Finance" });+ await page.click('[aria-label="Actions for Finance department"]', "Finance's menu");+ await page.until(`(() => { const item = [...document.querySelectorAll('[role=menuitem]')].find((entry) => entry.textContent.includes("Set for all bots")); item?.click(); return Boolean(item); })()`, "Set for all bots");+ await page.until(`(() => { const tab = [...document.querySelectorAll('[data-testid=team-settings-dialog] [role=tab]')].find((entry) => entry.textContent.trim() === "Access"); tab?.click(); return Boolean(tab); })()`, "the Access tab");+ const pick = (label: string, value: string) => page.evaluate(`(() => { const field = document.querySelector('[data-testid=team-settings-dialog] select[aria-label="${label}"]'); field.value = ${JSON.stringify(value)}; field.dispatchEvent(new Event("change", { bubbles: true })); return true; })()`);+ await pick("Everyone in Acme", "view");+ await pick("A person", PEOPLE.eve.email);+ await page.until(`(() => { const apply = [...document.querySelectorAll('[data-testid=team-settings-dialog] button')].find((entry) => entry.textContent.startsWith("Apply to")); apply?.click(); return Boolean(apply); })()`, "Apply");+ await page.until("Boolean(document.querySelector('[data-testid=team-settings-dialog] [role=status]')?.textContent.includes('applied'))", "the results");+ const shared = ((await as("ada", "GET", "/api/bots")).bots as Array<{ id: string; access?: { everyone: string; people: Record<string, string> } }>).filter((bot) => bot.id === payroll.id || bot.id === helpdesk.id);+ if (shared.length !== 2 || !shared.every((bot) => bot.access?.everyone === "view" && bot.access.people[PEOPLE.eve.email] === "chat")) throw new Error(`department access not applied: ${JSON.stringify(shared)}`);+ } },];let serving: Who | null = null;for (const shot of SHOTS.filter((entry) => !only || only.has(entry.name))) {diff --git a/src/components/TeamSettingsDialog.tsx b/src/components/TeamSettingsDialog.tsxindex edd040b3d3..8cc78f746f 100644--- a/src/components/TeamSettingsDialog.tsx+++ b/src/components/TeamSettingsDialog.tsx@@ -19,15 +19,20 @@ import {type TeamResultRow,} from "@/lib/team-bulk-settings";import { api, desktopApprovalBridge, persistBotUpdate, useStore } from "@/state/store";+import { useTeamPeople } from "@/state/team-people";+import { BOT_ACCESS_LEVELS, GRANTED_LEVELS, type BotAccessLevel, type GrantedLevel } from "../../shared/bot-access";import { EFFORT_LEVELS, type EffortLevel } from "../../shared/wire";+import { levelLabel, saveAccess } from "./bot-access/access";+import { useTeamName } from "./bot-access/ShareBotButton";import { approvalModeOptions } from "./ApprovalModeSelector";import { LocalComputerAutoWarning } from "./LocalComputerAutoWarning";import { effortLabel } from "./ModelPicker";import { Select } from "./Select";-type Tab = "approval" | "model";+type Tab = "approval" | "model" | "access";const KEEP = "";const ENGINE_DEFAULT = "default";+const REMOVE = "remove";export function TeamSettingsRows({ rows }: { rows: ReadonlyArray<TeamPlanRow | TeamResultRow> }) {return (@@ -54,6 +59,13 @@ export function TeamSettingsDialog({ team, onClose }: { team: string; onClose: (const [mode, setMode] = useState<TeamApprovalMode | null>(null);const [model, setModel] = useState<string>(KEEP);const [effort, setEffort] = useState<string>(KEEP);+ const [everyone, setEveryone] = useState<string>(KEEP);+ const [person, setPerson] = useState<string>(KEEP);+ const [personLevel, setPersonLevel] = useState<string>("chat");+ const teamName = useTeamName();+ const teamPeople = useTeamPeople();+ // Admins and owners always edit every bot, so only Users are offered.+ const members = useMemo(() => (teamPeople?.people ?? []).filter((one) => one.role === "member").sort((a, b) => a.name.localeCompare(b.name)), [teamPeople]);const [running, setRunning] = useState(false);const [progress, setProgress] = useState(0);const [results, setResults] = useState<TeamResultRow[] | null>(null);@@ -65,6 +77,12 @@ export function TeamSettingsDialog({ team, onClose }: { team: string; onClose: (const efforts = useMemo(() => teamEffortChoices(bots, state.instances, EFFORT_LEVELS), [bots, state.instances]);const change: TeamChange | null = tab === "approval"? mode ? { kind: "approval", mode } : null+ : tab === "access" ? everyone === KEEP && person === KEEP ? null+ : {+ kind: "access",+ ...(everyone === KEEP ? {} : { everyone: everyone as BotAccessLevel }),+ ...(person === KEEP ? {} : { person: { email: person, level: personLevel === REMOVE ? null : personLevel as GrantedLevel } }),+ }: model === KEEP && effort === KEEP ? null: {kind: "model",@@ -87,7 +105,10 @@ export function TeamSettingsDialog({ team, onClose }: { team: string; onClose: (const outcome = await applyTeamPlan(plan, async (bot, patch) => {const saved = await persistBotUpdate(bot.id, patch, new AbortController().signal, api, desktopApprovalBridge(), bot);dispatch({ type: "botPatched", bot: saved });- }, { acknowledgeLocalAuto, onProgress: setProgress });+ }, {+ acknowledgeLocalAuto, onProgress: setProgress,+ share: async (bot, access) => dispatch({ type: "botPatched", bot: await saveAccess(bot.id, access) }),+ });setResults(outcome);setRunning(false);};@@ -127,6 +148,7 @@ export function TeamSettingsDialog({ team, onClose }: { team: string; onClose: (<div className="mb-3 flex gap-1 rounded-lg bg-inset p-0.5" role="tablist"><button type="button" role="tab" aria-selected={tab === "approval"} disabled={running} className={tabClass(tab === "approval")} onClick={() => setTab("approval")}>{t("teamSettings.tab.approval")}</button><button type="button" role="tab" aria-selected={tab === "model"} disabled={running} className={tabClass(tab === "model")} onClick={() => setTab("model")}>{t("teamSettings.tab.model")}</button>+ {teamName && <button type="button" role="tab" aria-selected={tab === "access"} disabled={running} className={tabClass(tab === "access")} onClick={() => setTab("access")}>{t("teamSettings.tab.access")}</button>}</div>{tab === "approval" ? (<fieldset disabled={running} className="flex flex-col gap-1">@@ -143,6 +165,30 @@ export function TeamSettingsDialog({ team, onClose }: { team: string; onClose: ())}<p className="mt-1 text-[12px] text-ink-secondary">{t("teamSettings.allThreads")} {t("teamSettings.customPerBot")}</p></fieldset>+ ) : tab === "access" && teamName ? (+ <fieldset disabled={running} className="flex flex-col gap-3">+ <label className="text-[13px] text-ink-secondary">{t("botAccess.everyone", { team: teamName })}+ <Select className="mt-1 w-full" aria-label={t("botAccess.everyone", { team: teamName })} value={everyone} onChange={(event) => setEveryone(event.target.value)}>+ <option value={KEEP}>{t("teamSettings.keepEveryone")}</option>+ {BOT_ACCESS_LEVELS.map((level) => <option key={level} value={level}>{levelLabel(level)}</option>)}+ </Select>+ </label>+ <div className="flex gap-2">+ <label className="min-w-0 flex-1 text-[13px] text-ink-secondary">{t("teamSettings.person")}+ <Select className="mt-1 w-full" aria-label={t("teamSettings.person")} value={person} onChange={(event) => setPerson(event.target.value)}>+ <option value={KEEP}>{t("teamSettings.noPerson")}</option>+ {members.map((one) => <option key={one.email} value={one.email}>{one.name === one.email ? one.email : `${one.name} · ${one.email}`}</option>)}+ </Select>+ </label>+ <label className="w-[40%] text-[13px] text-ink-secondary">{t("teamSettings.personLevel")}+ <Select className="mt-1 w-full" aria-label={t("teamSettings.personLevel")} value={personLevel} disabled={person === KEEP} onChange={(event) => setPersonLevel(event.target.value)}>+ {GRANTED_LEVELS.map((level) => <option key={level} value={level}>{levelLabel(level)}</option>)}+ <option value={REMOVE}>{t("teamSettings.removePerson")}</option>+ </Select>+ </label>+ </div>+ <p className="text-[12px] text-ink-secondary">{t("teamSettings.accessHint")}</p>+ </fieldset>) : (<fieldset disabled={running} className="flex flex-col gap-3"><label className="text-[13px] text-ink-secondary">{t("teamSettings.model")}diff --git a/src/lib/team-bulk-settings.test.ts b/src/lib/team-bulk-settings.test.tsindex 4ae7174d8e..dced7e176c 100644--- a/src/lib/team-bulk-settings.test.ts+++ b/src/lib/team-bulk-settings.test.ts@@ -168,3 +168,41 @@ describe("team-wide settings", () => {expect(renderToStaticMarkup(createElement(TeamMenuItems, { ...base, onSetForAll: vi.fn() }))).toContain("Set for all bots in this department…");});});++describe("who can use a department's bots", () => {+ const shared = (id: string, access: Bot["access"], fields: Partial<Bot> = {}) => bot(id, { access, yourAccess: "edit", reportsTo: ADA, ...fields });++ it("sets everyone's level and one person's on each bot, keeping who else was added", () => {+ const payroll = shared("payroll", { everyone: "none", people: { [CARA]: "edit" } });+ const ledger = shared("ledger", { everyone: "chat", people: { [BOB]: "chat" } });+ const plan = planTeamChange([payroll, ledger], instances, { kind: "access", everyone: "chat", person: { email: BOB, level: "chat" } });+ expect(plan).toEqual([+ { bot: payroll, status: "apply", access: { everyone: "chat", people: { [CARA]: "edit", [BOB]: "chat" } } },+ { bot: ledger, status: "unchanged" },+ ]);+ expect(planTeamChange([ledger], instances, { kind: "access", person: { email: BOB, level: null } })).toEqual([+ { bot: ledger, status: "apply", access: { everyone: "chat", people: {} } },+ ]);+ });++ it("skips someone's own MausBot and a bot this person can't share, and never lists a bot's owner", () => {+ const own = shared("mine", { everyone: "none", people: {} }, { defaultBot: { person: BOB } } as Partial<Bot>);+ const viewOnly = shared("atlas", { everyone: "none", people: {} }, { yourAccess: "chat" });+ const owned = shared("owned", { everyone: "none", people: {} });+ const plan = planTeamChange([own, viewOnly, owned], instances, { kind: "access", person: { email: ADA, level: "chat" } });+ expect(plan.map((row) => row.status === "skip" ? row.reason : row.status)).toEqual(["it's someone's own MausBot", "you can't change who can use it", "unchanged"]);+ });++ it("saves each bot's sharing through its own request, one at a time, and never as a settings patch", async () => {+ const payroll = shared("payroll", { everyone: "none", people: {} });+ const plan = planTeamChange([payroll], instances, { kind: "access", everyone: "view" });+ const persist = vi.fn(async () => undefined);+ const share = vi.fn(async () => undefined);+ expect(planNeedsLocalAutoConsent(plan)).toBe(false);+ expect(await applyTeamPlan(plan, persist, { share })).toEqual([{ bot: payroll, status: "applied" }]);+ expect(share).toHaveBeenCalledWith(payroll, { everyone: "view", people: {} });+ expect(persist).not.toHaveBeenCalled();+ });+});+diff --git a/src/lib/team-bulk-settings.ts b/src/lib/team-bulk-settings.tsindex d963f2c06b..a36ae98ff7 100644--- a/src/lib/team-bulk-settings.ts+++ b/src/lib/team-bulk-settings.ts@@ -3,6 +3,9 @@ import { t } from "@/lib/i18n";import { threadApprovalModes, type Bot, type InstanceInfo } from "@/state/store";import type { BotUpdatePatch } from "@/state/bot-patch-queue";import { approvalModeFor, supportsApprovalMode, type ApprovalMode } from "../../shared/approval-mode";+import { sameAccess, type BotAccess, type BotAccessLevel, type GrantedLevel } from "../../shared/bot-access";+import { botOwner } from "../../shared/bot-owner";+import { accessOfBot, withPerson } from "@/components/bot-access/access";import type { EffortLevel, ModelSelection } from "../../shared/wire";/** Custom is per bot: it can only be granted through the desktop's confirmation for that one bot. */@@ -11,10 +14,13 @@ export type TeamApprovalMode = (typeof TEAM_APPROVAL_MODES)[number];export type TeamChange =| { kind: "approval"; mode: TeamApprovalMode }- | { kind: "model"; model?: string; effort?: EffortLevel | null };+ | { kind: "model"; model?: string; effort?: EffortLevel | null }+ /** A person's level null takes them off; the bot's owner is never listed, so they are left out for the bot they own. */+ | { kind: "access"; everyone?: BotAccessLevel; person?: { email: string; level: GrantedLevel | null } };export type TeamPlanRow =| { bot: Bot; status: "apply"; patch: BotUpdatePatch }+ | { bot: Bot; status: "apply"; access: BotAccess }| { bot: Bot; status: "unchanged" }| { bot: Bot; status: "skip"; reason: string };@@ -63,8 +69,18 @@ export function teamEffortChoices(bots: readonly Bot[], instances: readonly Instreturn order.filter((level) => offered.has(level));}+function planAccess(bot: Bot, change: Extract<TeamChange, { kind: "access" }>): TeamPlanRow {+ if (bot.defaultBot?.person) return { bot, status: "skip", reason: t("teamSettings.skip.ownMausBot") };+ if (bot.yourAccess !== "edit") return { bot, status: "skip", reason: t("teamSettings.skip.cantShare") };+ const before = accessOfBot(bot);+ let access: BotAccess = change.everyone ? { everyone: change.everyone, people: before.people } : before;+ if (change.person && change.person.email !== botOwner(bot)) access = withPerson(access, change.person.email, change.person.level);+ return sameAccess(before, access) ? { bot, status: "unchanged" } : { bot, status: "apply", access };+}+export function planTeamChange(bots: readonly Bot[], instances: readonly InstanceInfo[], change: TeamChange): TeamPlanRow[] {return bots.map((bot): TeamPlanRow => {+ if (change.kind === "access") return planAccess(bot, change);const engine = engineOf(bot, instances);const engineName = engine?.displayName ?? bot.modelSelection.instanceId;if (change.kind === "approval") {@@ -102,24 +118,26 @@ export function planTeamChange(bots: readonly Bot[], instances: readonly Instanc}export function planNeedsLocalAutoConsent(plan: readonly TeamPlanRow[]): boolean {- return plan.some((row) => row.status === "apply" && row.patch.approvalMode === "auto" && row.bot.computer === "local");+ return plan.some((row) => row.status === "apply" && "patch" in row && row.patch.approvalMode === "auto" && row.bot.computer === "local");}/** One bot at a time, never in parallel: a refusal on one must not race the next. */export async function applyTeamPlan(plan: readonly TeamPlanRow[],persist: (bot: Bot, patch: BotUpdatePatch) => Promise<unknown>,- options: { acknowledgeLocalAuto?: boolean; onProgress?: (done: number) => void } = {},+ options: { acknowledgeLocalAuto?: boolean; onProgress?: (done: number) => void; share?: (bot: Bot, access: BotAccess) => Promise<unknown> } = {},): Promise<TeamResultRow[]> {const results: TeamResultRow[] = [];for (const row of plan) {if (row.status === "unchanged") results.push({ bot: row.bot, status: "unchanged" });else if (row.status === "skip") results.push({ bot: row.bot, status: "skipped", reason: row.reason });else {- const patch = options.acknowledgeLocalAuto && row.patch.approvalMode === "auto" && row.bot.computer === "local"+ const patch = "access" in row ? null : options.acknowledgeLocalAuto && row.patch.approvalMode === "auto" && row.bot.computer === "local"? { ...row.patch, acknowledgeLocalAuto: true } : row.patch;try {- await persist(row.bot, patch);+ if (patch) await persist(row.bot, patch);+ else if ("access" in row && options.share) await options.share(row.bot, row.access);+ else throw new Error(t("teamSettings.skip.cantShare"));results.push({ bot: row.bot, status: "applied" });} catch (cause) {results.push({ bot: row.bot, status: "skipped", reason: cause instanceof Error ? cause.message : String(cause) });diff --git a/src/locales/en.json b/src/locales/en.jsonindex 98ad12ea6d..0cc7a559aa 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1724,6 +1724,15 @@"teamSettings.intro": "Applies to the {count} bots in this department, one bot at a time, with the same checks as each bot's own settings. Bots that would be refused are skipped and listed with the reason.","teamSettings.tab.approval": "Approval level","teamSettings.tab.model": "Model and effort",+ "teamSettings.tab.access": "Access",+ "teamSettings.keepEveryone": "Keep each bot's setting",+ "teamSettings.person": "A person",+ "teamSettings.noPerson": "Nobody else",+ "teamSettings.personLevel": "What they can do",+ "teamSettings.removePerson": "Remove their access",+ "teamSettings.accessHint": "Admins can always edit every bot, and each bot's owner keeps editing it.",+ "teamSettings.skip.ownMausBot": "it's someone's own MausBot",+ "teamSettings.skip.cantShare": "you can't change who can use it","teamSettings.customPerBot": "Custom approval stays a per-bot setting in that bot's settings.","teamSettings.allThreads": "Each bot gets this level on every one of its threads.","teamSettings.threadModels": "Threads that use their bot's model move with it. A thread with a model of its own keeps it.",