Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep the selected thread as the main one when an update first saves it
luishron1235b03ef25270b
diff --git a/server/index.ts b/server/index.tsindex 93128773ea..dd6d857650 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 {- const tasks = mainThreadTasks(botId); return mainThread(tasks, store.keepMainThread(botId, (chosen) => mainThreadToKeep(tasks, chosen)));+ const tasks = mainThreadTasks(botId); return mainThread(tasks, store.keepMainThread(botId, (chosen) => mainThreadToKeep(tasks, chosen, store.bot(botId)?.threadId)));} 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/main-thread.e2e.test.ts b/server/main-thread.e2e.test.tsindex 49d1307060..814ab39a72 100644--- a/server/main-thread.e2e.test.ts+++ b/server/main-thread.e2e.test.ts@@ -247,3 +247,41 @@ it("keeps the main thread an install already had across an update, then moves itawait server.close();}}, 180_000);++it("keeps the selected thread as the main one across an update for a bot nobody wrote to", async () => {+ const server = await launchRestartableServer();+ const api = async (method: string, path: string, body?: unknown, status = 200) => {+ const response = await fetch(`${server.url}${path}`, {+ method, headers: { "content-type": "application/json", origin: server.url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ const value = await response.json() as any;+ expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBe(status);+ return value;+ };+ try {+ const { bot } = await runControlOmb(["new-bot", "--name", "Quiet", "--url", server.url]) as any;+ const first = bot.activeTaskId as string;+ const main = async () => (await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id).mainThreadId;+ const saved = () => readRegistry(server.dataDir).bots.find((candidate: any) => candidate.id === bot.id);+ const second = (await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Second", approvalMode: "ask" }, 201)).task.threadId as string;++ // What an install saved before a main thread was kept: no choice, the second thread selected, nothing written anywhere.+ await server.stop();+ const file = join(server.dataDir, "bots.json");+ writeFileSync(file, JSON.stringify((JSON.parse(readFileSync(file, "utf8")) as any[]).map(({ mainThreadChoice: _choice, ...rest }) => rest)));+ expect(saved()).toMatchObject({ threadId: second });+ expect(saved().tasks.some((task: any) => task.askedAt !== undefined)).toBe(false);+ await server.start();+ expect(await main(), "the selected thread, as before the update").toBe(second);+ await api("POST", `/api/bots/${bot.id}/tasks/${first}`);+ expect((await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id).threadId).toBe(first);+ expect(await main(), "selecting another thread moves nothing").toBe(second);+ await server.stop();+ expect(saved().mainThreadChoice).toBe(second);+ await server.start();+ expect(await main()).toBe(second);+ } finally {+ await server.close();+ }+}, 120_000);diff --git a/server/main-thread.test.ts b/server/main-thread.test.tsindex 62405d01b0..e6c718c020 100644--- a/server/main-thread.test.ts+++ b/server/main-thread.test.ts@@ -55,10 +55,19 @@ describe("the main thread a bot keeps", () => {expect(mainThreadToKeep([latest, { ...later, askedAt: 30, routineRunId: "run" }, first])).toBe("first");});- it("is the oldest open conversation a person started when nobody wrote anywhere, and nothing when there is none", () => {- expect(mainThreadToKeep([latest, later, { ...first, openedBy: { botId: "teammate" } }])).toBe("later");- expect(mainThreadToKeep([{ ...first, openedBy: { botId: "teammate" } }])).toBeUndefined();- expect(mainThreadToKeep([{ ...first, archivedAt: 2 }])).toBeUndefined();+ it("is, where nobody wrote, the open thread that was selected, as it was before a main thread was kept", () => {+ expect(mainThreadToKeep([latest, later, first], undefined, "later")).toBe("later");+ expect(mainThreadToKeep([latest, later, { ...first, openedBy: { botId: "teammate" } }], undefined, "first")).toBe("first");+ expect(mainThreadToKeep([latest, { ...later, askedAt: 30 }, first], undefined, "latest")).toBe("later");+ expect(mainThreadToKeep([latest, { ...later, archivedAt: 5 }, first], undefined, "later")).toBe("first");+ expect(mainThreadToKeep([latest, { ...later, routineRunId: "run" }, first], undefined, "later")).toBe("first");+ expect(mainThreadToKeep([latest, later, first], undefined, "deleted")).toBe("first");+ });++ it("is the oldest open thread when nobody wrote and none is selected, whoever opened it, and nothing when none is open", () => {+ expect(mainThreadToKeep([latest, later, { ...first, openedBy: { botId: "teammate" } }])).toBe("first");+ expect(mainThreadToKeep([latest, { ...first, routineRunId: "run" }])).toBe("latest");+ expect(mainThreadToKeep([{ ...first, archivedAt: 2 }], undefined, "first")).toBeUndefined();});it("changes nothing while the saved thread is open", () => {@@ -68,6 +77,8 @@ describe("the main thread a bot keeps", () => {it("is the oldest open conversation a person started once the saved thread is archived or deleted, wherever they last wrote", () => {expect(mainThreadToKeep([latest, { ...later, askedAt: 30 }, { ...first, archivedAt: 40 }], "first")).toBe("later");expect(mainThreadToKeep([{ ...latest, askedAt: 50 }, later], "first")).toBe("later");+ expect(mainThreadToKeep([latest, later, { ...first, archivedAt: 40 }], "first", "latest")).toBe("later");+ expect(mainThreadToKeep([latest, { ...later, openedBy: { botId: "teammate" } }], "first", "later")).toBe("latest");});});diff --git a/server/main-thread.ts b/server/main-thread.tsindex bdb5be411a..3acd86eb3f 100644--- a/server/main-thread.ts+++ b/server/main-thread.ts@@ -31,14 +31,16 @@ export function mainThread(tasks: readonly MainThreadCandidate[], chosenId?: str}/** The thread to save as a bot's choice so its main thread stays put: nothing while the saved one is open. A bot that- * never had one keeps the open thread a person last wrote in, where it reported until now; one whose saved thread was- * archived or deleted moves to the oldest open conversation a person started, and reopening the old one moves nothing. */-export function mainThreadToKeep(tasks: readonly MainThreadCandidate[], chosenId?: string): string | undefined {- if (chosenId && tasks.some((task) => task.threadId === chosenId && open(task))) return undefined;- const asked = chosenId ? undefined : tasks.filter(open).reduce<MainThreadCandidate | undefined>(+ * never had one keeps the thread it showed until now: the open one a person last wrote in, else the selected one, else+ * the oldest open one. One whose saved thread was archived or deleted moves to the oldest open conversation a person+ * started, and reopening the old one moves nothing. */+export function mainThreadToKeep(tasks: readonly MainThreadCandidate[], chosenId?: string, selectedId?: string): string | undefined {+ if (chosenId) return tasks.some((task) => task.threadId === chosenId && open(task)) ? undefined : oldestThread(tasks.filter((task) => !task.openedBy && open(task)));+ const live = tasks.filter(open);+ const asked = live.reduce<MainThreadCandidate | undefined>((latest, task) => ((task.askedAt ?? -1) > (latest?.askedAt ?? -1) ? task : latest), undefined,);- return asked?.threadId ?? oldestThread(tasks.filter((task) => !task.openedBy && open(task)));+ return asked?.threadId ?? live.find((task) => task.threadId === selectedId)?.threadId ?? oldestThread(live);}/** The conversation whose saves stay in the bot's own memory: the one the person set as main while it is open, else the