Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(app-settings): refund failed batch writes and check bots.settings stale fields
jonathanwxh-cell66dfde50658a
diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.tsindex 7b7f1617c4..743ce29859 100644--- a/server/app-settings/host.test.ts+++ b/server/app-settings/host.test.ts@@ -754,4 +754,35 @@ describe("bulk bot settings (botIds)", () => {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");});++ it("releases the write reservation when all batch patchBot calls refuse", async () => {+ const fx = fixture({ patchRefusal: "busy" });+ for (let i = 0; i < WRITE_BUDGET + 2; i += 1) {+ expect((await fx.set("bots.color", JSON.stringify({ botIds: "all", color: "coral" }))).status).toBe(409);+ }+ for (let i = 0; i < WRITE_BUDGET; i += 1) {+ expect((await fx.set("rooms.turnTimeoutMinutes", 10 + i)).status).toBe(200);+ }+ expect((await fx.set("rooms.turnTimeoutMinutes", 99)).status).toBe(429);+ });++ it("detects stale targeted fields in bots.settings Undo without blocking when unrelated fields change", async () => {+ const fx = fixture();+ fx.bots[0]!.title = "Old A";+ fx.bots[1]!.title = "Old B";+ expect((await fx.set("bots.settings", JSON.stringify({ botIds: "all", title: "Batch" }))).status).toBe(200);+ // Changing an unrelated field keeps Undo valid.+ fx.bots[0]!.color = "teal";+ // Modifying one targeted field must trigger UNDO_STALE instead of clobbering "New B".+ fx.bots[1]!.title = "New B";+ expect(await fx.undo()).toMatchObject({ claimed: true, state: "invalid", error: UNDO_STALE, stale: true });+ expect(fx.bots[0]!.title).toBe("Batch");+ expect(fx.bots[1]!.title).toBe("New B");++ // Restoring targeted field back to applied state lets Undo succeed cleanly even with the unrelated color edit.+ fx.bots[1]!.title = "Batch";+ expect(await fx.undo()).toEqual({ claimed: true, state: "undone" });+ expect(fx.bots[0]!.title).toBe("Old A");+ expect(fx.bots[1]!.title).toBe("Old B");+ });});diff --git a/server/app-settings/host.ts b/server/app-settings/host.tsindex cd83c26466..e90b450fcb 100644--- a/server/app-settings/host.ts+++ b/server/app-settings/host.ts@@ -103,6 +103,11 @@ export function createAppSettings(deps: AppSettingsDeps) {if (writes.size > 200) writes.delete(writes.keys().next().value!);return null;};+ const releaseWrite = (turn: Turn): void => {+ const spent = writes.get(turn.generation) ?? 0;+ if (spent <= 1) writes.delete(turn.generation);+ else writes.set(turn.generation, spent - 1);+ };const isBatchValue = (value: unknown): value is { botIds: unknown } =>Boolean(value && typeof value === "object" && "botIds" in value && (value as { botIds?: unknown }).botIds !== undefined);@@ -115,7 +120,10 @@ export function createAppSettings(deps: AppSettingsDeps) {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);+ if (batch.refusal) {+ releaseWrite(turn);+ return refuse(409, batch.refusal);+ }before = batch.before;shownChange = batch.change;skipped = batch.skipped ?? [];@@ -125,8 +133,9 @@ export function createAppSettings(deps: AppSettingsDeps) {const refusal = await entry.write(value);if (refusal) return refuse(409, refusal);}- const after = entry.read();- const shown: Shown = shownChange === undefined ? { before: was, after } : { after: shownChange };+ const afterRead = entry.read();+ const after = entry.undoTag ? entry.undoTag(before) : afterRead;+ const shown: Shown = shownChange === undefined ? { before: was, after: afterRead } : { after: shownChange };const requestId = randomUUID();const language = deps.language(turn.threadId);const notSet = (value: string) => value || serverLine(language, "server.appSettings.notSet");@@ -138,7 +147,7 @@ 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 = shownChange === undefined ? `Changed ${entry.label} from ${text(was)} to ${text(after)}.` : `Done: ${shownChange}. ${entry.label} now: ${text(after)}.`;+ const done = shownChange === undefined ? `Changed ${entry.label} from ${text(was)} to ${text(afterRead)}.` : `Done: ${shownChange}. ${entry.label} now: ${text(afterRead)}.`;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(".") ? "" : "."}`: "";@@ -255,7 +264,8 @@ export function createAppSettings(deps: AppSettingsDeps) {if (current.undone) return { claimed: true, state: "already_undone" };const change = undoable.get(args.requestId);if (!change || current.answered !== "allow") return { claimed: true, state: "invalid", error: "This change can't be undone here.", status: 409 };- if (change.entry.read() !== change.after) return { claimed: true, state: "invalid", error: UNDO_STALE, status: 409, stale: true };+ const currentTag = change.entry.undoTag ? change.entry.undoTag(change.before) : change.entry.read();+ if (currentTag !== change.after) return { claimed: true, state: "invalid", error: UNDO_STALE, status: 409, stale: true };const refusal = change.before === undefined ? "The earlier value is not one that can be set back." : await change.entry.write(change.before);if (refusal) return { claimed: true, state: "invalid", error: refusal, status: 409 };undoable.delete(args.requestId);diff --git a/server/app-settings/registry-bots.ts b/server/app-settings/registry-bots.tsindex 775ce6670a..e49f573b2d 100644--- a/server/app-settings/registry-bots.ts+++ b/server/app-settings/registry-bots.ts@@ -283,6 +283,24 @@ export function botEntries(deps: Pick<RegistryDeps, "bots" | "engines" | "patchBeffect: (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)])) }),+ undoTag: (before) => {+ const items = isRestore(before)+ ? before.restore+ : before && typeof before === "object" && "botId" in before+ ? [before as Record<string, unknown>]+ : [];+ return JSON.stringify(items.map((item) => {+ const one = bot(String(item.botId));+ if (!one) return [item.botId, null];+ return [+ item.botId,+ Object.keys(item)+ .filter((field) => field in OTHER)+ .sort()+ .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 a2f74126e2..bdedf5f26e 100644--- a/server/app-settings/registry.ts+++ b/server/app-settings/registry.ts@@ -55,6 +55,8 @@ interface Writable {write(value: unknown): Promise<string | null>;writeBatch?(value: unknown): Promise<BatchWriteResult>;describe?(value: unknown): { change: string } | { refusal: string };+ /** Optional snapshot key of targeted live fields for Undo staleness checks when `read()` returns constant text. */+ undoTag?(before: unknown): string;}interface Secret {tier: "secret";@@ -102,8 +104,8 @@ const KEY_WHERE: Partial<Record<CredentialTargetId, Where>> = {onePasswordToken: "vault",};-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 };+export type WritableSpec = Omit<Base, "read"> & Omit<Writable, "tier" | "current" | "write" | "describe" | "writeBatch" | "undoTag"> & {+ read?(): string; current(value: never): unknown; write(value: never): Promise<string | null>; writeBatch?(value: never): Promise<BatchWriteResult>; describe?(value: never): { change: string } | { refusal: string }; undoTag?(before: unknown): 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,@@ -149,7 +151,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.writeBatch ? { writeBatch: spec.writeBatch as Writable["writeBatch"] } : {}), ...(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"] } : {}), ...(spec.undoTag ? { undoTag: spec.undoTag } : {}),});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({