Skip to content

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

fix(handoffs): close a hand-off thread as its wait goes, and keep the person's hour for queued work

luishron1231fc1e36025c1
diff --git a/server/handed-waits.e2e.test.ts b/server/handed-waits.e2e.test.ts
index c81607da30..556e397daf 100644
--- a/server/handed-waits.e2e.test.ts
+++ b/server/handed-waits.e2e.test.ts
@@ -100,7 +100,7 @@ describe("waits set by work a bot handed on", () => {
finish(sourceThread);
}, 60_000);
- it("closes a thread \"new\" opened but keeps it out of the archive while its wait is armed, so the wait's message is seen", async () => {
+ it("keeps a thread \"new\" opened open while its wait is armed, so the wait's message is seen, and closes it once that is read", async () => {
const sourceThread = (await api("GET", "/api/bots?messages=0")).bots.find((bot: any) => bot.id === source.id).threadId;
await control(["send", "--bot", source.id, "--text", "Have the peer tell me when the report lands."]);
const { receipts } = await api("POST", "/api/internal/coordinate-bots", { botIds: [peer.id], message: "Watch for the fixture report.", thread: "new" }, await token(sourceThread));
@@ -110,14 +110,22 @@ describe("waits set by work a bot handed on", () => {
expect(made.status, JSON.stringify(made.body)).toBe(201);
const peerTask = async () => (await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === peer.id).tasks.find((task: any) => task.threadId === work.threadId);
finish(work.threadId);
- await expect.poll(async () => (await peerTask()).closedBy?.botId, { timeout: 15_000 }).toBe(source.id);
+ // Its work is reported back: the thread is due to close, but the armed wait holds it.
+ await expect.poll(async () => typeof (await peerTask()).openedBy?.closesAt, { timeout: 15_000 }).toBe("number");
+ expect(await peerTask()).not.toHaveProperty("closedBy");
expect(await peerTask()).not.toHaveProperty("archivedAt");
writeFileSync(join(folder, "report.txt"), "here");
await expect.poll(async () => (await api("GET", `/api/threads/${work.threadId}/messages`)).messages.some((m: any) => m.wait?.status === "fired"), { timeout: 30_000 }).toBe(true);
expect(storedWaits()).toEqual([]);
expect(await peerTask()).toMatchObject({ unread: true });
+ expect(await peerTask()).not.toHaveProperty("closedBy");
expect(await peerTask()).not.toHaveProperty("archivedAt");
+
+ // The person reads the wait's message: nothing holds the thread now, so it closes into the archive.
+ expect((await call("POST", `/api/bots/${peer.id}/read`, { threadId: work.threadId })).status).toBe(200);
+ await expect.poll(async () => (await peerTask()).closedBy?.botId, { timeout: 15_000 }).toBe(source.id);
+ expect(typeof (await peerTask()).archivedAt).toBe("number");
finish(sourceThread);
}, 60_000);
diff --git a/server/host/finished-work.test.ts b/server/host/finished-work.test.ts
index 0ce071fc02..50529f0306 100644
--- a/server/host/finished-work.test.ts
+++ b/server/host/finished-work.test.ts
@@ -1,8 +1,12 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { HandoffView } from "../coordinator.ts";
import type { BotRecord, Message, StoreChange, TaskRecord } from "../store.ts";
-import { archivedOnResult, archivesOnResult, closesOnResult, createHandedClose, finishHandedThread, opensAgain, reopenHandedThread, STOP_GRACE_MS, stoppedByPerson, SYSTEM_STOP } from "./finished-work.ts";
+import { WaitManager } from "../waits.ts";
+import { archivedOnResult, archivesOnResult, closesOnResult, createHandedClose, finishHandedThread, type HandedCloseDeps, opensAgain, reopenHandedThread, STOP_GRACE_MS, stoppedByPerson, SYSTEM_STOP } from "./finished-work.ts";
type Task = Parameters<typeof closesOnResult>[0];
const opened = (more: Partial<NonNullable<TaskRecord["openedBy"]>> = {}): NonNullable<TaskRecord["openedBy"]> =>
@@ -137,6 +141,26 @@ describe("stoppedByPerson", () => {
expect(stoppedByPerson(ended({ outcomeDetail: "Stopped with the request it was for" }), { outcomeDetail: "The routine restarted" })).toBe(false);
expect(stoppedByPerson({ status: "failed", outcome: "stalled", outcomeDetail: "Stopped by user" })).toBe(false);
});
+
+ it("follows queued work the person's Stop ended before it started or resumed to that Stop, and a system stop to the system", () => {
+ for (const cause of ["Stopped before it started", "Stopped before it resumed"]) {
+ expect(stoppedByPerson(ended({ outcomeDetail: cause }), { outcomeDetail: "Stopped by user" })).toBe(true);
+ expect(stoppedByPerson(ended({ outcomeDetail: cause }), { outcomeDetail: "The coordinated turn was cut" })).toBe(false);
+ expect(stoppedByPerson(ended({ outcomeDetail: cause }), { outcomeDetail: "Stopped by @Clive, who handed this work on" })).toBe(false);
+ expect(stoppedByPerson(ended({ outcomeDetail: cause }))).toBe(false);
+ }
+ });
+
+ it("follows work handed on twice up to the conversation whose stop ended it", () => {
+ const nodes: Record<string, Pick<HandoffView, "outcomeDetail" | "parentId">> = {
+ person: { outcomeDetail: "Stopped by user" },
+ system: { outcomeDetail: "The routine restarted" },
+ };
+ const middle = (root: string) => ({ outcomeDetail: "Stopped with the request it was for", parentId: root });
+ expect(stoppedByPerson(ended({ outcomeDetail: "Stopped before it started" }), middle("person"), (id) => nodes[id])).toBe(true);
+ expect(stoppedByPerson(ended({ outcomeDetail: "Stopped with the request it was for" }), middle("person"), (id) => nodes[id])).toBe(true);
+ expect(stoppedByPerson(ended({ outcomeDetail: "Stopped before it started" }), middle("system"), (id) => nodes[id])).toBe(false);
+ });
});
describe("opensAgain", () => {
@@ -170,11 +194,11 @@ describe("createHandedClose", () => {
patchTask: (_botId: string, _threadId: string, patch: Partial<TaskRecord>) => { Object.assign(record, patch); return changed(); },
onChange: (listener: (change: StoreChange) => void) => { listeners.add(listener); return () => listeners.delete(listener); },
};
- const start = () => { const close = createHandedClose({ store, working: () => live.working, waitArmed: () => live.waitArmed }); vi.advanceTimersByTime(0); return close; };
+ const start = (more: Partial<HandedCloseDeps> = {}) => { const close = createHandedClose({ store, working: () => live.working, waitArmed: () => live.waitArmed, ...more }); vi.advanceTimersByTime(0); return close; };
const write = (message: Partial<Message>) => emit({ type: "message", threadId: record.threadId, message: message as Message });
/** Something on the thread changed outside this module: it was read, a question was answered, a turn ended. */
const update = (patch: Partial<TaskRecord>) => { Object.assign(record, patch); changed(); };
- return { record, live, start, write, update };
+ return { record, live, start, write, update, emit };
};
const chief = { id: "chief-node", botId: "chief", threadId: "chief-chat" } as HandoffView;
const work = (more: Partial<HandoffView>) => ({ id: "h1", parentId: "chief-node", botId: "lead", threadId: "lead-thread", status: "completed", ...more }) as HandoffView;
@@ -234,7 +258,6 @@ describe("createHandedClose", () => {
const cases: Array<[Partial<TaskRecord>, { working: boolean; waitArmed: boolean }, (w: ReturnType<typeof world>) => void]> = [
[{ unread: true }, { working: false, waitArmed: false }, (w) => w.update({ unread: false })],
[{ activity: "waiting-on-you" }, { working: false, waitArmed: false }, (w) => w.update({ activity: "idle" })],
- [{}, { working: false, waitArmed: true }, (w) => { w.live.waitArmed = false; w.update({}); }],
];
for (const [task, live, settle] of cases) {
const w = world({ openedBy: oneShot(), ...task }, { ...live });
@@ -249,6 +272,101 @@ describe("createHandedClose", () => {
}
});
+ describe("with the thread's bot waiting on something", () => {
+ const dirs: string[] = [];
+ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+ /** The real wait list, as the host wires it: a wait going tells the close to look again. */
+ const waiting = async (w: ReturnType<typeof world>, followUp?: string, post: () => boolean = () => true, report = { there: false }) => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-handed-waits-"));
+ dirs.push(dir);
+ let close: ReturnType<typeof createHandedClose> | undefined;
+ const waits = new WaitManager({
+ file: join(dir, "waits.json"), now: () => Date.now(), probes: { stamp: async () => (report.there ? { size: 4, mtimeMs: 1 } : null) },
+ sourceAlive: () => true, botBusy: () => false, post, followUp: () => {}, showCard: () => "card-1", settleCard: () => {},
+ ended: (wait) => close?.look(wait.botId),
+ });
+ close = w.start({ waitArmed: (botId, threadId) => waits.all().some((wait) => wait.botId === botId && wait.threadId === threadId) });
+ const made = await waits.create({ botId: "lead", threadId: "lead-thread", label: "the report", condition: { kind: "file_exists", path: "/nowhere/report.pdf" }, ...(followUp ? { followUp } : {}) });
+ if (made.state !== "created") throw new Error(`no wait: ${made.state}`);
+ return { close, waits, wait: made.wait };
+ };
+
+ it("closes the thread once the last wait there is cancelled, with nothing else changing", async () => {
+ for (const followUp of [undefined, "Send the report on"]) {
+ const w = world({ openedBy: oneShot() });
+ const { close, waits, wait } = await waiting(w, followUp);
+ const from = Date.now();
+ close.ended(work({}), chief, false);
+ expect(w.record.closedBy).toBeUndefined();
+ expect(w.record.archivedAt).toBeUndefined();
+ vi.advanceTimersByTime(5_000);
+ expect(waits.cancel(wait.id, "lead")).not.toBeNull();
+ expect(w.record).toMatchObject(closedAt(from + 5_000));
+ }
+ });
+
+ it("keeps the thread open through a wait's firing, so its message is read there, and closes it once read", async () => {
+ const w = world({ openedBy: oneShot() });
+ const report = { there: false };
+ // As the host posts a wait's message: the line lands first, then the thread is marked unread.
+ const { close, waits } = await waiting(w, undefined, () => {
+ w.emit({ type: "message", threadId: "lead-thread", message: { role: "bot", kind: "text" } as Message });
+ w.update({ unread: true });
+ return true;
+ }, report);
+ close.ended(work({}), chief, false);
+ report.there = true;
+ vi.advanceTimersByTime(60_000);
+ await waits.tick();
+ expect(waits.all()).toEqual([]);
+ expect(w.record.unread).toBe(true);
+ expect(w.record.closedBy).toBeUndefined();
+ expect(w.record.archivedAt).toBeUndefined();
+ w.update({ unread: false });
+ expect(w.record.archivedAt).toBe(1_000_000 + 60_000);
+ });
+
+ it("closes the thread once its bot, and so its waits, are gone", async () => {
+ const w = world({ openedBy: oneShot() });
+ const { close, waits } = await waiting(w);
+ close.ended(work({}), chief, false);
+ expect(w.record.archivedAt).toBeUndefined();
+ expect(waits.removeForBot("lead")).toBe(1);
+ expect(w.record.archivedAt).toBe(1_000_000);
+ });
+ });
+
+ it("looks again when a card in a due thread is settled, though the bot does not change", () => {
+ const { record, start, live, emit } = world({ openedBy: oneShot() }, { working: true, waitArmed: false });
+ start().ended(work({}), chief, false);
+ expect(record.archivedAt).toBeUndefined();
+ live.working = false;
+ emit({ type: "message.patch", threadId: "lead-thread", message: { role: "bot" } as Message });
+ expect(record.archivedAt).toBe(1_000_000);
+ });
+
+ it("gives queued work the person's Stop ended before it started or resumed the hour, and closes it at once for a system stop", () => {
+ for (const cause of ["Stopped before it started", "Stopped before it resumed"]) {
+ const person = world({ openedBy: oneShot() });
+ person.start().ended(work({ status: "cancelled", outcome: "stopped", outcomeDetail: cause }), { ...chief, outcomeDetail: "Stopped by user" }, false);
+ expect(person.record.archivedAt).toBeUndefined();
+ expect(person.record.openedBy?.closesAt).toBe(Date.now() + STOP_GRACE_MS);
+ const system = world({ openedBy: oneShot() });
+ system.start().ended(work({ status: "cancelled", outcome: "stopped", outcomeDetail: cause }), { ...chief, outcomeDetail: SYSTEM_STOP.turn }, false);
+ expect(system.record).toMatchObject(closedAt(Date.now()));
+ }
+ });
+
+ it("gives work handed on from work the person stopped the hour, reading up the line", () => {
+ const { record, start } = world({ openedBy: oneShot() });
+ const nodes: Record<string, HandoffView> = { root: { ...chief, id: "root", outcomeDetail: "Stopped by user" } };
+ const middle = { ...chief, id: "chief-node", parentId: "root", outcomeDetail: "Stopped with the request it was for" } as HandoffView;
+ start({ node: (id) => nodes[id] }).ended(work({ status: "cancelled", outcome: "stopped", outcomeDetail: "Stopped before it started" }), middle, false);
+ expect(record.closedBy).toBeUndefined();
+ vi.advanceTimersByTime(STOP_GRACE_MS);
+ expect(record.archivedAt).toBe(1_000_000 + STOP_GRACE_MS);
+ });
+
it("closes a one-shot thread a bot posted into and the person wrote in during the work", () => {
const { record, start, write } = world({ openedBy: oneShot(), askedAt: 5 });
const close = start();
diff --git a/server/host/finished-work.ts b/server/host/finished-work.ts
index 070a8cde8a..a0d809dd1f 100644
--- a/server/host/finished-work.ts
+++ b/server/host/finished-work.ts
@@ -4,7 +4,7 @@
// there waits on the person. The person's Stop makes it due only an hour later, so a stop by mistake can be taken back by
// writing there. A new message takes the due close off, and brings a closed thread back. Every other thread stays as it is.
import type { HandoffView } from "../coordinator.ts";
-import { STOPPED_BY_USER, STOPPED_WITH_REQUEST } from "../runtime/types.ts";
+import { STOPPED_BEFORE_RESUME, STOPPED_BEFORE_START, STOPPED_BY_USER, STOPPED_WITH_REQUEST, TURN_CUT } from "../runtime/types.ts";
import type { Message, Store, TaskRecord } from "../store.ts";
/** How long a thread whose work the person stopped stays open before it closes. */
@@ -57,12 +57,26 @@ export function reopenHandedThread(store: Pick<Store, "patchTask" | "setTaskClos
store.setTaskClosedBy(ownerBotId, task.threadId, null);
}
-/** Whether handed-off work ended on the person's Stop: in its own thread, or in the conversation that handed it on. A stop
- * the system made (a restart, a deleted conversation, a turn that could not start) or its requester made carries another
- * cause. */
-export function stoppedByPerson(child: Pick<HandoffView, "status" | "outcome" | "outcomeDetail">, parent?: Pick<HandoffView, "outcomeDetail">): boolean {
+/** The causes a stop leaves on work that only went down with the request it was for, so whose stop it was is that request's. */
+const STOPPED_WITH_IT: readonly string[] = [STOPPED_WITH_REQUEST, STOPPED_BEFORE_START, STOPPED_BEFORE_RESUME];
+
+/** Whether handed-off work ended on the person's Stop: in its own thread, or in a conversation up the line that handed it
+ * on, the work that never started or was due to start again included. A stop the system made (a restart, a deleted
+ * conversation, a turn that could not start) or its requester made carries another cause. `node` finds the requests above
+ * `parent`. */
+export function stoppedByPerson(
+ child: Pick<HandoffView, "status" | "outcome" | "outcomeDetail">,
+ parent?: Pick<HandoffView, "outcomeDetail" | "parentId">,
+ node: (id: string) => Pick<HandoffView, "outcomeDetail" | "parentId"> | undefined = () => undefined,
+): boolean {
if (child.status !== "cancelled" || child.outcome !== "stopped") return false;
- return child.outcomeDetail === STOPPED_BY_USER || (child.outcomeDetail === STOPPED_WITH_REQUEST && parent?.outcomeDetail === STOPPED_BY_USER);
+ let cause = child.outcomeDetail;
+ let above = parent;
+ for (let hops = 0; cause !== undefined && STOPPED_WITH_IT.includes(cause) && above && hops < 64; hops++) {
+ cause = above.outcomeDetail;
+ above = above.parentId ? node(above.parentId) : undefined;
+ }
+ return cause === STOPPED_BY_USER;
}
/** The causes the server gives the stops it makes itself, so none reads as the person's Stop. */
@@ -73,6 +87,8 @@ export const SYSTEM_STOP = {
dispatch: "The turn could not start",
/** The goal or routine run this turn served ended. */
goal: "The goal this turn served ended",
+ /** A coordinated turn's own abort: the stop under way, if any, else the system's cut (see stopAwaitingDirect). */
+ turn: TURN_CUT,
} as const;
/** A message that brings a closed hand-off thread back: the person writing, a bot posting into it, or new work handed there.
@@ -85,75 +101,121 @@ export interface HandedCloseDeps {
store: FinishStore & Pick<Store, "bots" | "botByThread" | "setTaskOpenedBy" | "onChange">;
/** Handed-off work is still live in the thread: queued, running, or parked on a question. */
working(threadId: string): boolean;
- /** A wait `botId` set in the thread is still armed. */
+ /** A wait `botId` set in the thread is still armed, or ended and its message not yet there. */
waitArmed(botId: string, threadId: string): boolean;
+ /** The hand-off with that id, to read whose stop ended the work. */
+ node?(id: string): Pick<HandoffView, "outcomeDetail" | "parentId"> | undefined;
now?: () => number;
}
+export interface HandedClose {
+ ended(child: HandoffView, parent: HandoffView, problem: boolean): void;
+ /** Something that held `botId`'s due threads, outside its threads, is gone: a wait it set fired, expired or was cancelled. */
+ look(botId: string): void;
+ dispose(): void;
+}
+
/** Closes hand-off threads as their work ends. A one-shot thread is marked due (`openedBy.closesAt`: now, or an hour on for
* the person's Stop) and closes into the archive once the moment has come, no bot works there and nothing waits on the
- * person. The standing work thread closes at once, or an hour after the person's Stop, once no bot works there. Each change to that bot's threads looks again, so a read, an answer or a turn's end lets it close. The mark is kept
- * on the thread, so a restart picks it up. */
-export function createHandedClose(deps: HandedCloseDeps): { ended(child: HandoffView, parent: HandoffView, problem: boolean): void; dispose(): void } {
+ * person. The standing work thread closes at once, or an hour after the person's Stop, once no bot works there. A change
+ * to a due thread, its bot or its messages looks again, so a read, an answer, a decided card or a turn's end lets it
+ * close; a wait going calls `look`. Only the due threads are looked at, kept in an index. The mark is kept on the thread,
+ * so a restart picks it up. */
+export function createHandedClose(deps: HandedCloseDeps): HandedClose {
const { store } = deps;
const now = deps.now ?? Date.now;
let timer: ReturnType<typeof setTimeout> | undefined;
let looking = false;
// The host builds this before the coordinator `working` asks, so the first look waits for the boot to finish.
let started = false;
+ /** The due threads, by bot: `openedBy.closesAt` is set on each. Filled from the saved threads at boot. */
+ const due = new Map<string, Set<string>>();
+ const index = (botId: string, threadId: string, on: boolean) => {
+ const threads = due.get(botId) ?? new Set<string>();
+ if (on) threads.add(threadId); else threads.delete(threadId);
+ if (threads.size) due.set(botId, threads); else due.delete(botId);
+ };
+ const dueTask = (botId: string, threadId: string) => {
+ const task = store.taskByThread(botId, threadId);
+ if (task?.openedBy?.closesAt !== undefined) return task;
+ index(botId, threadId, false);
+ return undefined;
+ };
- const due = (botId?: string) => store.bots.filter((bot) => botId === undefined || bot.id === botId)
- .flatMap((bot) => (bot.tasks ?? []).filter((task) => task.openedBy?.closesAt !== undefined).map((task) => ({ botId: bot.id, task })));
const arm = () => {
if (timer) clearTimeout(timer);
timer = undefined;
const at = now();
- const next = Math.min(...due().map(({ task }) => task.openedBy!.closesAt!).filter((closesAt) => closesAt > at));
+ let next = Infinity;
+ for (const [botId, threads] of due) {
+ for (const threadId of threads) {
+ const closesAt = dueTask(botId, threadId)?.openedBy!.closesAt;
+ if (closesAt !== undefined && closesAt > at) next = Math.min(next, closesAt);
+ }
+ }
if (!Number.isFinite(next)) return;
timer = setTimeout(() => { timer = undefined; look(); arm(); }, next - at);
timer.unref?.();
};
const unmark = (botId: string, task: TaskRecord) => {
+ index(botId, task.threadId, false);
const { closesAt: _closesAt, ...openedBy } = task.openedBy!;
store.setTaskOpenedBy(botId, task.threadId, openedBy);
};
- const holds = (botId: string, task: TaskRecord) => deps.working(task.threadId) || task.busy === true || task.activity === "working"
- || !archivesOnResult(task, deps.waitArmed(botId, task.threadId));
+ const busy = (task: TaskRecord) => deps.working(task.threadId) || task.busy === true || task.activity === "working";
/** Closes each due thread nothing holds; one that no longer closes (the person pinned it, say) loses the mark. */
- const look = (botId?: string) => {
+ const look = (botId?: string, threadId?: string) => {
if (looking || !started) return;
looking = true;
try {
const at = now();
- for (const { botId: owner, task } of due(botId)) {
- if (task.openedBy!.closesAt! > at) continue;
- const opener = task.openedBy!.botId;
- if (!closesOnResult(task, opener, owner)) { unmark(owner, task); continue; }
- if (task.openedBy!.kind === "work") {
- if (deps.working(task.threadId) || task.busy === true || task.activity === "working") continue;
+ const owners = botId === undefined ? [...due.keys()] : [botId];
+ for (const owner of owners) {
+ for (const id of threadId === undefined ? [...due.get(owner) ?? []] : [threadId]) {
+ const task = dueTask(owner, id);
+ if (!task || task.openedBy!.closesAt! > at) continue;
+ const opener = task.openedBy!.botId;
+ if (!closesOnResult(task, opener, owner)) { unmark(owner, task); continue; }
+ if (busy(task)) continue;
+ if (task.openedBy!.kind === "work") {
+ unmark(owner, task);
+ finishHandedThread(store, owner, task.threadId, opener, at);
+ continue;
+ }
+ if (!archivesOnResult(task, deps.waitArmed(owner, task.threadId))) continue;
unmark(owner, task);
- finishHandedThread(store, owner, task.threadId, opener, at);
- continue;
+ store.setTaskClosedBy(owner, task.threadId, { botId: opener, name: store.bot(opener)?.name ?? task.openedBy!.name, at });
+ store.patchTask(owner, task.threadId, { archivedAt: at });
}
- if (holds(owner, task)) continue;
- unmark(owner, task);
- store.setTaskClosedBy(owner, task.threadId, { botId: opener, name: store.bot(opener)?.name ?? task.openedBy!.name, at });
- store.patchTask(owner, task.threadId, { archivedAt: at });
}
} finally { looking = false; }
};
+ const dueOwner = (threadId: string) => {
+ for (const [botId, threads] of due) if (threads.has(threadId)) return botId;
+ return undefined;
+ };
const unsubscribe = store.onChange((change) => {
if (looking || !started) return;
- if (change.type === "bot") { look(change.botId); return; }
- if (change.type !== "message" || !opensAgain(change.message)) return;
- const botId = store.botByThread(change.threadId)?.id;
- const task = botId ? store.taskByThread(botId, change.threadId) : undefined;
- if (!botId || !task) return;
- if (task.openedBy?.closesAt !== undefined) { unmark(botId, task); arm(); }
- reopenHandedThread(store, botId, task);
+ 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;
+ if (change.type === "message" && opensAgain(change.message)) {
+ const botId = store.botByThread(change.threadId)?.id;
+ const task = botId ? store.taskByThread(botId, change.threadId) : undefined;
+ if (!botId || !task) return;
+ if (task.openedBy?.closesAt !== undefined) { unmark(botId, task); arm(); }
+ reopenHandedThread(store, botId, task);
+ return;
+ }
+ const owner = dueOwner(change.threadId);
+ if (owner !== undefined) look(owner, change.threadId);
});
- const boot = setTimeout(() => { started = true; look(); arm(); }, 0);
+ const boot = setTimeout(() => {
+ for (const bot of store.bots) for (const task of bot.tasks ?? []) if (task.openedBy?.closesAt !== undefined) index(bot.id, task.threadId, true);
+ started = true;
+ look();
+ arm();
+ }, 0);
boot.unref?.();
return {
@@ -162,15 +224,17 @@ export function createHandedClose(deps: HandedCloseDeps): { ended(child: Handoff
if (child.status === "completed" && problem) return;
const task = store.taskByThread(child.botId, child.threadId);
if (!task?.openedBy || !closesOnResult(task, parent.botId, child.botId)) return;
- const stopped = stoppedByPerson(child, parent);
+ const stopped = stoppedByPerson(child, parent, deps.node);
if (task.openedBy.kind === "work" && !stopped) {
if (!deps.working(child.threadId)) finishHandedThread(store, child.botId, child.threadId, parent.botId, now());
return;
}
store.setTaskOpenedBy(child.botId, child.threadId, { ...task.openedBy, closesAt: now() + (stopped ? STOP_GRACE_MS : 0) });
- look(child.botId);
+ index(child.botId, child.threadId, true);
+ look(child.botId, child.threadId);
arm();
},
+ look(botId) { if (due.has(botId)) look(botId); },
dispose() {
unsubscribe();
clearTimeout(boot);
diff --git a/server/index.ts b/server/index.ts
index 7ccdf336ff..0839912819 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -3801,7 +3801,7 @@ function runRootTurn(node: HandoffView, bot: BotRecord, signal: AbortSignal, com
done = true; signal.removeEventListener("abort", abort); resolve(outcome);
};
const abort = () => {
- void interruptDirectThread(bot.id, node.threadId).catch(() => {});
+ void interruptDirectThread(bot.id, node.threadId, SYSTEM_STOP.turn).catch(() => {});
finish({ ok: false, text: "The turn was stopped" });
};
signal.addEventListener("abort", abort, { once: true });
@@ -3841,7 +3841,7 @@ const questionRouting = createQuestionRouting({ store, handedInUnproven, active:
steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused", mayReach: outsideLineage.mayReach });
const remoteTeammates = new RemoteTeammates(); const remoteHandoff = createRemoteHandoff({ teammates: remoteTeammates, coordinator: () => coordinator, localBots: () => store.bots, botName: (id) => store.bot(id)?.name, outside: (threadId) => (outsideLineage.outsideDrivenThread(threadId) || outsideLineage.cloudGuestDriven(threadId) ? OUTSIDE_STAYS_HERE : undefined), file: join(DATA_DIR, "remote-teammate-work.json"), log: (line) => console.error(line) }); const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, botName: (id) => store.bot(id)?.name, node: (id) => coordinator.node(id), children: (id) => coordinator.children(id), discard: deleteAttachment, threadsReferencing, changes: (listener) => store.onChange(listener), log: (line) => console.error(line),
worksInOwnFolder: (botId, threadId) => turnsRunInOwnFolder(botId, threadId, store.taskByThread(botId, threadId)?.cwd, store.bot(botId)?.cwd, Boolean(store.groupByThread(threadId))), vmHome: (botId) => localVmMode(cfg) === "per-bot" ? perBotLocalVmTarget(botId).workspaceDir : null, withheld: (child, parent) => Boolean(roomHandoffProblem(child, parent)) || keptPrivate({ child: teamHost.privateTo(child.threadId), parent: teamHost.privateTo(parent.threadId) }) });
-const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => handedMainThread(store.bot(botId), (threadId) => store.taskByThread(botId, threadId)?.archivedAt !== undefined, () => botMainThread(botId) ?? store.bot(botId)?.threadId) }; const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handedClose = createHandedClose({ store, working: (threadId) => coordinator.activeDirect(threadId), waitArmed: (botId, threadId) => botWaits.list(botId).some((wait) => wait.threadId === threadId) }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
+const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => handedMainThread(store.bot(botId), (threadId) => store.taskByThread(botId, threadId)?.archivedAt !== undefined, () => botMainThread(botId) ?? store.bot(botId)?.threadId) }; const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handedClose = createHandedClose({ store, working: (threadId) => coordinator.activeDirect(threadId), node: (id) => coordinator.node(id), waitArmed: (botId, threadId) => botWaits.all().some((wait) => wait.botId === botId && wait.threadId === threadId) }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
dataDir: DATA_DIR, restartCut: restartCutStop({ dataDir: DATA_DIR, lines: (threadId) => store.activePath(threadId) }),
now: Date.now, wrote: () => { handoffTicks.kick(); handoffStatus.changed(); }, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },
log: line => console.error("coordinator:", line),
@@ -3980,7 +3980,7 @@ const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store
done = true; signal.removeEventListener("abort", abort); resolve(privateHandBack(outcome, { child: person, parent: parent ? teamHost.privateTo(parent.threadId) : null, bot: bot.name, person: (person && teamHost.personName(person)) || "them" }));
};
const abort = () => {
- void interruptDirectThread(bot.id, node.threadId).catch(() => {});
+ void interruptDirectThread(bot.id, node.threadId, SYSTEM_STOP.turn).catch(() => {});
finish({ ok: false, text: "Coordinated work was stopped" });
};
signal.addEventListener("abort", abort, { once: true });
@@ -8810,7 +8810,7 @@ calendarCalls = new CalendarCallManager({
botExists: (botId) => Boolean(store.bot(botId)),
onDue: deliverCalendarCall,
});
-const checkBacks = createCheckBacks({ dataDir: DATA_DIR, alive: (botId, threadId) => directChatOf(botId, threadId), busy: (botId, threadId) => threadBusy(botId, threadId), line: (record, line, messageId) => writeCheckBackLine(store, record, line, messageId, threadLanguage(record.threadId)), start: async (record, prompt) => { await startTurn(record.botId, prompt, { threadId: record.threadId, cardContinuation: true, origin: record.origin }); }, paused: (error) => [BOT_HELD_CODE, BOT_PAUSED_CODE].includes(String((error as { code?: unknown } | null)?.code)) }); const botWaits = new WaitManager(createWaitHost({ store, directChat: directChatOf, threadBusy, wrote: markTaskContextExternallyUpdated, notify, enqueue: (input) => routines!.enqueueWebhook(input), cloudHome: Boolean(CLOUD_HOME) })); store.onChange((change) => { if (change.type === "bot" && store.bot(change.botId)?.busy) botWaits.noteBotBusy(change.botId); });
+const checkBacks = createCheckBacks({ dataDir: DATA_DIR, alive: (botId, threadId) => directChatOf(botId, threadId), busy: (botId, threadId) => threadBusy(botId, threadId), line: (record, line, messageId) => writeCheckBackLine(store, record, line, messageId, threadLanguage(record.threadId)), start: async (record, prompt) => { await startTurn(record.botId, prompt, { threadId: record.threadId, cardContinuation: true, origin: record.origin }); }, paused: (error) => [BOT_HELD_CODE, BOT_PAUSED_CODE].includes(String((error as { code?: unknown } | null)?.code)) }); const botWaits = new WaitManager({ ...createWaitHost({ store, directChat: directChatOf, threadBusy, wrote: markTaskContextExternallyUpdated, notify, enqueue: (input) => routines!.enqueueWebhook(input), cloudHome: Boolean(CLOUD_HOME) }), ended: (wait) => handedClose.look(wait.botId) }); store.onChange((change) => { if (change.type === "bot" && store.bot(change.botId)?.busy) botWaits.noteBotBusy(change.botId); });
const recoveryOwners = routines.routineRequestReceiptOwners();
if (recoveryOwners.length > 0) {
const recoveryThreads = [...new Set(recoveryOwners.map((owner) => owner.threadId))];
diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.ts
index b5914980a3..72e9f8b8b2 100644
--- a/server/runtime-coordinator.test.ts
+++ b/server/runtime-coordinator.test.ts
@@ -8,7 +8,7 @@ import type { BeginTurnRequest, ComposedTurn, CoordinatorHost, HandoffLimit, Han
import type { RoomAddress } from "./coordinator.ts";
import { needsInputQuestion, RuntimeCoordinator, view } from "./runtime-coordinator.ts";
import { ENVELOPE_MARK } from "./runtime/envelope.ts";
-import type { Assignment, Level, Limits } from "./runtime/types.ts";
+import { TURN_CUT, type Assignment, type Level, type Limits } from "./runtime/types.ts";
import { removeTempDir } from "./testing/cleanup.ts";
const flush = () => new Promise<void>(resolve => setImmediate(resolve));
@@ -1173,6 +1173,29 @@ describe("RuntimeCoordinator: a stop the system made is never remembered as the
expect(send(w, chief, "gen-1", undefined, builder, "Plan the pricing feature", { rework: true }).node).toMatchObject({ botId: "builder", status: "queued" });
});
+ it("never takes a coordinated turn's own abort, with no stop under way, for the person's stop", async () => {
+ const { w, work, followUp } = await handedOut();
+ w.coordinator.stopAwaitingDirect("builder-work", TURN_CUT);
+ expect(w.coordinator.node(work.id)).toMatchObject({ status: "cancelled", outcomeDetail: TURN_CUT });
+ expect(w.coordinator.node(followUp.id)?.status).toBe("cancelled");
+ expect(w.coordinator.node(followUp.id)?.outcomeDetail).not.toBe("Stopped by user");
+ await tick();
+ expect(send(w, chief, "gen-1", undefined, builder, "Plan the pricing feature", { rework: true }).node).toMatchObject({ botId: "builder", status: "queued" });
+ });
+
+ it("takes a coordinated turn's own abort within the person's Stop of one hand-off as that stop, sparing the rest of the queue", async () => {
+ const w = world(hold);
+ const { node: first } = send(w, chief, "gen-1", undefined, builder, "Build it");
+ const { node: second } = send(w, { botId: "tester", threadId: "tester-chat" }, "gen-2", undefined, builder, "Build the other one");
+ w.coordinator.tick();
+ await tick();
+ const run = w.host.runs.find(r => r.node.id === first.id)!;
+ run.signal.addEventListener("abort", () => w.coordinator.stopAwaitingDirect(run.node.threadId, TURN_CUT), { once: true });
+ expect(w.coordinator.stopHandoff(first.id)).toBe("stopped");
+ expect(w.coordinator.node(first.id)).toMatchObject({ status: "cancelled", outcomeDetail: "Stopped by user" });
+ expect(w.coordinator.node(second.id)?.status).not.toBe("cancelled");
+ });
+
it("still remembers the person's own stop of that work, with the same follow-up queued", async () => {
const { w, work } = await handedOut();
w.coordinator.stopAwaitingDirect("builder-work");
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index b3bcf855f5..8ef4d6678d 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -11,7 +11,7 @@ import { personOnly, requesterDecides, withDefault } from "./runtime/questions.t
import { isStatusOnly, mayBeStatusOnly, statusReplyPrompt } from "./runtime/status-reply.ts";
import { answersSender, childrenSince, clip, isTerminal, ownThread, path } from "./runtime/tree.ts";
import type { Answerer, Assignee, Assignment, EndResult, Origin, Owner, Reply, Requester, RunInput, RunResult, StatusView, TurnRunner } from "./runtime/types.ts";
-import { STOPPED_BY_USER } from "./runtime/types.ts";
+import { STOPPED_BY_USER, TURN_CUT } from "./runtime/types.ts";
import { sameRequest } from "./same-request.ts";
const NOT_RUNNING = "The originating room task is no longer running";
@@ -457,13 +457,15 @@ export class RuntimeCoordinator implements Coordinator {
this.stopFor(reason, () => { for (const n of this.live()) if (this.direct(n, threadId)) this.runtime.cancel(n.id, reason, "stopped"); });
}
- /** With no reason given, the stop is the person's, unless it is part of a stop already under way: see stopFor. */
+ /** With no reason given, the stop is the person's, unless it is part of a stop already under way: see stopFor. TURN_CUT,
+ * a coordinated turn's own abort, is that stop too, and with none under way the system's cut. */
stopAwaitingDirect(threadId: string, reason?: string): void {
this.ready();
// The host stops a teammate's whole thread when one of its turns is aborted; when that turn is one hand-off the person
// stopped, the runtime already ends that hand-off and what it handed on, and other requests queued there go on.
- if (reason === undefined && this.stoppingHandoff) return;
- const cause = reason ?? this.stopCause ?? STOPPED_BY_USER;
+ const inner = reason === undefined || reason === TURN_CUT;
+ if (inner && this.stoppingHandoff) return;
+ const cause = (inner ? this.stopCause : undefined) ?? reason ?? STOPPED_BY_USER;
const stopping = cause === STOPPED_BY_USER ? this.live().filter(n => n.assignee.destination.threadId === threadId) : [];
const trees = stopping.map(n => ({ root: this.store.get(n.rootId), work: this.subtree(n).filter(a => !isTerminal(a)) }));
this.stopFor(cause, () => this.runtime.stopRequester({ threadId }, cause));
diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.ts
index f59498e8b9..ca92fb8ceb 100644
--- a/server/runtime/runtime.ts
+++ b/server/runtime/runtime.ts
@@ -7,7 +7,7 @@ import { composeEnvelope } from "./envelope.ts";
import { assignmentLevel } from "./level.ts";
import type { RuntimeStore } from "./store.ts";
import { answersSender, asking, awaited, childrenSince, settledSince, clip, continuations, CUT_TWICE, duration, isTerminal, loopStop, nextGuard, outwardDetail, ownsConversation, ownThread, path, restartNote, wakeOwner } from "./tree.ts";
-import { DEFAULT_LIMITS, STOPPED_BY_USER, STOPPED_WITH_REQUEST, type Answerer, type Assignment, type Assignee, type Clock, type EndResult, type EnqueueRequest, type EnqueueResult, type EnvelopeNames,
+import { DEFAULT_LIMITS, STOPPED_BEFORE_RESUME, STOPPED_BEFORE_START, STOPPED_BY_USER, STOPPED_WITH_REQUEST, type Answerer, type Assignment, type Assignee, type Clock, type EndResult, type EnqueueRequest, type EnqueueResult, type EnvelopeNames,
type EventKind, type InboxItem, type InboxKind, type Level, type Limits, type LiveEdge, type Origin, type Outcome, type Owner,
type Reply, type Requester, type RunInput, type RunResult, type StatusView, type TurnRunner } from "./types.ts";
@@ -683,7 +683,7 @@ export class Runtime {
for (const child of this.store.children(n.id)) {
if (isTerminal(child)) continue;
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",
+ this.cancelTree(child, !unstarted ? STOPPED_WITH_REQUEST : child.restart === "rerun" ? STOPPED_BEFORE_RESUME : STOPPED_BEFORE_START,
"cancelled", "stopped");
}
this.settle(n, "cancelled", "stopped", reason);
diff --git a/server/runtime/types.ts b/server/runtime/types.ts
index 739d65c305..ecdac9cb7e 100644
--- a/server/runtime/types.ts
+++ b/server/runtime/types.ts
@@ -64,6 +64,13 @@ export const TERMINAL: readonly Status[] = ["completed", "failed", "cancelled"];
export const STOPPED_BY_USER = "Stopped by user";
/** The cause a stop leaves on the work its stopped assignment had handed on. */
export const STOPPED_WITH_REQUEST = "Stopped with the request it was for";
+/** The causes a stopped requester leaves on the work it had queued: it never started, or was due to start again. Whose stop
+ * it was is the requester's. */
+export const STOPPED_BEFORE_START = "Stopped before it started";
+export const STOPPED_BEFORE_RESUME = "Stopped before it resumed";
+/** A coordinated turn's own abort. Within a stop under way it is that stop; with none it is a cut the system made, never
+ * the person's Stop. */
+export const TURN_CUT = "The coordinated turn was cut";
/** Why it ended the way it did, typed so a requester can branch on it. */
export type Outcome =
diff --git a/server/waits.ts b/server/waits.ts
index b593760b65..c4cbf65b51 100644
--- a/server/waits.ts
+++ b/server/waits.ts
@@ -68,6 +68,8 @@ export interface WaitManagerOptions {
followUp(wait: WaitRecord & { followUp: string }): void;
showCard(wait: WaitRecord & { followUp: string }): string | undefined;
settleCard(wait: WaitRecord, how: "fired" | "expired" | "cancelled"): void;
+ /** The wait left the list: it was posted, cancelled, or its bot went. Whatever it held may go on. */
+ ended?(wait: WaitRecord): void;
}
const stampSchema = z.object({ size: z.number(), mtimeMs: z.number() });
@@ -272,6 +274,7 @@ export class WaitManager {
if (!wait) return null;
this.commit(() => { this.waits = this.waits.filter((w) => w !== wait); });
if (wait.cardMessageId) this.safely(() => this.options.settleCard(wait, "cancelled"));
+ this.ended(wait);
return cloneWait(wait);
}
@@ -286,10 +289,11 @@ export class WaitManager {
}
removeForBot(botId: string): number {
- const removed = this.waits.filter((w) => w.botId === botId).length;
- if (!removed) return 0;
+ const gone = this.waits.filter((w) => w.botId === botId);
+ if (!gone.length) return 0;
this.commit(() => { this.waits = this.waits.filter((w) => w.botId !== botId); });
- return removed;
+ for (const wait of gone) this.ended(wait);
+ return gone.length;
}
noteBotBusy(botId: string): void {
@@ -386,6 +390,7 @@ export class WaitManager {
this.commit(() => { this.waits = this.waits.filter((w) => w !== wait); });
if (status === "fired" && wait.followUp) this.safely(() => this.options.followUp(wait as WaitRecord & { followUp: string }));
if (wait.cardMessageId) this.safely(() => this.options.settleCard(wait, status === "fired" ? "fired" : "expired"));
+ this.ended(wait);
}
} finally {
this.ticking = false;
@@ -440,6 +445,11 @@ export class WaitManager {
try { run(); } catch (error) { console.error("wait: callback failed", error); }
}
+ private ended(wait: WaitRecord): void {
+ const ended = this.options.ended;
+ if (ended) this.safely(() => ended(cloneWait(wait)));
+ }
+
private commit(mutate: () => void): void {
const before = this.waits.map(cloneWait);
const identity = this.waits.slice();