Skip to content

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

Teammates: a thread opened with thread "new" is also archived once its result is back

luishron123843cce017bcf
diff --git a/server/direct-coordination.e2e.test.ts b/server/direct-coordination.e2e.test.ts
index ec231b18fc..4206419e51 100644
--- a/server/direct-coordination.e2e.test.ts
+++ b/server/direct-coordination.e2e.test.ts
@@ -389,6 +389,7 @@ it("closes a thread \"new\" opened once its result is back, and opens it again f
const closed = await leadTask(child.threadId);
expect(closed.openedBy).not.toHaveProperty("kind");
expect(closed.closedBy).toMatchObject({ botId: f.chief.id, name: "Clive" });
+ expect(closed.archivedAt).toBe(closed.closedBy.at);
expect((await f.messages(child.threadId)).map((message: any) => message.text).filter(Boolean).join("\n")).toContain("FRESH_RESULT verified");
expect(await leadTask(f.lead.activeTaskId)).not.toHaveProperty("closedBy");
@@ -401,11 +402,69 @@ it("closes a thread \"new\" opened once its result is back, and opens it again f
await expect.poll(() => leadNodes().at(-1)?.status, { timeout: 15_000 }).toBe("running");
expect(leadNodes().map((node: any) => node.threadId)).toEqual([child.threadId, child.threadId]);
expect(await leadTask(child.threadId)).not.toHaveProperty("closedBy");
+ expect(await leadTask(child.threadId)).not.toHaveProperty("archivedAt");
writeFileSync(gate, "go");
expect((await f.wait()).status).toBe("settled");
await expect.poll(async () => (await leadTask(child.threadId)).closedBy, { timeout: 15_000 }).toMatchObject({ botId: f.chief.id });
+ expect((await leadTask(child.threadId)).archivedAt).toBeGreaterThan(closed.archivedAt);
}), 90_000);
+it("reruns an identical brief with rework=true in the archived thread \"new\" opened, which leaves the archive while it runs", () => fixture(async f => {
+ const brief = "REWORK_BRIEF run the export check";
+ const gate = join(f.session.info.dataDir, "rework.gate");
+ const opening = [
+ { steps: [{ arguments: { bot_ids: [f.lead.id], message: brief, thread: "new" } }], reply: "Opened a fresh thread" },
+ { reply: "The fresh thread reported back" },
+ ];
+ f.plan[f.chief.id] = { turns: opening };
+ f.plan[f.lead.id] = { turns: [{ reply: "REWORK_RESULT first" }, { gateFile: gate, reply: "REWORK_RESULT second" }] };
+ const leadTask = async (threadId: string) => (await f.api("/api/bots")).bots.find((bot: any) => bot.id === f.lead.id).tasks.find((task: any) => task.threadId === threadId);
+ await f.start();
+ expect((await f.wait()).status).toBe("settled");
+ const child = f.nodes().find((node: any) => node.botId === f.lead.id);
+ await expect.poll(async () => (await leadTask(child.threadId)).archivedAt, { timeout: 15_000 }).toBeTypeOf("number");
+
+ f.plan[f.chief.id] = { turns: [...opening,
+ { steps: [{ arguments: { bot_ids: [f.lead.id], message: brief, thread: child.threadId, rework: true } }], reply: "Sent it again" },
+ { reply: "The rework reported back" },
+ ] };
+ f.save();
+ await f.cli("send", "--bot", f.chief.id, "--task", f.chief.activeTaskId, "--text", "Have them run it once more in that thread.");
+ await expect.poll(() => f.nodes().filter((node: any) => node.botId === f.lead.id).at(-1)?.status, { timeout: 15_000 }).toBe("running");
+ const [sent] = f.evidence().filter((turn: any) => turn.botId === f.chief.id).at(-1).evidence.filter((entry: any) => entry.step).map((entry: any) => entry.response.result);
+ expect(sent.isError).toBeFalsy();
+ expect(JSON.parse(sent.content[0].text).receipts[0]).toMatchObject({ outcome: "queued", threadId: child.threadId });
+ const reopened = await leadTask(child.threadId);
+ expect(reopened).not.toHaveProperty("archivedAt");
+ expect(reopened).not.toHaveProperty("closedBy");
+ writeFileSync(gate, "go");
+ expect((await f.wait()).status).toBe("settled");
+ await expect.poll(async () => (await leadTask(child.threadId)).archivedAt, { timeout: 15_000 }).toBeTypeOf("number");
+ expect((await f.messages(child.threadId)).map((message: any) => message.text).filter(Boolean).join("\n")).toContain("REWORK_RESULT second");
+}), 90_000);
+
+it("lets the opener list and close a thread \"new\" opened after it was archived", () => fixture(async f => {
+ f.plan[f.chief.id] = { steps: [{ arguments: { bot_ids: [f.lead.id], message: "LISTED_BRIEF verify the CSV export yourself", thread: "new" } }],
+ reply: "Opened a fresh thread", resumeReply: "The fresh thread reported back" };
+ f.plan[f.lead.id] = { reply: "LISTED_RESULT verified" };
+ await f.start();
+ expect((await f.wait()).status).toBe("settled");
+ const child = f.nodes().find((node: any) => node.botId === f.lead.id);
+ await expect.poll(async () => (await f.api("/api/bots")).bots.find((bot: any) => bot.id === f.lead.id).tasks
+ .find((task: any) => task.threadId === child.threadId).archivedAt, { timeout: 15_000 }).toBeTypeOf("number");
+ f.plan[f.chief.id] = { steps: [
+ { tool: "list_threads", arguments: {} },
+ { tool: "close_thread", arguments: { thread_id: child.threadId } },
+ ], reply: "Checked the finished thread" };
+ f.save();
+ await f.cli("send", "--bot", f.chief.id, "--task", f.chief.activeTaskId, "--text", "Find the finished engineering thread and close it.");
+ expect((await f.wait()).status).toBe("settled");
+ const [listed, closed] = f.evidence().at(-1).evidence.filter((entry: any) => entry.step).map((entry: any) => entry.response.result);
+ expect(listed.content[0].text).toContain(child.threadId);
+ expect(closed.isError).toBeFalsy();
+ expect(closed.content[0].text).toContain("Closed #");
+}), 60_000);
+
it("keeps a thread \"new\" opened open when a person wrote in it before its result came back", () => fixture(async f => {
const gate = join(f.session.info.dataDir, "person-wrote.gate");
f.plan[f.chief.id] = { turns: [
@@ -606,6 +665,7 @@ it("continues one recipient thread for every follow-up from the same conversatio
expect(first.title).toBe("@Clive · work");
expect(first.openedBy).toMatchObject({ botId: f.chief.id, name: "Clive", kind: "work", threadId: f.chief.activeTaskId });
expect(first.closedBy).toMatchObject({ botId: f.chief.id });
+ expect(first).not.toHaveProperty("archivedAt");
await send("Now ask them to add the header row.");
await send("Now ask them to document it.");
const tasks = await leadTasks();
diff --git a/server/handed-waits.e2e.test.ts b/server/handed-waits.e2e.test.ts
index 5d00ef047f..c81607da30 100644
--- a/server/handed-waits.e2e.test.ts
+++ b/server/handed-waits.e2e.test.ts
@@ -100,6 +100,27 @@ describe("waits set by work a bot handed on", () => {
finish(sourceThread);
}, 60_000);
+ it("closes a thread \"new\" opened but keeps it out of the archive while its wait is armed, so the wait's message is seen", async () => {
+ const sourceThread = (await api("GET", "/api/bots?messages=0")).bots.find((bot: any) => bot.id === source.id).threadId;
+ await control(["send", "--bot", source.id, "--text", "Have the peer tell me when the report lands."]);
+ const { receipts } = await api("POST", "/api/internal/coordinate-bots", { botIds: [peer.id], message: "Watch for the fixture report.", thread: "new" }, await token(sourceThread));
+ expect(receipts).toHaveLength(1);
+ const work = await handedWork(sourceThread);
+ const made = await call("POST", "/api/internal/waits", fileWait("report"), await token(work.threadId));
+ expect(made.status, JSON.stringify(made.body)).toBe(201);
+ const peerTask = async () => (await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === peer.id).tasks.find((task: any) => task.threadId === work.threadId);
+ finish(work.threadId);
+ await expect.poll(async () => (await peerTask()).closedBy?.botId, { timeout: 15_000 }).toBe(source.id);
+ expect(await peerTask()).not.toHaveProperty("archivedAt");
+
+ writeFileSync(join(folder, "report.txt"), "here");
+ await expect.poll(async () => (await api("GET", `/api/threads/${work.threadId}/messages`)).messages.some((m: any) => m.wait?.status === "fired"), { timeout: 30_000 }).toBe(true);
+ expect(storedWaits()).toEqual([]);
+ expect(await peerTask()).toMatchObject({ unread: true });
+ expect(await peerTask()).not.toHaveProperty("archivedAt");
+ finish(sourceThread);
+ }, 60_000);
+
it("refuses a wait to work a routine handed on", async () => {
const { routine } = await api("POST", "/api/routines", {
name: "Handed watch", prompt: "Ask the peer to watch for the report.", botId: source.id,
diff --git a/server/host/finished-work.test.ts b/server/host/finished-work.test.ts
index 938f836a55..bef69eb2fb 100644
--- a/server/host/finished-work.test.ts
+++ b/server/host/finished-work.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { TaskRecord } from "../store.ts";
-import { closesOnResult } from "./finished-work.ts";
+import { archivesOnResult, closesOnResult, finishHandedThread, reopenHandedThread } from "./finished-work.ts";
type Task = Parameters<typeof closesOnResult>[0];
const opened = (more: Partial<NonNullable<TaskRecord["openedBy"]>> = {}): NonNullable<TaskRecord["openedBy"]> =>
@@ -42,3 +42,65 @@ describe("closesOnResult", () => {
expect(closes(undefined)).toBe(false);
});
});
+
+describe("archivesOnResult", () => {
+ it("archives a thread \"new\" opened, but not the standing work thread", () => {
+ expect(archivesOnResult({ openedBy: opened() }, false)).toBe(true);
+ expect(archivesOnResult({ openedBy: opened({ kind: "work" }) }, false)).toBe(false);
+ });
+
+ it("leaves an unread thread in the sidebar", () => {
+ expect(archivesOnResult({ openedBy: opened(), unread: true }, false)).toBe(false);
+ });
+
+ it("leaves a thread whose wait is still armed in the sidebar", () => {
+ expect(archivesOnResult({ openedBy: opened() }, true)).toBe(false);
+ });
+});
+
+describe("finishHandedThread", () => {
+ const fakeStore = (task: Partial<TaskRecord>) => {
+ const record = { threadId: "lead-thread", ...task } as TaskRecord;
+ const calls: string[] = [];
+ return {
+ record, calls,
+ taskByThread: (_botId: string, threadId: string) => threadId === record.threadId ? record : undefined,
+ bot: (botId: string) => (botId === "chief" ? { name: "Clive" } : undefined) as never,
+ setTaskClosedBy: (_botId: string, _threadId: string, closedBy: TaskRecord["closedBy"] | null) => { record.closedBy = closedBy ?? undefined; calls.push("closed"); return record; },
+ patchTask: (_botId: string, _threadId: string, patch: Partial<TaskRecord>) => { Object.assign(record, patch); calls.push(`archivedAt=${patch.archivedAt}`); return record; },
+ };
+ };
+
+ it("closes and archives a thread \"new\" opened at the same moment", () => {
+ const store = fakeStore({ openedBy: opened() });
+ finishHandedThread(store, "lead", "lead-thread", "chief", () => false, 42);
+ expect(store.record.closedBy).toEqual({ botId: "chief", name: "Clive", at: 42 });
+ expect(store.record.archivedAt).toBe(42);
+ });
+
+ it("only closes the standing work thread and an unread thread", () => {
+ for (const task of [{ openedBy: opened({ kind: "work" }) }, { openedBy: opened(), unread: true }]) {
+ 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: opened(), pinned: true }, { openedBy: opened(), askedAt: 1 }, { openedBy: opened({ kind: "pair" as const }) }]) {
+ const store = fakeStore(task);
+ finishHandedThread(store, "lead", "lead-thread", "chief", () => false, 42);
+ expect(store.calls).toEqual([]);
+ }
+ });
+});
+
+describe("reopenHandedThread", () => {
+ it("unarchives an archived thread and leaves an open one alone", () => {
+ const patches: unknown[] = [];
+ const store = { patchTask: (_botId: string, _threadId: string, patch: unknown) => { patches.push(patch); return null; } };
+ reopenHandedThread(store, "lead", { threadId: "t", archivedAt: 5 });
+ reopenHandedThread(store, "lead", { threadId: "t" });
+ expect(patches).toEqual([{ archivedAt: undefined }]);
+ });
+});
diff --git a/server/host/finished-work.ts b/server/host/finished-work.ts
index aef5c1ea2e..ec5eb76c99 100644
--- a/server/host/finished-work.ts
+++ b/server/host/finished-work.ts
@@ -1,6 +1,6 @@
// Work one bot hands a teammate is finished once its result is reported back: the thread it ran in closes, which folds
// it out of the sidebar, and the next turn in it opens it again.
-import type { TaskRecord } from "../store.ts";
+import type { Store, TaskRecord } from "../store.ts";
type FinishedTask = Pick<TaskRecord, "openedBy" | "closedBy" | "pinned" | "projectId" | "askedAt">;
@@ -14,3 +14,26 @@ export function closesOnResult(task: FinishedTask | undefined, openerBotId: stri
return openedBy.kind === undefined && ownerBotId !== openerBotId && !openedBy.burstId && !openedBy.roomLane
&& task.pinned !== true && task.projectId === undefined && task.askedAt === undefined;
}
+
+/** Whether a thread that just closed on its result is also archived: one opened with thread "new" 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 !== undefined && task.openedBy.kind === undefined && task.unread !== true && !waitArmed;
+}
+
+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 {
+ 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 });
+}
+
+/** A thread the opener sends to again leaves the archive, so the person sees the work it runs. */
+export function reopenHandedThread(store: Pick<Store, "patchTask">, ownerBotId: string, task: Pick<TaskRecord, "threadId" | "archivedAt">): void {
+ if (task.archivedAt !== undefined) store.patchTask(ownerBotId, task.threadId, { archivedAt: undefined });
+}
diff --git a/server/host/work-thread.test.ts b/server/host/work-thread.test.ts
index 9614c2c7cb..109017bf0b 100644
--- a/server/host/work-thread.test.ts
+++ b/server/host/work-thread.test.ts
@@ -28,6 +28,12 @@ describe("workThreadFor", () => {
expect(fromLiaison("opened-by-liaison", false)?.threadId).toBe("opened-by-liaison");
});
+ it("keeps a thread the sender opened after it was archived, so a follow-up or rework there reopens it", () => {
+ const archived = { ...store, taskByThread: () => task("finished-new", { botId: "liaison", name: "Liaison", threadId: "liaison-chat", at: 0 }, { archivedAt: 9, closedBy: { botId: "liaison", name: "Liaison", at: 9 } }) };
+ expect(workThreadFor(archived, { botId: "bugfixer", botName: "Bugfixer", fromBotId: "liaison", fromThreadId: "liaison-chat", thread: "finished-new",
+ notice: false, answering: undefined, also: () => true, reach: () => true })?.threadId).toBe("finished-new");
+ });
+
it("lets a one-way notice answer the thread that handed the sender work, and refuses new work there", () => {
expect(fromLiaison("run-1", true)?.threadId).toBe("run-1");
expect(() => fromLiaison("run-1", false)).toThrow(/handed you work: answer it there with reply "none"/);
diff --git a/server/host/work-thread.ts b/server/host/work-thread.ts
index 3a9ce81eb6..46a7c06a8d 100644
--- a/server/host/work-thread.ts
+++ b/server/host/work-thread.ts
@@ -3,7 +3,7 @@ import { OUTSIDE_STAYS_HERE } from "./outside-lineage.ts";
/** Where coordinate_bots sends to a teammate outside a room, by its `thread`: "standing" is the sender conversation's one
* work thread with that teammate (undefined until it is opened), "new" opens one (undefined), and any other value is the id
- * of a thread the sender opened on that teammate earlier, or `answering`: the requester of the sender's running assignment
+ * of a thread the sender opened on that teammate earlier, archived or not, or `answering`: the requester of the sender's running assignment
* when it asked with reply none. Nothing returns from such work on its own, so it takes a one-way notice (`notice`) there,
* never new work.
* Throws when it is neither. `also` narrows which threads count. */
@@ -18,12 +18,13 @@ export function workThreadFor(store: Pick<Store, "workThread" | "taskByThread">,
if (thread === "standing") return store.workThread(botId, input.fromBotId, input.fromThreadId, false, (task) => also(task) && reach(task));
const task = store.taskByThread(botId, thread);
if (task && !reach(task)) throw new Error(OUTSIDE_STAYS_HERE);
- const usable = task !== undefined && task.archivedAt === undefined && also(task);
+ const allowed = task !== undefined && also(task);
+ const usable = allowed && task.archivedAt === undefined;
if (input.any) {
if (usable && !task.closedBy) return task;
throw new Error(`"${thread}" is not an open thread of ${input.botName}: use a threadId list_threads shows on them`);
}
- if (usable && task.openedBy?.botId === input.fromBotId && !task.openedBy.roomLane) return task;
+ if (allowed && task.openedBy?.botId === input.fromBotId && !task.openedBy.roomLane) return task;
const handedWork = usable && input.answering?.botId === botId && input.answering.threadId === thread;
if (handedWork && input.notice) return task;
if (handedWork) throw new Error(`"${thread}" handed you work: answer it there with reply "none", a one-way notice; it cannot be given new work`);
diff --git a/server/index.ts b/server/index.ts
index 9774c2a55d..bff5c433c7 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, 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 } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { closesOnResult } 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 } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { finishHandedThread, 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";
@@ -3926,12 +3926,7 @@ const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate
const source = store.bot(parent.botId);
if (source) markTaskContextExternallyUpdated(source, parent.threadId);
}
- const childTask = store.taskByThread(child.botId, child.threadId);
- if (!child.groupId && child.status === "completed" && !problem && !coordinator.activeDirect(child.threadId)
- && closesOnResult(childTask, parent.botId, child.botId)) {
- store.setTaskClosedBy(child.botId, child.threadId,
- { botId: parent.botId, name: store.bot(parent.botId)?.name ?? childTask!.openedBy!.name, at: Date.now() });
- }
+ 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));
},
run: handoffFiles.around(async (node, resumed, signal, composed: ComposedTurn) => {
const group = node.groupId ? store.group(node.groupId) : undefined;
@@ -13589,7 +13584,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
});
usageTrace.link(node.id, node.parentId, { threadId: internalCapability.threadId, turnId: liveTurnByThread.get(internalCapability.threadId) ?? "" }); if (!duplicate) { actingPeople.handOn(internalCapability, node, lends, CLOUD_HOME ? undefined : OWN_SERVER_LENDER); if (!lends && !room && !lane) handedInUnproven(routed.threadId); }
if (!duplicate && call.files?.length) handoffFiles.sent(node.id, { botId: internalSender.id, name: internalSender.name }, call.files);
- if (duplicate && createdThread) store.deleteTask(target.botId, createdThread);
+ if (!duplicate && continued) reopenHandedThread(store, target.botId, continued); if (duplicate && createdThread) store.deleteTask(target.botId, createdThread);
else if (createdThread) {
threadStarters.set(createdThread, opener); if (via === "direct" && !(fresh && call.title)) titleHandedThread(target.botId, createdThread, call.message, fresh ? "" : `@${internalSender.name} · `);
if (fresh && !EXTERNAL) internalCapability.openedThreads += 1;