Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(app-settings): support bulk botIds updates (#7088)
jonathanwxh-cell32b140e614c7
diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.tsindex a41360dee8..7b7f1617c4 100644--- a/server/app-settings/host.test.ts+++ b/server/app-settings/host.test.ts@@ -19,7 +19,7 @@ afterEach(() => {for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });});-function fixture(options: { owner?: boolean; ownerRefusal?: TurnOwnerRefusal; guest?: boolean; group?: boolean; window?: boolean; pictureRefusal?: string; patchRefusal?: string; automated?: boolean } = {}) {+function fixture(options: { owner?: boolean; ownerRefusal?: TurnOwnerRefusal; guest?: boolean; group?: boolean; window?: boolean; pictureRefusal?: string; patchRefusal?: string; patchRefusalFor?: (botId: string) => string | null; emptyRegistryBots?: boolean; automated?: boolean } = {}) {const dataDir = mkdtempSync(join(tmpdir(), "app-settings-"));dirs.push(dataDir);const bots: BotRecord[] = [@@ -59,10 +59,10 @@ function fixture(options: { owner?: boolean; ownerRefusal?: TurnOwnerRefusal; guObject.assign(cfg, patch);return null;},- bots: () => bots,+ bots: () => (options.emptyRegistryBots ? [] : bots),sections: () => ["Sales"],reorderBots: async (botIds) => { bots.sort((a, b) => botIds.indexOf(a.id) - botIds.indexOf(b.id)); return null; },- patchBot: async (botId, body) => { if (options.patchRefusal) return options.patchRefusal; botPatches.push({ botId, body }); Object.assign(bots.find((bot) => bot.id === botId)!, body); return null; },+ patchBot: async (botId, body) => { const refusal = options.patchRefusal ?? options.patchRefusalFor?.(botId); if (refusal) return refusal; botPatches.push({ botId, body }); Object.assign(bots.find((bot) => bot.id === botId)!, body); return null; },call: async (route, method, path, body) => { routeCalls.push({ route, method, path, body }); return null; },read: async (_route, path) => (path === "/api/skills-library" ? { skills: [{ name: "notes", enabled: false, everyBot: false }] } : null),paused: () => [],@@ -594,3 +594,164 @@ describe("every other setting applies at once with Undo, Full access or not", ()]);});});++describe("bulk bot settings (botIds)", () => {+ it("applies one change across more than WRITE_BUDGET bots as one write and one Undo restoring each bot's prior state", async () => {+ const fx = fixture();+ (fx.bots[0] as { browser?: boolean }).browser = true;+ (fx.bots[1] as { browser?: boolean }).browser = false;+ for (let i = 3; i <= 12; i += 1) {+ fx.bots.push({+ id: `bot-${i}`, name: `Bot ${i}`, color: "green", threadId: `t-${i}`, approvalMode: "ask",+ browser: i % 2 === 1, modelSelection: { instanceId: "claude", model: "sonnet" },+ } as unknown as BotRecord);+ }+ const result = await fx.set("bots.settings", JSON.stringify({ botIds: "all", browser: true }));+ expect(result.status).toBe(200);+ expect(result.body.text).toContain("Built-in browser on for 12 bots");+ expect(fx.botPatches).toHaveLength(12);+ expect(fx.botPatches.every((patch) => !("botIds" in patch.body) && patch.body.browser === true)).toBe(true);+ expect(fx.cards()).toHaveLength(1);+ expect(fx.cards()[0]!.card).toMatchObject({+ autoApplied: true, answered: "allow", options: [], subtitle: "Built-in browser on for 12 bots",+ appSettingRequest: { settingId: "bots.settings", tier: "safe", after: "Built-in browser on for 12 bots" },+ });+ // Still counts as only 1 write against WRITE_BUDGET (10).+ for (let i = 1; i < WRITE_BUDGET; i += 1) {+ expect((await fx.set("rooms.turnTimeoutMinutes", 10 + i)).status).toBe(200);+ }+ expect((await fx.set("rooms.turnTimeoutMinutes", 55)).status).toBe(429);++ expect(await fx.host.undo({ threadId: fx.turn.threadId, requestId: String(fx.cards()[0]!.card.requestId) })).toEqual({ claimed: true, state: "undone" });+ expect(fx.bots.every((bot, index) => (bot as { browser?: boolean }).browser === (index % 2 === 0))).toBe(true);+ });++ it("supports explicit botIds lists across approvalModes, color, model, archived and tools with single Undo", async () => {+ const fx = fixture();+ fx.bots.push({ id: "plum", name: "Plum", color: "coral", threadId: "t-plum", approvalMode: "edits", modelSelection: { instanceId: "claude", model: "haiku", effort: "high" }, toolsOff: ["email"] } as unknown as BotRecord);+ (fx.bots[0] as { toolsOff?: string[] }).toolsOff = ["images"];++ expect((await fx.set("bots.color", JSON.stringify({ botIds: ["kiwi", "clive"], color: "teal" }))).status).toBe(200);+ expect(fx.cards().at(-1)!.card.subtitle).toBe("Make 2 bots (Kiwi, Clive) teal");+ expect(await fx.undo()).toEqual({ claimed: true, state: "undone" });+ expect(fx.bots.slice(0, 2).map((bot) => bot.color)).toEqual(["green", "blue"]);++ expect((await fx.set("bots.approvalModes", JSON.stringify({ botIds: ["kiwi", "clive"], mode: "edits" }))).status).toBe(200);+ expect(await fx.undo()).toEqual({ claimed: true, state: "undone" });+ expect(fx.bots.slice(0, 2).map((bot) => bot.approvalMode)).toEqual(["full", "ask"]);++ expect((await fx.set("bots.model", JSON.stringify({ botIds: "all", instanceId: "claude", model: "opus", effort: "low" }))).status).toBe(200);+ expect(await fx.undo()).toEqual({ claimed: true, state: "undone" });+ expect(fx.bots.map((bot) => bot.modelSelection)).toEqual([+ { instanceId: "claude", model: "opus" },+ { instanceId: "claude", model: "sonnet" },+ { instanceId: "claude", model: "haiku", effort: "high" },+ ]);++ expect((await fx.set("bots.tools", JSON.stringify({ botIds: ["kiwi", "plum"], turnOff: ["pages"] }))).status).toBe(200);+ expect(await fx.undo()).toEqual({ claimed: true, state: "undone" });+ expect(fx.bots[0]!.toolsOff).toEqual(["images"]);+ expect(fx.bots[2]!.toolsOff).toEqual(["email"]);++ expect((await fx.set("bots.archived", JSON.stringify({ botIds: ["clive", "plum"], archived: true }))).status).toBe(200);+ expect(fx.bots.map((bot) => Boolean(bot.hidden))).toEqual([false, true, true]);+ expect(await fx.undo()).toEqual({ claimed: true, state: "undone" });+ expect(fx.bots.map((bot) => Boolean(bot.hidden))).toEqual([false, false, false]);+ });++ it("enforces schema bounds, keeps bots.name single-bot, and retains key-leak and automation guards", async () => {+ const fx = fixture();+ for (const [id, payload] of [+ ["bots.color", { botId: "kiwi", botIds: ["clive"], color: "teal" }],+ ["bots.color", { color: "teal" }],+ ["bots.color", { botIds: [], color: "teal" }],+ ["bots.settings", { botIds: ["kiwi", "clive"] }],+ ["bots.name", { botIds: ["kiwi", "clive"], name: "Twin" }],+ ] as const) {+ expect((await fx.set(id, JSON.stringify(payload))).status, `${id}:${JSON.stringify(payload)}`).toBe(400);+ }+ const leak = await fx.set("bots.settings", JSON.stringify({ botIds: "all", apiKey: OPENAI_KEY }));+ expect(leak.status).toBe(400);+ expect(leak.body.error).toContain("Never put a key or token in the value");++ const autoFx = fixture({ automated: true });+ expect((await autoFx.set("bots.settings", JSON.stringify({ botIds: "all", computer: "local" }))).status).toBe(403);+ expect([fx.cards(), fx.botPatches, autoFx.cards(), autoFx.botPatches]).toEqual([[], [], [], []]);+ });++ it("refuses unknown explicit botIds, empty all-targets, or total effect refusals without spending budget", async () => {+ const fx = fixture();+ expect(await fx.set("bots.settings", JSON.stringify({ botIds: ["kiwi", "ghost"], browser: false }))).toMatchObject({+ status: 409,+ body: { error: "No bot has the id ghost. Use list_bots for the ids." },+ });+ expect(await fx.set("bots.model", JSON.stringify({ botIds: "all", instanceId: "nowhere", model: "x" }))).toMatchObject({+ status: 409,+ body: { error: expect.stringContaining("No engine has the id nowhere") },+ });+ fx.bots[0]!.approvalMode = "custom";+ fx.bots[1]!.approvalMode = "custom";+ expect((await fx.set("bots.approvalModes", JSON.stringify({ botIds: "all", mode: "ask" }))).status).toBe(409);++ const emptyFx = fixture({ emptyRegistryBots: true });+ expect((await emptyFx.set("bots.color", JSON.stringify({ botIds: "all", color: "coral" }))).status).toBe(409);+ expect(fx.cards()).toEqual([]);+ expect(fx.botPatches).toEqual([]);+ expect([emptyFx.cards(), emptyFx.botPatches]).toEqual([[], []]);+ for (let i = 0; i < WRITE_BUDGET; i += 1) {+ expect((await fx.set("rooms.turnTimeoutMinutes", 10 + i)).status).toBe(200);+ }+ });++ it("skips per-bot effect and patchBot refusals without blocking other bots, naming only changed bots on card and Undo", async () => {+ const fx = fixture();+ (fx.bots[0] as { defaultBot?: unknown }).defaultBot = { createdAt: 1 };+ fx.bots.push({ id: "plum", name: "Plum", color: "coral", threadId: "t-plum", approvalMode: "ask", modelSelection: { instanceId: "claude", model: "sonnet" } } as unknown as BotRecord);+ const archived = await fx.set("bots.archived", JSON.stringify({ botIds: "all", archived: true }));+ expect(archived.status).toBe(200);+ expect(archived.body.text).toContain("Kiwi is this place's own bot and is never archived");+ expect(fx.cards()).toHaveLength(1);+ expect(fx.cards()[0]!.card.subtitle).toBe("Archive 2 bots (Clive, Plum): they leave the sidebar and keep their chats");+ expect(fx.botPatches.map((p) => p.botId)).toEqual(["clive", "plum"]);+ expect(await fx.undo()).toEqual({ claimed: true, state: "undone" });+ expect(fx.botPatches.slice(2).map((p) => p.botId)).toEqual(["clive", "plum"]);++ const customFx = fixture({ patchRefusalFor: (botId) => (botId === "clive" ? "Clive is currently busy." : null) });+ const color = await customFx.set("bots.color", JSON.stringify({ botIds: ["kiwi", "clive"], color: "coral" }));+ expect(color.status).toBe(200);+ expect(color.body.text).toContain("Done: Make Kiwi coral.");+ expect(color.body.text).toContain("Clive is currently busy.");+ expect(customFx.cards()).toHaveLength(1);+ expect(customFx.cards()[0]!.card.subtitle).toBe("Make Kiwi coral");+ expect(customFx.botPatches).toEqual([{ botId: "kiwi", body: { color: "coral" } }]);+ expect(await customFx.undo()).toEqual({ claimed: true, state: "undone" });+ expect(customFx.botPatches).toEqual([{ botId: "kiwi", body: { color: "coral" } }, { botId: "kiwi", body: { color: "green" } }]);++ const allFailed = fixture({ patchRefusal: "busy" });+ expect(await allFailed.set("bots.color", JSON.stringify({ botIds: ["kiwi", "clive"], color: "coral" }))).toMatchObject({ status: 409 });+ expect(allFailed.cards()).toEqual([]);+ });++ it("deduplicates repeated botIds and detects stale state on Undo after a bulk edit", async () => {+ const fx = fixture();+ const dedup = await fx.set("bots.color", JSON.stringify({ botIds: ["kiwi", "kiwi"], color: "coral" }));+ expect(dedup.status).toBe(200);+ expect(fx.cards()[0]!.card.subtitle).toBe("Make Kiwi coral");+ expect(fx.botPatches).toEqual([{ botId: "kiwi", body: { color: "coral" } }]);+ expect(await fx.undo()).toEqual({ claimed: true, state: "undone" });+ expect(fx.botPatches).toEqual([{ botId: "kiwi", body: { color: "coral" } }, { botId: "kiwi", body: { color: "green" } }]);++ expect((await fx.set("bots.color", JSON.stringify({ botIds: "all", color: "teal" }))).status).toBe(200);+ fx.bots[1]!.color = "coral";+ expect(await fx.undo()).toMatchObject({ claimed: true, state: "invalid", error: UNDO_STALE, stale: true });+ });++ it("preserves chiefOfStaff demotion notice in bulk archive card after in-place patchBot mutation", async () => {+ const fx = fixture();+ (fx.bots[1] as { chiefOfStaff?: boolean }).chiefOfStaff = true;+ fx.bots.push({ id: "plum", name: "Plum", color: "coral", threadId: "t-plum", approvalMode: "ask", modelSelection: { instanceId: "claude", model: "sonnet" } } as unknown as BotRecord);+ const archived = await fx.set("bots.archived", JSON.stringify({ botIds: ["clive", "plum"], archived: true }));+ expect(archived.status).toBe(200);+ expect(fx.cards()[0]!.card.subtitle).toBe("Archive 2 bots (Clive, Plum): they leave the sidebar and keep their chats; Clive stops being Chief of Staff");+ });+});diff --git a/server/app-settings/host.ts b/server/app-settings/host.tsindex a421a0997d..cd83c26466 100644--- a/server/app-settings/host.ts+++ b/server/app-settings/host.ts@@ -104,14 +104,29 @@ export function createAppSettings(deps: AppSettingsDeps) {return null;};+ const isBatchValue = (value: unknown): value is { botIds: unknown } =>+ Boolean(value && typeof value === "object" && "botIds" in value && (value as { botIds?: unknown }).botIds !== undefined);+/** Applies the change, posts its applied card with Undo, and logs it in the decision log. */async function apply(turn: Turn, bot: BotRecord, entry: WritableEntry, value: unknown, change?: string) {- const before = await entry.current(value);- const was = entry.read();- const refusal = await entry.write(value);- if (refusal) return refuse(409, refusal);+ let before: unknown;+ let was = "";+ let shownChange = change;+ let skipped: Array<{ botId: string; name: string; reason: string }> = [];+ if (entry.writeBatch && isBatchValue(value)) {+ const batch = await entry.writeBatch(value);+ if (batch.refusal) return refuse(409, batch.refusal);+ before = batch.before;+ shownChange = batch.change;+ skipped = batch.skipped ?? [];+ } else {+ before = await entry.current(value);+ was = entry.read();+ const refusal = await entry.write(value);+ if (refusal) return refuse(409, refusal);+ }const after = entry.read();- const shown: Shown = change === undefined ? { before: was, after } : { after: change };+ const shown: Shown = shownChange === undefined ? { before: was, after } : { after: shownChange };const requestId = randomUUID();const language = deps.language(turn.threadId);const notSet = (value: string) => value || serverLine(language, "server.appSettings.notSet");@@ -123,8 +138,11 @@ export function createAppSettings(deps: AppSettingsDeps) {});undoable.set(requestId, { entry, before, after });appendDecision(deps.dataDir, { threadId: turn.threadId, requestId, botId: turn.botId, botName: bot.name, tool: TOOL, summary: `${entry.id}: ${said(shown)}`, decision: "auto-approved", source: "app-settings" });- const done = change === undefined ? `Changed ${entry.label} from ${text(was)} to ${text(after)}.` : `Done: ${change}. ${entry.label} now: ${text(after)}.`;- return reply(200, { text: `${done} The user can undo it from the card in the conversation.` });+ const done = shownChange === undefined ? `Changed ${entry.label} from ${text(was)} to ${text(after)}.` : `Done: ${shownChange}. ${entry.label} now: ${text(after)}.`;+ const skippedNote = skipped.length+ ? ` Skipped ${skipped.length} ${skipped.length === 1 ? "bot" : "bots"}: ${skipped.map((item) => `${item.name} (${item.reason})`).join("; ")}${skipped.at(-1)!.reason.endsWith(".") ? "" : "."}`+ : "";+ return reply(200, { text: `${done}${skippedNote} The user can undo it from the card in the conversation.` });}async function set(turn: Turn, body: Record<string, unknown>) {diff --git a/server/app-settings/registry-bots.ts b/server/app-settings/registry-bots.tsindex c0a4af4034..775ce6670a 100644--- a/server/app-settings/registry-bots.ts+++ b/server/app-settings/registry-bots.ts@@ -7,10 +7,14 @@ import { BOT_PROFILE_LIMITS } from "../../shared/bot-profile.ts";import { TOOL_GROUP_LABELS, TOOL_GROUPS, type ToolGroup } from "../../shared/tool-groups.ts";import { EFFORT_LEVELS, MAUS_COLOR_NAMES } from "../../shared/wire.ts";import type { BotRecord } from "../store.ts";-import { withoutKeys, type RegistryDeps, type SettingEntry, type WritableSpec } from "./registry.ts";+import { withoutKeys, type BatchWriteResult, type RegistryDeps, type SettingEntry, type WritableSpec } from "./registry.ts";const botId = z.string().regex(/^[\w-]{1,120}$/);-const forBot = <S extends z.ZodRawShape>(shape: S) => withoutKeys(z.object({ botId, ...shape }).strict());+const botIds = z.union([z.literal("all"), z.array(botId).min(1).max(200)]);+const forSingleBot = <S extends z.ZodRawShape>(shape: S) => withoutKeys(z.object({ botId, ...shape }).strict());+const forBot = <S extends z.ZodRawShape>(shape: S) => withoutKeys(+ z.object({ botId: botId.optional(), botIds: botIds.optional(), ...shape }).strict(),+).refine((value) => ((value as BotInput).botId !== undefined) !== ((value as BotInput).botIds !== undefined), 'name either botId or botIds (an array of ids or "all"), not both');const APPROVAL: Record<Exclude<ApprovalMode, "custom">, { label: string; effect: (name: string) => string }> = {ask: { label: "Ask for approval", effect: (name) => `Make ${name} ask you before each command or file change` },@@ -55,27 +59,146 @@ type OtherField = keyof typeof OTHER;const toolGroups = z.array(z.enum(TOOL_GROUPS)).max(TOOL_GROUPS.length).optional();const offNow = (one: BotRecord): ToolGroup[] => TOOL_GROUPS.filter((group) => one.toolsOff?.includes(group));const groupNames = (groups: readonly ToolGroup[]) => groups.map((group) => TOOL_GROUP_LABELS[group]).join(", ");+const formatBots = (bots: readonly BotRecord[]) => (+ bots.length <= 3+ ? `${bots.length} bots (${bots.map((one) => one.name).join(", ")})`+ : `${bots.length} bots`+);+const otherChanges = (value: Record<string, unknown>) =>+ (Object.keys(value) as string[])+ .filter((field): field is OtherField => field !== "botId" && field !== "botIds" && field in OTHER)+ .map((field) => `${OTHER[field].label} ${OTHER[field].shown(value[field] as never)}`)+ .join("; ");+const capitalize = (line: string) => (line ? `${line[0]!.toUpperCase()}${line.slice(1)}` : line);+const BOT_TARGET = '"botId" or "botIds":[...]|"all"';++type BotInput = { botId?: string; botIds?: "all" | string[] };+type SingleTarget<V extends BotInput> = Omit<V, "botId" | "botIds"> & { botId: string };+const stripTarget = <V extends BotInput>(value: V, id: string): SingleTarget<V> => {+ const { botId: _id, botIds: _ids, ...rest } = value;+ return { ...rest, botId: id } as SingleTarget<V>;+};+const isRestore = <V extends BotInput>(value: unknown): value is { restore: Array<SingleTarget<V>> } =>+ Boolean(value && typeof value === "object" && "restore" in value && Array.isArray((value as { restore?: unknown }).restore));export function botEntries(deps: Pick<RegistryDeps, "bots" | "engines" | "patchBot">, writable: (spec: WritableSpec) => SettingEntry): SettingEntry[] {const bot = (id: string) => deps.bots().find((candidate) => candidate.id === id);const missing = (id: string) => ({ refusal: `No bot has the id ${id}. Use list_bots for the ids.` });const everyBot = (line: (one: BotRecord) => string) => () => deps.bots().map((one) => `${one.name}: ${line(one)}`).join("; ");+ const resolveTargets = (value: BotInput): { bots: BotRecord[] } | { refusal: string } => {+ if (value.botIds === "all") {+ const all = deps.bots();+ return all.length ? { bots: all } : { refusal: "There are no bots to change." };+ }+ const found: BotRecord[] = [];+ for (const id of new Set(value.botIds)) {+ const one = bot(id);+ if (!one) return missing(id);+ found.push(one);+ }+ return { bots: found };+ };+ const dedupRefusals = (reasons: readonly string[]) => [...new Set(reasons)].join(" ");+/** A per-bot entry: `effect` names the change for the card, or refuses it, once the bot is known to exist; `was` is the- * same bot's value before it, for Undo. */- const perBot = <V extends { botId: string }>(spec: Omit<WritableSpec, "current" | "write" | "describe" | "value"> & {- value: z.ZodType<V>; effect(one: BotRecord, value: V): { change: string } | { refusal: string }; was(one: BotRecord, value: V): V; patch(one: BotRecord, value: V): Record<string, unknown>;- }) => writable({- ...spec, current: (value: V) => { const one = bot(value.botId); return one ? spec.was(one, value) : undefined; },- describe: (value: V) => { const one = bot(value.botId); return one ? spec.effect(one, value) : missing(value.botId); },- write: (value: V) => { const one = bot(value.botId); return one ? deps.patchBot(one.id, spec.patch(one, value)) : Promise.resolve(missing(value.botId).refusal); },- });+ * same bot's value before it, for Undo. Entries with `bulkEffect` also accept `botIds` (`["id", ...]` or `"all"`). */+ const perBot = <V extends BotInput>(spec: Omit<WritableSpec, "current" | "write" | "writeBatch" | "describe" | "value"> & {+ value: z.ZodType<V>;+ effect(one: BotRecord, value: SingleTarget<V>): { change: string } | { refusal: string };+ bulkEffect?(bots: BotRecord[], value: Omit<V, "botId" | "botIds">): string;+ was(one: BotRecord, value: SingleTarget<V>): SingleTarget<V>;+ patch(one: BotRecord, value: SingleTarget<V>): Record<string, unknown>;+ }) => {+ const singleOutcome = (one: BotRecord, value: V) => spec.effect(one, stripTarget(value, one.id));+ const singleChange = (one: BotRecord, value: V) => {+ const outcome = singleOutcome(one, value);+ return "change" in outcome ? outcome.change : one.name;+ };+ const writeBatch = spec.bulkEffect+ ? async (value: V): Promise<BatchWriteResult> => {+ const resolved = resolveTargets(value);+ if ("refusal" in resolved) return { refusal: resolved.refusal, change: "", before: undefined };+ const applied: Array<{ snapshot: BotRecord; singleText: string }> = [];+ const restores: Array<SingleTarget<V>> = [];+ const skipped: Array<{ botId: string; name: string; reason: string }> = [];+ for (const one of resolved.bots) {+ const single = stripTarget(value, one.id);+ const checked = spec.effect(one, single);+ if ("refusal" in checked) {+ skipped.push({ botId: one.id, name: one.name, reason: checked.refusal });+ continue;+ }+ const snapshot = { ...one };+ const prior = spec.was(one, single);+ const refusal = await deps.patchBot(one.id, spec.patch(one, single));+ if (refusal) {+ skipped.push({ botId: one.id, name: one.name, reason: refusal });+ continue;+ }+ applied.push({ snapshot, singleText: checked.change });+ restores.push(prior);+ }+ if (!applied.length) return { refusal: dedupRefusals(skipped.map((item) => item.reason)), change: "", before: undefined };+ const change = applied.length === 1+ ? applied[0]!.singleText+ : spec.bulkEffect!(applied.map((item) => item.snapshot), value);+ return { change, before: { restore: restores }, ...(skipped.length ? { skipped } : {}) };+ }+ : undefined;++ return writable({+ ...spec,+ current: (value: V) => {+ if (value.botId === undefined) return undefined;+ const one = bot(value.botId);+ return one ? spec.was(one, stripTarget(value, one.id)) : undefined;+ },+ describe: (value: V) => {+ if (value.botId !== undefined) {+ const one = bot(value.botId);+ return one ? singleOutcome(one, value) : missing(value.botId);+ }+ const resolved = resolveTargets(value);+ if ("refusal" in resolved) return resolved;+ const passing: BotRecord[] = [];+ const reasons: string[] = [];+ for (const one of resolved.bots) {+ const checked = singleOutcome(one, value);+ if ("refusal" in checked) reasons.push(checked.refusal);+ else passing.push(one);+ }+ if (!passing.length) return { refusal: dedupRefusals(reasons) };+ if (passing.length === 1) return { change: singleChange(passing[0]!, value) };+ return { change: spec.bulkEffect ? spec.bulkEffect(passing, value) : `Update ${formatBots(passing)}` };+ },+ write: async (value: V | { restore: Array<SingleTarget<V>> }) => {+ if (isRestore(value)) {+ const errors: string[] = [];+ const remaining: Array<SingleTarget<V>> = [];+ for (const item of value.restore) {+ const one = bot(item.botId);+ const refusal = one ? await deps.patchBot(one.id, spec.patch(one, item)) : missing(item.botId).refusal;+ if (refusal) {+ errors.push(refusal);+ remaining.push(item);+ }+ }+ value.restore.splice(0, value.restore.length, ...remaining);+ return errors.length ? dedupRefusals(errors) : null;+ }+ const one = value.botId === undefined ? undefined : bot(value.botId);+ return one ? deps.patchBot(one.id, spec.patch(one, stripTarget(value, one.id))) : missing(value.botId ?? "").refusal;+ },+ ...(writeBatch ? { writeBatch } : {}),+ });+ };return [perBot({- id: "bots.approvalModes", label: "Approval mode", help: "What one bot may do without asking you, on every one of its conversations.", where: "bot-settings",+ id: "bots.approvalModes", label: "Approval mode", help: "What one or more bots may do without asking you, on every one of their conversations.", where: "bot-settings",synonyms: ["permissions", "full access", "approve", "ask", "approval", "autonomy", "approve for me", "auto-accept edits"],value: forBot({ mode: z.enum(["ask", "edits", "auto", "full"]) }),- allowed: '{"botId","mode"} with mode ask (Ask for approval), edits (Auto-accept edits), auto (Approve for me) or full (Full access). Custom is chosen only in the desktop app',+ allowed: `{${BOT_TARGET},"mode"} with mode ask (Ask for approval), edits (Auto-accept edits), auto (Approve for me) or full (Full access). Custom is chosen only in the desktop app`,read: everyBot((one) => approvalName(approvalModeFor(one))),effect: (one, { mode }) => {if (approvalModeFor(one) === "custom") return { refusal: `${one.name} is on Custom approval, which is changed only in the desktop app, in ${one.name}'s Settings. Tell the user where.` };@@ -83,38 +206,49 @@ export function botEntries(deps: Pick<RegistryDeps, "bots" | "engines" | "patchBif (mode === "auto" && one.computer === "local") return { refusal: `Approve for me while ${one.name} uses this computer's own desktop needs a warning only ${one.name}'s Settings shows. Tell the user to choose it there.` };return { change: `${APPROVAL[mode].effect(one.name)} (${APPROVAL[mode].label})` };},+ bulkEffect: (bots, { mode }) => `Set approval mode to ${APPROVAL[mode].label} for ${formatBots(bots)}`,was: (one, { botId }) => ({ botId, mode: approvalModeFor(one) as Exclude<ApprovalMode, "custom"> }),patch: (_one, { mode }) => ({ approvalMode: mode, applyToAllThreads: true }),}),perBot({id: "bots.name", label: "Bot name", help: "A bot's name, as the sidebar and chats show it.", where: "bot-settings", synonyms: ["rename", "name", "call", "bot name"],- value: forBot({ name: z.string().trim().min(1).max(BOT_PROFILE_LIMITS.name) }), allowed: '{"botId","name"}', read: everyBot((one) => one.name),+ value: forSingleBot({ name: z.string().trim().min(1).max(BOT_PROFILE_LIMITS.name) }), allowed: '{"botId","name"}', read: everyBot((one) => one.name),effect: (one, { name }) => ({ change: `Rename ${one.name} to "${name}"` }), was: (one, { botId }) => ({ botId, name: one.name }), patch: (_one, { name }) => ({ name }),}),perBot({- id: "bots.color", label: "Bot colour", help: "A bot's colour in the sidebar and its chat.", where: "bot-settings", synonyms: ["color", "colour", "tint", "bot color"],- value: forBot({ color: z.enum(MAUS_COLOR_NAMES) }), allowed: `{"botId","color"} with color one of ${MAUS_COLOR_NAMES.join(", ")}`, read: everyBot((one) => one.color),- effect: (one, { color }) => ({ change: `Make ${one.name} ${color}` }), was: (one, { botId }) => ({ botId, color: one.color }), patch: (_one, { color }) => ({ color }),+ id: "bots.color", label: "Bot colour", help: "A bot's colour in the sidebar and its chat, for one or more bots.", where: "bot-settings", synonyms: ["color", "colour", "tint", "bot color"],+ value: forBot({ color: z.enum(MAUS_COLOR_NAMES) }), allowed: `{${BOT_TARGET},"color"} with color one of ${MAUS_COLOR_NAMES.join(", ")}`, read: everyBot((one) => one.color),+ effect: (one, { color }) => ({ change: `Make ${one.name} ${color}` }), bulkEffect: (bots, { color }) => `Make ${formatBots(bots)} ${color}`, was: (one, { botId }) => ({ botId, color: one.color }), patch: (_one, { color }) => ({ color }),}),perBot({- id: "bots.model", label: "Bot model", help: "The engine and model one bot runs on, for its conversations. Ids come from list_models.", where: "bot-settings",+ id: "bots.model", label: "Bot model", help: "The engine and model one or more bots run on, for their conversations. Ids come from list_models.", where: "bot-settings",synonyms: ["model", "engine", "switch model", "change model", "effort", "reasoning"],value: forBot({ instanceId: z.string().min(1).max(120), model: z.string().min(1).max(200), effort: z.enum(EFFORT_LEVELS).optional() }),- allowed: '{"botId","instanceId","model","effort"?} from list_models', read: everyBot((one) => `${one.modelSelection.instanceId} / ${one.modelSelection.model}`),+ allowed: `{${BOT_TARGET},"instanceId","model","effort"?} from list_models`, read: everyBot((one) => `${one.modelSelection.instanceId} / ${one.modelSelection.model}`),effect: (one, { instanceId, model, effort }) => {const engine = deps.engines().find((candidate) => candidate.instanceId === instanceId);if (!engine) return { refusal: `No engine has the id ${instanceId}. Use list_models for engine and model ids.` };return { change: `Move ${one.name} to ${engine.name}, model ${model}${effort ? `, ${effort} effort` : ""}` };},+ bulkEffect: (bots, { instanceId, model, effort }) => {+ const engineName = deps.engines().find((candidate) => candidate.instanceId === instanceId)?.name ?? instanceId;+ return `Move ${formatBots(bots)} to ${engineName}, model ${model}${effort ? `, ${effort} effort` : ""}`;+ },was: (one, { botId }) => ({ botId, instanceId: one.modelSelection.instanceId, model: one.modelSelection.model, ...(one.modelSelection.effort ? { effort: one.modelSelection.effort } : {}) }),patch: (_one, { instanceId, model, effort }) => ({ modelSelection: { instanceId, model, ...(effort ? { effort } : {}) }, requireAvailableModel: true }),}),perBot({- id: "bots.archived", label: "Archived bots", help: "Archive a bot to take it out of the sidebar, keeping its chats; false brings it back.", where: "sidebar",+ id: "bots.archived", label: "Archived bots", help: "Archive one or more bots to take them out of the sidebar, keeping their chats; false brings them back.", where: "sidebar",synonyms: ["archive", "unarchive", "restore bot", "hide bot", "show bot", "hidden"],- value: forBot({ archived: z.boolean() }), allowed: '{"botId","archived":true|false}', read: () => deps.bots().filter((one) => one.hidden).map((one) => one.name).join(", "),+ value: forBot({ archived: z.boolean() }), allowed: `{${BOT_TARGET},"archived":true|false}`, read: () => deps.bots().filter((one) => one.hidden).map((one) => one.name).join(", "),effect: (one, { archived }) => one.defaultBot && archived ? { refusal: `${one.name} is this place's own bot and is never archived. To take it out of the sidebar use sidebar.showHelper.` }: { change: archived ? `Archive ${one.name}: it leaves the sidebar and keeps its chats${one.chiefOfStaff ? ", and stops being Chief of Staff" : ""}` : `Bring ${one.name} back to the sidebar` },+ bulkEffect: (bots, { archived }) => {+ const chiefs = archived ? bots.filter((one) => one.chiefOfStaff).map((one) => one.name) : [];+ return archived+ ? `Archive ${formatBots(bots)}: they leave the sidebar and keep their chats${chiefs.length ? `; ${chiefs.join(", ")} stops being Chief of Staff` : ""}`+ : `Bring ${formatBots(bots)} back to the sidebar`;+ },was: (one, { botId }) => ({ botId, archived: one.hidden === true }),patch: (one, { archived }) => ({ hidden: archived, ...(archived && one.chiefOfStaff ? { chiefOfStaff: false } : {}) }),}),@@ -127,27 +261,28 @@ export function botEntries(deps: Pick<RegistryDeps, "bots" | "engines" | "patchB}),perBot({id: "bots.tools", label: "Bot tool groups", where: "bot-settings",- help: `Turn groups of one bot's built-in tools off to make every request smaller, or back on: ${TOOL_GROUPS.map((group) => `${group} (${TOOL_GROUP_LABELS[group]})`).join(", ")}. Memory, X research, the browser and connected apps have their own settings.`,+ help: `Turn groups of one or more bots' built-in tools off to make every request smaller, or back on: ${TOOL_GROUPS.map((group) => `${group} (${TOOL_GROUP_LABELS[group]})`).join(", ")}. Memory, X research, the browser and connected apps have their own settings.`,synonyms: ["tools", "tool groups", "turn off tools", "meetings", "data", "pages", "publish", "images", "email", "tokens", "smaller requests"],value: forBot({ turnOff: toolGroups, turnOn: toolGroups }).refine((value) => Boolean(value.turnOff?.length || value.turnOn?.length), "name a group in turnOff or turnOn").refine((value) => !value.turnOff?.some((group) => value.turnOn?.includes(group)), "a group can't be in both turnOff and turnOn"),- allowed: `{"botId","turnOff"?:[...],"turnOn"?:[...]} with groups from ${TOOL_GROUPS.join(", ")}`,+ allowed: `{${BOT_TARGET},"turnOff"?:[...],"turnOn"?:[...]} with groups from ${TOOL_GROUPS.join(", ")}`,read: everyBot((one) => (offNow(one).length ? `off: ${groupNames(offNow(one))}` : "all on")),effect: (one, { turnOff = [], turnOn = [] }) => ({ change: `${one.name}: ${[turnOff.length ? `turn off ${groupNames(turnOff)}` : "", turnOn.length ? `turn on ${groupNames(turnOn)}` : ""].filter(Boolean).join("; ")}` }),+ bulkEffect: (bots, { turnOff = [], turnOn = [] }) => `${[turnOff.length ? `Turn off ${groupNames(turnOff)}` : "", turnOn.length ? `Turn on ${groupNames(turnOn)}` : ""].filter(Boolean).join("; ")} for ${formatBots(bots)}`,was: (one, { botId }) => ({ botId, turnOff: offNow(one), turnOn: TOOL_GROUPS.filter((group) => !offNow(one).includes(group)) }),patch: (one, { turnOff = [], turnOn = [] }) => ({ toolsOff: TOOL_GROUPS.filter((group) => turnOff.includes(group) || (offNow(one).includes(group) && !turnOn.includes(group))) }),}),perBot({- id: "bots.settings", label: "Other bot settings", help: `More of one bot's own settings: ${Object.values(OTHER).map((field) => field.label).join(", ")}.`, where: "bot-settings",+ id: "bots.settings", label: "Other bot settings", help: `More of one or more bots' own settings: ${Object.values(OTHER).map((field) => field.label).join(", ")}.`, where: "bot-settings",synonyms: ["voice", "voice notes", "memory", "notifications", "browser", "instructions", "soul", "title", "description", "reply style", "computer", "desktop", "composio", "x research", "keep warm"],value: forBot(Object.fromEntries(Object.entries(OTHER).map(([field, spec]) => [field, spec.value.optional()])) as { [F in OtherField]: z.ZodOptional<(typeof OTHER)[F]["value"]> })- .refine((value) => Object.keys(value).length > 1, "name at least one setting besides botId"),- allowed: `{"botId", ...one or more of ${(Object.keys(OTHER) as OtherField[]).join(", ")}}`,+ .refine((value) => Object.keys(value).some((field) => field !== "botId" && field !== "botIds"), "name at least one setting besides botId or botIds"),+ allowed: `{${BOT_TARGET}, ...one or more of ${(Object.keys(OTHER) as OtherField[]).join(", ")}}`,read: () => "use get on a bot's own fields through list_bots",- effect: (one, value) => ({ change: `${one.name}: ${(Object.keys(value) as Array<OtherField | "botId">).filter((field) => field !== "botId")- .map((field) => `${OTHER[field as OtherField].label} ${OTHER[field as OtherField].shown(value[field as OtherField] as never)}`).join("; ")}` }),- was: (one, value) => ({ botId: one.id, ...Object.fromEntries(Object.keys(value).filter((field) => field !== "botId").map((field) => [field, OTHER[field as OtherField].was(one)])) }),+ effect: (one, value) => ({ change: `${one.name}: ${otherChanges(value)}` }),+ bulkEffect: (bots, value) => `${capitalize(otherChanges(value))} for ${formatBots(bots)}`,+ was: (one, value) => ({ botId: one.id, ...Object.fromEntries(Object.keys(value).filter((field) => field !== "botId" && field !== "botIds").map((field) => [field, OTHER[field as OtherField].was(one)])) }),patch: (_one, { botId: _id, computer, ...rest }) => ({ ...rest, ...(computer ? { computer: computer === "auto" ? null : computer } : {}) }),}),];diff --git a/server/app-settings/registry.ts b/server/app-settings/registry.tsindex 03d019a0a4..a2f74126e2 100644--- a/server/app-settings/registry.ts+++ b/server/app-settings/registry.ts@@ -34,6 +34,13 @@ interface Base {/** What a person or bot sees. Never a secret: a key reads as set or not set. */read(): string;}+export interface BatchWriteResult {+ refusal?: string;+ change: string;+ before: unknown;+ skipped?: Array<{ botId: string; name: string; reason: string }>;+}+/** `value` checks what the bot sends at the boundary. `current`, read just before the write, is what Undo writes back to* put things as they were (typed as `write` takes it); undefined when the earlier state can't be set back. `describe` is* for a change that does not read as before → after: the one line its applied card shows, or why a bot may not make it. */@@ -46,6 +53,7 @@ interface Writable {fromFile?: true;current(value: unknown): unknown;write(value: unknown): Promise<string | null>;+ writeBatch?(value: unknown): Promise<BatchWriteResult>;describe?(value: unknown): { change: string } | { refusal: string };}interface Secret {@@ -94,8 +102,8 @@ const KEY_WHERE: Partial<Record<CredentialTargetId, Where>> = {onePasswordToken: "vault",};-export type WritableSpec = Omit<Base, "read"> & Omit<Writable, "tier" | "current" | "write" | "describe"> & {- read?(): string; current(value: never): unknown; write(value: never): Promise<string | null>; describe?(value: never): { change: string } | { refusal: string };+export type WritableSpec = Omit<Base, "read"> & Omit<Writable, "tier" | "current" | "write" | "describe" | "writeBatch"> & {+ read?(): string; current(value: never): unknown; write(value: never): Promise<string | null>; writeBatch?(value: never): Promise<BatchWriteResult>; describe?(value: never): { change: string } | { refusal: string };};/** `line` says what the new value does on the applied card; `refusal` names a value only the person sets, in Settings. */export type WindowPref = (id: WindowPrefId, label: string, help: string, where: Where, synonyms: string[], allowed: string,@@ -141,7 +149,7 @@ export function createSettingsRegistry(deps: RegistryDeps): SettingEntry[] {const names = (ids: readonly string[]) => ids.map((id) => deps.bots().find((bot) => bot.id === id)?.name ?? id).join(", ");const writable = (spec: WritableSpec): SettingEntry => ({...spec, tier: "safe", read: spec.read ?? (() => display((spec.current as () => unknown)())), current: spec.current as Writable["current"],- write: spec.write as Writable["write"], ...(spec.describe ? { describe: spec.describe as Writable["describe"] } : {}),+ write: spec.write as Writable["write"], ...(spec.writeBatch ? { writeBatch: spec.writeBatch as Writable["writeBatch"] } : {}), ...(spec.describe ? { describe: spec.describe as Writable["describe"] } : {}),});const config = <V,>(patch: (value: V) => Record<string, unknown>) => (value: V) => deps.saveConfig(patch(value));const windowPref: WindowPref = (id, label, help, where, synonyms, allowed, line) => writable({