Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
app_settings: bots pin and unpin bots
aivsomkar1d5360d3c027
diff --git a/server/app-settings.e2e.test.ts b/server/app-settings.e2e.test.tsindex fec886ae41..d0c37f469f 100644--- a/server/app-settings.e2e.test.ts+++ b/server/app-settings.e2e.test.ts@@ -233,6 +233,17 @@ it("an owner-only setting is refused with where to change it", async () => {text: "Approval modes is changed only by the owner, in a bot's Settings. Tell the user where to find it; do not try another way." })]);}, 60_000);+it("pinning a bot goes through the sidebar's own bot route, and Undo unpins it", async () => {+ const pinnedNow = async () => (await api("GET", "/api/bots")).bots.find((one: any) => one.id === bot.id)?.pinned === true;+ expect(await pinnedNow()).toBe(false);+ await start("PIN-1", [step({ action: "set", id: "bots.pinned", value: JSON.stringify([bot.id]) })]);+ expect(results(await finished("PIN-1"))[0]).toMatchObject({ isError: false, text: expect.stringMatching(/^Changed Pinned bots from not set to /) });+ expect(await pinnedNow()).toBe(true);+ const card = (await settingCards(bot.threadId)).find((one) => one.card.appSettingRequest.settingId === "bots.pinned");+ expect(await api("POST", `/api/threads/${bot.threadId}/undo`, { requestId: card.card.requestId })).toMatchObject({ ok: true, undone: true });+ expect(await pinnedNow()).toBe(false);+}, 60_000);+it("a window preference changes only while the app window's stream is open: refused with none, applied once one connects, refused after it closes, applied again on reconnect", async () => {const openWindow = async () => {const closed = new AbortController();diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.tsindex ebfb9347ae..558d1e515c 100644--- a/server/app-settings/host.test.ts+++ b/server/app-settings/host.test.ts@@ -63,6 +63,7 @@ function fixture(options: { owner?: boolean; guest?: boolean; group?: boolean; wbots: () => bots,sections: () => ["Sales"],reorderBots: async (botIds) => { bots.sort((a, b) => botIds.indexOf(a.id) - botIds.indexOf(b.id)); return null; },+ pinBot: async (botId, pinned) => { (bots.find((bot) => bot.id === botId) as { pinned?: boolean }).pinned = pinned || undefined; return null; },groupBots: async (name, botIds) => { for (const bot of bots) if (botIds.includes(bot.id)) (bot as { section?: string }).section = name || undefined; return null; },credentials: () => cfg,window: {@@ -190,6 +191,19 @@ describe("safe tier", () => {expect(bots.map((bot) => bot.section)).toEqual(["Sales", undefined]);});+ it("pins and unpins bots from the full list sent, refuses an unknown id, and Undo restores the earlier pins", async () => {+ const { host, set, bots, cards, turn } = fixture();+ const pins = () => bots.filter((bot) => bot.pinned).map((bot) => bot.id);+ expect((await set("bots.pinned", JSON.stringify(["clive"]))).body.text).toMatch(/^Changed Pinned bots from not set to Clive\./);+ expect(pins()).toEqual(["clive"]);+ expect((await set("bots.pinned", ["kiwi"])).status).toBe(200);+ expect(pins()).toEqual(["kiwi"]);+ expect(await host.undo({ threadId: turn.threadId, requestId: String(cards()[1]!.card.requestId) })).toEqual({ claimed: true, state: "undone" });+ expect(pins()).toEqual(["clive"]);+ expect((await set("bots.pinned", ["ghost"])).body.error).toContain("No bot has the id ghost");+ expect(pins()).toEqual(["clive"]);+ });+it("a window preference refuses until a window has reported, then pushes the change", async () => {const closed = fixture({ window: false });const refused = await closed.set("appearance.skin", "midnight");diff --git a/server/app-settings/registry.ts b/server/app-settings/registry.tsindex 8b42c58649..484d512920 100644--- a/server/app-settings/registry.ts+++ b/server/app-settings/registry.ts@@ -60,6 +60,7 @@ export interface RegistryDeps {reorderBots(botIds: string[]): Promise<string | null>;/** Moves bots into a sidebar group, making it when new; an empty name ungroups them. */groupBots(name: string, botIds: string[]): Promise<string | null>;+ pinBot(botId: string, pinned: boolean): Promise<string | null>;credentials(): CredentialConfig;window: { read(id: WindowPrefId): unknown; write(id: WindowPrefId, value: unknown): string | null };/** The engines Settings → AI lists; never a key. */@@ -115,6 +116,7 @@ export function createSettingsRegistry(deps: RegistryDeps): SettingEntry[] {const windowPref = (id: WindowPrefId, label: string, help: string, where: Where, synonyms: string[], allowed: string): SettingEntry =>writable({ id, label, help, where, synonyms, tier: "safe", value: WINDOW_PREFS[id], allowed, current: () => deps.window.read(id), write: async (value: unknown) => deps.window.write(id, value) });const enumOf = (values: readonly string[]) => values.join(", ");+ const pinned = () => deps.bots().filter((bot) => bot.pinned).map((bot) => bot.id);const groups = () => Object.fromEntries(deps.sections().map((section) => [section, deps.bots().filter((bot) => bot.section === section).map((bot) => bot.id)]));const safe: SettingEntry[] = [@@ -134,6 +136,21 @@ export function createSettingsRegistry(deps: RegistryDeps): SettingEntry[] {synonyms: ["reorder", "sidebar order", "sort bots", "move bot", "arrange"], tier: "safe", value: z.array(z.string().regex(/^[\w-]+$/)).min(1).max(100), allowed: "an array of bot ids in the wanted order",current: () => deps.bots().map((bot) => bot.id), read: () => names(deps.bots().map((bot) => bot.id)), write: (botIds: string[]) => deps.reorderBots(botIds),}),+ writable({+ id: "bots.pinned", label: "Pinned bots", help: "Which bots are pinned to the top of the sidebar. Send every bot id that should be pinned, including ones already pinned; the rest are unpinned.", where: "the sidebar",+ synonyms: ["pin", "pinned", "unpin", "favorite", "favourite", "top", "star"], tier: "safe", value: z.array(z.string().regex(/^[\w-]+$/)).max(100), allowed: "an array of the bot ids to pin; an empty array unpins every bot",+ current: pinned, read: () => names(pinned()),+ write: async (botIds: string[]) => {+ const unknown = botIds.find((id) => !deps.bots().some((bot) => bot.id === id));+ if (unknown) return `No bot has the id ${unknown}. Use list_bots for the ids.`;+ for (const bot of deps.bots()) {+ if (Boolean(bot.pinned) === botIds.includes(bot.id)) continue;+ const refusal = await deps.pinBot(bot.id, botIds.includes(bot.id));+ if (refusal) return refusal;+ }+ return null;+ },+ }),writable({id: "bots.groups", label: "Sidebar groups", help: "Which bots sit in which sidebar group (department). Send an object of group name to bot ids; a bot in no listed group is ungrouped.", where: "the sidebar",synonyms: ["group", "groups", "department", "departments", "section", "sections", "team", "folder"], tier: "safe",@@ -291,7 +308,7 @@ export function findSettings(entries: readonly SettingEntry[], query: string, liexport function routeBackedRegistry(deps: {cfg(): AppConfig;store: Pick<Store, "bots" | "sections" | "tasks">;- routes: { config: RouteHandler; botOrder: RouteHandler; sections: RouteHandler; instances: RouteHandler };+ routes: { config: RouteHandler; botOrder: RouteHandler; botPatch: RouteHandler; sections: RouteHandler; instances: RouteHandler };providers: Pick<ProviderRegistry, "instances" | "lastSnapshot">;credentials(): CredentialConfig;window: RegistryDeps["window"];@@ -302,6 +319,7 @@ export function routeBackedRegistry(deps: {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 })),+ pinBot: (botId, pinned) => refusal(callRoute(deps.routes.botPatch, { method: "PATCH", path: `/api/bots/${encodeURIComponent(botId)}`, body: { pinned }, auth })),groupBots: (name, botIds) => refusal(callRoute(deps.routes.sections, { method: "POST", path: "/api/sidebar-sections", body: { name, botIds }, auth })),engines: () => deps.providers.instances().filter((instance) => instance.enabled).map((instance) => ({instanceId: instance.instanceId, working: deps.providers.lastSnapshot(instance.instanceId)?.state === "available",diff --git a/server/index.ts b/server/index.tsindex a57c0d048d..69e2c1c3e2 100644--- a/server/index.ts+++ b/server/index.ts@@ -12120,14 +12120,14 @@ ROUTES.push(createBotSettingsRoutes({canManageCommandAllowlist, commandAllowlistResponse, cardAnswerRefusal, threadRead: teamMessages.seen, levelOf, personMarkThread: personRooms.personMarkThread,}));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({+const botPatchRoutes = createBotPatchRoutes({store, cfg, registry, sessions, browserRuntime, browserLive, memoryUpkeep, cacheKeepWarm, hostedModels, supportsApprovalMode,routines: () => routines, activeVpsThreads,hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED,broadcast, wireBot, publicGroupState, audienceChanged, storedAvatarExists, requestedTaskBot, threadBusy, activeGroupTurnForBot,checkedModelSelection, engineSwitchNeedsAsk, currentBrowserSession, interruptAllDirectThreads, cancelGroupTurnOperations,revokeInternalCapabilitiesForThread, runningTurnInstance, closeOpenApprovals, assertTeamComputerChangeIdle, forgetTemporaryBrowser, levelOf, team: Boolean(CLOUD_TEAM), mainThreadTasks, chiefChanged: (changed) => chiefRooms.moved(changed), ...(personRooms.personMarkThread ? { personMarkThread: personRooms.personMarkThread, shownThread: (auth: RequestAuth, bot: BotRecord) => memberBot(wireBot(bot), visibleTo(viewerFor(auth))).threadId } : {}),-}));+}); ROUTES.push(botPatchRoutes);ROUTES.push(createBotLifecycleRoutes({store, routines: () => routines, interruptAllDirectThreads, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread,activeGroupTurnForBot, cancelGroupTurnOperations, runningTurnInstance, closeOpenApprovals, deleteBotWithLifecycle, deleteRefusal: (auth, botId) => memberDeleteRefusal(auth, store.bot(botId), Boolean(CLOUD_TEAM)),@@ -12359,7 +12359,7 @@ const instanceRoutes = createInstanceRoutes({providerConfigBusy: { get: () => providerConfigBusy, set: (busy) => { providerConfigBusy = busy; } },providerInstancesChanging, describeInstances, persistProviderInstance, configStatus, broadcast, testCliBinary,cliProbeEnvironment, threadBusy, botForThread, activeGroupTurnForBot, checkInstance: testedAi.check,-}); const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin, windowOpen: () => [...sseClients].some((client) => client.admin && client.appWindow) }); const appSettings = createAppSettings({ store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, sections: sidebarRoutes, instances: instanceRoutes }, providers: registry, 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(instanceRoutes, windowPrefs.routes);+}); const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin, windowOpen: () => [...sseClients].some((client) => client.admin && client.appWindow) }); const appSettings = createAppSettings({ store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, botPatch: botPatchRoutes, sections: sidebarRoutes, instances: instanceRoutes }, providers: registry, 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(instanceRoutes, windowPrefs.routes);ROUTES.push(createMcpServerRoutes({cfg, bot: (id) => store.bot(id), sessions, mcpOAuth, teamConnections,cloudHome: CLOUD_HOME,