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): say why a settings change was refused and what to do
AdityaUmalec3ae85c4b1b6
diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.tsindex efdd276e67..6bd8746c1f 100644--- a/server/app-settings/host.test.ts+++ b/server/app-settings/host.test.ts@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from "vitest";import type { AppConfig } from "../config.ts";import { flushDecisionLog, readDecisions } from "../decision-log.ts";import { UNDO_STALE } from "../direct-apply.ts";+import type { TurnOwnerRefusal } from "../host/phones.ts";import type { BotRecord } from "../store.ts";import { createAppSettings, WRITE_BUDGET } from "./host.ts";import { createSettingsRegistry } from "./registry.ts";@@ -18,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; 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; automated?: boolean } = {}) {const dataDir = mkdtempSync(join(tmpdir(), "app-settings-"));dirs.push(dataDir);const bots: BotRecord[] = [@@ -85,6 +86,7 @@ function fixture(options: { owner?: boolean; guest?: boolean; group?: boolean; wconst host = createAppSettings({store: store as never, dataDir, entries,turnOwner: () => (options.owner === false ? null : "owner"),+ ownerRefusal: () => (options.owner === false ? (options.ownerRefusal ?? null) : null),guestDriven: () => options.guest === true,automated: () => options.automated === true,requestCredential: async (_bot, _threadId, body) => { credentialCards.push(body); return { status: 201, body: { messageId: "secret-1", label: "OpenAI API key" } }; },@@ -148,6 +150,31 @@ describe("reads", () => {expect(saved).toEqual([]);});+ it("says why a turn is not the owner's own and what the person can do instead, and still changes nothing", async () => {+ const said = async (options: Parameters<typeof fixture>[0]) => {+ const { host, turn, set, saved } = fixture(options);+ const where = (JSON.parse(String((await host.handle({ action: "get", id: "general.language" }, turn)).body.text)) as { where: string }).where;+ const refused = await set("general.language", "de");+ expect(refused.status).toBe(403);+ expect(saved).toEqual([]);+ const error = String(refused.body.error);+ expect(error).toMatch(/^Settings change only in the owner's own conversation, so nothing changed; you may still read settings\. /);+ expect(error).toContain(`The person can change it themselves in ${where}.`);+ return error;+ };+ expect(await said({ owner: false, ownerRefusal: "shared" })).toContain("Several people share this server");+ expect(await said({ owner: false, ownerRefusal: "service" })).toContain("set up as a shared or hosted server");+ expect(await said({ guest: true })).toContain("A guest writes in this conversation");+ const someoneElse = await said({ owner: false, ownerRefusal: "someone-else" });+ expect(someoneElse).toContain("asking again here won't work");+ expect(someoneElse).toContain("a new conversation with this bot that only they write in");+ expect(await said({ owner: false, ownerRefusal: "not-owner" })).toContain("started by someone other than the owner");+ expect(await said({ owner: false, ownerRefusal: "memory-changed" })).toContain("tap Mark reviewed");+ expect(await said({ owner: false, ownerRefusal: "unproven" })).toContain("can't be tied to a message the owner sent here");+ // No reason given: the plain words, still refused.+ expect(await said({ owner: false })).toContain("can't be tied to a message the owner sent here");+ });+it("refuses writes in a guest-driven conversation", async () => {const { set, saved } = fixture({ guest: true });expect((await set("general.language", "de")).status).toBe(403);diff --git a/server/app-settings/host.ts b/server/app-settings/host.tsindex ea82b70877..27a36df1c0 100644--- a/server/app-settings/host.ts+++ b/server/app-settings/host.ts@@ -6,6 +6,7 @@ import { randomUUID } from "node:crypto";import { isSettingsCardId, SETTINGS_CARD_IDS, type AppSettingRequest, type SettingsCardId } from "../../shared/app-settings.ts";import { appendDecision } from "../decision-log.ts";import { UNDO_STALE } from "../direct-apply.ts";+import type { TurnOwnerRefusal } from "../host/phones.ts";import { serverLine } from "../server-lines.ts";import type { BotRecord, GroupRecord, Store } from "../store.ts";import type { ThemeTool } from "../themes/tool.ts";@@ -65,6 +66,8 @@ export interface AppSettingsDeps {entries: readonly SettingEntry[];/** Non-null when the turn is the owner's own (phones.turnOwner); null on a Team Cloud or hosted workspace. */turnOwner(turn: Turn): string | null;+ /** Why turnOwner is null (phones.turnOwnerRefusal), for the refusal's words only; turnOwner stays the guard. */+ ownerRefusal?(turn: Turn): TurnOwnerRefusal | null;guestDriven(threadId: string): boolean;/** The turn answers a routine, webhook or other automation, owner-written ones included: no lasting move onto this computer. */automated?(turn: Turn): boolean;@@ -89,6 +92,9 @@ export function createAppSettings(deps: AppSettingsDeps) {const reply = (status: number, body: Record<string, unknown>) => ({ status, body });const refuse = (status: number, error: string) => reply(status, { error });const describe = (entry: SettingEntry) => ({ id: entry.id, label: entry.label, tier: entry.tier, value: text(entry.read()), where: placePath(entry.where) });+ /** Null when the turn is the owner's own; otherwise why not, so the refusal can say what the person can do instead. */+ const notOwners = (turn: Turn): NotOwners | null =>+ deps.guestDriven(turn.threadId) ? "guest" : deps.turnOwner(turn) !== null ? null : (deps.ownerRefusal?.(turn) ?? "unknown");const from = (bot: BotRecord, threadId: string) => (deps.connectorThread(bot.id, threadId)?.group ? { from: { botId: bot.id, name: bot.name, color: bot.color } } : {});const spendWrite = (turn: Turn): string | null => {const spent = writes.get(turn.generation) ?? 0;@@ -127,7 +133,8 @@ export function createAppSettings(deps: AppSettingsDeps) {const bot = store.bot(turn.botId);if (!bot) return refuse(404, "This bot no longer exists.");if (entry.tier === "owner-only") return refuse(403, personOnly(entry.label, entry.where));- if (deps.guestDriven(turn.threadId) || deps.turnOwner(turn) === null) return refuse(403, "Settings change only in the owner's own conversation. This turn was not started by the owner here, so nothing changed; you may still read settings.");+ const notOwner = notOwners(turn);+ if (notOwner) return refuse(403, `Settings change only in the owner's own conversation, so nothing changed; you may still read settings. ${whyNotOwners(notOwner, placePath(entry.where))}`);if (entry.tier === "secret") {if (body.value !== undefined) return refuse(400, `Never send a key or token as a value. Call set on ${entry.id} with no value: a secure card asks the user for it, and you never see it.`);const budget = spendWrite(turn);@@ -186,7 +193,8 @@ export function createAppSettings(deps: AppSettingsDeps) {const card = SETTINGS_CARDS[body.card];const bot = store.bot(turn.botId);if (!bot) return refuse(404, "This bot no longer exists.");- if (deps.guestDriven(turn.threadId) || deps.turnOwner(turn) === null) return refuse(403, "A settings card shows only in the owner's own conversation, when they asked. This turn was not started by the owner here, so nothing was shown.");+ const notOwner = notOwners(turn);+ if (notOwner) return refuse(403, `A settings card shows only in the owner's own conversation, when they asked, so nothing was shown. ${whyNotOwners(notOwner, "Settings")}`);if (!deps.cards?.here(body.card)) return reply(200, { text: cardElsewhere(card) });if (deps.connectorThread(bot.id, turn.threadId)?.group) return reply(200, { text: cardNotInRoom(card) });const budget = spendWrite(turn);@@ -238,3 +246,22 @@ export function createAppSettings(deps: AppSettingsDeps) {},};}++type NotOwners = TurnOwnerRefusal | "guest" | "unknown";++/** Why a turn is not the owner's own, and what the person can do instead, in words the bot can pass on. */+export function whyNotOwners(why: NotOwners, where: string): string {+ const themselves = `The person can change it themselves in ${where}.`;+ const fresh = "Or they ask again in a new conversation with this bot that only they write in.";+ switch (why) {+ case "shared": return `Several people share this server, so bots never change its settings. ${themselves}`;+ case "service": return `This server is set up as a shared or hosted server, so bots never change its settings. ${themselves}`;+ case "guest": return `A guest writes in this conversation, so it is not the owner's own. ${themselves}`;+ case "someone-else": return `Someone else wrote or answered in this conversation, or a bot opened it, so asking again here won't work. ${themselves} ${fresh}`;+ case "not-owner": return `This turn was started by someone other than the owner, or by a routine, webhook or app the owner didn't write. ${themselves} ${fresh}`;+ case "memory-changed":+ case "memory-changed-here": return `This bot's memory was changed in a conversation the owner didn't write. ${themselves} Or, in this bot's settings, they open Memory, check what changed, tap Mark reviewed and ask again.`;+ case "unproven":+ case "unknown": return `This turn can't be tied to a message the owner sent here (it was stopped, or started another way). ${themselves} Or they send the request again.`;+ }+}diff --git a/server/host/phones.test.ts b/server/host/phones.test.tsindex e4930a3175..013670f79b 100644--- a/server/host/phones.test.ts+++ b/server/host/phones.test.ts@@ -114,21 +114,25 @@ describe("whose phones", () => {expect(phones.fromPhone(loopback)).toBe(false);// No request this turn can prove: no phone.expect(phones.turnOwner(TURN)).toBeNull();+ expect(phones.turnOwnerRefusal(TURN)).toBe("unproven");send(phones.sendIdFor(loopback));expect(phones.turnOwner(TURN)).toBe("owner");+ expect(phones.turnOwnerRefusal(TURN)).toBeNull();expect(phones.integration(chief, TURN)).toMatchObject({ env: { OMB_MCP_TOKEN_DEVICE: "turn-token", OMB_HARNESS_URL: "http://127.0.0.1:1" } });// A line from a person who holds no admin session here is not the owner's, nor is anything after it.send("guest-send-0000000001", { origin: { kind: "user" } }, "p_guest");expect(phones.turnOwner(TURN)).toBeNull();+ expect(phones.turnOwnerRefusal(TURN)).not.toBeNull();expect(phones.integration(chief, TURN)).toBeNull();});it("a Team Cloud or hosted workspace, a server several people sign in to, and a service-trust machine get no phone", () => {- for (const overrides of [{ shared: true }, { sharedMembership: () => true }, { loopbackTrust: "service" as const }]) {+ for (const [overrides, why] of [[{ shared: true }, "shared"], [{ sharedMembership: () => true }, "shared"], [{ loopbackTrust: "service" as const }, "service"]] as const) {const { phones, send } = world(overrides);send(phones.sendIdFor(loopback));expect(phones.fromPhone(session(PHONE_SESSION))).toBe(true);expect(phones.turnOwner(TURN)).toBeNull();+ expect(phones.turnOwnerRefusal(TURN)).toBe(why);expect(phones.integration(chief, TURN)).toBeNull();expect(phones.previewParts(chief, true)).toEqual([]);expect(phones.promptParts(chief, { mounted: false, offered: true, turn: TURN, place: "computer" })).toEqual([{ id: "device", label: "Phone", text: "" }]);@@ -136,11 +140,12 @@ describe("whose phones", () => {});it("on a Cloud home only the owner's session holds a phone, and only a turn the lent Mac would allow reaches it", () => {- let refusal: string | null = null;+ let refusal: ReturnType<PhonesDeps["cloudLendingRefusal"]> = null;const { phones } = world({ cloudHome: true, cloudOwnerKey: "owner", cloudOwnerSession: (auth) => auth.kind === "session" && auth.session.id === PHONE_SESSION.id, cloudLendingRefusal: () => refusal });expect(phones.turnOwner(TURN)).toBe("owner");refusal = "someone-else";expect(phones.turnOwner(TURN)).toBeNull();+ expect(phones.turnOwnerRefusal(TURN)).toBe("someone-else");expect(phones.integration(chief, TURN)).toBeNull();});});diff --git a/server/host/phones.ts b/server/host/phones.tsindex 128a68e82d..b55361be4f 100644--- a/server/host/phones.ts+++ b/server/host/phones.ts@@ -4,7 +4,7 @@ import { randomUUID } from "node:crypto";import { existsSync } from "node:fs";import { join } from "node:path";-import { cloudHomeLendingRefusal, createCloudRoutineAuthors, type CloudLendingTurn } from "../cloud-lending.ts";+import { cloudHomeLendingRefusal, createCloudRoutineAuthors, type CloudLendingRefusal, type CloudLendingTurn } from "../cloud-lending.ts";import { personKey } from "../person-key.ts";import type { PhoneBot, PhonePlace } from "../phones/access.ts";import { createPhoneHost } from "../phones/host.ts";@@ -24,6 +24,9 @@ type Turn = { botId: string; threadId: string; generation: string };/** The owner of a desktop's phones: whoever works at this machine or holds an admin session. */const DESKTOP_OWNER = "owner";+/** Why a turn is not the owner's own: a server several people share, a service-trust machine, or the lent-computer verdict. */+export type TurnOwnerRefusal = "shared" | "service" | CloudLendingRefusal | "memory-changed" | "memory-changed-here";+export interface PhonesDeps {dataDir: string;/** A Team Cloud or a hosted workspace: several people share it, so no phone is anyone's. */@@ -39,7 +42,7 @@ export interface PhonesDeps {ownerOrAdmin(auth: RequestAuth): boolean;cloudOwnerSession(auth: RequestAuth): boolean;/** The lent-Mac test on a Cloud home: null when the turn may use the owner's things. */- cloudLendingRefusal(turn: Turn): string | null;+ cloudLendingRefusal(turn: Turn): CloudLendingRefusal | "memory-changed" | "memory-changed-here" | null;cloudLendingTurn(turn: Turn): CloudLendingTurn;/** The harness's record says this turn's work came from the user. */originIsUser(turn: Turn): boolean;@@ -81,9 +84,15 @@ export function createPhones(deps: PhonesDeps) {/** Whose phones a turn may use: on a Cloud home the owner's, when the lent Mac would allow the turn; elsewhere the desktop owner's. */function turnOwner(turn: Turn): string | null {- if (deps.shared) return null;- if (deps.cloudHome) return deps.cloudLendingRefusal(turn) === null ? deps.cloudOwnerKey : null;- if (!desktopPhones()) return null;+ if (turnOwnerRefusal(turn) !== null) return null;+ return deps.cloudHome ? deps.cloudOwnerKey : DESKTOP_OWNER;+ }++ /** Null when the turn is the owner's own (turnOwner); otherwise why not. */+ function turnOwnerRefusal(turn: Turn): TurnOwnerRefusal | null {+ if (deps.shared) return "shared";+ if (deps.cloudHome) return deps.cloudLendingRefusal(turn);+ if (!desktopPhones()) return deps.sharedMembership() ? "shared" : "service";const lending = desktopLendingTurn({ ...deps.cloudLendingTurn(turn), thread: store.messagesFor(turn.threadId) }, {adminPersons: () => new Set(deps.sessions.list().filter((session) => session.scopes.includes("admin")).map((session) => personKey(session))),originIsUser: () => deps.originIsUser(turn),@@ -92,7 +101,7 @@ export function createPhones(deps: PhonesDeps) {return Boolean(routine && routineAuthors?.authored(routine.id, routine));},});- return cloudHomeLendingRefusal(lending) === null ? DESKTOP_OWNER : null;+ return cloudHomeLendingRefusal(lending);}const fromPhone = (auth: RequestAuth): boolean => {@@ -118,6 +127,7 @@ export function createPhones(deps: PhonesDeps) {return sendId;},turnOwner,+ turnOwnerRefusal,/** Where the person is, from where the turn came from: the phone's send, the person at the computer, or nobody. */place(threadId: string, personAsked: boolean): PhonePlace {const request = deps.request(threadId);diff --git a/server/index.ts b/server/index.tsindex 2785c558d7..4b68ee56b1 100644--- a/server/index.ts+++ b/server/index.ts@@ -12278,7 +12278,7 @@ const instanceRoutes = createInstanceRoutes({providerConfigBusy: { get: () => providerConfigBusy, set: (busy) => { providerConfigBusy = busy; } },providerInstancesChanging, describeInstances, persistProviderInstance, configStatus, broadcast, testCliBinary,cliProbeEnvironment, threadBusy, botForThread, activeGroupTurnForBot, checkInstance: testedAi.check,-}); ROUTES.push(createCustomDomainRoutes({ desktopManaged: DESKTOP_MANAGED, status: customDomainStatus, verify: (domain) => customDomainVerifier.verify(domain), save: (origin) => { saveConfig({ customDomain: origin }); cfg.customDomain = origin; }, sessionEnded: (auth) => auth.kind === "session" && !sessions.isLive(auth.session.id) })); const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin, windowOpen: () => [...sseClients].some((client) => client.admin && client.appWindow) }); const themeStore = createThemeStore({ dataDir: DATA_DIR }); const themeChanged = (person: string, skin?: string) => broadcast({ kind: "theme", ...(skin ? { skin } : {}) }, CLOUD_TEAM ? { person } : { adminOnly: true }); ROUTES.push(createThemeRoutes({ store: themeStore, changed: themeChanged, person: (auth) => (CLOUD_TEAM ? (auth.kind === "session" ? personKey(auth.session) : null) : ownerOrAdmin(auth) ? "owner" : null) })); const themeTool = createThemeTool({ store: themeStore, changed: themeChanged, person: (turn) => (CLOUD_TEAM ? actingPeople.requester(turn.threadId, turn.generation) : phones.turnOwner(turn) ? "owner" : null), sources: (turn) => ({ roots: messageFileRootsForThread(turn.botId, turn.threadId).filter((root) => root !== ATTACHMENTS_DIR), attachments: store.messagesFor(turn.threadId).flatMap((message) => (message.attachments ?? []).flatMap((file) => (file.kind === "audio" ? [] : [file.path]))) }) }); const appSettings = createAppSettings({ themes: themeTool, cards: { here: (id) => id === "ai-sign-in" || DESKTOP_MANAGED, on: () => (tailnetShare.origin() !== null ? true : null) }, store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, botPatch: botPatchRoutes, sections: sidebarRoutes, instances: instanceRoutes, starterAwake: starterAwakeRoutes, skills: skillsRoutes }, providers: registry, credentials: () => botLogins.credentialConfig(cfg), window: windowPrefs, paused: () => starterAwake.paused() }), turnOwner: (turn) => phones.turnOwner(turn), guestDriven: cloudGuestDriven, automated: (turn) => { const request = directRequestOwners.get(turn.threadId); return Boolean(request?.automation) && (request!.generation === turn.generation || request!.generations.has(turn.generation)); }, requestCredential: (bot, threadId, body) => secretCards.requestCredential(bot, threadId, body), connectorThread, language: threadLanguage, pictures: createPictureFiles({ attachmentsDir: ATTACHMENTS_DIR, ownFolders: (turn) => messageFileRootsForThread(turn.botId, turn.threadId).filter((root) => root !== ATTACHMENTS_DIR), inConversation: (turn, name) => threadsReferencing(name).includes(turn.threadId), save: (bytes, mime) => saveImage(bytes, mime).path, remove: deleteAttachment }) }); ROUTES.push(instanceRoutes, windowPrefs.routes);+}); ROUTES.push(createCustomDomainRoutes({ desktopManaged: DESKTOP_MANAGED, status: customDomainStatus, verify: (domain) => customDomainVerifier.verify(domain), save: (origin) => { saveConfig({ customDomain: origin }); cfg.customDomain = origin; }, sessionEnded: (auth) => auth.kind === "session" && !sessions.isLive(auth.session.id) })); const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin, windowOpen: () => [...sseClients].some((client) => client.admin && client.appWindow) }); const themeStore = createThemeStore({ dataDir: DATA_DIR }); const themeChanged = (person: string, skin?: string) => broadcast({ kind: "theme", ...(skin ? { skin } : {}) }, CLOUD_TEAM ? { person } : { adminOnly: true }); ROUTES.push(createThemeRoutes({ store: themeStore, changed: themeChanged, person: (auth) => (CLOUD_TEAM ? (auth.kind === "session" ? personKey(auth.session) : null) : ownerOrAdmin(auth) ? "owner" : null) })); const themeTool = createThemeTool({ store: themeStore, changed: themeChanged, person: (turn) => (CLOUD_TEAM ? actingPeople.requester(turn.threadId, turn.generation) : phones.turnOwner(turn) ? "owner" : null), sources: (turn) => ({ roots: messageFileRootsForThread(turn.botId, turn.threadId).filter((root) => root !== ATTACHMENTS_DIR), attachments: store.messagesFor(turn.threadId).flatMap((message) => (message.attachments ?? []).flatMap((file) => (file.kind === "audio" ? [] : [file.path]))) }) }); const appSettings = createAppSettings({ themes: themeTool, cards: { here: (id) => id === "ai-sign-in" || DESKTOP_MANAGED, on: () => (tailnetShare.origin() !== null ? true : null) }, store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, botPatch: botPatchRoutes, sections: sidebarRoutes, instances: instanceRoutes, starterAwake: starterAwakeRoutes, skills: skillsRoutes }, providers: registry, credentials: () => botLogins.credentialConfig(cfg), window: windowPrefs, paused: () => starterAwake.paused() }), turnOwner: (turn) => phones.turnOwner(turn), ownerRefusal: (turn) => phones.turnOwnerRefusal(turn), guestDriven: cloudGuestDriven, automated: (turn) => { const request = directRequestOwners.get(turn.threadId); return Boolean(request?.automation) && (request!.generation === turn.generation || request!.generations.has(turn.generation)); }, requestCredential: (bot, threadId, body) => secretCards.requestCredential(bot, threadId, body), connectorThread, language: threadLanguage, pictures: createPictureFiles({ attachmentsDir: ATTACHMENTS_DIR, ownFolders: (turn) => messageFileRootsForThread(turn.botId, turn.threadId).filter((root) => root !== ATTACHMENTS_DIR), inConversation: (turn, name) => threadsReferencing(name).includes(turn.threadId), save: (bytes, mime) => saveImage(bytes, mime).path, remove: deleteAttachment }) }); ROUTES.push(instanceRoutes, windowPrefs.routes);ROUTES.push(createMcpServerRoutes({cfg, bot: (id) => store.bot(id), sessions, mcpOAuth, teamConnections,cloudHome: CLOUD_HOME,