Skip to content

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

fix(rooms): drop a speaker whose turn is no longer live

erywimb239a0fc64ad
diff --git a/server/host/room-speaker.test.ts b/server/host/room-speaker.test.ts
new file mode 100644
index 0000000000..58347ba52f
--- /dev/null
+++ b/server/host/room-speaker.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createRoomSpeakers, forgetStaleSpeakers, ROOM_SPEAKER_GRACE_MS, type RoomSpeaker } from "./room-speaker.ts";
+
+const speaker = (over: Partial<RoomSpeaker> = {}): RoomSpeaker => ({ botId: "bot-ada", name: "Ada", color: "blue", since: 0, ...over });
+
+function fixture(speakers: Array<[string, RoomSpeaker]>, live: { engine?: string[]; liveTurn?: string[]; settling?: string[]; operation?: string[]; busy?: string[]; now?: number; graceMs?: number } = {}) {
+ const map = new Map(speakers);
+ const forget = vi.fn();
+ const forgotten = forgetStaleSpeakers(map, {
+ engine: (threadId) => (live.engine ?? []).includes(threadId),
+ liveTurn: (threadId) => (live.liveTurn ?? []).includes(threadId),
+ settling: (threadId) => (live.settling ?? []).includes(threadId),
+ operation: (threadId) => (live.operation ?? []).includes(threadId),
+ botBusy: (botId) => (live.busy ?? []).includes(botId),
+ now: () => live.now ?? ROOM_SPEAKER_GRACE_MS,
+ ...(live.graceMs === undefined ? {} : { graceMs: live.graceMs }),
+ forget,
+ });
+ return { map, forget, forgotten };
+}
+
+describe("a room's stale speaker", () => {
+ it("keeps an entry while its engine, live turn, settling turn, operation, or bot still holds the room", () => {
+ for (const live of [{ engine: ["t1"] }, { liveTurn: ["t1"] }, { settling: ["t1"] }, { operation: ["t1"] }, { busy: ["bot-ada"] }]) {
+ const { map, forget } = fixture([["t1", speaker()]], live);
+ expect(map.has("t1"), JSON.stringify(live)).toBe(true);
+ expect(forget).not.toHaveBeenCalled();
+ }
+ });
+
+ it("keeps an entry through setup, and one with no recorded start, rather than guessing", () => {
+ expect(fixture([["t1", speaker({ since: 900 })]], { now: 1_000 }).forgotten).toEqual([]);
+ expect(fixture([["t1", speaker({ since: undefined })]], { now: 1e9 }).forgotten).toEqual([]);
+ });
+
+ it("forgets an entry with nothing live once its grace has passed", () => {
+ const { map, forget, forgotten } = fixture([["t1", speaker({ since: 0 })]], { now: ROOM_SPEAKER_GRACE_MS });
+ expect(forgotten).toEqual([{ threadId: "t1", speaker: speaker({ since: 0 }) }]);
+ expect(map.has("t1")).toBe(false);
+ expect(forget).toHaveBeenCalledExactlyOnceWith("t1", speaker({ since: 0 }));
+ });
+
+ it("forgets only the stale entries, and honours a caller's grace", () => {
+ const { map, forgotten } = fixture([
+ ["stale", speaker({ since: 0 })],
+ ["live", speaker({ botId: "bot-ops", since: 0 })],
+ ["recent", speaker({ botId: "bot-kim", since: 980 })],
+ ], { busy: ["bot-ops"], now: 1_000, graceMs: 50 });
+ expect(forgotten.map((entry) => entry.threadId)).toEqual(["stale"]);
+ expect([...map.keys()]).toEqual(["live", "recent"]);
+ });
+});
+
+describe("a room's speaker registry", () => {
+ const NOW = 1_000_000;
+ function registry() {
+ const speakers = new Map<string, RoomSpeaker>();
+ const operations = new Map<string, Set<{ cancelled: boolean; threadId: string }>>();
+ const groups = new Map([["room-1", { id: "room-1", threadId: "room-main" }]]);
+ const tasks = new Map([["room-1", [{ threadId: "room-task" }]]]);
+ const forget = vi.fn();
+ const rooms = createRoomSpeakers({
+ speakers, operations, forget,
+ group: (id) => groups.get(id),
+ groupTasks: (id) => tasks.get(id) ?? [],
+ groupByThread: (threadId) => [...groups.values()].find((group) => group.threadId === threadId || (tasks.get(group.id) ?? []).some((task) => task.threadId === threadId)),
+ engine: () => false, liveTurn: () => false, settling: () => false, botBusy: () => false, now: () => NOW,
+ });
+ return { speakers, operations, forget, rooms };
+ }
+
+ it("holds a room thread for its speaker or for work still running on it, never for cancelled work", () => {
+ const { speakers, operations, rooms } = registry();
+ expect(rooms.working("room-1", "room-main")).toBe(false);
+ speakers.set("room-main", speaker({ since: NOW }));
+ expect(rooms.working("room-1", "room-main")).toBe(true);
+ speakers.clear();
+ operations.set("room-1", new Set([{ cancelled: true, threadId: "room-main" }]));
+ expect(rooms.working("room-1", "room-main")).toBe(false);
+ operations.get("room-1")!.add({ cancelled: false, threadId: "room-main" });
+ expect(rooms.working("room-1", "room-main")).toBe(true);
+ });
+
+ it("names the main thread's speaker first, then a task thread's", () => {
+ const { speakers, rooms } = registry();
+ expect(rooms.active("room-1")).toBeUndefined();
+ const task = speaker({ botId: "bot-ops" });
+ speakers.set("room-task", task);
+ expect(rooms.active("room-1")).toEqual(task);
+ const main = speaker({ botId: "bot-ada" });
+ speakers.set("room-main", main);
+ expect(rooms.active("room-1")).toEqual(main);
+ expect(rooms.active("no-such-room")).toBeUndefined();
+ });
+
+ it("drops a stale speaker and hands the room to whoever still holds it", () => {
+ const { speakers, forget, rooms } = registry();
+ const stale = speaker({ since: 0 });
+ const remaining = speaker({ botId: "bot-ops", since: NOW });
+ speakers.set("room-main", stale);
+ speakers.set("room-task", remaining);
+ expect(rooms.forgetStale()).toBe(1);
+ expect(speakers.has("room-main")).toBe(false);
+ expect(speakers.get("room-task")).toEqual(remaining);
+ expect(forget).toHaveBeenCalledExactlyOnceWith("room-main", "room-1", stale, remaining);
+ });
+
+ it("drops a speaker for a thread no room owns, without inventing a room to report", () => {
+ const { speakers, forget, rooms } = registry();
+ speakers.set("orphan", speaker({ since: 0 }));
+ expect(rooms.forgetStale()).toBe(1);
+ expect(speakers.has("orphan")).toBe(false);
+ expect(forget).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/host/room-speaker.ts b/server/host/room-speaker.ts
new file mode 100644
index 0000000000..0dfda64c8d
--- /dev/null
+++ b/server/host/room-speaker.ts
@@ -0,0 +1,105 @@
+/** A room's speaker entry, kept while its turn still holds the room. */
+export interface RoomSpeaker {
+ botId: string;
+ name: string;
+ color: string;
+ since?: number;
+}
+
+/** Long enough for setup to reach the engine, short enough that a dead turn does not strand the room. */
+export const ROOM_SPEAKER_GRACE_MS = 10_000;
+
+interface SpeakerLiveness {
+ /** The engine process this turn is running on. */
+ engine(threadId: string): boolean;
+ /** A turn the harness is still following live (`liveTurns`). */
+ liveTurn(threadId: string): boolean;
+ /** A turn that has ended but whose state is still settling. */
+ settling(threadId: string): boolean;
+ /** Queued work this room thread still owns. */
+ operation(threadId: string): boolean;
+ botBusy(botId: string): boolean;
+ now(): number;
+ graceMs?: number;
+}
+
+/** The speakers with no live turn, removed from `speakers` before `forget` is called for each. */
+export function forgetStaleSpeakers(speakers: Map<string, RoomSpeaker>, live: SpeakerLiveness & { forget(threadId: string, speaker: RoomSpeaker): void }): Array<{ threadId: string; speaker: RoomSpeaker }> {
+ const forgotten: Array<{ threadId: string; speaker: RoomSpeaker }> = [];
+ for (const [threadId, speaker] of speakers) {
+ const alive = live.engine(threadId) || live.liveTurn(threadId) || live.settling(threadId) || live.operation(threadId) || live.botBusy(speaker.botId)
+ || speaker.since === undefined || live.now() - speaker.since < (live.graceMs ?? ROOM_SPEAKER_GRACE_MS);
+ if (alive) continue;
+ speakers.delete(threadId);
+ forgotten.push({ threadId, speaker });
+ live.forget(threadId, speaker);
+ }
+ return forgotten;
+}
+
+/** The room shape the registry reads: a group and the threads it owns. */
+export interface RoomSpeakerGroup {
+ id: string;
+ threadId: string;
+}
+
+/** Queued work on a room thread, as the registry reads it. */
+export interface RoomSpeakerOperation {
+ cancelled: boolean;
+ threadId: string;
+}
+
+export interface RoomSpeakersDeps {
+ speakers: Map<string, RoomSpeaker>;
+ operations: Map<string, Set<RoomSpeakerOperation>>;
+ group(groupId: string): RoomSpeakerGroup | undefined;
+ groupTasks(groupId: string): Array<{ threadId: string }>;
+ groupByThread(threadId: string): RoomSpeakerGroup | undefined;
+ engine(threadId: string): boolean;
+ liveTurn(threadId: string): boolean;
+ settling(threadId: string): boolean;
+ botBusy(botId: string): boolean;
+ now(): number;
+ /** After an entry is removed: the room it held, and whoever still holds it once it is gone. */
+ forget(threadId: string, groupId: string, speaker: RoomSpeaker, remaining: RoomSpeaker | undefined): void;
+}
+
+/** A room's speaker entries: who is speaking, what holds a room thread, and the sweep that drops leftovers. */
+export function createRoomSpeakers(deps: RoomSpeakersDeps) {
+ /** The speaker of a room's current thread, else one of its task threads. */
+ const active = (groupId: string): RoomSpeaker | undefined => {
+ const group = deps.group(groupId);
+ if (!group) return undefined;
+ const activeSpeaker = deps.speakers.get(group.threadId);
+ if (activeSpeaker) return activeSpeaker;
+ for (const task of deps.groupTasks(groupId)) {
+ const speaker = deps.speakers.get(task.threadId);
+ if (speaker) return speaker;
+ }
+ return undefined;
+ };
+ /** Whether a room thread is held by a speaker or by queued work still running on it. */
+ const working = (groupId: string, threadId: string): boolean => {
+ if (deps.speakers.has(threadId)) return true;
+ const activeOps = deps.operations.get(groupId);
+ if (activeOps) for (const op of activeOps) if (!op.cancelled && op.threadId === threadId) return true;
+ return false;
+ };
+ /** Drop every speaker with no live turn behind it; returns how many were dropped. */
+ const forgetStale = (): number => forgetStaleSpeakers(deps.speakers, {
+ engine: deps.engine,
+ liveTurn: deps.liveTurn,
+ settling: deps.settling,
+ operation: (threadId) => {
+ const group = deps.groupByThread(threadId);
+ return Boolean(group && [...(deps.operations.get(group.id) ?? [])].some((op) => !op.cancelled && op.threadId === threadId));
+ },
+ botBusy: deps.botBusy,
+ now: deps.now,
+ forget: (threadId, speaker) => {
+ const group = deps.groupByThread(threadId);
+ if (group) deps.forget(threadId, group.id, speaker, active(group.id));
+ },
+ }).length;
+ return { active, working, forgetStale };
+}
diff --git a/server/index.ts b/server/index.ts
index 2d5930c9d1..84139e50b1 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -19,7 +19,7 @@ import { compactionReading } from "./context-budget.ts";
import { autoCompactWindow } from "./drivers/claude.ts";
import { RoomContextTracker, roomResetNote } from "./room-context.ts";
import { createRoomTranscript, GROUP_CONTEXT_MESSAGES } from "./host/room-transcript.ts";
-import { createRoomSessions } from "./host/room-sessions.ts";
+import { createRoomSessions } from "./host/room-sessions.ts"; import { createRoomSpeakers, type RoomSpeaker } from "./host/room-speaker.ts";
import { LentComputers, provenRequestPerson, SharedComputers, sharedComputerOperation } from "./shared-computers.ts"; import { lentScreenResult } from "./lent-screen-guidance.ts"; import { DeviceLinks } from "./device-links.ts"; import { createLentMcp, isLentMcpPath } from "./lent-mcp.ts";
import { cloudHomeLendingRefusal, cloudHomeOwnTurnRefusal, createCloudRoutineAuthors, ownerOnlyConversation } from "./cloud-lending.ts"; import { createOwnHome, oneOwner, selfHostedPersonName } from "./own-home.ts"; import { createPlacesElsewhere } from "./places-elsewhere.ts"; import { createPlacesElsewhereRoutes } from "./routes/places-elsewhere.ts"; import { assertRoomFolder } from "./room-folder.ts"; import { cloudConnectedAppsBrokerUrl, startCloudHomeConnectedApps, stopCloudHomeConnectedApps } from "./cloud-connected-apps.ts"; import { createTeamConnectionsHost } from "./host/team-connections-host.ts"; import { createCloudLendingTurns } from "./host/cloud-lending-turns.ts"; import { createTeamConnectionRoutes } from "./routes/team-connections.ts";
import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";
@@ -3470,7 +3470,19 @@ type GroupTurnOperation = {
// Wider than busyBotId (setup and queued responders too), so polling clients never mistake a handoff for completion.
const groupTurnOperations = new Map<string, Set<GroupTurnOperation>>();
-const groupSpeakers = new Map<string, { botId: string; name: string; color: string; since?: number }>();
+const groupSpeakers = new Map<string, RoomSpeaker>();
+const roomSpeakers = createRoomSpeakers({
+ speakers: groupSpeakers, operations: groupTurnOperations, group: (id) => store.group(id), groupTasks: (id) => store.groupTasks(id), groupByThread: (threadId) => store.groupByThread(threadId),
+ engine: (threadId) => runningTurnEngines.has(threadId), liveTurn: (threadId) => liveTurns.running(threadId) !== undefined, settling: (threadId) => settlingTurns.has(threadId),
+ botBusy: (botId) => Boolean(store.bot(botId)?.busy), now: Date.now,
+ forget: (threadId, groupId, speaker, remaining) => {
+ markGroupThreadUnreadAfterTurn(store, groupId, threadId, remaining?.botId ?? null);
+ store.patchGroup(groupId, { busyBotId: remaining?.botId ?? null });
+ console.warn(`rooms: dropped a stale speaker (${speaker.name}) on ${threadId}${remaining ? `; ${remaining.name} still holds the room` : ""}`);
+ },
+});
+const groupThreadIsWorking = (groupId: string, threadId: string) => roomSpeakers.working(groupId, threadId);
+const activeGroupSpeaker = (groupId: string) => roomSpeakers.active(groupId);
const roomMemberContexts = new RoomContextTracker({
heldUntil: (threadId) => cacheKeepWarmStatus(threadId)?.until,
expired: (threadId) => { const room = store.groupByThread(threadId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); },
@@ -3478,30 +3490,6 @@ const roomMemberContexts = new RoomContextTracker({
/** Holds a member for the thread it was handed to until that turn marks the bot busy. */
const roomMemberLock = new RoomMemberLock();
-function groupThreadIsWorking(groupId: string, threadId: string): boolean {
- if (groupSpeakers.has(threadId)) return true;
- const activeOps = groupTurnOperations.get(groupId);
- if (activeOps) {
- for (const op of activeOps) {
- if (!op.cancelled && op.threadId === threadId) return true;
- }
- }
- return false;
-}
-
-function activeGroupSpeaker(groupId: string): { botId: string; name: string; color: string } | undefined {
- const group = store.group(groupId);
- if (!group) return undefined;
- const activeSpeaker = groupSpeakers.get(group.threadId);
- if (activeSpeaker) return activeSpeaker;
- const tasks = store.groupTasks(groupId);
- for (const task of tasks) {
- const s = groupSpeakers.get(task.threadId);
- if (s) return s;
- }
- return undefined;
-}
-
const goalTurns = createGoalTurns({ retireProviderTurn });
const goalCards = createGoalCards({ store, routines: () => routines, notify, routineSourceOwner, routineSourceThread });
const oneOnOneGoals = createOneOnOneGoals({
@@ -7034,6 +7022,7 @@ function drainQueuedSends() {
}
}
function drainQueuedSendsNow() {
+ roomSpeakers.forgetStale();
automationReports.flush();
drainSteeredMessages(store, (botId, threadId, prompt, userMessage, excludeIds, unattended, head) =>
new Promise<void>((resolve, reject) => {
@@ -15024,6 +15013,7 @@ const pruneDecisionLog = () => {
};
pruneDecisionLog();
setInterval(pruneDecisionLog, 6 * 60 * 60_000).unref();
+setInterval(() => { if (roomSpeakers.forgetStale() > 0) drainQueuedSends(); }, 15_000).unref();
workspaceAccess = createWorkspaceAccess({ sessions, cookieName: SESSION_COOKIE, closeSessionStreams });
// With the bridge's five-second deadline, this bounds stale portal access on quiet streams to fifteen seconds.
const workspaceAccessTimer = workspaceAccess ? setInterval(() => {