Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Rooms: feed reply counts follow the shown branch; inbox count matches For you (#7651)
Milind Soni9ef5e4b6ea71
diff --git a/server/host/place-inbox.test.ts b/server/host/place-inbox.test.tsindex 965205708e..c9e8794535 100644--- a/server/host/place-inbox.test.ts+++ b/server/host/place-inbox.test.ts@@ -80,10 +80,21 @@ describe("finished work reaches the inbox once", () => {f.tick(1);f.inbox.route(summary, { summary: true });expect(infoRows(f).map((row) => row.text)).toEqual(["All three pages are live.", "Weekly report."]);- expect(f.inbox.count(OWNER)).toBe(2);+ expect(f.inbox.count(OWNER), "finished work sits in Activity, which the inbox's number never counts").toBe(0);expect(f.sent).toEqual([]);});+ it("counts a failure, which is for the person, until it is read", () => {+ const f = setup();+ f.handed.set("eli-pricing", "mira");+ f.inbox.route(failure("eli-pricing"));+ const [row] = infoRows(f);+ expect(row).toMatchObject({ tab: "info", unread: true });+ expect(f.inbox.count(OWNER)).toBe(1);+ expect(f.inbox.markRead(OWNER, row!.id)).toBe(true);+ expect(f.inbox.count(OWNER)).toBe(0);+ });+it("keeps one row per job: the next summary replaces the last one the person has not read", () => {const f = setup();f.inbox.route({ kind: "delegation-settled", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Results", body: "Results from Mira" } as Notification, { summary: true });@@ -362,7 +373,7 @@ describe("the inbox of a place that is no team's", () => {expect(f.inbox.message("nobody", "eli-main", "hi").status).toBe(403);});- it("counts news until it is read, and a routine's report notifies only through the notification it came with", () => {+ it("lists a routine's report unread in Activity without counting it, and it notifies only through the notification it came with", () => {const f = setup();const note: Notification = { kind: "done", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Daily digest", body: "3 new leads" };expect(f.inbox.route(note, { routine: true })).toBe(note);@@ -370,9 +381,9 @@ describe("the inbox of a place that is no team's", () => {const [row] = f.inbox.view(OWNER).rows;expect(row).toMatchObject({ kind: "result", text: "3 new leads", tab: "info", unread: true });expect(row!.replies).toBeUndefined();- expect(f.inbox.count(OWNER)).toBe(1);+ expect(f.inbox.count(OWNER), "a report is finished work: Activity, never counted").toBe(0);expect(f.inbox.markRead(OWNER, row!.id)).toBe(true);- expect(f.inbox.count(OWNER)).toBe(0);+ expect(f.inbox.view(OWNER).rows[0]!.unread).toBe(false);expect(f.inbox.markDone(OWNER, row!.id)).toBe("done");expect(f.inbox.view(OWNER).rows[0]!.tab).toBe("done");});diff --git a/server/host/place-inbox.ts b/server/host/place-inbox.tsindex 1de349d759..8e90602e8b 100644--- a/server/host/place-inbox.ts+++ b/server/host/place-inbox.ts@@ -10,6 +10,7 @@ import { join } from "node:path";import { z } from "zod";import type { InboxItem, InboxRow, InboxView } from "../../shared/inbox.ts";+import { countsForYou } from "../../shared/inbox-reason.ts";import type { Notification } from "../../shared/notification.ts";import { overtakenQuestions, personWait, type PersonWait } from "../../shared/person-wait.ts";import type { OptionCardData } from "../../shared/wire.ts";@@ -278,9 +279,9 @@ export function createPlaceInbox(deps: PlaceInboxDeps) {view,message,route,- /** What waits on this viewer: every open ask, and news they have not read. */+ /** What waits on this viewer in For you: open asks and unread news, never Activity (finished or shared). */count(auth: RequestAuth): number {- return view(auth).rows.filter((row) => row.tab === "needs-you" || (row.tab === "info" && row.unread)).length;+ return view(auth).rows.filter(countsForYou).length;},/** The viewer read a line or an open ask, or marked it unread again. */markRead(auth: RequestAuth, lineId: string, read = true): boolean {diff --git a/server/host/team-messages.ts b/server/host/team-messages.tsindex db282de55a..2a5a688068 100644--- a/server/host/team-messages.ts+++ b/server/host/team-messages.ts@@ -13,6 +13,7 @@ import { nameFromEmail, ownerEmail } from "../../shared/bot-owner.ts";import type { Notification } from "../../shared/notification.ts";import { mentionablePeople, teammateMentions } from "../../shared/person-mention.ts";import type { InboxView } from "../../shared/inbox.ts";+import { countsForYou } from "../../shared/inbox-reason.ts";import type { NeedsYouItem } from "../../shared/today.ts";import type { ResolvedSender } from "../../shared/wire.ts";import { audienceMember, type Audience } from "../audience.ts";@@ -400,12 +401,12 @@ export function createTeamMessages(deps: TeamMessagesDeps) {const me = sessionPerson(auth);return team && me ? inbox.view(me.key) : null;},- /** How many of the viewer's lines wait on them. */+ /** How many of the viewer's For you lines wait on them, the number the inbox shows; Activity is never counted. */count(auth: RequestAuth): number | null {if (!team && deps.place) return deps.place.count(auth);const me = sessionPerson(auth);const view = team && me ? inbox.view(me.key) : null;- return view ? view.rows.filter((row) => row.tab === "needs-you" || (row.tab === "info" && row.unread)).length : null;+ return view ? view.rows.filter(countsForYou).length : null;},/** The viewer is done with a line of news in their inbox. */markDone(auth: RequestAuth, id: string): ReturnType<PersonInbox["markDone"]> {diff --git a/server/message-db-thread-summaries.test.ts b/server/message-db-thread-summaries.test.tsindex 137ab2518d..945e26acba 100644--- a/server/message-db-thread-summaries.test.ts+++ b/server/message-db-thread-summaries.test.ts@@ -96,4 +96,32 @@ describe("room thread summaries", () => {expect(summary.replies).toBe(1);expect(summary.repliers).toEqual([{ person: {} }]);});++ it("counts only the branch a thread shows: an edited line and a retried answer leave no extra replies", () => {+ const first = add("g", person("Plan the launch", { parentId: null }));+ const asked = add("g", person("Which day?", { parentId: first.id }));+ const old = add("g", answer("kiwi", "Friday", { parentId: asked.id }));+ // Editing "Which day?" sends the new words beside it, and the bot answers again on the new branch.+ const edited = add("g", person("Which day, and who?", { parentId: first.id }));+ const fresh = add("g", answer("pip", "Friday, with Ana", { parentId: edited.id }));+ // A lone thread beside it keeps its plain count in the same read.+ add("h", person("Plain", { parentId: null }));+ const plainReply = add("h", answer("kiwi", "Yes", { parentId: "m-none" }));++ const [g, h] = roomThreadSummaries(["g", "h"]);+ expect(g).toMatchObject({ first: { text: "Plan the launch" }, replies: 2, lastReplyAt: fresh.at, repliers: [{ botId: "pip" }, { person: {} }] });+ expect(h).toMatchObject({ replies: 1, lastReplyAt: plainReply.at });++ mdb.setActiveLeaf("g", old.id);+ const [back] = roomThreadSummaries(["g"]);+ expect(back, "switching back shows the older branch's lines").toMatchObject({ replies: 2, lastReplyAt: old.at, repliers: [{ botId: "kiwi" }, { person: {} }] });+ });++ it("reads an edited first line as the thread's first line", () => {+ add("i", person("Draft", { parentId: null }));+ const edited = add("i", person("Final words", { parentId: null }));+ add("i", answer("kiwi", "Got it", { parentId: edited.id }));+ const [summary] = roomThreadSummaries(["i"]);+ expect(summary).toMatchObject({ first: { text: "Final words", at: edited.at }, replies: 1, repliers: [{ botId: "kiwi" }] });+ });});diff --git a/server/message-db-thread-summaries.ts b/server/message-db-thread-summaries.tsindex dd7edb6fc5..912880a494 100644--- a/server/message-db-thread-summaries.ts+++ b/server/message-db-thread-summaries.ts@@ -4,19 +4,39 @@ import { ROOM_THREAD_FIRST_CHARS, ROOM_THREAD_REPLIERS, type RoomThreadSpeaker,/** A thread's conversation lines: a person's text that no bot asked or slipped into a running turn for them, and each* bot turn's final answer.* ORDERING_ROW is repeated verbatim so SQLite can read messages_thread_order, whose partial WHERE it is. */-const LINES = `FROM messages INDEXED BY messages_thread_order WHERE thread_id IN (SELECT value FROM json_each(?)) AND ${ORDERING_ROW} AND (role = 'bot' OR (kind = 'text' AND json_extract(json, '$.aside') IS NULL))`;+const IN_THREADS = "thread_id IN (SELECT value FROM json_each(?))";+const LINE_ROWS = `FROM messages INDEXED BY messages_thread_order WHERE ${IN_THREADS} AND ${ORDERING_ROW}`;+const LINES = `${LINE_ROWS} AND (role = 'bot' OR (kind = 'text' AND json_extract(json, '$.aside') IS NULL))`;const BOT = "json_extract(json, '$.from.botId')";const SENDER_ID = "json_extract(json, '$.sender.id')";const SENDER_NAME = "json_extract(json, '$.sender.name')";+/** Threads an edit, Regenerate or Try again branched: only those send a person's line beside an earlier one+ * (store.branchMessage), so two of their person lines share a parent. A first line has an explicit null parent, which+ * counts as one; a row stored with no parent at all links nothing and is left out. Person lines are small, so this stays cheap. */+const PARENT = "CASE json_type(json, '$.parentId') WHEN 'null' THEN '' WHEN 'text' THEN json_extract(json, '$.parentId') END";+const BRANCHED = `SELECT thread_id AS threadId ${LINE_ROWS} AND role = 'user' AND kind = 'text' GROUP BY thread_id ` ++ `HAVING COUNT(${PARENT}) > COUNT(DISTINCT ${PARENT})`;+/** The rows on a thread's shown branch, walked from its active leaf up its parents. Each step parses a row's JSON,+ * so only branched threads take this walk. */+const ON_PATH = `WITH RECURSIVE path(thread_id, id) AS (SELECT thread_id, active_leaf_id FROM thread_state WHERE ${IN_THREADS} ` ++ "AND active_leaf_id IS NOT NULL UNION ALL SELECT m.thread_id, json_extract(m.json, '$.parentId') FROM path p " ++ "JOIN messages m ON m.thread_id = p.thread_id AND m.id = p.id WHERE json_extract(m.json, '$.parentId') IS NOT NULL)";+const PATH_ONLY = " AND id IN (SELECT path.id FROM path WHERE path.thread_id = messages.thread_id)";+/** SQLite takes the bare columns of a MIN() aggregate from the row that holds the minimum. */-const FIRSTS = `SELECT thread_id AS threadId, MIN(rowid) AS row, at, role, substr(text, 1, ${ROOM_THREAD_FIRST_CHARS + 1}) AS text, ` +- `${BOT} AS botId, ${SENDER_ID} AS senderId, ${SENDER_NAME} AS senderName ${LINES} GROUP BY thread_id`;+const firsts = (lines: string) => `SELECT thread_id AS threadId, MIN(rowid) AS row, at, role, substr(text, 1, ${ROOM_THREAD_FIRST_CHARS + 1}) AS text, ` ++ `${BOT} AS botId, ${SENDER_ID} AS senderId, ${SENDER_NAME} AS senderName ${lines} GROUP BY thread_id`;/** Each line's speaker is read out of its JSON once, in a materialized step, before grouping: grouping on the* json_extract calls themselves parses every line's JSON several times, about three times slower on long answers. */-const SPEAKERS = `WITH spoken AS MATERIALIZED (SELECT thread_id AS threadId, role, ${BOT} AS botId, ${SENDER_ID} AS senderId, ` +- `${SENDER_NAME} AS senderName, rowid AS row, at ${LINES}) SELECT threadId, role, botId, senderId, senderName, COUNT(*) AS lines, ` +- `MAX(row) AS lastRow, MAX(at) AS lastAt FROM spoken GROUP BY threadId, role, botId, senderId, senderName`;+const spoken = (lines: string) => `spoken AS MATERIALIZED (SELECT thread_id AS threadId, role, ${BOT} AS botId, ${SENDER_ID} AS senderId, ` ++ `${SENDER_NAME} AS senderName, rowid AS row, at ${lines}) SELECT threadId, role, botId, senderId, senderName, COUNT(*) AS lines, ` ++ "MAX(row) AS lastRow, MAX(at) AS lastAt FROM spoken GROUP BY threadId, role, botId, senderId, senderName";+const FIRSTS = firsts(LINES);+const SPEAKERS = `WITH ${spoken(LINES)}`;+/** The same two reads kept to the shown branch; the path's thread list is the first parameter, the lines' the second. */+const PATH_FIRSTS = `${ON_PATH} ${firsts(LINES + PATH_ONLY)}`;+const PATH_SPEAKERS = `${ON_PATH}, ${spoken(LINES + PATH_ONLY)}`;type Who = { role: string; botId: string | null; senderId: string | null; senderName: string | null };type FirstRow = Who & { threadId: string; row: number; at: number; text: string | null };@@ -29,15 +49,24 @@ function speakerOf(who: Who): RoomThreadSpeaker {const sameSpeaker = (a: Who, b: Who) => a.role === b.role && a.botId === b.botId && a.senderId === b.senderId && a.senderName === b.senderName;-/** Each listed thread's first line, how many lines came after it and from whom, in two statements for all of them.- * Every branch of a thread counts: a line an edit or a retry left on an older branch is still counted as a reply. */+/** Each listed thread's first line, how many lines came after it and from whom. Only the branch the thread shows+ * counts: a line an edit or a retry left on an older branch is not a reply. Unbranched threads, nearly all of them,+ * take two statements together; branched ones take the same two kept to their shown branch. */export function roomThreadSummaries(threadIds: readonly string[]): RoomThreadSummary[] {const ids = [...new Set(threadIds.filter((id) => id.length > 0))];if (ids.length === 0) return [];- const list = JSON.stringify(ids);- const firsts = new Map((prepared(FIRSTS).all(list) as FirstRow[]).map((row) => [row.threadId, row]));+ const branched = new Set((prepared(BRANCHED).all(JSON.stringify(ids)) as Array<{ threadId: string }>).map((row) => row.threadId));+ const plain = JSON.stringify(ids.filter((id) => !branched.has(id)));+ const onPath = JSON.stringify([...branched]);+ const firstRows = prepared(FIRSTS).all(plain) as FirstRow[];+ const speakerRows = prepared(SPEAKERS).all(plain) as SpeakerRow[];+ if (branched.size > 0) {+ firstRows.push(...(prepared(PATH_FIRSTS).all(onPath, onPath) as FirstRow[]));+ speakerRows.push(...(prepared(PATH_SPEAKERS).all(onPath, onPath) as SpeakerRow[]));+ }+ const firsts = new Map(firstRows.map((row) => [row.threadId, row]));const speakers = new Map<string, SpeakerRow[]>();- for (const row of prepared(SPEAKERS).all(list) as SpeakerRow[]) speakers.set(row.threadId, [...(speakers.get(row.threadId) ?? []), row]);+ for (const row of speakerRows) speakers.set(row.threadId, [...(speakers.get(row.threadId) ?? []), row]);return ids.map((threadId) => {const first = firsts.get(threadId);if (!first) return { threadId, first: null, replies: 0, lastReplyAt: null, repliers: [] };