Skip to content

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

perf(engines): a key in the composer starts the engine again; archived bots and cross-conversation launch proven

milind-sonife9f53a9cf0c
diff --git a/server/engine-prestart-opened.e2e.test.ts b/server/engine-prestart-opened.e2e.test.ts
index 3773b665d4..c3dff95f23 100644
--- a/server/engine-prestart-opened.e2e.test.ts
+++ b/server/engine-prestart-opened.e2e.test.ts
@@ -8,7 +8,7 @@ import { waitForExit } from "./testing/cleanup.ts";
const alive = (pid: number): boolean => { try { process.kill(pid, 0); return true; } catch { return false; } };
-it("opening a conversation whose engine has closed starts it again, resuming its session, and the next message runs in it", async () => {
+it("opening a conversation whose engine has closed starts it from the bot's last launch in another conversation, resuming its own session, and the next message runs in it; an archived one starts nothing", async () => {
const fixture = await launchVerificationServer();
const { dataDir, url, logPath } = fixture.info;
let server: ChildProcess | undefined;
@@ -20,7 +20,7 @@ it("opening a conversation whose engine has closed starts it again, resuming its
...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),
});
const value = await response.json() as any;
- expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBe(200);
+ expect(response.ok, `${method} ${path}: ${response.status} ${JSON.stringify(value).slice(0, 300)}`).toBe(true);
return value;
};
const control = async (...args: string[]) => {
@@ -31,13 +31,14 @@ it("opening a conversation whose engine has closed starts it again, resuming its
const jsonLines = (file: string): any[] => existsSync(file) ? readFileSync(file, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
const launches = () => (jsonLines(launchesFile) as Array<{ pid: number; argv: string[] }>).filter((launch) => launch.argv.includes("--input-format"));
try {
- // Restarted with an idle time short enough to see the engine close, and without the free-memory reading so the
- // runner's free memory does not decide the outcome.
+ // Restarted with an idle time short enough to see the engine close, without the free-memory reading so the runner's
+ // free memory does not decide the outcome, and with turns not waiting for room (a Linux runner can count as a server
+ // whose engines do, where nothing starts ahead).
await waitForExit(fixture.child, { signal: "SIGTERM" });
const log = openSync(logPath, "a", 0o600);
server = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {
cwd: fileURLToPath(new URL("..", import.meta.url)),
- env: { ...verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), OMB_SESSION_IDLE_MS: "10000", OMB_ENGINE_PRESTART: "unmetered",
+ env: { ...verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), OMB_SESSION_IDLE_MS: "10000", OMB_ENGINE_PRESTART: "unmetered", OMB_TURNS_MAX_RUNNING: "off",
FAKE_CLAUDE_LAUNCHES: launchesFile, FAKE_CLAUDE_PROMPTS: promptsFile, FAKE_CLAUDE_MCP_RECONNECT: join(dataDir, "relists.jsonl") },
stdio: ["ignore", log, log],
});
@@ -47,34 +48,46 @@ it("opening a conversation whose engine has closed starts it again, resuming its
}, { timeout: 30_000 }).toBe(true);
const { bot } = await control("new-bot", "--name", "Prestart bot");
- const threadId = bot.activeTaskId as string;
- const send = async (text: string) => {
+ const first = bot.activeTaskId as string;
+ const second = (await api("POST", `/api/bots/${bot.id}/tasks`, { select: false })).task.threadId as string;
+ const send = async (threadId: string, text: string) => {
await control("send", "--bot", bot.id, "--task", threadId, "--text", text);
expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");
};
- const messages = async () => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];
+ const messages = async (threadId: string) => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];
const closed = () => expect.poll(() => launches().every((launch) => !alive(launch.pid)), { timeout: 30_000, interval: 250 }).toBe(true);
+ const open = (threadId: string) => api("POST", `/api/bots/${bot.id}/tasks/${threadId}?messages=0`);
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 3_000));
- await send("FIRST_PRESTART_1");
- expect(launches(), JSON.stringify(launches())).toHaveLength(1);
+ await send(first, "FIRST_PRESTART_1");
+ // The bot's last launch is now the second conversation's.
+ await send(second, "SECOND_PRESTART_1");
await closed();
+ const launched = launches().length;
- const before = await messages();
- await api("POST", `/api/bots/${bot.id}/tasks/${threadId}?messages=0`);
- await expect.poll(() => launches().length, { timeout: 15_000 }).toBe(2);
- const spare = launches()[1]!;
+ const before = await messages(first);
+ await open(first);
+ await expect.poll(() => launches().length, { timeout: 15_000 }).toBe(launched + 1);
+ const spare = launches().at(-1)!;
expect(spare.argv).toContain("--resume");
+ expect(spare.argv.join(" ")).not.toContain(second);
+ await settle();
expect(alive(spare.pid)).toBe(true);
// Started, and nothing said: no prompt reached the engine, nothing was written to the conversation.
- expect(jsonLines(promptsFile)).toHaveLength(1);
- expect(await messages()).toEqual(before);
-
- await send("SECOND_PRESTART_2");
- expect(launches()).toHaveLength(2);
expect(jsonLines(promptsFile)).toHaveLength(2);
- expect((await messages()).filter((message) => message.role === "user").map((message) => message.text)).toEqual(["FIRST_PRESTART_1", "SECOND_PRESTART_2"]);
- expect((await messages()).findLast((message) => message.role === "bot" && message.kind === "text")?.turnSucceeded).toBe(true);
- evidence.push({ launches: launches(), messages: await messages() });
+ expect(await messages(first)).toEqual(before);
+
+ await send(first, "FIRST_PRESTART_2");
+ expect(launches(), "the message ran in the process started on open").toHaveLength(launched + 1);
+ expect(jsonLines(promptsFile)).toHaveLength(3);
+ expect((await messages(first)).filter((message) => message.role === "user").map((message) => message.text)).toEqual(["FIRST_PRESTART_1", "FIRST_PRESTART_2"]);
+ expect((await messages(first)).findLast((message) => message.role === "bot" && message.kind === "text")?.turnSucceeded).toBe(true);
+
+ await api("PATCH", `/api/bots/${bot.id}/tasks/${second}`, { archivedAt: Date.now() });
+ await open(second);
+ await settle();
+ expect(launches(), "an archived conversation starts nothing").toHaveLength(launched + 1);
+ evidence.push({ launches: launches(), first: await messages(first) });
} finally {
writeFileSync(`${logPath}.prestart-opened.json`, JSON.stringify(evidence, null, 2));
await waitForExit(server, { signal: "SIGTERM" });
diff --git a/server/engine-prestart.test.ts b/server/engine-prestart.test.ts
index 13f9e2aad6..06862bee3c 100644
--- a/server/engine-prestart.test.ts
+++ b/server/engine-prestart.test.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { SendTurnInput } from "./contracts.ts";
import { OPENED_PRESTART_IDLE_MS, PRESTART_IDLE_MS, PRESTART_MOST } from "./drivers/session-idle.ts";
-import { createEnginePrestart, OPENED_AGAIN_AFTER_MS, OPENED_SETTLE_MS, type EnginePrestartDeps, type SessionCredentials } from "./engine-prestart.ts";
+import { createEnginePrestart, OPENED_AGAIN_AFTER_MS, OPENED_SETTLE_MS, prestartClosed, type EnginePrestartDeps, type SessionCredentials } from "./engine-prestart.ts";
const FIRST = "11111111-aaaa-4aaa-8aaa-111111111111";
const NEXT = "22222222-bbbb-4bbb-8bbb-222222222222";
@@ -321,6 +321,18 @@ describe("starting the engine of a conversation a person opens or types in", ()
expect(setup.started).toHaveLength(2);
});
+ it("starts it again at once when the person types in its composer", () => {
+ const setup = afterATurn();
+ opened(setup, NEXT);
+ vi.advanceTimersByTime(OPENED_PRESTART_IDLE_MS + 5_000);
+ setup.held.clear();
+ opened(setup, NEXT);
+ expect(setup.started).toHaveLength(1);
+ setup.prestart.typedIn(NEXT);
+ opened(setup, NEXT);
+ expect(setup.started.map((launch) => launch.threadId)).toEqual([NEXT, NEXT]);
+ });
+
it("starts it again at once after a message was sent there", () => {
const setup = afterATurn();
opened(setup, NEXT);
@@ -380,3 +392,15 @@ describe("starting the engine of a conversation a person opens or types in", ()
expect(setup.started).toEqual([]);
});
});
+
+describe("what is never started ahead", () => {
+ it("an archived bot or conversation, or an engine signed out or unavailable at its last status read", () => {
+ const signedIn = { state: "available", authenticated: true };
+ expect(prestartClosed({}, {}, signedIn)).toBe(false);
+ expect(prestartClosed({}, null, undefined)).toBe(false);
+ expect(prestartClosed({ hidden: true }, {}, signedIn)).toBe(true);
+ expect(prestartClosed({}, { archivedAt: 1 }, signedIn)).toBe(true);
+ expect(prestartClosed({}, {}, { state: "available", authenticated: false })).toBe(true);
+ expect(prestartClosed({}, {}, { state: "unavailable" })).toBe(true);
+ });
+});
diff --git a/server/engine-prestart.ts b/server/engine-prestart.ts
index 3c475ce8dd..2a45598b4d 100644
--- a/server/engine-prestart.ts
+++ b/server/engine-prestart.ts
@@ -79,11 +79,19 @@ function startsOnlyOwnServers(input: SendTurnInput): boolean {
&& !input.guestConfined && !input.mcpFromUserConfig && input.toolScope === undefined;
}
+/** Nothing starts ahead for an archived bot or conversation, or on an engine whose last status read was signed out or
+ * unavailable. */
+export function prestartClosed(bot: { hidden?: boolean }, task: { archivedAt?: number } | null | undefined,
+ engine: { authenticated?: boolean; state?: string } | null | undefined): boolean {
+ return Boolean(bot.hidden) || task?.archivedAt !== undefined || engine?.authenticated === false || engine?.state === "unavailable";
+}
+
const RELEASE_AFTER_MS = 5_000;
/** An open is acted on once the conversation stayed in front of the person this long, so clicking through conversations
* starts nothing, and the switch itself never waits on the work. */
export const OPENED_SETTLE_MS = 1_000;
-/** An opened conversation whose engine went unused is not started again this soon, though the person stays active in it. */
+/** An opened conversation whose engine went unused is not started again this soon on the person's activity alone; typing
+ * in its composer starts it again. */
export const OPENED_AGAIN_AFTER_MS = 15 * 60_000;
/** One launch per bot, for the bots a person wrote to most recently. */
const LAUNCHES_KEPT = 32;
@@ -197,6 +205,11 @@ export function createEnginePrestart(deps: EnginePrestartDeps) {
settling = { threadId, timer };
},
+ /** A person is typing in the conversation: an engine that went unused there before may start again. */
+ typedIn(threadId: string): void {
+ unused.delete(threadId);
+ },
+
/** The conversation's bearers were retired (a Stop, a delete): an engine started ahead with them goes too. */
drop(threadId: string): void {
if (settling?.threadId === threadId) { clearTimeout(settling.timer); settling = null; }
diff --git a/server/index.ts b/server/index.ts
index 4ed2d6ff87..5ca0f9415c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -644,7 +644,7 @@ import { withScopeHint } from "./connector-scope-hint.ts"; import { accountsByAp
import { connectorFileDeps, connectorFileScope, prepareConnectorFiles, withMissingFileHint } from "./connector-files.ts";
import { createConnectorCards } from "./host/connector-cards.ts";
import { createLoginMailCodes } from "./host/login-mail-codes.ts"; import { startEngineSessionSweep } from "./host/engine-session-sweep.ts"; import { createLateToolResults } from "./host/late-tool-results.ts"; import { internalBodyRefusal } from "./host/internal-body-ids.ts";
-import { onThreadMade, onThreadSeen, personAsks as personAskAt, sawThread } from "./thread-presence.ts"; import { bearerForGrants, createEnginePrestart } from "./engine-prestart.ts"; import { prestartAllowed } from "./drivers/session-idle.ts"; import { createWarmSummaryHost, HARNESS_IDLE_FRACTION } from "./host/warm-summary-host.ts";
+import { onThreadMade, onThreadSeen, personAsks as personAskAt, sawThread } from "./thread-presence.ts"; import { bearerForGrants, createEnginePrestart, prestartClosed } from "./engine-prestart.ts"; import { prestartAllowed } from "./drivers/session-idle.ts"; import { createWarmSummaryHost, HARNESS_IDLE_FRACTION } from "./host/warm-summary-host.ts";
const PORT = Number(process.env.OMB_PORT || process.env.OGB_PORT || 8799);
const WEBHOOK_PORT = Number(process.env.OMB_WEBHOOK_PORT || PORT + 1);
@@ -1653,7 +1653,7 @@ const sessionCredentials = new Map<string, Map<string, { grants: string; token:
const enginePrestart = createEnginePrestart({ adapter: (id) => registry.get(id)?.adapter, credentials: sessionCredentials, allowed: prestartAllowed, blank: (threadId) => store.messagesFor(threadId).length === 0, busy: (botId, threadId) => threadBusy(botId, threadId), approval: (botId, threadId) => { const thread = botForThread(botId, threadId); return thread ? approvalModeFor(thread) : null; },
shape: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId), task = store.taskByThread(botId, threadId); return bot && task ? JSON.stringify([bot.modelSelection, approvalModeForTurn(bot, false, threadId), task.projectId ?? null, task.cwd?.includes(threadId) ? null : task.cwd ?? null]) : null; },
folder: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId), instance = bot && registry.get(bot.modelSelection.instanceId); if (!bot || !instance || !supportsWorkspaceFiles(instance.driverKind)) return null; ensureWorkspace(botId, appLanguage()); return ensureTaskWorkspaceWithSkills(botId, threadId, skillsHost.turnImports(bot, threadId, instance)) ?? null; },
- refused: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId); try { assertWithinBudget(cfg, DATA_DIR); } catch { return true; } return !bot || Boolean(bot.approvalGrant) || providerInstancesChanging.has(bot.modelSelection.instanceId) || limitTakeover.stillSignedOut(bot.modelSelection.instanceId) || botAtThreadCapacity(botId, threadId) || Boolean(botHolds.text(botId, threadLanguage(threadId)) ?? starterCaps.pausedText(botId, threadLanguage(threadId), threadId)) || store.taskByThread(botId, threadId)?.archivedAt !== undefined || registry.lastSnapshot(bot.modelSelection.instanceId)?.authenticated === false || registry.lastSnapshot(bot.modelSelection.instanceId)?.state === "unavailable"; }, botOf: (threadId) => store.botByThread(threadId)?.id ?? null, cursor: (botId, threadId, instanceId) => { const task = store.taskByThread(botId, threadId); return task?.lastInstanceId === instanceId ? task.resumeCursors[instanceId] : undefined; } }); onThreadMade(enginePrestart.threadMade); onThreadSeen(enginePrestart.threadSeen);
+ refused: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId); try { assertWithinBudget(cfg, DATA_DIR); } catch { return true; } return !bot || Boolean(bot.approvalGrant) || providerInstancesChanging.has(bot.modelSelection.instanceId) || limitTakeover.stillSignedOut(bot.modelSelection.instanceId) || botAtThreadCapacity(botId, threadId) || Boolean(botHolds.text(botId, threadLanguage(threadId)) ?? starterCaps.pausedText(botId, threadLanguage(threadId), threadId)) || prestartClosed(bot, store.taskByThread(botId, threadId), registry.lastSnapshot(bot.modelSelection.instanceId)); }, botOf: (threadId) => store.botByThread(threadId)?.id ?? null, cursor: (botId, threadId, instanceId) => { const task = store.taskByThread(botId, threadId); return task?.lastInstanceId === instanceId ? task.resumeCursors[instanceId] : undefined; } }); onThreadMade(enginePrestart.threadMade); onThreadSeen(enginePrestart.threadSeen);
function sessionGrants({ generation: _turn, depth: _depth, roomHandoffId: _handoff, skillAuthoring: _skills, ...grants }: Omit<InternalCapability, "orphanExpiresAt">): string {
const thread = botForThread(grants.botId, grants.threadId);
@@ -12039,7 +12039,7 @@ ROUTES.push(createBotMemoryRoutes({
}));
const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: personLanguages.forPlace, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages)); const conversationSharing = createConversationSharing({ team: CLOUD_TEAM, store: () => store, shares: conversationShares, saves: createTeamMemorySaves({ dataDir: DATA_DIR }), starter: (threadId) => threadStarters.get(threadId), audienceOf: teamHost.audienceOf, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), levelOf, levelFor: (person, botId) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }).level(botId), people: () => teamOwners.people?.list() ?? [], nameOf: (email) => teamHost.personName(personKey({ id: "", email })) ?? email, language: (person) => personLanguages.forLine(person), busy: threadBusy, routinesIn: (threadId) => (routines?.listRoutines() ?? []).filter((routine) => routine.sourceThreadId === threadId || routine.resultsThreadId === threadId).length, outside: cloudGuestDriven, audienceChanged: (botId, threadId) => { store.patchTask(botId, threadId, { rewound: true, resumeCursors: {} }); }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, inbox: () => teamMessages.inbox, looking: (email, threadId) => teamPresence.looking(email, threadId), notify, botOf: (threadId) => store.botByThread(threadId)?.id, handTo: (threadId, person) => threadStarters.handTo(threadId, person) }); ROUTES.push(conversationSharing.routes);
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
-const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
+const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId, typing) => { if (!store.botByThread(threadId)) return; if (typing) enginePrestart.typedIn(threadId); sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: async (live) => live ? composio.connectedServices(cfg) : (await composio.sharedConnectedInventory(cfg)).services, offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));
ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true })); const githubSignIn = createGithubSignIn({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), vault: logins, tools: createGhTools({ dataDir: DATA_DIR, personalAllowed: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !botBox.enabled() }), remember: (token) => heldSecrets.remember(token, "password") }); provideGithubSignIn(githubSignIn); ROUTES.push(createGithubSignInRoutes({ signIn: githubSignIn, team: Boolean(CLOUD_TEAM) })); ROUTES.push(createGitCredentialRoutes({ port: PORT, enabled: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !CLOUD_TEAM && !botBox.enabled() }));
ROUTES.push(createRoomHoldRoutes({
diff --git a/server/routes/presence.test.ts b/server/routes/presence.test.ts
index 0979418127..e2198fefe0 100644
--- a/server/routes/presence.test.ts
+++ b/server/routes/presence.test.ts
@@ -6,7 +6,7 @@ import { createPresenceRoutes } from "./presence.ts";
function call(auth: RequestAuth, body: unknown, active = vi.fn(async () => ({ returned: true })), team = false) {
const answers: Array<[number, unknown]> = [];
const heard = vi.fn((_auth: RequestAuth, _language: string) => {});
- const sawChat = vi.fn((_auth: RequestAuth, _threadId: string) => {});
+ const sawChat = vi.fn((_auth: RequestAuth, _threadId: string, _typing: boolean) => {});
const route = createPresenceRoutes({ isOwner: (who) => who.scopes.includes("admin"), active, heard, sawChat, ...(team ? { member: () => ({ returned: false }) } : {}) });
const done = route({
req: {} as never, res: {} as never, url: new URL("http://x/api/presence/active"), path: "/api/presence/active", method: "POST", auth,
@@ -50,7 +50,13 @@ describe("POST /api/presence/active", () => {
const owner = { kind: "loopback", scopes: ["admin", "client"] } as RequestAuth;
const open = call(owner, { source: "desktop", language: "en", threadId: "3f2a-thread_1" });
await open.done;
- expect(open.sawChat).toHaveBeenCalledWith(owner, "3f2a-thread_1");
+ expect(open.sawChat).toHaveBeenCalledWith(owner, "3f2a-thread_1", false);
+ const typing = call(owner, { source: "desktop", language: "en", threadId: "t1", typing: true });
+ await typing.done;
+ expect(typing.sawChat, "a key in its composer").toHaveBeenCalledWith(owner, "t1", true);
+ const truthy = call(owner, { threadId: "t1", typing: "yes" });
+ await truthy.done;
+ expect(truthy.sawChat).toHaveBeenCalledWith(owner, "t1", false);
for (const threadId of ["../etc", "x".repeat(101), 42, ""]) {
const odd = call(owner, { threadId });
await odd.done;
@@ -62,7 +68,7 @@ describe("POST /api/presence/active", () => {
const member = { kind: "loopback", scopes: ["client"] } as RequestAuth;
const onTeam = call(member, { threadId: "t1" }, undefined, true);
await onTeam.done;
- expect(onTeam.sawChat, "a User's open chat is in front of them as an admin's is").toHaveBeenCalledWith(member, "t1");
+ expect(onTeam.sawChat, "a User's open chat is in front of them as an admin's is").toHaveBeenCalledWith(member, "t1", false);
const guest = call(member, { threadId: "t1" });
await guest.done;
expect(guest.sawChat, "a My Cloud guest's is not the owner's").not.toHaveBeenCalled();
diff --git a/server/routes/presence.ts b/server/routes/presence.ts
index 11ae1705a3..a34025bd80 100644
--- a/server/routes/presence.ts
+++ b/server/routes/presence.ts
@@ -13,15 +13,15 @@ export interface PresenceRouteDeps {
heard?(auth: RequestAuth, language: string): void;
/** The conversation open in the app while a person who counts was active (the owner, or on a Team Cloud any
* member): it is the one in front of them. */
- sawChat?(auth: RequestAuth, threadId: string): void;
+ sawChat?(auth: RequestAuth, threadId: string, typing: boolean): void;
}
const IANA_ZONE = /^(?:UTC|[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)+)$/;
const LANGUAGE_TAG = /^[a-z]{2,3}(?:-[a-z0-9]{2,8}){0,3}$/i;
const THREAD_ID = /^[\w-]{1,100}$/;
-/** POST /api/presence/active {source, timeZone, language, threadId}: the person opened or used the app, with that
- * conversation open. Only the owner's counts. */
+/** POST /api/presence/active {source, timeZone, language, threadId, typing}: the person opened or used the app, with that
+ * conversation open (`typing`: a key in its composer). Only the owner's counts. */
export function createPresenceRoutes(deps: PresenceRouteDeps): RouteHandler {
return async ({ req, res, path, method, auth, json, readBody }) => {
if (method !== "POST" || path !== "/api/presence/active") return PASS;
@@ -32,7 +32,7 @@ export function createPresenceRoutes(deps: PresenceRouteDeps): RouteHandler {
const language = typeof given.language === "string" && LANGUAGE_TAG.test(given.language) ? given.language.toLowerCase() : undefined;
const counts = Boolean(deps.member) || deps.isOwner(auth);
if (language && counts) deps.heard?.(auth, language);
- if (counts && typeof given.threadId === "string" && THREAD_ID.test(given.threadId)) deps.sawChat?.(auth, given.threadId);
+ if (counts && typeof given.threadId === "string" && THREAD_ID.test(given.threadId)) deps.sawChat?.(auth, given.threadId, given.typing === true);
if (deps.member) return json(res, 200, { ok: true, ...deps.member(auth, language) });
// A guest's activation is not the person's: answered, never recorded.
if (!deps.isOwner(auth)) return json(res, 200, { ok: true, returned: false });
diff --git a/src/hooks/use-presence.test.ts b/src/hooks/use-presence.test.ts
index 23328e4db6..fe116f36be 100644
--- a/src/hooks/use-presence.test.ts
+++ b/src/hooks/use-presence.test.ts
@@ -39,18 +39,18 @@ function rerender(state: AppState, dispatch: (action: Action) => void) {
}
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
-type Listener = { scope: "window" | "document"; name: string; fn: () => void; options?: unknown };
+type Listener = { scope: "window" | "document"; name: string; fn: (event?: unknown) => void; options?: unknown };
function stubDom(options: { visibilityState?: "visible" | "hidden"; ogb?: unknown } = {}) {
const added: Listener[] = [];
const removed: Listener[] = [];
const target = (scope: Listener["scope"]) => ({
- addEventListener: (name: string, fn: () => void, listenerOptions?: unknown) => { added.push({ scope, name, fn, options: listenerOptions }); },
- removeEventListener: (name: string, fn: () => void) => { removed.push({ scope, name, fn }); },
+ addEventListener: (name: string, fn: (event?: unknown) => void, listenerOptions?: unknown) => { added.push({ scope, name, fn, options: listenerOptions }); },
+ removeEventListener: (name: string, fn: (event?: unknown) => void) => { removed.push({ scope, name, fn }); },
});
const doc = { ...target("document"), visibilityState: options.visibilityState ?? "visible" };
vi.stubGlobal("window", { ogb: options.ogb, ...target("window") });
vi.stubGlobal("document", doc);
- const fire = (name: string) => { for (const listener of added.filter((entry) => entry.name === name)) listener.fn(); };
+ const fire = (name: string, event?: unknown) => { for (const listener of added.filter((entry) => entry.name === name)) listener.fn(event); };
return { added, removed, doc, fire };
}
@@ -173,6 +173,32 @@ describe("usePresence", () => {
}
});
+ it("says at once that the person is typing in the open chat's composer, then once a minute at most while they type there", async () => {
+ const dom = stubDom();
+ const now = vi.spyOn(Date, "now").mockReturnValue(1_000_000);
+ fixture.api.mockResolvedValue({ ok: true, returned: false });
+ render(loaded, vi.fn());
+ await flush();
+ const inComposer = { closest: (selector: string) => (selector === "[data-composer-row]" ? {} : null) };
+ const elsewhere = { closest: () => null };
+ const bodies = () => fixture.api.mock.calls.map(([, init]) => JSON.parse((init as { body: string }).body));
+ now.mockReturnValue(1_000_000 + 5_000);
+ dom.fire("keydown", { type: "keydown", target: elsewhere });
+ await flush();
+ expect(fixture.api).toHaveBeenCalledTimes(1);
+ dom.fire("keydown", { type: "keydown", target: inComposer });
+ await flush();
+ expect(bodies()[1]).toMatchObject({ threadId: "chief-main", typing: true });
+ now.mockReturnValue(1_000_000 + 30_000);
+ dom.fire("keydown", { type: "keydown", target: inComposer });
+ await flush();
+ expect(fixture.api).toHaveBeenCalledTimes(2);
+ now.mockReturnValue(1_000_000 + 65_000);
+ dom.fire("keydown", { type: "keydown", target: inComposer });
+ await flush();
+ expect(bodies()[2]).toMatchObject({ threadId: "chief-main", typing: true });
+ });
+
it.each([
["another bot", { ...team, selectedId: "scout" }],
["another of the Chief's threads", { ...team, bots: [{ ...chief, switchingTo: "chief-2" }, scout] }],
diff --git a/src/hooks/use-presence.ts b/src/hooks/use-presence.ts
index cb2f6c1b1f..1802fe6e8f 100644
--- a/src/hooks/use-presence.ts
+++ b/src/hooks/use-presence.ts
@@ -1,6 +1,6 @@
import { useEffect, useRef } from "react";
import { useLanguageChoice } from "@/lib/language-preference";
-import { duePing, openTarget, presenceBody, shownLanguage } from "@/lib/presence-client";
+import { composerKey, duePing, dueTyping, openTarget, presenceBody, shownLanguage } from "@/lib/presence-client";
import { useShowThreads } from "@/lib/thread-preferences";
import { existingThreadTarget } from "@/lib/thread-target";
import { openThread } from "@/state/thread-navigation";
@@ -25,6 +25,7 @@ function openChat(state: AppState): string | undefined {
export function usePresence(state: AppState, dispatch: (action: Action) => void): void {
const showThreads = useShowThreads();
const lastPing = useRef<number | null>(null);
+ const lastTyping = useRef<{ threadId: string; at: number } | null>(null);
const language = shownLanguage(state.config?.language, useLanguageChoice());
const latest = useRef({ state, dispatch, showThreads, language });
latest.current = { state, dispatch, showThreads, language };
@@ -32,20 +33,26 @@ export function usePresence(state: AppState, dispatch: (action: Action) => void)
const pingNow = useRef<() => void>(() => {});
useEffect(() => {
if (!state.hydrated) return;
- const ping = (force = false) => {
+ const ping = (force = false, typing = false) => {
const now = Date.now();
if (!force && !duePing(lastPing.current, now)) return;
lastPing.current = now;
const sentFrom = selection(latest.current.state);
sentLanguage.current = latest.current.language;
- const body = presenceBody(Intl.DateTimeFormat().resolvedOptions().timeZone, sentLanguage.current, openChat(latest.current.state));
+ const chat = openChat(latest.current.state);
+ if (typing && chat) lastTyping.current = { threadId: chat, at: now };
+ const body = presenceBody(Intl.DateTimeFormat().resolvedOptions().timeZone, sentLanguage.current, chat, typing);
void api("/api/presence/active", { method: "POST", body: JSON.stringify(body) }).then((answer) => {
const live = latest.current;
const target = existingThreadTarget(openTarget(answer), live.state);
if (target && !live.state.newChat && selection(live.state) === sentFrom) openThread(live.dispatch, target, live.state, live.showThreads);
}, () => {});
};
- const onActivity = () => ping();
+ const onActivity = (event: Event) => {
+ const chat = composerKey(event) ? openChat(latest.current.state) : undefined;
+ if (chat && dueTyping(lastTyping.current, chat, Date.now())) ping(true, true);
+ else ping();
+ };
const onVisible = () => { if (document.visibilityState === "visible") ping(); };
pingNow.current = () => ping(true);
onVisible();
diff --git a/src/lib/presence-client.test.ts b/src/lib/presence-client.test.ts
index f9475c6d4c..1827986d59 100644
--- a/src/lib/presence-client.test.ts
+++ b/src/lib/presence-client.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { setLanguageChoice } from "./language-preference";
-import { duePing, openTarget, PRESENCE_MIN_INTERVAL_MS, presenceBody, shownLanguage } from "./presence-client";
+import { composerKey, duePing, dueTyping, openTarget, PRESENCE_MIN_INTERVAL_MS, presenceBody, shownLanguage } from "./presence-client";
describe("presence client", () => {
it("sends the device's zone and the app's language with the desktop source", () => {
@@ -22,6 +22,27 @@ describe("presence client", () => {
expect(duePing(1_000, 1_000 + PRESENCE_MIN_INTERVAL_MS)).toBe(true);
});
+ it("says typing only with the chat it is typed in", () => {
+ expect(presenceBody("UTC", "en", "thread-1", true)).toEqual({ source: "desktop", timeZone: "UTC", language: "en", threadId: "thread-1", typing: true });
+ expect(presenceBody("UTC", "en", undefined, true)).toEqual({ source: "desktop", timeZone: "UTC", language: "en" });
+ });
+
+ it("knows a key in a chat's composer from any other key or event", () => {
+ const composer = { closest: (selector: string) => (selector === "[data-composer-row]" ? {} : null) };
+ expect(composerKey({ type: "keydown", target: composer as unknown as EventTarget })).toBe(true);
+ expect(composerKey({ type: "pointerdown", target: composer as unknown as EventTarget })).toBe(false);
+ expect(composerKey({ type: "keydown", target: { closest: () => null } as unknown as EventTarget })).toBe(false);
+ expect(composerKey({ type: "keydown", target: null })).toBe(false);
+ expect(composerKey(undefined)).toBe(false);
+ });
+
+ it("tells typing in a chat at once, then once a minute there, and at once in another chat", () => {
+ expect(dueTyping(null, "t1", 1_000)).toBe(true);
+ expect(dueTyping({ threadId: "t1", at: 1_000 }, "t1", 1_000 + PRESENCE_MIN_INTERVAL_MS - 1)).toBe(false);
+ expect(dueTyping({ threadId: "t1", at: 1_000 }, "t2", 1_001)).toBe(true);
+ expect(dueTyping({ threadId: "t1", at: 1_000 }, "t1", 1_000 + PRESENCE_MIN_INTERVAL_MS)).toBe(true);
+ });
+
it("reads only a well-formed open target from the answer", () => {
expect(openTarget({ ok: true, returned: true, open: { botId: "chief", threadId: "t1" } })).toEqual({ botId: "chief", threadId: "t1" });
expect(openTarget({ ok: true, returned: false })).toBeNull();
diff --git a/src/lib/presence-client.ts b/src/lib/presence-client.ts
index 1d692ce1c4..d3b2b8b793 100644
--- a/src/lib/presence-client.ts
+++ b/src/lib/presence-client.ts
@@ -8,15 +8,27 @@ export function shownLanguage(serverDefault: string | undefined, choice: string
return resolveLocale(effectiveLanguage(choice, serverDefault) || globalThis.navigator?.language, knownLocales());
}
-/** The language lets the brief the server writes match the app; the open chat lets the server get it ready to answer. */
-export function presenceBody(timeZone: string, language: string, threadId?: string): { source: "desktop"; timeZone?: string; language: string; threadId?: string } {
- return { source: "desktop", ...(timeZone ? { timeZone } : {}), language, ...(threadId ? { threadId } : {}) };
+/** The language lets the brief the server writes match the app; the open chat lets the server get it ready to answer, and
+ * `typing` (a key in its composer) says an answer is on its way. */
+export function presenceBody(timeZone: string, language: string, threadId?: string, typing = false): { source: "desktop"; timeZone?: string; language: string; threadId?: string; typing?: true } {
+ return { source: "desktop", ...(timeZone ? { timeZone } : {}), language, ...(threadId ? { threadId } : {}), ...(threadId && typing ? { typing: true } : {}) };
}
export function duePing(lastAt: number | null, now: number): boolean {
return lastAt === null || now - lastAt >= PRESENCE_MIN_INTERVAL_MS;
}
+/** A key pressed in a chat's composer. */
+export function composerKey(event: Pick<Event, "type" | "target"> | undefined): boolean {
+ const target = event?.target as { closest?: (selector: string) => unknown } | null | undefined;
+ return event?.type === "keydown" && typeof target?.closest === "function" && Boolean(target.closest("[data-composer-row]"));
+}
+
+/** Typing in a conversation is told at once, then once a minute at most while typing goes on there. */
+export function dueTyping(last: { threadId: string; at: number } | null, threadId: string, now: number): boolean {
+ return !last || last.threadId !== threadId || now - last.at >= PRESENCE_MIN_INTERVAL_MS;
+}
+
export function openTarget(answer: unknown): { botId: string; threadId: string } | null {
if (!answer || typeof answer !== "object") return null;