Skip to content

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

fix: bind wait continuations to their originating run

fangyuanbcd832d7be85
diff --git a/docs/verification/waits.md b/docs/verification/waits.md
index 3cd153fc9a..3eb5ed31fd 100644
--- a/docs/verification/waits.md
+++ b/docs/verification/waits.md
@@ -13,9 +13,10 @@ pnpm exec vitest run server/wait-probes.test.ts server/waits.test.ts server/wait
## In a fixture
The fake engine calls `wait_until` on every turn it runs, including the follow-up.
-A follow-up proved by the server's wait run and fired notice can create its next wait
-in the same bot's direct chat. The multi-stage e2e test exercises two completions and
-registration of the next stage. Scheduled routines and unrelated outside events
+A follow-up proved by its live turn generation, originating wait run and fired notice
+can create its next wait in the same bot's direct chat. Continuation authorization is
+checked again after the initial probe and immediately before persistence. The multi-stage
+e2e test exercises two completions and registration of the next stage. Scheduled routines and unrelated outside events
retain their existing refusal. A condition already true returns immediately and
directs the bot to carry out its follow-up in that turn.
@@ -64,8 +65,10 @@ internet, and what a real model does with the follow-up (the fake engine replies
## Last exercised
-2026-11-16, macOS arm64, Node 26.5.0. Five focused Vitest files passed with
-60 tests, including successive build, test and package waits in one direct chat.
+2026-11-16, macOS arm64, Node 26.5.0. Twelve targeted Vitest files passed with
+500 tests, including successive build, test and package waits in one direct chat,
+originating-run and live-generation authorization, and rejection before persistence
+when continuation authorization changes during a URL probe.
The packaged server passed its smoke checks and all four wait and handed-wait
e2e tests against disposable fixture data. The route tests also cover immediate
follow-up when the requested condition already holds.
diff --git a/server/index.ts b/server/index.ts
index c0e79302c0..5b4380bc54 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -484,7 +484,7 @@ import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts"
import { addressFor } from "./webhook-address.ts";
import { assertModelVariantSupported, memberTurnSelection } from "./member-turn.ts";
import { WebhookManager } from "./webhooks.ts";
-import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { cancelWaitFromCard, createWaitHost, waitContinuesHere, waitRunChat } from "./wait-host.ts"; import { continuedConversation } from "./routine-same-conversation.ts"; import { createWaitRoutes, findWaitPeer, handedAssignment, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts";
+import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { cancelWaitFromCard, createWaitHost, waitContinuationCheck, waitRunChat, waitTurnRunId } from "./wait-host.ts"; import { continuedConversation } from "./routine-same-conversation.ts"; import { createWaitRoutes, findWaitPeer, handedAssignment, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts";
import type { WebhookTrigger } from "../shared/webhooks.ts";
import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";
import { agentsProxyLaunch, agentsToolBridgeEnv, applyAgentsBridge, bridgedToolTitle, turnEngine } from "./agents-bridge-switch.ts"; import { serverTurnedOff } from "./drivers/agents-tool-groups.ts"; import { availableToolGroups, toolsOffPart } from "./tool-groups.ts"; import { agentsServerEnv, botDrivenConversation, COMPUTER_OFF_REFUSAL, computerPickRefusal, directTurnKind, roomSkillsRefusal, type TurnKind } from "./agents-turn.ts";
@@ -1916,7 +1916,7 @@ const directTurnGenerationByThread = new Map<string, string>();
// Latest direct request per thread, kept past Stop until completion or failure cleanup; unknown continuations deliberately lose proof.
const directRequestOwners = new Map<string, {
generation: string; messageId?: string; generations: Set<string>; turnId: string | null; stopped?: boolean;
- automation?: RoutineRunTrigger;
+ automation?: RoutineRunTrigger; automationRunId?: string;
origin?: WorkOrigin; personLine?: true; kind?: TurnKind;
gmailDrafts?: Set<string>;
}>();
@@ -7535,6 +7535,7 @@ async function beginTurn(
runOn?: RoutineRunOn;
/** Puts externally supplied payloads behind an explicit untrusted-data boundary in the system prompt. */
automationSource?: RoutineRunTrigger;
+ automationRunId?: string;
unattended?: boolean;
peerAsk?: Message["peerAsk"];
/** The prompt is control-plane context, never a message authored by the user. */
@@ -7744,7 +7745,7 @@ async function beginTurn(
gmailDrafts: opts?.coordination ? gmailDrafts.forNode(opts.coordination.id) :
continuation && previousRequest && !previousRequest.stopped && (!requestMessageId || previousRequest.messageId === requestMessageId)
? previousRequest.gmailDrafts ?? new Set<string>() : new Set<string>(),
- generations: requestGenerations, turnId: null, ...(opts?.automationSource ? { automation: opts.automationSource } : {}), origin: requestOrigin, ...(personLine || (continued && previousRequest?.personLine) ? { personLine: true as const } : {}),
+ generations: requestGenerations, turnId: null, ...(opts?.automationSource ? { automation: opts.automationSource } : {}), automationRunId: waitTurnRunId(opts, previousRequest, requestMessageId), origin: requestOrigin, ...(personLine || (continued && previousRequest?.personLine) ? { personLine: true as const } : {}),
kind: directTurnKind({ ...opts, peerAsk: opts?.peerAsk ?? userMessage.peerAsk }) });
const notesRefused = CLOUD_PERSONAL && cloudHomeOwnTurnRefusal(cloudLendingTurn({ botId, threadId, generation: dispatchClaimId })) !== null;
if (notesRefused) noteForeignTurn(botId, threadId, dispatchClaimId);
@@ -8842,8 +8843,8 @@ routines = new RoutineManager({
handoffs.forget(threadId);
}
},
- startTurn: async (botId, threadId, prompt, runOn, triggerSource, onDispatchError) => {
- if (!companyShutdown) await startTurn(botId, prompt, { threadId, runOn, automationSource: triggerSource, onDispatchError });
+ startTurn: async (botId, threadId, prompt, runOn, triggerSource, onDispatchError, runId) => {
+ if (!companyShutdown) await startTurn(botId, prompt, { threadId, runOn, automationSource: triggerSource, automationRunId: runId, onDispatchError });
},
startGoal: async (groupId, threadId, prompt, coordinatorBotId, runId, _onDispatchError) => {
if (!groupId) {
@@ -11117,8 +11118,9 @@ function connectorThread(botId: string, threadId: string) {
return null;
}
function directChatOf(botId: string, threadId: string): boolean { const source = connectorThread(botId, threadId); return source !== null && !source.group; }
-function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick<WaitRouteContext, "sourceRefusal" | "assignmentId" | "hostRefusal" | "guest" | "peer" | "elsewhere"> { const { threadId } = capability, place = () => { const turn = turnPlaces.get(threadId); return turn?.botId === sender.id ? turn.place : null; }, assignmentId = () => handedAssignment(capability.roomHandoffId ?? directCoordinationSettlers.get(capability.generation)?.nodeId, (id) => coordinator.node(id));
- return { assignmentId, sourceRefusal: (op, assignment) => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), waitContinuation: !capability.externalRuntime && directRequestOwners.get(threadId)?.generations.has(capability.generation) === true && waitContinuesHere(activeRoutineRunForThread(threadId), sender.id, threadId, store), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId), op, assignmentId: assignment }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), hosted: HOSTED_WORKSPACE, guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain }; }
+function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick<WaitRouteContext, "sourceRefusal" | "assignmentId" | "continuationAllowed" | "hostRefusal" | "guest" | "peer" | "elsewhere"> { const { threadId } = capability, place = () => { const turn = turnPlaces.get(threadId); return turn?.botId === sender.id ? turn.place : null; }, assignmentId = () => handedAssignment(capability.roomHandoffId ?? directCoordinationSettlers.get(capability.generation)?.nodeId, (id) => coordinator.node(id));
+ const continuationAllowed = waitContinuationCheck(capability, { active: internalCapabilityIsActive, request: (id) => directRequestOwners.get(id), run: activeRoutineRunForThread, store });
+ return { assignmentId, continuationAllowed, sourceRefusal: (op, assignment) => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), waitContinuation: continuationAllowed(), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId), op, assignmentId: assignment }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), hosted: HOSTED_WORKSPACE, guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain }; }
/** Read fresh every time; a line stamped via the HTTP API does not count, so a bot cannot re-arm the ceiling it just spent. */
function lastHumanRoomMessageAt(group: GroupRecord): number | undefined {
diff --git a/server/routes/waits.test.ts b/server/routes/waits.test.ts
index 77286e55d9..f7cae2a0ad 100644
--- a/server/routes/waits.test.ts
+++ b/server/routes/waits.test.ts
@@ -260,6 +260,18 @@ describe("the waits route", () => {
await call("POST", "/api/internal/waits", FILE_WAIT);
expect(waits.create.mock.calls[0]![0]).not.toHaveProperty("stillAllowed");
});
+ it("rechecks a continuation before storing while leaving ordinary top-level waits unchanged", async () => {
+ waits.create.mockClear();
+ let allowed = true;
+ await call("POST", "/api/internal/waits", FILE_WAIT, { continuationAllowed: () => allowed });
+ const { stillAllowed } = waits.create.mock.calls[0]![0];
+ expect(stillAllowed?.()).toBeNull();
+ allowed = false;
+ expect(stillAllowed?.()).toBe(WAIT_MESSAGES.notPerson);
+ waits.create.mockClear();
+ await call("POST", "/api/internal/waits", FILE_WAIT, { continuationAllowed: () => false });
+ expect(waits.create.mock.calls[0]![0]).not.toHaveProperty("stillAllowed");
+ });
it("offers files and programs only on the bot's own computer", () => {
const own = { cloudHome: false, hosted: false, guest: false, place: null };
for (const place of [null, "local", "browser"] as const) expect(hostWaitRefusal({ ...own, place })).toBeNull();
diff --git a/server/routes/waits.ts b/server/routes/waits.ts
index eaaec3915e..596ca59b1a 100644
--- a/server/routes/waits.ts
+++ b/server/routes/waits.ts
@@ -171,6 +171,7 @@ export interface WaitRouteContext {
readBody: () => Promise<unknown>;
sourceRefusal: (op: "create" | "cancel", assignmentId: string | undefined) => string | null;
assignmentId?: () => string | undefined;
+ continuationAllowed?: () => boolean;
hostRefusal: () => string | null;
/** A Cloud guest's turn: its follow-up would run later as the owner's, so a guest's wait only tells. */
guest: () => boolean;
@@ -197,6 +198,7 @@ export function createWaitRoutes(deps: { waits: Pick<WaitManager, "create" | "li
if (ctx.method !== "POST" || (ctx.path !== WAITS && ctx.path !== CANCEL)) return PASS;
const assignmentId = ctx.assignmentId?.();
+ const continuation = ctx.continuationAllowed?.() === true;
const refusal = ctx.sourceRefusal(ctx.path === CANCEL ? "cancel" : "create", assignmentId);
if (refusal) return void json(res, 403, { error: refusal });
const body = await ctx.readBody();
@@ -244,7 +246,14 @@ export function createWaitRoutes(deps: { waits: Pick<WaitManager, "create" | "li
condition,
...(request.followUp ? { followUp: request.followUp } : {}),
hours: request.hours,
- ...(assignmentId ? { assignmentId, stillAllowed: () => (ctx.assignmentId?.() === assignmentId ? null : WAIT_MESSAGES.notPerson) } : {}),
+ ...(assignmentId ? { assignmentId } : {}),
+ ...(assignmentId || continuation ? {
+ stillAllowed: () => {
+ if (assignmentId && ctx.assignmentId?.() !== assignmentId) return WAIT_MESSAGES.notPerson;
+ if (continuation && (!ctx.continuationAllowed?.() || ctx.sourceRefusal("create", assignmentId))) return WAIT_MESSAGES.notPerson;
+ return null;
+ },
+ } : {}),
});
if (result.state === "refused") return void json(res, result.status, { error: result.error });
if (result.state === "already") return void json(res, 200, { text: request.followUp
diff --git a/server/routines.test.ts b/server/routines.test.ts
index 86154d2626..bff33a9e47 100644
--- a/server/routines.test.ts
+++ b/server/routines.test.ts
@@ -48,6 +48,7 @@ function harness(start = new Date(2026, 7, 17, 8, 0, 0).getTime()) {
}> = [];
const runOns: string[] = [];
const triggerSources: string[] = [];
+ const runIds: string[] = [];
const taskTitles: string[] = [];
const goalTasks: Array<{ groupId: string; title: string }> = [];
const interruptedTurns: Array<{ botId: string; threadId: string }> = [];
@@ -74,10 +75,11 @@ function harness(start = new Date(2026, 7, 17, 8, 0, 0).getTime()) {
goalTasks.push({ groupId, title });
return { threadId: `goal-thread-${++goalTask}` };
},
- startTurn: async (botId, threadId, prompt, runOn, triggerSource) => {
+ startTurn: async (botId, threadId, prompt, runOn, triggerSource, _onDispatchError, runId) => {
started.push({ botId, threadId, prompt });
runOns.push(runOn);
triggerSources.push(triggerSource);
+ runIds.push(runId);
},
startGoal: async (groupId, threadId, prompt, coordinatorBotId, runId, onDispatchError) => {
startedGoals.push({ groupId, threadId, prompt, coordinatorBotId, runId, onDispatchError });
@@ -101,6 +103,7 @@ function harness(start = new Date(2026, 7, 17, 8, 0, 0).getTime()) {
startedGoals,
runOns,
triggerSources,
+ runIds,
taskTitles,
goalTasks,
interruptedTurns,
@@ -2897,6 +2900,7 @@ describe("RoutineManager", () => {
expect(h.started).toEqual([{ botId: "maus-webhook", threadId: "thread-1", prompt: "Handle ticket 42" }]);
expect(h.runOns).toEqual(["cloud"]);
expect(h.triggerSources).toEqual(["webhook"]);
+ expect(h.runIds).toEqual([queued.id]);
expect(h.taskTitles).toHaveLength(1);
});
diff --git a/server/routines.ts b/server/routines.ts
index e434266f66..5d884de85b 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -255,6 +255,7 @@ export interface RoutineManagerOptions {
runOn: RoutineRunOn,
triggerSource: RoutineRunTrigger,
onDispatchError: (message: string) => void,
+ runId: string,
) => Promise<void>;
startGoal?: (
groupId: string | undefined,
@@ -1188,6 +1189,7 @@ export class RoutineManager {
run.runOn ?? "maus",
triggerSource,
(message) => this.failThread(task.threadId, message, { cause: "refused" }),
+ run.id,
);
}
} catch (error) {
diff --git a/server/wait-host.test.ts b/server/wait-host.test.ts
index 574e701e5e..79f4f08caf 100644
--- a/server/wait-host.test.ts
+++ b/server/wait-host.test.ts
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Notification } from "../shared/notification.ts";
import type { Message } from "./store.ts";
-import { cancelWaitFromCard, createWaitHost, waitContinuesHere, waitRunChat, type WaitHostDeps } from "./wait-host.ts";
+import { cancelWaitFromCard, createWaitHost, waitContinuesHere, waitContinuationCheck, waitRunChat, waitTurnRunId, type WaitHostDeps } from "./wait-host.ts";
import type { WaitRecord } from "./waits.ts";
const NOW = 1_700_000_000_000;
@@ -111,18 +111,65 @@ describe("the store side of waits", () => {
expect([host.botBusy("bot-1"), host.botBusy("gone")]).toEqual([false, undefined]);
});
+ it("carries run identity only from dispatch or a continuation of the same known request", () => {
+ const previous = { automationRunId: "run-1", messageId: "request-1" };
+ expect(waitTurnRunId({ automationRunId: "run-2" }, previous, "request-2")).toBe("run-2");
+ expect(waitTurnRunId({ cardContinuation: true }, previous, "request-1")).toBe("run-1");
+ expect(waitTurnRunId({ computerSelectionContinuation: true }, previous, "request-1")).toBe("run-1");
+ expect(waitTurnRunId(undefined, previous, "request-1")).toBeUndefined();
+ expect(waitTurnRunId({ cardContinuation: true }, previous, undefined)).toBeUndefined();
+ expect(waitTurnRunId({ cardContinuation: true }, previous, "unrelated-request")).toBeUndefined();
+ expect(waitTurnRunId({ cardContinuation: true }, { ...previous, stopped: true }, "request-1")).toBeUndefined();
+ expect(waitTurnRunId({ cardContinuation: true }, undefined, "request-1")).toBeUndefined();
+ });
+
+ it("binds a continuation capability to its own live request and run", () => {
+ host.post(wait, { status: "fired", text: "done" });
+ const run = { id: "run-1", eventSource: "wait" as const, triggerSource: "webhook" as const, botId: "bot-1", threadId: "t-1", resultsThreadId: "t-1", webhookId: "wait:w1", deliveryId: "w1" };
+ const capability = { botId: "bot-1", threadId: "t-1", generation: "generation-1" };
+ let request: { automationRunId?: string; stopped?: boolean; generations: Set<string> } = { automationRunId: run.id, generations: new Set([capability.generation]) };
+ let active = true;
+ let currentRun: typeof run | null = run;
+ const deps = { active: () => active, request: () => request, run: () => currentRun, store };
+ const allowed = waitContinuationCheck(capability, deps);
+ expect(allowed()).toBe(true);
+ request = { generations: new Set([capability.generation]) };
+ expect(allowed()).toBe(false);
+ request.automationRunId = "unrelated-run";
+ expect(allowed()).toBe(false);
+ request.automationRunId = run.id;
+ expect(allowed()).toBe(true);
+ request.generations = new Set(["unrelated-generation"]);
+ expect(allowed()).toBe(false);
+ request.generations.add(capability.generation);
+ active = false;
+ expect(allowed()).toBe(false);
+ active = true;
+ request.stopped = true;
+ expect(allowed()).toBe(false);
+ request.stopped = false;
+ currentRun = { ...run, id: "different-run" };
+ expect(allowed()).toBe(false);
+ currentRun = null;
+ expect(allowed()).toBe(false);
+ currentRun = run;
+ expect(waitContinuationCheck({ ...capability, externalRuntime: {} }, deps)()).toBe(false);
+ });
+
it("proves a wait continuation from the run and its fired notice in the same chat", () => {
- const run = { eventSource: "wait" as const, triggerSource: "webhook" as const, botId: "bot-1", threadId: "t-1", resultsThreadId: "t-1", webhookId: "wait:w1", deliveryId: "w1" };
- expect(waitContinuesHere(run, "bot-1", "t-1", store)).toBe(false);
+ const run = { id: "run-1", eventSource: "wait" as const, triggerSource: "webhook" as const, botId: "bot-1", threadId: "t-1", resultsThreadId: "t-1", webhookId: "wait:w1", deliveryId: "w1" };
+ expect(waitContinuesHere(run, "bot-1", "t-1", store, "run-1")).toBe(false);
host.post(wait, { status: "fired", text: "done" });
- expect(waitContinuesHere(run, "bot-1", "t-1", store)).toBe(true);
- expect(waitContinuesHere(null, "bot-1", "t-1", store)).toBe(false);
+ expect(waitContinuesHere(run, "bot-1", "t-1", store, "run-1")).toBe(true);
+ expect(waitContinuesHere(run, "bot-1", "t-1", store, undefined)).toBe(false);
+ expect(waitContinuesHere(run, "bot-1", "t-1", store, "unrelated-run")).toBe(false);
+ expect(waitContinuesHere(null, "bot-1", "t-1", store, "run-1")).toBe(false);
for (const patch of [
{ eventSource: "app" as const }, { eventSource: undefined }, { triggerSource: "schedule" as const },
- { botId: "other" }, { threadId: "other" }, { resultsThreadId: "other" },
+ { id: "other" }, { botId: "other" }, { threadId: "other" }, { resultsThreadId: "other" },
{ deliveryId: "other" }, { deliveryId: undefined }, { webhookId: "other" },
- ]) expect(waitContinuesHere({ ...run, ...patch }, "bot-1", "t-1", store)).toBe(false);
+ ]) expect(waitContinuesHere({ ...run, ...patch }, "bot-1", "t-1", store, "run-1")).toBe(false);
store.messages[0]!.wait!.status = "expired";
- expect(waitContinuesHere(run, "bot-1", "t-1", store)).toBe(false);
+ expect(waitContinuesHere(run, "bot-1", "t-1", store, "run-1")).toBe(false);
});
});
diff --git a/server/wait-host.ts b/server/wait-host.ts
index 014636f64b..58f5a9836e 100644
--- a/server/wait-host.ts
+++ b/server/wait-host.ts
@@ -28,19 +28,55 @@ export function waitRunChat(
return directChat(run.botId, run.resultsThreadId) ? run.resultsThreadId : null;
}
-/** A wait continuation is proved by the server's run and fired notice in the same bot's chat, never its prompt. */
+/** A wait continuation is proved by the turn's originating run and fired notice in the same bot's chat, never its prompt. */
export function waitContinuesHere(
- run: Pick<RoutineRun, "eventSource" | "triggerSource" | "botId" | "threadId" | "resultsThreadId" | "webhookId" | "deliveryId"> | null,
+ run: Pick<RoutineRun, "id" | "eventSource" | "triggerSource" | "botId" | "threadId" | "resultsThreadId" | "webhookId" | "deliveryId"> | null,
botId: string,
threadId: string,
store: Pick<Store, "messagesFor">,
+ originatingRunId: string | undefined,
): boolean {
- if (!run || run.eventSource !== "wait" || run.triggerSource !== "webhook" || run.botId !== botId
+ if (!run || !originatingRunId || run.id !== originatingRunId || run.eventSource !== "wait" || run.triggerSource !== "webhook" || run.botId !== botId
|| run.threadId !== threadId || run.resultsThreadId !== threadId || !run.deliveryId
|| run.webhookId !== `wait:${run.deliveryId}`) return false;
return store.messagesFor(threadId).some((message) => message.wait?.status === "fired" && message.wait.id === run.deliveryId);
}
+interface WaitRunOwner {
+ automationRunId?: string;
+ messageId?: string;
+ stopped?: boolean;
+ generations: ReadonlySet<string>;
+}
+
+export function waitTurnRunId(
+ turn: { automationRunId?: string; cardContinuation?: boolean; computerSelectionContinuation?: boolean } | undefined,
+ previous: Pick<WaitRunOwner, "automationRunId" | "messageId" | "stopped"> | undefined,
+ requestMessageId: string | undefined,
+): string | undefined {
+ if (turn?.automationRunId) return turn.automationRunId;
+ if (!(turn?.cardContinuation || turn?.computerSelectionContinuation) || !requestMessageId
+ || previous?.stopped || previous?.messageId !== requestMessageId) return undefined;
+ return previous.automationRunId;
+}
+
+export function waitContinuationCheck<T extends { botId: string; threadId: string; generation: string; externalRuntime?: unknown }>(
+ capability: T,
+ deps: {
+ active: (capability: T) => boolean;
+ request: (threadId: string) => WaitRunOwner | undefined;
+ run: (threadId: string) => Parameters<typeof waitContinuesHere>[0];
+ store: Pick<Store, "messagesFor">;
+ },
+): () => boolean {
+ return () => {
+ const request = deps.request(capability.threadId);
+ return !capability.externalRuntime && deps.active(capability)
+ && request?.stopped !== true && request?.generations.has(capability.generation) === true
+ && waitContinuesHere(deps.run(capability.threadId), capability.botId, capability.threadId, deps.store, request.automationRunId);
+ };
+}
+
type CardStore = Pick<Store, "messagesFor" | "patchMessage">;
function settleWaitCard(store: CardStore, threadId: string, messageId: string, how: "fired" | "expired" | "cancelled"): void {
diff --git a/server/waits.test.ts b/server/waits.test.ts
index 24daf3adbd..cbd9a1a53c 100644
--- a/server/waits.test.ts
+++ b/server/waits.test.ts
@@ -1,8 +1,9 @@
-import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { createWaitRoutes, WAIT_MESSAGES } from "./routes/waits.ts";
import type { FileStamp, PageResult, ProcessEntry } from "./wait-probes.ts";
import { CLOUD_IDLE_AWAKE_MS, createCloudPower } from "./cloud-power.ts";
import { describeCondition, WAIT_WAKE_MS, WaitManager, waitList, type NewWaitCondition, type WaitManagerOptions, type WaitNotice, type WaitRecord } from "./waits.ts";
@@ -90,6 +91,35 @@ function harness(options: Partial<WaitManagerOptions> = {}) {
}
describe("WaitManager", () => {
+ it.each(["ended", "new generation", "different run"])("refuses to persist a continuation that changed during a URL probe: %s", async (change) => {
+ const h = harness();
+ const route = createWaitRoutes({ waits: h.manager });
+ const json = vi.fn();
+ const turn = { active: true, generation: "generation-1", runId: "run-1" };
+ const continuationAllowed = () => turn.active && turn.generation === "generation-1" && turn.runId === "run-1";
+ let finishProbe!: () => void;
+ h.pageGate = new Promise<void>((resolve) => { finishProbe = resolve; });
+ const pending = route({
+ method: "POST", path: "/api/internal/waits", res: {} as never, json,
+ botId: "bot-1", threadId: "t-1",
+ readBody: async () => ({ label: "the build", kind: "url_contains", url: "https://example.test/build", text: "done", follow_up: "Run tests." }),
+ sourceRefusal: () => null, continuationAllowed, hostRefusal: () => null, guest: () => false, peer: () => null,
+ });
+ try {
+ await expect.poll(() => h.pageInFlight).toBe(1);
+ if (change === "ended") turn.active = false;
+ if (change === "new generation") turn.generation = "generation-2";
+ if (change === "different run") turn.runId = "run-2";
+ } finally {
+ finishProbe();
+ await pending;
+ }
+ expect(json).toHaveBeenCalledWith(expect.anything(), 403, { error: WAIT_MESSAGES.notPerson });
+ expect(h.manager.list("bot-1")).toEqual([]);
+ expect(existsSync(h.file)).toBe(false);
+ expect(h.showCard).not.toHaveBeenCalled();
+ });
+
it("keeps work a bot handed on to one open wait per assignment, across a restart, until it ends", async () => {
const h = harness();
const handed = (assignmentId: string) => h.manager.create({ botId: "bot-1", threadId: "t-1", label: "the report", condition: { kind: "file_exists", path: "/r.txt" }, assignmentId });