Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
A shared computer goes back only when the person presses Done or Cancel on its last open sign-in card
Xiaolei Shi21ef898d081d
diff --git a/server/computer-control.test.ts b/server/computer-control.test.tsindex 9f29c5e0fb..606ac14f41 100644--- a/server/computer-control.test.ts+++ b/server/computer-control.test.ts@@ -99,6 +99,32 @@ describe("computer control", () => {expect(control.snapshot("b1")).toMatchObject({ helpReason: "first", help: { messageId: "card-1" } });});+ it("a plea whose card no longer waits is neither shown nor listed, and counts again once its card waits again", () => {+ const waiting = new Set(["card-1", "card-2"]);+ const control = new ComputerControl(() => {}, Date.now, (ref) => waiting.has(ref.messageId));+ control.requestHelp("b1", "first", ref("card-1"));+ control.requestHelp("b1", "second", ref("card-2"));+ waiting.delete("card-2");+ expect(control.snapshot("b1")).toMatchObject({ helpReason: "first", help: { messageId: "card-1" } });+ expect(control.pleas("b1").map((plea) => plea.messageId)).toEqual(["card-1"]);+ waiting.delete("card-1");+ expect(control.snapshot("b1")).toEqual({ held: false, helpReason: null, heldSinceMs: null });+ expect(control.pleas("b1")).toEqual([]);+ waiting.add("card-2");+ expect(control.snapshot("b1")).toMatchObject({ helpReason: "second", help: { messageId: "card-2" } });+ });++ it("lists every open plea on a key, oldest first", () => {+ const { control } = tracked();+ control.requestHelp("b1", "first", ref("card-1"));+ control.requestHelp("b1", "second", ref("card-2"));+ control.requestHelp("b2", "elsewhere", ref("card-3"));+ expect(control.pleas("b1").map((plea) => plea.messageId)).toEqual(["card-1", "card-2"]);+ control.settleHelp("card-1");+ expect(control.pleas("b1").map((plea) => plea.messageId)).toEqual(["card-2"]);+ expect(control.pleas("nobody")).toEqual([]);+ });+it("settles only the card it names, wherever it was raised", () => {const { control, changes } = tracked();control.requestHelp("b1", "first", ref("card-1"));diff --git a/server/computer-control.ts b/server/computer-control.tsindex e14c83fe8d..096cc677d2 100644--- a/server/computer-control.ts+++ b/server/computer-control.ts@@ -30,7 +30,7 @@ const MAX_REASON_CHARS = 280;interface Entry {heldSinceMs: number | null;- /** Open pleas, oldest first; the newest is the one shown. */+ /** Open pleas, oldest first; the newest whose card still waits is the one shown. */pleas: Array<{ reason: string; ref: ComputerHelpRef }>;/** Opaque workspace lease. It is deliberately absent from every snapshot. */controlLeaseId: string | null;@@ -40,19 +40,28 @@ export class ComputerControl {private entries = new Map<string, Entry>();private onChange: (botId: string, snapshot: ControlSnapshot) => void;private now: () => number;+ private waits: (ref: ComputerHelpRef) => boolean;constructor(onChange: (botId: string, snapshot: ControlSnapshot) => void = () => {},now: () => number = Date.now,+ /** Whether a plea's sign-in card still waits for the person. A plea whose card stopped, left the active branch or lost its+ * conversation is kept but neither shown nor counted, and counts again if its card waits again. */+ waits: (ref: ComputerHelpRef) => boolean = () => true,) {this.onChange = onChange;this.now = now;+ this.waits = waits;+ }++ private waiting(entry: Entry): Entry["pleas"] {+ return entry.pleas.filter((plea) => this.waits(plea.ref));}snapshot(botId: string): ControlSnapshot {const entry = this.entries.get(botId);if (!entry) return NO_CONTROL;- const plea = entry.pleas.at(-1);+ const plea = this.waiting(entry).at(-1);return {held: entry.heldSinceMs !== null,helpReason: plea?.reason ?? null,@@ -106,6 +115,12 @@ export class ComputerControl {return { snapshot: this.changed(botId), released: true };}+ /** Open pleas on this key whose cards still wait, oldest first. */+ pleas(botId: string): ComputerHelpRef[] {+ const entry = this.entries.get(botId);+ return entry ? this.waiting(entry).map((plea) => plea.ref) : [];+ }+/** Never grants anything by itself; the same card asking again replaces its own plea. */requestHelp(botId: string, reason: unknown, ref: ComputerHelpRef): ControlSnapshot {const text = typeof reason === "string" ? reason.trim().slice(0, MAX_REASON_CHARS) : "";diff --git a/server/host/sign-in-settle.test.ts b/server/host/sign-in-settle.test.tsindex b4ab51d0c7..0ecfcc1cad 100644--- a/server/host/sign-in-settle.test.ts+++ b/server/host/sign-in-settle.test.ts@@ -4,13 +4,14 @@ import type { HandoffView } from "../coordinator.ts";import type { BotRecord, Message } from "../store.ts";import { createSignInSettle, signInChatPrompt, type SignInSettleDeps } from "./sign-in-settle.ts";-function world(parked?: Partial<HandoffView>) {+function world(parked?: Partial<HandoffView>, pleas = new Map<string, string[]>()) {let rows: Message[] = [];let ids = 0;const add = (message: Partial<Message>) => { const full = { id: `m${++ids}`, at: 1_000 + ids, role: "bot", ...message } as Message; rows.push(full); return full; };const answered: Array<{ messageId: string; text: string }> = [];const released: string[] = [];const handedBack: string[] = [];+ const handedBackKeys: string[] = [];const node = parked ? { id: "as_1", threadId: "work", botId: "dachs", status: "waiting", createdAt: 1_000, ...parked } as HandoffView : undefined;const deps: SignInSettleDeps = {store: {@@ -23,12 +24,17 @@ function world(parked?: Partial<HandoffView>) {releaseCardNode: (_threadId, messageId) => { released.push(messageId); },resumableCards: () => [],parkedDirect: () => node,- settleHelp: () => [],+ settleHelp: (messageId) => [...pleas].filter(([, cards]) => cards.includes(messageId)).map(([key, cards]) => {+ pleas.set(key, cards.filter((id) => id !== messageId));+ return key;+ }),handBackBrowser: (_bot, threadId) => { handedBack.push(threadId); },- releaseComputer: () => {},- computerKey: () => "computer",+ releaseComputer: (key) => { handedBackKeys.push(key); },+ computerKey: (bot) => bot.id,+ sharedKey: (key) => key.startsWith("computer_"),+ pleas: (key) => (pleas.get(key) ?? []).map((messageId) => ({ botId: "dachs", threadId: "work", messageId, site: "notion.so", place: "vm" })),};- return { settle: createSignInSettle(deps), add, rows: () => rows, answered, released, handedBack };+ return { settle: createSignInSettle(deps), add, rows: () => rows, answered, released, handedBack, handedBackKeys };}const card = (site = "notion.so") => ({ kind: "signin" as const, text: `Sign in to ${site}`, signIn: { url: `https://${site}`, site, place: "browser" as const } });@@ -72,3 +78,31 @@ describe("a sign-in settled without the person pressing Done", () => {expect(w.rows().filter((row) => row.signIn).map((row) => [row.signIn!.site, row.signIn!.done ?? false])).toEqual([["notion.so", true], ["github.com", false]]);});});++describe("the computer a sign-in card lent the person", () => {+ type Path = "done" | "cancelled" | "answered in chat" | "answered elsewhere" | "verified";+ const handsBack = (path: Path, key: string, otherPlea: boolean): boolean => {+ const w = world(undefined, new Map([[key, ["m1", ...(otherPlea ? ["m2"] : [])]]]));+ w.add({ ...card(), signIn: { ...card().signIn, place: "vm" } });+ if (otherPlea) w.add({ ...card("figma.com"), signIn: { ...card("figma.com").signIn, place: "vm" } });+ if (path === "done" || path === "cancelled") w.settle.settle("dachs", "work", "m1", path);+ if (path === "answered in chat") w.settle.answerInChat("dachs", "work", "Bin angemeldet");+ if (path === "answered elsewhere") w.settle.answeredElsewhere({ id: "as_1", threadId: "work", botId: "dachs", cards: ["m1"] } as HandoffView);+ if (path === "verified") {+ w.add({ kind: "activity", tool: { name: "browser_open", ok: true, input: JSON.stringify({ url: "https://www.notion.so/workspace" }) } });+ w.settle.verified("dachs", "work", 0);+ }+ return w.handedBackKeys.includes(key);+ };++ it("goes back on every path when it is the bot's own, and a shared one only when the person settles its last plea", () => {+ const paths: Path[] = ["done", "cancelled", "answered in chat", "answered elsewhere", "verified"];+ expect(paths.map((path) => [path, handsBack(path, "dachs", false), handsBack(path, "dachs", true), handsBack(path, "computer_team", false), handsBack(path, "computer_team", true)])).toEqual([+ ["done", true, true, true, false],+ ["cancelled", true, true, true, false],+ ["answered in chat", true, true, false, false],+ ["answered elsewhere", true, true, false, false],+ ["verified", true, true, false, false],+ ]);+ });+});diff --git a/server/host/sign-in-settle.ts b/server/host/sign-in-settle.tsindex f640b6cd19..a0205d4cfa 100644--- a/server/host/sign-in-settle.ts+++ b/server/host/sign-in-settle.ts@@ -1,6 +1,7 @@import { userError } from "../user-errors.ts";import { savedLoginResumePrompt } from "../../shared/logins.ts";import { signInOutcome, signInResumePrompt, signInWaits } from "../../shared/sign-in-request.ts";+import type { ComputerHelpRef } from "../../shared/wire.ts";import type { HandoffView } from "../coordinator.ts";import type { BotRecord, Message, Store } from "../store.ts";import type { Surface } from "../surface.ts";@@ -18,6 +19,10 @@ export interface SignInSettleDeps {handBackBrowser(bot: BotRecord, threadId: string): void;releaseComputer(key: string): void;computerKey(bot: BotRecord): string;+ /** True when several bots drive the computer behind this control key, so no one bot's card may hand it back alone. */+ sharedKey(key: string): boolean;+ /** The sign-in cards on this control key that still wait for the person. */+ pleas(key: string): ComputerHelpRef[];}export type SignInSettled = { status: number; body: Record<string, unknown> };@@ -30,11 +35,14 @@ export function signInChatPrompt(site: string, line: string): string {export function createSignInSettle(deps: SignInSettleDeps) {const { store } = deps;- /** The person is through with the place the card lent them: its plea goes, and the browser or computer goes back to the bot. */- const handPlaceBack = (bot: BotRecord, threadId: string, messageId: string, place: Surface): void => {+ /** The person is through with the place the card lent them: its plea goes, and the browser or computer goes back to the+ * bot. A computer several bots share goes back only when the person pressed Done or Cancel and no other card waits for it. */+ const handPlaceBack = (bot: BotRecord, threadId: string, messageId: string, place: Surface, byPerson: boolean): void => {const pleaded = deps.settleHelp(messageId);if (place === "browser") deps.handBackBrowser(bot, threadId);- else for (const key of pleaded.length ? pleaded : [deps.computerKey(bot)]) deps.releaseComputer(key);+ else for (const key of pleaded.length ? pleaded : [deps.computerKey(bot)]) {+ if (!deps.sharedKey(key) || (byPerson && !deps.pleas(key).length)) deps.releaseComputer(key);+ }};const settle = (botId: string, threadId: string, messageId: string, outcome: "done" | "cancelled", saved?: { site: string }): SignInSettled => {@@ -49,7 +57,7 @@ export function createSignInSettle(deps: SignInSettleDeps) {return { status: 409, body: { ...userError(settled === "done" ? "serverError.signIn.alreadyDone" : "serverError.signIn.alreadyCancelled") } };}if (settled && card.resumed) return { status: 200, body: { [outcome]: true, resumed: true } };- if (!settled) handPlaceBack(bot, threadId, message.id, card.place);+ if (!settled) handPlaceBack(bot, threadId, message.id, card.place, true);const savedLogin = saved?.site ?? card.savedLogin;const resumed = deps.answerCardNode(threadId, message.id, savedLogin ? savedLoginResumePrompt(savedLogin) : signInResumePrompt(card.site, outcome));store.patchMessage(threadId, message.id, {@@ -64,7 +72,7 @@ export function createSignInSettle(deps: SignInSettleDeps) {for (const message of store.activePath(threadId)) {const card = message.signIn;if (message.kind !== "signin" || !card || card.stopped || !signInWaits(card) || (only && !only.includes(message.id))) continue;- handPlaceBack(bot, threadId, message.id, card.place);+ handPlaceBack(bot, threadId, message.id, card.place, false);store.patchMessage(threadId, message.id, { signIn: { ...card, answeredInChat: true, error: undefined } });settled.push({ id: message.id, site: card.site });}@@ -103,7 +111,7 @@ export function createSignInSettle(deps: SignInSettleDeps) {const site = card.site.toLowerCase();const used = path.slice(index + 1).some((row) => row.kind === "activity" && row.tool?.ok === true && (row.tool.input ?? "").toLowerCase().includes(site));if (!used) return;- handPlaceBack(bot, threadId, message.id, card.place);+ handPlaceBack(bot, threadId, message.id, card.place, false);store.patchMessage(threadId, message.id, { signIn: { ...card, done: true, resumed: true, error: undefined } });});};diff --git a/server/index.ts b/server/index.tsindex f8906fd387..7727d3c370 100644--- a/server/index.ts+++ b/server/index.ts@@ -44,7 +44,7 @@ import {} from "../shared/approval-mode.ts";import { createApprovalModeSupport } from "./harness-capabilities.ts";import { escapeAttribute } from "../src/lib/composer-attachments.ts";-import { isPendingSignInRequest, normalizeSignInSite, signInOutcome, signInResumePrompt } from "../shared/sign-in-request.ts";+import { isPendingSignInRequest, normalizeSignInSite, signInCardWaits, signInOutcome, signInResumePrompt } from "../shared/sign-in-request.ts";import { createRoomTurnLevels } from "./room-turn-level.ts";import { createSignInSettle } from "./host/sign-in-settle.ts"; import { createPersonLanguages, THIS_COMPUTER } from "./host/person-languages.ts"; import "./server-line-packs.ts"; import { conversationLanguage, serverLine, setConversationLanguage } from "./server-lines.ts";@@ -2468,7 +2468,7 @@ const computerControl = new ComputerControl((key, snapshot) => {}broadcast({ kind: "computer-control", botId, held: snapshot.held, helpReason: snapshot.helpReason, ...(snapshot.help ? { help: snapshot.help } : {}) });}-});+}, Date.now, (ref) => signInCardWaits(signInMessage(ref.botId, ref.threadId, ref.messageId)?.signIn));const controlLeaseIdSchema = z.string().min(16).max(120).regex(/^[A-Za-z0-9_-]+$/);function controlIntegration(botId: string,@@ -11580,7 +11580,7 @@ const signInSettle = createSignInSettle({store, signInMessage, answerCardNode, releaseCardNode, resumableCards,parkedDirect: (threadId) => coordinator.parkedDirect(threadId) ?? coordinator.active().find((n) => n.threadId === threadId && n.parentId && !n.groupId && n.status === "waiting" && n.cards?.length), settleHelp: (messageId) => computerControl.settleHelp(messageId),handBackBrowser: (bot, threadId) => browserLive.handBack(currentBrowserSession(bot.id, bot.browserProfile, teamHost.browserAudience(threadId))),- releaseComputer: (key) => computerControl.release(key), computerKey: botComputerControlKey,+ releaseComputer: (key) => computerControl.release(key), computerKey: botComputerControlKey, sharedKey: (key) => key.startsWith(teamComputerOwner("")), pleas: (key) => computerControl.pleas(key),});/** The open sign-in card the person is answering, and the page its bot's browser shows (null when none a login could fill). */diff --git a/shared/sign-in-request.test.ts b/shared/sign-in-request.test.tsnew file mode 100644index 0000000000..46bf83356e--- /dev/null+++ b/shared/sign-in-request.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from "vitest";++import { signInCardWaits } from "./sign-in-request.ts";++describe("a sign-in card that still waits for the person", () => {+ it.each([+ { row: "an open card", card: { site: "a.example" }, waits: true },+ { row: "a stopped card", card: { site: "a.example", stopped: true }, waits: false },+ { row: "a card the person finished", card: { site: "a.example", done: true }, waits: false },+ { row: "a card the person cancelled", card: { site: "a.example", cancelled: true }, waits: false },+ { row: "a card a newer one replaced", card: { site: "a.example", superseded: true }, waits: false },+ { row: "a card answered in the chat", card: { site: "a.example", answeredInChat: true }, waits: false },+ { row: "no card, as when its conversation or branch is gone", card: undefined, waits: false },+ ])("$row", ({ card, waits }) => {+ expect(signInCardWaits(card)).toBe(waits);+ });+});diff --git a/shared/sign-in-request.ts b/shared/sign-in-request.tsindex 56c11d3b15..f15641fc05 100644--- a/shared/sign-in-request.ts+++ b/shared/sign-in-request.ts@@ -59,6 +59,11 @@ export function signInWaits(card: { done?: unknown; cancelled?: unknown; supersereturn card.done !== true && card.cancelled !== true && card.superseded !== true && card.answeredInChat !== true;}+/** Whether a sign-in card, if there still is one, waits on the person: not stopped and still open. */+export function signInCardWaits(card: ({ stopped?: unknown } & Parameters<typeof signInWaits>[0]) | undefined): boolean {+ return card !== undefined && card.stopped !== true && signInWaits(card);+}+/** How a card ended, or null while it is open. */export function signInOutcome(state: { done?: unknown; cancelled?: unknown }): "done" | "cancelled" | null {if (state.done === true) return "done";