Skip to content

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

fix(handoffs): close a hand-off thread only once nothing holds it

luishron12337f28ab4009b
diff --git a/server/host/finished-work-restart.test.ts b/server/host/finished-work-restart.test.ts
new file mode 100644
index 0000000000..5e1e0531ad
--- /dev/null
+++ b/server/host/finished-work-restart.test.ts
@@ -0,0 +1,47 @@
+import { rmSync } from "node:fs";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { DATA_DIR } from "../config.ts";
+import type { HandoffView } from "../coordinator.ts";
+import { closeMessageDb } from "../message-db.ts";
+import { flushLaterSaves } from "../save-batch.ts";
+import { Store } from "../store.ts";
+import { createHandedClose, STOP_GRACE_MS } from "./finished-work.ts";
+
+const selection = () => ({ instanceId: "claude", model: "claude-sonnet-5" });
+
+describe("a stopped hand-off thread across a restart", () => {
+ beforeEach(() => {
+ rmSync(DATA_DIR, { recursive: true, force: true });
+ vi.useFakeTimers();
+ vi.setSystemTime(1_000_000);
+ });
+ afterEach(() => {
+ flushLaterSaves();
+ closeMessageDb();
+ vi.useRealTimers();
+ });
+
+ it("closes on time from the deadline bots.json holds, in a server that starts from that file", () => {
+ const before = new Store(selection);
+ const chief = before.createBot({ name: "Clive" }, { seedMessages: false });
+ const lead = before.createBot({ name: "Lee" }, { seedMessages: false });
+ const thread = before.createTask(lead.id, "Work", false, undefined, { botId: chief.id, name: "Clive", threadId: chief.threadId, at: 0, oneShot: true })!;
+ const deps = { working: () => false, waitArmed: () => false };
+ const running = createHandedClose({ store: before, ...deps });
+ vi.advanceTimersByTime(0);
+ running.ended({ id: "h1", parentId: "p", botId: lead.id, threadId: thread.threadId, status: "cancelled", outcome: "stopped", outcomeDetail: "Stopped by user" } as HandoffView,
+ { id: "p", botId: chief.id, threadId: chief.threadId } as HandoffView, false);
+ running.dispose();
+ flushLaterSaves();
+
+ vi.advanceTimersByTime(40 * 60_000);
+ const after = new Store(selection);
+ expect(after.taskByThread(lead.id, thread.threadId)?.openedBy?.closesAt).toBe(1_000_000 + STOP_GRACE_MS);
+ createHandedClose({ store: after, ...deps });
+ vi.advanceTimersByTime(20 * 60_000 - 1);
+ expect(after.taskByThread(lead.id, thread.threadId)?.archivedAt).toBeUndefined();
+ vi.advanceTimersByTime(1);
+ expect(after.taskByThread(lead.id, thread.threadId)).toMatchObject({ archivedAt: 1_000_000 + STOP_GRACE_MS, closedBy: { botId: chief.id, at: 1_000_000 + STOP_GRACE_MS } });
+ });
+});
diff --git a/server/host/finished-work.test.ts b/server/host/finished-work.test.ts
index 4b58b4b68c..0ce071fc02 100644
--- a/server/host/finished-work.test.ts
+++ b/server/host/finished-work.test.ts
@@ -2,7 +2,7 @@ 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 } from "./finished-work.ts";
+import { archivedOnResult, archivesOnResult, closesOnResult, createHandedClose, finishHandedThread, 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"]> =>
@@ -86,25 +86,17 @@ describe("finishHandedThread", () => {
};
};
- it("closes and archives a one-shot thread at the same moment", () => {
- const store = fakeStore({ openedBy: oneShot() });
- finishHandedThread(store, "lead", "lead-thread", "chief", () => false, 42);
+ it("closes the standing work thread, and leaves it in the sidebar", () => {
+ const store = fakeStore({ openedBy: opened({ kind: "work" }), unread: true });
+ finishHandedThread(store, "lead", "lead-thread", "chief", 42);
expect(store.record.closedBy).toEqual({ botId: "chief", name: "Clive", at: 42 });
- expect(store.record.archivedAt).toBe(42);
+ expect(store.calls).toEqual(["closed"]);
});
- it("only closes the standing work thread and an unread thread", () => {
- for (const task of [{ openedBy: opened({ kind: "work" }) }, { openedBy: oneShot(), unread: true }]) {
+ it("leaves a one-shot thread to createHandedClose, and a thread that stays open alone", () => {
+ for (const task of [{ openedBy: oneShot() }, { openedBy: oneShot(), pinned: true }, { openedBy: oneShot({ kind: "pair" as const }) }, { openedBy: opened() }]) {
const store = fakeStore(task);
- finishHandedThread(store, "lead", "lead-thread", "chief", () => false, 42);
- expect(store.calls).toEqual(["closed"]);
- }
- });
-
- it("neither closes nor archives a thread that stays open", () => {
- for (const task of [{ openedBy: oneShot(), pinned: true }, { openedBy: oneShot({ kind: "pair" as const }) }, { openedBy: opened() }]) {
- const store = fakeStore(task);
- finishHandedThread(store, "lead", "lead-thread", "chief", () => false, 42);
+ finishHandedThread(store, "lead", "lead-thread", "chief", 42);
expect(store.calls).toEqual([]);
}
});
@@ -112,12 +104,15 @@ describe("finishHandedThread", () => {
describe("reopenHandedThread", () => {
const closedBy = { botId: "chief", name: "Clive", at: 5 };
- it("takes a one-shot thread out of the archive its result put it in", () => {
- const patches: unknown[] = [];
- const store = { patchTask: (_botId: string, _threadId: string, patch: unknown) => { patches.push(patch); return null; } };
+ it("takes a one-shot thread out of the archive its ended work put it in, and takes that close off", () => {
+ const calls: unknown[] = [];
+ const store = {
+ patchTask: (_botId: string, _threadId: string, patch: unknown) => { calls.push(patch); return null; },
+ setTaskClosedBy: (_botId: string, _threadId: string, closed: unknown) => { calls.push({ closedBy: closed }); return null; },
+ };
reopenHandedThread(store, "lead", { threadId: "t", openedBy: oneShot(), closedBy, archivedAt: 5 });
reopenHandedThread(store, "lead", { threadId: "t", openedBy: oneShot() });
- expect(patches).toEqual([{ archivedAt: undefined }]);
+ expect(calls).toEqual([{ archivedAt: undefined }, { closedBy: null }]);
});
it("leaves a thread the person archived in the archive", () => {
@@ -129,7 +124,6 @@ describe("reopenHandedThread", () => {
});
});
-
describe("stoppedByPerson", () => {
const ended = (more: Partial<HandoffView>) => ({ status: "cancelled" as const, outcome: "stopped" as const, ...more });
it("is the person's Stop in the thread, or in the conversation that handed the work on", () => {
@@ -159,53 +153,100 @@ describe("createHandedClose", () => {
beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(1_000_000); });
afterEach(() => { vi.useRealTimers(); });
- /** One saved thread of "lead" that "chief" handed work to; `records` is what survives a restart. */
+ /** One saved thread of "lead" that "chief" handed work to. Each change to it says so, as the store does. */
const world = (task: Partial<TaskRecord>, live = { working: false, waitArmed: false }) => {
const record = { threadId: "lead-thread", title: "Work", ...task } as TaskRecord;
const bots = [{ id: "lead", name: "Lee", tasks: [record] }] as unknown as BotRecord[];
const listeners = new Set<(change: StoreChange) => void>();
+ const emit = (change: StoreChange) => { for (const listener of listeners) listener(change); };
+ const changed = () => { emit({ type: "bot", botId: "lead", threadId: record.threadId }); return record; };
const store = {
bots,
bot: (botId: string) => (botId === "chief" ? { name: "Clive" } : undefined) as never,
botByThread: (threadId: string) => (threadId === record.threadId ? bots[0] : undefined) as never,
taskByThread: (_botId: string, threadId: string) => threadId === record.threadId ? record : undefined,
- setTaskClosedBy: (_botId: string, _threadId: string, closedBy: TaskRecord["closedBy"] | null) => { record.closedBy = closedBy ?? undefined; return record; },
- setTaskOpenedBy: (_botId: string, _threadId: string, openedBy: TaskRecord["openedBy"]) => { record.openedBy = openedBy; return record; },
- patchTask: (_botId: string, _threadId: string, patch: Partial<TaskRecord>) => { Object.assign(record, patch); return record; },
+ setTaskClosedBy: (_botId: string, _threadId: string, closedBy: TaskRecord["closedBy"] | null) => { record.closedBy = closedBy ?? undefined; return changed(); },
+ setTaskOpenedBy: (_botId: string, _threadId: string, openedBy: TaskRecord["openedBy"]) => { record.openedBy = openedBy; return changed(); },
+ 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 = () => createHandedClose({ store, working: () => live.working, waitArmed: () => live.waitArmed });
- const write = (message: Partial<Message>) => { for (const listener of listeners) listener({ type: "message", threadId: record.threadId, message: message as Message }); };
- return { record, live, start, write };
+ const start = () => { const close = createHandedClose({ store, working: () => live.working, waitArmed: () => live.waitArmed }); 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 };
};
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;
const personStop = work({ status: "cancelled", outcome: "stopped", outcomeDetail: "Stopped by user" });
+ const failed = work({ status: "failed", outcome: "provider_error" });
+ const closedAt = (at: number) => ({ closedBy: { botId: "chief", name: "Clive", at }, archivedAt: at });
it("closes and archives a one-shot thread when its work is done, failed, or stopped by the bot that handed it on", () => {
- for (const ended of [work({}), work({ status: "failed", outcome: "provider_error" }), work({ status: "failed", outcome: "stalled" }),
+ for (const ended of [work({}), failed, work({ status: "failed", outcome: "stalled" }),
work({ status: "cancelled", outcome: "stopped", outcomeDetail: "Stopped by @Clive, who handed this work on" })]) {
const { record, start } = world({ openedBy: oneShot() });
start().ended(ended, chief, false);
- expect(record.closedBy).toEqual({ botId: "chief", name: "Clive", at: 1_000_000 });
- expect(record.archivedAt).toBe(1_000_000);
+ expect(record).toMatchObject(closedAt(1_000_000));
+ expect(record.openedBy).toEqual(oneShot());
+ }
+ });
+
+ it("closes at once work the server stopped itself, without the person's hour", () => {
+ for (const cause of Object.values(SYSTEM_STOP)) {
+ const { record, start } = world({ openedBy: oneShot() });
+ start().ended(work({ status: "cancelled", outcome: "stopped", outcomeDetail: cause }), chief, false);
+ expect(record).toMatchObject(closedAt(1_000_000));
}
});
it("only closes the standing work thread when its work fails", () => {
const { record, start } = world({ openedBy: opened({ kind: "work" }) });
- start().ended(work({ status: "failed", outcome: "provider_error" }), chief, false);
+ start().ended(failed, chief, false);
expect(record.closedBy?.botId).toBe("chief");
expect(record.archivedAt).toBeUndefined();
});
- it("leaves a thread open while work there is still live, and a done result its requester could not take", () => {
- const busy = world({ openedBy: oneShot() }, { working: true, waitArmed: false });
- busy.start().ended(work({ status: "failed", outcome: "provider_error" }), chief, false);
- expect(busy.record.closedBy).toBeUndefined();
+ it("leaves a done result its requester could not take open", () => {
const withheld = world({ openedBy: oneShot() });
withheld.start().ended(work({}), chief, true);
expect(withheld.record.closedBy).toBeUndefined();
+ expect(withheld.record.openedBy?.closesAt).toBeUndefined();
+ });
+
+ it("keeps a thread whose work ended open while a bot still works there, and closes it when that turn ends", () => {
+ const cases: Array<[Partial<TaskRecord>, boolean]> = [[{}, true], [{ activity: "working" }, false], [{ busy: true }, false]];
+ for (const [task, working] of cases) {
+ const { record, live, start, update } = world({ openedBy: oneShot(), ...task }, { working, waitArmed: false });
+ const from = Date.now();
+ start().ended(failed, chief, false);
+ expect(record.closedBy).toBeUndefined();
+ expect(record.archivedAt).toBeUndefined();
+ vi.advanceTimersByTime(2 * STOP_GRACE_MS);
+ expect(record.archivedAt).toBeUndefined();
+ live.working = false;
+ update({ activity: "idle", busy: false });
+ expect(record).toMatchObject(closedAt(from + 2 * STOP_GRACE_MS));
+ }
+ });
+
+ it("neither closes nor archives a thread that waits on the person, and closes it once that is settled", () => {
+ 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 });
+ const from = Date.now();
+ w.start().ended(work({}), chief, false);
+ expect(w.record.closedBy).toBeUndefined();
+ expect(w.record.archivedAt).toBeUndefined();
+ expect(w.record.openedBy?.closesAt).toBe(from);
+ vi.advanceTimersByTime(5_000);
+ settle(w);
+ expect(w.record).toMatchObject(closedAt(from + 5_000));
+ }
});
it("closes a one-shot thread a bot posted into and the person wrote in during the work", () => {
@@ -226,11 +267,20 @@ describe("createHandedClose", () => {
vi.advanceTimersByTime(STOP_GRACE_MS - 1);
expect(record.closedBy).toBeUndefined();
vi.advanceTimersByTime(1);
- expect(record.closedBy).toEqual({ botId: "chief", name: "Clive", at: 1_000_000 + STOP_GRACE_MS });
- expect(record.archivedAt).toBe(1_000_000 + STOP_GRACE_MS);
+ expect(record).toMatchObject(closedAt(1_000_000 + STOP_GRACE_MS));
expect(record.openedBy).toEqual(oneShot());
});
+ it("keeps the standing work thread the person stopped open for an hour too, then only closes it", () => {
+ const { record, start } = world({ openedBy: opened({ kind: "work" }) });
+ start().ended(personStop, chief, false);
+ expect(record.closedBy).toBeUndefined();
+ vi.advanceTimersByTime(STOP_GRACE_MS);
+ expect(record.closedBy).toEqual({ botId: "chief", name: "Clive", at: 1_000_000 + STOP_GRACE_MS });
+ expect(record.archivedAt).toBeUndefined();
+ expect(record.openedBy).toEqual(opened({ kind: "work" }));
+ });
+
it("waits the hour too when the person stopped the conversation that handed the work on", () => {
const { record, start } = world({ openedBy: oneShot() });
start().ended(work({ status: "cancelled", outcome: "stopped", outcomeDetail: "Stopped with the request it was for" }), { ...chief, outcomeDetail: "Stopped by user" }, false);
@@ -252,55 +302,46 @@ describe("createHandedClose", () => {
}
});
- it("closes a stopped thread on time after a restart, from the deadline it saved", () => {
- const { record, start } = world({ openedBy: oneShot() });
- const before = start();
- before.ended(personStop, chief, false);
- before.dispose();
- vi.advanceTimersByTime(40 * 60_000);
- start();
- vi.advanceTimersByTime(20 * 60_000 - 1);
- expect(record.closedBy).toBeUndefined();
- vi.advanceTimersByTime(1);
- expect(record.archivedAt).toBe(1_000_000 + STOP_GRACE_MS);
- });
-
it("closes at once on restart a stopped thread whose hour passed while the server was down", () => {
const { record, start } = world({ openedBy: oneShot({ closesAt: 1_000_000 - 1 }) });
start();
- vi.advanceTimersByTime(0);
expect(record.archivedAt).toBe(1_000_000);
});
- it("at the hour, leaves open a stopped thread a bot works in, and in the sidebar one that waits on the person", () => {
- const busy = world({ openedBy: oneShot() });
- busy.start().ended(personStop, chief, false);
- busy.live.working = true;
+ it("at the hour, keeps a stopped thread a bot works in due, and closes it when the turn ends", () => {
+ const { record, live, start, update } = world({ openedBy: oneShot() });
+ start().ended(personStop, chief, false);
+ live.working = true;
vi.advanceTimersByTime(STOP_GRACE_MS);
- expect(busy.record.closedBy).toBeUndefined();
- expect(busy.record.openedBy?.closesAt).toBeUndefined();
- for (const [task, live] of [[{ unread: true }, { working: false, waitArmed: false }], [{ activity: "waiting-on-you" as const }, { working: false, waitArmed: false }],
- [{}, { working: false, waitArmed: true }]] as const) {
- const waiting = world({ openedBy: oneShot(), ...task }, { ...live });
- waiting.start().ended(personStop, chief, false);
- vi.advanceTimersByTime(STOP_GRACE_MS);
- expect(waiting.record.closedBy?.botId).toBe("chief");
- expect(waiting.record.archivedAt).toBeUndefined();
- }
+ expect(record.closedBy).toBeUndefined();
+ expect(record.openedBy?.closesAt).toBe(1_000_000 + STOP_GRACE_MS);
+ vi.advanceTimersByTime(60_000);
+ live.working = false;
+ update({});
+ expect(record).toMatchObject(closedAt(1_000_000 + STOP_GRACE_MS + 60_000));
});
- it("takes a closed one-shot thread out of the archive on a new message, not on the lines a run leaves", () => {
+ it("takes a closed one-shot thread out of the archive, and takes the close off, on a new message; not on the lines a run leaves", () => {
const { record, start, write } = world({ openedBy: oneShot() });
start().ended(work({}), chief, false);
write({ role: "bot", kind: "activity" });
- expect(record.archivedAt).toBe(1_000_000);
+ expect(record).toMatchObject(closedAt(1_000_000));
write({ role: "bot", threadPost: { deliveryId: "d", fromBotId: "chief", fromThreadId: "chief-chat" } });
expect(record.archivedAt).toBeUndefined();
+ expect(record.closedBy).toBeUndefined();
+ });
+
+ it("drops the due close of a thread the person pinned meanwhile", () => {
+ const { record, start, update } = world({ openedBy: oneShot(), unread: true });
+ start().ended(work({}), chief, false);
+ update({ pinned: true, unread: false });
+ expect(record.closedBy).toBeUndefined();
+ expect(record.openedBy?.closesAt).toBeUndefined();
});
it("never closes a thread the person started, or one start_thread opened, however its work ends", () => {
for (const task of [{}, { openedBy: opened() }]) {
- for (const ended of [work({}), work({ status: "failed", outcome: "provider_error" }), personStop]) {
+ for (const ended of [work({}), failed, personStop]) {
const { record, start } = world(task);
start().ended(ended, chief, false);
vi.advanceTimersByTime(STOP_GRACE_MS);
diff --git a/server/host/finished-work.ts b/server/host/finished-work.ts
index 3e063c60d4..070a8cde8a 100644
--- a/server/host/finished-work.ts
+++ b/server/host/finished-work.ts
@@ -1,8 +1,8 @@
// Work one bot hands a teammate is finished once its result is reported back, whether it was done, failed or was stopped.
// The standing work thread closes, which folds it out of the sidebar. A thread coordinate_bots opened with thread "new" for
-// that one hand-off (`openedBy.oneShot`) also closes, and leaves the sidebar for the archive. The person's Stop closes it
-// only an hour later, so a stop by mistake can be taken back by writing there. A new message reopens it. Every other
-// thread stays as it is.
+// that one hand-off (`openedBy.oneShot`) is due to close, and closes into the archive once no bot works there and nothing
+// 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 type { Message, Store, TaskRecord } from "../store.ts";
@@ -24,16 +24,16 @@ export function closesOnResult(task: FinishedTask | undefined, openerBotId: stri
&& task.pinned !== true && task.projectId === undefined;
}
-/** Whether a thread that just closed on its result is also archived: a one-shot thread is, unless something there waits on
- * the person (it is unread, its bot asks them something, or a wait it set is still armed and its message lands there
- * later). The standing work thread is not, so the opener's next work goes on in it. */
+/** Whether a one-shot thread may close into the archive now: nothing there waits on the person (it is unread, its bot asks
+ * them something, or a wait it set is still armed and its message lands there later). The standing work thread never is
+ * archived, so the opener's next work goes on in it. */
export function archivesOnResult(task: Pick<TaskRecord, "openedBy" | "unread" | "activity">, waitArmed: boolean): boolean {
return task.openedBy?.oneShot === true && task.openedBy.kind === undefined && task.unread !== true
&& task.activity !== "waiting-on-you" && !waitArmed;
}
-/** Whether a one-shot thread is in the archive because its result came back (`finishHandedThread` stamps the close and the
- * archive at the same moment), not because the person archived it. Only such a thread may be taken out of the archive. */
+/** Whether a one-shot thread is in the archive because its work ended (the close and the archive are stamped at the same
+ * moment), not because the person archived it. Only such a thread may be taken out of the archive. */
export function archivedOnResult(task: Pick<TaskRecord, "openedBy" | "closedBy" | "archivedAt">): boolean {
return task.openedBy?.oneShot === true && task.archivedAt !== undefined
&& task.closedBy?.botId === task.openedBy.botId && task.closedBy.at === task.archivedAt;
@@ -41,28 +41,40 @@ export function archivedOnResult(task: Pick<TaskRecord, "openedBy" | "closedBy"
type FinishStore = Pick<Store, "taskByThread" | "bot" | "setTaskClosedBy" | "patchTask">;
-/** Closes, and archives where it should, the thread of `ownerBotId` that `openerBotId` handed work to, now that its result is reported. */
-export function finishHandedThread(store: FinishStore, ownerBotId: string, threadId: string, openerBotId: string,
- waitArmed: (threadId: string) => boolean, now = Date.now()): void {
+/** Closes the standing work thread `openerBotId` handed work to, now that its result is reported. A one-shot thread closes
+ * through `createHandedClose`, which waits until nothing holds it. */
+export function finishHandedThread(store: FinishStore, ownerBotId: string, threadId: string, openerBotId: string, now = Date.now()): void {
const task = store.taskByThread(ownerBotId, threadId);
- if (!task || !closesOnResult(task, openerBotId, ownerBotId)) return;
- store.setTaskClosedBy(ownerBotId, threadId, { botId: openerBotId, name: store.bot(openerBotId)?.name ?? task.openedBy!.name, at: now });
- if (archivesOnResult(task, waitArmed(threadId))) store.patchTask(ownerBotId, threadId, { archivedAt: now });
+ if (!task || task.openedBy?.kind !== "work" || !closesOnResult(task, openerBotId, ownerBotId)) return;
+ store.setTaskClosedBy(ownerBotId, threadId, { botId: openerBotId, name: store.bot(openerBotId)?.name ?? task.openedBy.name, at: now });
}
-/** A one-shot thread its opener sends to again leaves the archive its result put it in, so the person sees the work it
- * runs. A thread the person archived stays there. */
-export function reopenHandedThread(store: Pick<Store, "patchTask">, ownerBotId: string, task: Pick<TaskRecord, "threadId" | "openedBy" | "closedBy" | "archivedAt">): void {
- if (archivedOnResult(task)) store.patchTask(ownerBotId, task.threadId, { archivedAt: undefined });
+/** A one-shot thread a new message reaches leaves the archive its ended work put it in, and loses that close, so the person
+ * sees the work it runs and it can close again when that ends. A thread the person archived stays there. */
+export function reopenHandedThread(store: Pick<Store, "patchTask" | "setTaskClosedBy">, ownerBotId: string, task: Pick<TaskRecord, "threadId" | "openedBy" | "closedBy" | "archivedAt">): void {
+ if (!archivedOnResult(task)) return;
+ store.patchTask(ownerBotId, task.threadId, { archivedAt: undefined });
+ 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) or its requester made carries another cause. */
+ * 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 {
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);
}
+/** The causes the server gives the stops it makes itself, so none reads as the person's Stop. */
+export const SYSTEM_STOP = {
+ /** The bot was deleted, or its approval level was lowered in an emergency. */
+ bot: "The bot's work was stopped by the server",
+ /** The turn could not be started. */
+ dispatch: "The turn could not start",
+ /** The goal or routine run this turn served ended. */
+ goal: "The goal this turn served ended",
+} 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.
* The lines a run leaves on its way out are not. */
export function opensAgain(message: Pick<Message, "role" | "threadPost" | "roomRequest">): boolean {
@@ -78,64 +90,90 @@ export interface HandedCloseDeps {
now?: () => number;
}
-/** Closes hand-off threads as their work ends, and the ones the person stopped once `STOP_GRACE_MS` passes with nothing
- * new written there. The deadline is kept on the thread (`openedBy.closesAt`), so a restart picks it up. */
+/** 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 } {
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;
- const deadlines = () => store.bots.flatMap((bot) => (bot.tasks ?? []).filter((task) => task.openedBy?.closesAt !== undefined).map((task) => ({ botId: bot.id, task })));
+ 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 next = Math.min(...deadlines().map(({ task }) => task.openedBy!.closesAt!));
+ const at = now();
+ const next = Math.min(...due().map(({ task }) => task.openedBy!.closesAt!).filter((closesAt) => closesAt > at));
if (!Number.isFinite(next)) return;
- timer = setTimeout(due, Math.max(0, next - now()));
+ timer = setTimeout(() => { timer = undefined; look(); arm(); }, next - at);
timer.unref?.();
};
- const clear = (botId: string, task: TaskRecord) => {
+ const unmark = (botId: string, task: TaskRecord) => {
const { closesAt: _closesAt, ...openedBy } = task.openedBy!;
store.setTaskOpenedBy(botId, task.threadId, openedBy);
};
- const finish = (botId: string, threadId: string, openerBotId: string) =>
- finishHandedThread(store, botId, threadId, openerBotId, (id) => deps.waitArmed(botId, id), now());
- const due = () => {
- timer = undefined;
- const at = now();
- for (const { botId, task } of deadlines()) {
- if (task.openedBy!.closesAt! > at) continue;
- clear(botId, task);
- if (!deps.working(task.threadId) && task.activity !== "working") finish(botId, task.threadId, task.openedBy!.botId);
- }
- arm();
+ const holds = (botId: string, task: TaskRecord) => deps.working(task.threadId) || task.busy === true || task.activity === "working"
+ || !archivesOnResult(task, deps.waitArmed(botId, task.threadId));
+ /** Closes each due thread nothing holds; one that no longer closes (the person pinned it, say) loses the mark. */
+ const look = (botId?: 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;
+ unmark(owner, task);
+ finishHandedThread(store, owner, task.threadId, opener, at);
+ continue;
+ }
+ 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 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) { clear(botId, task); arm(); }
+ if (task.openedBy?.closesAt !== undefined) { unmark(botId, task); arm(); }
reopenHandedThread(store, botId, task);
});
- arm();
+ const boot = setTimeout(() => { started = true; look(); arm(); }, 0);
+ boot.unref?.();
return {
ended(child, parent, problem) {
if (child.groupId || (child.status !== "completed" && child.status !== "failed" && child.status !== "cancelled")) return;
if (child.status === "completed" && problem) return;
- if (!stoppedByPerson(child, parent)) {
- if (!deps.working(child.threadId)) finish(child.botId, child.threadId, parent.botId);
- return;
- }
const task = store.taskByThread(child.botId, child.threadId);
if (!task?.openedBy || !closesOnResult(task, parent.botId, child.botId)) return;
- store.setTaskOpenedBy(child.botId, child.threadId, { ...task.openedBy, closesAt: now() + STOP_GRACE_MS });
+ const stopped = stoppedByPerson(child, parent);
+ 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);
arm();
},
dispose() {
unsubscribe();
+ clearTimeout(boot);
if (timer) clearTimeout(timer);
timer = undefined;
},
diff --git a/server/index.ts b/server/index.ts
index f269f78db2..7ccdf336ff 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -26,7 +26,7 @@ import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";
import { SharedComputerControl } from "./shared-computer-control.ts";
import { STATUS_REPLY_TIMEOUT_MS } from "./runtime/status-reply.ts"; import { createCoordinator, sameTurnReturns, type ComposedTurn, type CoordinateBotsCall, type Coordinator, type HandoffOpener, type HandoffOptions, type HandoffView, type HostTurnResult } from "./coordinator.ts";
import { queuedBehindPersonText, turnWaitedOnPerson, UnansweredApprovals } from "./waiting-on-person.ts";
-import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, createAskCards, settleRequestCard } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { besideBusy, workThreadFor } from "./host/work-thread.ts"; import { createHandedClose, reopenHandedThread } from "./host/finished-work.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts"; import { createConnectCardSettle } from "./host/connect-card-settle.ts";
+import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, createAskCards, settleRequestCard } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { besideBusy, workThreadFor } from "./host/work-thread.ts"; import { createHandedClose, reopenHandedThread, SYSTEM_STOP } from "./host/finished-work.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts"; import { createConnectCardSettle } from "./host/connect-card-settle.ts";
import { assertRequestTarget, guardedRequestPath, requestConflict, requestNeedsInput } from "./guarded-requests.ts";
import { botAvatarUrlFromStoredPath } from "../shared/bot-avatar.ts";
import { BOT_PROFILE_LIMITS } from "../shared/bot-profile.ts";
@@ -2260,7 +2260,7 @@ async function interruptAllDirectThreads(botId: string): Promise<void> {
cancelDirectTurnDispatch(botId, task.threadId);
revokeInternalCapabilitiesForThread(task.threadId);
}
- await Promise.all(threads.map((task) => interruptDirectThread(botId, task.threadId)));
+ await Promise.all(threads.map((task) => interruptDirectThread(botId, task.threadId, SYSTEM_STOP.bot)));
}
const retiredProviderTurns = new RetiredTurnRegistry();
const pendingCancelledProviderHandshakes = new PendingTurnCancellations();
@@ -7936,7 +7936,7 @@ async function beginTurn(
resourceOwner.lazyClaimFailureReported = true;
}
opts?.onDispatchError?.(message);
- void interruptDirectThread(bot.id, threadId).catch(() => {});
+ void interruptDirectThread(bot.id, threadId, SYSTEM_STOP.dispatch).catch(() => {});
};
/** A poller started after its own turn.completed would never stop: same still-running guard as dispatch. */
@@ -8586,7 +8586,7 @@ async function interruptRoutineGroupGoal(
if (!groupId) {
oneOnOneGoals.stop(threadId, outcome);
const owner = store.botByThread(threadId);
- if (owner && directRequestOwners.get(threadId)?.origin?.kind !== "user") await interruptDirectThread(owner.id, threadId);
+ if (owner && directRequestOwners.get(threadId)?.origin?.kind !== "user") await interruptDirectThread(owner.id, threadId, SYSTEM_STOP.goal);
return;
}
const speaker = groupSpeakers.get(threadId);
@@ -11737,7 +11737,7 @@ async function stopCompanyInstances(ids: string[]) {
.map(task => ({ botId: bot.id, threadId: task.threadId, owner: turnResourceOwners.get(task.threadId), generation: directTurnGenerationByThread.get(task.threadId) })));
// Mark stopping first: a turn's own end can settle its requester before the loop below.
for (const { threadId } of direct) turnStops.stopping(threadId, liveTurnByThread.get(threadId), cause);
- await Promise.all(direct.map(task => interruptDirectThread(task.botId, task.threadId)));
+ await Promise.all(direct.map(task => interruptDirectThread(task.botId, task.threadId, cause)));
for (const { botId, threadId, owner, generation } of direct) {
const interrupted = stoppedTurnText(threadId, liveTurnByThread.get(threadId), cause);
releaseTurnResources(owner);