Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

refactor: move routine stop and card settle wiring out of size-ratcheted files; test Settings path

AdityaUmale6c6591f5ae12
diff --git a/server/host/connect-card-settle.test.ts b/server/host/connect-card-settle.test.ts
index 8b5b9790ca..497be2ce07 100644
--- a/server/host/connect-card-settle.test.ts
+++ b/server/host/connect-card-settle.test.ts
@@ -2,7 +2,7 @@ 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";
+import { createConnectCardSettle, settleOpenConnectCards } from "./connect-card-settle.ts";
const NOW = Date.parse("2026-11-12T10:00:00Z");
const card = (id: string, connector: Partial<ConnectorCardData>): Message => ({
@@ -56,4 +56,14 @@ describe("reconnecting an app settles older open connect cards for it", () => {
expect(settleOpenConnectCards(h.deps, "instagram")).toBe(2);
expect(h.resumed).toEqual([["t", "k"]]);
});
+
+ it("settles from what Settings reads once an app or an account is active, and nothing for one still pending", () => {
+ const h = harness({ t: [card("plain", {}), card("work", { alias: "work" }), card("gmail", { slug: "gmail", label: "Gmail" }), card("drive", { slug: "googledrive", label: "Drive" })] });
+ createConnectCardSettle(h.deps).services({
+ instagram: { connected: true, accounts: [{ alias: "work", status: "ACTIVE" }] },
+ gmail: { connected: false, accounts: [{ status: "INITIATED" }] },
+ googledrive: undefined,
+ });
+ expect(["plain", "work", "gmail", "drive"].map((id) => h.status("t", id))).toEqual(["connected", "connected", "required", "required"]);
+ });
});
diff --git a/server/host/connect-card-settle.ts b/server/host/connect-card-settle.ts
index cde3c0b8d3..09e59f8f37 100644
--- a/server/host/connect-card-settle.ts
+++ b/server/host/connect-card-settle.ts
@@ -32,3 +32,18 @@ export function settleOpenConnectCards(deps: ConnectCardSettleDeps, slug: string
}
return settled;
}
+
+type ServiceStatus = { connected?: boolean; accounts?: ReadonlyArray<{ alias?: string; status: string }> } | undefined;
+
+/** The host's two moments an account connects: a connect card's own check, and Settings asking about apps it is connecting. */
+export function createConnectCardSettle(deps: ConnectCardSettleDeps) {
+ return {
+ card: (slug: string, alias?: string) => settleOpenConnectCards(deps, slug, alias),
+ services(services: Record<string, ServiceStatus>) {
+ for (const [slug, service] of Object.entries(services)) {
+ if (service?.connected) settleOpenConnectCards(deps, slug);
+ for (const account of service?.accounts ?? []) if (account.alias && /^active$/i.test(account.status)) settleOpenConnectCards(deps, slug, account.alias);
+ }
+ },
+ };
+}
diff --git a/server/index.ts b/server/index.ts
index f5edf5df9a..39e020639f 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 { settleOpenConnectCards } from "./host/connect-card-settle.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 { createConnectCardSettle } 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,21 +11494,6 @@ 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();
@@ -11650,7 +11635,7 @@ async function botBrowserTarget(bot: BotRecord, threadId: string): Promise<{ ses
return target && { ...target, env: browserRuntimeEnv({ ...target.spec.env, AGENT_BROWSER_SESSION: target.session }) };
}
-const connectorCardRequests = createConnectorCards({ cfg: () => cfg, store, composio, connectorThread, refusal: (capability, slugs) => managedPolicy.appsConnectRefusal(slugs) ?? teamConnections.connectRefusal(capability, slugs), decide: (row) => appendDecision(DATA_DIR, row), language: threadLanguage, maybeResume: maybeResumeConnectors });
+const connectorCardRequests = createConnectorCards({ cfg: () => cfg, store, composio, connectorThread, refusal: (capability, slugs) => managedPolicy.appsConnectRefusal(slugs) ?? teamConnections.connectRefusal(capability, slugs), decide: (row) => appendDecision(DATA_DIR, row), language: threadLanguage, maybeResume: maybeResumeConnectors }); const connectCardSettle = createConnectCardSettle({ threadsWithCards: threadsWithCardsSince, messagesFor: (threadId) => store.messagesFor(threadId), patchMessage: (threadId, messageId, patch) => store.patchMessage(threadId, messageId, patch), resume: maybeResumeConnectors, now: Date.now });
const loginMailCodes = createLoginMailCodes({ dataDir: DATA_DIR, cfg: () => cfg, composio, personApps: () => teamConnections.personApps(), turnPerson: (threadId, generation) => teamConnections.turnPerson(threadId, generation), appsAccess: (person) => teamConnections.people.appsAccess(person), appAllowed: (slug) => managedPolicy.appAllowed(slug), imapAccounts: (bot) => (emailHost.mounts(bot) && emailAccess(bot, "EMAIL_READ_MESSAGE").ok ? emailService.store.list() : []), imapGuard: emailService.guard, unattended: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined, connectCard: (turn, input) => connectorCardRequests.request(turn, input, () => {}) });
const { fillLoginForTurn } = createFillLoginTurn({
mailCodes: loginMailCodes, turnActive: (turn) => internalCapabilityIsActive(turn as InternalCapability),
@@ -15035,9 +15020,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
services: {},
});
}
- 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);
+ const status = await composio.connectionStatus(cfg, services.length ? services : composio.CURATED_SLUGS); if (services.length) connectCardSettle.services(status); // Settings polls these after Connect: older open cards stop waiting.
return json(res, 200, { configured: true, services: status });
}
m = path.match(/^\/api\/connectors\/([\w-]+)\/authorize$/);
@@ -15096,10 +15079,7 @@ 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);
- settleOpenConnectCards(connectCardSettle, connector.slug, connector.alias);
- }
+ if (state?.connected) { maybeResumeConnectors(threadId, connector.resumeKey); connectCardSettle.card(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/routine-stops.ts b/server/routine-stops.ts
new file mode 100644
index 0000000000..676775b9e1
--- /dev/null
+++ b/server/routine-stops.ts
@@ -0,0 +1,29 @@
+/** Pausing or deleting a routine ends its runs that have not started, and those waiting for the person, whose turns end too. */
+import type { RoutineManagerOptions, RoutineRun } from "./routines.ts";
+
+/** Cancels this routine's queued and waiting runs; returns them all, and the waiting ones apart. */
+export function cancelUnfinishedRuns(runs: readonly RoutineRun[], routineId: string, now: number, change: "paused" | "deleted") {
+ const cancelled: RoutineRun[] = [];
+ const waited: RoutineRun[] = [];
+ for (const run of runs) {
+ if (run.routineId !== routineId || (run.status !== "queued" && run.status !== "waiting")) continue;
+ if (run.status === "waiting") {
+ run.error = `The routine was ${change} while this run waited for you`;
+ if (run.target === "room-goal") run.goalStatus = "stopped";
+ waited.push(run);
+ } else if (change === "paused") run.error = "The routine was paused before this run started";
+ run.status = "cancelled";
+ run.attention = undefined;
+ run.finishedAt = now;
+ cancelled.push(run);
+ }
+ return { cancelled, waited };
+}
+
+/** Ends the turns of runs that stopped while their bot or room worked or waited, so their open cards stop and nothing shows them waiting. */
+export function interruptRunTurns(runs: readonly RoutineRun[], options: Pick<RoutineManagerOptions, "interruptTurn" | "interruptGoal">) {
+ for (const run of runs) {
+ if (run.threadId && run.target === "room-goal") void options.interruptGoal?.(run.groupId, run.threadId).catch(() => {});
+ else if (run.threadId) void options.interruptTurn?.(run.botId, run.threadId).catch(() => {});
+ }
+}
diff --git a/server/routines.ts b/server/routines.ts
index 2d56773771..5aa46d45ac 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -32,6 +32,7 @@ import { EVENT_RETRY_WINDOW_MS, loadEventReceipts, MAX_EVENT_RECEIPTS, type Even
import { attachmentPathsOf, attachmentsMalformed, cloneAttachments } from "./routine-attachments.ts";
import { loadInstalledPackage, loadRequestReceipts, loadRoutine, loadRun } from "./routine-load.ts";
import { applyHolds, holdCauses, type AppliedHolds } from "./routine-holds.ts";
+import { cancelUnfinishedRuns, interruptRunTurns } from "./routine-stops.ts";
import { sanitizeInput } from "./routine-input.ts";
import { applyCheckResult, routineLine, runLineFields, type RoutineLineCodes, type RoutineTroubleCode } from "./routine-lines.ts";
import { checkHold, CHECK_BOOT_HOLD_MS, type CheckHold } from "./routine-check-pacing.ts";
@@ -608,8 +609,7 @@ export class RoutineManager {
const destination = { ...routine, ...clean };
if (destination.botId !== routine.botId) delete destination.resultsThreadId;
const discardResults = this.applyResultsInput(destination, patch.resultsThreadId);
- const cancelledRuns: RoutineRun[] = [];
- const stoppedRuns: RoutineRun[] = [];
+ let stopped: ReturnType<typeof cancelUnfinishedRuns> | undefined;
this.commitMutation(() => {
Object.assign(routine, clean, {
resultsThreadId: destination.resultsThreadId,
@@ -623,25 +623,11 @@ export class RoutineManager {
if (Object.hasOwn(patch, "timeoutMinutes") && patch.timeoutMinutes == null) {
delete routine.timeoutMinutes;
}
- if (patch.enabled === false) {
- for (const run of this.runs) {
- 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();
- cancelledRuns.push(run);
- }
- }
+ if (patch.enabled === false) stopped = cancelUnfinishedRuns(this.runs, routine.id, this.now(), "paused");
if (request) this.rememberRoutineRequest(request, routine.id, now);
}, discardResults);
- for (const run of cancelledRuns) this.emitRun(run);
- this.stopWaitingTurns(stoppedRuns);
+ for (const run of stopped?.cancelled ?? []) this.emitRun(run);
+ interruptRunTurns(stopped?.waited ?? [], this.options);
this.emitRoutine(routine);
return this.routineWithHealth(routine);
}
@@ -652,43 +638,23 @@ export class RoutineManager {
const at = this.routines.findIndex((r) => r.id === id);
if (at === -1) return false;
const changedRuns: RoutineRun[] = [];
- const stoppedRuns: RoutineRun[] = [];
+ let stopped: ReturnType<typeof cancelUnfinishedRuns> | undefined;
this.commitMutation(() => {
this.routines.splice(at, 1);
for (const run of this.runs) {
- if (run.routineId !== id) continue;
- 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();
- changedRuns.push(run);
- } else if (!run.seenAt && isRoutineProblemRun(run)) {
- run.seenAt = this.now();
- changedRuns.push(run);
- }
+ if (run.routineId !== id || run.status === "queued" || run.status === "waiting" || run.seenAt || !isRoutineProblemRun(run)) continue;
+ run.seenAt = this.now();
+ changedRuns.push(run);
}
+ stopped = cancelUnfinishedRuns(this.runs, id, this.now(), "deleted");
if (request) this.rememberRoutineRequest(request, id, this.now());
});
- for (const run of changedRuns) this.emitRun(run);
- this.stopWaitingTurns(stoppedRuns);
+ for (const run of [...stopped!.cancelled, ...changedRuns]) this.emitRun(run);
+ interruptRunTurns(stopped!.waited, this.options);
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);
@@ -700,8 +666,7 @@ export class RoutineManager {
run.finishedAt = this.now();
run.error = routineId === undefined ? "The assigned bot was deleted" : "The routine was deleted";
this.emitRun(run);
- if (run.threadId && run.target === "room-goal") void this.options.interruptGoal?.(run.groupId, run.threadId).catch(() => {});
- else if (run.threadId) void this.options.interruptTurn?.(run.botId, run.threadId).catch(() => {});
+ interruptRunTurns([run], this.options);
}
const kept = this.runs.filter((run) => run.botId !== botId || (routineId !== undefined && run.routineId !== routineId));
if (kept.length !== this.runs.length) this.commitMutation(() => { this.runs = kept; });