Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Say why a queued handoff has not started, with its handoff id (#4378)
Aditya Umale17b11dfcb117
diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex ca6fa5d20f..956b7ea26f 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -76,7 +76,8 @@ function assignmentLine(a: Json): string {: typeof a.botId === "string" && a.botId ? a.botId : "a teammate";const status = String(a.status ?? "unknown");const outcome = typeof a.outcome === "string" && a.outcome && a.outcome !== "done" && a.outcome !== status ? ` (${a.outcome})` : "";- const detail = typeof a.outcomeDetail === "string" && a.outcomeDetail.trim() ? `: ${a.outcomeDetail.trim()}` : "";+ const detail = typeof a.outcomeDetail === "string" && a.outcomeDetail.trim() ? `: ${a.outcomeDetail.trim()}`+ : typeof a.waiting === "string" && a.waiting ? `: ${a.waiting}` : "";return `${id} → ${who}: ${STATUS_WORDS[status] ?? status}${outcome}${detail}`;}@@ -385,7 +386,8 @@ export async function callTool(called: string, input: Json, context: ToolCallConconst state = stateWord[String(thread.state)] ?? String(thread.state);const unread = thread.unread === true ? ", unread for the person" : "";const handoff = typeof thread.delegationId === "string" && thread.delegationId ? ` [delegation id: ${thread.delegationId}]` : "";- return `- #${String(thread.title)} (${where}, ${state}${unread}) [thread id: ${String(thread.threadId)}]${handoff}`;+ const waiting = typeof thread.waiting === "string" && thread.waiting ? `: ${thread.waiting}` : "";+ return `- #${String(thread.title)} (${where}, ${state}${waiting}${unread}) [thread id: ${String(thread.threadId)}]${handoff}`;});return { text: `Threads, newest first:\n${lines.join("\n")}` };}diff --git a/server/drivers/agents-proxy.test.ts b/server/drivers/agents-proxy.test.tsindex b233aea499..4ab807b526 100644--- a/server/drivers/agents-proxy.test.ts+++ b/server/drivers/agents-proxy.test.ts@@ -47,6 +47,7 @@ let assignmentStatusResponse: unknown = DONE_ASSIGNMENT;let assignmentStatusCode = 200;let lastThreadBody: any = null;let threadCalls = 0;+let threadsList: unknown = { threads: [] };let threadResponse: unknown = { threadId: "thread-new", title: "QA: PR #1", botId: "bot-asker", botName: "Asker", self: true, state: "running", limit: 3 };let computerRequests: { method: string; url: string; body: unknown }[] = [];let computerResponse: unknown = { current: "local", available: ["local", "vm"] };@@ -259,6 +260,11 @@ beforeAll(async () => {res.end(JSON.stringify(assignmentStatusResponse));return;}+ if (req.method === "GET" && req.url?.startsWith("/api/internal/threads?")) {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify(threadsList));+ return;+ }if (req.method === "POST" && req.url === "/api/internal/threads") {let data = "";req.on("data", (c) => (data += c));@@ -1239,6 +1245,19 @@ describe("agents-proxy MCP surface", () => {assignmentStatusResponse = DONE_ASSIGNMENT;});+ it("assignment_status and list_threads say why a queued handoff has not started, with its handoff id", async () => {+ const waiting = "waiting for a free thread slot: Ops is already running 3 of 3 threads at once";+ assignmentStatusResponse = { outstanding: [{ id: "asg-q", botId: "bot-ops", botName: "Ops", status: "queued", waiting }] };+ threadsList = { threads: [{ threadId: "t-q", botId: "bot-ops", botName: "Ops", title: "Export CSV", state: "queued", waiting, delegationId: "asg-q", own: false, unread: false, openedAt: 1 }] };+ try {+ expect((await callTool("assignment_status", {})).result.content[0].text).toContain(`- asg-q → @Ops: queued, not started yet: ${waiting}`);+ expect((await callTool("list_threads", {})).result.content[0].text).toContain(`#Export CSV (on @Ops, queued: ${waiting}) [thread id: t-q] [delegation id: asg-q]`);+ } finally {+ assignmentStatusResponse = DONE_ASSIGNMENT;+ threadsList = { threads: [] };+ }+ });+it("assignment_status with an id renders status, outcome, the result head and the assignment's own hand-offs", async () => {assignmentStatusResponse = {assignment: { id: "asg-9", botId: "bot-helper", botName: "Helper", status: "failed", outcome: "provider_error", outcomeDetail: "the engine exited early", result: "x".repeat(2_500) },diff --git a/server/host/queued-reason.test.ts b/server/host/queued-reason.test.tsnew file mode 100644index 0000000000..08c0a22dae--- /dev/null+++ b/server/host/queued-reason.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from "vitest";++import type { HandoffView } from "../coordinator.ts";+import { createQueuedReason, type QueuedReasonDeps } from "./queued-reason.ts";++const node = (over: Partial<HandoffView> = {}) => ({ id: "h-1", rootId: "h-0", parentId: "h-0", threadId: "t-new", botId: "bot-ops", status: "queued", ...over }) as HandoffView;+const busy = [{ threadId: "t-a", title: "Weekly report" }, { threadId: "t-b", title: "Fix login" }];+const reason = (over: Partial<QueuedReasonDeps> = {}) => createQueuedReason({+ botName: () => "Ops", waitsForComputer: () => false, threadBusy: () => false,+ slots: () => ({ busy, limit: 2 }), groupTurn: () => false, behindPerson: () => undefined, ...over,+});+const full = "waiting for a free thread slot: Ops is already running 2 of 2 threads at once";++describe("why a queued handoff has not started", () => {+ it("names a full thread list with its count, and the busy threads only to a caller allowed to see them", () => {+ expect(reason()(node())).toBe(full);+ expect(reason()(node(), () => true)).toBe(`${full}: "Weekly report", "Fix login"`);+ expect(reason()(node(), (threadId) => threadId === "t-b")).toBe(`${full}: "Fix login"`);+ expect(reason()(node(), () => false)).toBe(full);+ });++ it("keeps the person's open card first, as before", () => {+ expect(reason({ behindPerson: () => ({ kind: "question", title: "Pick a date" }) })(node()))+ .toBe('waiting for a free slot: that teammate is waiting on the person\'s answer in its thread "Pick a date"; tell the person to open it');+ });++ it("says when it waits for a computer, an earlier turn in its thread, or a room turn", () => {+ expect(reason({ waitsForComputer: () => true })(node())).toBe("waiting for the computer it needs, which another turn is using");+ expect(reason({ threadBusy: (_bot, threadId) => threadId === "t-new" })(node())).toBe("waiting for an earlier turn in that thread to finish");+ expect(reason({ slots: () => ({ busy: [], limit: 2 }), groupTurn: () => true })(node())).toBe("waiting for Ops to finish its turn in a room");+ });++ it("falls back to the plain line when nothing explains it, and for a room's handoff", () => {+ expect(reason({ slots: () => ({ busy: [], limit: 2 }) })(node())).toBe("waiting for that teammate to be free");+ expect(reason()(node({ groupId: "room-1" }))).toBe("waiting for that teammate to be free");+ });+});diff --git a/server/host/queued-reason.ts b/server/host/queued-reason.tsnew file mode 100644index 0000000000..10fca2e1ec--- /dev/null+++ b/server/host/queued-reason.ts@@ -0,0 +1,33 @@+import type { HandoffView } from "../coordinator.ts";++export interface QueuedReasonDeps {+ botName(botId: string): string | undefined;+ /** The handoff already ran and is parked until a computer another turn uses is free. */+ waitsForComputer(node: HandoffView): boolean;+ threadBusy(botId: string, threadId: string): boolean;+ /** The bot's threads that hold a slot now, and how many it may run at once when a bot starts the work. */+ slots(botId: string): { busy: { threadId: string; title: string }[]; limit: number };+ groupTurn(botId: string): boolean;+ behindPerson(node: HandoffView): { kind: "approval" | "question" | "review"; title: string } | undefined;+}++/** `showTitle`: name the busy threads it allows; only for the receiver itself, whose own threads they are. Otherwise just the count. */+export function createQueuedReason(deps: QueuedReasonDeps) {+ return (node: HandoffView, showTitle?: (threadId: string) => boolean): string => {+ const card = deps.behindPerson(node);+ if (card) return `waiting for a free slot: that teammate is waiting on the person's ${card.kind === "question" ? "answer" : card.kind} in its thread ${JSON.stringify(card.title)}; tell the person to open it`;+ // A room's handoff waits on the room, not on these.+ if (node.groupId) return "waiting for that teammate to be free";+ const name = deps.botName(node.botId) ?? "that teammate";+ if (deps.waitsForComputer(node)) return "waiting for the computer it needs, which another turn is using";+ if (deps.threadBusy(node.botId, node.threadId)) return "waiting for an earlier turn in that thread to finish";+ const { busy, limit } = deps.slots(node.botId);+ if (busy.length >= limit) {+ const named = showTitle ? busy.filter((thread) => showTitle(thread.threadId)) : [];+ const which = named.length ? `: ${named.map((thread) => JSON.stringify(thread.title)).join(", ")}` : "";+ return `waiting for a free thread slot: ${name} is already running ${busy.length} of ${limit} threads at once${which}`;+ }+ if (deps.groupTurn(node.botId)) return `waiting for ${name} to finish its turn in a room`;+ return "waiting for that teammate to be free";+ };+}diff --git a/server/index.ts b/server/index.tsindex 2f9d2519f7..799f453446 100644--- a/server/index.ts+++ b/server/index.ts@@ -295,6 +295,7 @@ import { CONSENT_RULE, escapeNotes, labelledLine, OUTSIDE, peerLineText, peerProimport { decideRoomPost, emptyRoomPostBudget, type RoomPostAttempt, type RoomPostBudget } from "./room-post-budget.ts";import { pageMessage, pageSize, slimMessage } from "./host/message-pages.ts";import { createTeammatePrompts } from "./host/teammate-prompts.ts";+import { createQueuedReason } from "./host/queued-reason.ts";import { ReplayBuffer } from "./host/sse-replay.ts";import {mentionedBots,@@ -3802,6 +3803,9 @@ function coordinationSystemInstructions(): string {}const threadReadableFrom = (threadId: string) => (other: string): boolean => !proactive.fence.confines(other) && (CLOUD_TEAM ? teamHost.readableFrom(threadId)(other) : !CLOUD_HOME || cloudOwnerOnlyThread(other));+const queuedStatus = createQueuedReason({ botName: (id) => store.bot(id)?.name, threadBusy, groupTurn: (id) => Boolean(activeGroupTurnForBot(id)), behindPerson: queuedBehindPerson,+ waitsForComputer: (node) => { const seat = parkedSeats.get(node.id); return Boolean(seat && !turnResources.free(seat)); },+ slots: (id) => ({ busy: store.tasks(id).filter((task) => threadBusy(id, task.threadId)).map(({ threadId, title }) => ({ threadId, title })), limit: maxConcurrentChildThreads(cfg, botThreadsHost(cloudPlanTier.starter())) }) });const teammatePrompts = createTeammatePrompts({ store, outstandingDirect: (threadId) => coordinator.outstandingDirect(threadId), openPersonCard, queuedStatus, isUnattended, fullAccess: fullAccessForSource, startedOutside: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "outside" || coordinator.active().some((node) => node.threadId === threadId && node.origin?.kind === "outside"), guestDriven: cloudGuestDriven, confined: (threadId) => proactive.fence.confines(threadId), readableFrom: threadReadableFrom, waitingForPerson: (chief, teammates, readable) => questionRouting.waitingForPerson(chief, teammates, readable) });function queuedBehindPerson(node: HandoffView): { threadId: string; kind: "approval" | "question" | "review"; title: string } | undefined {@@ -3814,12 +3818,6 @@ function queuedBehindPerson(node: HandoffView): { threadId: string; kind: "approreturn undefined;}-function queuedStatus(node: HandoffView): string {- const card = queuedBehindPerson(node);- return card ? `waiting for a free slot: that teammate is waiting on the person's ${card.kind === "question" ? "answer" : card.kind} in its thread ${JSON.stringify(card.title)}; tell the person to open it`- : "waiting for that teammate to be free";-}-const queuedBehindPersonNoted = new Set<string>();function noteQueuedBehindPerson(node: HandoffView): void {@@ -13396,7 +13394,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {store, coordinator, from: internalSender, fromThreadId: internalCapability.threadId,ownsThread: (botId, threadId) => Boolean(connectorThread(botId, threadId)),shown: (id) => !proactive.fence.confines(id) && (CLOUD_TEAM ? teamHost.readableFrom(internalCapability.threadId)(id) : cloudLendingView(internalCapability) ? cloudOwnerOnlyThread(id) : true),- threadBusy, queuedThreadPosition,+ threadBusy, queuedThreadPosition, queuedReason: queuedStatus,}), createToolTimingRoute(usageTrace, internalCapability.threadId)], { req, res, url, path, method, auth, json, readBody })) return;if (method === "POST" && path === "/api/internal/attach-file") {const from = internalSender;@@ -14025,10 +14023,11 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const fromThreadId = internalCapability.threadId;if (!connectorThread(internalSender.id, fromThreadId)) return json(res, 403, { error: "source conversation does not belong to sender" });type Row = NonNullable<ReturnType<Coordinator["status"]>>["assignment"];+ const queuedWaiting = (id: string) => { const node = coordinator.node(id); return node?.status === "queued" ? { waiting: queuedStatus(node) } : {}; };const shape = (a: Row) => ({id: a.id, botId: a.assignee.botId, botName: store.bot(a.assignee.botId)?.name ?? a.assignee.botId, status: a.status,...(a.outcome !== undefined ? { outcome: a.outcome } : {}), ...(a.outcomeDetail !== undefined ? { outcomeDetail: a.outcomeDetail } : {}),- result: a.result, ...(a.question !== undefined ? { question: a.question } : {}), mode: a.mode, reply: a.reply,+ result: a.result, ...(a.question !== undefined ? { question: a.question } : {}), mode: a.mode, reply: a.reply, ...queuedWaiting(a.id),createdAt: a.createdAt, ...(a.startedAt !== undefined ? { startedAt: a.startedAt } : {}), ...(a.finishedAt !== undefined ? { finishedAt: a.finishedAt } : {}),});// Only this conversation's own tree; a row of another conversation is refused.diff --git a/server/routes/internal-threads.test.ts b/server/routes/internal-threads.test.tsnew file mode 100644index 0000000000..ee9eabc044--- /dev/null+++ b/server/routes/internal-threads.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vitest";++import type { HandoffView } from "../coordinator.ts";+import type { BotRecord, TaskRecord } from "../store.ts";+import { createInternalThreadRoutes } from "./internal-threads.ts";++const lead = { id: "bot-lead", name: "Lead", section: "Work" } as BotRecord;+const ops = { id: "bot-ops", name: "Ops", section: "Work" } as BotRecord;+const task = (threadId: string, title: string, openedBy?: unknown) => ({ threadId, title, createdAt: 1, openedBy }) as TaskRecord;+const handoff = { id: "h-42", rootId: "h-1", parentId: "h-1", threadId: "t-ops-new", botId: "bot-ops", status: "queued" } as HandoffView;+const tasks: Record<string, TaskRecord[]> = {+ "bot-lead": [task("t-lead", "Lead main")],+ "bot-ops": [task("t-ops-busy", "Weekly report"), task("t-ops-new", "Export CSV", { botId: "bot-lead", name: "Lead", at: 5 })],+};++async function listThreads(from: BotRecord) {+ const route = createInternalThreadRoutes({+ store: { bot: (id: string) => [lead, ops].find((bot) => bot.id === id), bots: [lead, ops], tasks: (id: string) => tasks[id] ?? [] } as never,+ coordinator: { awaitingAnswer: () => false, parkedDirect: () => undefined, activeDirect: (threadId: string) => threadId === "t-ops-new" ? handoff : undefined, active: () => [handoff] } as never,+ from, fromThreadId: "t-own", ownsThread: () => true, shown: () => true,+ threadBusy: (_bot, threadId) => threadId === "t-ops-busy", queuedThreadPosition: () => null,+ queuedReason: (node, showTitle) => `${node.id} waits${showTitle ? " (titles)" : ""}`,+ });+ let body: { threads: Array<Record<string, unknown>> } | undefined;+ await route({ res: {}, path: "/api/internal/threads", method: "GET", json: (_res: unknown, _status: number, value: never) => { body = value; } } as never);+ return body!.threads;+}++describe("list_threads on a queued handoff", () => {+ it("tells the sender why it waits and which handoff it is, without the receiver's thread titles", async () => {+ const row = (await listThreads(lead)).find((thread) => thread.threadId === "t-ops-new");+ expect(row).toMatchObject({ state: "queued", waiting: "h-42 waits", delegationId: "h-42", own: false });+ });++ it("lets the receiver name its own busy threads, and adds nothing to a thread that is not queued", async () => {+ const rows = await listThreads(ops);+ expect(rows.find((thread) => thread.threadId === "t-ops-new")).toMatchObject({ state: "queued", waiting: "h-42 waits (titles)", delegationId: "h-42", own: true });+ const running = rows.find((thread) => thread.threadId === "t-ops-busy");+ expect(running).toMatchObject({ state: "running" });+ expect(running).not.toHaveProperty("waiting");+ });+});diff --git a/server/routes/internal-threads.ts b/server/routes/internal-threads.tsindex ee326fe053..f19538398c 100644--- a/server/routes/internal-threads.ts+++ b/server/routes/internal-threads.ts@@ -1,5 +1,5 @@import { chiefTidies } from "../chief-of-staff.ts";-import type { Coordinator } from "../coordinator.ts";+import type { Coordinator, HandoffView } from "../coordinator.ts";import { reachablePeers } from "../peer-roster.ts";import type { BotRecord, Store, TaskRecord } from "../store.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -11,13 +11,15 @@ interface ThreadRow {threadId: string; botId: string; botName: string; title: string;state: ThreadState;unread: boolean; openedAt: number; delegationId?: string; own: boolean;+ /** Why a queued handoff hasn't started (host/queued-reason.ts). */+ waiting?: string;openedBy?: string;}/** Only dispatch inside the internal capability gate: `from` and `fromThreadId` come from the caller's capability. */export function createInternalThreadRoutes(deps: {store: Pick<Store, "bot" | "bots" | "tasks" | "taskByThread" | "appendMessage" | "patchTask" | "setTaskClosedBy">;- coordinator: Pick<Coordinator, "awaitingAnswer" | "parkedDirect" | "activeDirect">;+ coordinator: Pick<Coordinator, "awaitingAnswer" | "parkedDirect" | "activeDirect" | "active">;from: BotRecord;fromThreadId: string;ownsThread(botId: string, threadId: string): boolean;@@ -25,6 +27,8 @@ export function createInternalThreadRoutes(deps: {shown(threadId: string): boolean;threadBusy(botId: string, threadId: string): boolean;queuedThreadPosition(botId: string, threadId: string): number | null;+ /** `showTitle`: the caller is the receiver, so its own busy threads it may see can be named. */+ queuedReason(node: HandoffView, showTitle?: (threadId: string) => boolean): string;}): RouteHandler {const { store, coordinator, from, fromThreadId } = deps;return async ({ res, path, method, json }) => {@@ -43,12 +47,18 @@ export function createInternalThreadRoutes(deps: {if (task.closedBy) return "closed" as const;return "idle" as const;};+ // A queued handoff says why it waits and which handoff it is, so a bot can tell the person and match a report.+ const queued = (bot: BotRecord, task: TaskRecord, state: ThreadState): Pick<ThreadRow, "waiting" | "delegationId"> => {+ const node = state === "queued" ? coordinator.active().find((n) => n.threadId === task.threadId && n.botId === bot.id && !n.groupId && n.status === "queued") : undefined;+ return node ? { waiting: deps.queuedReason(node, bot.id === from.id ? deps.shown : undefined), delegationId: node.id } : {};+ };for (const task of store.tasks(from.id)) {if (!deps.shown(task.threadId)) continue;+ const state = stateOf(from, task);rows.push({threadId: task.threadId, botId: from.id, botName: from.name, title: task.title,- state: stateOf(from, task), unread: task.unread === true, openedAt: task.openedBy?.at ?? task.createdAt,- delegationId: task.openedBy?.delegationId, own: true,+ state, unread: task.unread === true, openedAt: task.openedBy?.at ?? task.createdAt,+ delegationId: task.openedBy?.delegationId, own: true, ...queued(from, task, state),});}for (const peer of reachablePeers(store.bots, from)) {@@ -57,10 +67,11 @@ export function createInternalThreadRoutes(deps: {if (!opener || !deps.shown(task.threadId)) continue;const mine = opener.botId === from.id;if (!mine && !chiefTidies(from, task, store.bot(opener.botId), peer)) continue;+ const state = stateOf(peer, task);rows.push({threadId: task.threadId, botId: peer.id, botName: peer.name, title: task.title,- state: stateOf(peer, task), unread: task.unread === true, openedAt: opener.at,- delegationId: opener.delegationId, own: false,+ state, unread: task.unread === true, openedAt: opener.at,+ delegationId: opener.delegationId, own: false, ...queued(peer, task, state),...(mine ? {} : { openedBy: opener.name }),});}