Skip to content

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

fix(handoffs): end the request before its work on the person's Stop, so each close reads whose stop it was

luishron12333753589decc
diff --git a/server/host/finished-work.test.ts b/server/host/finished-work.test.ts
index 50529f0306..f01e9528a0 100644
--- a/server/host/finished-work.test.ts
+++ b/server/host/finished-work.test.ts
@@ -407,6 +407,15 @@ describe("createHandedClose", () => {
expect(record.archivedAt).toBe(1_000_000 + STOP_GRACE_MS);
});
+ it("forgets a deleted bot's due threads: the hour that comes closes nothing", () => {
+ const { record, start, emit } = world({ openedBy: oneShot() });
+ start().ended(personStop, chief, false);
+ emit({ type: "bot.deleted", botId: "lead" });
+ vi.advanceTimersByTime(STOP_GRACE_MS);
+ expect(record.closedBy).toBeUndefined();
+ expect(record.archivedAt).toBeUndefined();
+ });
+
it("keeps a stopped thread open for good when anyone writes in it within the hour", () => {
for (const message of [{ role: "user" as const }, { role: "bot" as const, threadPost: { deliveryId: "d", fromBotId: "chief", fromThreadId: "chief-chat" } }]) {
const { record, start, write } = world({ openedBy: oneShot() });
diff --git a/server/host/finished-work.ts b/server/host/finished-work.ts
index a0d809dd1f..16b149e07a 100644
--- a/server/host/finished-work.ts
+++ b/server/host/finished-work.ts
@@ -196,6 +196,8 @@ export function createHandedClose(deps: HandedCloseDeps): HandedClose {
};
const unsubscribe = store.onChange((change) => {
+ // A deleted bot's threads went with it, so its due ones leave the index.
+ if (change.type === "bot.deleted") { due.delete(change.botId); arm(); return; }
if (looking || !started) return;
if (change.type === "bot") { if (due.has(change.botId)) look(change.botId, change.threadId !== undefined && due.get(change.botId)!.has(change.threadId) ? change.threadId : undefined); return; }
if (change.type !== "message" && change.type !== "message.patch") return;
diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.ts
index 72e9f8b8b2..e909b866d8 100644
--- a/server/runtime-coordinator.test.ts
+++ b/server/runtime-coordinator.test.ts
@@ -9,6 +9,8 @@ import type { RoomAddress } from "./coordinator.ts";
import { needsInputQuestion, RuntimeCoordinator, view } from "./runtime-coordinator.ts";
import { ENVELOPE_MARK } from "./runtime/envelope.ts";
import { TURN_CUT, type Assignment, type Level, type Limits } from "./runtime/types.ts";
+import { createHandedClose, type HandedCloseDeps, STOP_GRACE_MS, SYSTEM_STOP } from "./host/finished-work.ts";
+import type { TaskRecord } from "./store.ts";
import { removeTempDir } from "./testing/cleanup.ts";
const flush = () => new Promise<void>(resolve => setImmediate(resolve));
@@ -920,6 +922,82 @@ describe("RuntimeCoordinator: stops", () => {
});
});
+describe("RuntimeCoordinator: a Stop's cause reaches the close of each thread it ended", () => {
+ /** The host's close of hand-off threads, fed by the coordinator's reports as they happen: the due time it gives each thread. */
+ const closing = (w: World, openers: Record<string, string> = {}) => {
+ const tasks = new Map<string, TaskRecord>();
+ const record = (botId: string, threadId: string) => {
+ const key = `${botId}/${threadId}`;
+ if (!tasks.has(key)) tasks.set(key, { threadId, title: "Work", unread: true, openedBy: { botId: openers[botId] ?? "chief", name: "Opener", threadId: "chief-chat", at: 0, oneShot: true } } as TaskRecord);
+ return tasks.get(key)!;
+ };
+ const close = createHandedClose({
+ store: {
+ bots: [], bot: () => undefined, botByThread: () => undefined, onChange: () => () => {},
+ taskByThread: (botId: string, threadId: string) => record(botId, threadId),
+ setTaskOpenedBy: (botId: string, threadId: string, openedBy: TaskRecord["openedBy"]) => { record(botId, threadId).openedBy = openedBy; return null; },
+ setTaskClosedBy: () => null, patchTask: () => null,
+ } as unknown as HandedCloseDeps["store"],
+ working: () => false, waitArmed: () => false, node: (id) => w.coordinator.node(id), now: () => 1_000,
+ });
+ const report = w.host.report.bind(w.host);
+ w.host.report = (child, parent) => { report(child, parent); if (parent) close.ended(child, parent, false); };
+ return { closesAt: (address: RoomAddress) => record(address.botId, address.threadId).openedBy?.closesAt, dispose: () => close.dispose() };
+ };
+
+ it("gives work that never started the person's hour, and closes it at once for a system stop", () => {
+ for (const [cause, due] of [[undefined, 1_000 + STOP_GRACE_MS], [SYSTEM_STOP.bot, 1_000]] as const) {
+ const w = world(hold);
+ const close = closing(w);
+ const { node: t } = send(w, chief, "gen-1", undefined, tester, "Test it");
+ w.host.busyAnswer = node => node.botId === "tester";
+ w.coordinator.tick();
+ w.coordinator.stopAwaitingDirect("chief-chat", cause);
+ expect(w.coordinator.node(t.id)).toMatchObject({ status: "cancelled", result: "Stopped before it started" });
+ expect(close.closesAt(tester)).toBe(due);
+ close.dispose();
+ }
+ });
+
+ it("gives work handed on twice the person's hour, the stop read up the line as each report comes", () => {
+ for (const [cause, due] of [[undefined, 1_000 + STOP_GRACE_MS], [SYSTEM_STOP.bot, 1_000]] as const) {
+ const w = world(hold);
+ const close = closing(w, { tester: "builder" });
+ const { node: b } = send(w, chief, "gen-1", undefined, builder, "Build it");
+ w.coordinator.tick();
+ const { node: t } = send(w, builder, "gen-1", b.id, tester, "Test it");
+ w.host.busyAnswer = node => node.botId === "tester";
+ w.coordinator.tick();
+ expect(w.coordinator.node(t.id)?.status).toBe("queued");
+ w.coordinator.stopAwaitingDirect("chief-chat", cause);
+ expect(w.coordinator.node(t.id)).toMatchObject({ status: "cancelled", result: "Stopped with the request it was for" });
+ expect(close.closesAt(builder)).toBe(due);
+ expect(close.closesAt(tester)).toBe(due);
+ close.dispose();
+ }
+ });
+
+ it("gives work a restart left to resume the person's hour, and closes it at once for a system stop", async () => {
+ for (const [cause, due] of [[undefined, 1_000 + STOP_GRACE_MS], [SYSTEM_STOP.bot, 1_000]] as const) {
+ const dir = mkdtempSync(join(tmpdir(), "runtime-coordinator-"));
+ try {
+ const before = world(hold, {}, dir);
+ const { node } = send(before, chief, "gen-1", undefined, builder, "Build it");
+ before.coordinator.tick();
+ before.coordinator.close();
+ const after = world(undefined, {}, dir);
+ const close = closing(after);
+ expect(after.coordinator.node(node.id)).toMatchObject({ status: "queued", restart: "rerun" });
+ after.coordinator.stopAwaitingDirect("chief-chat", cause);
+ expect(after.coordinator.node(node.id)).toMatchObject({ status: "cancelled", result: "Stopped before it resumed" });
+ expect(close.closesAt(builder)).toBe(due);
+ close.dispose();
+ after.coordinator.close();
+ } finally { await removeTempDir(dir); }
+ }
+ });
+});
+
describe("RuntimeCoordinator: the person stops one hand-off", () => {
const holdAll: Script = () => "hold";
diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.ts
index ca92fb8ceb..9b736fb518 100644
--- a/server/runtime/runtime.ts
+++ b/server/runtime/runtime.ts
@@ -680,13 +680,13 @@ export class Runtime {
if (!ownsConversation(snapshot, owner)) continue;
const n = this.store.get(snapshot.id);
if (!n || isTerminal(n)) continue;
- for (const child of this.store.children(n.id)) {
- if (isTerminal(child)) continue;
+ const children = this.store.children(n.id).filter(child => !isTerminal(child));
+ // The request ends first, so the report of each piece of its work already finds whose stop it was up the line.
+ this.settle(n, "cancelled", "stopped", reason);
+ for (const child of children) {
const unstarted = child.status === "queued" && (child.executions === 0 || child.restart === "rerun");
- this.cancelTree(child, !unstarted ? STOPPED_WITH_REQUEST : child.restart === "rerun" ? STOPPED_BEFORE_RESUME : STOPPED_BEFORE_START,
- "cancelled", "stopped");
+ this.stopTree(child, !unstarted ? STOPPED_WITH_REQUEST : child.restart === "rerun" ? STOPPED_BEFORE_RESUME : STOPPED_BEFORE_START);
}
- this.settle(n, "cancelled", "stopped", reason);
}
});
}
@@ -751,6 +751,15 @@ export class Runtime {
if (fresh && !isTerminal(fresh)) this.settle(fresh, status, outcome, reason);
}
+ /** Stops `n`, then what it handed on, each down the line after the request it went down with. */
+ private stopTree(n: Assignment, reason: string): void {
+ const fresh = this.store.get(n.id);
+ if (!fresh || isTerminal(fresh)) return;
+ const children = this.store.children(n.id).filter(child => !isTerminal(child));
+ this.settle(fresh, "cancelled", "stopped", reason);
+ for (const child of children) this.stopTree(child, STOPPED_WITH_REQUEST);
+ }
+
private settle(n: Assignment, status: TerminalStatus, outcome: Outcome, detail?: string, ownTurn = false): void {
if (isTerminal(n)) return;
const now = this.clock.now();