Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Check the account limit as a queued app-event run starts
Bugfixer 2c7b049aec368
diff --git a/server/app-trigger-host.ts b/server/app-trigger-host.tsindex 07a97a6e64..90f49e3dfa 100644--- a/server/app-trigger-host.ts+++ b/server/app-trigger-host.ts@@ -228,6 +228,8 @@ export function createAppTriggerHost(deps: AppTriggerHostDeps) {submit,undo: (args: { botId: string; threadId: string; requestId: string }) => requests.undo(args),isApp: (id: string) => manager.get(id) !== null,+ /** For the run scheduler, right before a queued run starts: why this app-event run may not. */+ runRefusal: (run: { webhookId?: string; eventSource?: string }) => (run.eventSource === "app" && run.webhookId ? manager.runRefusal(run.webhookId) : null),start: () => manager.start(),stop: () => manager.stop(),/** Access to the service changed (the desktop handed its token over, or a Cloud registered). */diff --git a/server/app-triggers.test.ts b/server/app-triggers.test.tsindex 1ddfe0472f..72138cf5b2 100644--- a/server/app-triggers.test.ts+++ b/server/app-triggers.test.ts@@ -576,6 +576,23 @@ describe("a bot limited to some accounts of an app", () => {expect(runsOf(trigger.id)).toMatchObject([{ status: "cancelled", error: expect.stringContaining("may no longer use this account") }]);});+ it("refuses a queued run as it starts, before any reconcile, even while the service is unavailable", async () => {+ let allowed: string[] | undefined;+ let service: ReturnType<AppTriggerManagerOptions["service"]> = { available: true };+ const triggers = manager({ accountLimit: () => allowed, service: () => service });+ const trigger = await triggers.create({ botId: "bot-1", name: "Sales", prompt: "Draft a reply.", app: "gmail", event: "GMAIL_NEW_GMAIL_MESSAGE", account: "sales" });+ await broker.deliver(trigger.remote.triggerId!, { subject: "Hello", sender: "[email protected]" }, "msg_q2");+ await drain(triggers);+ expect(runsOf(trigger.id)).toMatchObject([{ status: "queued" }]);+ expect(triggers.runRefusal(trigger.id)).toBeNull();+ allowed = [support];+ service = { available: false, reason: "unavailable" };+ expect(triggers.runRefusal(trigger.id)).toContain("may no longer use this account");+ allowed = undefined;+ expect(triggers.runRefusal(trigger.id)).toBeNull();+ expect(triggers.runRefusal("no-such-automation")).toBeNull();+ });+it("lists only the accounts the bot may use in its event list", async () => {const client = brokerClient(() => ({ url: broker.url, token: owner.token }));const bot = { connectorScopes: { apps: { gmail: "read" as const }, accounts: { gmail: [support] } } };diff --git a/server/app-triggers.ts b/server/app-triggers.tsindex 4fd864e87e..1d1a64943e 100644--- a/server/app-triggers.ts+++ b/server/app-triggers.ts@@ -166,6 +166,7 @@ export interface AppTriggerPatch {const utcDay = (at: number) => new Date(at).toISOString().slice(0, 10);const active = (status: string) => /^active$/i.test(status);const ACCOUNT_NOT_ALLOWED = "Its bot may no longer use this account. Allow it again under the bot's Access settings, or make the automation for an account the bot may use.";+const QUEUED_RUN_REFUSED = "Its bot may no longer use this account, so this event's run did not start";const names = (accounts: Array<{ id: string; alias?: string }>) => accounts.map((account) => account.alias ?? account.id).join(", ");function cleanFilter(filter: AppTriggerFilter | null | undefined): AppTriggerFilter | undefined {@@ -427,6 +428,12 @@ export class AppTriggerManager {});}+ /** Why a queued run of this automation may not start now, checked as it starts: its bot lost the account since the event came in. */+ runRefusal(id: string): string | null {+ const trigger = this.triggers.find((candidate) => candidate.id === id);+ return trigger && !this.botMayUse(trigger.botId, trigger.app, trigger.accountId) ? QUEUED_RUN_REFUSED : null;+ }+/** A test event marked as one, sent through the service's real queue when the automation has its copy there. */async runNow(id: string): Promise<{ via: "service" | "here"; runId?: string } | null> {const trigger = this.triggers.find((candidate) => candidate.id === id);@@ -648,7 +655,7 @@ export class AppTriggerManager {// Its bot is gone: paused here, so Composio stops sending what no one would run.if (trigger.enabled && this.options.botState(trigger.botId) === "missing") trigger.enabled = false;const allowed = this.botMayUse(trigger.botId, trigger.app, trigger.accountId);- if (!allowed) this.options.runs.cancelQueued(trigger.id, "Its bot may no longer use this account, so this event's run did not start");+ if (!allowed) this.options.runs.cancelQueued(trigger.id, QUEUED_RUN_REFUSED);const account = accounts?.[trigger.app]?.accounts.find((candidate) => candidate.id === trigger.accountId);if (accounts && (!account || !active(account.status))) {if (trigger.problem?.kind !== "reconnect") trigger.problem = { kind: "reconnect", at: this.now() };diff --git a/server/index.ts b/server/index.tsindex 50384d56ba..a29562a3cd 100644--- a/server/index.ts+++ b/server/index.ts@@ -8664,7 +8664,7 @@ routines = new RoutineManager({skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), prepareRun: (run, signal) => runComputers.prepare(run, signal), preparing: RUN_COMPUTER_LINES.waking, // a Cloud home waking from a sleep it was stopped forhasPendingDelegations: runtimeWorkPending, refusedHandoff: takeRefusedRun, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined, personTurn: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "user", home: { machine: CLOUD_HOME?.machineId, cloud: CLOUD_HOME !== null }, turnLive: (run) => runTurnLive(run, (threadId) => ({ busy: threadBusy(run.botId, threadId), settling: settlingTurns.has(threadId), queued: queuedThreadPosition(run.botId, threadId) !== null, pending: runtimeWorkPending(threadId), parked: store.taskByThread(run.botId, threadId)?.activity === "parked.computer" })),- botState: unattendedDispatchState, pausedText: (botId, run) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? (run ? starterRoutineWake?.refusal(run) ?? null : null), /* the Starter limit only as the owner's options say: a routine wakes its bot (host/starter-routine-wake.ts) */ held: (botId) => botHolds.held(botId), capSkip: (botId, routineId) => usageCapGate.routineSkip(botId, routineId), capText: (botId, trigger) => usageCapGate.runText(botId, trigger, threadLanguage(store.bot(botId)?.threadId ?? "")),+ botState: unattendedDispatchState, pausedText: (botId, run) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? (run ? starterRoutineWake?.refusal(run) ?? appTriggers.runRefusal(run) : null), /* the Starter limit only as the owner's options say: a routine wakes its bot (host/starter-routine-wake.ts) */ held: (botId) => botHolds.held(botId), capSkip: (botId, routineId) => usageCapGate.routineSkip(botId, routineId), capText: (botId, trigger) => usageCapGate.runText(botId, trigger, threadLanguage(store.bot(botId)?.threadId ?? "")),goalState: (groupId, coordinatorBotId) => {if (!groupId) return unattendedDispatchState(coordinatorBotId);const group = store.group(groupId);diff --git a/server/routines.test.ts b/server/routines.test.tsindex bede24d230..39bfe6adce 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -4184,6 +4184,19 @@ describe("turning a schedule back on, and a deleted bot's schedules", () => {});});+describe("an app-event run its automation refuses as it starts", () => {+ it("does not start a queued app-event run its automation now refuses, and tells the hook which run it is", async () => {+ const h = harness();+ const refused = "Its bot may no longer use this account, so this event's run did not start";+ h.options.pausedText = (_botId, run) => (run?.eventSource === "app" && run.webhookId === "trigger-1" ? refused : null);+ h.manager.enqueueWebhook({ webhookId: "trigger-1", webhookName: "Sales mail", prompt: "Draft a reply.", botId: "maus-1", runOn: "maus", deliveryId: "msg_1", receivedAt: Date.now(), eventSource: "app" });+ h.manager.enqueueWebhook({ webhookId: "trigger-2", webhookName: "Support mail", prompt: "Draft a reply.", botId: "maus-1", runOn: "maus", deliveryId: "msg_2", receivedAt: Date.now(), eventSource: "app" });+ await h.manager.tick();+ expect(h.started).toHaveLength(1);+ expect(h.manager.listRuns().map((run) => [run.webhookId, run.status, run.error])).toEqual(expect.arrayContaining([["trigger-1", "failed", refused], ["trigger-2", "running", undefined]]));+ });+});+describe("a reached usage cap", () => {const start = Date.parse("2026-09-13T08:00:00Z"), HOUR = 3_600_000, DAY = 24 * HOUR;const line = (count: number) => ({ text: count === 1 ? "Skipped: the cap is reached" : `Skipped ${count} runs: the cap is reached`, codes: {} });