Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Teammates: a thread opened with thread "new" closes once its result is back
luishron1234d082bc8d47a
diff --git a/server/direct-coordination.e2e.test.ts b/server/direct-coordination.e2e.test.tsindex 0742b9d68a..ec231b18fc 100644--- a/server/direct-coordination.e2e.test.ts+++ b/server/direct-coordination.e2e.test.ts@@ -373,6 +373,63 @@ it("opens a fresh thread on a teammate with coordinate_bots thread \"new\" and gexpect((await f.messages(f.chief.activeTaskId)).some((message: any) => message.tool?.name === "Engineering lead replied" && message.tool.output === "NEW_THREAD_RESULT verified")).toBe(true);}), 45_000);+it("closes a thread \"new\" opened once its result is back, and opens it again for a follow-up sent to it", () => fixture(async f => {+ const gate = join(f.session.info.dataDir, "follow-up.gate");+ const opening = [+ { steps: [{ arguments: { bot_ids: [f.lead.id], message: "FRESH_BRIEF verify the CSV export yourself", 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: "FRESH_RESULT verified" }, { gateFile: gate, reply: "FRESH_RESULT checked again" }] };+ 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);+ const leadNodes = () => f.nodes().filter((node: any) => node.botId === f.lead.id);+ await f.start();+ expect((await f.wait()).status).toBe("settled");+ const [child] = leadNodes();+ const closed = await leadTask(child.threadId);+ expect(closed.openedBy).not.toHaveProperty("kind");+ expect(closed.closedBy).toMatchObject({ botId: f.chief.id, name: "Clive" });+ 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");++ f.plan[f.chief.id] = { turns: [...opening,+ { steps: [{ arguments: { bot_ids: [f.lead.id], message: "FRESH_FOLLOW_UP check it once more", thread: child.threadId } }], reply: "Sent the follow-up" },+ { reply: "The follow-up reported back" },+ ] };+ f.save();+ await f.cli("send", "--bot", f.chief.id, "--task", f.chief.activeTaskId, "--text", "Ask them to check once more in that thread.");+ 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");+ 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 });+}), 90_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: [+ { steps: [{ arguments: { bot_ids: [f.lead.id], message: "JOINED_BRIEF verify the CSV export yourself", thread: "new" } }], reply: "Opened a fresh thread" },+ { reply: "The fresh thread reported back" },+ ] };+ f.plan[f.lead.id] = { turns: [{ gateFile: gate, reply: "JOINED_RESULT verified" }, { reply: "JOINED_RESULT noted" }] };+ 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);+ const stream = await openSse(`${f.session.info.url}/api/events`);+ await f.start();+ await expect.poll(() => f.nodes().find((node: any) => node.botId === f.lead.id)?.status, { timeout: 15_000 }).toBe("running");+ const child = f.nodes().find((node: any) => node.botId === f.lead.id);+ await f.api(`/api/bots/${f.lead.id}/messages`, { text: "Also check the header row while you are there.", threadId: child.threadId });+ await expect.poll(async () => (await f.messages(child.threadId)).some((message: any) => message.role === "user" && !message.peerAsk && message.text === "Also check the header row while you are there."), { timeout: 15_000 }).toBe(true);+ writeFileSync(gate, "go");+ expect((await f.wait()).status).toBe("settled");+ await expect.poll(async () => (await f.messages(f.chief.activeTaskId)).some((message: any) => message.tool?.output === "JOINED_RESULT verified"), { timeout: 15_000 }).toBe(true);+ await expect.poll(async () => (await leadTask(child.threadId)).busy, { timeout: 15_000 }).toBeFalsy();+ stream.close();+ expect(stream.frames.some(frame => frame.kind === "bot" && frame.bot?.id === f.lead.id+ && frame.bot.tasks?.find((task: any) => task.threadId === child.threadId)?.closedBy)).toBe(false);+ expect(await leadTask(child.threadId)).not.toHaveProperty("closedBy");+}), 90_000);+it("names a fresh teammate thread with coordinate_bots title", () => fixture(async f => {f.plan[f.chief.id] = { steps: [{ arguments: { bot_ids: [f.lead.id], message: "TITLED_BRIEF verify the CSV export yourself", thread: "new", title: "CSV export: verify" } }],reply: "Opened a titled thread", resumeReply: "The titled thread reported back" };diff --git a/server/host/finished-work.test.ts b/server/host/finished-work.test.tsnew file mode 100644index 0000000000..938f836a55--- /dev/null+++ b/server/host/finished-work.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest";++import type { TaskRecord } from "../store.ts";+import { closesOnResult } from "./finished-work.ts";++type Task = Parameters<typeof closesOnResult>[0];+const opened = (more: Partial<NonNullable<TaskRecord["openedBy"]>> = {}): NonNullable<TaskRecord["openedBy"]> =>+ ({ botId: "chief", name: "Clive", threadId: "chief-chat", at: 0, ...more });+const closes = (task: Task, opener = "chief", owner = "lead") => closesOnResult(task, opener, owner);++describe("closesOnResult", () => {+ it("closes the standing work thread", () => {+ expect(closes({ openedBy: opened({ kind: "work" }) })).toBe(true);+ });++ it("closes a thread a teammate opened with thread \"new\"", () => {+ expect(closes({ openedBy: opened() })).toBe(true);+ });++ it("keeps a thread \"new\" opened that was pinned, filed in a folder or written in by a person", () => {+ expect(closes({ openedBy: opened(), pinned: true })).toBe(false);+ expect(closes({ openedBy: opened(), projectId: "folder-1" })).toBe(false);+ expect(closes({ openedBy: opened(), askedAt: 1 })).toBe(false);+ });++ 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);+ });++ it("keeps the pair conversation, a burst's part, a room lane and a thread a bot opened on itself", () => {+ expect(closes({ openedBy: opened({ kind: "pair" }) })).toBe(false);+ expect(closes({ openedBy: opened({ burstId: "burst-1" }) })).toBe(false);+ expect(closes({ openedBy: opened({ roomLane: true }) })).toBe(false);+ expect(closes({ openedBy: opened({ botId: "lead" }) }, "lead", "lead")).toBe(false);+ });++ it("leaves a thread another bot opened, one already closed, and one nobody opened", () => {+ expect(closes({ openedBy: opened({ botId: "other" }) })).toBe(false);+ expect(closes({ openedBy: opened({ kind: "work", botId: "other" }) })).toBe(false);+ expect(closes({ openedBy: opened(), closedBy: { botId: "chief", name: "Clive", at: 1 } })).toBe(false);+ expect(closes({})).toBe(false);+ expect(closes(undefined)).toBe(false);+ });+});diff --git a/server/host/finished-work.ts b/server/host/finished-work.tsnew file mode 100644index 0000000000..aef5c1ea2e--- /dev/null+++ b/server/host/finished-work.ts@@ -0,0 +1,16 @@+// 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";++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 thread opened with coordinate_bots thread "new" does too, unless it was kept:+ * pinned, filed in a folder, or written in by a person. The pair conversation, a burst's part 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.kind === undefined && ownerBotId !== openerBotId && !openedBy.burstId && !openedBy.roomLane+ && task.pinned !== true && task.projectId === undefined && task.askedAt === undefined;+}diff --git a/server/index.ts b/server/index.tsindex 1157980893..9774c2a55d 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 { 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 { 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 { assertRequestTarget, guardedRequestPath, requestConflict, requestNeedsInput } from "./guarded-requests.ts";import { botAvatarUrlFromStoredPath } from "../shared/bot-avatar.ts";import { BOT_PROFILE_LIMITS } from "../shared/bot-profile.ts";@@ -3927,10 +3927,10 @@ const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGateif (source) markTaskContextExternallyUpdated(source, parent.threadId);}const childTask = store.taskByThread(child.botId, child.threadId);- if (!child.groupId && child.status === "completed" && !problem && !childTask?.closedBy && !coordinator.activeDirect(child.threadId)- && childTask?.openedBy?.kind === "work" && childTask.openedBy.botId === parent.botId) {+ 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() });+ { botId: parent.botId, name: store.bot(parent.botId)?.name ?? childTask!.openedBy!.name, at: Date.now() });}},run: handoffFiles.around(async (node, resumed, signal, composed: ComposedTurn) => {