Skip to content

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

fix: prevent routine dispatch after shutdown begins

Sebastian Bd5a85c7000ee
diff --git a/server/index.ts b/server/index.ts
index ac530bbb91..ff50e4c54c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2438,7 +2438,7 @@ function shouldIgnoreProviderEvent(event: RuntimeEvent): boolean {
function directTurnClaimIsCurrent(botId: string, claimId: string, threadId: string): boolean {
const claim = directTurnDispatchClaims.get(threadId);
- return claim?.id === claimId && claim.botId === botId && store.taskByThread(botId, threadId)?.busy === true;
+ return !companyShutdown && claim?.id === claimId && claim.botId === botId && store.taskByThread(botId, threadId)?.busy === true;
}
function directTurnClaimExists(botId: string, claimId: string, threadId: string): boolean {
@@ -8502,9 +8502,6 @@ async function startTurn(
forgetTurnCheckpoint(threadId);
if (before) turnCheckpoints.set(threadId, { botId: bot.id, cwd: checkpointCwd, hash: before, pin: dispatchClaimId });
}
- if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) {
- throw new DirectTurnSetupCancelled("turn stopped before dispatch");
- }
// One bot snapshot for the browser bearer, setupModeActive and the prompt's soul, so a soul saved mid-dispatch cannot split them.
const liveBot = store.bot(bot.id);
const setupMode =
@@ -8622,6 +8619,9 @@ async function startTurn(
conversations: commsDepth === 0 && !coordinationNode && !opts?.automationSource && !opts?.unattended,
userName: userNameFor(threadId),
});
+ if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) {
+ throw new DirectTurnSetupCancelled("turn stopped before dispatch");
+ }
runningTurnEngines.set(threadId, instance);
// Re-decide from the soul actually sent, except on an unattended continuation wake, so a session started under an old soul never survives a soul change by laundering its record.
const dispatchedConfig = sessionConfig(liveBot?.soul ?? bot.soul);
@@ -8659,7 +8659,7 @@ async function startTurn(
...(integrations.browser && browserIsThePlace(plan) ? { preloadBrowserTools: true } : {}),
...settingsTurnFields(cfg, DATA_DIR, managedPolicy.restrictsMcp()),
cwd,
- }, route.quickModel ? { model, own: bot.modelSelection, onFallback: () => store.patchMessage(threadId, userMessage.id, { quickModel: undefined }) } : undefined)), () => !directTurnClaimExists(bot.id, dispatchClaimId, threadId), async () => {
+ }, route.quickModel ? { model, own: bot.modelSelection, onFallback: () => store.patchMessage(threadId, userMessage.id, { quickModel: undefined }) } : undefined)), () => companyShutdown || !directTurnClaimExists(bot.id, dispatchClaimId, threadId), async () => {
await instance.adapter.interruptTurn(threadId).catch(() => {});
});
if (dispatch.cancelled) {
@@ -9032,7 +9032,7 @@ routines = new RoutineManager({
}
},
startTurn: async (botId, threadId, prompt, runOn, triggerSource, onDispatchError) => {
- await startTurn(botId, prompt, { threadId, runOn, automationSource: triggerSource, onDispatchError });
+ if (!companyShutdown) await startTurn(botId, prompt, { threadId, runOn, automationSource: triggerSource, onDispatchError });
},
startGoal: async (groupId, threadId, prompt, coordinatorBotId, runId, _onDispatchError) => {
if (!groupId) {
diff --git a/server/routine-checks-engine.test.ts b/server/routine-checks-engine.test.ts
index 494f012a1b..8eaec92af5 100644
--- a/server/routine-checks-engine.test.ts
+++ b/server/routine-checks-engine.test.ts
@@ -11,7 +11,7 @@ const MINUTE = 60_000;
const dirs: string[] = [];
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
-function harness(options: { bot?: () => "ready" | "busy" | "missing" } = {}) {
+function harness(options: { bot?: () => "ready" | "busy" | "missing"; turn?: () => Promise<void> } = {}) {
const dir = mkdtempSync(join(tmpdir(), "omb-checks-"));
dirs.push(dir);
let now = new Date(2026, 9, 22, 9, 0, 0).getTime();
@@ -38,7 +38,7 @@ function harness(options: { bot?: () => "ready" | "busy" | "missing" } = {}) {
const make = () => new RoutineManager({
file: join(dir, "routines.json"), now: () => now, botState: options.bot ?? (() => "ready"),
createTask: () => ({ threadId: `thread-${++thread}` }),
- startTurn: async (botId, threadId, prompt) => { started.push({ botId, threadId, prompt }); },
+ startTurn: async (botId, threadId, prompt) => { started.push({ botId, threadId, prompt }); await options.turn?.(); },
onRunFailed: (run, alert) => failed.push({ run, alert }),
onRunDeferred: (run) => deferred.push(run),
checks,
@@ -66,6 +66,61 @@ function harness(options: { bot?: () => "ready" | "busy" | "missing" } = {}) {
const past = (h: ReturnType<typeof harness>, ms: number) => { h.advance(ms); return h.tick(); };
describe("routines with checks", () => {
+ it.each(["manual", "scheduled"])("drops a %s check that finishes after close without changing its receipt", async (mode) => {
+ const h = harness();
+ const routine = h.watch();
+ let open!: () => void;
+ h.gate.wait = new Promise((resolve) => { open = resolve; });
+ h.answers.push({ run: { prompt: "Late inbox result", key: "late-batch" } });
+ if (mode === "manual") h.manager.runNow(routine.id);
+ else h.advance(CHECK_BOOT_HOLD_MS + 15 * MINUTE);
+ await h.tick();
+ const before = readFileSync(h.file, "utf8");
+ h.manager.close();
+ open();
+ await h.settle();
+ expect(h.started).toEqual([]);
+ expect(h.released).toEqual(["late-batch"]);
+ expect(readFileSync(h.file, "utf8")).toBe(before);
+ await h.tick();
+ expect(h.asked).toHaveLength(1);
+ });
+
+ it("does not restart scheduling or accept a new manual run after close", async () => {
+ const h = harness();
+ const routine = h.watch({ runOnStartup: true });
+ h.manager.close();
+ const before = readFileSync(h.file, "utf8");
+ try {
+ h.advance(CHECK_BOOT_HOLD_MS + 15 * MINUTE);
+ h.manager.start();
+ await h.tick();
+ expect(h.manager.runNow(routine.id)).toBeNull();
+ expect(h.asked).toEqual([]);
+ expect(h.started).toEqual([]);
+ expect(readFileSync(h.file, "utf8")).toBe(before);
+ } finally { h.manager.stop(); }
+ });
+
+ it("keeps the next queued run untouched when close happens while dispatch is awaited", async () => {
+ let open!: () => void;
+ const pending = new Promise<void>((resolve) => { open = resolve; });
+ const h = harness({ turn: () => pending });
+ const routine = h.watch({ checks: null });
+ const first = h.manager.runNow(routine.id)!;
+ const second = h.manager.runNow(routine.id)!;
+ await h.settle();
+ expect(h.started).toHaveLength(1);
+ h.manager.close();
+ open();
+ await h.settle();
+ expect(h.started).toHaveLength(1);
+ expect(h.manager.listRuns()).toEqual([
+ expect.objectContaining({ id: first.id, status: "running" }),
+ expect.objectContaining({ id: second.id, status: "queued" }),
+ ]);
+ });
+
it.each(["run", "trouble", "quiet"])("rechecks an edited definition before using a pending %s result", async (result) => {
const h = harness();
const routine = h.watch({ botId: "bot-a", checks: ["mail"], prompt: "Old mail instructions" });
diff --git a/server/routines.ts b/server/routines.ts
index a460441c2d..6ab4cddfd7 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -733,6 +733,7 @@ export class RoutineManager {
}
runNow(id: string, request?: RoutineRequestCommitFor<"run_now">): RoutineRun | null {
+ if (this.closing) return null;
if (request) {
const receipt = this.matchingRoutineRequestReceipt(request);
if (receipt) {
@@ -950,7 +951,7 @@ export class RoutineManager {
private tickInBackground(): void { this.tick().catch((error) => console.error("routines: a scheduler pass failed", error)); }
start() {
- if (this.timer) return;
+ if (this.closing || this.timer) return;
if (!this.startupRunsQueued) this.startupRunsQueued = this.queueStartupRuns();
this.tickInBackground();
this.timer = setInterval(() => this.tickInBackground(), 10_000);
@@ -1006,7 +1007,7 @@ export class RoutineManager {
}
async tick(): Promise<void> {
- if (this.ticking) return;
+ if (this.closing || this.ticking) return;
this.ticking = true;
try {
const now = this.now();
@@ -1015,7 +1016,7 @@ export class RoutineManager {
activeMs(run, now) < run.timeoutMinutes * 60_000) continue;
await this.stopRun(run, `Stopped after reaching the ${run.timeoutMinutes}-minute run limit`, "limit-reached");
}
- const isDue = (routine: Routine) => routine.enabled && this.targetState(routine) !== "missing" && (!routine.checks
+ const isDue = (routine: Routine) => !this.closing && routine.enabled && this.targetState(routine) !== "missing" && (!routine.checks
? routine.nextRunAt != null && routine.nextRunAt <= now
: now >= this.bootedAt + CHECK_BOOT_HOLD_MS && [routine.nextRunAt, routine.wakeAt].some((at) => at != null && at <= now));
// An unanswered wait gives way to its routine's next occurrence, which would otherwise be skipped behind it.
@@ -1084,6 +1085,7 @@ export class RoutineManager {
// Oldest first, by id: a rollback across awaits can replace the run objects.
for (const id of this.runs.map((run) => run.id)) {
+ if (this.closing) return;
const run = this.runs.find((candidate) => candidate.id === id);
if (!run || run.status !== "queued" || (run.retryAt ?? 0) > now) continue;
const triggerSource = run.triggerSource ?? (run.manual ? "manual" : "schedule");
@@ -1197,7 +1199,7 @@ export class RoutineManager {
* Nothing new leaves no run behind a scheduled check, and a quiet completed one behind a manual check. */
private async runChecks(routineId: string, hold: CheckHold | undefined, manual?: string): Promise<void> {
const hook = this.options.checks, key = manual ?? routineId, routine = this.routines.find((candidate) => candidate.id === routineId);
- if (!hook || !routine || this.checking.has(key)) return;
+ if (this.closing || !hook || !routine || this.checking.has(key)) return;
const revision = routine.updatedAt;
this.checking.add(key);
let result: RoutineCheckResult;
@@ -1211,7 +1213,7 @@ export class RoutineManager {
}
const current = this.routines.find((candidate) => candidate.id === routineId);
const queued = manual === undefined ? undefined : this.runs.find((run) => run.id === manual && run.status === "queued");
- if (!current?.checks || (manual === undefined ? !current.enabled : !queued)) {
+ if (this.closing || !current?.checks || (manual === undefined ? !current.enabled : !queued)) {
if (result.run) hook.release(result.run.key);
return;
}