Skip to content

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

Hand-off threads: keep the rule that a thread the person wrote in, or a post_to_thread reached, stays open

milind-sonifcdffba7c711
diff --git a/server/host/finished-work.test.ts b/server/host/finished-work.test.ts
index f01e9528a0..5ad1ecc294 100644
--- a/server/host/finished-work.test.ts
+++ b/server/host/finished-work.test.ts
@@ -6,7 +6,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 { WaitManager } from "../waits.ts";
-import { archivedOnResult, archivesOnResult, closesOnResult, createHandedClose, finishHandedThread, type HandedCloseDeps, opensAgain, reopenHandedThread, STOP_GRACE_MS, stoppedByPerson, SYSTEM_STOP } from "./finished-work.ts";
+import { archivedOnResult, archivesOnResult, closesOnResult, createHandedClose, finishHandedThread, type HandedCloseDeps, keepHandedThread, 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"]> =>
@@ -33,8 +33,8 @@ describe("closesOnResult", () => {
expect(closes({ openedBy: oneShot(), projectId: "folder-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("keeps a thread \"new\" opened that the person wrote in", () => {
+ expect(closes({ openedBy: oneShot(), askedAt: 1 })).toBe(false);
});
it("closes the standing work thread whether or not it was kept", () => {
@@ -367,14 +367,14 @@ describe("createHandedClose", () => {
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();
- 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 one-shot thread the person wrote in open, however its work ends", () => {
+ for (const ended of [work({}), work({ status: "failed" }), personStop]) {
+ const { record, start } = world({ openedBy: oneShot(), askedAt: 5 });
+ start().ended(ended, chief, false);
+ vi.advanceTimersByTime(2 * STOP_GRACE_MS);
+ expect(record.closedBy).toBeUndefined();
+ expect(record.archivedAt).toBeUndefined();
+ }
});
it("keeps a thread the person stopped open for an hour, then closes and archives it", () => {
@@ -485,3 +485,18 @@ describe("createHandedClose", () => {
expect(record.closedBy).toBeUndefined();
});
});
+
+describe("keepHandedThread", () => {
+ it("takes the one-shot mark and any due close off a thread a post_to_thread reached, and leaves other threads alone", () => {
+ const tasks: Record<string, Partial<TaskRecord>> = { shot: { openedBy: oneShot({ closesAt: 5 }) }, plain: { openedBy: opened() } };
+ const written: unknown[] = [];
+ 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; },
+ };
+ keepHandedThread(store, "lead", "shot");
+ keepHandedThread(store, "lead", "plain");
+ keepHandedThread(store, "lead", "gone");
+ expect(written).toEqual([["shot", opened()]]);
+ });
+});
diff --git a/server/host/finished-work.ts b/server/host/finished-work.ts
index 16b149e07a..d84ed0818e 100644
--- a/server/host/finished-work.ts
+++ b/server/host/finished-work.ts
@@ -2,7 +2,8 @@
// 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`) 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.
+// writing there: a thread the person wrote in, or one a post_to_thread reached, stays open for good. 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_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";
@@ -10,18 +11,18 @@ import type { Message, Store, TaskRecord } from "../store.ts";
/** 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">;
+type FinishedTask = Pick<TaskRecord, "openedBy" | "closedBy" | "pinned" | "projectId" | "askedAt">;
/** 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 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. */
+ * 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. */
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.pinned !== true && task.projectId === undefined && task.askedAt === undefined;
}
/** Whether a one-shot thread may close into the archive now: nothing there waits on the person (it is unread, its bot asks
@@ -57,6 +58,14 @@ export function reopenHandedThread(store: Pick<Store, "patchTask" | "setTaskClos
store.setTaskClosedBy(ownerBotId, task.threadId, null);
}
+/** 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 its work ends. */
+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, closesAt: _closesAt, ...kept } = openedBy;
+ store.setTaskOpenedBy(ownerBotId, threadId, kept);
+}
+
/** 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];
diff --git a/server/host/thread-posts.test.ts b/server/host/thread-posts.test.ts
index 911b0ce5ce..bafd38a99c 100644
--- a/server/host/thread-posts.test.ts
+++ b/server/host/thread-posts.test.ts
@@ -99,6 +99,16 @@ 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 a07c260cc5..ae8e53a579 100644
--- a/server/host/thread-posts.ts
+++ b/server/host/thread-posts.ts
@@ -80,7 +80,9 @@ 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> }): Promise<Reply> {
+ 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 when a hand-off's work ends. */
+ kept?: (botId: string, threadId: string) => void }): 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.`);
@@ -110,6 +112,7 @@ 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 f6023c046b..19f7fba271 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 { handoffReply } from "./runtime-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, 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 { 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, keepHandedThread, 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";
@@ -13655,7 +13655,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, 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, 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 === "GET" && path === "/api/internal/room-targets") {
const source = store.groupByThread(internalCapability.threadId);
if (source && (source.dm || !source.memberIds.includes(internalSender.id))) {