Skip to content

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

Run one bot's room turns in different room threads at once

AdityaUmale8c0b3a33d8b0
diff --git a/server/host/member-own-bot.ts b/server/host/member-own-bot.ts
index 2794082943..b29ad3708a 100644
--- a/server/host/member-own-bot.ts
+++ b/server/host/member-own-bot.ts
@@ -6,7 +6,7 @@ import type { BotRecord, Store } from "../store.ts";
export interface MemberOwnBotDeps {
store(): Pick<Store, "bot" | "patchBot">;
routines(): Pick<RoutineManager, "activeRunForBot" | "cancelRun"> | null;
- activeGroupTurnForBot(botId: string): { group: { id: string }; threadId: string } | null;
+ groupTurnsForBot(botId: string): { group: { id: string }; threadId: string }[];
cancelGroupTurnOperations(groupId: string, threadId: string): void;
revokeInternalCapabilitiesForThread(threadId: string): void;
interruptAllDirectThreads(botId: string): Promise<void>;
@@ -19,23 +19,23 @@ export interface MemberOwnBotDeps {
export function createMemberOwnBot(deps: MemberOwnBotDeps) {
return {
- /** Stops every turn of a bot: its chats, its routine run and the room turn it is in. */
+ /** Stops every turn of a bot: its chats, its routine run and every room turn it is in. */
async stopWork(botId: string, cause: string): Promise<void> {
const bot = deps.store().bot(botId);
if (!bot) return;
const routines = deps.routines();
const run = routines?.activeRunForBot(botId);
- const groupTurn = deps.activeGroupTurnForBot(botId);
- if (groupTurn) {
+ const groupTurns = deps.groupTurnsForBot(botId);
+ for (const groupTurn of groupTurns) {
deps.cancelGroupTurnOperations(groupTurn.group.id, groupTurn.threadId);
deps.revokeInternalCapabilitiesForThread(groupTurn.threadId);
}
await Promise.allSettled([
deps.interruptAllDirectThreads(botId),
run ? routines!.cancelRun(run.id, cause) : undefined,
- groupTurn ? deps.interruptTurn(bot, groupTurn.threadId) : undefined,
+ ...groupTurns.map((groupTurn) => deps.interruptTurn(bot, groupTurn.threadId)),
]);
- if (groupTurn) deps.closeOpenApprovals(groupTurn.threadId);
+ for (const groupTurn of groupTurns) deps.closeOpenApprovals(groupTurn.threadId);
},
/** Deletes a member's own MausBot, which stops being their default bot first; it is theirs again if that fails. */
async remove(botId: string): Promise<boolean> {
diff --git a/server/independent-task-store.test.ts b/server/independent-task-store.test.ts
index 2fef2ce578..fe9ce0a86a 100644
--- a/server/independent-task-store.test.ts
+++ b/server/independent-task-store.test.ts
@@ -17,6 +17,25 @@ describe("independent bot task state", () => {
// The shared Vitest setup gives this file its own disposable home.
beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+ it("keeps a bot's room turns per room thread, so ending one leaves the others running", () => {
+ const store = new Store(selection);
+ 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.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 });
+ store.setActivity(bot.id, "waiting-on-you", "room-b");
+ expect(store.roomActivity(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");
+ expect(store.busyForRoomThread(bot.id, "room-c")).toBe(true);
+ });
+
it("applies an explicit bot-wide approval mode without changing history or provider choices", () => {
const store = new Store(selection);
const bot = store.createBot({}, { seedMessages: false });
diff --git a/server/index.ts b/server/index.ts
index e8b24b6a66..c8bcea6a98 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2760,7 +2760,7 @@ const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, le
const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersonStop({
store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, stopping: (botId, threadId) => idleThreads.stopping(botId, threadId), clearUnattended,
stopGoal: (threadId) => { oneOnOneGoals.stop(threadId); checkWork.stop(threadId); }, markStopped: (threadId, by) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId), by), working: (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId) || checkWork.holds(threadId), asking: (threadId) => coordinator.awaitingAnswer(threadId) || Boolean(openPersonCard(threadId)), language: threadLanguage, stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by),
-}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, live: (threadId, requestId) => askMessageByRequest.has(`${threadId}:${requestId}`), waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), named: { personNames: (threadId) => [cfg.profile?.name, CLOUD_PERSONAL && cloudGuestDriven(threadId) ? guestNameIn(store.messagesFor(threadId)) : undefined], elsewhere: (to) => botsElsewhere(botLink.link, (name) => botLink.explain(name, placesElsewhere), to) }, team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, delivered: (item, delivery) => teamAway.delivered(item, delivery), changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null, opened: (made) => void mausbotOwnChat.claim(made) }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(...teamConnections.via(access))).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(teamConnections.via(access)[0], payload as never, session, undefined, signal, teamConnections.via(access)[1]) }).busy } } });
+}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, live: (threadId, requestId) => askMessageByRequest.has(`${threadId}:${requestId}`), waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), named: { personNames: (threadId) => [cfg.profile?.name, CLOUD_PERSONAL && cloudGuestDriven(threadId) ? guestNameIn(store.messagesFor(threadId)) : undefined], elsewhere: (to) => botsElsewhere(botLink.link, (name) => botLink.explain(name, placesElsewhere), to) }, team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, delivered: (item, delivery) => teamAway.delivered(item, delivery), changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null, opened: (made) => void mausbotOwnChat.claim(made) }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId, threadId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(...teamConnections.via(access))).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(teamConnections.via(access)[0], payload as never, session, undefined, signal, teamConnections.via(access)[1]) }).busy } } });
const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });
const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });
@@ -4138,10 +4138,17 @@ 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 (bot.busy || roomMemberLock.heldElsewhere(botId, operation.threadId)) return "busy";
+ if (store.busyForRoomThread(botId, operation.threadId) || roomThreadsFull(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()));
+}
+
/** One synchronous step, so threads woken by the same release cannot all read the member as free. */
function claimGroupMemberBot(botId: string, operation: GroupTurnOperation): GroupMemberBotAvailability {
const availability = groupMemberBotAvailability(botId, operation);
@@ -4408,25 +4415,31 @@ function groupProviderHandshakeSettled(operation: GroupTurnOperation): void {
clearCancelledProviderHandshake(operation.threadId, `group:${operation.id}`);
}
-function activeGroupTurnForBot(botId: string): { group: GroupRecord; threadId: string } | null {
+/** Every room thread this bot has a turn in: one bot's turns in different room threads run at once. */
+function groupTurnsForBot(botId: string): { group: GroupRecord; threadId: string }[] {
+ const turns = new Map<string, { group: GroupRecord; threadId: string }>();
for (const group of store.groups) {
for (const operation of groupTurnOperations.get(group.id) ?? []) {
- if (!operation.cancelled && operation.botIds.has(botId)) {
- return { group, threadId: operation.threadId };
- }
+ if (!operation.cancelled && operation.botIds.has(botId) && !turns.has(operation.threadId)) turns.set(operation.threadId, { group, threadId: operation.threadId });
}
for (const [threadId, speaker] of groupSpeakers) {
- if (speaker.botId !== botId) continue;
+ if (speaker.botId !== botId || turns.has(threadId)) continue;
const ownsThread = group.dm
? group.threadId === threadId
: Boolean(store.groupTaskByThread(group.id, threadId));
- if (ownsThread) return { group, threadId };
+ if (ownsThread) turns.set(threadId, { group, threadId });
}
- if (group.busyBotId === botId) {
- return { 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 null;
+ 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 groupWithThread = (group: GroupRecord) => {
@@ -4993,7 +5006,7 @@ const watchdog = new TurnWatchdog({
stopScreenPoller(currentBot.id, turn.threadId);
vpsThreadEnded(currentBot.id, turn.threadId);
if (store.taskByThread(currentBot.id, turn.threadId)) store.setTaskActivity(currentBot.id, turn.threadId, "idle");
- else store.setActivity(currentBot.id, "idle");
+ else store.setActivity(currentBot.id, "idle", turn.threadId);
directTurnBots.delete(turn.threadId);
// Stands in for the missing turn.completed: release everything queued behind this bot.
drainQueuedSends();
@@ -6553,7 +6566,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 (asker.busy) store.setActivity(asker.id, "waiting-on-you");
+ else if (store.roomActivity(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(
@@ -6572,7 +6585,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 && turnWaitedOnPerson(waiting)) store.setActivity(waiting.id, "working");
+ } else if (!bot && waiting && turnWaitedOnPerson(store.roomActivity(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);
@@ -6802,7 +6815,7 @@ bus.subscribe((event: RuntimeEvent) => {
const remaining = group ? activeGroupSpeaker(group.id) : undefined;
if (group) markGroupThreadUnreadAfterTurn(store, group.id, event.threadId, remaining?.botId ?? null);
const speakingBot = store.bot(speaker.botId);
- if (speakingBot?.busy) store.setActivity(speakingBot.id, "idle");
+ if (speakingBot?.busy) store.setActivity(speakingBot.id, "idle", event.threadId);
}
if (!bot) fileIncident();
break;
@@ -7038,7 +7051,7 @@ function drainQueuedSendsNow() {
}).catch(reject);
}),
// Provider completion can precede its dispatch promise: keep the queue until that exact handshake releases its claim.
- (botId, threadId, head) => threadBusy(botId, threadId) || botAtThreadCapacity(botId, head.peerAsk ? undefined : threadId, Boolean(head.peerAsk)) || roomTurnHolds(activeGroupTurnForBot(botId), threadId, !head.peerAsk)
+ (botId, threadId, head) => threadBusy(botId, threadId) || botAtThreadCapacity(botId, head.peerAsk ? undefined : threadId, Boolean(head.peerAsk)) || roomTurnHolds(activeGroupTurnForBot(botId, threadId), threadId, !head.peerAsk)
|| directRootQueued(threadId) || (!head.peerAsk?.incident && parksBehindCoordination(botId, threadId)),
);
}
@@ -7047,7 +7060,7 @@ async function startOrQueueDirectMessage(botId: string, threadId: string, text:
const decision = admit("direct", {}, {
atCapacity: botAtThreadCapacity(botId, threadId),
threadBusy: threadBusy(botId, threadId),
- groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, true),
+ groupTurn: roomTurnHolds(activeGroupTurnForBot(botId, threadId), threadId, true),
parksBehindCoordination: parksBehindCoordination(botId, threadId),
});
if (decision.action === "queue") {
@@ -7473,7 +7486,7 @@ async function beginTurn(
computerSkipped ??= changing;
}
if (threadBusy(botId, threadId)) throw Object.assign(new Error("this thread is already working — interrupt it first"), { status: 409, code: "thread_busy" });
- if (roomTurnHolds(activeGroupTurnForBot(botId), threadId, opts?.allowRoomTurnElsewhere === true)) {
+ if (roomTurnHolds(activeGroupTurnForBot(botId, threadId), threadId, opts?.allowRoomTurnElsewhere === true)) {
throw Object.assign(new Error("the bot is already working in a channel — wait for it to finish"), { status: 409, code: "thread_busy" });
}
if (botAtThreadCapacity(botId, threadId, Boolean(opts?.coordination || opts?.peerAsk || opts?.commsDepth || opts?.cardContinuation || opts?.computerSelectionContinuation))) {
@@ -8611,15 +8624,17 @@ async function stopBotForEmergencyApprovalDowngrade(botId: string): Promise<void
return;
}
- const groupTurn = activeGroupTurnForBot(bot.id);
- if (groupTurn) {
- revokeInternalCapabilitiesForThread(groupTurn.threadId);
- cancelGroupTurnOperations(groupTurn.group.id, groupTurn.threadId);
+ const groupTurns = groupTurnsForBot(bot.id);
+ if (groupTurns.length) {
+ for (const groupTurn of groupTurns) {
+ revokeInternalCapabilitiesForThread(groupTurn.threadId);
+ cancelGroupTurnOperations(groupTurn.group.id, groupTurn.threadId);
+ }
const results = await Promise.allSettled([
directStop,
- runningTurnInstance(bot, groupTurn.threadId)?.adapter.interruptTurn(groupTurn.threadId),
+ ...groupTurns.map((groupTurn) => runningTurnInstance(bot, groupTurn.threadId)?.adapter.interruptTurn(groupTurn.threadId)),
]);
- closeOpenApprovals(groupTurn.threadId);
+ for (const groupTurn of groupTurns) closeOpenApprovals(groupTurn.threadId);
const failure = results.find((result): result is PromiseRejectedResult => result.status === "rejected");
if (failure) throw failure.reason;
return;
@@ -8875,7 +8890,7 @@ const routineRequests = new RoutineRequestService({
return null;
},
});
-const memberOwnBot = createMemberOwnBot({ store: () => store, routines: () => routines, activeGroupTurnForBot, cancelGroupTurnOperations, revokeInternalCapabilitiesForThread, interruptAllDirectThreads,
+const memberOwnBot = createMemberOwnBot({ store: () => store, routines: () => routines, groupTurnsForBot, cancelGroupTurnOperations, revokeInternalCapabilitiesForThread, interruptAllDirectThreads,
interruptTurn: (bot, threadId) => runningTurnInstance(bot, threadId)?.adapter.interruptTurn(threadId), closeOpenApprovals, deleteBot: (botId) => deleteBotWithLifecycle(botId) });
async function deleteBotWithLifecycle(botId: string, revalidate: () => void = () => {}, setupRequest?: TeamSetupRequest) {
@@ -9089,11 +9104,10 @@ const teamSetupRequests = new TeamSetupRequestService({
mcpServerProblem: (name, botId) => mcpServerProblemFor(cfg.mcpServers, name, botId), ownsThread: (botId, threadId) => Boolean(connectorThread(botId, threadId)),
targetBusy: (botId, sourceThreadId) => {
if (!sourceThreadId) return Boolean(store.bot(botId)?.busy || hasDirectDispatch(botId) || activeGroupTurnForBot(botId) || routines?.activeRunForBot(botId));
- const group = activeGroupTurnForBot(botId);
const run = routines?.activeRunForBot(botId);
return store.tasks(botId).some(task => task.threadId !== sourceThreadId && threadBusy(botId, task.threadId)) ||
[...directTurnDispatchClaims].some(([threadId, claim]) => threadId !== sourceThreadId && claim.botId === botId) ||
- Boolean(group && group.threadId !== sourceThreadId) || Boolean(run && run.threadId !== sourceThreadId);
+ groupTurnsForBot(botId).some((turn) => turn.threadId !== sourceThreadId) || Boolean(run && run.threadId !== sourceThreadId);
},
validateModel: validateModelProposal,
driverCapabilities: driverCapabilitiesFor, deletionRefusal: sharedVm.deletionRefusal,
@@ -9528,8 +9542,8 @@ async function runClaimedGroupMemberTurn(
onDispatchError?.(message);
return true;
}
- // One turn per bot across 1:1 and rooms: the last-line guard for a 1:1 that re-claimed the bot after the member wait settled.
- if (bot.busy) {
+ // 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 (orchestration) {
orchestration.result.outcome = "busy";
return true;
@@ -9741,7 +9755,7 @@ async function runClaimedGroupMemberTurn(
reportDispatchError(message);
return true;
}
- if (readyBot.busy) {
+ if (store.busyForRoomThread(bot.id, threadId) || roomThreadsFull(bot.id, threadId)) {
if (orchestration) {
orchestration.result.outcome = "busy";
return true;
@@ -9756,7 +9770,7 @@ async function runClaimedGroupMemberTurn(
reportDispatchError(message);
return true;
}
- store.setActivity(bot.id, "working");
+ store.setActivity(bot.id, "working", threadId);
roomMemberLock.release(bot.id, threadId);
// Claim cleanup ownership before browser preparation can yield; the finally releases exactly this setup, never a newer turn.
roomSpeaker = { botId: bot.id, name: bot.name, color: bot.color, since: Date.now() };
@@ -10037,13 +10051,13 @@ 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.bot(bot.id)?.busy !== true
+ !store.roomActivity(bot.id, threadId).busy
) {
groupSpeakers.delete(threadId);
const remaining = activeGroupSpeaker(group.id);
markGroupThreadUnreadAfterTurn(store, group.id, threadId, remaining?.botId ?? null);
if (store.bot(bot.id)?.busy) {
- store.setActivity(bot.id, "idle");
+ store.setActivity(bot.id, "idle", threadId);
}
watchdog.settle(threadId);
heldInterrupts.delete(`${threadId}:${bot.id}`);
@@ -10240,7 +10254,7 @@ async function runClaimedGroupMemberTurn(
markGroupThreadUnreadAfterTurn(store, currentGroup?.id ?? group.id, threadId, remaining?.botId ?? null);
const currentBot = store.bot(bot.id);
if (currentBot?.busy) {
- store.setActivity(currentBot.id, "idle");
+ store.setActivity(currentBot.id, "idle", threadId);
}
watchdog.settle(threadId);
drainQueuedSends();
@@ -10264,7 +10278,7 @@ async function runClaimedGroupMemberTurn(
}
const currentBot = store.bot(bot.id);
if (currentBot?.busy) {
- store.setActivity(bot.id, "idle");
+ store.setActivity(bot.id, "idle", threadId);
drainQueuedSends();
}
};
@@ -10277,7 +10291,7 @@ async function runClaimedGroupMemberTurn(
groupSpeakers.delete(threadId);
markGroupThreadUnreadAfterTurn(store, group.id, threadId, activeGroupSpeaker(group.id)?.botId ?? null);
if (store.bot(bot.id)?.busy) {
- store.setActivity(bot.id, "idle");
+ store.setActivity(bot.id, "idle", threadId);
}
if (outcome === "dispatch_failed") {
if (roomSkills.claims) takeRoomSkills(skillAuthoringClaim, hop, bot.id, false);
@@ -10436,7 +10450,7 @@ async function runClaimedGroupMemberTurn(
const remaining = activeGroupSpeaker(group.id);
store.patchGroup(group.id, { busyBotId: remaining?.botId ?? null });
if (store.bot(bot.id)?.busy) {
- store.setActivity(bot.id, "idle");
+ store.setActivity(bot.id, "idle", threadId);
}
drainQueuedSends();
}
@@ -11747,7 +11761,7 @@ async function stopCompanyInstances(ids: string[]) {
watchdog.settle(threadId); closeOpenApprovals(threadId);
groupSpeakers.delete(threadId);
if (group) store.patchGroup(group.id, { busyBotId: activeGroupSpeaker(group.id)?.botId ?? null });
- store.setActivity(bot.id, "idle");
+ store.setActivity(bot.id, "idle", threadId);
}
for (const id of ids) { providerAuthSessions.clearInstance(id); bus.detach(id); }
}
@@ -11844,7 +11858,7 @@ async function reloadProviders(before: Record<string, unknown>) {
groupSpeakers.delete(threadId);
const group = store.groupByThread(threadId);
if (group) store.patchGroup(group.id, { busyBotId: activeGroupSpeaker(group.id)?.botId ?? null });
- store.setActivity(speaker.botId, "idle");
+ store.setActivity(speaker.botId, "idle", threadId);
}
for (const id of changed) providerInstancesChanging.delete(id);
providerFleetReloading = false;
@@ -11968,13 +11982,13 @@ const botPatchRoutes = createBotPatchRoutes({ turnBots: directTurnBots, modelSwi
store, cfg, registry, sessions, browserRuntime, browserLive, memoryUpkeep, cacheKeepWarm, hostedModels, supportsApprovalMode,
routines: () => routines, activeVpsThreads,
hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED,
- broadcast, wireBot, publicGroupState, audienceChanged, storedAvatarExists, requestedTaskBot, threadBusy, activeGroupTurnForBot,
+ broadcast, wireBot, publicGroupState, audienceChanged, storedAvatarExists, requestedTaskBot, threadBusy, activeGroupTurnForBot, groupTurnsForBot,
checkedModelSelection, engineSwitchNeedsAsk, currentBrowserSession, interruptAllDirectThreads, cancelGroupTurnOperations,
revokeInternalCapabilitiesForThread, runningTurnInstance, closeOpenApprovals, assertTeamComputerChangeIdle, forgetTemporaryBrowser, levelOf, team: Boolean(CLOUD_TEAM), mainThreadTasks, chiefChanged: (changed) => chiefRooms.moved(changed), ...(personRooms.personMarkThread ? { personMarkThread: personRooms.personMarkThread, shownThread: (auth: RequestAuth, bot: BotRecord) => memberBot(wireBot(bot), visibleTo(viewerFor(auth))).threadId } : {}),
}); ROUTES.push(botPatchRoutes);
ROUTES.push(createBotLifecycleRoutes({
store, routines: () => routines, interruptAllDirectThreads, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread,
- activeGroupTurnForBot, cancelGroupTurnOperations, runningTurnInstance, closeOpenApprovals, deleteBotWithLifecycle, deleteRefusal: (auth, botId) => memberDeleteRefusal(auth, store.bot(botId), Boolean(CLOUD_TEAM)),
+ groupTurnsForBot, cancelGroupTurnOperations, runningTurnInstance, closeOpenApprovals, deleteBotWithLifecycle, deleteRefusal: (auth, botId) => memberDeleteRefusal(auth, store.bot(botId), Boolean(CLOUD_TEAM)),
}));
const skillsRoutes = createBotSkillsRoutes({ store, cfg, listBotSkills, readBotSkillFile, stagedSkillListing, team: Boolean(CLOUD_TEAM) }); ROUTES.push(createSkillsForAllBotsRoutes({ store, host: allBotsSkills }), skillsRoutes);
ROUTES.push(createEmailRoutes({ service: emailService }));
diff --git a/server/outbound-hold.ts b/server/outbound-hold.ts
index 1fcf4f7ad3..b97bcc8d36 100644
--- a/server/outbound-hold.ts
+++ b/server/outbound-hold.ts
@@ -16,13 +16,13 @@ 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" | "setActivity" | "setTaskActivity" | "taskByThread">;
+ store: Pick<Store, "appendMessage" | "bot" | "messagesFor" | "patchMessage" | "roomActivity" | "setActivity" | "setTaskActivity" | "taskByThread">;
dataDir: string;
outboundRequests: OutboundRequestService;
/** How long a "Send on your behalf?" card waits before it times out. */
holdMs: number;
connectorThread: (botId: string, threadId: string) => { group?: GroupRecord } | null;
- activeGroupTurnForBot: (botId: string) => { threadId: string } | null;
+ activeGroupTurnForBot: (botId: string, threadId?: string) => { threadId: string } | null;
notify: (notification: Notification | null) => void;
}
@@ -75,7 +75,7 @@ export function createOutboundHold(deps: OutboundHoldDeps): OutboundHold {
tool: outboundTool, summary, decision: "card-shown", source: "outbound",
});
if (owner?.group) {
- if (activeGroupTurnForBot(currentSender.id)?.threadId === threadId) store.setActivity(currentSender.id, "waiting-on-you");
+ if (activeGroupTurnForBot(currentSender.id, threadId)?.threadId === threadId) store.setActivity(currentSender.id, "waiting-on-you", threadId);
} else if (store.taskByThread(currentSender.id, threadId)?.busy) {
store.setTaskActivity(currentSender.id, threadId, "waiting-on-you");
}
@@ -83,9 +83,8 @@ export function createOutboundHold(deps: OutboundHoldDeps): OutboundHold {
const answer = await held.answer;
outboundRequests.forget(held.requestId);
if (active()) {
- const waiting = store.bot(currentSender.id);
if (owner?.group) {
- if (activeGroupTurnForBot(currentSender.id)?.threadId === threadId && turnWaitedOnPerson(waiting)) store.setActivity(waiting.id, "working");
+ if (activeGroupTurnForBot(currentSender.id, threadId)?.threadId === threadId && turnWaitedOnPerson(store.roomActivity(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-member-lock.test.ts b/server/room-member-lock.test.ts
index 7b054c7c07..b38776c1dc 100644
--- a/server/room-member-lock.test.ts
+++ b/server/room-member-lock.test.ts
@@ -2,26 +2,27 @@ import { describe, expect, it } from "vitest";
import { RoomMemberLock } from "./room-member-lock.ts";
describe("RoomMemberLock", () => {
- it("lets one room thread hold a bot at a time", () => {
+ it("lets one bot hold several room threads at once", () => {
const lock = new RoomMemberLock();
- expect(lock.claim("scout", "thread-a")).toBe(true);
- expect(lock.claim("scout", "thread-a")).toBe(true);
- expect(lock.claim("scout", "thread-b")).toBe(false);
- expect(lock.holder("scout")).toBe("thread-a");
- expect(lock.heldElsewhere("scout", "thread-b")).toBe(true);
+ lock.claim("scout", "thread-a");
+ lock.claim("scout", "thread-a");
+ lock.claim("scout", "thread-b");
+ expect(lock.threads("scout").sort()).toEqual(["thread-a", "thread-b"]);
+ expect(lock.heldElsewhere("scout", "thread-a")).toBe(true);
+ lock.release("scout", "thread-b");
expect(lock.heldElsewhere("scout", "thread-a")).toBe(false);
- expect(lock.claim("pixel", "thread-b")).toBe(true);
+ expect(lock.heldElsewhere("pixel", "thread-b")).toBe(false);
});
- it("releases only the holder's claim and wakes waiters after the claim is gone", () => {
+ it("releases only that thread's claim and wakes waiters after the claim is gone", () => {
const lock = new RoomMemberLock();
lock.claim("scout", "thread-a");
- const woken: Array<{ botId: string; holder: string | undefined }> = [];
- const stop = lock.onRelease((botId) => woken.push({ botId, holder: lock.holder(botId) }));
+ const woken: Array<{ botId: string; threads: string[] }> = [];
+ const stop = lock.onRelease((botId) => woken.push({ botId, threads: lock.threads(botId) }));
expect(lock.release("scout", "thread-b")).toBe(false);
expect(woken).toEqual([]);
expect(lock.release("scout", "thread-a")).toBe(true);
- expect(woken).toEqual([{ botId: "scout", holder: undefined }]);
+ expect(woken).toEqual([{ botId: "scout", threads: [] }]);
expect(lock.release("scout", "thread-a")).toBe(false);
stop();
lock.claim("scout", "thread-b");
@@ -29,30 +30,18 @@ describe("RoomMemberLock", () => {
expect(woken).toHaveLength(1);
});
- it("hands a freed bot to exactly one of several waiting threads", () => {
- const lock = new RoomMemberLock();
- lock.claim("scout", "thread-a");
- const winners: string[] = [];
- for (const waiter of ["thread-b", "thread-c"]) {
- lock.onRelease((botId) => {
- if (botId === "scout" && lock.claim("scout", waiter)) winners.push(waiter);
- });
- }
- lock.release("scout", "thread-a");
- expect(winners).toEqual(["thread-b"]);
- expect(lock.holder("scout")).toBe("thread-b");
- });
-
it("drops every claim of a thread whose drive ended", () => {
const lock = new RoomMemberLock();
lock.claim("scout", "thread-a");
+ lock.claim("scout", "thread-b");
lock.claim("pixel", "thread-a");
lock.claim("echo", "thread-b");
const woken: string[] = [];
lock.onRelease((botId) => woken.push(botId));
expect(lock.releaseThread("thread-a").sort()).toEqual(["pixel", "scout"]);
expect(woken.sort()).toEqual(["pixel", "scout"]);
- expect(lock.holder("echo")).toBe("thread-b");
+ expect(lock.threads("scout")).toEqual(["thread-b"]);
+ expect(lock.threads("echo")).toEqual(["thread-b"]);
});
it("keeps notifying when one listener throws", () => {
diff --git a/server/room-member-lock.ts b/server/room-member-lock.ts
index a989bdbb99..283293348d 100644
--- a/server/room-member-lock.ts
+++ b/server/room-member-lock.ts
@@ -1,39 +1,41 @@
// Covers the gap before a member turn marks the bot busy: woken waiters must claim in the same synchronous step, or all read the bot as free.
+// One bot may hold several room threads at once; the caller decides how many with its thread limit.
export type RoomMemberReleaseListener = (botId: string) => void;
export class RoomMemberLock {
- private readonly holders = new Map<string, string>();
+ private readonly holders = new Map<string, Set<string>>();
private readonly listeners = new Set<RoomMemberReleaseListener>();
- holder(botId: string): string | undefined {
- return this.holders.get(botId);
+ threads(botId: string): string[] {
+ return [...(this.holders.get(botId) ?? [])];
}
heldElsewhere(botId: string, threadId: string): boolean {
- const holder = this.holders.get(botId);
- return holder !== undefined && holder !== threadId;
+ return this.threads(botId).some((holder) => holder !== threadId);
}
- claim(botId: string, threadId: string): boolean {
- if (this.heldElsewhere(botId, threadId)) return false;
- this.holders.set(botId, threadId);
- return true;
+ claim(botId: string, threadId: string): void {
+ const threads = this.holders.get(botId) ?? new Set<string>();
+ threads.add(threadId);
+ this.holders.set(botId, threads);
}
release(botId: string, threadId: string): boolean {
- if (this.holders.get(botId) !== threadId) return false;
- this.holders.delete(botId);
+ const threads = this.holders.get(botId);
+ if (!threads?.delete(threadId)) return false;
+ if (!threads.size) this.holders.delete(botId);
this.notify(botId);
return true;
}
releaseThread(threadId: string): string[] {
const released: string[] = [];
- for (const [botId, holder] of this.holders) {
- if (holder === threadId) released.push(botId);
+ for (const [botId, threads] of this.holders) {
+ if (!threads.delete(threadId)) continue;
+ released.push(botId);
+ if (!threads.size) this.holders.delete(botId);
}
- for (const botId of released) this.holders.delete(botId);
for (const botId of released) this.notify(botId);
return released;
}
diff --git a/server/room-parallel-threads.e2e.test.ts b/server/room-parallel-threads.e2e.test.ts
index 97e6c7a124..07903e4110 100644
--- a/server/room-parallel-threads.e2e.test.ts
+++ b/server/room-parallel-threads.e2e.test.ts
@@ -9,7 +9,7 @@ import type { WireGroup } from "../shared/wire.ts";
type Message = { role: string; kind: string; text?: string; tool?: { name?: string; ok?: boolean }; from?: { botId: string } };
describe.skipIf(process.platform === "win32")("parallel room threads", () => {
- it("runs threads side by side, stops one thread alone, and queues a shared bot thread by thread", async () => {
+ it("runs threads side by side, stops one thread alone, and runs one bot in several threads at once", async () => {
const gateDir = mkdtempSync(join(tmpdir(), "omb-parallel-threads-"));
const gate = join(gateDir, "finish.gate");
const fixture = await launchVerificationServer({
@@ -51,25 +51,27 @@ describe.skipIf(process.platform === "win32")("parallel room threads", () => {
await expect.poll(async () => (await task(solo.id, soloFirst))?.busyBotId, POLL).toBe(xena.id);
await send(solo.id, soloSecond, "Second thread work");
await send(solo.id, soloThird, "Third thread work");
- for (const threadId of [soloSecond, soloThird]) {
- await expect.poll(async () => (await messages(threadId)).some((message) =>
- message.kind === "activity" && message.tool?.name?.includes("is finishing another conversation")), POLL).toBe(true);
- expect((await task(solo.id, threadId))?.working).toBe(true);
- }
- expect((await room(solo.id)).tasks?.filter((item) => item.busyBotId === xena.id).map((item) => item.threadId)).toEqual([soloFirst]);
+ // One bot works in all three threads at once: none waits for another.
+ await expect.poll(async () => (await room(solo.id)).tasks?.filter((item) => item.busyBotId === xena.id).map((item) => item.threadId).sort(), POLL)
+ .toEqual([soloFirst, soloSecond, soloThird].sort());
+
+ await api("POST", `/api/groups/${solo.id}/interrupt`, { threadId: soloThird });
+ await expect.poll(async () => (await task(solo.id, soloThird))?.working, POLL).toBe(false);
+ expect(await task(solo.id, soloFirst)).toMatchObject({ working: true, busyBotId: xena.id });
+ expect(await task(solo.id, soloSecond)).toMatchObject({ working: true, busyBotId: xena.id });
writeFileSync(gate, "finish");
- for (const threadId of [soloFirst, soloSecond, soloThird]) {
+ for (const threadId of [soloFirst, soloSecond]) {
// on failure, name what the thread holds instead (a skip, a stale chip)
await expect.poll(() => replied(threadId, xena.id), POLL).toBe(true).catch(async (error) => {
throw new Error(`${threadId}: ${JSON.stringify((await messages(threadId)).map((m) => [m.role, m.kind, m.text?.slice(0, 80), m.tool?.name]))}\n${error}`);
});
}
await expect.poll(async () => (await room(solo.id)).tasks?.some((item) => item.working || item.busyBotId), POLL).toBe(false);
- for (const threadId of [soloSecond, soloThird]) {
+ await expect.poll(async () => (await fleet()).bots.find((bot) => bot.id === xena.id)?.busy, POLL).toBe(false);
+ for (const threadId of [soloFirst, soloSecond, soloThird]) {
const transcript = await messages(threadId);
- expect(transcript.filter((message) => message.kind === "activity" && /skipped/.test(message.tool?.name ?? ""))).toEqual([]);
- expect(transcript.find((message) => message.tool?.name?.includes("is finishing another conversation"))?.tool?.ok).toBe(true);
+ expect(transcript.filter((message) => message.kind === "activity" && /skipped|is finishing another conversation/.test(message.tool?.name ?? ""))).toEqual([]);
}
rmSync(gate);
diff --git a/server/routes/bot-lifecycle.ts b/server/routes/bot-lifecycle.ts
index 6d6ba00773..3b11affbd6 100644
--- a/server/routes/bot-lifecycle.ts
+++ b/server/routes/bot-lifecycle.ts
@@ -10,7 +10,7 @@ export interface BotLifecycleRouteDeps {
interruptAllDirectThreads(botId: string): Promise<void>;
cancelDirectTurnDispatch(botId: string, expectedThreadId?: string): unknown;
revokeInternalCapabilitiesForThread(threadId: string): void;
- activeGroupTurnForBot(botId: string): { group: GroupRecord; threadId: string } | null;
+ groupTurnsForBot(botId: string): { group: GroupRecord; threadId: string }[];
cancelGroupTurnOperations(groupId: string, threadId: string): void;
runningTurnInstance(bot: BotRecord | null | undefined, threadId: string): ReturnType<ProviderRegistry["get"]>;
closeOpenApprovals(threadId: string): void;
@@ -22,7 +22,7 @@ export interface BotLifecycleRouteDeps {
export function createBotLifecycleRoutes(deps: BotLifecycleRouteDeps): RouteHandler {
const {
- store, interruptAllDirectThreads, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread, activeGroupTurnForBot,
+ store, interruptAllDirectThreads, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread, groupTurnsForBot,
cancelGroupTurnOperations, runningTurnInstance, closeOpenApprovals, deleteBotWithLifecycle,
} = deps;
return async ({ req, res, path, method, auth, json }) => {
@@ -45,8 +45,7 @@ export function createBotLifecycleRoutes(deps: BotLifecycleRouteDeps): RouteHand
}
await routines!.cancelRun(routineRun.id);
}
- const groupTurn = activeGroupTurnForBot(bot.id);
- if (groupTurn) {
+ for (const groupTurn of groupTurnsForBot(bot.id)) {
cancelGroupTurnOperations(groupTurn.group.id, groupTurn.threadId);
revokeInternalCapabilitiesForThread(groupTurn.threadId);
await runningTurnInstance(bot, groupTurn.threadId)?.adapter.interruptTurn(groupTurn.threadId).catch(() => {});
diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.ts
index 4ad196417a..d12fe27280 100644
--- a/server/routes/bot-messages.ts
+++ b/server/routes/bot-messages.ts
@@ -93,7 +93,7 @@ export interface BotMessageRouteDeps {
threadBusy(botId: string, threadId: string): boolean;
botAtThreadCapacity(botId: string): boolean;
parksBehindCoordination(botId: string, threadId: string): boolean;
- activeGroupTurnForBot(botId: string): { group: GroupRecord; threadId: string } | null;
+ activeGroupTurnForBot(botId: string, threadId?: string): { group: GroupRecord; threadId: string } | null;
runningTurnInstance(bot: BotRecord | null | undefined, threadId: string): RunningInstance;
engineSteersImages(instance: RunningInstance | undefined): boolean;
resolveReplyTarget(threadId: string, value: unknown): Message | undefined;
@@ -871,7 +871,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
return json(res, 200, { ok: true });
}
const instance = registry.get((botForThread(bot.id, expectedThreadId ?? bot.threadId) ?? bot).modelSelection.instanceId);
- const busyGroup = activeGroupTurnForBot(bot.id);
+ const busyGroup = activeGroupTurnForBot(bot.id, expectedThreadId);
if (busyGroup) {
if (expectedThreadId !== undefined && busyGroup.threadId !== expectedThreadId) {
return json(res, 409, userError("serverError.chat.busyInRoom", { room: busyGroup.group.name }));
diff --git a/server/routes/bot-patch.test.ts b/server/routes/bot-patch.test.ts
index 9e06fba33d..43646d7f29 100644
--- a/server/routes/bot-patch.test.ts
+++ b/server/routes/bot-patch.test.ts
@@ -63,6 +63,7 @@ function fixture(extra: Partial<BotPatchRouteDeps> = {}) {
levelOf: () => "chat",
mainThreadTasks: (botId: string) => store.tasks(botId).filter((task) => !privateThreads.has(task.threadId)),
activeGroupTurnForBot: () => null,
+ groupTurnsForBot: () => [],
...extra,
} as unknown as BotPatchRouteDeps;
const handler = createBotPatchRoutes(deps);
diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.ts
index 9a664d9b27..ff6932a872 100644
--- a/server/routes/bot-patch.ts
+++ b/server/routes/bot-patch.ts
@@ -71,6 +71,7 @@ export interface BotPatchRouteDeps {
requestedTaskBot(botId: string, rawThreadId: unknown): BotRecord;
threadBusy(botId: string, threadId: string): boolean;
activeGroupTurnForBot(botId: string): { group: GroupRecord; threadId: string } | null;
+ groupTurnsForBot(botId: string): { group: GroupRecord; threadId: string }[];
checkedModelSelection(raw: unknown, current?: { selection: ModelSelection; busy: boolean }, requireAvailableModel?: boolean): ModelSelectionCheck;
engineSwitchNeedsAsk(mode: ApprovalMode, from: ModelSelection, to: ModelSelection): boolean;
currentBrowserSession(botId: string, profile: string | undefined): string;
@@ -104,7 +105,7 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
const {
store, cfg, registry, sessions, browserRuntime, browserLive, memoryUpkeep, cacheKeepWarm, hostedModels, supportsApprovalMode, activeVpsThreads,
hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED,
- broadcast, wireBot, publicGroupState, audienceChanged, storedAvatarExists, requestedTaskBot, threadBusy, activeGroupTurnForBot,
+ broadcast, wireBot, publicGroupState, audienceChanged, storedAvatarExists, requestedTaskBot, threadBusy, activeGroupTurnForBot, groupTurnsForBot,
checkedModelSelection, engineSwitchNeedsAsk, currentBrowserSession, interruptAllDirectThreads, cancelGroupTurnOperations,
revokeInternalCapabilitiesForThread, runningTurnInstance, closeOpenApprovals, assertTeamComputerChangeIdle, forgetTemporaryBrowser,
} = deps;
@@ -677,8 +678,7 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
await interruptAllDirectThreads(existingBot.id);
const routine = routines!.activeBotRunForBot(existingBot.id);
if (routine) await routines!.cancelRun(routine.id);
- const groupTurn = activeGroupTurnForBot(existingBot.id);
- if (groupTurn) {
+ for (const groupTurn of groupTurnsForBot(existingBot.id)) {
cancelGroupTurnOperations(groupTurn.group.id, groupTurn.threadId);
revokeInternalCapabilitiesForThread(groupTurn.threadId);
await runningTurnInstance(existingBot, groupTurn.threadId)?.adapter.interruptTurn(groupTurn.threadId).catch(() => {});
diff --git a/server/store.ts b/server/store.ts
index 0ebf67153b..c095cb25bc 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -266,8 +266,8 @@ export class Store {
private registeringInitialSections = true;
/** Where bots, rooms and their threads are saved (server/registry-store.ts). */
private readonly registry: RegistryStore = new JsonRegistry();
- /** Clearing this slot must not clear a concurrently running task's activity. */
- private legacyActivities = new Map<string, BotActivity>();
+ /** 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>>();
constructor(
defaultSelection: () => ModelSelection,
@@ -1587,11 +1587,15 @@ export class Store {
return { ok: true, bots: this.bots.filter(bot => ids.has(bot.id)) };
}
- setActivity(botId: string, activity: BotActivity): BotRecord | null {
+ setActivity(botId: string, activity: BotActivity, threadId = ""): BotRecord | null {
const bot = this.own(botId);
if (!bot) return null;
- if ((this.legacyActivities.get(botId) ?? "idle") === activity) return bot;
- this.legacyActivities.set(botId, activity);
+ 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);
this.refreshBotActivity(bot);
this.emit({ type: "bot", botId });
return bot;
@@ -1618,10 +1622,30 @@ export class Store {
}
private refreshBotActivity(bot: BotRecord) {
- const activities = [this.legacyActivities.get(bot.id), ...(bot.tasks ?? []).map((task) => task.activity)];
+ const legacy = [...(this.legacyActivities.get(bot.id)?.values() ?? [])];
+ 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 = ACTIVITY_BUSY.has(this.legacyActivities.get(bot.id) ?? "idle") || (bot.tasks ?? []).some((task) => task.busy);
+ 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);
}
/** Makes `id` its scope's one Chief (its owner's on a Team Cloud, else its department's), or with no `id` leaves