Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
End a held unread mark by write order, not by the clock
luishron123d74e6a0ddc68
diff --git a/server/host/room-reads.test.ts b/server/host/room-reads.test.tsindex 84d44774ee..325dd697b6 100644--- a/server/host/room-reads.test.ts+++ b/server/host/room-reads.test.ts@@ -158,34 +158,56 @@ it("shows a person's mark on a shared chat with no reply before its newest one aexpect(rooms.taskForPerson(main, adaKey), "marked with only that first reply in it").toEqual({ threadId: "main", unread: true, heldUnread: "m1" });});-it("ends each person's mark on a shared chat when a reply is inserted before the message they marked, keeping their lines apart", () => {- const dir = mkdtempSync(join(tmpdir(), "room-reads-"));- const thread: Array<{ id: string; role: string; kind?: string; at: number }> = [{ id: "m1", role: "user", at: 1 }, { id: "m2", role: "bot", at: 2 }, { id: "m3", role: "user", at: 3 }, { id: "m4", role: "bot", at: 4 }];+type Line = { id: string; role: string; kind?: string; at: number };+/** A shared chat whose path order (`path`) and write order (`written`) can differ, as an inserted reply makes them. */+function sharedChat(path: Line[], written: Line[] = [...path]) {const rooms = createPersonRooms({- reads: createRoomReads(dir),- store: () => ({ activePath: () => thread, messagesFor: () => thread, botByThread: () => ({ id: "scout" }) }),+ reads: createRoomReads(mkdtempSync(join(tmpdir(), "room-reads-"))),+ store: () => ({ activePath: () => path, messagesFor: () => written, botByThread: () => ({ id: "scout" }) }),shared: (threadId) => threadId === "main",wireBot: (id) => ({ id }),- newestMessageId: () => thread.at(-1)?.id,+ newestMessageId: () => path.at(-1)?.id,publicGroupState: (room) => room as never,broadcast: () => {},});- const session = (email: string) => ({ kind: "session", session: { id: email, email } }) as never;+ const insert = (index: number, line: Line) => { path.splice(index, 0, line); written.push(line); };+ return { rooms, insert };+}+const session = (email: string) => ({ kind: "session", session: { id: email, email } }) as never;++it("ends each person's mark on a shared chat when a reply is inserted before the message they marked, keeping their lines apart", () => {+ const { rooms, insert } = sharedChat([{ id: "m1", role: "user", at: 1 }, { id: "m2", role: "bot", at: 2 }, { id: "m3", role: "user", at: 3 }, { id: "m4", role: "bot", at: 4 }]);const ada = session("[email protected]"), ben = session("[email protected]"), cleo = session("[email protected]");const key = (email: string) => personKey({ id: "", email });const main = { threadId: "main", unread: false };rooms.personMarkThread!(ada, "main", true);rooms.personMarkThread!(ben, "main", true);rooms.personMarkThread!(cleo, "main", false);- thread.splice(2, 0, { id: "late", role: "bot", at: 5 });- expect(rooms.personHeldUnread!(ada, "main"), "a reply newer than the marked message, placed before it").toBe(false);+ insert(2, { id: "late", role: "bot", at: 5 });+ expect(rooms.personHeldUnread!(ada, "main"), "a reply written after the mark, placed before the marked message").toBe(false);expect(rooms.personHeldUnread!(ben, "main")).toBe(false);expect(rooms.taskForPerson(main, key("[email protected]")), "still unread, read up to where Ada was").toEqual({ threadId: "main", unread: true, lastReadMessageId: "m3" });expect(rooms.taskForPerson(main, key("[email protected]")), "Cleo's line is her own").toEqual({ threadId: "main", unread: false, lastReadMessageId: "m4" });rooms.personMarkThread!(ada, "main", true);- expect(rooms.personHeldUnread!(ada, "main"), "marking again after it holds").toBe(true);+ expect(rooms.personHeldUnread!(ada, "main"), "marking again right after it holds").toBe(true);expect(rooms.personHeldUnread!(ben, "main"), "without bringing back Ben's").toBe(false);- thread.splice(3, 0, { id: "trail", role: "bot", kind: "activity", at: 6 });+ insert(3, { id: "trail", role: "bot", kind: "activity", at: 6 });expect(rooms.personHeldUnread!(ada, "main"), "an inserted working line is no reply").toBe(true);});++it("ends a mark on a shared chat by when a reply was written, not by its clock", () => {+ const ada = session("[email protected]");+ const sameTime = sharedChat([{ id: "a", role: "bot", at: 10 }, { id: "b", role: "bot", at: 20 }]);+ sameTime.rooms.personMarkThread!(ada, "main", true);+ sameTime.insert(1, { id: "c", role: "bot", at: 20 });+ expect(sameTime.rooms.personHeldUnread!(ada, "main"), "inserted mid-history in the marked message's millisecond").toBe(false);+ const clockBack = sharedChat([{ id: "a", role: "bot", at: 10 }, { id: "b", role: "bot", at: 20 }]);+ clockBack.rooms.personMarkThread!(ada, "main", true);+ clockBack.insert(2, { id: "c", role: "bot", at: -80 });+ expect(clockBack.rooms.personHeldUnread!(ada, "main"), "added at the end after the clock went back").toBe(false);+ const untimed = sharedChat([{ id: "a", role: "bot", at: 10 }, { id: "b", role: "user", at: 20 }]);+ untimed.rooms.personMarkThread!(ada, "main", true);+ untimed.insert(0, { id: "old", role: "bot", at: 0 });+ expect(untimed.rooms.personHeldUnread!(ada, "main"), "any reply written after the mark, even one dated long before").toBe(false);+});diff --git a/server/host/room-reads.ts b/server/host/room-reads.tsindex b37851591d..21b2af0b7a 100644--- a/server/host/room-reads.ts+++ b/server/host/room-reads.ts@@ -28,20 +28,19 @@ export function roomUnreadFor(path: readonly PathMessage[], readUpTo: string | ureturn path.slice(from).some(isReply);}-/** The message a mark holds from: the path's newest by time, since a reply inserted mid-history is newer than the line- * after it; "" for an empty conversation. */-export function heldFrom(path: readonly PathMessage[]): string {- return path.reduce<PathMessage | undefined>((newest, message) => !newest || (message.at ?? 0) >= (newest.at ?? 0) ? message : newest, undefined)?.id ?? "";+/** The message a mark holds from: of those on the path, the one written last, whatever its clock says; "" for an empty+ * conversation. `written` is the conversation's messages in the order they were written. */+export function heldFrom(path: readonly PathMessage[], written: readonly PathMessage[] = path): string {+ const onPath = new Set(path.map((message) => message.id));+ return written.findLast((message) => onPath.has(message.id))?.id ?? "";}-/** A conversation marked unread with `held` from {@link heldFrom} stays held until a reply newer than it comes, wherever- * on the path it lands. A message no longer on the path (an edit or a retry moved it) ends the mark. */-export function stillHeldUnread(path: readonly PathMessage[], held: string | undefined): boolean {- if (held === undefined) return false;- const index = held === "" ? -1 : path.findIndex((message) => message.id === held), heldAt = path[index]?.at;- if (held !== "" && index < 0) return false;- const newer = (message: PathMessage, at: number) => heldAt === undefined || message.at === undefined ? at > index : message.at > heldAt || (at > index && message.at === heldAt);- return !path.some((message, at) => isReply(message) && newer(message, at));+/** A conversation marked unread with `held` from {@link heldFrom} stays held until a reply written after it reaches the+ * path, at any place on it and with any clock. A message no longer on the path (an edit or a retry moved it) ends the mark. */+export function stillHeldUnread(path: readonly PathMessage[], held: string | undefined, written: readonly PathMessage[] = path): boolean {+ if (held === undefined || (held !== "" && !path.some((message) => message.id === held))) return false;+ const order = new Map(written.map((message, index) => [message.id, index])), heldAt = held === "" ? -1 : order.get(held) ?? -1;+ return !path.some((message) => isReply(message) && (order.get(message.id) ?? Infinity) > heldAt);}/** `alsoForget`: a person's other marks of their own (their bots' order, their notification reads), which go with@@ -147,7 +146,7 @@ export function createPersonRooms(deps: PersonRoomsDeps) {function taskForPerson<T extends { threadId: string; unread?: boolean; lastReadMessageId?: string; heldUnread?: string }>(task: T, person: string): T {if (!reads || !deps.shared(task.threadId)) return task;const path = deps.store().activePath(task.threadId), readUpTo = reads.readUpTo(threadReadKey(task.threadId), person);- const held = reads.readUpTo(threadHoldKey(task.threadId), person), heldUnread = stillHeldUnread(path, held) ? held : undefined;+ const held = reads.readUpTo(threadHoldKey(task.threadId), person), heldUnread = stillHeldUnread(path, held, deps.store().messagesFor(task.threadId)) ? held : undefined;const unread = heldUnread !== undefined || roomUnreadFor(path, readUpTo, task.unread === true, atOf(task.threadId));if (unread === (task.unread === true) && readUpTo === task.lastReadMessageId && heldUnread === task.heldUnread) return task;const { lastReadMessageId: _shared, heldUnread: _held, ...rest } = task;@@ -198,7 +197,7 @@ export function createPersonRooms(deps: PersonRoomsDeps) {const path = deps.store().activePath(threadId), reply = path.findLastIndex(isReply);if (reply > 0) reads.read(key, person, path[reply - 1]!.id);else reads.forget(key, person);- reads.read(threadHoldKey(threadId), person, heldFrom(path));+ reads.read(threadHoldKey(threadId), person, heldFrom(path, deps.store().messagesFor(threadId)));} else {reads.forget(threadHoldKey(threadId), person);if (newest) reads.read(key, person, newest);@@ -211,7 +210,7 @@ export function createPersonRooms(deps: PersonRoomsDeps) {* conversation's own mark. */personHeldUnread: (auth: RequestAuth, threadId: string): boolean | null => {if (auth.kind !== "session" || !deps.shared(threadId)) return null;- return stillHeldUnread(deps.store().activePath(threadId), reads.readUpTo(threadHoldKey(threadId), personKey(auth.session)));+ return stillHeldUnread(deps.store().activePath(threadId), reads.readUpTo(threadHoldKey(threadId), personKey(auth.session)), deps.store().messagesFor(threadId));} } : {}),};}diff --git a/server/routes/bot-patch.test.ts b/server/routes/bot-patch.test.tsindex 8dbe49d79b..e4dcce217e 100644--- a/server/routes/bot-patch.test.ts+++ b/server/routes/bot-patch.test.ts@@ -13,6 +13,7 @@ import type { RequestAuth } from "../request-auth.ts";import { Store, type BotRecord } from "../store.ts";import * as vps from "../vps-computer.ts";import type { ManagedVpsInventory } from "../vps-computer.ts";+import { stillHeldUnread } from "../host/room-reads.ts";import { createBotPatchRoutes, type BotPatchRouteDeps } from "./bot-patch.ts";import { PASS, type RouteContext } from "./table.ts";@@ -538,3 +539,17 @@ describe("PATCH /api/bots/:id mainThreadChoice", () => {expect(store.bot(bot.id)?.mainThreadChoice).toBeUndefined();});});++describe("PATCH /api/bots/:id unread", () => {+ it("holds a mark made right after a reply was inserted mid-history, until a reply written later comes", async () => {+ const { store, bot, patch } = fixture();+ const first = store.appendMessage(bot.threadId, { role: "bot", kind: "text", text: "First answer." });+ store.appendMessage(bot.threadId, { role: "user", kind: "text", text: "Thanks.", at: 1 });+ store.insertMessageAfter(bot.threadId, first.id, { role: "bot", kind: "text", text: "A late note under the first answer." });+ expect((await patch(bot.id, { unread: true })).status).toBe(200);+ const held = () => stillHeldUnread(store.activePath(bot.threadId), store.taskByThread(bot.id, bot.threadId)?.heldUnread, store.messagesFor(bot.threadId));+ expect(held(), "the inserted reply was there when the person marked").toBe(true);+ store.appendMessage(bot.threadId, { role: "bot", kind: "text", text: "A new answer.", at: 0 });+ expect(store.taskByThread(bot.id, bot.threadId)?.heldUnread, "a reply written after it ends it, whatever its clock").toBeUndefined();+ });+});diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.tsindex 6630e668e8..750f0e6045 100644--- a/server/routes/bot-patch.ts+++ b/server/routes/bot-patch.ts@@ -24,6 +24,7 @@ import type { ModelSelection } from "../contracts.ts";import type { createApprovalModeSupport } from "../harness-capabilities.ts";import type { ProviderRegistry } from "../harness/registry.ts";import type { hostedModelPolicy } from "../hosted-models.ts";+import { heldFrom } from "../host/room-reads.ts";import { MAX_MCP_SERVERS, mcpServerNameError } from "../mcp-registry.ts";import type { MemoryUpkeep } from "../memory-upkeep.ts";import { phoneAppsFor } from "../phones/access.ts";@@ -720,7 +721,7 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {}if (!bot) return json(res, 404, { error: "no such bot" });if (typeof body.unread === "boolean") {- store.patchTask(bot.id, bot.threadId, { unread: body.unread, heldUnread: body.unread ? store.activePath(bot.threadId).at(-1)?.id ?? "" : undefined });+ store.patchTask(bot.id, bot.threadId, { unread: body.unread, heldUnread: body.unread ? heldFrom(store.activePath(bot.threadId), store.messagesFor(bot.threadId)) : undefined });}if (body.applyToAllThreads === true && requestedApprovalMode !== "custom") store.setAllThreadApprovalMode(bot.id, requestedApprovalMode);if (body.memoryUpkeep === false || body.memoryEnabled === false) memoryUpkeep.dropBot(bot.id);diff --git a/server/routes/bot-settings.ts b/server/routes/bot-settings.tsindex 1b0d360b9b..60a13ae3e8 100644--- a/server/routes/bot-settings.ts+++ b/server/routes/bot-settings.ts@@ -177,7 +177,7 @@ export function createBotSettingsRoutes(deps: BotSettingsRouteDeps): RouteHandleconst current = requestedTaskBot(m[1], body?.threadId);// "seen": the conversation is only on screen. A mark the person made with it open holds against that.if (body?.reason === "seen" && (deps.personHeldUnread?.(auth, current.threadId) ??- stillHeldUnread(store.activePath(current.threadId), store.taskByThread(current.id, current.threadId)?.heldUnread))) {+ stillHeldUnread(store.activePath(current.threadId), store.taskByThread(current.id, current.threadId)?.heldUnread, store.messagesFor(current.threadId)))) {return json(res, 200, { bot: wireBot(store.bot(current.id)!) });}sawThread(current.threadId);