Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
app_settings: wire the tool into the server
aivsomkara7571ddfd4a7
diff --git a/docs/superpowers/specs/2026-11-12-app-settings-tool-design.md b/docs/superpowers/specs/2026-11-12-app-settings-tool-design.mdindex 81cb76eea0..bad52aea8a 100644--- a/docs/superpowers/specs/2026-11-12-app-settings-tool-design.md+++ b/docs/superpowers/specs/2026-11-12-app-settings-tool-design.md@@ -26,12 +26,16 @@ interface SettingEntry<V> {synonyms?: string[]; // for findtier: SettingTier;value?: z.ZodType<V>; // absent for secret and owner-only- read(ctx): Display; // never returns a secret; keys read as "set" | "not set"- write?(ctx, value: V): Promise<void>; // absent for secret and owner-only+ read(): string; // display; never a secret: a key reads as "set" or empty (unset)+ current?(): V; // the typed value as write takes it, kept in server memory for Undo+ write?(value: V): Promise<string | null>; // a refusal, or null; absent for secret and owner-only}```-The tier is the whole policy. Handlers branch on the tier, never on the id.+The tier is the whole policy. Handlers branch on the tier, never on the id. As built (`server/app-settings/registry.ts`)+the entry is a discriminated union on `tier`, so a `safe` or `confirm` entry must carry `value`, `current` and `write`,+a `secret` entry carries only its `credentialId`, and an `owner-only` entry carries neither. Entries close over the+registry's deps instead of taking a `ctx`.| Tier | Behaviour | Examples ||---|---|---|@@ -86,3 +90,30 @@ Skin, Simple mode, font, chat width, send key and notification sounds live in th## Out of scopeRemote access, Cloud, Vault and backup writes. Adding or removing engine instances. Phone-side Undo for the applied card if phones do not already draw it (follow-up in mausbot-mobile).++## As built (2026-11-12)++Deviations from the design above, each chosen as the safer or simpler option:++- **Undo keeps the typed earlier value in server memory**, keyed by the card's request id, not on the card. The card carries+ display strings only, as designed; a display string cannot be parsed back into a number, an id list or the groups map.+ After a server restart an older applied card's Undo answers "This change can't be undone here."+- **A confirm write runs when the owner taps Change**, inside the card's answer route, so a refused write (the config+ route's 4xx) is shown to the person on the tap and reaches the bot through the hold. The hold carries applied, failed,+ cancelled or timed out to the waiting tool call.+- **Secret entries are derived from `CREDENTIAL_TARGETS`** as `keys.<credentialId>` (19 entries), so a new credential card+ target is a setting with no further registration.+- **`where` strings live in the registry.** `src/components/settings/settings-index.ts` imports lucide icons and the+ renderer's locale types, so it is not imported server-side.+- **Window preferences count as reachable once any window has reported** (`PUT /api/window-prefs`), which every setter+ does at start-up and on each change. There is no window-closed signal; a closed window leaves the last report in place+ until the server restarts.+- **The write budget counts accepted sets** (a safe or confirm write, or a secret card request). A set refused by+ validation, the tier or the turn does not spend it.+- **A groups write leaves an emptied group in place** rather than deleting it; the group's own delete rules+ (`serverError.department.*`) stay with the sidebar.+- **Stop does not close an open "Change X?" card**; it times out after 9 minutes like the outbound card.+- **The tool is in every profile** and is not a bridge hot tool: on the bridged list it is reached through `find_tool`.+- **Writes use the Settings window's own routes** (`PUT /api/config`, `PUT /api/bots/order`, `POST /api/sidebar-sections`)+ through `server/routes/call-route.ts`, so provider reloads, broadcasts and refusals are the Settings window's. On a+ shared-membership server (a Team Cloud) `turnOwner` is null for every turn, so no write happens there.diff --git a/server/app-settings/host.ts b/server/app-settings/host.tsindex 4a0df742ff..5de33f49fe 100644--- a/server/app-settings/host.ts+++ b/server/app-settings/host.ts@@ -17,13 +17,10 @@ import { turnWaitedOnPerson } from "../waiting-on-person.ts";import { display, findSettings, type SettingEntry, type WritableEntry } from "./registry.ts";export const TOOL = "app_settings";-/** How long a "Change X?" card waits on the person. */export const APP_SETTINGS_HOLD_MS = 9 * 60_000;-/** Writes one turn (generation) may make. */export const WRITE_BUDGET = 10;const FIND_LIMIT = 8;const NOT_RETRY = "Do not retry it; ask the user what they would like instead.";-/** What the bot reads for an unset value. */const NOT_SET = "not set";const text = (value: string) => value || NOT_SET;@@ -193,7 +190,6 @@ export function createAppSettings(deps: AppSettingsDeps) {}return {- /** POST /api/internal/app-settings. */async handle(body: Record<string, unknown>, turn: Turn): Promise<{ status: number; body: Record<string, unknown> }> {if (body.action === "find") {const query = typeof body.query === "string" ? body.query : "";diff --git a/server/app-settings/registry.ts b/server/app-settings/registry.tsindex 075ba8a675..dca115e16d 100644--- a/server/app-settings/registry.ts+++ b/server/app-settings/registry.ts@@ -4,7 +4,10 @@ import { credentialIsConfigured, CREDENTIAL_TARGETS, PROVIDER_CREDENTIAL_TARGETSimport { WINDOW_PREFS, type WindowPrefId } from "../../shared/app-settings.ts";import { MAX_CONCURRENT_BOT_THREADS } from "../bot-thread-limits.ts";import { MAX_MCP_CALL_TIMEOUT_MINUTES, MAX_ROOM_TURN_TIMEOUT_MINUTES, MIN_MCP_CALL_TIMEOUT_MINUTES, MIN_ROOM_TURN_TIMEOUT_MINUTES, type AppConfig } from "../config.ts";-import type { BotRecord } from "../store.ts";+import type { RequestAuth } from "../request-auth.ts";+import { callRoute, type RouteReply } from "../routes/call-route.ts";+import type { RouteHandler } from "../routes/table.ts";+import type { BotRecord, Store } from "../store.ts";/** Where the person changes it by hand, as the bot tells them. */type Where = "Settings → Appearance" | "Settings → General" | "Settings → AI" | "Settings → AI → API keys" | "Settings → You and your bots"@@ -179,7 +182,6 @@ export function createSettingsRegistry(deps: RegistryDeps): SettingEntry[] {return [...safe, ...confirm, ...secret, ...owner];}-/** Up to `limit` entries whose id, label, help or synonyms carry a word of the query, best first. */export function findSettings(entries: readonly SettingEntry[], query: string, limit = 8): SettingEntry[] {const words = query.toLowerCase().split(/[^a-z0-9.-]+/).filter((word) => word.length > 1);if (!words.length) return [];@@ -194,3 +196,21 @@ export function findSettings(entries: readonly SettingEntry[], query: string, li}).filter((hit) => hit.score > 0).sort((a, b) => b.score - a.score);return scored.slice(0, limit).map((hit) => hit.entry);}++/** The registry over the Settings window's own routes, called as the window calls them. */+export function routeBackedRegistry(deps: {+ cfg(): AppConfig;+ store: Pick<Store, "bots" | "sections">;+ routes: { config: RouteHandler; botOrder: RouteHandler; sections: RouteHandler };+ credentials(): CredentialConfig;+ window: RegistryDeps["window"];+}): SettingEntry[] {+ const auth: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };+ const refusal = async (reply: Promise<RouteReply>) => { const { status, body } = await reply; return status < 300 ? null : String(body.error ?? `HTTP ${status}`); };+ return createSettingsRegistry({+ cfg: deps.cfg, bots: () => deps.store.bots, sections: () => deps.store.sections, credentials: deps.credentials, window: deps.window,+ saveConfig: (patch) => refusal(callRoute(deps.routes.config, { method: "PUT", path: "/api/config", body: patch, auth })),+ reorderBots: (botIds) => refusal(callRoute(deps.routes.botOrder, { method: "PUT", path: "/api/bots/order", body: { botIds }, auth })),+ groupBots: (name, botIds) => refusal(callRoute(deps.routes.sections, { method: "POST", path: "/api/sidebar-sections", body: { name, botIds }, auth })),+ });+}diff --git a/server/drivers/agents-proxy.test.ts b/server/drivers/agents-proxy.test.tsindex 56a7e447b2..1c8749db7c 100644--- a/server/drivers/agents-proxy.test.ts+++ b/server/drivers/agents-proxy.test.ts@@ -685,6 +685,7 @@ describe("agents-proxy MCP surface", () => {"skills_list","skill_manage","mcp_server",+ "app_settings",]);const tool = (name: string) => list.result.tools.find((entry: { name: string }) => entry.name === name);const coordinate = tool("coordinate_bots");diff --git a/server/host/trust-answers.ts b/server/host/trust-answers.tsnew file mode 100644index 0000000000..04361d39ef--- /dev/null+++ b/server/host/trust-answers.ts@@ -0,0 +1,64 @@+import type { ServerResponse } from "node:http";++import { appendDecision } from "../decision-log.ts";+import { json } from "../harness/http.ts";+import type { OutboundRequestService } from "../outbound-requests.ts";+import type { Store } from "../store.ts";++/** A proposal a person answers on a card, settled by its own service. */+interface Remembered {+ resolve(threadId: string, requestId: string, behavior: string): { ok: true; outcome: string; alreadySettled?: true } | null;+}++export interface TrustAnswerDeps {+ store: Pick<Store, "messagesFor" | "bot" | "botByThread" | "patchMessage">;+ dataDir: string;+ teamMemoryRequests: Remembered;+ outsideWrites: Remembered;+ outboundRequests: OutboundRequestService;+}++/** The person's answer to a team-memory, outside-write or "Send on your behalf?" card. */+export function createTrustAnswers(deps: TrustAnswerDeps) {+ const { store, teamMemoryRequests, outsideWrites, outboundRequests } = deps;+ const DATA_DIR = deps.dataDir;++ function resolveAndSendTrust(res: ServerResponse, threadId: string, requestId: string, behavior: "allow" | "deny" | "answer"): boolean {+ const remembered = teamMemoryRequests.resolve(threadId, requestId, behavior) ?? outsideWrites.resolve(threadId, requestId, behavior);+ if (remembered) {+ json(res, 200, remembered);+ return true;+ }+ const outboundCard = store.messagesFor(threadId).find(+ (message) => message.card?.requestId === requestId && message.card.outboundRequest,+ );+ if (outboundCard?.card?.outboundRequest) {+ const outboundBot = outboundCard.from?.botId ? store.bot(outboundCard.from.botId) : store.botByThread(threadId);+ const result = outboundRequests.resolve({ threadId, requestId, behavior });+ if (!result.claimed) {+ if (!outboundCard.card.answered) {+ store.patchMessage(threadId, outboundCard.id, { card: { ...outboundCard.card, answered: "unavailable", dismissed: true } });+ }+ json(res, 200, { ok: true, outcome: "unavailable" });+ return true;+ }+ if (result.state === "already_settled") {+ json(res, 200, { ok: true, outcome: result.behavior === "allow" ? "allowed-once" : "rejected", alreadySettled: true });+ return true;+ }+ store.patchMessage(threadId, outboundCard.id, {+ card: { ...outboundCard.card, answered: result.state === "allowed" ? "allow" : "deny" },+ });+ appendDecision(DATA_DIR, {+ threadId, requestId, botId: outboundBot?.id, botName: outboundBot?.name,+ tool: outboundCard.card.tool, summary: outboundCard.card.subtitle,+ decision: result.state === "allowed" ? "user-approved" : "user-denied", source: "user",+ });+ json(res, 200, { ok: true, outcome: result.state === "allowed" ? "allowed-once" : "rejected" });+ return true;+ }+ return false;+ }++ return { resolveAndSendTrust };+}diff --git a/server/index.ts b/server/index.tsindex f8906fd387..fb730cc973 100644--- a/server/index.ts+++ b/server/index.ts@@ -597,6 +597,10 @@ import { createUpdateCheckRoutes, updateRouteDeps } from "./routes/update-check.import { createBrowserSiteRoutes } from "./routes/browser-sites.ts";import { createInternalSignInRoutes } from "./routes/sign-in.ts";import { createInternalMcpRoutes } from "./routes/internal-mcp.ts";+import { createInternalAppSettingsRoutes, createWindowPrefs } from "./routes/app-settings.ts";+import { createAppSettings } from "./app-settings/host.ts";+import { routeBackedRegistry } from "./app-settings/registry.ts";+import { createTrustAnswers } from "./host/trust-answers.ts";import { createInternalThreadRoutes } from "./routes/internal-threads.ts";import { createBrowserEvidenceRoutes } from "./routes/browser-evidence.ts";import { createSignInCardRoutes } from "./routes/sign-in-cards.ts";@@ -9197,42 +9201,7 @@ const outsideWrites = createOutsideWrites({ store, notify, language: (threadId)const outboundRequests = new OutboundRequestService();const outboundHold = createOutboundHold({ store, dataDir: DATA_DIR, outboundRequests, holdMs: OUTBOUND_HOLD_MS, connectorThread, activeGroupTurnForBot, notify });-function resolveAndSendTrust(res: ServerResponse, threadId: string, requestId: string, behavior: "allow" | "deny" | "answer"): boolean {- const remembered = teamMemoryRequests.resolve(threadId, requestId, behavior) ?? outsideWrites.resolve(threadId, requestId, behavior);- if (remembered) {- json(res, 200, remembered);- return true;- }- const outboundCard = store.messagesFor(threadId).find(- (message) => message.card?.requestId === requestId && message.card.outboundRequest,- );- if (outboundCard?.card?.outboundRequest) {- const outboundBot = outboundCard.from?.botId ? store.bot(outboundCard.from.botId) : store.botByThread(threadId);- const result = outboundRequests.resolve({ threadId, requestId, behavior });- if (!result.claimed) {- if (!outboundCard.card.answered) {- store.patchMessage(threadId, outboundCard.id, { card: { ...outboundCard.card, answered: "unavailable", dismissed: true } });- }- json(res, 200, { ok: true, outcome: "unavailable" });- return true;- }- if (result.state === "already_settled") {- json(res, 200, { ok: true, outcome: result.behavior === "allow" ? "allowed-once" : "rejected", alreadySettled: true });- return true;- }- store.patchMessage(threadId, outboundCard.id, {- card: { ...outboundCard.card, answered: result.state === "allowed" ? "allow" : "deny" },- });- appendDecision(DATA_DIR, {- threadId, requestId, botId: outboundBot?.id, botName: outboundBot?.name,- tool: outboundCard.card.tool, summary: outboundCard.card.subtitle,- decision: result.state === "allowed" ? "user-approved" : "user-denied", source: "user",- });- json(res, 200, { ok: true, outcome: result.state === "allowed" ? "allowed-once" : "rejected" });- return true;- }- return false;-}+const { resolveAndSendTrust } = createTrustAnswers({ store, dataDir: DATA_DIR, teamMemoryRequests, outsideWrites, outboundRequests });const profileRequests = new ProfileRequestService({store,@@ -9472,7 +9441,7 @@ async function undoAppliedChange(res: ServerResponse, threadId: string, requestIresult = teamMemoryRequests.undo(threadId, requestId);} else if (card.teamSetupRequest) {result = await teamSetupRequests.undo({ botId, threadId, requestId });- }+ } else if (card.appSettingRequest) { result = await appSettings.undo({ threadId, requestId }); }if (!result.claimed) return json(res, 409, { error: "Only a change that applied on its own can be undone here." });if (result.state === "invalid") {return json(res, result.status, { error: result.error, ...userErrorFields(result), ...(result.stale ? { code: "changed-since" } : {}) });@@ -12100,7 +12069,7 @@ ROUTES.push(createBotMessageRoutes({acceptDirectSend, directSendRefusal, startTurn, usageTriggerFor, messageSender, cloudGuestSendRefusal, cloudThreadRefusal, runOwners, runActor, resolveAccessRequest: (threadId, requestId, behavior, message) => lendingLifts?.resolve(threadId, requestId, behavior) ?? accessRequests.resolve(threadId, requestId, behavior, message), relayRefusal: CLOUD_TEAM ? (bot, email) => relayedSendRefusal(bot, email, Boolean(email && teamOwners.people?.list().some((one) => one.email === email && one.role !== "member"))) : undefined,noAiRefusal: noAiNotice.refusal, cardAnswerRefusal, commandRememberRefusal, requestBehavior, requestedTaskBot, botForThread, threadBusy,botAtThreadCapacity, parksBehindCoordination, activeGroupTurnForBot, runningTurnInstance, engineSteersImages, resolveReplyTarget,- turnSelection, policyModelRefusal, clearUnattended, drainQueuedSends, answeringCardAs, resolveAndSendTrust, resolveAndSendTeamSetup, resolveAndSendMcp,+ turnSelection, policyModelRefusal, clearUnattended, drainQueuedSends, answeringCardAs, resolveAndSendTrust, resolveAndSendTeamSetup, resolveAndSendMcp, resolveAndSendAppSettings: (res, args, review) => appSettings.resolveAndSend(res, args, review),resolveAndSendRoutine, resolveAndSendProfile, resolveAndSendModel, resolveSkillRequest, sendSkillResolution, answerRequest,deliverLateQuestionAnswer, stopThreadForPerson, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread,cancelGroupTurnOperations, closeOpenApprovals, harnessCardOutcome, answeredIn: (threadId, requestId) => automationReports.answeredIn(teamMessages.inbox.answeredIn(threadId, requestId), requestId), pressRecords: proactive.brief.pressRecords, serverPress: (bot, threadId, messageId, action, auth) => meetingsHost.serverPress(bot, threadId, messageId, action, auth) ?? proactive.brief.serverPress(bot, threadId, messageId, action, auth),@@ -12149,7 +12118,7 @@ ROUTES.push(createBotSettingsRoutes({requestedTaskBot, threadBusy, activeGroupTurnForBot, checkedModelSelection, engineSwitchNeedsAsk, readCursor,canManageCommandAllowlist, commandAllowlistResponse, cardAnswerRefusal, threadRead: teamMessages.seen, levelOf, personMarkThread: personRooms.personMarkThread,}));-ROUTES.push(createBotOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(botOrders ? { own: { person: botOrders.personOf, order: botOrders, told: (person, botIds) => broadcast({ kind: "bots.order", botIds }, { person }) } } : {}) }), createBotAccessRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, levelOf, wireBot, publicGroupState, broadcast, audienceChanged, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), shared: createShareNotice({ people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, store: () => store, inbox: () => teamMessages.inbox }) }), accessRequests.routes);+const botOrderRoutes = createBotOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(botOrders ? { own: { person: botOrders.personOf, order: botOrders, told: (person, botIds) => broadcast({ kind: "bots.order", botIds }, { person }) } } : {}) }); ROUTES.push(botOrderRoutes, createBotAccessRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, levelOf, wireBot, publicGroupState, broadcast, audienceChanged, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), shared: createShareNotice({ people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, store: () => store, inbox: () => teamMessages.inbox }) }), accessRequests.routes);ROUTES.push(createBotPatchRoutes({store, cfg, registry, sessions, browserRuntime, browserLive, memoryUpkeep, cacheKeepWarm, hostedModels, supportsApprovalMode,routines: () => routines, activeVpsThreads,@@ -12201,7 +12170,7 @@ ROUTES.push(createBotMemoryRoutes({}));const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages)); const conversationSharing = createConversationSharing({ team: CLOUD_TEAM, store: () => store, shares: conversationShares, saves: createTeamMemorySaves({ dataDir: DATA_DIR }), starter: (threadId) => threadStarters.get(threadId), audienceOf: teamHost.audienceOf, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), levelOf, levelFor: (person, botId) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }).level(botId), people: () => teamOwners.people?.list() ?? [], nameOf: (email) => teamHost.personName(personKey({ id: "", email })) ?? email, language: (person) => personLanguages.forLine(person), busy: threadBusy, routinesIn: (threadId) => (routines?.listRoutines() ?? []).filter((routine) => routine.sourceThreadId === threadId || routine.resultsThreadId === threadId).length, outside: cloudGuestDriven, audienceChanged: (botId, threadId) => { store.patchTask(botId, threadId, { rewound: true, resumeCursors: {} }); }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, inbox: () => teamMessages.inbox, looking: (email, threadId) => teamPresence.looking(email, threadId), notify, botOf: (threadId) => store.botByThread(threadId)?.id, handTo: (threadId, person) => threadStarters.handTo(threadId, person) }); ROUTES.push(conversationSharing.routes);if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));-ROUTES.push(teamPresence.routes, createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),+const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: () => composio.connectedServices(cfg), offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));ROUTES.push(createRoomHoldRoutes({group: (id) => store.group(id),@@ -12368,7 +12337,7 @@ const mcpConfig = createMcpConfig({connectionsChanged: (change) => void routineHolds?.connections(change), probeAs: mcpServersHost.probeAs, testElsewhere: (name, server, lender, signal) => lentMcp.test(name, server, lender, signal),changed: () => broadcast({ kind: "mcp.changed" }) });const persistAnnouncedMcpServers = (next: Record<string, unknown>) => { persistMcpServers(next); broadcast({ kind: "mcp.changed" }); };-const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persistAnnouncedMcpServers, mcpConfigBusy: mcpConfig.busy, mcpPolicyRefusal, appCatalog: chatAppsMcp, team: teamConnections, loopback: !CLOUD_HOME && !HOSTED_WORKSPACE }); ROUTES.push(createPostizRoutes({ postiz }), createConfigRoutes({+const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persistAnnouncedMcpServers, mcpConfigBusy: mcpConfig.busy, mcpPolicyRefusal, appCatalog: chatAppsMcp, team: teamConnections, loopback: !CLOUD_HOME && !HOSTED_WORKSPACE }); const configRoutes = createConfigRoutes({store, cfg, registry, sessions, browserCleanup, browserLive, browserRuntime, usedBrowserSessions, decider,sharedComputers, sharedComputerControl, closeBrowser, browserEngineSwitched,hostedModels: Boolean(hostedModels),@@ -12382,7 +12351,8 @@ const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persiconfigForAccess: (status, auth) => configForAccess(status as ReturnType<typeof configStatus>, auth.scopes.includes("admin"), auth.kind === "session" ? auth.session : null),...(CLOUD_TEAM ? { ownProfile: (auth: RequestAuth, profile: { name?: string; avatarUrl?: string; aboutMe?: string }) => auth.kind === "session" ? (teamHost.saveMemberProfile(auth.session, profile), true) : false, ownHints: (auth: RequestAuth, hints: string[]) => auth.kind === "session" ? (teamWelcome.save(personKey(auth.session), { hints }), true) : false } : {}),resyncOpenCodeProviderKeys, revokeEngineCapabilities, reloadProviders, broadcast, drainQueuedSends, postiz,-}));+}); ROUTES.push(createPostizRoutes({ postiz }), configRoutes);+const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin }); const appSettings = createAppSettings({ store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, sections: sidebarRoutes }, credentials: () => botLogins.credentialConfig(cfg), window: windowPrefs }), turnOwner: (turn) => phones.turnOwner(turn), guestDriven: cloudGuestDriven, requestCredential: (bot, threadId, body) => secretCards.requestCredential(bot, threadId, body), connectorThread, activeGroupTurnForBot, notify, language: threadLanguage }); ROUTES.push(windowPrefs.routes);ROUTES.push(createInstanceRoutes({store, cfg, registry, sessions, providerAuthSessions,hostedModels: Boolean(hostedModels),@@ -14325,7 +14295,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}if (await dispatchRoutes([createInternalMcpRoutes({...mcpServerDeps(internalSender, internalCapability.threadId, internalCapability.generation), readBody: readInternalBody,- })], { req, res, url, path, method, auth, json, readBody })) return;+ }), createInternalAppSettingsRoutes({ readBody: readInternalBody, handle: (body) => appSettings.handle(body, internalCapability) })], { req, res, url, path, method, auth, json, readBody })) return;if (await dispatchRoutes([createInternalCredentialRequestRoutes({ readBody: readInternalBody, request: (body) => secretCards.requestCredential(internalSender, internalCapability.threadId, body) })], { req, res, url, path, method, auth, json, readBody })) return;if (await dispatchRoutes([createInternalSignInRoutes({readBody: readInternalBody,diff --git a/server/routes/app-settings.test.ts b/server/routes/app-settings.test.tsnew file mode 100644index 0000000000..0325067ce1--- /dev/null+++ b/server/routes/app-settings.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";++import type { RequestAuth } from "../request-auth.ts";+import { createWindowPrefs } from "./app-settings.ts";+import { callRoute } from "./call-route.ts";++const owner: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };+const phone: RequestAuth = { kind: "loopback", scopes: ["client"] };++describe("window preferences on the server", () => {+ it("keeps what an owner's window reports, drops what the schema refuses, and pushes a change as a frame", async () => {+ const frames: Record<string, unknown>[] = [];+ const prefs = createWindowPrefs({ broadcast: (frame) => frames.push(frame), ownerOrAdmin: (auth) => auth.scopes.includes("admin") });+ expect(prefs.write("appearance.skin", "midnight")).toContain("Open MausBot on this computer first");+ expect(await callRoute(prefs.routes, { method: "PUT", path: "/api/window-prefs", body: { values: { "appearance.skin": "daylight" } }, auth: phone })).toMatchObject({ status: 403 });+ expect(await callRoute(prefs.routes, { method: "PUT", path: "/api/window-prefs", body: { values: { "appearance.skin": "daylight", "appearance.font": "comic", "nope": 1 } }, auth: owner })).toMatchObject({ status: 200 });+ expect(prefs.read("appearance.skin")).toBe("daylight");+ expect(prefs.read("appearance.font")).toBeUndefined();+ expect(prefs.write("appearance.skin", "midnight")).toBeNull();+ expect(prefs.read("appearance.skin")).toBe("midnight");+ expect(frames).toEqual([{ kind: "window-pref", id: "appearance.skin", value: "midnight" }]);+ });+});diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 579a5959c3..27ccfdf249 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -100,6 +100,8 @@ export interface BotMessageRouteDeps {resolveAndSendTrust(res: ServerResponse, threadId: string, requestId: string, behavior: Behavior): boolean;resolveAndSendTeamSetup(res: ServerResponse, args: { botId: string; threadId: string; requestId: string; behavior: string }, ownerReview: boolean): Promise<boolean>;resolveAndSendMcp(res: ServerResponse, args: { botId: string; threadId: string; requestId: string; behavior: string }, ownerReview: boolean): Promise<boolean>;+ /** A "Change X?" card for an app setting; Allow counts only with ownerReview. */+ resolveAndSendAppSettings?(res: ServerResponse, args: { threadId: string; requestId: string; behavior: string }, ownerReview: boolean): boolean;resolveAndSendRoutine(res: ServerResponse, args: CardAnswer): boolean;resolveAndSendProfile(res: ServerResponse, args: CardAnswer): boolean;resolveAndSendModel(res: ServerResponse, args: CardAnswer): boolean;@@ -588,6 +590,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerconst answer = { botId: bot.id, threadId: bot.threadId, requestId: String(body.requestId), behavior };if (await resolveAndSendTeamSetup(res, answer, ownerReview(auth, req))) return;if (await resolveAndSendMcp(res, answer, ownerReview(auth, req))) return;+ if (deps.resolveAndSendAppSettings?.(res, answer, ownerReview(auth, req))) return;if (resolveAndSendRoutine(res, {botId: bot.id,botName: bot.name,@@ -700,6 +703,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerif (!mcpBotId) return json(res, 400, { error: "This MCP server card has no valid owner" });if (await resolveAndSendMcp(res, { botId: mcpBotId, threadId, requestId, behavior }, ownerReview(auth, req))) return;}+ if (deps.resolveAndSendAppSettings?.(res, { threadId, requestId, behavior }, ownerReview(auth, req))) return;const profileCard = store.messagesFor(threadId).find((message) => message.card?.requestId === requestId && message.card.profileRequest,);diff --git a/src/lib/window-prefs.test.ts b/src/lib/window-prefs.test.tsnew file mode 100644index 0000000000..ab2cbc97bf--- /dev/null+++ b/src/lib/window-prefs.test.ts@@ -0,0 +1,39 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { applyWindowPref, reportWindowPrefs, windowPrefValues } from "./window-prefs";++const values = new Map<string, string>();+beforeEach(() => {+ values.clear();+ vi.stubGlobal("window", {});+ vi.stubGlobal("localStorage", { getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); }, removeItem: (key: string) => { values.delete(key); } });+});+afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe("window preferences", () => {+ it("applies a frame with the preference's setter and ignores a value the schema refuses", () => {+ applyWindowPref({ kind: "window-pref", id: "general.sendKey", value: "mod-enter" });+ expect(values.get("omb-send-key")).toBe("mod-enter");+ applyWindowPref({ kind: "window-pref", id: "general.sendKey", value: "space" });+ expect(values.get("omb-send-key")).toBe("mod-enter");+ applyWindowPref({ kind: "window-pref", id: "general.notificationSounds", value: false });+ expect(windowPrefValues()).toMatchObject({ "general.sendKey": "mod-enter", "general.notificationSounds": false });+ });++ it("reports the window's values once after a burst of setters", async () => {+ vi.useFakeTimers();+ const fetched = vi.fn(async () => new Response("{}"));+ vi.stubGlobal("fetch", fetched);+ applyWindowPref({ kind: "window-pref", id: "general.sendKey", value: "shift-enter" });+ reportWindowPrefs();+ reportWindowPrefs();+ await vi.advanceTimersByTimeAsync(250);+ expect(fetched).toHaveBeenCalledTimes(1);+ const [url, init] = fetched.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe("/api/window-prefs");+ expect(JSON.parse(String(init.body)).values).toMatchObject({ "general.sendKey": "shift-enter" });+ });+});diff --git a/src/lib/window-prefs.ts b/src/lib/window-prefs.tsindex 84cd222a12..3275998062 100644--- a/src/lib/window-prefs.ts+++ b/src/lib/window-prefs.ts@@ -8,8 +8,7 @@ import { notificationSoundsEnabled, setNotificationSounds } from "./notificationimport { readSendKey, setSendKey } from "./send-key";import { applySkinChoice, readSkinChoice } from "./skins";-type Pref<I extends WindowPrefId> = { read(): unknown; write(value: ReturnType<(typeof WINDOW_PREFS)[I]["parse"]>): void };-const PREFS: { [I in WindowPrefId]: Pref<I> } = {+const PREFS: Record<WindowPrefId, { read(): unknown; write(value: never): void }> = {"appearance.skin": { read: readSkinChoice, write: applySkinChoice },"appearance.advanced": { read: readAdvancedMode, write: setAdvancedMode },"appearance.font": { read: readFont, write: applyFont },@@ -22,7 +21,7 @@ export function applyWindowPref(frame: WindowPrefFrame): void {const schema = WINDOW_PREFS[frame.id];const parsed = schema?.safeParse(frame.value);if (!parsed?.success) return;- (PREFS[frame.id] as Pref<typeof frame.id>).write(parsed.data as never);+ PREFS[frame.id].write(parsed.data as never);}export function windowPrefValues(): Record<WindowPrefId, unknown> {