Skip to content

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

End a held unread mark only where the person or a new reply ends it

luishron1238658f320c155
diff --git a/server/automation-reports.test.ts b/server/automation-reports.test.ts
index cf2f2f286f..dd9f1e8289 100644
--- a/server/automation-reports.test.ts
+++ b/server/automation-reports.test.ts
@@ -156,6 +156,19 @@ describe("automation reports", () => {
expect(f.store.messagesFor(f.main).some((message) => message.kind === "routine.run")).toBe(false);
});
+ it("ends the person's own unread mark on the chat with a report, and keeps it through a run with nothing new", () => {
+ const f = fixture();
+ const held = () => f.store.taskByThread(f.bot.id, f.main)?.heldUnread;
+ f.store.patchTask(f.bot.id, f.main, { unread: true, heldUnread: f.store.activePath(f.main).at(-1)!.id });
+ const quiet = f.finished("NOTHING NEW");
+ f.reports.runSettled(quiet, `turn-${quiet.id}`);
+ expect(held(), "nothing was written").toBeDefined();
+ const run = f.finished("Acme replied about the order.");
+ f.reports.runSettled(run, `turn-${run.id}`);
+ expect(f.store.taskByThread(f.bot.id, f.main)).toMatchObject({ unread: true });
+ expect(held(), "a report the person has not read yet is news").toBeUndefined();
+ });
+
it("writes nothing, marks nothing and notifies nobody for a run with nothing new", () => {
const f = fixture();
const run = f.finished("Checked 14 emails.\nNOTHING NEW");
diff --git a/server/held-unread.e2e.test.ts b/server/held-unread.e2e.test.ts
index 25a6d13347..0c1e8c9c0b 100644
--- a/server/held-unread.e2e.test.ts
+++ b/server/held-unread.e2e.test.ts
@@ -59,3 +59,50 @@ it("holds a conversation marked unread with it open against being on screen, in
await fixture.close();
}
}, 120_000);
+
+it("ends the mark, in every window, when a routine reports into the conversation, so being on screen reads it again", async () => {
+ const fixture = await launchVerificationServer();
+ const { url } = fixture.info;
+ const otherWindow = await openSse(`${url}/api/events`, { origin: url });
+ const api = async (method: string, path: string, body?: unknown, status = 200) => {
+ const response = await fetch(url + path, {
+ method, headers: { "content-type": "application/json", origin: url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ const value = await response.json() as any;
+ expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBe(status);
+ return value;
+ };
+ try {
+ const { bot: created } = await runControlOmb(["new-bot", "--name", "Reports", "--url", url]) as any;
+ const botId = created.id as string;
+ const threadId = (await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === botId).threadId as string;
+ const reloaded = async () => ((await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === botId)).tasks
+ .find((task: any) => task.threadId === threadId) as { unread?: boolean; heldUnread?: string };
+ const told = (held: boolean, after: number) => otherWindow.until((frame) => otherWindow.frames.indexOf(frame) >= after && frame.kind === "bot" && frame.bot?.id === botId &&
+ frame.bot.tasks?.some((task: any) => task.threadId === threadId && task.unread === true && (task.heldUnread !== undefined) === held), 15_000);
+ const { routine } = await api("POST", "/api/routines", {
+ name: "Morning report", prompt: "Report this run's state.", botId, enabled: false,
+ schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 },
+ }, 201);
+
+ const beforeMark = otherWindow.frames.length;
+ await api("PATCH", `/api/bots/${botId}`, { unread: true });
+ await told(true, beforeMark);
+ await api("POST", `/api/bots/${botId}/read`, { threadId, reason: "seen" });
+ expect(await reloaded(), "held before the report").toMatchObject({ unread: true, heldUnread: expect.any(String) });
+
+ const beforeReport = otherWindow.frames.length;
+ const { run } = await api("POST", `/api/routines/${routine.id}/run`, undefined, 201);
+ await expect.poll(async () => (await api("GET", "/api/routines")).runs.find((one: any) => one.id === run.id)?.report?.state,
+ { timeout: 30_000 }).toBe("posted");
+ await told(false, beforeReport);
+ expect(await reloaded(), "a reloaded page reads the same").toMatchObject({ unread: true });
+ expect(await reloaded()).not.toHaveProperty("heldUnread");
+ await api("POST", `/api/bots/${botId}/read`, { threadId, reason: "seen" });
+ expect(await reloaded(), "the report on screen is read").toMatchObject({ unread: false });
+ } finally {
+ otherWindow.close();
+ await fixture.close();
+ }
+}, 120_000);
diff --git a/server/held-unread.test.ts b/server/held-unread.test.ts
index a5a8ea9f90..81dd3863fc 100644
--- a/server/held-unread.test.ts
+++ b/server/held-unread.test.ts
@@ -20,3 +20,31 @@ it("keeps a conversation's mark the person made with it open until its unread ma
store.patchTask(bot.id, bot.threadId, { unread: false });
expect(held(), "a person's turn or an explicit read").toBeUndefined();
});
+
+it("ends the mark with anything new a bot says in it, whoever wrote it, and an emitted change, but not with its working trail", () => {
+ const store = new Store(() => ({ instanceId: "personal", model: "claude-sonnet-5" }));
+ const bot = store.createBot({}, { seedMessages: false });
+ const held = () => store.taskByThread(bot.id, bot.threadId)?.heldUnread;
+ const changes: unknown[] = [];
+ store.onChange((change) => { if (change.type === "bot") changes.push(change); });
+ const first = store.appendMessage(bot.threadId, { role: "bot", kind: "text", text: "Done." });
+ store.patchTask(bot.id, bot.threadId, { unread: true, heldUnread: first.id });
+ for (const kind of ["activity", "screen", "digest", "compaction"] as const) store.appendMessage(bot.threadId, { role: "bot", kind });
+ expect(held(), "a bot's working trail").toBe(first.id);
+ for (const said of [
+ { role: "bot", kind: "text", text: "Report from another bot." },
+ { role: "bot", kind: "options", card: { requestType: "question", question: "Which?", options: [] } },
+ ] as const) {
+ store.patchTask(bot.id, bot.threadId, { unread: true, heldUnread: store.activePath(bot.threadId).at(-1)!.id });
+ changes.length = 0;
+ store.appendMessage(bot.threadId, said as never);
+ expect(held(), said.kind).toBeUndefined();
+ expect(store.taskByThread(bot.id, bot.threadId)?.unread, "the chat stays unread").toBe(true);
+ expect(changes, "every window is told").toContainEqual({ type: "bot", botId: bot.id, threadId: bot.threadId });
+ }
+ store.patchTask(bot.id, bot.threadId, { unread: true, heldUnread: store.activePath(bot.threadId).at(-1)!.id });
+ store.insertMessageAfter(bot.threadId, first.id, { role: "bot", kind: "text", text: "A late answer under an earlier line." });
+ expect(held(), "a line written under an earlier one").toBeUndefined();
+ expect(new Store(() => ({ instanceId: "personal", model: "claude-sonnet-5" })).taskByThread(bot.id, bot.threadId)?.heldUnread,
+ "a restarted server").toBeUndefined();
+});
diff --git a/server/held-unread.ts b/server/held-unread.ts
new file mode 100644
index 0000000000..527803add4
--- /dev/null
+++ b/server/held-unread.ts
@@ -0,0 +1,14 @@
+import type { Store } from "./store.ts";
+
+type Line = { role: string; kind?: string };
+const NOT_A_REPLY = new Set(["activity", "screen", "digest", "compaction"]);
+
+/** A bot's line the person reads: a reply, a routine's report, another bot's handoff or a notice; not its working trail. */
+export const isReply = (message: Line): boolean => message.role === "bot" && !NOT_A_REPLY.has(message.kind ?? "text");
+
+/** A conversation the person marked unread stays so until something new arrives in it: any reply ends the mark, whatever
+ * wrote it, so no window keeps holding a conversation that has news. */
+export function endHeldUnread(store: Pick<Store, "botByThread" | "taskByThread" | "patchTask">, threadId: string, message: Line): void {
+ const bot = isReply(message) ? store.botByThread(threadId) : null;
+ if (bot && store.taskByThread(bot.id, threadId)?.heldUnread !== undefined) store.patchTask(bot.id, threadId, { heldUnread: undefined });
+}
diff --git a/server/host/room-reads.test.ts b/server/host/room-reads.test.ts
index 058ebc8fd2..a8e79d748f 100644
--- a/server/host/room-reads.test.ts
+++ b/server/host/room-reads.test.ts
@@ -132,3 +132,28 @@ it("forgets a person's other marks of their own with their read lines", () => {
reads.forgetPerson("p_ada");
expect(forgotten, "even with no read line of theirs").toEqual(["p_ada"]);
});
+
+it("shows a person's mark on a shared chat with no reply before its newest one as unread, until a reply follows", () => {
+ const dir = mkdtempSync(join(tmpdir(), "room-reads-"));
+ const thread: Array<{ id: string; role: string }> = [];
+ const rooms = createPersonRooms({
+ reads: createRoomReads(dir),
+ store: () => ({ activePath: () => thread, messagesFor: () => thread, botByThread: () => ({ id: "scout" }) }),
+ shared: (threadId) => threadId === "main",
+ wireBot: (id) => ({ id }),
+ newestMessageId: () => thread.at(-1)?.id,
+ publicGroupState: (room) => room as never,
+ broadcast: () => {},
+ });
+ const ada = { kind: "session", session: { id: "s1", email: "[email protected]" } } as never;
+ const adaKey = personKey({ id: "", email: "[email protected]" }), cleoKey = personKey({ id: "", email: "[email protected]" });
+ const main = { threadId: "main", unread: false };
+ rooms.personMarkThread!(ada, "main", true);
+ expect(rooms.taskForPerson(main, adaKey), "an empty chat").toEqual({ threadId: "main", unread: true, heldUnread: "" });
+ expect(rooms.taskForPerson(main, cleoKey).unread, "nobody else's").toBe(false);
+ thread.push({ id: "m1", role: "bot" });
+ expect(rooms.taskForPerson(main, adaKey), "its first reply ends the mark, and with nothing read yet the chat's own mark shows")
+ .toEqual({ threadId: "main", unread: false });
+ rooms.personMarkThread!(ada, "main", true);
+ expect(rooms.taskForPerson(main, adaKey), "marked with only that first reply in it").toEqual({ threadId: "main", unread: true, heldUnread: "m1" });
+});
diff --git a/server/host/room-reads.ts b/server/host/room-reads.ts
index 8c7c2fdd87..5f1d6b77f4 100644
--- a/server/host/room-reads.ts
+++ b/server/host/room-reads.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
import type { WireGroup } from "../../shared/wire.ts";
import { writeFileAtomic } from "../atomic.ts";
+import { isReply } from "../held-unread.ts";
import { personKey } from "../person-key.ts";
import type { RequestAuth } from "../request-auth.ts";
import type { GroupRecord } from "../store.ts";
@@ -13,8 +14,6 @@ const fileSchema = z.object({ version: z.literal(1), reads: z.record(z.string(),
type PathMessage = { id: string; role: string; kind?: string; at?: number };
-const NOT_A_REPLY = new Set(["activity", "screen", "digest", "compaction"]);
-const isReply = (message: PathMessage) => message.role === "bot" && !NOT_A_REPLY.has(message.kind ?? "text");
/** Unread for a person: a bot replied after where they read up to; with no line yet, the room's own mark. A line no
* longer on the path (an edit or a retry moved it) reads up to the last message at or before it; `atOf` gives its time. */
@@ -140,8 +139,8 @@ 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 unread = roomUnreadFor(path, readUpTo, task.unread === true, atOf(task.threadId));
- const held = reads.readUpTo(threadHoldKey(task.threadId), person), heldUnread = unread && stillHeldUnread(path, held) ? held : undefined;
+ const held = reads.readUpTo(threadHoldKey(task.threadId), person), heldUnread = stillHeldUnread(path, held) ? 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;
return { ...rest, unread, ...(readUpTo ? { lastReadMessageId: readUpTo } : {}), ...(heldUnread !== undefined ? { heldUnread } : {}) } as T;
diff --git a/server/store.ts b/server/store.ts
index 1ac6cfc836..0157253e45 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -47,6 +47,7 @@ import { repairLegacyWorkThreads } from "./legacy-work-threads.ts";
import { createBotFork, createGroupFork } from "./store-forks.ts";
import { branchLeafFrom } from "../shared/conversation-branch.ts";
import { createThreadBotIndex } from "./thread-bot-index.ts";
+import { endHeldUnread } from "./held-unread.ts";
import { activeGroupTask, groupTaskByThread, groupTasks, migrateGroupTaskRead, mirrorActiveGroupTask, refreshGroupUnread, setGroupTaskRead, syncGroupReadPatch } from "./group-task-state.ts";
export { titleFromMessage, UNTITLED_TASK } from "./thread-title.ts";
export { threadTitleFrom, UNTITLED_THREAD } from "./task-record.ts";
@@ -1145,7 +1146,7 @@ export class Store {
}
}
this.noteThreadActivity(threadId, full.at, movesThreadToTop(full), full.turnCompletedAt ?? full.at);
- this.emit({ type: "message", threadId, message: full });
+ this.emit({ type: "message", threadId, message: full }); endHeldUnread(this, threadId, full);
if (full.role === "user" && full.kind === "text") this.dismissOnboardingCard(threadId);
return full;
}
@@ -1165,7 +1166,7 @@ export class Store {
}
}
this.noteThreadActivity(threadId, full.at, movesThreadToTop(full), full.turnCompletedAt ?? full.at);
- this.emit({ type: "message", threadId, message: full });
+ this.emit({ type: "message", threadId, message: full }); endHeldUnread(this, threadId, full);
// After the insert, so no client ever sees two siblings claiming the same parent.
for (const child of children) this.patchMessage(threadId, child.id, { parentId: full.id });
return full;
diff --git a/src/state/read-in-flight.test.ts b/src/state/read-in-flight.test.ts
index a31f329d0c..4b3a8a4df4 100644
--- a/src/state/read-in-flight.test.ts
+++ b/src/state/read-in-flight.test.ts
@@ -90,7 +90,7 @@ describe("marking the shown chat read while a read is in flight", () => {
expect(seen.activeView).toBe("chat");
sendUnread();
- expect(reads.map((read) => read.body)).toEqual([{ threadId: "thread" }]);
+ expect(reads.map((read) => read.body)).toEqual([{ threadId: "thread", reason: "seen" }]);
sendUnread();
sendUnread();
@@ -100,7 +100,7 @@ describe("marking the shown chat read while a read is in flight", () => {
reads[0]!.answer();
await settle();
- expect(reads.map((read) => read.body)).toEqual([{ threadId: "thread" }, { threadId: "thread" }]);
+ expect(reads.map((read) => read.body)).toEqual([{ threadId: "thread", reason: "seen" }, { threadId: "thread", reason: "seen" }]);
reads[1]!.answer();
await settle();
diff --git a/src/state/read-visible.test.ts b/src/state/read-visible.test.ts
index 0a5697eab5..fe6b8290c4 100644
--- a/src/state/read-visible.test.ts
+++ b/src/state/read-visible.test.ts
@@ -163,6 +163,19 @@ describe("a conversation marked unread while it is open", () => {
expect(see(heldBy()).reasons).toEqual(["main:open"]);
});
+ it("ends only for the conversation the person opens, never for a marked one shown beside it", async () => {
+ const both = () => ({ id: "bot", unread: true, tasks: [{ threadId: "main", unread: true, updatedAt: 10, heldUnread: "m1" },
+ { threadId: "fork", unread: true, updatedAt: 10, heldUnread: "f1" }] }) as unknown as BotAnnouncement;
+ const state = { ...showing(both()), forkPanel: { kind: "bot", ownerId: "bot", threadId: "fork" } } as unknown as AppState;
+ const { page, see } = await reloadedPage(state);
+ page.holdMarkedUnread({ type: "select", id: "bot" } as Action, state);
+ expect(see(both())).toEqual({ reasons: ["main:open"], unread: true });
+ page.holdMarkedUnread({ type: "switchTask", botId: "bot", threadId: "fork" } as Action, state);
+ const mainRead = both();
+ mainRead.tasks![0] = { threadId: "main", unread: false, updatedAt: 10 } as never;
+ expect(see(mainRead).reasons).toEqual(["main:open", "fork:open"]);
+ });
+
it("is read as only seen once the server says a newer reply ended it", async () => {
const after = { id: "bot", unread: true, tasks: [{ threadId: "main", unread: true, updatedAt: 11 }] } as unknown as BotAnnouncement;
const state = showing(after);
diff --git a/src/state/read-visible.ts b/src/state/read-visible.ts
index 48db087bb1..4348287bf6 100644
--- a/src/state/read-visible.ts
+++ b/src/state/read-visible.ts
@@ -23,12 +23,22 @@ function shownBotThread(state: AppState): string | undefined {
return bot?.switchingTo ?? bot?.threadId;
}
+/** The conversation an action puts on screen or writes in, which the person chose; never one merely shown beside it. */
+function openedBotThread(action: Action, state: AppState): string | undefined {
+ if ((action.type === "switchTask" || action.type === "send") && action.threadId) return action.threadId;
+ const botId = action.type === "select" ? action.id : action.type === "openDataResult" || action.type === "send" ? action.botId : undefined;
+ const bot = botId === undefined ? undefined : state.bots.find((candidate) => candidate.id === botId);
+ return bot?.switchingTo ?? bot?.threadId;
+}
+
/** "Mark as unread" on the open conversation holds while the person stays on it. It ends when they open a conversation,
- * this one included, write in one, or act from anywhere else in the app. */
+ * this one included, write in one, or act from anywhere else in the app. The server's own mark ends only for the
+ * conversation they open or write in. */
export function holdMarkedUnread(action: Action, state: AppState): void {
const shown = shownBotThread(state), leaves = OPENS_A_CONVERSATION.has(action.type) || !shown;
if (leaves || !markedUnread.has(shown)) markedUnread.clear();
- if (leaves) for (const task of state.bots.flatMap((bot) => bot.tasks ?? [])) if (task.heldUnread !== undefined) reopened.add(task.threadId);
+ const opened = OPENS_A_CONVERSATION.has(action.type) ? openedBotThread(action, state) : undefined;
+ if (opened && state.bots.some((bot) => bot.tasks?.some((task) => task.threadId === opened && task.heldUnread !== undefined))) reopened.add(opened);
if (action.type !== "markUnread" || action.botId !== state.selectedId || !shown) return;
const bot = state.bots.find((candidate) => candidate.id === action.botId);
markedUnread.set(shown, bot?.tasks?.find((task) => task.threadId === shown)?.updatedAt);