Skip to content

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

Stop means stop: a person's Stop ends the teammates working for that request

milind-soniba0039a09574
diff --git a/docs/verification/room-coordination.md b/docs/verification/room-coordination.md
index af196dea8f..7c7ae2fede 100644
--- a/docs/verification/room-coordination.md
+++ b/docs/verification/room-coordination.md
@@ -38,9 +38,8 @@ At the next start (the runtime's restart policy, `server/runtime/runtime.ts` `op
Every time budget of a tree that outlived a restart starts again at boot
(downtime is nobody's budget); request and execution counts carry on, and a
rerun costs one execution. Stop on the requester cancels a rerun not yet
- started, "Stopped before it resumed", since nothing of it is running; a
- rerun already running is left alone like any teammate mid-turn, and so is
- one the person left working by a Stop before the restart.
+ started, "Stopped before it resumed", and a rerun already running, like any
+ teammate mid-turn.
- A routine run still going at a restart fails, as before, and its
teammates' work ends with it, "OpenMausBot restarted while this routine was
running": none of it runs again, so no result lands after the person was
@@ -180,16 +179,14 @@ every outstanding assignment has settled and the resumed coordination has
finished. Steering stays the default; Stop keeps its conversation-scoped
behavior either way.
-Stop is scoped to the conversation it was pressed in. It ends that bot's turn
-and stops the conversation awaiting its teammates, so nothing resumes into a
-stopped chat. An assignment that had not started yet is cancelled, since
-nothing is lost. A teammate already mid-turn keeps its own provider process:
-it finishes, and its result is still recorded and reported back here as the
-usual receipt. Each teammate Stop leaves running gets its own pill in the
-transcript — "Stopped here — Eli is still working; open to stop it too" —
-which survives Tool calls being hidden and opens that teammate's conversation,
-where Stop reaches its turn for real. Deleting a waiting source still cancels
-its whole tree, and never recreates the conversation.
+Stop is scoped to the request in the conversation it was pressed in, and stop
+means stop. It ends that bot's turn and everything the request handed out: an
+assignment that had not started yet ("Stopped before it started") and a
+teammate already mid-turn ("Stopped with the request it was for"), with what
+they handed on in turn. Nothing resumes into a stopped chat, and no result
+arrives after it. Each stopped assignment is still recorded and reported back
+here as the usual receipt. Deleting a waiting source still cancels its whole
+tree, and never recreates the conversation.
Provider work and waiting-on-teammate status stay separate internally, so
waiting does not hold a provider session or block another independent
diff --git a/server/coordinator.ts b/server/coordinator.ts
index c52f8c67e0..e31a1b19ce 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -196,7 +196,8 @@ export interface Coordinator {
/** Direct conversations whose turn waits on teammates: an open handoff it made that owes a reply, or a root parked to resume with no question for the person. */
awaitingTeammateThreads(): Set<string>;
liveEdges(): LiveHandoffEdge[];
- stopAwaitingDirect(threadId: string, reason?: string): HandoffView[];
+ /** The conversation stopped: its work and everything that work handed out end, and nothing resumes it. */
+ stopAwaitingDirect(threadId: string, reason?: string): void;
/** The next start goes on with this thread's turn, so a shutdown's "cut" line would be false. */
continuesAfterRestart(threadId: string): boolean;
note(id: string): string | undefined;
diff --git a/server/delta-context.e2e.test.ts b/server/delta-context.e2e.test.ts
index f76f96d74d..8ec20f37aa 100644
--- a/server/delta-context.e2e.test.ts
+++ b/server/delta-context.e2e.test.ts
@@ -217,7 +217,7 @@ it("gives the return turn a result that landed while a newer message was running
expect(f.launches().at(-1).resume).not.toBeNull();
}), hostTimeout(60_000));
-it("offers a result that lands mid-turn after its source was stopped to the next turn, once, labelled", () => fixture(async (f) => {
+it("stops the teammate with the source it worked for, so no result of it lands later or reaches a later turn", () => fixture(async (f) => {
await warmUp(f);
f.plan[f.lead.id] = { reply: "STOPPED_SOURCE_RESULT", gateFile: f.gate("lead") };
f.plan[f.chief.id] = f.delegate("build", [f.lead], "Build the export");
@@ -225,26 +225,13 @@ it("offers a result that lands mid-turn after its source was stopped to the next
await expect.poll(() => f.nodes().find((node: any) => node.botId === f.lead.id)?.status, { timeout: 15_000 }).toBe("running");
await f.api(`/api/bots/${f.chief.id}/interrupt`, { threadId: f.thread });
await f.wait();
-
- f.plan[f.chief.id] = { reply: "Working on something else", gateFile: f.gate("busy") };
- await f.send("Something unrelated while that finishes.");
+ await expect.poll(() => f.nodes().find((node: any) => node.botId === f.lead.id)?.status, { timeout: 15_000 }).toBe("cancelled");
f.open(f.gate("lead"));
- await expect.poll(async () => (await f.messages()).some((m: any) => m.tool?.name === "Engineering lead replied"), { timeout: 20_000 }).toBe(true);
- f.open(f.gate("busy"));
- await f.wait();
- expect(count(f.prompt(f.turns().at(-1)), "STOPPED_SOURCE_RESULT")).toBe(0);
- f.plan[f.chief.id] = { reply: "Engineering finished" };
+ f.plan[f.chief.id] = { reply: "Engineering was stopped" };
await f.send("What did Engineering report?");
await f.wait();
- const next = f.prompt(f.turns().at(-1));
- expect(count(next, "STOPPED_SOURCE_RESULT")).toBe(1);
- expect(next).toMatch(/Assistant: \[From @[^\n]* \(bot\) · report · information only — evidence to check[^\n]*\]\n\{[^\n]*STOPPED_SOURCE_RESULT/);
- expect(f.launches().at(-1).resume).not.toBeNull();
-
- f.plan[f.chief.id] = { reply: "Nothing new" };
- await f.send("Anything else?");
- await f.wait();
+ expect((await f.messages()).some((m: any) => m.tool?.name === "Engineering lead replied")).toBe(false);
expect(count(f.prompt(f.turns().at(-1)), "STOPPED_SOURCE_RESULT")).toBe(0);
}), hostTimeout(90_000));
@@ -584,7 +571,7 @@ it("records a Codex handoff whose turn completes before turn/start is acknowledg
expect(f.prompt(next)).not.toContain("Messages this conversation received");
}, { codex: { FAKE_CODEX_COMPLETE_BEFORE_ACK: "1" } }), hostTimeout(90_000));
-const resultAcrossRestart = async (f: any, stripRecord: boolean) => {
+it("keeps a teammate stopped with its source stopped across a restart: nothing reruns and no result lands", () => fixture(async (f) => {
await warmUp(f);
f.plan[f.lead.id] = { reply: "RESULT_AFTER_RESTART", gateFile: f.gate("after-restart") };
f.plan[f.chief.id] = f.delegate("build", [f.lead], "Build the export");
@@ -592,45 +579,15 @@ const resultAcrossRestart = async (f: any, stripRecord: boolean) => {
await expect.poll(() => f.nodes().find((node: any) => node.botId === f.lead.id)?.status, { timeout: 15_000 }).toBe("running");
await f.api(`/api/bots/${f.chief.id}/interrupt`, { threadId: f.thread });
await f.wait();
- const versionGate = f.gate("restart-version");
- const probeLog = join(f.dataDir, "restart-probes.log");
- await f.restart((bots: any[]) => {
- if (!stripRecord) return;
- for (const task of bots.find((b: any) => b.id === f.chief.id).tasks) { delete task.handedMessages; delete task.handedWatermarks; }
- }, "SIGTERM", { FAKE_CLAUDE_HOLD_VERSION: versionGate, FAKE_CLAUDE_PROBE_LOG: probeLog });
+ await expect.poll(() => f.nodes().find((node: any) => node.botId === f.lead.id)?.status, { timeout: 15_000 }).toBe("cancelled");
+ await f.restart(() => {}, "SIGTERM");
f.open(f.gate("after-restart"));
- try {
- await expect.poll(() => existsSync(probeLog) && readFileSync(probeLog, "utf8").includes("version "), { timeout: 10_000 }).toBe(true);
- // Hold the capability probe across room-handoff ticks, as on a loaded host.
- await new Promise((resolve) => setTimeout(resolve, 750));
- } finally {
- f.open(versionGate);
- }
- await expect.poll(async () => (await f.messages()).some((m: any) => m.roomRequest?.phase === "result"), { timeout: 20_000 }).toBe(true);
- f.plan[f.chief.id] = { reply: "Engineering was interrupted" };
+ f.plan[f.chief.id] = { reply: "Engineering was stopped" };
await f.send("What happened to the Engineering work?");
await f.wait();
- return f.turns().at(-1);
-};
-
-it("replays once for a stored conversation without a handoff record when a result arrives after restart", () => fixture(async (f) => {
- const turn = await resultAcrossRestart(f, true);
- expect(count(f.prompt(turn), "RESULT_AFTER_RESTART")).toBe(1);
- expect(f.prompt(turn)).toContain("ORCHID_7Q");
- expect(f.launches().at(-1).resume).toBeNull();
- const rebuilt = f.nativeSession();
- f.plan[f.chief.id] = { reply: "ok" };
- await f.send("Thanks.");
- await f.wait();
+ expect(f.nodes().find((node: any) => node.botId === f.lead.id)?.status).toBe("cancelled");
+ expect((await f.messages()).some((m: any) => m.tool?.name === "Engineering lead replied")).toBe(false);
expect(count(f.prompt(f.turns().at(-1)), "RESULT_AFTER_RESTART")).toBe(0);
- expect(f.nativeSession()).toBe(rebuilt);
-}), hostTimeout(90_000));
-
-it("keeps resuming a stored conversation with a handoff record when a result arrives after restart", () => fixture(async (f) => {
- const turn = await resultAcrossRestart(f, false);
- expect(count(f.prompt(turn), "RESULT_AFTER_RESTART")).toBe(1);
- expect(f.prompt(turn)).not.toContain("ORCHID_7Q");
- expect(f.launches().at(-1).resume).not.toBeNull();
}), hostTimeout(90_000));
it.each(["SIGTERM", "SIGKILL"] as const)("runs each teammate turn a restart cut again once, in place, and resumes the Chief told so (%s)", (signal) => fixture(async (f) => {
diff --git a/server/direct-coordination.e2e.test.ts b/server/direct-coordination.e2e.test.ts
index 9e7b17975b..6ca84dc58e 100644
--- a/server/direct-coordination.e2e.test.ts
+++ b/server/direct-coordination.e2e.test.ts
@@ -309,13 +309,14 @@ it.each(["resume", "stop", "failed resume", "failed root"] as const)("keeps a gu
await api("POST", `${route}/interrupt`, { ...target, expectedExecutionId: null }, 409);
expect(await api("POST", `${route}/interrupt`, target)).toEqual({ ok: true, outcome: "stopped" });
await api("POST", `${route}/interrupt`, target, 409);
- expect(f.nodes().find((node: any) => node.botId === f.lead.id).status).toBe("running");
+ // Stop means stop: the teammate working for the request ends with it.
+ expect(f.nodes().find((node: any) => node.botId === f.lead.id).status).toBe("cancelled");
}
writeFileSync(gate, "finish only the isolated teammate");
const childWait = await f.cli("wait", "--bot", f.lead.id, "--task", child.threadId, "--timeout", "20");
evidence.push({ command: ["wait", "--bot", f.lead.id, "--task", child.threadId, "--timeout", "20"], result: childWait });
expect(childWait.status).toBe("settled");
- await expect.poll(() => f.nodes().find((node: any) => node.botId === f.lead.id).status).toBe("completed");
+ await expect.poll(() => f.nodes().find((node: any) => node.botId === f.lead.id).status).toBe(action === "stop" ? "cancelled" : "completed");
const finalWait = await f.wait();
evidence.push({ command: ["wait", "--bot", f.chief.id, "--task", threadId, "--timeout", "30"], result: finalWait });
expect(action === "failed resume" ? ["settled", "failed"] : ["settled"]).toContain(finalWait.status);
@@ -826,7 +827,7 @@ it("runs a teammate's hand-off to the Chief in the Chief's work thread for that
await expect.poll(() => f.nodes().every((node: any) => node.status === "completed"), { timeout: 10_000 }).toBe(true);
}), 60_000);
-it("stops a waiting source without reaching into the teammate already working", () => fixture(async f => {
+it("stops a waiting source and the teammate already working for it, with no late result and no pill", () => fixture(async f => {
const childGate = join(f.session.info.dataDir, "child-ready");
f.plan[f.lead.id] = { gateFile: childGate, reply: "Finished after the source was stopped" };
await f.start();
@@ -834,21 +835,16 @@ it("stops a waiting source without reaching into the teammate already working",
await assigningTurnEnded(f);
await f.api(`/api/bots/${f.chief.id}/interrupt`, { threadId: f.chief.activeTaskId });
- await expect.poll(() => f.nodes().find((node: any) => !node.parentId)?.status).toBe("cancelled");
- expect(f.nodes().find((node: any) => node.parentId).status).toBe("running");
+ await expect.poll(() => f.nodes().map((node: any) => [Boolean(node.parentId), node.status])).toEqual([[false, "cancelled"], [true, "cancelled"]]);
writeFileSync(childGate, "finish after the source was stopped");
expect((await f.wait()).status).toBe("settled");
- const chip = (await f.messages(f.chief.activeTaskId)).find((message: any) => message.tool?.name?.startsWith("Stopped here"));
- expect(chip.tool.name).toContain("Engineering lead");
- expect(chip.threadRef).toMatchObject({ botId: f.lead.id, threadId: f.nodes().find((node: any) => node.parentId).threadId });
-
- await expect.poll(() => f.nodes().find((node: any) => node.parentId)?.status, { timeout: 20_000 }).toBe("completed");
- expect(f.nodes().find((node: any) => node.parentId).result).toContain("Finished after the source was stopped");
- await expect.poll(async () => (await f.messages(f.chief.activeTaskId)).some((message: any) => message.tool?.name === "Engineering lead replied")).toBe(true);
- const replied = (await f.messages(f.chief.activeTaskId)).find((message: any) => message.tool?.name === "Engineering lead replied");
- expect(replied.tool.output).toContain("Finished after the source was stopped");
+ await new Promise(resolve => setTimeout(resolve, 1_000));
+ const rows = await f.messages(f.chief.activeTaskId);
+ expect(rows.some((message: any) => message.tool?.name?.startsWith("Stopped here"))).toBe(false);
+ expect(rows.some((message: any) => message.tool?.output?.includes("Finished after the source was stopped"))).toBe(false);
+ expect(f.nodes().find((node: any) => node.parentId).status).toBe("cancelled");
expect(f.evidence().filter((turn: any) => turn.botId === f.chief.id)).toHaveLength(1);
- expect((await f.messages(f.chief.activeTaskId)).some((message: any) => message.text === "The requested CSV export is implemented and verified")).toBe(false);
+ expect(rows.some((message: any) => message.text === "The requested CSV export is implemented and verified")).toBe(false);
}), 60_000);
it("deleting the waiting source cancels its tree and never recreates the deleted conversation", () => fixture(async f => {
diff --git a/server/host/person-stop.ts b/server/host/person-stop.ts
index 1f2d703f24..85fb3a00f7 100644
--- a/server/host/person-stop.ts
+++ b/server/host/person-stop.ts
@@ -1,6 +1,5 @@
// What a person's Stop does to a direct thread: the Stop button (POST /api/bots/:id/interrupt), a typed "stop"
-// while the bot works (acceptDirectSend), "Restart turn" from the send menu, and the pills for teammates a stop leaves running.
-import type { HandoffView } from "../coordinator.ts";
+// while the bot works (acceptDirectSend), and "Restart turn" from the send menu. A stop ends what the request handed out too.
import type { Handoffs } from "../delta-context.ts";
import { addressesEveryone, isStopCommand } from "../room-holds.ts";
import type { RoutineManager } from "../routines.ts";
@@ -79,20 +78,5 @@ export function createPersonStop(deps: PersonStopDeps) {
await stopThreadForPerson(botId, threadId);
}
- /** Stop left teammates mid-turn: one pill each links to the conversation where Stop reaches that turn. */
- function noteTeammatesLeftRunning(threadId: string, running: HandoffView[]): void {
- if (!store.botByThread(threadId) && !store.groupByThread(threadId)) return;
- for (const node of running) {
- const name = store.bot(node.botId)?.name ?? "A teammate";
- const task = store.taskByThread(node.botId, node.threadId);
- store.appendMessage(threadId, {
- role: "bot",
- kind: "activity",
- tool: { name: `Stopped here — ${name} is still working; open to stop it too`, ok: true },
- ...(task ? { threadRef: { botId: node.botId, threadId: node.threadId, title: task.title } } : {}),
- });
- }
- }
-
- return { stopThreadForPerson, stopOnTypedCommand, restartForPerson, noteTeammatesLeftRunning };
+ return { stopThreadForPerson, stopOnTypedCommand, restartForPerson };
}
diff --git a/server/index.ts b/server/index.ts
index 7b429c62f6..fee2c44507 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2308,7 +2308,7 @@ async function interruptDirectThread(botId: string, threadId: string, cause?: st
if (requestOwner.messageId) store.patchMessage(threadId, requestOwner.messageId, { requestCancelled: true });
}
stopParkedCards(threadId);
- noteTeammatesLeftRunning(threadId, coordinator.stopAwaitingDirect(threadId, cause));
+ coordinator.stopAwaitingDirect(threadId, cause);
const owner = botForThread(botId, threadId);
const generation = directTurnGenerationByThread.get(threadId);
cancelDirectTurnDispatch(botId, threadId);
@@ -2862,7 +2862,7 @@ const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusalForBot,
const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) }); const lendingLifts = lendingMemory ? createLendingLifts({ store, stopped: (threadId) => directRequestOwners.get(threadId)?.stopped === true, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn, notify, language: (threadId) => threadLanguage(threadId), device: () => deviceWord(sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform), decide: (row) => appendDecision(DATA_DIR, row), words: changedWords, ownersAnswer: (card) => cloudProvenOwnerPerson(cloudCardAnswerer(card)), memory: { info: (botId) => lendingMemory.reviewInfo(botId), accept: (botId, token) => lendingMemory.review(botId, foreignTurnRunning(botId), token).ok } }) : null;
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, noteTeammatesLeftRunning } = createPersonStop({
+const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersonStop({
store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, 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, 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 } } });
@@ -3852,7 +3852,7 @@ function noteQueuedBehindPerson(node: HandoffView): void {
function runRoomNode(node: HandoffView, group: GroupRecord, bot: BotRecord, signal: AbortSignal, parent: HandoffView | undefined,
turn: (operation: GroupTurnOperation, result: GroupTurnOrchestration["result"], coordination: NonNullable<GroupTurnOrchestration["coordination"]>) => Promise<unknown>,
): Promise<HostTurnResult> {
- const operation = Object.assign(beginGroupTurnOperation(group.id, node.threadId, [bot.id]), { handedFor: actingPeople.handedRun(node.id) });
+ const operation = Object.assign(beginGroupTurnOperation(group.id, node.threadId, [bot.id]), { handedFor: actingPeople.handedRun(node.id), speaking: false });
return new Promise<HostTurnResult>(resolve => {
let done = false;
const finish = (outcome: HostTurnResult) => {
@@ -3860,7 +3860,7 @@ function runRoomNode(node: HandoffView, group: GroupRecord, bot: BotRecord, sign
done = true; resolve(outcome);
};
const result: GroupTurnOrchestration["result"] = {};
- const abort = () => { operation.cancelled = true; operation.cancellation.abort(); };
+ const abort = () => { operation.cancelled = true; operation.cancellation.abort(); if (operation.speaking) void runningTurnInstance(bot, node.threadId)?.adapter.interruptTurn(node.threadId).catch(() => {}); };
signal.addEventListener("abort", abort, { once: true });
if (signal.aborted) abort();
const run = (groupQueues.get(node.threadId) ?? Promise.resolve()).catch(() => {}).then(async () => {
@@ -3869,7 +3869,7 @@ function runRoomNode(node: HandoffView, group: GroupRecord, bot: BotRecord, sign
if (problem) throw new Error(problem);
const available = await waitForChatRoomMember(operation, node.threadId, bot);
if (available !== "run") { result.outcome = "cancelled"; return; }
- await turn(operation, result, { id: node.id, settle: finish });
+ operation.speaking = true; await turn(operation, result, { id: node.id, settle: finish });
});
const tracked = run.finally(() => {
signal.removeEventListener("abort", abort);
@@ -4495,7 +4495,7 @@ function cancelGroupTurnOperations(
if (outcome.byHarness) coordinator.cancelRoom(groupId, threadId, outcome.detail, "failed");
else {
stopParkedCards(threadId);
- noteTeammatesLeftRunning(threadId, coordinator.stopAwaitingDirect(threadId));
+ coordinator.stopAwaitingDirect(threadId);
coordinator.cancelRoom(groupId, threadId);
}
roomMemberLock.releaseThread(threadId);
@@ -8955,7 +8955,7 @@ routines = new RoutineManager({
cancelDirectTurnDispatch(botId, threadId);
revokeInternalCapabilitiesForThread(threadId);
stopParkedCards(threadId);
- noteTeammatesLeftRunning(threadId, coordinator.stopAwaitingDirect(threadId));
+ coordinator.stopAwaitingDirect(threadId);
try {
await runningTurnInstance(bot, threadId)?.adapter.interruptTurn(threadId);
} finally {
diff --git a/server/managed-desktop-cleanup.test.ts b/server/managed-desktop-cleanup.test.ts
index 745b7e9b31..d51f4386a7 100644
--- a/server/managed-desktop-cleanup.test.ts
+++ b/server/managed-desktop-cleanup.test.ts
@@ -95,8 +95,8 @@ function fixture(kind: "direct" | "group", threadIds = ["first"]) {
if (generation === undefined || yourComputerAsks.get(threadId) === generation) yourComputerAsks.delete(threadId);
},
turnResources: { release() {} }, cloudComputerPower: { released() {} }, settlingResourceOwners: new Map(), turnComputerResources: new Map(), teamComputerTurns: new Map(),
- coordinator: { stopAwaitingDirect: (threadId: string) => { stopAwaiting.push(threadId); return []; } },
- noteTeammatesLeftRunning() {}, stopParkedCards: (threadId: string) => stoppedCards.push(threadId),
+ coordinator: { stopAwaitingDirect: (threadId: string) => { stopAwaiting.push(threadId); } },
+ stopParkedCards: (threadId: string) => stoppedCards.push(threadId),
cancelDirectTurnDispatch: (_botId: string, threadId: string) => cancelled.push(threadId),
cancelGroupTurnOperations: (_groupId: string, threadId: string, outcome?: { status: string; detail: string; byHarness?: boolean }) => {
cancelled.push(threadId);
@@ -383,10 +383,9 @@ it("ends a room stopped by the harness with its cause, and one the person stoppe
const context = vm.createContext({
coordinator: {
cancelRoom: (...args: string[]) => calls.push(`assignments:${args.join("|")}`),
- stopAwaitingDirect: (threadId: string) => { calls.push(`stop-awaiting:${threadId}`); return ["mid-turn teammate"]; },
+ stopAwaitingDirect: (threadId: string) => { calls.push(`stop-awaiting:${threadId}`); },
},
stopParkedCards: (threadId: string) => calls.push(`cards-stopped:${threadId}`),
- noteTeammatesLeftRunning: (threadId: string, left: string[]) => calls.push(`left-running:${threadId}:${left.join(",")}`),
roomMemberLock: { releaseThread: (threadId: string) => calls.push(`member-claims:${threadId}`) },
groupTurnOperations: new Map([["g", new Set([{ threadId: "room", cancellation: new AbortController() }])]]),
finishGroupGoalRun: (_groupId: string, _operation: unknown, status: string, detail: string) => calls.push(`goal:${status}|${detail}`),
@@ -403,7 +402,7 @@ it("ends a room stopped by the harness with its cause, and one the person stoppe
"goal:stopped|Turn interrupted — provider settings changed.",
]);
expect(run()).toEqual([
- "cards-stopped:room", "stop-awaiting:room", "left-running:room:mid-turn teammate",
+ "cards-stopped:room", "stop-awaiting:room",
"assignments:g|room", "member-claims:room", "goal:stopped|Stopped by you.",
]);
});
diff --git a/server/room-coordination.e2e.test.ts b/server/room-coordination.e2e.test.ts
index 88f05e445c..88e0d3b8d1 100644
--- a/server/room-coordination.e2e.test.ts
+++ b/server/room-coordination.e2e.test.ts
@@ -259,7 +259,7 @@ it("keeps a busy recipient queued and rejects revoked peer access before dispatc
await f.cli("wait", "--bot", f.target.id, "--timeout", "15");
}), 45_000);
-it("stops awaiting on Stop in the source room: the running downstream turn is left to finish, said once, and nothing resumes the room", () => withRooms(async f => {
+it("stops awaiting on Stop in the source room, and stop means stop: the running downstream turn ends too, and nothing resumes the room", () => withRooms(async f => {
f.plan[f.target.id].delayMs = 10_000;
await f.start();
await expect.poll(() => f.nodes().find((n: any) => n.parentId)?.status, { timeout: 10_000 }).toBe("running");
@@ -269,14 +269,14 @@ it("stops awaiting on Stop in the source room: the running downstream turn is le
return { senderBusy: bots.find((b: any) => b.id === f.sender.id)?.busy, taskWorking: task?.working };
}, { timeout: 10_000 }).toEqual({ senderBusy: false, taskWorking: true });
await f.cli("interrupt", "--channel", f.source.id);
- await expect.poll(() => f.nodes().map((n: any) => [Boolean(n.parentId), n.status]), { timeout: 5_000 }).toEqual([[false, "cancelled"], [true, "running"]]);
- expect((await f.messages(f.source.activeTaskId)).filter((m: any) => m.tool?.name === "Stopped here — Engineer is still working; open to stop it too")).toHaveLength(1);
- await expect.poll(() => f.nodes().find((n: any) => n.parentId)?.status, { timeout: 20_000 }).toBe("completed");
+ await expect.poll(() => f.nodes().map((n: any) => [Boolean(n.parentId), n.status]), { timeout: 5_000 }).toEqual([[false, "cancelled"], [true, "cancelled"]]);
+ expect((await f.messages(f.source.activeTaskId)).some((m: any) => /still working; open to stop it too/.test(m.tool?.name ?? ""))).toBe(false);
await expect.poll(async () => {
const { bots } = await f.api("/api/bots"); return bots.find((b: any) => b.id === f.target.id)?.busy;
}, { timeout: 10_000 }).toBeFalsy();
- expect((await f.messages(f.destination.activeTaskId)).some((m: any) => m.text === "Built CSV")).toBe(true);
- expect(f.provider().map((turn: any) => turn.botId)).toEqual([f.sender.id, f.target.id]);
+ await new Promise((resolve) => setTimeout(resolve, 11_000));
+ expect((await f.messages(f.destination.activeTaskId)).some((m: any) => m.text === "Built CSV")).toBe(false);
+ expect(f.nodes().map((n: any) => n.status)).toEqual(["cancelled", "cancelled"]);
expect((await f.messages(f.source.activeTaskId)).some((m: any) => m.text === "Reviewed downstream outcome")).toBe(false);
}), 45_000);
diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.ts
index 04282c8a1e..a49bd5b917 100644
--- a/server/runtime-coordinator.test.ts
+++ b/server/runtime-coordinator.test.ts
@@ -697,7 +697,7 @@ describe("RuntimeCoordinator: stops", () => {
expect(w.host.reports.map(r => r.child.id).sort()).toEqual([b.id, other.id, t.id].sort());
});
- it("stopAwaitingDirect drops what never started, leaves a working teammate, and stops the requester", async () => {
+ it("stopAwaitingDirect stops the requester and everything it handed out: what never started, and a teammate at work", async () => {
const w = world(hold);
const { node: b } = send(w, chief, "gen-1", undefined, builder, "Build it");
const { node: t } = send(w, chief, "gen-1", undefined, tester, "Test it");
@@ -707,16 +707,14 @@ describe("RuntimeCoordinator: stops", () => {
expect(w.coordinator.node(t.id)?.status).toBe("queued");
expect(w.coordinator.outstandingDirect("chief-chat").map(n => n.id).sort()).toEqual([b.id, t.id].sort());
expect(w.coordinator.assignerOf("builder-work")?.id).toBe("gen-1");
- const left = w.coordinator.stopAwaitingDirect("chief-chat");
- expect(left.map(n => n.id)).toEqual([b.id]);
+ w.coordinator.stopAwaitingDirect("chief-chat");
expect(w.coordinator.node(t.id)).toMatchObject({ status: "cancelled", result: "Stopped before it started" });
+ expect(w.coordinator.node(b.id)).toMatchObject({ status: "cancelled", result: "Stopped with the request it was for", reported: true });
expect(w.coordinator.node("gen-1")).toMatchObject({ status: "cancelled", result: "Stopped by user" });
- expect(w.host.runs[0]!.signal.aborted).toBe(false);
+ expect(w.host.runs[0]!.signal.aborted).toBe(true);
expect(w.coordinator.outstandingDirect("chief-chat")).toEqual([]);
expect(w.coordinator.assignerOf("builder-work")).toBeUndefined();
- await w.host.release(b.id, { ok: true, text: "built anyway" });
- expect(w.coordinator.node(b.id)).toMatchObject({ status: "completed", result: "built anyway", reported: true });
- expect(w.host.reports.at(-1)).toMatchObject({ child: { id: b.id }, parent: { id: "gen-1", status: "cancelled" } });
+ expect(w.coordinator.active()).toEqual([]);
});
});
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index 678e853e22..4bf49cdb41 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -388,9 +388,9 @@ export class RuntimeCoordinator implements Coordinator {
for (const n of this.live()) if (this.direct(n, threadId)) this.runtime.cancel(n.id, reason, "stopped");
}
- stopAwaitingDirect(threadId: string, reason = "Stopped by user"): HandoffView[] {
+ stopAwaitingDirect(threadId: string, reason = "Stopped by user"): void {
this.ready();
- return this.runtime.stopRequester({ threadId }, reason).map(a => this.project(a));
+ this.runtime.stopRequester({ threadId }, reason);
}
activeDirect(threadId: string): boolean {
diff --git a/server/runtime/runtime.test.ts b/server/runtime/runtime.test.ts
index 2a424e91fb..d5bce94a7f 100644
--- a/server/runtime/runtime.test.ts
+++ b/server/runtime/runtime.test.ts
@@ -420,7 +420,7 @@ describe("Runtime: one tree, one lane", () => {
invariants(w);
});
- it("stops awaiting: queued work is dropped, a teammate mid-turn keeps its process and still reports", async () => {
+ it("stops awaiting, and stop means stop: queued work is dropped and a teammate mid-turn is stopped too", async () => {
const w = world(() => "hold");
const root = w.runtime.begin(beginReq());
const running = ok(w.runtime.enqueue(toBot("running", root.id)));
@@ -428,18 +428,18 @@ describe("Runtime: one tree, one lane", () => {
w.runner.canStartAnswer = false;
const queued = ok(w.runtime.enqueue(toBot("queued", root.id)));
w.runtime.tick();
- const left = w.runtime.stopRequester({ threadId: "chief-chat" });
- expect(left.map(a => a.id)).toEqual([running.id]);
+ w.runtime.stopRequester({ threadId: "chief-chat" });
expect(w.store.get(queued.id)).toMatchObject({ status: "cancelled", outcomeDetail: "Stopped before it started" });
+ expect(w.store.get(running.id)).toMatchObject({ status: "cancelled", outcome: "stopped", outcomeDetail: "Stopped with the request it was for" });
expect(w.store.get(root.id)).toMatchObject({ status: "cancelled", outcome: "stopped" });
- expect(w.runner.runs[0]!.signal.aborted).toBe(false);
+ expect(w.runner.runs[0]!.signal.aborted).toBe(true);
await w.runner.release(running.id, { kind: "completed", text: "finished anyway" });
- expect(w.store.get(running.id)).toMatchObject({ status: "completed", result: "finished anyway" });
- expect(w.runner.reports.map(r => r.a.id)).toEqual([queued.id, root.id, running.id]);
+ expect(w.store.get(running.id)).toMatchObject({ status: "cancelled", result: "Stopped with the request it was for" });
+ expect(w.runner.reports.map(r => r.a.id).sort()).toEqual([queued.id, running.id, root.id].sort());
w.runtime.tick();
expect(w.store.get(root.id)?.status).toBe("cancelled");
expect(w.runner.runs).toHaveLength(1);
- expect(w.runtime.stopRequester({ threadId: "chief-chat" })).toEqual([]);
+ expect(w.store.all({ nonTerminal: true })).toEqual([]);
invariants(w);
});
@@ -732,7 +732,7 @@ describe("Runtime: what the host relies on for the new modes and openers", () =>
expect(w.runtime.poll({ runId: "run-9" }).items).toEqual([]);
expect(w.store.inbox({ threadId: "chief-chat" }).map(i => i.assignmentId)).toEqual([a.id]);
expect(w.runtime.outstanding({ runId: "run-9" }).map(x => x.id)).toEqual([root.id]);
- expect(w.runtime.stopRequester({ runId: "run-9" })).toEqual([]);
+ w.runtime.stopRequester({ runId: "run-9" });
expect(w.store.get(b.id)).toMatchObject({ status: "cancelled", outcomeDetail: "Stopped before it started" });
expect(w.store.get(root.id)).toMatchObject({ status: "cancelled", outcome: "stopped" });
expect(w.runtime.outstanding({ runId: "run-9" })).toEqual([]);
diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.ts
index 478532dad4..ab6bbbd0e1 100644
--- a/server/runtime/runtime.ts
+++ b/server/runtime/runtime.ts
@@ -36,6 +36,7 @@ export interface BeginRequest {
const BRIEF_MAX = 12_000;
const RESULT_MAX = 12_000;
+const STOPPED_WITH_REQUEST = "Stopped with the request it was for";
const DETAIL_MAX = 400;
const defaultClock: Clock = { now: () => Date.now(), monotonic: () => performance.now() };
@@ -571,10 +572,10 @@ export class Runtime {
this.withBatch(() => outcome === "failed" ? this.cancelTree(n, reason, "failed", "interrupted") : this.cancelTree(n, reason, "cancelled", "stopped"));
}
- /** The person stopped the requester's conversation: work that never started is dropped, a teammate
- * mid-turn still reports, and nothing resumes the stopped conversation. */
- stopRequester(owner: Owner, reason = "Stopped by user"): Assignment[] {
- const left: Assignment[] = [];
+ /** The person stopped the requester's conversation, and stop means stop: everything it handed out ends with it, work
+ * that never started and teammates mid-turn alike (and what they handed on), and nothing resumes the stopped
+ * conversation. */
+ stopRequester(owner: Owner, reason = "Stopped by user"): void {
this.withBatch(() => {
for (const snapshot of this.store.all({ nonTerminal: true })) {
if (!ownsConversation(snapshot, owner)) continue;
@@ -582,14 +583,13 @@ export class Runtime {
if (!n || isTerminal(n)) continue;
for (const child of this.store.children(n.id)) {
if (isTerminal(child)) continue;
- if (child.status === "queued" && (child.executions === 0 || child.restart === "rerun")) {
- this.cancelTree(child, child.restart === "rerun" ? "Stopped before it resumed" : "Stopped before it started", "cancelled", "stopped");
- } else left.push(child);
+ const unstarted = child.status === "queued" && (child.executions === 0 || child.restart === "rerun");
+ this.cancelTree(child, !unstarted ? STOPPED_WITH_REQUEST : child.restart === "rerun" ? "Stopped before it resumed" : "Stopped before it started",
+ "cancelled", "stopped");
}
this.settle(n, "cancelled", "stopped", reason);
}
});
- return left;
}
status(id: string): StatusView | undefined {
diff --git a/server/runtime/scenarios.test.ts b/server/runtime/scenarios.test.ts
index 077903246b..d697a98c50 100644
--- a/server/runtime/scenarios.test.ts
+++ b/server/runtime/scenarios.test.ts
@@ -831,7 +831,7 @@ describe("§2 cancel and stop awaiting", () => {
invariants(w);
});
- it("S17 stopRequester: queued children cancelled, the running child keeps going and reports, the requester never resumes", async () => {
+ it("S17 stopRequester: queued and running children are stopped with it, and the requester never resumes", async () => {
const w = world();
const root = beginChief(w);
const a = ok(enqueueFrom(w, root, workFor("dev", "Build")));
@@ -843,20 +843,15 @@ describe("§2 cancel and stop awaiting", () => {
expect(get(w, a.id).status).toBe("running");
expect(get(w, b.id).status).toBe("queued");
- const left = w.rt.stopRequester(chiefOwner, "person stopped the chat");
- expect(left.map((x) => x.id)).toEqual([a.id]);
+ w.rt.stopRequester(chiefOwner, "person stopped the chat");
expect(get(w, b.id)).toMatchObject({ status: "cancelled", outcome: "stopped" });
expect(get(w, root.id)).toMatchObject({ status: "cancelled", outcome: "stopped" });
- expect(get(w, a.id).status).toBe("running");
- expect(w.runner.runs(a.id)[0].signal!.aborted).toBe(false);
- expect(w.runner.running.has(a.id)).toBe(true);
- await drain(w);
- expect(get(w, a.id).status).toBe("running");
+ expect(get(w, a.id)).toMatchObject({ status: "cancelled", outcome: "stopped" });
+ expect(w.runner.runs(a.id)[0].signal!.aborted).toBe(true);
invariants(w);
- w.runner.release(a.id, complete("late but done"));
await drain(w);
- expect(get(w, a.id)).toMatchObject({ status: "completed", outcome: "done", result: "late but done" });
+ expect(get(w, a.id)).toMatchObject({ status: "cancelled", outcome: "stopped" });
expect(w.runner.reports(a.id)).toHaveLength(1);
expect(w.runner.reports(a.id)[0].parent?.id).toBe(root.id);
expect(w.runner.reports(b.id)).toHaveLength(1);
diff --git a/server/stop-stops-helpers.e2e.test.ts b/server/stop-stops-helpers.e2e.test.ts
new file mode 100644
index 0000000000..cbd03b0ea6
--- /dev/null
+++ b/server/stop-stops-helpers.e2e.test.ts
@@ -0,0 +1,50 @@
+// Stop means stop, end to end on the scripted engine: the person's Stop in the chat that handed work out also stops the
+// teammates working for that request, not only the ones that had not started. Modelled on a real day, when a stop left
+// hand-offs running and their results kept arriving for minutes after it.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { request } from "../scripts/mcp-server.ts";
+import { readHandoffs } from "./testing/handoff-rows.ts";
+
+it("stops the teammates working for a request when the person stops the chat that asked, with no late results", async () => {
+ const session = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });
+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: session.info.url } }) as Promise<any>;
+ const api = (path: string, body?: unknown, method = "POST") =>
+ request(path, body === undefined ? {} : { method, body: JSON.stringify(body) }, session.info.url) as Promise<any>;
+ try {
+ const post = (await cli("new-bot", "--name", "Post")).bot;
+ const cos = (await cli("new-bot", "--name", "Chief of staff")).bot;
+ const research = (await cli("new-bot", "--name", "Research")).bot;
+ const planPath = join(session.info.dataDir, "room-plan.json");
+ const started = join(session.info.dataDir, "helpers-started");
+ writeFileSync(planPath, JSON.stringify({
+ [post.id]: { script: [{ key: "S1", match: ["S1-JOB"], steps: [{ arguments: { bot_ids: [cos.id, research.id], message: "S1-ASK: find the mailbox settings" } }], reply: "S1: asked two teammates." }] },
+ [cos.id]: { script: [{ key: "S1-ASK", match: ["S1-ASK"], readyFile: started, delayMs: 8_000, reply: "S1-ASK late: the settings are in the old notes." }] },
+ [research.id]: { script: [{ key: "S1-ASK", match: ["S1-ASK"], delayMs: 8_000, reply: "S1-ASK late: the host is imap.example.test." }] },
+ }));
+ const evidence = (): any[] => existsSync(`${planPath}.evidence.jsonl`)
+ ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
+ const messages = async (threadId: string) => (await api(`/api/threads/${threadId}/messages`)).messages as any[];
+ const busy = async (id: string) => ((await api("/api/bots?messages=0", undefined, "GET")).bots as any[]).find((bot) => bot.id === id)?.busy;
+ const helpers = () => readHandoffs(session.info.dataDir).filter((node) => node.parentId);
+
+ await cli("send", "--bot", post.id, "--task", post.activeTaskId, "--text", "S1-JOB: fetch my mail");
+ await expect.poll(() => existsSync(started) && helpers().every((node) => node.status === "running"), { timeout: 20_000 }).toBe(true);
+ expect(helpers()).toHaveLength(2);
+
+ await cli("interrupt", "--bot", post.id, "--task", post.activeTaskId);
+ await expect.poll(() => helpers().map((node) => node.status), { timeout: 5_000 }).toEqual(["cancelled", "cancelled"]);
+ await expect.poll(async () => (await busy(cos.id)) || (await busy(research.id)), { timeout: 10_000 }).toBeFalsy();
+ expect((await messages(post.activeTaskId)).some((row) => /still working; open to stop it too/.test(row.tool?.name ?? "")), "no pill: nothing was left running").toBe(false);
+
+ // Past the moment the helpers would have answered: nothing lands, and the asking chat never resumes.
+ await new Promise((resolve) => setTimeout(resolve, 9_000));
+ for (const node of helpers()) expect((await messages(node.threadId)).some((row) => /late:/.test(row.text ?? ""))).toBe(false);
+ expect(evidence().filter((turn) => turn.botId === post.id).map((turn) => turn.planKey), "the asking chat never resumed").toEqual(["S1"]);
+ expect(helpers().map((node) => node.status)).toEqual(["cancelled", "cancelled"]);
+ } finally {
+ await session.close();
+ }
+}, 90_000);
diff --git a/src/locales/server-lines.test.ts b/src/locales/server-lines.test.ts
index 2a3166740e..5d1bb29427 100644
--- a/src/locales/server-lines.test.ts
+++ b/src/locales/server-lines.test.ts
@@ -497,7 +497,6 @@ const PENDING: Readonly<Record<string, ReadonlyArray<readonly [file: string, sni
["server/team-setup-requests.ts", "Team setup not applied"],
],
"restarts, stops and context": [
- ["server/host/person-stop.ts", "Stopped here — … is still working; open to stop it too"],
["server/index.ts", "Resuming after a restart"],
["server/index.ts", "… was cut off by a restart; resuming"],
["server/index.ts", "context compaction started ( … )"],