Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Keep room-thread activity in its own module, within the file-size ratchet

AdityaUmale97b8a29b39f3
diff --git a/server/independent-task-store.test.ts b/server/independent-task-store.test.ts
index fe9ce0a86a..9a03b484fb 100644
--- a/server/independent-task-store.test.ts
+++ b/server/independent-task-store.test.ts
@@ -22,14 +22,14 @@ describe("independent bot task state", () => {
const bot = store.createBot({}, { seedMessages: false });
store.setActivity(bot.id, "working", "room-a");
store.setActivity(bot.id, "working", "room-b");
- expect(store.busyRoomThreads(bot.id).sort()).toEqual(["room-a", "room-b"]);
+ expect(store.roomActivities.busyThreads(bot.id).sort()).toEqual(["room-a", "room-b"]);
expect(store.busyForRoomThread(bot.id, "room-c")).toBe(false);
expect(store.busyForRoomThread(bot.id, "room-a")).toBe(true);
store.setActivity(bot.id, "idle", "room-a");
expect(bot).toMatchObject({ activity: "working", busy: true });
- expect(store.roomActivity(bot.id, "room-a")).toEqual({ activity: "idle", busy: false });
+ expect(store.roomActivities.of(bot.id, "room-a")).toEqual({ activity: "idle", busy: false });
store.setActivity(bot.id, "waiting-on-you", "room-b");
- expect(store.roomActivity(bot.id, "room-b")).toEqual({ activity: "waiting-on-you", busy: true });
+ expect(store.roomActivities.of(bot.id, "room-b")).toEqual({ activity: "waiting-on-you", busy: true });
store.setActivity(bot.id, "idle", "room-b");
expect(bot).toMatchObject({ activity: "idle", busy: false });
store.setTaskActivity(bot.id, bot.threadId, "working");
diff --git a/server/index.ts b/server/index.ts
index c8bcea6a98..f03a31929c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -4138,15 +4138,14 @@ function groupMemberBotAvailability(botId: string, operation: GroupTurnOperation
if (operation.cancelled || operation.cancellation.signal.aborted) return "cancelled";
const bot = store.bot(botId);
if (!bot || bot.hidden) return "unavailable";
- if (store.busyForRoomThread(botId, operation.threadId) || roomThreadsFull(botId, operation.threadId)) return "busy";
+ if (roomTurnBlocked(botId, operation.threadId)) return "busy";
return "ready";
}
/** One bot's turns in different room threads run at once, within the same per-bot thread limit as its own chats. */
-function roomThreadsFull(botId: string, threadId: string): boolean {
- const others = new Set([...roomMemberLock.threads(botId), ...store.busyRoomThreads(botId)]);
- others.delete(threadId);
- return others.size >= maxConcurrentBotThreads(cfg, botThreadsHost(cloudPlanTier.starter()));
+function roomTurnBlocked(botId: string, threadId: string): boolean {
+ const others = new Set([...roomMemberLock.threads(botId), ...store.roomActivities.busyThreads(botId)]); others.delete(threadId);
+ return store.busyForRoomThread(botId, threadId) || others.size >= maxConcurrentBotThreads(cfg, botThreadsHost(cloudPlanTier.starter()));
}
/** One synchronous step, so threads woken by the same release cannot all read the member as free. */
@@ -4415,7 +4414,7 @@ function groupProviderHandshakeSettled(operation: GroupTurnOperation): void {
clearCancelledProviderHandshake(operation.threadId, `group:${operation.id}`);
}
-/** Every room thread this bot has a turn in: one bot's turns in different room threads run at once. */
+/** Every room thread this bot has a turn in. */
function groupTurnsForBot(botId: string): { group: GroupRecord; threadId: string }[] {
const turns = new Map<string, { group: GroupRecord; threadId: string }>();
for (const group of store.groups) {
@@ -4429,17 +4428,14 @@ function groupTurnsForBot(botId: string): { group: GroupRecord; threadId: string
: Boolean(store.groupTaskByThread(group.id, threadId));
if (ownsThread) turns.set(threadId, { group, threadId });
}
- if (group.busyBotId === botId && ![...turns.values()].some((turn) => turn.group.id === group.id)) {
- turns.set(group.threadId, { group, threadId: group.threadId });
- }
+ if (group.busyBotId === botId && ![...turns.values()].some((turn) => turn.group.id === group.id)) turns.set(group.threadId, { group, threadId: group.threadId });
}
return [...turns.values()];
}
/** The bot's room turn in threadId when it has one there, else any of its room turns. */
function activeGroupTurnForBot(botId: string, threadId?: string): { group: GroupRecord; threadId: string } | null {
- const turns = groupTurnsForBot(botId);
- return turns.find((turn) => turn.threadId === threadId) ?? turns[0] ?? null;
+ const turns = groupTurnsForBot(botId); return turns.find((turn) => turn.threadId === threadId) ?? turns[0] ?? null;
}
const groupWithThread = (group: GroupRecord) => {
@@ -6566,7 +6562,7 @@ bus.subscribe((event: RuntimeEvent) => {
const card = store.messagesFor(event.threadId).find((candidate) => candidate.id === message.id)?.card;
if (card && !card.answered) {
if (bot) store.setTaskActivity(bot.id, event.threadId, "waiting-on-you");
- else if (store.roomActivity(asker.id, event.threadId).busy) store.setActivity(asker.id, "waiting-on-you", event.threadId);
+ else if (store.roomActivities.of(asker.id, event.threadId).busy) store.setActivity(asker.id, "waiting-on-you", event.threadId);
if (event.requestId) askCards.showWaitingOnPersonChip(event.threadId, event.requestId, asker, permission ? "approval" : "answer");
const notificationBot = (routineRun && routineSourceOwner(routineRun)?.bot) || asker;
notify(buildNotification(
@@ -6585,7 +6581,7 @@ bus.subscribe((event: RuntimeEvent) => {
const waiting = bot ?? (speaker ? store.bot(speaker.botId) : undefined);
if (bot && turnWaitedOnPerson(store.taskByThread(bot.id, event.threadId))) {
store.setTaskActivity(bot.id, event.threadId, "working");
- } else if (!bot && waiting && turnWaitedOnPerson(store.roomActivity(waiting.id, event.threadId))) store.setActivity(waiting.id, "working", event.threadId);
+ } else if (!bot && waiting && turnWaitedOnPerson(store.roomActivities.of(waiting.id, event.threadId))) store.setActivity(waiting.id, "working", event.threadId);
const messageId = event.requestId ? askMessageByRequest.get(`${event.threadId}:${event.requestId}`) : null;
if (messageId) {
const existing = store.messagesFor(event.threadId).find((m) => m.id === messageId);
@@ -8626,10 +8622,7 @@ async function stopBotForEmergencyApprovalDowngrade(botId: string): Promise<void
const groupTurns = groupTurnsForBot(bot.id);
if (groupTurns.length) {
- for (const groupTurn of groupTurns) {
- revokeInternalCapabilitiesForThread(groupTurn.threadId);
- cancelGroupTurnOperations(groupTurn.group.id, groupTurn.threadId);
- }
+ for (const groupTurn of groupTurns) { revokeInternalCapabilitiesForThread(groupTurn.threadId); cancelGroupTurnOperations(groupTurn.group.id, groupTurn.threadId); }
const results = await Promise.allSettled([
directStop,
...groupTurns.map((groupTurn) => runningTurnInstance(bot, groupTurn.threadId)?.adapter.interruptTurn(groupTurn.threadId)),
@@ -9543,7 +9536,7 @@ async function runClaimedGroupMemberTurn(
return true;
}
// The last-line guard for a 1:1 that re-claimed the bot, or a room thread that filled its thread limit, after the member wait settled.
- if (store.busyForRoomThread(bot.id, threadId) || roomThreadsFull(bot.id, threadId)) {
+ if (roomTurnBlocked(bot.id, threadId)) {
if (orchestration) {
orchestration.result.outcome = "busy";
return true;
@@ -9755,7 +9748,7 @@ async function runClaimedGroupMemberTurn(
reportDispatchError(message);
return true;
}
- if (store.busyForRoomThread(bot.id, threadId) || roomThreadsFull(bot.id, threadId)) {
+ if (roomTurnBlocked(bot.id, threadId)) {
if (orchestration) {
orchestration.result.outcome = "busy";
return true;
@@ -10051,7 +10044,7 @@ async function runClaimedGroupMemberTurn(
isCancelled?.() ||
// This thread's own speaker: another thread's member claiming meanwhile moves the room-wide busyBotId, never this turn.
groupSpeakers.get(threadId) !== roomSpeaker ||
- !store.roomActivity(bot.id, threadId).busy
+ !store.roomActivities.of(bot.id, threadId).busy
) {
groupSpeakers.delete(threadId);
const remaining = activeGroupSpeaker(group.id);
diff --git a/server/outbound-hold.ts b/server/outbound-hold.ts
index b97bcc8d36..20fb9d0044 100644
--- a/server/outbound-hold.ts
+++ b/server/outbound-hold.ts
@@ -16,7 +16,7 @@ export const OUTBOUND_HOLD_MS = 9 * 60_000;
export type OutboundHoldBot = Pick<BotRecord, "id" | "name" | "color" | "outbound" | "avatarUrl" | "notifications">;
export interface OutboundHoldDeps {
- store: Pick<Store, "appendMessage" | "bot" | "messagesFor" | "patchMessage" | "roomActivity" | "setActivity" | "setTaskActivity" | "taskByThread">;
+ store: Pick<Store, "appendMessage" | "bot" | "messagesFor" | "patchMessage" | "roomActivities" | "setActivity" | "setTaskActivity" | "taskByThread">;
dataDir: string;
outboundRequests: OutboundRequestService;
/** How long a "Send on your behalf?" card waits before it times out. */
@@ -84,7 +84,7 @@ export function createOutboundHold(deps: OutboundHoldDeps): OutboundHold {
outboundRequests.forget(held.requestId);
if (active()) {
if (owner?.group) {
- if (activeGroupTurnForBot(currentSender.id, threadId)?.threadId === threadId && turnWaitedOnPerson(store.roomActivity(currentSender.id, threadId))) store.setActivity(currentSender.id, "working", threadId);
+ if (activeGroupTurnForBot(currentSender.id, threadId)?.threadId === threadId && turnWaitedOnPerson(store.roomActivities.of(currentSender.id, threadId))) store.setActivity(currentSender.id, "working", threadId);
} else if (turnWaitedOnPerson(store.taskByThread(currentSender.id, threadId))) {
store.setTaskActivity(currentSender.id, threadId, "working");
}
diff --git a/server/room-activities.ts b/server/room-activities.ts
new file mode 100644
index 0000000000..24642b256c
--- /dev/null
+++ b/server/room-activities.ts
@@ -0,0 +1,43 @@
+// A bot's room turns keep one activity per room thread, so ending one leaves the bot's other room threads running.
+import type { BotActivity } from "../shared/wire.ts";
+
+export const ACTIVITY_BUSY: ReadonlySet<BotActivity> = new Set(["working", "waiting-on-you", "no-signal"]);
+
+export class RoomActivities {
+ private readonly byBot = new Map<string, Map<string, BotActivity>>();
+
+ /** False when the thread already had this activity. */
+ set(botId: string, threadId: string, activity: BotActivity): boolean {
+ const threads = this.byBot.get(botId) ?? new Map<string, BotActivity>();
+ if ((threads.get(threadId) ?? "idle") === activity) return false;
+ if (activity === "idle") threads.delete(threadId);
+ else threads.set(threadId, activity);
+ if (threads.size) this.byBot.set(botId, threads);
+ else this.byBot.delete(botId);
+ return true;
+ }
+
+ /** This bot's room turn in one room thread, shaped like a task's activity. */
+ of(botId: string, threadId: string): { activity: BotActivity; busy: boolean } {
+ const activity = this.byBot.get(botId)?.get(threadId) ?? "idle";
+ return { activity, busy: ACTIVITY_BUSY.has(activity) };
+ }
+
+ activities(botId: string): BotActivity[] {
+ return [...(this.byBot.get(botId)?.values() ?? [])];
+ }
+
+ /** Room threads this bot has a running turn in. */
+ busyThreads(botId: string): string[] {
+ return [...(this.byBot.get(botId) ?? [])].filter(([threadId, activity]) => threadId && ACTIVITY_BUSY.has(activity)).map(([threadId]) => threadId);
+ }
+
+ /** A turn in this room thread, or one set without a thread, is running. */
+ busyIn(botId: string, threadId: string): boolean {
+ return this.of(botId, threadId).busy || this.of(botId, "").busy;
+ }
+
+ forget(botId: string): void {
+ this.byBot.delete(botId);
+ }
+}
diff --git a/server/store.ts b/server/store.ts
index c095cb25bc..ff405ec06b 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -8,7 +8,7 @@ import { reorderInPlace } from "../shared/bot-order.ts"; import { trimOutboundPo
import { botOwner, chiefConflict, chiefScope, ownerEmail } from "../shared/bot-owner.ts"; import { reshowWhenMoved } from "../shared/default-bot.ts";
import { ensureSections, readSections, changeEmptySection, reorderSectionNames } from "./section-context.ts"; import { grantNewDepartments } from "./department-grants.ts";
import type { TeamComputers } from "./team-computers.ts";
-import { removeBotFolder, soulFile, soulHash, writeSoulMirror } from "./bot-folder.ts";
+import { removeBotFolder, soulFile, soulHash, writeSoulMirror } from "./bot-folder.ts"; import { ACTIVITY_BUSY, RoomActivities } from "./room-activities.ts";
import type { BotProfilePatch } from "./bot-profile.ts";
import { DATA_DIR, EVENTS_DIR, NATIVE_DIR, loadBrowserProfileIdAliases } from "./config.ts";
import * as mdb from "./message-db.ts";
@@ -121,7 +121,7 @@ export type TaskPatch = Partial<Pick<TaskRecord, typeof TASK_PATCH_FIELDS[number
export type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "pinned">> & { turnTimeoutMinutes?: number | null; archivedAt?: number | null; activity?: "waiting-on-you" | null; closed?: { at: number; by: NonNullable<GroupTaskRecord["closedBy"]> } | null };
-export const ACTIVITY_BUSY: ReadonlySet<BotActivity> = new Set(["working", "waiting-on-you", "no-signal"]);
+export { ACTIVITY_BUSY };
export type StoreChange =
| { type: "sections" }
@@ -267,7 +267,7 @@ export class Store {
/** Where bots, rooms and their threads are saved (server/registry-store.ts). */
private readonly registry: RegistryStore = new JsonRegistry();
/** A room turn's activity, per room thread: clearing one must not clear another thread's or a task's. */
- private legacyActivities = new Map<string, Map<string, BotActivity>>();
+ readonly roomActivities = new RoomActivities();
constructor(
defaultSelection: () => ModelSelection,
@@ -1420,7 +1420,7 @@ export class Store {
// Persist removal before deleting data: a failed save must leave the bot recoverable.
this.registry.deleteOwner({ kind: "bot", id }, () => this.saveBots(nextBots));
this.bots = nextBots;
- this.legacyActivities.delete(id);
+ this.roomActivities.forget(id);
const rooms = this.groups.filter((g) => !g.dm && g.memberIds.includes(id));
for (const g of rooms) {
g.memberIds = g.memberIds.filter((member) => member !== id);
@@ -1590,12 +1590,7 @@ export class Store {
setActivity(botId: string, activity: BotActivity, threadId = ""): BotRecord | null {
const bot = this.own(botId);
if (!bot) return null;
- const threads = this.legacyActivities.get(botId) ?? new Map<string, BotActivity>();
- if ((threads.get(threadId) ?? "idle") === activity) return bot;
- if (activity === "idle") threads.delete(threadId);
- else threads.set(threadId, activity);
- if (threads.size) this.legacyActivities.set(botId, threads);
- else this.legacyActivities.delete(botId);
+ if (!this.roomActivities.set(botId, threadId, activity)) return bot;
this.refreshBotActivity(bot);
this.emit({ type: "bot", botId });
return bot;
@@ -1622,30 +1617,17 @@ export class Store {
}
private refreshBotActivity(bot: BotRecord) {
- const legacy = [...(this.legacyActivities.get(bot.id)?.values() ?? [])];
+ const legacy = this.roomActivities.activities(bot.id);
const activities = [...legacy, ...(bot.tasks ?? []).map((task) => task.activity)];
bot.activity = (["waiting-on-you", "no-signal", "working", "dead"] as const)
.find((activity) => activities.includes(activity)) ?? "idle";
bot.busy = legacy.some((activity) => ACTIVITY_BUSY.has(activity)) || (bot.tasks ?? []).some((task) => task.busy);
}
- /** This bot's room turn in one room thread, shaped like a task's activity. */
- roomActivity(botId: string, threadId: string): { activity: BotActivity; busy: boolean } {
- const activity = this.legacyActivities.get(botId)?.get(threadId) ?? "idle";
- return { activity, busy: ACTIVITY_BUSY.has(activity) };
- }
-
- /** Room threads this bot has a running turn in. */
- busyRoomThreads(botId: string): string[] {
- return [...(this.legacyActivities.get(botId) ?? [])].filter(([threadId, activity]) => threadId && ACTIVITY_BUSY.has(activity)).map(([threadId]) => threadId);
- }
-
/** Busy anywhere except a room turn in another room thread: those run beside this one. */
busyForRoomThread(botId: string, threadId: string): boolean {
const bot = this.own(botId);
- if (!bot) return this.bot(botId)?.busy === true;
- const room = [...(this.legacyActivities.get(botId) ?? [])].some(([thread, activity]) => (thread === threadId || thread === "") && ACTIVITY_BUSY.has(activity));
- return room || (bot.tasks ?? []).some((task) => task.busy);
+ return bot ? this.roomActivities.busyIn(botId, threadId) || (bot.tasks ?? []).some((task) => task.busy) : this.bot(botId)?.busy === true;
}
/** Makes `id` its scope's one Chief (its owner's on a Team Cloud, else its department's), or with no `id` leaves