Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(routines): pausing a routine ends its run waiting on you; reconnecting an app settles older connect cards
AdityaUmale19b8b0259f41
diff --git a/server/host/connect-card-settle.test.ts b/server/host/connect-card-settle.test.tsnew file mode 100644index 0000000000..8b5b9790ca--- /dev/null+++ b/server/host/connect-card-settle.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from "vitest";++import type { ConnectorCardData } from "../../shared/connector-card.ts";+import type { WireMessage as Message } from "../../shared/wire.ts";+import { settleOpenConnectCards } from "./connect-card-settle.ts";++const NOW = Date.parse("2026-11-12T10:00:00Z");+const card = (id: string, connector: Partial<ConnectorCardData>): Message => ({+ id, role: "bot", kind: "connector", text: "", at: NOW,+ connector: { slug: "instagram", label: "Instagram", description: "", status: "required", resumeKey: `key-${id}`, ...connector },+} as Message);++function harness(threads: Record<string, Message[]>) {+ const resumed: Array<[string, string]> = [];+ const deps = {+ threadsWithCards: () => Object.keys(threads),+ messagesFor: (threadId: string) => threads[threadId] ?? [],+ patchMessage: (threadId: string, messageId: string, patch: Partial<Message>) => {+ const list = threads[threadId]!;+ const at = list.findIndex((message) => message.id === messageId);+ list[at] = { ...list[at]!, ...patch };+ },+ resume: (threadId: string, resumeKey: string) => { resumed.push([threadId, resumeKey]); },+ now: () => NOW,+ };+ const status = (threadId: string, id: string) => threads[threadId]!.find((message) => message.id === id)!.connector!.status;+ return { deps, resumed, status };+}++describe("reconnecting an app settles older open connect cards for it", () => {+ it("marks an older run's open card for the same app connected and lets its parked work carry on", () => {+ const h = harness({ "old-run": [card("a", { status: "authorizing" })], "other-app": [card("b", { slug: "gmail", label: "Gmail" })] });+ expect(settleOpenConnectCards(h.deps, "Instagram")).toBe(1);+ expect(h.status("old-run", "a")).toBe("connected");+ expect(h.status("other-app", "b")).toBe("required");+ expect(h.resumed).toEqual([["old-run", "key-a"]]);+ });++ it("only settles cards for that same account", () => {+ const h = harness({ t: [card("work", { alias: "Work" }), card("plain", {}), card("home", { alias: "home" })] });+ expect(settleOpenConnectCards(h.deps, "instagram", " work ")).toBe(1);+ expect([h.status("t", "work"), h.status("t", "plain"), h.status("t", "home")]).toEqual(["connected", "required", "required"]);+ });++ it("leaves cards the person closed, stopped or already finished, and MCP sign-in cards", () => {+ const h = harness({ t: [+ card("dismissed", { dismissed: true }), card("superseded", { superseded: true }), card("stopped", { stopped: true }),+ card("resumed", { resumed: true }), card("mcp", { source: "mcp" }), card("done", { status: "connected" }),+ ] });+ expect(settleOpenConnectCards(h.deps, "instagram")).toBe(0);+ expect(h.resumed).toEqual([]);+ });++ it("resumes each request once even when it had several cards for the app", () => {+ const h = harness({ t: [card("one", { resumeKey: "k" }), card("two", { resumeKey: "k", status: "failed", error: "Connection expired" })] });+ expect(settleOpenConnectCards(h.deps, "instagram")).toBe(2);+ expect(h.resumed).toEqual([["t", "k"]]);+ });+});diff --git a/server/host/connect-card-settle.ts b/server/host/connect-card-settle.tsnew file mode 100644index 0000000000..cde3c0b8d3--- /dev/null+++ b/server/host/connect-card-settle.ts@@ -0,0 +1,34 @@+/** An app account was just (re)connected: connect cards still open for that same app and account, in any conversation of the last week, show it connected, and work parked on them carries on. */+import type { WireMessage as Message } from "../../shared/wire.ts";+import { NEEDS_YOU_WINDOW_MS } from "../../shared/today.ts";++export interface ConnectCardSettleDeps {+ threadsWithCards(since: number): readonly string[];+ messagesFor(threadId: string): readonly Message[];+ patchMessage(threadId: string, messageId: string, patch: Partial<Message>): unknown;+ /** Continues the turn parked on these cards once every card of its request is connected. */+ resume(threadId: string, resumeKey: string): unknown;+ now(): number;+}++const accountKey = (alias: string | undefined) => alias?.trim().toLowerCase() ?? "";++/** Returns how many cards it settled. MCP sign-in cards, and cards dismissed, superseded, stopped or resumed, are left as they are. */+export function settleOpenConnectCards(deps: ConnectCardSettleDeps, slug: string, alias?: string): number {+ const app = slug.toLowerCase();+ const account = accountKey(alias);+ let settled = 0;+ for (const threadId of deps.threadsWithCards(deps.now() - NEEDS_YOU_WINDOW_MS)) {+ const resumeKeys = new Set<string>();+ for (const message of deps.messagesFor(threadId)) {+ const card = message.kind === "connector" ? message.connector : undefined;+ if (!card || card.source === "mcp" || card.slug.toLowerCase() !== app || accountKey(card.alias) !== account) continue;+ if (card.status === "connected" || card.dismissed || card.superseded || card.stopped || card.resumed) continue;+ deps.patchMessage(threadId, message.id, { connector: { ...card, status: "connected", error: undefined } });+ resumeKeys.add(card.resumeKey);+ settled++;+ }+ for (const resumeKey of resumeKeys) deps.resume(threadId, resumeKey);+ }+ return settled;+}diff --git a/server/index.ts b/server/index.tsindex f8906fd387..f5edf5df9a 100644--- a/server/index.ts+++ b/server/index.ts@@ -26,7 +26,7 @@ import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";import { SharedComputerControl } from "./shared-computer-control.ts";import { STATUS_REPLY_TIMEOUT_MS } from "./runtime/status-reply.ts"; import { createCoordinator, type ComposedTurn, type CoordinateBotsCall, type Coordinator, type HandoffOpener, type HandoffOptions, type HandoffView, type HostTurnResult } from "./coordinator.ts";import { queuedBehindPersonText, turnWaitedOnPerson, UnansweredApprovals } from "./waiting-on-person.ts";-import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, createAskCards } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts";+import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, createAskCards } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts"; import { settleOpenConnectCards } from "./host/connect-card-settle.ts";import { assertRequestTarget, guardedRequestPath, requestConflict, requestNeedsInput } from "./guarded-requests.ts";import { botAvatarUrlFromStoredPath } from "../shared/bot-avatar.ts";import { BOT_PROFILE_LIMITS } from "../shared/bot-profile.ts";@@ -11494,6 +11494,21 @@ function maybeResumeConnectors(threadId: string, resumeKey: string) {return true;}+const connectCardSettle = {+ threadsWithCards: threadsWithCardsSince,+ messagesFor: (threadId: string) => store.messagesFor(threadId),+ patchMessage: (threadId: string, messageId: string, patch: Partial<Message>) => store.patchMessage(threadId, messageId, patch),+ resume: maybeResumeConnectors,+ now: Date.now,+};++function settleConnectedAccounts(services: Awaited<ReturnType<typeof composio.connectionStatus>>) {+ for (const [slug, service] of Object.entries(services)) {+ if (service?.connected) settleOpenConnectCards(connectCardSettle, slug);+ for (const account of service?.accounts ?? []) if (account.alias && /^active$/i.test(account.status)) settleOpenConnectCards(connectCardSettle, slug, account.alias);+ }+}+const phoneSecretSubmissions = new PhoneSecretSubmissionRegistry();@@ -15021,6 +15036,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {});}const status = await composio.connectionStatus(cfg, services.length ? services : composio.CURATED_SLUGS);+ // Settings asked about these apps (it polls after Connect): open connect cards for an account that is now connected stop waiting.+ if (services.length) settleConnectedAccounts(status);return json(res, 200, { configured: true, services: status });}m = path.match(/^\/api\/connectors\/([\w-]+)\/authorize$/);@@ -15079,7 +15096,10 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {error: failed ? `Connection ${state?.status ?? "failed"}` : undefined,};store.patchMessage(threadId, message.id, { connector: next });- if (state?.connected) maybeResumeConnectors(threadId, connector.resumeKey);+ if (state?.connected) {+ maybeResumeConnectors(threadId, connector.resumeKey);+ settleOpenConnectCards(connectCardSettle, connector.slug, connector.alias);+ }return json(res, 200, { connected: Boolean(state?.connected), pending: Boolean(state?.pending), status: state?.status });}if (m[3] === "resume" && method === "POST") {diff --git a/server/routines.test.ts b/server/routines.test.tsindex a2f008f50c..2b822abe2a 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -434,6 +434,31 @@ describe("a run left waiting for the person", () => {if (change === "rescheduled") expect(h.manager.listRoutines()[0].nextRunAt).toBe(monday + minutes(240));});+ it.each(["paused", "deleted"] as const)("stops a run still waiting for the person when its routine is %s, so the bot stops waiting", async (change) => {+ const h = harness(monday);+ const routine = h.manager.create(daily);+ h.setNow(routine.nextRunAt!); await h.manager.tick();+ h.setNow(routine.nextRunAt! + minutes(2)); parkOnPerson(h, "thread-1");+ expect(h.manager.listRuns()[0]).toMatchObject({ status: "waiting" });++ h.setNow(routine.nextRunAt! + minutes(30));+ if (change === "paused") h.manager.update(routine.id, { enabled: false });+ else h.manager.remove(routine.id);+ const why = change === "paused" ? "The routine was paused while this run waited for you" : "The routine was deleted while this run waited for you";+ expect(h.manager.listRuns()[0]).toMatchObject({ status: "cancelled", error: why, finishedAt: routine.nextRunAt! + minutes(30), threadId: "thread-1" });+ expect(h.manager.listRuns()[0].attention).toBeUndefined();+ await vi.waitFor(() => expect(h.interruptedTurns).toEqual([{ botId: "maus-1", threadId: "thread-1" }]));+ });++ it("leaves a run that is still working alone when its routine is paused", async () => {+ const h = harness(monday);+ const routine = h.manager.create(daily);+ h.setNow(routine.nextRunAt!); await h.manager.tick();+ h.manager.update(routine.id, { enabled: false });+ expect(h.manager.listRuns()[0]).toMatchObject({ status: "running" });+ expect(h.interruptedTurns).toEqual([]);+ });+it.each(["skip", "queue"] as const)("keeps today's %s overlap behind a run that was answered and is still working", async (overlap) => {const h = harness(monday);const routine = h.manager.create({ ...daily, ...(overlap === "queue" ? { overlap } : {}) });diff --git a/server/routines.ts b/server/routines.tsindex ec27249270..2d56773771 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -609,6 +609,7 @@ export class RoutineManager {if (destination.botId !== routine.botId) delete destination.resultsThreadId;const discardResults = this.applyResultsInput(destination, patch.resultsThreadId);const cancelledRuns: RoutineRun[] = [];+ const stoppedRuns: RoutineRun[] = [];this.commitMutation(() => {Object.assign(routine, clean, {resultsThreadId: destination.resultsThreadId,@@ -624,17 +625,23 @@ export class RoutineManager {}if (patch.enabled === false) {for (const run of this.runs) {- if (run.routineId !== routine.id || run.status !== "queued") continue;+ if (run.routineId !== routine.id || (run.status !== "queued" && run.status !== "waiting")) continue;+ const waited = run.status === "waiting";+ run.error = waited ? "The routine was paused while this run waited for you" : "The routine was paused before this run started";+ if (waited) {+ stoppedRuns.push(run);+ if (run.target === "room-goal") run.goalStatus = "stopped";+ }run.status = "cancelled";run.attention = undefined;run.finishedAt = this.now();- run.error = "The routine was paused before this run started";cancelledRuns.push(run);}}if (request) this.rememberRoutineRequest(request, routine.id, now);}, discardResults);for (const run of cancelledRuns) this.emitRun(run);+ this.stopWaitingTurns(stoppedRuns);this.emitRoutine(routine);return this.routineWithHealth(routine);}@@ -645,11 +652,17 @@ export class RoutineManager {const at = this.routines.findIndex((r) => r.id === id);if (at === -1) return false;const changedRuns: RoutineRun[] = [];+ const stoppedRuns: RoutineRun[] = [];this.commitMutation(() => {this.routines.splice(at, 1);for (const run of this.runs) {if (run.routineId !== id) continue;- if (run.status === "queued") {+ if (run.status === "queued" || run.status === "waiting") {+ if (run.status === "waiting") {+ run.error = "The routine was deleted while this run waited for you";+ stoppedRuns.push(run);+ if (run.target === "room-goal") run.goalStatus = "stopped";+ }run.status = "cancelled";run.attention = undefined;run.finishedAt = this.now();@@ -662,10 +675,20 @@ export class RoutineManager {if (request) this.rememberRoutineRequest(request, id, this.now());});for (const run of changedRuns) this.emitRun(run);+ this.stopWaitingTurns(stoppedRuns);this.options.emit?.({ kind: "routine.deleted", routineId: id });return true;}+ /** A run that waited for the person was cancelled: end its turn too, so its open cards stop and the bot no longer shows it waiting. */+ private stopWaitingTurns(runs: readonly RoutineRun[]) {+ for (const run of runs) {+ if (!run.threadId) continue;+ if (run.target === "room-goal") void this.options.interruptGoal?.(run.groupId, run.threadId).catch(() => {});+ else void this.options.interruptTurn?.(run.botId, run.threadId).catch(() => {});+ }+ }+/** A deleted bot's schedules go with it, or with `routineId` that one only (one person's alone, gone as they leave a team): each is removed, its unfinished runs stop, and its run history is dropped. */removeForBot(botId: string, routineId?: string) {for (const routine of this.routines.filter((candidate) => candidate.botId === botId && (routineId === undefined || candidate.id === routineId))) this.remove(routine.id);