Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a bot's main thread where it is until the person moves it
luishron123cab04170d86b
diff --git a/docs/desktop-chat-links.md b/docs/desktop-chat-links.mdindex e9f607c330..33cd0326a7 100644--- a/docs/desktop-chat-links.md+++ b/docs/desktop-chat-links.md@@ -26,7 +26,7 @@ openmausbot://bot/<bot-id>that bot's, nothing opens.- **`openmausbot://bot/<bot-id>`** — the bot's current conversation, exactlyas clicking the bot in the sidebar opens it: with threads hidden, its main- thread, the conversation the person last wrote in. Handy for a team map+ thread, the one the person chose or else its oldest open conversation. Handy for a team mapwhose Chat button only knows the bot's id. A room's id works here too.## What opening one doesdiff --git a/docs/team-slack.md b/docs/team-slack.mdindex d47f68a9eb..f76590d720 100644--- a/docs/team-slack.md+++ b/docs/team-slack.md@@ -76,8 +76,8 @@ ones on this page. What differs, because there is one person and no team:direct message. `{ default: true }` is the Cloud's MausBot, else the first bot.- **Where it came from.** The titles are the same. A conversation a channel's message opened is still never the chatits bot opens to; with no sharing to record it in, its id is kept in `team-slack-messages.json` (`channels`), after- its messages are dropped. A direct message's conversation is as any the owner opens, so the one they last wrote in- is the chat the bot opens to.+ its messages are dropped. A direct message's conversation is as any the owner opens, so writing in it does+ not move the chat the bot opens to.- **Nobody leaves.** Nothing is forgotten for a person; the record keeps its week, month and 2,000.## The routesdiff --git a/docs/verification/routines.md b/docs/verification/routines.mdindex 7b7c5a2705..53dbe711ed 100644--- a/docs/verification/routines.md+++ b/docs/verification/routines.md@@ -90,7 +90,7 @@ The final startup JSON includes the server `url`, `previewUrl`, `pepperId`,the card must become settled and exactly one matching routine must appear.Reloading must preserve both the routine and the card's settled state.Open that routine and run it. Its report lands in Pepper's main thread (the- open conversation the person last wrote in, here the source chat), not a new+ one set as main, else Pepper's oldest open conversation), not a new"· Results" thread, as one Pepper message captioned with the routine's name,and the caption's **See run** leads to the isolated execution thread. See[automation reports](automation-reports.md) for quiet runs, questions and@@ -142,12 +142,11 @@ The final startup JSON includes the server `url`, `previewUrl`, `pepperId`,Every routine reports into its bot's main thread unless the user chooses anotherdestination, whether it was made in a chat, the editor or the API, and whether a-teammate (such as a Chief) asked for it. The main thread is the open-conversation a person last wrote in (until anyone has, the selected one, then-the oldest); a bot with hidden threads opens there too. Conversations from-before the server kept that take it, once on upgrade, from the newest line a-person sent there from the app. Each run looks it up-again, so the routine saves nothing and its results follow the person. A routine+teammate (such as a Chief) asked for it. The main thread is the one the person set+as main while it is open, else the oldest open conversation a person started,+else the oldest open one; a bot with hidden threads opens there too. Writing in+another conversation never moves it. Each run looks it up+again, so the routine saves nothing and its results follow the main thread. A routinestill pointing at an automatic "<name> · Results" thread from an older versionmoves to the main thread on its next run; that thread and its reports stay. Theoldest thread that v0.1.98 to v0.1.107 saved on routines as if it were chosen isdiff --git a/docs/verification/threads.md b/docs/verification/threads.mdindex 4a7f2911ac..4116eb91e9 100644--- a/docs/verification/threads.md+++ b/docs/verification/threads.md@@ -65,7 +65,8 @@ switching and Stop can be exercised without a real provider or account.The header stays uncluttered; **Other activity** appears below it only whenthere is sibling activity, including when the sidebar is closed. Open asibling from its activity entry, then click the bot's row: it returns to- the conversation you last wrote in (the bot's main thread). Open another+ the bot's main thread (the one you set as main, else its oldest open+ conversation), not to the conversation you last wrote in. Open anotherbot, let a reply land in the sibling it was left on, and check that thesibling has its own activity entry under that bot. Follow a notification,a thread chip or a search hit to a third thread of that bot: the siblingdiff --git a/server/cloud-lending-memory.e2e.test.ts b/server/cloud-lending-memory.e2e.test.tsindex a6d28638b1..79205ccde1 100644--- a/server/cloud-lending-memory.e2e.test.ts+++ b/server/cloud-lending-memory.e2e.test.ts@@ -849,14 +849,15 @@ it("the results conversation of a routine a guest left behind never reaches theexpect(JSON.stringify(await ownerTools("list_threads", {}))).toContain(bot.threadId);}, 60_000);-it("an owner's routine reports into the conversation the owner last wrote in, never one a guest left behind", async () => {+it("an owner's routine reports into the owner's oldest open conversation, never an older one a guest left behind", async () => {const bot = await newBot("Main thread", "done");- const mine = await newThread(bot);- await completedTurn(() => say(owner, bot, "Morning.", mine));- await settled(mine);const left = await newThread(bot, owner, "Guest's");await completedTurn(() => say(owner, bot, "Evening.", left));await settled(left);+ const mine = await newThread(bot);+ await completedTurn(() => say(owner, bot, "Morning.", mine));+ await settled(mine);+ expect((await api("PATCH", `/api/bots/${bot.id}/tasks/${bot.threadId}`, { token: owner, body: { archivedAt: Date.now() } })).status).toBe(200);await leftBehind({ threadIds: [left] });const created = await api("POST", "/api/routines", { token: owner, body: {name: "OWNER-REPORT", prompt: "Summarize my day.", botId: bot.id, enabled: false,diff --git a/server/cloud-personal-slack.e2e.test.ts b/server/cloud-personal-slack.e2e.test.tsindex 972ff3218a..3c0cd94756 100644--- a/server/cloud-personal-slack.e2e.test.ts+++ b/server/cloud-personal-slack.e2e.test.ts@@ -207,8 +207,8 @@ it("a direct message is an ordinary conversation too, with the owner's MausBot bexpect(named.status, JSON.stringify(named.body)).toBe(202);expect(named.body.bot).toEqual({ id: scout.id, name: "Scout" });await finished(named.id);- // A direct message's conversation is as any the owner opens: the one they last wrote in is the chat the bot opens to.- expect((await botOf(scout.id)).mainThreadId).toBe(named.body.conversationId);+ // A direct message's conversation is as any the owner opens: writing in it does not move the chat the bot opens to.+ expect((await botOf(scout.id)).mainThreadId).toBe(scout.threadId);// There is one person and no audience to tell apart: a thread continues by its id whichever audience is named.const more = await slack(ownerSlack, { audience: "team", conversationId: channelThread, text: "And the week after?" });@@ -229,7 +229,7 @@ it("a direct message is an ordinary conversation too, with the owner's MausBot bexpect(missing.status).toBe(404);expect(missing.body).toEqual({ error: "No such bot.", code: "no_such_bot" });// The channel's conversation, though written in last, is still not that chat.- expect((await botOf(scout.id)).mainThreadId).toBe(named.body.conversationId);+ expect((await botOf(scout.id)).mainThreadId).toBe(scout.threadId);}, hostTimeout(180_000));it("a line written while the bot works waits in the queue and runs after, as its own turn", async () => {diff --git a/server/index.ts b/server/index.tsindex 1157980893..3c4809a626 100644--- a/server/index.ts+++ b/server/index.ts@@ -8544,7 +8544,7 @@ function routineSourceOwner(run: Pick<RoutineRun, "botId" | "sourceThreadId" | "function mainThreadTasks(botId: string) { const tasks = store.tasks(botId), own = store.bot(botId)?.defaultBot?.person ? [...tasks].sort((a, b) => a.createdAt - b.createdAt)[0]?.threadId : undefined; return CLOUD_TEAM ? tasks.filter((task) => (teamHost.audienceOf(task.threadId) === "team" && !conversationShares.fromSlack(task.threadId)) || task.threadId === own) : CLOUD_HOME ? tasks.filter((task) => !cloudGuestOpened(task.threadId) && !personalSlackMessages?.channelThread(task.threadId)) : tasks; }function botMainThread(botId: string): string | undefined {- return mainThread(mainThreadTasks(botId), store.bot(botId)?.threadId, store.bot(botId)?.mainThreadChoice);+ return mainThread(mainThreadTasks(botId), store.bot(botId)?.mainThreadChoice);} const threadScoped = createThreadScope({ tasks: mainThreadTasks, chosen: (botId) => store.bot(botId)?.mainThreadChoice, room: (threadId) => Boolean(store.groupByThread(threadId)), routineRun: (threadId) => Boolean(routines?.runForThread(threadId)), team: Boolean(CLOUD_TEAM) }), threadSaveLines = createThreadSaveLines({ bus, append: (threadId, tool) => void store.appendMessage(threadId, { role: "bot", kind: "activity", tool }) });function routineSourceThread(run: RoutineRun): string | null {diff --git a/server/long-running-chief.e2e.test.ts b/server/long-running-chief.e2e.test.tsindex c440794bbf..b5d5a3ace7 100644--- a/server/long-running-chief.e2e.test.ts+++ b/server/long-running-chief.e2e.test.ts@@ -263,7 +263,7 @@ it("carries a consult-and-implement job over several teammate turns, through a sexpect(f.prompt(f.turn(key))).not.toMatch(DISTRUST);}const mainThreads = Object.fromEntries(((await f.api("GET", "/api/bots?messages=0")).body.bots as any[]).map((bot) => [bot.id, bot.mainThreadId]));- expect(mainThreads).toMatchObject({ [f.clive.id]: job, [f.mira.id]: f.mira.activeTaskId, [f.eli.id]: f.eli.activeTaskId });+ expect(mainThreads).toMatchObject({ [f.clive.id]: f.clive.activeTaskId, [f.mira.id]: f.mira.activeTaskId, [f.eli.id]: f.eli.activeTaskId });}), hostTimeout(120_000));it("tells the Chief what happened to each approval: allowed or denied, and parks a hand-off on the person when nobody answered", () => chiefJob(async (f) => {diff --git a/server/main-thread.test.ts b/server/main-thread.test.tsindex 6f13c2cff0..70fb29dcca 100644--- a/server/main-thread.test.ts+++ b/server/main-thread.test.ts@@ -7,38 +7,40 @@ const later = { threadId: "later", createdAt: 2 };const latest = { threadId: "latest", createdAt: 3 };describe("a bot's main thread", () => {- it("is the open thread a person last wrote in, wherever the selection is", () => {+ it("is the oldest open conversation, wherever a person last wrote and whichever is selected", () => {const tasks = [{ ...latest, askedAt: 10 }, { ...later, askedAt: 30 }, { ...first, askedAt: 20 }];- expect(mainThread(tasks, "first")).toBe("later");- expect(mainThread(tasks)).toBe("later");+ expect(mainThread(tasks)).toBe("first");+ const newest = { threadId: "newest", createdAt: 4, askedAt: 40 };+ expect(mainThread([...tasks, newest])).toBe("first");});- it("is the thread the person chose while it is open, else the usual pick", () => {+ it("is the thread the person chose while it is open, else the oldest open one", () => {const tasks = [{ ...latest, askedAt: 10 }, { ...later, askedAt: 30 }, { ...first, askedAt: 20 }];- expect(mainThread(tasks, "later", "first")).toBe("first");- expect(mainThread([{ ...latest, archivedAt: 5 }, { ...later, askedAt: 30 }], "later", "latest")).toBe("later");- expect(mainThread([{ ...latest, routineRunId: "run" }, later], "later", "latest")).toBe("later");- expect(mainThread(tasks, "later", "deleted")).toBe("later");+ expect(mainThread(tasks, "later")).toBe("later");+ expect(mainThread([{ ...latest, archivedAt: 5 }, later, first], "latest")).toBe("first");+ expect(mainThread([{ ...latest, routineRunId: "run" }, later, first], "latest")).toBe("first");+ expect(mainThread(tasks, "deleted")).toBe("first");});- it("is never a routine run or an archived thread, however recently written in", () => {- const tasks = [- { ...latest, askedAt: 50, routineRunId: "run" },- { ...later, askedAt: 40, archivedAt: 41 },- { ...first, askedAt: 10 },- ];- expect(mainThread(tasks, "later")).toBe("first");+ it("moves to the next oldest open conversation only when it is archived or deleted", () => {+ expect(mainThread([latest, later, { ...first, archivedAt: 9 }])).toBe("later");+ expect(mainThread([latest, later])).toBe("later");});- it("is the selected thread before anyone writes, while that is an open conversation", () => {- expect(mainThread([latest, later, first], "later")).toBe("later");- expect(mainThread([latest, { ...later, archivedAt: 5 }, first], "later")).toBe("first");- expect(mainThread([{ ...latest, routineRunId: "run" }, later, first], "latest")).toBe("first");- expect(mainThread([latest, later, first], "deleted")).toBe("first");+ it("is never by default a thread a bot opened, while the person has an open one of their own", () => {+ const handed = { ...first, openedBy: { botId: "teammate", name: "Teammate" } };+ expect(mainThread([latest, later, handed])).toBe("later");+ expect(mainThread([latest, { ...later, archivedAt: 5 }, handed])).toBe("latest");+ expect(mainThread([{ ...latest, routineRunId: "run" }, { ...later, archivedAt: 5 }, handed])).toBe("first");+ expect(mainThread([latest, later, handed], "first")).toBe("first");+ });++ it("is never a routine run or an archived thread, however old", () => {+ expect(mainThread([latest, { ...later, archivedAt: 41 }, { ...first, routineRunId: "run" }])).toBe("latest");});it("is the oldest archived thread when every thread is archived, and nothing without threads", () => {- expect(mainThread([{ ...latest, archivedAt: 9, askedAt: 9 }, { ...later, archivedAt: 8 }], "latest")).toBe("later");+ expect(mainThread([{ ...latest, archivedAt: 9 }, { ...later, archivedAt: 8 }])).toBe("later");expect(mainThread([{ ...first, routineRunId: "run" }])).toBeUndefined();expect(mainThread([])).toBeUndefined();});diff --git a/server/main-thread.ts b/server/main-thread.tsindex 16b7e54886..733c9032da 100644--- a/server/main-thread.ts+++ b/server/main-thread.ts@@ -1,9 +1,10 @@interface MainThreadCandidate {threadId: string;createdAt: number;- askedAt?: number;archivedAt?: number;routineRunId?: string;+ /** Set when a bot opened the thread: a hand-off, a burst lane, its own side job. */+ openedBy?: object;}export function oldestThread(tasks: readonly MainThreadCandidate[]): string | undefined {@@ -19,15 +20,13 @@ export function wasOldestThread(tasks: readonly MainThreadCandidate[], threadId:return saved !== undefined && !tasks.some((task) => !task.routineRunId && task.archivedAt === undefined && task.createdAt < saved.createdAt);}-/** The thread a bot opens to when threads are hidden: the one the person chose (while it is open), else the open thread- * they last wrote in, else the selected one, else the oldest. */-export function mainThread(tasks: readonly MainThreadCandidate[], selectedId?: string, chosenId?: string): string | undefined {- const open = tasks.filter((task) => !task.routineRunId && task.archivedAt === undefined);- if (chosenId && open.some((task) => task.threadId === chosenId)) return chosenId;- const asked = open.reduce<MainThreadCandidate | undefined>(- (latest, task) => ((task.askedAt ?? -1) > (latest?.askedAt ?? -1) ? task : latest), undefined,- );- return asked?.threadId ?? open.find((task) => task.threadId === selectedId)?.threadId ?? oldestThread(tasks);+/** A bot's main thread, where it opens to with threads hidden and where its routines and briefs report: the one the+ * person chose (while it is open), else the oldest open conversation a person started, else the oldest open one. Writing+ * in another thread never moves it. */+export function mainThread(tasks: readonly MainThreadCandidate[], chosenId?: string): string | undefined {+ const chosen = chosenId ? tasks.find((task) => task.threadId === chosenId) : undefined;+ if (chosen && !chosen.routineRunId && chosen.archivedAt === undefined) return chosen.threadId;+ return oldestThread(tasks.filter((task) => !task.openedBy && task.archivedAt === undefined)) ?? oldestThread(tasks);}/** The conversation whose saves stay in the bot's own memory: the one the person set as main while it is open, else thediff --git a/server/routine-results.e2e.test.ts b/server/routine-results.e2e.test.tsindex 615c220d60..347a69aab9 100644--- a/server/routine-results.e2e.test.ts+++ b/server/routine-results.e2e.test.ts@@ -78,6 +78,8 @@ it("reports every run into the bot's main thread while fresh executions, approvaexpect(promoted.routineRunId).toBeUndefined();expect(promoted.unread).toBe(true);const live = completed[0].threadId as string;+ expect((await currentBot()).mainThreadId, "writing in another thread leaves the main one alone").toBe(originalThread);+ await api("PATCH", `/api/bots/${bot.id}`, { mainThreadChoice: live });expect((await currentBot()).mainThreadId).toBe(live);const { task: chosenTask } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Chosen reports" }, 201);const dedicated = chosenTask.threadId as string;@@ -149,7 +151,7 @@ it("reports every run into the bot's main thread while fresh executions, approva}}, 90_000);-it("reports a routine made in a chat into that chat once the person writes there, not the bot's first thread or a new results thread", async () => {+it("reports a routine made in a chat into the bot's main thread, which writing in that chat does not move, not a new results thread", async () => {const fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });const evidence: unknown[] = [{ fixture: fixture.info }];const planPath = join(fixture.info.dataDir, "room-plan.json");@@ -186,21 +188,21 @@ it("reports a routine made in a chat into that chat once the person writes thereexpect(definition.sourceThreadId).toBe(chat);const { run } = await api("POST", `/api/routines/${routineId}/run`, undefined, 201);- expect(run.resultsThreadId).toBe(chat);+ expect(run.resultsThreadId).toBe(first);await expect.poll(async () => (await api("GET", "/api/routines")).runs.find((candidate: any) => candidate.id === run.id)?.status, { timeout: 20_000 }).toBe("completed");const finished = (await api("GET", "/api/routines")).runs.find((candidate: any) => candidate.id === run.id);- // The chat that made it keeps its one trigger card, and the run's reply lands there as the bot's own line.- expect((await messages(chat)).some((message) => message.routineRun?.runId === run.id)).toBe(false);- await expect.poll(async () => (await messages(chat)).filter((message) => message.automation?.runId === run.id).map((message) => message.text), { timeout: 15_000 })+ // The chat that made it keeps its one trigger card, and the run's reply lands in the main thread as the bot's own line.+ expect((await messages(first)).some((message) => message.routineRun?.runId === run.id)).toBe(false);+ await expect.poll(async () => (await messages(first)).filter((message) => message.automation?.runId === run.id).map((message) => message.text), { timeout: 15_000 }).toEqual(["Fresh chat report"]);expect((await messages(chat)).filter((message) => message.card?.routineRequest?.resultId === routineId)).toHaveLength(1);- expect((await messages(first)).some((message) => message.kind === "routine.run" || message.automation)).toBe(false);+ expect((await messages(chat)).some((message) => message.kind === "routine.run" || message.automation)).toBe(false);const saved = (await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id);expect(saved.tasks.filter((candidate: any) => !candidate.routineRunId).map((candidate: any) => candidate.threadId).sort()).toEqual([first, chat].sort());- expect(saved.tasks.find((candidate: any) => candidate.threadId === chat).unread).toBe(true);+ expect(saved.mainThreadId).toBe(first);expect(saved.tasks.find((candidate: any) => candidate.threadId === finished.threadId)).toMatchObject({ routineRunId: run.id });- evidence.push({ run: finished, bot: saved, main: await messages(chat) });+ evidence.push({ run: finished, bot: saved, main: await messages(first) });} finally {const evidencePath = `${fixture.info.logPath}.chat-results.json`;writeFileSync(evidencePath, JSON.stringify(evidence, null, 2));@@ -262,7 +264,7 @@ async function resultsFixture() {return { api, control, messages, savedBot, destination, routine, report, restart, close };}-it("reports into the conversation the person is in, the one a bot with hidden threads opens, after they used threads", async () => {+it("reports into the bot's main thread, its first conversation, whichever one the person wrote in last or left selected", async () => {const f = await resultsFixture();try {const { bot } = await f.control("new-bot", "--name", "Hidden threads");@@ -270,24 +272,23 @@ it("reports into the conversation the person is in, the one a bot with hidden thconst { task } = await f.api("POST", `/api/bots/${bot.id}/tasks`, { title: "Later chat" }, 201);const live = task.threadId as string;const routine = await f.routine(bot.id);- expect(await f.report(routine)).toBe(live);+ expect(await f.report(routine)).toBe(oldest);await f.control("send", "--bot", bot.id, "--task", live, "--text", "Good morning.");expect((await f.control("wait", "--bot", bot.id, "--task", live, "--timeout", "20")).status).toBe("settled");- await f.api("POST", `/api/bots/${bot.id}/tasks/${oldest}?messages=0`);- expect(await f.report(routine)).toBe(live);- expect((await f.messages(live)).filter((message) => message.automation)).toHaveLength(2);- expect((await f.messages(oldest)).some((message) => message.automation)).toBe(false);+ await f.api("POST", `/api/bots/${bot.id}/tasks/${live}?messages=0`);+ expect(await f.report(routine)).toBe(oldest);+ expect((await f.messages(oldest)).filter((message) => message.automation)).toHaveLength(2);+ expect((await f.messages(live)).some((message) => message.automation)).toBe(false);const saved = await f.savedBot(bot.id);- expect(saved.threadId).toBe(oldest);- expect(saved.tasks.find((candidate: any) => candidate.threadId === live).unread).toBe(true);- expect(saved.mainThreadId).toBe(live);+ expect(saved.threadId).toBe(live);+ expect(saved.mainThreadId).toBe(oldest);expect(await f.destination(routine)).toBeUndefined();} finally {await f.close();}}, 90_000);-it("after the upgrade, reports into and opens the conversation the person last wrote in before it, not the one left selected", async () => {+it("after the upgrade, still reports into and opens the bot's first conversation, whichever one the person last wrote in before it", async () => {const f = await resultsFixture();try {const { bot } = await f.control("new-bot", "--name", "Upgraded");@@ -309,8 +310,8 @@ it("after the upgrade, reports into and opens the conversation the person last w});const saved = await f.savedBot(bot.id);expect(saved.threadId).toBe(oldest);- expect(saved.mainThreadId).toBe(theirs);- expect(await f.report(routine)).toBe(theirs);+ expect(saved.mainThreadId).toBe(oldest);+ expect(await f.report(routine)).toBe(oldest);} finally {await f.close();}@@ -334,7 +335,8 @@ it("clears the oldest thread v0.1.98 to v0.1.107 saved as a routine's destinatiofile.routines.find((candidate: any) => candidate.id === tidiedRoutine).resultsThreadId = archived;});expect(await f.destination(routine)).toBeUndefined();- expect(await f.report(routine)).toBe(task.threadId);+ expect(task.threadId).not.toBe(oldest);+ expect(await f.report(routine)).toBe(oldest);expect(await f.destination(tidiedRoutine)).toBeUndefined();expect(await f.report(tidiedRoutine)).toBe(kept.threadId);expect((await f.api("PATCH", `/api/routines/${routine}`, { resultsThreadId: oldest })).routine.resultsThreadId).toBe(oldest);