Skip to content

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

Free a chat that an allowed lending card left showing Working (#5023)

Milind Soni1d72099d5c05
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.ts
index 60c35cd03e..76c0014447 100644
--- a/server/drivers/acp/acp.test.ts
+++ b/server/drivers/acp/acp.test.ts
@@ -390,7 +390,7 @@ describe("ACP turns (fake CLI)", () => {
// The stall watchdog sees no tool left running, so the turn's own silence limit applies.
let now = 0;
const limits: number[] = [];
- const dog = new TurnWatchdog({ stallMs: 10, toolStallMs: 1_000, checkMs: 60_000, now: () => now, onStall: (_turn, silentMs) => limits.push(silentMs) });
+ const dog = new TurnWatchdog({ stallMs: 10, toolStallMs: 1_000, parkedStallMs: 10_000, checkMs: 60_000, now: () => now, onStall: (_turn, silentMs) => limits.push(silentMs) });
dog.watch("t-finished-tools", "bot");
for (const event of recorder.events) dog.observe(event);
now = 10;
diff --git a/server/host/idle-threads.test.ts b/server/host/idle-threads.test.ts
new file mode 100644
index 0000000000..8ab5e23f82
--- /dev/null
+++ b/server/host/idle-threads.test.ts
@@ -0,0 +1,124 @@
+import { rmSync } from "node:fs";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { DATA_DIR } from "../config.ts";
+import type { RoutineRun } from "../routines.ts";
+import { Store } from "../store.ts";
+import { createIdleThreads } from "./idle-threads.ts";
+import { createPersonStop } from "./person-stop.ts";
+
+type Hold = "setup" | "dispatching" | "engine";
+
+function fixture({ routineRun = false } = {}) {
+ const store = new Store(() => ({ instanceId: "claude", model: "claude-sonnet-5" }));
+ const bot = store.createBot({ name: "Postie" });
+ const thread = bot.threadId;
+ const task = () => store.taskByThread(bot.id, thread)!;
+ const claims = new Map<string, { phase: "setup" | "dispatching" }>();
+ const engines = new Set<string>();
+ const generations = new Map([[thread, "gen-1"]]);
+ const holds = { set: (threadId: string, hold: Hold) => { if (hold === "engine") engines.add(threadId); else claims.set(threadId, { phase: hold }); } };
+ const state = { newerTurnDuringInterrupt: false };
+ const settled: string[] = [], released: string[] = [], cancelledRuns: string[] = [];
+ let drains = 0;
+ const idle = createIdleThreads({
+ store, claims, generations,
+ engineTurn: (threadId) => engines.has(threadId),
+ settle: (_botId, threadId) => { settled.push(threadId); },
+ releaseComputer: (_botId, threadId) => { released.push(threadId); },
+ drain: () => { drains += 1; },
+ });
+ // As index.ts's interrupts, a person's or a routine's: the dispatch claim goes at once, while an engine's turn is only asked to end.
+ const interrupt = (threadId: string) => {
+ claims.delete(threadId);
+ if (state.newerTurnDuringInterrupt) generations.set(threadId, "gen-2");
+ };
+ const run = { id: "run-1", threadId: thread } as RoutineRun;
+ const stop = createPersonStop({
+ store, handoffs: () => ({ stoppedByPerson: () => {} }) as never,
+ routines: () => (routineRun ? { activeBotRunForBot: () => run, cancelRun: async (id: string) => { cancelledRuns.push(id); interrupt(thread); return null; } } : null),
+ interruptDirectThread: async (_botId, threadId) => interrupt(threadId),
+ stopping: idle.stopping, clearUnattended: () => {}, markStopped: () => {}, stopGoal: () => {},
+ working: () => true, asking: () => false, language: () => undefined,
+ });
+ return { store, bot, thread, task, holds, state, settled, released, cancelledRuns, drains: () => drains, idle, stop };
+}
+
+describe("a conversation shown working with nothing running for it (server/host/idle-threads.ts)", () => {
+ beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+
+ it("is freed by the person's Stop, though no turn ever started there", async () => {
+ const { store, bot, thread, task, settled, released, drains, stop } = fixture();
+ store.setTaskActivity(bot.id, thread, "working");
+ await stop.stopThreadForPerson(bot.id, thread);
+ expect(task()).toMatchObject({ activity: "idle", busy: false });
+ expect(store.bot(bot.id)).toMatchObject({ activity: "idle", busy: false });
+ expect(settled).toEqual([thread]);
+ expect(released).toEqual([thread]);
+ expect(drains()).toBe(1);
+ });
+
+ it("is freed at once by a Stop during a setup that never returns, which lets go of its computer", async () => {
+ const { store, bot, thread, task, holds, settled, released, drains, stop } = fixture();
+ holds.set(thread, "setup");
+ store.setTaskActivity(bot.id, thread, "working");
+ await stop.stopThreadForPerson(bot.id, thread);
+ expect(task()).toMatchObject({ activity: "idle", busy: false });
+ expect(settled).toEqual([thread]);
+ expect(released).toEqual([thread]);
+ expect(drains()).toBe(1);
+ });
+
+ it("is freed by a Stop that cancels a routine run whose setup never returns", async () => {
+ const { store, bot, thread, task, holds, released, cancelledRuns, stop } = fixture({ routineRun: true });
+ holds.set(thread, "setup");
+ store.setTaskActivity(bot.id, thread, "working");
+ await stop.stopThreadForPerson(bot.id, thread);
+ expect(cancelledRuns).toEqual(["run-1"]);
+ expect(task()).toMatchObject({ activity: "idle", busy: false });
+ expect(released).toEqual([thread]);
+ });
+
+ it.each(["dispatching", "engine"] as const)("a Stop leaves a turn an engine has (%s) to that turn's own end", async (hold) => {
+ for (const routineRun of [false, true]) {
+ const { store, bot, thread, task, holds, settled, released, drains, stop } = fixture({ routineRun });
+ holds.set(thread, hold);
+ store.setTaskActivity(bot.id, thread, "working");
+ await stop.stopThreadForPerson(bot.id, thread);
+ expect(task()).toMatchObject({ activity: "working", busy: true });
+ expect(settled).toEqual([]);
+ expect(released).toEqual([]);
+ expect(drains()).toBe(0);
+ }
+ });
+
+ it("a Stop never frees a newer turn that began while it interrupted, nor touches that turn's computer", async () => {
+ const { store, bot, thread, task, holds, state, settled, released, stop } = fixture();
+ holds.set(thread, "setup");
+ state.newerTurnDuringInterrupt = true;
+ store.setTaskActivity(bot.id, thread, "working");
+ await stop.stopThreadForPerson(bot.id, thread);
+ expect(task()).toMatchObject({ activity: "working", busy: true });
+ expect(settled).toEqual([]);
+ expect(released).toEqual([]);
+ });
+
+ it("lists for the watchdog only what nothing holds, and frees only that", () => {
+ const { store, bot, thread, task, holds, settled, released, idle } = fixture();
+ const other = store.createTask(bot.id, "Other", false)!.threadId;
+ const resting = store.createTask(bot.id, "Resting", false)!.threadId;
+ store.setTaskActivity(bot.id, thread, "working");
+ store.setTaskActivity(bot.id, other, "working");
+ store.setTaskActivity(bot.id, resting, "waiting-on-you", true);
+ holds.set(other, "setup");
+ expect(idle.unheld()).toEqual([{ threadId: thread, botId: bot.id }]);
+ idle.free(bot.id, other);
+ idle.free(bot.id, resting);
+ expect(store.taskByThread(bot.id, other)).toMatchObject({ activity: "working", busy: true });
+ expect(store.taskByThread(bot.id, resting)).toMatchObject({ activity: "waiting-on-you", busy: false });
+ idle.free(bot.id, thread);
+ expect(task()).toMatchObject({ activity: "idle", busy: false });
+ expect(settled).toEqual([thread]);
+ expect(released).toEqual([thread]);
+ });
+});
diff --git a/server/host/idle-threads.ts b/server/host/idle-threads.ts
new file mode 100644
index 0000000000..3911c3bfaf
--- /dev/null
+++ b/server/host/idle-threads.ts
@@ -0,0 +1,50 @@
+// A conversation shown working while nothing runs for it holds every message and hand-off queued behind it, and no turn's
+// end will ever free it. A person's Stop frees one at once and the turn watchdog frees one nobody stops. A turn an engine
+// has, or is being handed, is left to its own end, so that turn's late events can never settle a newer one.
+import type { Store } from "../store.ts";
+
+export interface IdleThreadsDeps {
+ store: Pick<Store, "bots" | "tasks" | "taskByThread" | "setTaskActivity">;
+ /** Each thread's direct turn dispatch claim: "setup" before any engine has the turn, "dispatching" while one is handed it. */
+ claims: ReadonlyMap<string, { phase: "setup" | "dispatching" }>;
+ /** Each thread's direct turn generation. */
+ generations: ReadonlyMap<string, string>;
+ /** An engine has the thread's turn, or that turn's end is still settling. */
+ engineTurn(threadId: string): boolean;
+ /** Ends what the harness keeps for a turn on the thread: its watch, follow-ups and screen. */
+ settle(botId: string, threadId: string): void;
+ /** Lets go of the computer the thread's turn held: its claims, Local VM lease and remote computer. */
+ releaseComputer(botId: string, threadId: string): void;
+ drain(): void;
+}
+
+export function createIdleThreads(deps: IdleThreadsDeps) {
+ const { store } = deps;
+ const engineHolds = (threadId: string) => deps.claims.get(threadId)?.phase === "dispatching" || deps.engineTurn(threadId);
+ const held = (threadId: string) => deps.claims.has(threadId) || engineHolds(threadId);
+
+ function free(botId: string, threadId: string): void {
+ if (held(threadId) || !store.taskByThread(botId, threadId)?.busy) return;
+ deps.settle(botId, threadId);
+ deps.releaseComputer(botId, threadId);
+ store.setTaskActivity(botId, threadId, "idle");
+ deps.drain();
+ }
+
+ return {
+ free,
+ /** The conversations shown working that nothing holds but, maybe, a watched turn. */
+ unheld(): Array<{ threadId: string; botId: string }> {
+ return store.bots.flatMap((bot) => store.tasks(bot.id).flatMap((task) => (task.busy && !held(task.threadId) ? [{ threadId: task.threadId, botId: bot.id }] : [])));
+ },
+ /** Read before a Stop's interrupt drops the thread's dispatch claim. What it returns frees the thread once interrupted,
+ * unless an engine had the turn or another turn began meanwhile. */
+ stopping(botId: string, threadId: string): () => void {
+ const generation = deps.generations.get(threadId);
+ if (engineHolds(threadId)) return () => {};
+ return () => {
+ if (deps.generations.get(threadId) === generation) free(botId, threadId);
+ };
+ },
+ };
+}
diff --git a/server/host/lending-lifts.test.ts b/server/host/lending-lifts.test.ts
index 90a726d5a6..18dcb9c684 100644
--- a/server/host/lending-lifts.test.ts
+++ b/server/host/lending-lifts.test.ts
@@ -1,8 +1,14 @@
-import { describe, expect, it, vi } from "vitest";
+import { rmSync } from "node:fs";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { CUSTOM_SECRET_TARGET } from "../../shared/credential-request.ts";
import { parseOptionsCardInput } from "../../shared/options-card.ts";
import { liveDecisionRefusal } from "../../shared/live-approval.ts";
+import { CARRY_ON_MS } from "../computer-asks.ts";
+import { DATA_DIR } from "../config.ts";
import "../server-line-packs.ts";
+import { Store } from "../store.ts";
import { createLendingLifts, handedInSince, type LendingLiftDeps } from "./lending-lifts.ts";
+import { createPersonWaits } from "./person-waits.ts";
const OWNER = "p_owner";
@@ -262,3 +268,101 @@ describe("the card that lifts a lock on the lent computer (server/host/lending-l
expect(world().answer("something-else", "allow")).toBeNull();
});
});
+
+describe("Allow on the card, in a conversation whose waiting state follows its open cards", () => {
+ beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+
+ function conversation({ stopped = false, rejects = false } = {}) {
+ const store = new Store(() => ({ instanceId: "claude", model: "claude-sonnet-5" }));
+ createPersonWaits({ store, notify: () => {}, threadsWithCards: () => [] });
+ const bot = store.createBot({ name: "Postmeister" });
+ const thread = bot.threadId;
+ const request = store.appendMessage(thread, { role: "user", kind: "text", text: "Save it into my folder" });
+ const task = () => store.taskByThread(bot.id, thread)!;
+ const continued: unknown[] = [];
+ const timers: Array<() => void> = [];
+ let at = 0;
+ const lifts = createLendingLifts({
+ store,
+ memory: { info: () => ({ token: "t1", changed: [] }), accept: () => true },
+ words: () => undefined, ownersAnswer: () => true, stopped: () => stopped,
+ // As index.ts's threadBusy reads a thread with no dispatch claim.
+ threadBusy: (botId, threadId) => store.taskByThread(botId, threadId)?.busy === true,
+ queued: () => false,
+ continueRequest: async (...args) => { continued.push(args); if (rejects) throw new Error("the engine is gone"); },
+ language: () => undefined, device: () => "PC", notify: () => {}, decide: () => {},
+ setTimer: ((run: () => void) => { timers.push(run); return {}; }) as never,
+ now: () => at,
+ });
+ /** The turn answering the request asks for a password, then for the PC, and leaves both cards open. */
+ const turnRaisesCards = () => {
+ store.setTaskActivity(bot.id, thread, "working");
+ store.appendMessage(thread, { role: "bot", kind: "secret", text: "enter it", secret: { target: CUSTOM_SECRET_TARGET, label: "Share password", description: "", reason: "To open the share.", placeholder: "", helpUrl: "", requestKey: "k", delivery: "ref" } });
+ expect(lifts.raise({ botId: bot.id, threadId: thread, requestMessageId: request.id, memoryChanged: false, outside: true })).toBe("open");
+ };
+ const allow = () => lifts.resolve(thread, store.messagesFor(thread).find((line) => line.card?.lendingLift)!.card!.requestId!, "allow");
+ const runTimers = () => { while (timers.length) { at += 5_000; timers.shift()!(); } };
+ return { store, bot, thread, task, continued, timers, turnRaisesCards, allow, runTimers, later: (ms: number) => { at += ms; } };
+ }
+
+ it("never shows a conversation resting on its cards working: the request goes on at once", () => {
+ const { store, bot, thread, task, continued, turnRaisesCards, allow } = conversation();
+ turnRaisesCards();
+ store.setTaskActivity(bot.id, thread, "idle");
+ expect(task()).toMatchObject({ activity: "waiting-on-you", busy: false });
+ expect(allow()).toEqual({ status: 200, body: { ok: true, outcome: "allowed-once" } });
+ expect(task()).toMatchObject({ activity: "waiting-on-you", busy: false });
+ expect(continued).toEqual([[bot.id, expect.stringContaining("Carry on"), expect.objectContaining({ threadId: thread, cardContinuation: true })]]);
+ });
+
+ it.each([
+ ["the person stopped the conversation", { stopped: true }],
+ ["the continuation can't start", { rejects: true }],
+ ])("leaves nothing working when the request doesn't go on: %s", async (_why, options) => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const { store, bot, thread, task, turnRaisesCards, allow } = conversation(options);
+ turnRaisesCards();
+ store.setTaskActivity(bot.id, thread, "idle");
+ allow();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(task()).toMatchObject({ busy: false });
+ expect(store.bot(bot.id)).toMatchObject({ busy: false });
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("leaves nothing working when someone wrote since", () => {
+ const { store, bot, thread, task, continued, turnRaisesCards, allow } = conversation();
+ turnRaisesCards();
+ store.setTaskActivity(bot.id, thread, "idle");
+ store.appendMessage(thread, { role: "user", kind: "text", text: "Never mind" });
+ allow();
+ expect(task()).toMatchObject({ busy: false });
+ expect(continued).toEqual([]);
+ });
+
+ it("a turn still running when they allow it goes back to working, and the request goes on once it ends", () => {
+ const { store, bot, thread, task, continued, timers, turnRaisesCards, allow } = conversation();
+ turnRaisesCards();
+ expect(task()).toMatchObject({ activity: "waiting-on-you", busy: true });
+ allow();
+ expect(task()).toMatchObject({ activity: "working", busy: true });
+ expect(continued).toEqual([]);
+ store.setTaskActivity(bot.id, thread, "idle");
+ timers.shift()!();
+ expect(continued).toHaveLength(1);
+ });
+
+ it("gives up on a conversation that stays busy, which its own turn then frees", () => {
+ const { store, bot, thread, task, continued, turnRaisesCards, allow, runTimers, later } = conversation();
+ turnRaisesCards();
+ allow();
+ later(CARRY_ON_MS);
+ runTimers();
+ expect(continued).toEqual([]);
+ store.setTaskActivity(bot.id, thread, "idle");
+ expect(task()).toMatchObject({ activity: "waiting-on-you", busy: false });
+ });
+});
diff --git a/server/host/lending-lifts.ts b/server/host/lending-lifts.ts
index 12e2761d7c..df14341e12 100644
--- a/server/host/lending-lifts.ts
+++ b/server/host/lending-lifts.ts
@@ -13,6 +13,7 @@ import { buildNotification, type Notification } from "../notify.ts";
import { redactSecretsInText } from "../redact.ts";
import { serverLine } from "../server-lines.ts";
import type { Message, Store } from "../store.ts";
+import { turnWaitedOnPerson } from "../waiting-on-person.ts";
import { workspaceDir } from "../workspace.ts";
const TOOL = "lending_lift";
@@ -181,7 +182,7 @@ export function createLendingLifts(deps: LendingLiftDeps) {
// When they allowed it: work handed in after this shuts it again.
store.patchMessage(threadId, message.id, { card: { ...card, answered: allowed ? "allow" : "deny", ...(allowed ? { lendingLift: { ...lift, allowedAt: now() } } : {}) } });
deps.decide({ threadId, requestId, botId, botName: bot?.name, tool: TOOL, summary: card.title, decision: allowed ? "user-approved" : "user-denied", source: "user" });
- if (store.projectBotForTask(botId, threadId)?.activity === "waiting-on-you") store.setTaskActivity(botId, threadId, "working");
+ if (turnWaitedOnPerson(store.taskByThread(botId, threadId))) store.setTaskActivity(botId, threadId, "working");
if (allowed && store.groupByThread(threadId)) {
store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: serverLine(deps.language(threadId), "server.lendingLift.askAgain"), ok: true } });
} else if (allowed) carryOn(botId, threadId, lift.requestMessageId, now());
diff --git a/server/host/person-stop.test.ts b/server/host/person-stop.test.ts
index 8945ae20c1..5e65a6b8d5 100644
--- a/server/host/person-stop.test.ts
+++ b/server/host/person-stop.test.ts
@@ -11,7 +11,7 @@ function world(over: { working?: string[]; asking?: boolean; threads?: string[]
bot: () => ({ name: "Ada" }), botByThread: () => undefined, groupByThread: () => undefined, taskByThread: () => undefined,
tasks: () => (over.threads ?? ["t", "other"]).map((threadId) => ({ threadId })),
} as unknown as PersonStopDeps["store"],
- routines: () => null, handoffs: () => ({ stoppedByPerson: () => {} }) as never, interruptDirectThread: async (_botId, threadId) => { stopped.push(threadId); },
+ routines: () => null, handoffs: () => ({ stoppedByPerson: () => {} }) as never, interruptDirectThread: async (_botId, threadId) => { stopped.push(threadId); }, stopping: () => () => {},
clearUnattended: () => {}, markStopped: () => {}, stopGoal: () => {},
working: (_botId, threadId) => (over.working ?? []).includes(threadId), asking: () => over.asking === true, language: () => undefined,
});
diff --git a/server/host/person-stop.ts b/server/host/person-stop.ts
index 85fb3a00f7..27b18dec08 100644
--- a/server/host/person-stop.ts
+++ b/server/host/person-stop.ts
@@ -12,6 +12,8 @@ export interface PersonStopDeps {
routines(): Pick<RoutineManager, "activeBotRunForBot" | "cancelRun"> | null;
handoffs(): Pick<Handoffs, "stoppedByPerson">;
interruptDirectThread(botId: string, threadId: string): Promise<void>;
+ /** Read before the interrupt: what frees the thread once it is interrupted, when no turn's end will. */
+ stopping(botId: string, threadId: string): () => void;
clearUnattended(threadId: string): void;
/** Remembers that the person stopped the turn running in this thread, so it ends as their stop. */
markStopped(threadId: string): void;
@@ -44,14 +46,15 @@ export function createPersonStop(deps: PersonStopDeps) {
async function stopThreadForPerson(botId: string, threadId: string): Promise<void> {
const routines = deps.routines();
const routine = routines?.activeBotRunForBot(botId);
- if (routine?.threadId === threadId) {
- await routines!.cancelRun(routine.id);
- return;
+ const free = deps.stopping(botId, threadId);
+ if (routine?.threadId === threadId) await routines!.cancelRun(routine.id);
+ else {
+ deps.handoffs().stoppedByPerson(threadId);
+ deps.markStopped(threadId);
+ deps.stopGoal(threadId);
+ await deps.interruptDirectThread(botId, threadId);
}
- deps.handoffs().stoppedByPerson(threadId);
- deps.markStopped(threadId);
- deps.stopGoal(threadId);
- await deps.interruptDirectThread(botId, threadId);
+ free();
}
/** Only a message made of stop words, from a person, acts as Stop: it is recorded, and never reaches the turn it ends. With no
diff --git a/server/index.ts b/server/index.ts
index c6d8a82a4a..ec8c7232b4 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -335,7 +335,7 @@ import { Handoffs, handedStateUsable, isContextMessage, recordHanded, renderUnse
import { extractReplayImages, extractTurnImages, videoFramesWithin } from "./turn-images.ts";
import { callTitleExcerpt } from "./thread-title.ts";
import { generateThreadTitle, llmThreadTitlesEnabled } from "./thread-title-generate.ts";
-import { stallLimitMs, TurnWatchdog } from "./turn-watchdog.ts";
+import { engineProcessGone, stallLimitMs, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts";
import { TurnResources, type TurnOwner } from "./turn-resources.ts";
import {
ensureWorkspace,
@@ -2816,7 +2816,7 @@ const actingPeople = createActingPeople({ store, direct: (threadId) => directReq
const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, lending: sharedComputers, principal: CLOUD_HOME_LENDER, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn,
refusal: (turn) => sharedComputerPrincipal(turn) ? null : cloudLendingRefusalForBot(turn) ?? "This conversation can't use your computer.", request: (threadId) => directRequestOwners.get(threadId), active: (turn) => internalCapabilityIsActive(turn as InternalCapability) }) : null;
const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersonStop({
- store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,
+ store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, stopping: (botId, threadId) => idleThreads.stopping(botId, threadId), clearUnattended,
stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)), working: (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId), asking: (threadId) => coordinator.awaitingAnswer(threadId) || Boolean(openPersonCard(threadId)), language: threadLanguage,
}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });
const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
@@ -4991,8 +4991,8 @@ function stoppedTurnText(threadId: string, turnId: string | undefined, cause?: s
});
}
const watchdog = new TurnWatchdog({
- stallMs: TURN_STALL_MS, toolStallMs: TOOL_STALL_MS,
- checkMs: 60_000,
+ stallMs: TURN_STALL_MS, toolStallMs: TOOL_STALL_MS, parkedStallMs: COMPUTER_WAIT_MAX_MS + TURN_STALL_MS,
+ checkMs: 60_000, unheld: { threads: () => idleThreads.unheld(), free: (threadId, botId) => idleThreads.free(botId, threadId) }, engineGone: (turn) => engineProcessGone(runningTurnInstance(botForThread(turn.botId, turn.threadId), turn.threadId)?.adapter, turn.threadId),
onStall: (turn, silentMs) => {
const stalledResourceOwner = turnResourceOwners.get(turn.threadId);
const stalledGeneration = directTurnGenerationByThread.get(turn.threadId);
@@ -5062,7 +5062,7 @@ const watchdog = new TurnWatchdog({
release.unref?.();
},
});
-watchdog.start();
+watchdog.start(); const idleThreads = createIdleThreads({ store, claims: directTurnDispatchClaims, generations: directTurnGenerationByThread, drain: drainQueuedSends, engineTurn: (threadId) => runningTurnEngines.has(threadId) || liveTurns.running(threadId) !== undefined || settlingTurns.has(threadId), settle: (botId, threadId) => { watchdog.settle(threadId); settleDirectFollowup(directTurnGenerationByThread.get(threadId)); stopScreenPoller(botId, threadId); directTurnBots.delete(threadId); }, releaseComputer: (botId, threadId) => { releaseTurnResources(turnResourceOwners.get(threadId)); releaseLocalVmThread(threadId); vpsThreadEnded(botId, threadId); } });
bus.subscribe((event: RuntimeEvent) => {
if (shouldIgnoreProviderEvent(event)) return;
@@ -7929,7 +7929,7 @@ async function beginTurn(
attachCustomMcp(integrations, { ...custom, ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: dispatchClaimId }) }, cfg, { botId: bot.id, threadId });
if (Object.keys(custom).length) Object.assign(integrations, chatAppsMcp.turnMounts(custom, bot.toolScope));
}
- const worksInWorkspace = supportsWorkspaceFiles(instance.driverKind);
+ if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) throw new DirectTurnSetupCancelled("turn stopped while its tools were prepared"); const worksInWorkspace = supportsWorkspaceFiles(instance.driverKind);
if (worksInWorkspace) {
ensureWorkspace(bot.id, appLanguage());
if (bot.memoryEnabled !== false) beginMemoryTurn(teamHost.layer(bot.id, threadId), threadId); botBox.lend(bot.id, threadId, teamHost.layerDirs(bot.id, threadId));
@@ -15085,7 +15085,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
// No await between comparing the exact lease and revoking it.
owner.stopped = true;
handoffs.stoppedByPerson(threadId); personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId));
- await interruptDirectThread(m[1], threadId);
+ const free = idleThreads.stopping(m[1], threadId); await interruptDirectThread(m[1], threadId); free();
return json(res, 200, { ok: true, outcome: "stopped" });
}
diff --git a/server/turn-watchdog.test.ts b/server/turn-watchdog.test.ts
index fe4b4ab08b..ef08cbe9ae 100644
--- a/server/turn-watchdog.test.ts
+++ b/server/turn-watchdog.test.ts
@@ -4,14 +4,15 @@ import ts from "typescript";
import { describe, expect, it, vi } from "vitest";
import { chatNotice, failedNoticeTool } from "./chat-notices.ts";
-import type { RuntimeEvent } from "./contracts.ts";
+import type { ProviderAdapter, RuntimeEvent } from "./contracts.ts";
import { EngineMemory } from "./engine-memory.ts";
import type { Message } from "./store.ts";
import { TurnStops, stoppedTurnOutcome } from "./turn-outcome.ts";
-import { stallLimitMs, TurnWatchdog, type WatchedTurn } from "./turn-watchdog.ts";
+import { engineProcessGone, stallLimitMs, TurnWatchdog, type WatchedTurn } from "./turn-watchdog.ts";
const STALL = 10_000;
const TOOL_STALL = 50_000;
+const PARKED_STALL = 1_000 * STALL;
const base = { eventId: "e1", provider: "claudeAgent", threadId: "t1", createdAt: "2026-01-01T00:00:00.000Z" };
const text: RuntimeEvent = { ...base, type: "content.delta", streamKind: "assistant_text", delta: "working" };
const toolStarted = (itemId: string): RuntimeEvent => ({ ...base, type: "item.started", itemType: "tool", itemId });
@@ -21,16 +22,30 @@ function rig() {
let now = 0;
const stalls: WatchedTurn[] = [];
const limits: number[] = [];
+ const adapters = new Map<string, Pick<ProviderAdapter, "enginePid">>();
+ const alive = new Set<number>();
+ const working: Array<{ threadId: string; botId: string }> = [];
+ const freed: string[] = [];
const dog = new TurnWatchdog({
stallMs: STALL,
toolStallMs: TOOL_STALL,
+ parkedStallMs: PARKED_STALL,
checkMs: 60_000,
+ engineGone: (turn) => engineProcessGone(adapters.get(turn.threadId), turn.threadId, (pid) => alive.has(pid)),
onStall: (turn, silentMs) => { stalls.push(turn); limits.push(silentMs); },
+ unheld: {
+ threads: () => [...working],
+ free: (threadId) => { freed.push(threadId); working.splice(working.findIndex((thread) => thread.threadId === threadId), 1); },
+ },
now: () => now,
});
- return { dog, stalls, limits, tick: (ms: number) => (now += ms) };
+ return { dog, stalls, limits, adapters, alive, working, freed, tick: (ms: number) => (now += ms) };
}
+const ENGINE_PID = 4242;
+/** A driver that tracks its engine process: it names one while the turn is active, and none once it is not. */
+const tracked = (pid: number | undefined): Pick<ProviderAdapter, "enginePid"> => ({ enginePid: () => pid });
+
describe("TurnWatchdog", () => {
it("stalls a silent turn once, and only once", () => {
const { dog, stalls, tick } = rig();
@@ -57,20 +72,73 @@ describe("TurnWatchdog", () => {
expect(stalls).toHaveLength(0);
});
- it("never stalls a turn waiting on a human, however long they take", () => {
- const { dog, stalls, tick } = rig();
+ it("never stalls a turn waiting on a human while its engine may still run it, however long they take", () => {
+ const engines: Array<[string, Pick<ProviderAdapter, "enginePid"> | undefined]> = [
+ ["no engine known", undefined],
+ // An in-process engine (the OpenAI-compatible ask_user path) names no process: that proves nothing about its turn.
+ ["an engine that names no process", {}],
+ ["an engine whose process runs", tracked(ENGINE_PID)],
+ ];
+ for (const [name, adapter] of engines) {
+ const { dog, stalls, adapters, alive, tick } = rig();
+ if (adapter) adapters.set("t1", adapter);
+ alive.add(ENGINE_PID);
+ dog.watch("t1", "bot1");
+ dog.setWaitingOnHuman("t1", true);
+ tick(PARKED_STALL * 2);
+ dog.sweep();
+ expect(stalls, name).toHaveLength(0);
+ dog.setWaitingOnHuman("t1", false);
+ tick(STALL - 1);
+ dog.sweep();
+ expect(stalls, name).toHaveLength(0);
+ tick(2);
+ dog.sweep();
+ expect(stalls, name).toHaveLength(1);
+ }
+ });
+
+ it("stops a parked turn whose engine is known to be gone, once it has been silent past the parked limit", () => {
+ for (const park of ["human", "computer"] as const) {
+ for (const [name, adapter] of [["no process tracked for the turn", tracked(undefined)], ["its process exited", tracked(ENGINE_PID)]] as const) {
+ const { dog, stalls, limits, adapters, tick } = rig();
+ adapters.set("t1", adapter);
+ dog.watch("t1", "bot1");
+ if (park === "human") dog.setWaitingOnHuman("t1", true);
+ else dog.setWaitingOnComputer("t1", true);
+ tick(PARKED_STALL - 1);
+ dog.sweep();
+ expect(stalls, `${park}, ${name}`).toHaveLength(0);
+ expect(dog.answering("bot1"), park).toBe(false);
+ tick(2);
+ dog.sweep();
+ expect(stalls, `${park}, ${name}`).toEqual([expect.objectContaining({ threadId: "t1", botId: "bot1" })]);
+ expect(limits, `${park}, ${name}`).toEqual([PARKED_STALL]);
+ expect(dog.watching("t1"), park).toBe(false);
+ }
+ }
+ });
+
+ it("stops a turn that waited long on a live engine as soon as that engine's process exits", () => {
+ const { dog, stalls, limits, adapters, alive, tick } = rig();
+ adapters.set("t1", tracked(ENGINE_PID));
+ alive.add(ENGINE_PID);
dog.watch("t1", "bot1");
dog.setWaitingOnHuman("t1", true);
- tick(STALL * 100);
+ tick(PARKED_STALL * 3);
dog.sweep();
expect(stalls).toHaveLength(0);
- dog.setWaitingOnHuman("t1", false);
- tick(STALL - 1);
- dog.sweep();
- expect(stalls).toHaveLength(0);
- tick(2);
+ alive.delete(ENGINE_PID);
dog.sweep();
- expect(stalls).toHaveLength(1);
+ expect(limits).toEqual([PARKED_STALL]);
+ });
+
+ it("reads an engine as gone only when its driver tracks a process and that process is not there", () => {
+ expect(engineProcessGone(undefined, "t1")).toBe(false);
+ expect(engineProcessGone({}, "t1")).toBe(false);
+ expect(engineProcessGone(tracked(undefined), "t1")).toBe(true);
+ expect(engineProcessGone(tracked(process.pid), "t1")).toBe(false);
+ expect(engineProcessGone(tracked(ENGINE_PID), "t1", () => false)).toBe(true);
});
it("a settled turn is forgotten", () => {
@@ -190,7 +258,7 @@ describe("TurnWatchdog", () => {
it("does not count the time the computer slept as a turn's silence", () => {
vi.useFakeTimers({ now: 0 });
const stalls: WatchedTurn[] = [];
- const dog = new TurnWatchdog({ stallMs: STALL, toolStallMs: TOOL_STALL, checkMs: 1_000, onStall: (turn) => stalls.push(turn) });
+ const dog = new TurnWatchdog({ stallMs: STALL, toolStallMs: TOOL_STALL, parkedStallMs: PARKED_STALL, checkMs: 1_000, onStall: (turn) => stalls.push(turn) });
try {
dog.start();
dog.watch("t1", "bot1");
@@ -212,7 +280,7 @@ describe("TurnWatchdog", () => {
it("still counts silence across sweeps that are only a little late", () => {
vi.useFakeTimers({ now: 0 });
const stalls: WatchedTurn[] = [];
- const dog = new TurnWatchdog({ stallMs: STALL, toolStallMs: TOOL_STALL, checkMs: 1_000, onStall: (turn) => stalls.push(turn) });
+ const dog = new TurnWatchdog({ stallMs: STALL, toolStallMs: TOOL_STALL, parkedStallMs: PARKED_STALL, checkMs: 1_000, onStall: (turn) => stalls.push(turn) });
try {
dog.start();
dog.watch("t1", "bot1");
@@ -243,6 +311,59 @@ describe("TurnWatchdog", () => {
expect(dog.answering("bot1")).toBe(false);
expect(dog.answering("bot2")).toBe(true);
});
+
+ it("frees a conversation shown working that no turn holds, once it has stayed so for the stall limit", () => {
+ const { dog, working, freed, stalls, tick } = rig();
+ working.push({ threadId: "t1", botId: "bot1" });
+ dog.sweep();
+ tick(STALL - 1);
+ dog.sweep();
+ expect(freed).toEqual([]);
+ tick(1);
+ dog.sweep();
+ expect(freed).toEqual(["t1"]);
+ tick(STALL * 2);
+ dog.sweep();
+ expect(freed).toEqual(["t1"]);
+ expect(stalls).toEqual([]);
+ });
+
+ it("leaves a conversation to the turn it watches, and counts from that turn's end", () => {
+ const { dog, working, freed, tick } = rig();
+ dog.watch("t1", "bot1");
+ working.push({ threadId: "t1", botId: "bot1" });
+ dog.setWaitingOnHuman("t1", true);
+ dog.sweep();
+ tick(STALL * 3);
+ dog.sweep();
+ expect(freed).toEqual([]);
+ dog.settle("t1");
+ dog.sweep();
+ tick(STALL - 1);
+ dog.sweep();
+ expect(freed).toEqual([]);
+ tick(1);
+ dog.sweep();
+ expect(freed).toEqual(["t1"]);
+ });
+
+ it("counts again from the start for a conversation that went back to being held in between", () => {
+ const { dog, working, freed, tick } = rig();
+ working.push({ threadId: "t1", botId: "bot1" });
+ dog.sweep();
+ tick(STALL - 1);
+ working.pop();
+ dog.sweep();
+ working.push({ threadId: "t1", botId: "bot1" });
+ tick(1);
+ dog.sweep();
+ tick(STALL - 1);
+ dog.sweep();
+ expect(freed).toEqual([]);
+ tick(1);
+ dog.sweep();
+ expect(freed).toEqual(["t1"]);
+ });
});
// The harness's stall handler (index.ts), run without starting a server.
diff --git a/server/turn-watchdog.ts b/server/turn-watchdog.ts
index e0d31cb6e7..76a76614cf 100644
--- a/server/turn-watchdog.ts
+++ b/server/turn-watchdog.ts
@@ -1,7 +1,9 @@
-import type { RuntimeEvent } from "./contracts.ts";
+import { processAlive } from "./browser-processes.ts";
+import type { ProviderAdapter, RuntimeEvent } from "./contracts.ts";
-// A turn whose thread emits nothing for stallMs is wedged; waiting on a person or a computer is not a stall.
-// Drivers report a tool only when it starts and when it ends, so a turn with a tool running may stay silent for toolStallMs.
+// A turn whose thread emits nothing for stallMs is wedged; waiting on a person or a computer is not a stall unless the
+// turn's engine is known to have no process left. Drivers report a tool only when it starts and when it ends, so a turn
+// with a tool running may stay silent for toolStallMs.
export interface WatchedTurn {
threadId: string;
botId: string;
@@ -18,6 +20,14 @@ export function stallLimitMs(raw: string | undefined, fallback: number): number
return Number.isFinite(ms) && ms > 0 ? ms : fallback;
}
+/** The engine is known to run no process for the thread's turn: its driver tracks one and has none, or the one it names has
+ * exited. A driver that tracks no process proves nothing, so this is false for it. */
+export function engineProcessGone(adapter: Pick<ProviderAdapter, "enginePid"> | null | undefined, threadId: string, alive = processAlive): boolean {
+ if (!adapter?.enginePid) return false;
+ const pid = adapter.enginePid(threadId);
+ return pid === undefined || !alive(pid);
+}
+
const SUSPENDED_SWEEPS = 3;
const parked = (turn: WatchedTurn): boolean => turn.waitingOnHuman || turn.waitingOnComputer;
@@ -25,14 +35,22 @@ const parked = (turn: WatchedTurn): boolean => turn.waitingOnHuman || turn.waiti
export interface TurnWatchdogOptions {
stallMs: number;
toolStallMs: number;
+ /** The silence that stops a parked turn whose engine is known to be gone: longer than any wait the harness bounds itself. */
+ parkedStallMs: number;
checkMs: number;
- /** silentMs: the silence that stopped the turn, stallMs or toolStallMs. */
+ /** The turn's engine is known to have no process left for it; absent or false, a parked turn waits on. */
+ engineGone?: (turn: WatchedTurn) => boolean;
+ /** silentMs: the silence that stopped the turn, stallMs, toolStallMs or parkedStallMs. */
onStall: (turn: WatchedTurn, silentMs: number) => void;
+ /** The conversations shown working that nothing holds but a watched turn (no dispatch, engine or settling turn): one no
+ * watched turn holds either is freed once it has stayed so for stallMs. */
+ unheld?: { threads(): Iterable<{ threadId: string; botId: string }>; free(threadId: string, botId: string): void };
now?: () => number;
}
export class TurnWatchdog {
private turns = new Map<string, WatchedTurn>();
+ private unheldSince = new Map<string, number>();
private timer: ReturnType<typeof setInterval> | null = null;
private opts: TurnWatchdogOptions;
@@ -63,6 +81,7 @@ export class TurnWatchdog {
if (this.timer) clearInterval(this.timer);
this.timer = null;
this.turns.clear();
+ this.unheldSince.clear();
}
watch(threadId: string, botId: string): void {
@@ -129,11 +148,30 @@ export class TurnWatchdog {
const at = this.now();
for (const turn of this.turns.values()) {
if (sleptMs) turn.lastEventAt = Math.min(at, turn.lastEventAt + sleptMs);
- if (parked(turn)) continue;
- const silentMs = turn.runningTools.size > 0 ? Math.max(this.opts.stallMs, this.opts.toolStallMs) : this.opts.stallMs;
- if (at - turn.lastEventAt < silentMs) continue;
+ const silentMs = this.silenceLimit(turn);
+ if (silentMs === null || at - turn.lastEventAt < silentMs) continue;
this.turns.delete(turn.threadId);
this.opts.onStall(turn, silentMs);
}
+ this.freeUnheld(at);
+ }
+
+ /** null: the turn may wait on, parked while its engine is not known to be gone. */
+ private silenceLimit(turn: WatchedTurn): number | null {
+ if (parked(turn)) return this.opts.engineGone?.(turn) ? this.opts.parkedStallMs : null;
+ return turn.runningTools.size > 0 ? Math.max(this.opts.stallMs, this.opts.toolStallMs) : this.opts.stallMs;
+ }
+
+ private freeUnheld(at: number): void {
+ const unheld = this.opts.unheld;
+ if (!unheld) return;
+ const still = new Map<string, number>();
+ for (const { threadId, botId } of unheld.threads()) {
+ if (this.turns.has(threadId)) continue;
+ const since = this.unheldSince.get(threadId) ?? at;
+ if (at - since < this.opts.stallMs) still.set(threadId, since);
+ else unheld.free(threadId, botId);
+ }
+ this.unheldSince = still;
}
}