Skip to content

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

fix(handoffs): close a hand-off thread when its work fails or is stopped

luishron12372a70d1e198d
diff --git a/packages/phone-protocol/src/task-provenance.ts b/packages/phone-protocol/src/task-provenance.ts
index ae9f12842f..59af787c93 100644
--- a/packages/phone-protocol/src/task-provenance.ts
+++ b/packages/phone-protocol/src/task-provenance.ts
@@ -8,8 +8,11 @@ export interface TaskOpenedBy {
* result has been reported. */
kind?: "pair" | "work";
/** coordinate_bots opened it with thread "new" for one hand-off: it closes, and leaves the sidebar, once its result is
- * back (server/host/finished-work.ts). start_thread never sets it, and a post_to_thread into the thread takes it off. */
+ * back (server/host/finished-work.ts). start_thread never sets it. */
oneShot?: true;
+ /** Epoch ms this thread closes at, set when the person stopped the work handed to it: a new message there before then
+ * takes it off and keeps the thread open. Older servers ignore it. */
+ closesAt?: number;
/** The burst this thread is one part of: it is listed under that burst's card. */
burstId?: string;
/** The opener's own conversation this "work" thread was opened from.
diff --git a/server/host/finished-work.test.ts b/server/host/finished-work.test.ts
index 9afa2745b7..4b58b4b68c 100644
--- a/server/host/finished-work.test.ts
+++ b/server/host/finished-work.test.ts
@@ -1,7 +1,8 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import type { TaskRecord } from "../store.ts";
-import { archivedOnResult, archivesOnResult, closesOnResult, finishHandedThread, keepHandedThread, reopenHandedThread } from "./finished-work.ts";
+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";
type Task = Parameters<typeof closesOnResult>[0];
const opened = (more: Partial<NonNullable<TaskRecord["openedBy"]>> = {}): NonNullable<TaskRecord["openedBy"]> =>
@@ -23,14 +24,17 @@ describe("closesOnResult", () => {
expect(closes({ openedBy: opened() })).toBe(false);
});
- it("keeps a thread \"new\" opened that was pinned, filed in a folder or written in by a person", () => {
+ it("keeps a thread \"new\" opened that was pinned or filed in a folder", () => {
expect(closes({ openedBy: oneShot(), pinned: true })).toBe(false);
expect(closes({ openedBy: oneShot(), projectId: "folder-1" })).toBe(false);
- expect(closes({ openedBy: oneShot(), askedAt: 1 })).toBe(false);
+ });
+
+ it("closes a thread \"new\" opened that the person wrote in during the work", () => {
+ expect(closes({ openedBy: oneShot(), askedAt: 1 } as Task)).toBe(true);
});
it("closes the standing work thread whether or not it was kept", () => {
- expect(closes({ openedBy: opened({ kind: "work" }), pinned: true, projectId: "folder-1", askedAt: 1 })).toBe(true);
+ expect(closes({ openedBy: opened({ kind: "work" }), pinned: true, projectId: "folder-1" })).toBe(true);
});
it("keeps the pair conversation, a burst's part, a room lane and a thread a bot opened on itself", () => {
@@ -63,6 +67,10 @@ describe("archivesOnResult", () => {
it("leaves a thread whose wait is still armed in the sidebar", () => {
expect(archivesOnResult({ openedBy: oneShot() }, true)).toBe(false);
});
+
+ it("leaves a thread whose bot asks the person something in the sidebar", () => {
+ expect(archivesOnResult({ openedBy: oneShot(), activity: "waiting-on-you" }, false)).toBe(false);
+ });
});
describe("finishHandedThread", () => {
@@ -94,7 +102,7 @@ describe("finishHandedThread", () => {
});
it("neither closes nor archives a thread that stays open", () => {
- for (const task of [{ openedBy: oneShot(), pinned: true }, { openedBy: oneShot(), askedAt: 1 }, { openedBy: oneShot({ kind: "pair" as const }) }, { openedBy: opened() }]) {
+ 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);
expect(store.calls).toEqual([]);
@@ -121,17 +129,191 @@ describe("reopenHandedThread", () => {
});
});
-describe("keepHandedThread", () => {
- it("takes the one-shot mark off a thread a post_to_thread reached, and leaves other threads alone", () => {
- const tasks: Record<string, Partial<TaskRecord>> = { shot: { openedBy: oneShot() }, plain: { openedBy: opened() } };
- const written: unknown[] = [];
+
+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", () => {
+ expect(stoppedByPerson(ended({ outcomeDetail: "Stopped by user" }))).toBe(true);
+ expect(stoppedByPerson(ended({ outcomeDetail: "Stopped with the request it was for" }), { outcomeDetail: "Stopped by user" })).toBe(true);
+ });
+
+ it("is not a stop its requester or the system made, nor a failure", () => {
+ expect(stoppedByPerson(ended({ outcomeDetail: "Stopped by @Clive, who handed this work on" }))).toBe(false);
+ expect(stoppedByPerson(ended({ outcomeDetail: "The source conversation was deleted" }))).toBe(false);
+ 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);
+ });
+});
+
+describe("opensAgain", () => {
+ it("is the person writing, a bot's post, or new work handed there; not the lines a run leaves", () => {
+ expect(opensAgain({ role: "user" })).toBe(true);
+ expect(opensAgain({ role: "bot", threadPost: { deliveryId: "d", fromBotId: "chief", fromThreadId: "chief-chat" } })).toBe(true);
+ expect(opensAgain({ role: "bot", roomRequest: { id: "h", phase: "request" } })).toBe(true);
+ expect(opensAgain({ role: "bot", roomRequest: { id: "h", phase: "result" } })).toBe(false);
+ expect(opensAgain({ role: "bot" })).toBe(false);
+ });
+});
+
+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. */
+ 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 store = {
- taskByThread: (_botId: string, threadId: string) => tasks[threadId] as TaskRecord | undefined,
- setTaskOpenedBy: (_botId: string, threadId: string, openedBy: TaskRecord["openedBy"]) => { written.push([threadId, openedBy]); return null; },
+ 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; },
+ onChange: (listener: (change: StoreChange) => void) => { listeners.add(listener); return () => listeners.delete(listener); },
};
- keepHandedThread(store, "lead", "shot");
- keepHandedThread(store, "lead", "plain");
- keepHandedThread(store, "lead", "gone");
- expect(written).toEqual([["shot", opened()]]);
+ 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 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" });
+
+ 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" }),
+ 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);
+ }
+ });
+
+ 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);
+ 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();
+ const withheld = world({ openedBy: oneShot() });
+ withheld.start().ended(work({}), chief, true);
+ expect(withheld.record.closedBy).toBeUndefined();
+ });
+
+ 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();
+ write({ role: "bot", threadPost: { deliveryId: "d", fromBotId: "chief", fromThreadId: "chief-chat" } });
+ write({ role: "user" });
+ close.ended(work({}), chief, false);
+ expect(record.openedBy?.oneShot).toBe(true);
+ expect(record.archivedAt).toBe(1_000_000);
+ });
+
+ it("keeps a thread the person stopped open for an hour, then closes and archives it", () => {
+ const { record, start } = world({ openedBy: oneShot() });
+ start().ended(personStop, chief, false);
+ expect(record.closedBy).toBeUndefined();
+ expect(record.openedBy?.closesAt).toBe(1_000_000 + STOP_GRACE_MS);
+ 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.openedBy).toEqual(oneShot());
+ });
+
+ 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);
+ expect(record.closedBy).toBeUndefined();
+ vi.advanceTimersByTime(STOP_GRACE_MS);
+ expect(record.archivedAt).toBe(1_000_000 + STOP_GRACE_MS);
+ });
+
+ 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() });
+ start().ended(personStop, chief, false);
+ vi.advanceTimersByTime(30 * 60_000);
+ write(message);
+ expect(record.openedBy?.closesAt).toBeUndefined();
+ vi.advanceTimersByTime(2 * STOP_GRACE_MS);
+ expect(record.closedBy).toBeUndefined();
+ expect(record.archivedAt).toBeUndefined();
+ }
+ });
+
+ 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;
+ 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();
+ }
+ });
+
+ it("takes a closed one-shot thread out of the archive 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);
+ write({ role: "bot", threadPost: { deliveryId: "d", fromBotId: "chief", fromThreadId: "chief-chat" } });
+ expect(record.archivedAt).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]) {
+ const { record, start } = world(task);
+ start().ended(ended, chief, false);
+ vi.advanceTimersByTime(STOP_GRACE_MS);
+ expect(record.closedBy).toBeUndefined();
+ expect(record.archivedAt).toBeUndefined();
+ expect(record.openedBy?.closesAt).toBeUndefined();
+ }
+ }
+ });
+
+ it("leaves a room's work alone", () => {
+ const { record, start } = world({ openedBy: oneShot() });
+ start().ended(work({ status: "failed", outcome: "provider_error", groupId: "room-1" }), chief, false);
+ expect(record.closedBy).toBeUndefined();
});
});
diff --git a/server/host/finished-work.ts b/server/host/finished-work.ts
index 5feffd3ea6..3e063c60d4 100644
--- a/server/host/finished-work.ts
+++ b/server/host/finished-work.ts
@@ -1,27 +1,35 @@
-// Work one bot hands a teammate is finished once its result is reported back. 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 next turn in either opens it again. Every other thread stays as it is.
-import type { Store, TaskRecord } from "../store.ts";
+// 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.
+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";
-type FinishedTask = Pick<TaskRecord, "openedBy" | "closedBy" | "pinned" | "projectId" | "askedAt">;
+/** How long a thread whose work the person stopped stays open before it closes. */
+export const STOP_GRACE_MS = 60 * 60_000;
+
+type FinishedTask = Pick<TaskRecord, "openedBy" | "closedBy" | "pinned" | "projectId">;
/** Whether `task`, a thread of `ownerBotId` that `openerBotId` handed work to, closes now that the result is reported.
- * The standing work thread always does. A one-shot thread does too, unless it was kept: pinned, filed in a folder, or
- * written in by a person. A thread start_thread opened, one a post_to_thread reached, the pair conversation, a burst's
- * part, a room lane and a thread a bot opened on itself never do. */
+ * The standing work thread always does. A one-shot thread does too, unless the person kept it: pinned or filed in a
+ * folder. A thread start_thread opened, the pair conversation, a burst's part, a room lane and a thread a bot opened on
+ * itself never do. */
export function closesOnResult(task: FinishedTask | undefined, openerBotId: string, ownerBotId: string): boolean {
const openedBy = task?.openedBy;
if (!task || !openedBy || task.closedBy || openedBy.botId !== openerBotId) return false;
if (openedBy.kind === "work") return true;
return openedBy.oneShot === true && openedBy.kind === undefined && ownerBotId !== openerBotId && !openedBy.burstId && !openedBy.roomLane
- && task.pinned !== true && task.projectId === undefined && task.askedAt === undefined;
+ && task.pinned !== true && task.projectId === undefined;
}
-/** Whether a thread that just closed on its result is also archived: a one-shot thread is, unless it is unread or a wait
- * it set is still armed, since that wait's message lands there later. The standing work thread is not, so the opener's
- * next work goes on in it. */
-export function archivesOnResult(task: Pick<TaskRecord, "openedBy" | "unread">, waitArmed: boolean): boolean {
- return task.openedBy?.oneShot === true && task.openedBy.kind === undefined && task.unread !== true && !waitArmed;
+/** 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. */
+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
@@ -48,10 +56,88 @@ export function reopenHandedThread(store: Pick<Store, "patchTask">, ownerBotId:
if (archivedOnResult(task)) store.patchTask(ownerBotId, task.threadId, { archivedAt: undefined });
}
-/** A post_to_thread reached this thread: bots go on writing in it, so it is no longer one hand-off's and stays open after a result. */
-export function keepHandedThread(store: Pick<Store, "taskByThread" | "setTaskOpenedBy">, ownerBotId: string, threadId: string): void {
- const openedBy = store.taskByThread(ownerBotId, threadId)?.openedBy;
- if (!openedBy?.oneShot) return;
- const { oneShot: _oneShot, ...kept } = openedBy;
- store.setTaskOpenedBy(ownerBotId, threadId, kept);
+/** 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. */
+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);
+}
+
+/** 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 {
+ return message.role === "user" || message.threadPost !== undefined || message.roomRequest?.phase === "request";
+}
+
+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. */
+ waitArmed(botId: string, threadId: string): boolean;
+ 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. */
+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;
+
+ const deadlines = () => store.bots.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!));
+ if (!Number.isFinite(next)) return;
+ timer = setTimeout(due, Math.max(0, next - now()));
+ timer.unref?.();
+ };
+ const clear = (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 unsubscribe = store.onChange((change) => {
+ 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(); }
+ reopenHandedThread(store, botId, task);
+ });
+ arm();
+
+ 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 });
+ arm();
+ },
+ dispose() {
+ unsubscribe();
+ if (timer) clearTimeout(timer);
+ timer = undefined;
+ },
+ };
}
diff --git a/server/host/thread-posts.test.ts b/server/host/thread-posts.test.ts
index bafd38a99c..911b0ce5ce 100644
--- a/server/host/thread-posts.test.ts
+++ b/server/host/thread-posts.test.ts
@@ -99,16 +99,6 @@ describe("thread posts", () => {
expect(calls).toHaveLength(3);
});
- it("keeps the thread a delivered post reached, and not one a refused post named", async () => {
- const { deps: d } = deps("sender-kept");
- const kept: string[] = [];
- d.kept = (botId, threadId) => { kept.push(`${botId}/${threadId}`); };
- expect((await postToThread({ toThreadId: "t-1", message: "hi", deliveryId: "kept-1" }, d)).status).toBe(200);
- d.coordinateBots = async () => ({ status: 403, body: { error: "not reachable" } });
- expect((await postToThread({ toThreadId: "t-2", message: "hi", deliveryId: "kept-2" }, d)).status).toBe(403);
- expect(kept).toEqual(["bot-b/t-1"]);
- });
-
it("refuses a call made from a room", async () => {
const { calls, deps: d } = deps("sender-room", ["from-run"]);
expect((await postToThread({ toThreadId: "t-1", message: "hi" }, d)).status).toBe(409);
diff --git a/server/host/thread-posts.ts b/server/host/thread-posts.ts
index bbd78c2ee9..a07c260cc5 100644
--- a/server/host/thread-posts.ts
+++ b/server/host/thread-posts.ts
@@ -80,9 +80,7 @@ const pending = new Map<string, string>();
/** POST /api/internal/post-to-thread: checks the call and sends it through coordinate_bots as a post, so its reach rules hold. */
export async function postToThread(body: unknown, deps: { senderId: string; fromThreadId: string; waitsOn: (threadId: string) => boolean;
- store: Pick<Store, "botByThread" | "groupByThread" | "messagesFor">; coordinateBots: (call: CoordinateBotsCall) => Promise<Reply>;
- /** A delivered post makes the thread one bots go on writing in, so it no longer closes on a hand-off's result. */
- kept?: (botId: string, threadId: string) => void }): Promise<Reply> {
+ store: Pick<Store, "botByThread" | "groupByThread" | "messagesFor">; coordinateBots: (call: CoordinateBotsCall) => Promise<Reply> }): Promise<Reply> {
const refuse = (status: number, error: string): Reply => ({ status, body: { error } });
const parsed = PostBody.safeParse(body);
if (!parsed.success) return refuse(400, `Give thread_id (from list_threads) and a message of 1-${THREAD_POST_MAX_CHARS} characters; wake is true or false.`);
@@ -112,7 +110,6 @@ export async function postToThread(body: unknown, deps: { senderId: string; from
return refuse(result.status === 200 ? 409 : result.status, String(receipt?.detail ?? result.body.error ?? "Not delivered."));
}
deliveries.set(key, threadId);
- deps.kept?.(owner.id, threadId);
if (deliveries.size > 1_000) deliveries.delete(deliveries.keys().next().value!);
return { status: 200, body: { deliveryId, threadId, botName: owner.name, woke: wake,
message: wake ? `Delivered; that thread runs it ${receipt.outcome === "injected" ? "in its running turn" : "next"}. Nothing comes back to you.` : "Posted; nothing started there. That thread reads it on its next run." } };
diff --git a/server/index.ts b/server/index.ts
index a293d62865..f269f78db2 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 { finishHandedThread, keepHandedThread, 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 } 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";
@@ -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 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), waitArmed: (botId, threadId) => botWaits.list(botId).some((wait) => 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),
@@ -3926,7 +3926,7 @@ const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store
const source = store.bot(parent.botId);
if (source) markTaskContextExternallyUpdated(source, parent.threadId);
}
- if (!child.groupId && child.status === "completed" && !problem && !coordinator.activeDirect(child.threadId)) finishHandedThread(store, child.botId, child.threadId, parent.botId, (threadId) => botWaits.list(child.botId).some((wait) => wait.threadId === threadId));
+ handedClose.ended(child, parent, Boolean(problem));
},
run: handoffFiles.around(async (node, resumed, signal, composed: ComposedTurn) => {
const group = node.groupId ? store.group(node.groupId) : undefined;
@@ -13689,7 +13689,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const callRun = activeRoutineRunForThread(internalCapability.threadId) ?? undefined, result = await handoffFiles.coordinate({ paths, answers, senderId: internalSender.id, recipients: botIds.length, saveOne: async (path) => saveTurnFile(internalCapability, internalSender.id, await attachmentVmForTurn(internalCapability), path, undefined, true),
send: (files) => coordinateBots({ groupId, botIds, message, reason: reason || undefined, rework, thread, title: title || undefined, reply, consult, inMyFolder, doneWhen: doneWhen || undefined, ...(answers ? { answers } : {}), ...(files ? { files } : {}), ...(thread === "new" ? { oneShot: true as const } : {}) }) }); refusedHandoffs.settled(internalCapability.threadId, internalSender, botIds, result.status, callRun);
return json(res, result.status, result.body);
- } if (method === "POST" && path === "/api/internal/post-to-thread") { const posted = await postToThread(await readInternalBody(), { senderId: internalSender.id, fromThreadId: internalCapability.threadId, store, coordinateBots, kept: (botId, threadId) => keepHandedThread(store, botId, threadId), waitsOn: (threadId) => threadWaitsOn(coordinator, internalCapability.roomHandoffId ?? internalCapability.generation, threadId) }); return json(res, posted.status, posted.body); }
+ } if (method === "POST" && path === "/api/internal/post-to-thread") { const posted = await postToThread(await readInternalBody(), { senderId: internalSender.id, fromThreadId: internalCapability.threadId, store, coordinateBots, waitsOn: (threadId) => threadWaitsOn(coordinator, internalCapability.roomHandoffId ?? internalCapability.generation, threadId) }); return json(res, posted.status, posted.body); }
if (method === "GET" && path === "/api/internal/room-targets") {
const source = store.groupByThread(internalCapability.threadId);
if (source && (source.dm || !source.memberIds.includes(internalSender.id))) {
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index 80477147aa..b3bcf855f5 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -11,6 +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 { sameRequest } from "./same-request.ts";
const NOT_RUNNING = "The originating room task is no longer running";
@@ -23,8 +24,6 @@ const TOTAL_BUDGET = /^Request budget exhausted: \d+ turns in all/;
const totalRefusal = (limit: number): string => `This request has started ${limit} turns in all, the most one request may take, so this one was not sent. Nobody can reset that, the person included, so don't ask them to, and don't send it another way. Finish with what you have and say what is left undone.`;
const budgetRefusal = (limit: number): string => `This request reached its limit of ${limit} hand-offs since any work last came back, so this one was not sent. The limit belongs to the request: nobody can reset it, the person included, so don't ask them to, and don't send it another way. If work is still out, end your turn: each result that comes back renews the limit and resumes you. If nothing is out, finish with what you have and say what is left undone.`;
const NO_TURN = "The requesting turn has no root (no turn)";
-/** A stop with no other cause is the person's own. */
-const STOPPED_BY_USER = "Stopped by user";
/** How long a person's stop holds against the same request coming back. */
const STOP_MEMORY_MS = 24 * 60 * 60_000;
const STOPPED_AGAIN = "The person stopped this teammate's work on this request. It isn't handed out again until the person asks again: tell them what you still wanted done, and don't send it another way.";
diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.ts
index 17a5f3827a..f59498e8b9 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, type Answerer, type Assignment, type Assignee, type Clock, type EndResult, type EnqueueRequest, type EnqueueResult, type EnvelopeNames,
+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,
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";
@@ -53,7 +53,6 @@ export interface BeginRequest {
const BRIEF_MAX = 12_000;
const RESULT_MAX = 12_000;
-const STOPPED_WITH_REQUEST = "Stopped with the request it was for";
const DETAIL_MAX = 400;
/** progress() runs once per runtime event; lastActivityAt catches up at this cadence, not per event. */
export const PROGRESS_WRITE_MS = 10_000;
@@ -666,7 +665,7 @@ export class Runtime {
}
/** Cancel this node and everything under it; abort running turns. */
- cancel(id: string, reason = "Stopped by user", outcome: "stopped" | "failed" = "stopped"): void {
+ cancel(id: string, reason = STOPPED_BY_USER, outcome: "stopped" | "failed" = "stopped"): void {
const n = this.store.get(id);
if (!n) return;
this.withBatch(() => outcome === "failed" ? this.cancelTree(n, reason, "failed", "interrupted") : this.cancelTree(n, reason, "cancelled", "stopped"));
@@ -675,7 +674,7 @@ export class Runtime {
/** The person stopped the requester's conversation, and stop means stop: everything it handed out ends with it, work
* that never started and teammates mid-turn alike (and what they handed on), and nothing resumes the stopped
* conversation. */
- stopRequester(owner: Owner, reason = "Stopped by user"): void {
+ stopRequester(owner: Owner, reason = STOPPED_BY_USER): void {
this.withBatch(() => {
for (const snapshot of this.store.all({ nonTerminal: true })) {
if (!ownsConversation(snapshot, owner)) continue;
diff --git a/server/runtime/types.ts b/server/runtime/types.ts
index 1219fd633b..739d65c305 100644
--- a/server/runtime/types.ts
+++ b/server/runtime/types.ts
@@ -60,6 +60,11 @@ export type Status =
export const TERMINAL: readonly Status[] = ["completed", "failed", "cancelled"];
+/** A stop with no other cause is the person's own. */
+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";
+
/** Why it ended the way it did, typed so a requester can branch on it. */
export type Outcome =
| "done"