Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chats on their own computer: forks keep it, Simple mode shows it, tests for two computers at once (#7143)
Milind Sonia797ccd01c23
diff --git a/apps/docs/content/docs/computers/index.mdx b/apps/docs/content/docs/computers/index.mdxindex 07f9a5fb5a..1def4ef3c3 100644--- a/apps/docs/content/docs/computers/index.mdx+++ b/apps/docs/content/docs/computers/index.mdx@@ -19,7 +19,25 @@ To use your own Linux server as the desktop, start with [Your own VPS (BYO)](/do## Auto, local, and cloud selection-Computer selection is explicit per bot. Auto may reuse a ready, verified backend, but it does not silently provision every backend or turn on host control.+Each bot has a default computer, its **Works on** setting. Auto may reuse a ready, verified backend, but it does not silently provision every backend or turn on host control.++## A different computer for one chat++One chat can work somewhere other than its bot's default, so the same bot can work on this computer in one chat and on its Local VM or cloud desktop in another, at the same time. This choice is in **Advanced mode**: open the **+** under the message box and choose **Works on**.++- **Follow this bot's setting** (or **Auto**) is the default: the chat uses whatever the bot works on.+- Any other place is for this chat only. Places this bot can't use are listed but dimmed, with the reason.++While a chat has its own place, a small icon under the message box shows it; open it to change it or to follow the bot again. Other chats of the bot, other bots and the bot's own setting are unchanged.++In **Simple mode** there is no picker. A chat given its own place in Advanced mode keeps it, and shows a small icon of that place beside the **+** (not on a phone); the Screen panel says the chat has its own place and can switch it back to the bot's.++- The change applies from the chat's next message. It can't be changed while the bot is working in that chat.+- The choice is saved on the server with the chat, so every device you use shows the same one.+- A fork of the chat keeps its place. A new chat follows the bot.+- If the chosen place isn't available when the bot starts, the bot doesn't work anywhere else instead: the chat says why in one line, with the fix (such as connecting the cloud desktop service) or a button to follow the bot again. In Advanced mode, the chat's icon switches it back at any time.+- If the bot's **Works on** is **Off**, no chat of that bot gets a computer.+- The choice is a kind of place (this computer, Local VM, cloud desktop, Browser). Which cloud desktop or VPS server a bot uses is still set for the whole bot.## Preview and takeoverdiff --git a/server/fork-tasks.test.ts b/server/fork-tasks.test.tsindex d8e97c297e..b9175c7864 100644--- a/server/fork-tasks.test.ts+++ b/server/fork-tasks.test.ts@@ -118,6 +118,27 @@ it("preserves an explicit no-folder choice when forking a bot conversation", asyexpect(store.pinTaskCwd(bot.id, fork.threadId, join(home, "available-folder"))).toBeNull();});+it("carries a person's computer for the conversation into its fork, never an Auto pin", async () => {+ const store = await freshStore();+ const bot = store.createBot();+ const other = store.createTask(bot.id, "Sibling", false)!;+ const anchor = store.appendMessage(bot.threadId, { role: "user", kind: "text", text: "Work on the private desktop" });+ store.patchTask(bot.id, bot.threadId, { surface: "vm", surfaceSource: "user" });+ const chosen = store.forkTask(bot.id, bot.threadId, anchor.id)!;+ expect(store.taskByThread(bot.id, chosen.threadId)).toMatchObject({ surface: "vm", surfaceSource: "user" });+ expect(store.taskByThread(bot.id, other.threadId)?.surface).toBeUndefined();+ expect(store.bot(bot.id)?.computer).toBeUndefined();++ store.patchTask(bot.id, bot.threadId, { surface: "local", surfaceSource: undefined });+ expect(store.taskByThread(bot.id, store.forkTask(bot.id, bot.threadId, anchor.id)!.threadId)?.surface).toBe("local");++ store.patchTask(bot.id, bot.threadId, { surface: "cloud", surfaceSource: "auto" });+ const followsBot = store.taskByThread(bot.id, store.forkTask(bot.id, bot.threadId, anchor.id)!.threadId)!;+ expect(followsBot.surface).toBeUndefined();+ expect(followsBot.surfaceSource).toBeUndefined();+ expect(store.createTask(bot.id, "New", false)?.surface).toBeUndefined();+});+it("removes copied history when registering the fork fails", async () => {const store = await freshStore();const bot = store.createBot();diff --git a/server/store-forks.ts b/server/store-forks.tsindex 60c92b508e..89e3d5a4d1 100644--- a/server/store-forks.ts+++ b/server/store-forks.ts@@ -57,6 +57,10 @@ export function createBotFork(bot: BotRecord, source: TaskRecord, path: Message[task.outside = source.outside;task.botApi = source.botApi;if (source.botApiAsOwner) task.botApiAsOwner = true;+ if (source.surface && source.surfaceSource !== "auto") {+ task.surface = source.surface;+ if (source.surfaceSource) task.surfaceSource = source.surfaceSource;+ }task.origin = { threadId: source.threadId, messageId };task.lastReadMessageId = messageId;registerImportedFork(task, history, messageId, register);diff --git a/server/surface-pins.e2e.test.ts b/server/surface-pins.e2e.test.tsindex 10dd6143b3..1f4c716dd0 100644--- a/server/surface-pins.e2e.test.ts+++ b/server/surface-pins.e2e.test.ts@@ -392,6 +392,111 @@ describe("surface pin provenance against the real server", () => {await stop();});+ // Linux needs a separately validated native runtime descriptor for this computer (see the test above).+ it.skipIf(process.platform === "linux")("runs two threads of one bot on two computers at once, and keeps each choice to its own thread", async () => {+ // The app's driver record is there from the server's start, so this computer is ready before the first turn.+ mkdirSync(dirname(cuaDescriptor), { recursive: true });+ writeFileSync(cuaDescriptor, JSON.stringify({+ mode: "embedded", status: "ready", socketPath: join(home, "cua.sock"),+ mcpCommand: "/fixture/cua-driver", mcpArgs: ["mcp"], mcpEnv: {},+ }), { mode: 0o600 });+ await start();+ const { bot } = await apiOk("POST", "/api/bots", { name: "Two Places Bot" });+ const { bot: neighbour } = await apiOk("POST", "/api/bots", { name: "Neighbour Bot" });+ for (const id of [bot.id, neighbour.id]) await apiOk("PATCH", `/api/bots/${id}`, { computer: "vm" });+ const [mine, sibling] = (await Promise.all([+ apiOk("POST", `/api/bots/${bot.id}/tasks`, {}),+ apiOk("POST", `/api/bots/${bot.id}/tasks`, {}),+ ])).map(({ task }) => task);+ const { task: theirs } = await apiOk("POST", `/api/bots/${neighbour.id}/tasks`, {});+ await apiOk("PATCH", `/api/bots/${bot.id}/tasks/${mine.threadId}`, { surface: "local" });+ expect((await apiOk("GET", `/api/bots/${bot.id}/computer?threadId=${mine.threadId}`)).surface).toBe("local");+ expect((await apiOk("GET", `/api/bots/${bot.id}/computer?threadId=${sibling.threadId}`)).surface).toBe("vm");+ const onVm = (sent: any) => mountedComputer(sent)?.args.some((arg: string) => arg.includes("container-mcp")) === true;+ const turnIn = async (botId: string, threadId: string, text: string) => {+ rmSync(dumpFile, { force: true });+ await apiOk("POST", `/api/bots/${botId}/messages`, { text, threadId });+ const sent = await until(dump, (candidate) => JSON.stringify(candidate.prompt).includes(text));+ await busy(botId, threadId);+ return sent;+ };+ try {+ resetTurn();+ const here = await turnIn(bot.id, mine.threadId, "Pinned thread: work on this computer.");+ expect(here.systemPrompt).toContain("You can act on the user's computer");+ expect(mountedComputer(here).env.OMB_CUA_COMMAND).toBe("/fixture/cua-driver");+ expect(onVm(here)).toBe(false);++ const there = await turnIn(bot.id, sibling.threadId, "Sibling thread: work where the bot works.");+ expect(onVm(there)).toBe(true);+ expect(mountedComputer(there).env.OMB_CUA_COMMAND).toBeUndefined();+ expect(there.systemPrompt).not.toContain("You can act on the user's computer");+ // Both turns of the one bot are running at once, each on its own computer.+ expect((await threadState(bot.id, mine.threadId)).busy).toBe(true);+ expect((await threadState(bot.id, sibling.threadId)).busy).toBe(true);+ writeFileSync(finishFile, "finish");+ await idle(bot.id, mine.threadId);+ await idle(bot.id, sibling.threadId);++ rmSync(finishFile, { force: true });+ const neighbours = await turnIn(neighbour.id, theirs.threadId, "Neighbour: work where you work.");+ expect(onVm(neighbours)).toBe(true);+ expect(mountedComputer(neighbours).env.OMB_CUA_COMMAND).toBeUndefined();+ writeFileSync(finishFile, "finish");+ await idle(neighbour.id, theirs.threadId);+ } finally {+ rmSync(cuaDescriptor, { force: true });+ }+ expect(savedTask(bot.id, mine.threadId)).toMatchObject({ surface: "local", surfaceSource: "user" });+ expect(savedTask(bot.id, sibling.threadId)).not.toHaveProperty("surface");+ expect(savedTask(neighbour.id, theirs.threadId)).not.toHaveProperty("surface");+ expect((readRegistry(data).bots as any[]).find((saved: any) => saved.id === bot.id).computer).toBe("vm");++ const { messages } = await apiOk("GET", `/api/threads/${mine.threadId}/messages?limit=30`);+ const reply = messages.findLast((message: any) => message.role === "bot" && message.kind === "text");+ const { task: forked } = await apiOk("POST", `/api/bots/${bot.id}/tasks/${mine.threadId}/forks`, { messageId: reply.id });+ expect(savedTask(bot.id, forked.threadId)).toMatchObject({ surface: "local", surfaceSource: "user" });+ const { task: fresh } = await apiOk("POST", `/api/bots/${bot.id}/tasks`, {});+ expect(savedTask(bot.id, fresh.threadId)).not.toHaveProperty("surface");++ await apiOk("PATCH", `/api/bots/${bot.id}/tasks/${mine.threadId}`, { surface: null });+ expect((await apiOk("GET", `/api/bots/${bot.id}/computer?threadId=${mine.threadId}`)).surface).toBe("vm");+ for (const id of [bot.id, neighbour.id]) await apiOk("DELETE", `/api/bots/${id}`);+ await stop();+ }, 60_000);++ it.skipIf(process.platform === "linux")("never puts a thread chosen for the Local VM on this computer when the VM can't be had", async () => {+ mkdirSync(dirname(cuaDescriptor), { recursive: true });+ writeFileSync(cuaDescriptor, JSON.stringify({+ mode: "embedded", status: "ready", socketPath: join(home, "cua.sock"),+ mcpCommand: "/fixture/cua-driver", mcpArgs: ["mcp"], mcpEnv: {},+ }), { mode: 0o600 });+ await start();+ try {+ const { bot } = await apiOk("POST", "/api/bots", { name: "Isolated Bot" });+ await apiOk("PATCH", `/api/bots/${bot.id}`, { computer: "local" });+ const { task } = await apiOk("POST", `/api/bots/${bot.id}/tasks`, {});+ await apiOk("PATCH", `/api/bots/${bot.id}/tasks/${task.threadId}`, { surface: "vm" });+ resetTurn();+ vmState({ failed: true });+ await apiOk("POST", `/api/bots/${bot.id}/messages`, { text: "Use the private desktop.", threadId: task.threadId });+ const lastRow = async () => {+ const { messages } = await apiOk("GET", `/api/threads/${task.threadId}/messages?limit=30`);+ return String(messages.filter((message: any) => message.kind !== "digest").at(-1)?.tool?.name ?? "");+ };+ await until(() => lastRow(), (row) => row.startsWith("error:"));+ await idle(bot.id, task.threadId);+ // Refused before any engine started: no tools at all, so none on this computer.+ expect(existsSync(dumpFile)).toBe(false);+ expect(await lastRow()).toMatch(/Clear this conversation's place/);+ expect(savedTask(bot.id, task.threadId)).toMatchObject({ surface: "vm", surfaceSource: "user" });+ await apiOk("DELETE", `/api/bots/${bot.id}`);+ } finally {+ rmSync(cuaDescriptor, { force: true });+ }+ await stop();+ }, 60_000);+it("clears a select_computer pin to a cloud computer that fails, and keeps a person's pin", async () => {await start();const { bot } = await apiOk("POST", "/api/bots", { name: "Failed place bot" });diff --git a/server/surface.test.ts b/server/surface.test.tsindex 98036e07d8..45d9b00e55 100644--- a/server/surface.test.ts+++ b/server/surface.test.ts@@ -661,3 +661,27 @@ describe("a vm_exec command that names this computer's own paths", () => {expect(failedOnHostPath("ls /Users/ana/Desktop", failed, "linux")).toBe(false);});});++describe("a thread's own computer", () => {+ const turn = (worksOn: "cloud" | "vm" | "local" | "browser" | "off" | undefined, task?: { surface?: "cloud" | "vm" | "local" | "browser"; surfaceSource?: "user" | "auto" }) =>+ resolveSurface({ destination: worksOn, pinnedSurface: chosenPin(task), browserOn: true });++ it("runs on the thread's choice over the bot's, and on the bot's once cleared", () => {+ expect(turn("cloud", { surface: "vm", surfaceSource: "user" })).toMatchObject({ computer: "vm", pinned: "vm" });+ expect(turn("vm", { surface: "local", surfaceSource: "user" })).toMatchObject({ computer: "local", pinned: "local" });+ expect(turn(undefined, { surface: "cloud", surfaceSource: "user" })).toMatchObject({ computer: "cloud", pinned: "cloud" });+ expect(turn("cloud", {})).toMatchObject({ computer: "cloud", pinned: null });+ expect(turn(undefined, {})).toMatchObject({ computer: undefined, pinned: null });+ });++ it("takes an Auto pin for no choice of the person's, and lets the bot's Off beat any choice", () => {+ expect(turn("vm", { surface: "local", surfaceSource: "auto" })).toMatchObject({ computer: "vm", pinned: null });+ expect(turn("off", { surface: "vm", surfaceSource: "user" })).toMatchObject({ computer: "off", browser: false, pinned: null });+ });++ it("does not swap in another place when the thread's choice can't be had", () => {+ const plan = resolveSurface({ destination: "local", pinnedSurface: "browser", browserOn: false });+ expect(plan).toMatchObject({ computer: "off", browser: false, pinned: "browser" });+ expect(plan.note).toMatch(/No computer is mounted instead/);+ });+});diff --git a/src/components/Composer.phone.test.ts b/src/components/Composer.phone.test.tsindex db2b1e958a..af74f6666c 100644--- a/src/components/Composer.phone.test.ts+++ b/src/components/Composer.phone.test.ts@@ -97,6 +97,8 @@ describe("the phone composer", () => {expect(plus()).not.toBeNull();expect(fixture.call).toMatchObject({ placement: "composer", inverse: true });expect(fixture.call?.fill).toBeUndefined();+ openPlus();+ expect([...menu()!.querySelectorAll("[data-menu-key]")].map((row) => row.getAttribute("data-menu-key"))).not.toContain("place");});it("moves Advanced mode's row of buttons into the +", () => {diff --git a/src/components/Composer.simple.test.ts b/src/components/Composer.simple.test.tsindex 4a840bbdc8..9eec28c5c8 100644--- a/src/components/Composer.simple.test.ts+++ b/src/components/Composer.simple.test.ts@@ -135,6 +135,31 @@ describe("the Simple composer in a bot chat", () => {expect(menu()!.className.split(" ")).toEqual(expect.arrayContaining(["popover-surface", "rounded-[12px]", "w-max", "min-w-[200px]", "max-w-[280px]"]));});+ it("has no place picker, and only marks a conversation an Advanced choice put somewhere other than its bot", () => {+ const onVm = { ...bot, computer: "vm" as const };+ const chat = (surface?: "cloud" | "vm", surfaceAuto?: true) => ({ ...onVm, tasks: [{ threadId: bot.threadId, title: "Chat", createdAt: 1, surface, surfaceAuto }] });+ render({ bot: chat() });+ expect(container.querySelector('[data-testid="place-chip"]')).toBeNull();+ expect(container.querySelector('[data-testid="place-mark"]')).toBeNull();+ openPlus();+ expect([...menu()!.querySelectorAll("[data-menu-key]")].map((row) => row.getAttribute("data-menu-key"))).toEqual(["attach", "goal", "teach"]);+ expect(document.body.textContent).not.toContain("Works on");++ for (const [shown, marked] of [[chat("cloud"), true], [chat("vm"), false], [chat("cloud", true), false]] as const) {+ flushSync(() => root.unmount());+ root = createRoot(container);+ render({ bot: shown });+ const mark = container.querySelector<HTMLElement>('[data-testid="place-mark"]');+ expect(Boolean(mark), JSON.stringify(shown.tasks)).toBe(marked);+ expect(container.querySelector('[data-testid="place-chip"]')).toBeNull();+ if (!mark) continue;+ expect(mark.getAttribute("aria-label")).toBe("Where this conversation works: Cloud desktop");+ expect(mark.closest("button")).toBeNull();+ expect(mark.querySelector("button, [role=menu], [tabindex]")).toBeNull();+ }+ expect(fixture.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: "updateTask" }));+ });+it("starts a /learn draft from Teach a task, ahead of anything already typed", () => {restoreComposerDraft(`bot:${bot.id}:${bot.threadId}`, { text: "how I file expenses", attachments: [] });render({ bot });diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex e89c4eae91..7fff41cca6 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -72,6 +72,8 @@ import { PendingApprovalActions, PendingApprovalPanel, pendingApprovals } from "import { CallButton } from "./CallView";import { GroupCallButton } from "./GroupCallView";import { ApprovalChip, ComposerPlusMenu, GoalToggle } from "./ComposerPlusMenu";+import { PlaceMark } from "./PlaceChip";+import type { Place } from "@/lib/place";import { PhonePlus } from "./PhonePlus";import { useThreadApproval } from "./thread-approval";import { useTallPill } from "./composer-wrap";@@ -484,6 +486,8 @@ export function Composer({const fileInput = useRef<HTMLInputElement>(null);const [attachmentNotice, setAttachmentNotice] = useState<string | null>(null);const modeBot = group ? undefined : bot;+ const pinPlace = (surface: Place | null) => modeBot && dispatch({ type: "updateTask", botId: modeBot.id, threadId: modeBot.threadId, patch: { surface } });+ const place = modeBot && !remoteClient && advanced ? { bot: modeBot, task: composerTask, disabled: Boolean(modeBot.busy), onPin: pinPlace } : undefined;const { choice: approvalChoice, dialogs: approvalDialogs } = useThreadApproval(modeBot);const uploadImage = useCallback((file: File) => uploadDraftImage(draftId, file), [draftId]);const pickFiles = async (picked: FileList | readonly File[] | null) => {@@ -789,12 +793,7 @@ export function Composer({teach={canLearn ? teachTask : undefined}approval={approvalChoice && modeBot && { name: modeBot.name, choice: approvalChoice }}callBotId={bot && !group ? bot.id : undefined}- place={modeBot && !remoteClient && advanced ? {- bot: modeBot,- task: composerTask,- disabled: Boolean(modeBot.busy),- onPin: (surface) => dispatch({ type: "updateTask", botId: modeBot.id, threadId: modeBot.threadId, patch: { surface } }),- } : undefined}+ place={place}/></div>)}@@ -818,6 +817,7 @@ export function Composer({{/* Simple mode shows a mode's chip only while it is on, so a choice made in the + menu or the bot panel stays in view. */}{goal?.on && <GoalToggle {...goal} />}{approvalChoice && profile && bot && approvalModeFor(bot) !== approvalModeFor(profile) && <ApprovalChip choice={approvalChoice} />}+ {modeBot && <PlaceMark bot={modeBot} task={composerTask} />}</div>)}<MentionTextarea@@ -929,7 +929,7 @@ export function Composer({<ComposerAdvancedTools profile={profile} bot={modeBot} task={composerTask} locked={locked} remoteClient={remoteClient}onAttach={() => fileInput.current?.click()} goal={goal} teach={canLearn ? teachTask : undefined} approval={approvalChoice}callBotId={callShown && bot && !group ? bot.id : undefined}- onPin={(surface) => modeBot && dispatch({ type: "updateTask", botId: modeBot.id, threadId: modeBot.threadId, patch: { surface } })} />+ onPin={pinPlace} />)}<div data-composer-actions className={cn("flex items-center", simpleDock ? "gap-2" : "gap-1", stacked && "ms-auto")}>{(simpleDock ? stoppable : busy && mayStop) && !locked && (diff --git a/src/components/PlaceChip.tsx b/src/components/PlaceChip.tsxindex 90d67f1881..82ecf63731 100644--- a/src/components/PlaceChip.tsx+++ b/src/components/PlaceChip.tsx@@ -96,6 +96,19 @@ const DESCRIPTION: Record<Place, "computer.dest.cloudDesc" | "computer.dest.vmDecloud: "computer.dest.cloudDesc", vm: "computer.dest.vmDesc", local: "computer.dest.localDesc", browser: "computer.dest.browserDesc",};+/** Simple mode's read-only mark for a conversation that works somewhere other than its bot: the place is chosen in+ * Advanced mode, so here it only shows, beside the +. Nothing when the conversation follows its bot. */+export function PlaceMark({ bot, task }: { bot: Pick<Bot, "computer">; task?: Pick<Task, "surface" | "surfaceAuto"> | null }) {+ const pin = personPin(task);+ if (!pin || bot.computer === "off" || pin === bot.computer) return null;+ const label = t("place.chipAria", { place: t(placeLabelKey(pin)) });+ return (+ <span role="img" aria-label={label} title={label} data-testid="place-mark" className="flex size-7 shrink-0 items-center justify-center text-accent">+ <PlaceIcon place={pin} size={16} className="opacity-80" aria-hidden="true" />+ </span>+ );+}+export function PlaceChip({ bot, task, live, disabled = false, onPin }: {bot: Bot;task?: Pick<Task, "surface" | "surfaceAuto"> | null;