Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(peer): resend a limit-hit turn that ended before its dispatch named it
AdityaUmalec3e07a4a9c3c
diff --git a/server/host/peer-limit-resend.test.ts b/server/host/peer-limit-resend.test.tsindex 75c8498c7f..5ee7363881 100644--- a/server/host/peer-limit-resend.test.ts+++ b/server/host/peer-limit-resend.test.ts@@ -20,6 +20,8 @@ describe("nothingRan", () => {expect(nothingRan([toolCall, failure], 100, "turn-1")).toBe(false);expect(nothingRan([reply, failure], 100, "turn-1")).toBe(false);expect(nothingRan([{ ...reply, kind: "widget" } as Message], 100, "turn-1")).toBe(false);+ // The digest written after the turn ends only sums it up.+ expect(nothingRan([failure, { ...reply, kind: "digest", text: "[digest] · no tool activity observed in this turn" } as Message], 100, "turn-1")).toBe(true);});it("ignores rows from before the turn, from another turn, and the hand-off's request card", () => {@@ -143,4 +145,40 @@ describe("peer limit resend", () => {expect(replaced.settle).toHaveBeenCalledWith("gen-1", { ok: false, text: "limit" });expect(replaced.startTurn).not.toHaveBeenCalled();});+ it("resends a turn whose end came before its dispatch named it, whether the thread settled before or after the bind", async () => {+ for (const settleFirst of [false, true]) {+ const { resend, startTurn, settle, failed } = fixture([ask, failure]);+ resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "Check the build", opts: peerOpts, userMessage: ask });+ // turn.completed arrives with no bound owner: nothing is judged yet.+ resend.endedUnbound(failed, false);+ if (settleFirst) expect(resend.resend("t1", "gen-1")).toBe(false);+ resend.bound("t1", "turn-1", "gen-1");+ expect(resend.hold("gen-1", { ok: false, text: "limit" }), `settleFirst=${settleFirst}`).toBe(true);+ if (!settleFirst) expect(resend.resend("t1", "gen-1")).toBe(true);+ await flush(); await flush();+ expect(startTurn, `settleFirst=${settleFirst}`).toHaveBeenCalledTimes(1);+ expect(settle).not.toHaveBeenCalled();+ }+ });++ it("ignores an early end for another turn id when the dispatch binds", () => {+ const { resend, failed } = fixture([ask, failure]);+ resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: peerOpts, userMessage: ask });+ resend.endedUnbound(failed, false);+ resend.bound("t1", "turn-other", "gen-1");+ expect(resend.hold("gen-1", { ok: false, text: "limit" })).toBe(false);+ });++ it("gives up when the turn's file landed after its end was judged", async () => {+ const rows = [ask, failure];+ const { resend, startTurn, settle, failed } = fixture(rows);+ resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: peerOpts, userMessage: ask });+ resend.ended(failed, "gen-1", false);+ resend.hold("gen-1", { ok: false, text: "limit" });+ rows.push({ id: "img", at: LATER, role: "bot", kind: "image", turnId: "turn-1" } as unknown as Message);+ expect(resend.resend("t1")).toBe(true);+ await flush();+ expect(startTurn).not.toHaveBeenCalled();+ expect(settle).toHaveBeenCalledWith("gen-1", { ok: false, text: "limit" });+ });});diff --git a/server/host/peer-limit-resend.ts b/server/host/peer-limit-resend.tsindex c9eff33fcf..478146f045 100644--- a/server/host/peer-limit-resend.ts+++ b/server/host/peer-limit-resend.ts@@ -43,8 +43,12 @@ export interface Claimed<Opts, Outcome> extends PeerTurn<Opts> {scope: Exclude<TakeoverScope, "signed-out">;/** The failed attempt's outcome, reported when the resend cannot run. */held?: Outcome;+ turnId?: string;+ stopError?: string;}+type EndedTurn = SettledTurn & { threadId: string; turnId?: string; ok: boolean };+export interface PeerLimitResendDeps<Opts, Outcome> {store: Pick<Store, "botByThread" | "projectBotForTask" | "taskByThread" | "activePath" | "appendMessage" | "switchTaskModel">;registry: Pick<ProviderRegistry, "get">;@@ -83,7 +87,8 @@ export interface PeerLimitResendDeps<Opts, Outcome> {*/export function nothingRan(rows: readonly Message[], since: number, turnId: string | undefined, stopError?: string): boolean {const said = stopError?.trim();- return !rows.some((row) => row.at >= since && row.role === "bot" && row.roomRequest?.phase !== "request" && (!turnId || !row.turnId || row.turnId === turnId) && (+ // The turn's digest is written after it ends and only sums it up.+ return !rows.some((row) => row.at >= since && row.role === "bot" && row.kind !== "digest" && row.roomRequest?.phase !== "request" && (!turnId || !row.turnId || row.turnId === turnId) && (row.kind === "activity" ? Boolean(row.tool?.itemId): row.kind === "text" ? Boolean(row.text?.trim()) && row.text!.trim() !== said: true));@@ -99,6 +104,10 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcomconst running = new Map<string, PeerTurn<Opts>>();/** Turns that met a limit before anything ran, until their resend is taken. */const claimed = new Map<string, Claimed<Opts, Outcome>>();+ /** A tracked turn's end that came before its dispatch named the turn, until the dispatch binds it. */+ const unbound = new Map<string, { event: EndedTurn; capped: boolean }>();+ /** Generations whose thread settled before their turn's end was bound: the bind resends at once. */+ const settledEarly = new Set<string>();/** At a turn's start: follows a relayed ask or a teammate's assignment, never the person's own, a routine's or a guest's. */function track(turn: Omit<PeerTurn<Opts>, "since">): void {@@ -107,18 +116,35 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcom|| opts.coordination?.resumed || deps.guest(turn.threadId)) return;if (opts.coordination ? !deps.handedOff(opts.coordination.id) : opts.cardContinuation || !(opts.peerAsk ?? turn.userMessage.peerAsk)) return;running.set(turn.threadId, { ...turn, since: Date.now() });+ unbound.delete(turn.threadId);}/** At the turn's end, before its hand-off hears the outcome: keeps it for a resend only for a usage limit met before anything ran. */- function ended(event: SettledTurn & { threadId: string; turnId?: string; ok: boolean }, generation: string, capped: boolean): void {+ function ended(event: EndedTurn, generation: string, capped: boolean): void {const turn = running.get(event.threadId);if (turn?.generation !== generation) return;running.delete(event.threadId);+ unbound.delete(event.threadId);+ const settled = settledEarly.delete(generation);// Held only where the bot's own turn end resends it or reports the failure (never a room's thread).const stop = event.ok || capped || !store.botByThread(event.threadId) || !deps.quotaSwitchEnabled() ? undefined : deps.turnStops.read(event.threadId, event.turnId);const scope = stop && turnLimitScope(event, stop.flags, deps.turnStops.failureCause(event));if (!scope || scope === "signed-out" || !nothingRan(store.activePath(event.threadId), turn.since, event.turnId, stop?.error)) return;- claimed.set(event.threadId, { ...turn, scope });+ claimed.set(event.threadId, { ...turn, scope, turnId: event.turnId, stopError: stop?.error });+ // The thread settled before the dispatch named this turn: resend now, once its hand-off has held the outcome.+ if (settled) setImmediate(() => resend(event.threadId));+ }++ /** A tracked thread's turn ended before its dispatch named the turn: kept until bound() gives its generation. */+ function endedUnbound(event: EndedTurn, capped: boolean): void {+ if (event.turnId && running.has(event.threadId)) unbound.set(event.threadId, { event, capped });+ }++ /** The dispatch named the turn after it had already ended: judges that end as ended() would have. */+ function bound(threadId: string, turnId: string, generation: string): void {+ const early = unbound.get(threadId);+ if (early?.event.turnId !== turnId) return;+ ended(early.event, generation, early.capped);}/** Keeps the failed attempt's outcome for its hand-off while the resend is pending; false when none is. */@@ -137,9 +163,13 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcom}/** Once the turn has settled: resends a claimed turn on the backup AI; true when it will. Otherwise its hand-off hears the failure as before. */- function resend(threadId: string): boolean {+ function resend(threadId: string, generation?: string): boolean {const turn = take(threadId);- if (!turn) return false;+ if (!turn) {+ // Settled before its end was bound to this generation: the bind resends instead.+ if (generation && running.get(threadId)?.generation === generation && unbound.has(threadId)) settledEarly.add(generation);+ return false;+ }const giveUp = (detail?: string): false => {if (detail && store.taskByThread(turn.botId, threadId)) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: deps.failedLine(threadId, detail), ok: false } });if (turn.held) deps.settle(turn.generation, turn.held);@@ -150,7 +180,9 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcom// Stop, deletion, a new send, or any replacement generation wins.const current = store.projectBotForTask(turn.botId, threadId);if (!current || deps.generation(threadId) !== turn.generation || deps.blocked(turn.botId, threadId)- || (turn.latestUser && store.activePath(threadId).findLast(m => m.role === "user" && m.kind === "text")?.id !== turn.latestUser)) return giveUp();+ || (turn.latestUser && store.activePath(threadId).findLast(m => m.role === "user" && m.kind === "text")?.id !== turn.latestUser)+ // A file the turn made lands after its end was judged: anything it left by now still means no resend.+ || !nothingRan(store.activePath(threadId), turn.since, turn.turnId, turn.stopError)) return giveUp();const from = current.modelSelection, instance = registry.get(from.instanceId);const backup = deps.takeover().backups(turn.botId, from, turn.scope, approvalModeFor(current)).find(candidate => {const target = registry.get(candidate.instanceId);@@ -183,5 +215,5 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcomreturn true;}- return { track, ended, hold, resend };+ return { track, ended, endedUnbound, bound, hold, resend };}diff --git a/server/index.ts b/server/index.tsindex cbc1e09c70..572c3e06b4 100644--- a/server/index.ts+++ b/server/index.ts@@ -4980,7 +4980,7 @@ const TURN_STALL_MS = Math.max(60_000, stallLimitMs(process.env.OMB_TURN_STALL_Mconst TOOL_STALL_MS = Math.max(TURN_STALL_MS, stallLimitMs(process.env.OMB_TOOL_STALL_MS, 2 * 60 * 60_000));const COMPUTER_WAIT_MAX_MS = Math.max(1_000, Number(process.env.OMB_COMPUTER_WAIT_MAX_MS) || 30 * 60_000);const roomStallCompletions = new RoomTurnStallRegistry();-const turnStops = new TurnStops(); const peerLimitResend = createPeerLimitResend<NonNullable<Parameters<typeof startTurn>[2]>, DirectTurnOutcome>({ store, registry, takeover: () => limitTakeover, turnStops, hostedModels, providerConfigs, quotaSwitchEnabled: () => quotaSwitchEnabled(), policyModelRefusal, checkedTaskModelSwitch, assertWithinBudget: () => assertWithinBudget(cfg, DATA_DIR), handedOff: (id) => coordinator.node(id)?.parentId !== undefined, guest: (threadId) => guestDrivenTurns.has(threadId) || cloudGuestDriven(threadId), generation: (threadId) => directTurnGenerationByThread.get(threadId), blocked: (botId, threadId) => threadBusy(botId, threadId) || hasQueuedSteeredMessages(botId, threadId) || Boolean(directRequestOwners.get(threadId)?.stopped), settle: settleDirectCoordination, release: (generation) => directCoordinationSettlers.delete(generation), failedLine: (threadId, detail) => serverLine(threadLanguage(threadId), "server.peerResend.failed", { detail }), startTurn }); // bot-to-bot turns whose AI met its usage limit before anything ran go once to the backup AI+const turnStops = new TurnStops();function stoppedTurnText(threadId: string, turnId: string | undefined, cause?: string, stopReason?: string | null): string {const stop = turnStops.read(threadId, turnId);const reason = cause ?? stop?.cause ?? stop?.error ?? `The turn did not complete (${stopReason?.trim() || "no reason given"})`;@@ -5063,7 +5063,7 @@ const watchdog = new TurnWatchdog({release.unref?.();},});-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); } });+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); } }); const peerLimitResend = createPeerLimitResend<NonNullable<Parameters<typeof startTurn>[2]>, DirectTurnOutcome>({ store, registry, takeover: () => limitTakeover, turnStops, hostedModels, providerConfigs, quotaSwitchEnabled: () => quotaSwitchEnabled(), policyModelRefusal, checkedTaskModelSwitch, assertWithinBudget: () => assertWithinBudget(cfg, DATA_DIR), handedOff: (id) => coordinator.node(id)?.parentId !== undefined, guest: (threadId) => guestDrivenTurns.has(threadId) || cloudGuestDriven(threadId), generation: (threadId) => directTurnGenerationByThread.get(threadId), blocked: (botId, threadId) => threadBusy(botId, threadId) || hasQueuedSteeredMessages(botId, threadId) || Boolean(directRequestOwners.get(threadId)?.stopped), settle: settleDirectCoordination, release: (generation) => directCoordinationSettlers.delete(generation), failedLine: (threadId, detail) => serverLine(threadLanguage(threadId), "server.peerResend.failed", { detail }), startTurn }); // bot-to-bot turns whose AI met its usage limit before anything ran go once to the backup AIbus.subscribe((event: RuntimeEvent) => {if (shouldIgnoreProviderEvent(event)) return;@@ -5087,7 +5087,7 @@ bus.subscribe((event: RuntimeEvent) => {if (owner) {peerLimitResend.ended(event, owner.generation, Boolean(handoffPath)); settleDirectCoordination(owner.generation, outcome);settleDirectFollowup(owner.generation);- }+ } else peerLimitResend.endedUnbound(event, Boolean(handoffPath));}} else if (event.type !== "session.exited") {watchdog.observe(event);@@ -6745,12 +6745,12 @@ bus.subscribe((event: RuntimeEvent) => {releaseLocalVmThread(event.threadId);}releaseTurnResources(resourceOwner);- if (!isCurrent()) return void peerLimitResend.resend(event.threadId);+ if (!isCurrent()) return void peerLimitResend.resend(event.threadId, generation);if (store.taskByThread(bot.id, event.threadId)?.activity !== "dead") {store.setTaskActivity(bot.id, event.threadId, resourceOwner?.computerParkedOn !== undefined ? "parked.computer" : "idle");}directTurnBots.delete(event.threadId);- if (continueComputerSelection(event.threadId, generation, event.ok) || peerLimitResend.resend(event.threadId)) return;+ if (continueComputerSelection(event.threadId, generation, event.ok) || peerLimitResend.resend(event.threadId, generation)) return;// An asynchronous screenshot finishes after the bus subscribers that normally drain have run.if (resumeQueued) {drainQueuedSends();@@ -8477,7 +8477,7 @@ async function beginTurn(if (directFollowupSettlers.has(dispatchClaimId) && dispatch.value.turnId &&!directFollowupTurns.bind(threadId, dispatchClaimId, dispatch.value.turnId)) {const outcome = directFollowupTurns.takeEarlyCompletion(threadId, dispatch.value.turnId);- if (outcome) settleDirectCoordination(dispatchClaimId, outcome);+ if (outcome) { peerLimitResend.bound(threadId, dispatch.value.turnId, dispatchClaimId); settleDirectCoordination(dispatchClaimId, outcome); }settleDirectFollowup(dispatchClaimId);}clearDirectTurnDispatch(threadId, dispatchClaimId);