Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a person's unread mark across reloads and windows
luishron1231ff606ed7320
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex 26b5bb041e..ae0b7251fe 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -163,7 +163,7 @@ export interface WireTask extends InboxTask, HandoffStatusField {approvalMode?: ApprovalMode;autoApprove?: boolean;alwaysAllow?: string[];- unread?: boolean;+ unread?: boolean; /** Marked unread by the person with it open: the newest message then ("" for none). Being on screen alone does not read it until a reply follows; opening it, writing in it or a new reply ends the mark. */ heldUnread?: string;/** The newest message on screen the last time the person read this* conversation. The New divider goes after it. */lastReadMessageId?: string;diff --git a/server/held-unread.e2e.test.ts b/server/held-unread.e2e.test.tsnew file mode 100644index 0000000000..25a6d13347--- /dev/null+++ b/server/held-unread.e2e.test.ts@@ -0,0 +1,61 @@+import { expect, it } from "vitest";+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";+import { openSse } from "./testing/sse.ts";++it("holds a conversation marked unread with it open against being on screen, in every window, until it is opened or answered", 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", "Infra", "--url", url]) as any;+ const botId = created.id 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 threadId = (await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === botId).threadId as string;+ const answered = async (text: string) => {+ await api("POST", `/api/bots/${botId}/messages`, { threadId, text }, 202);+ await expect.poll(async () => (await reloaded()).unread, { timeout: 30_000 }).toBe(true);+ };+ const mark = async () => {+ await api("PATCH", `/api/bots/${botId}`, { unread: true });+ return (await otherWindow.until((frame) => frame.kind === "bot" && frame.bot?.id === botId &&+ frame.bot.tasks?.some((task: any) => task.threadId === threadId && task.heldUnread !== undefined), 10_000))+ .bot.tasks.find((task: any) => task.threadId === threadId);+ };+ await answered("Summarize the queue.");+ await api("POST", `/api/bots/${botId}/read`, { threadId });++ const told = await mark();+ expect(told, "another window is told").toMatchObject({ unread: true });+ expect(await reloaded(), "a reloaded page reads the same").toMatchObject({ unread: true, heldUnread: told.heldUnread });+ await api("POST", `/api/bots/${botId}/read`, { threadId, reason: "seen" });+ await api("POST", `/api/bots/${botId}/read`, { threadId, reason: "seen" });+ expect(await reloaded(), "being on screen reads it no more").toMatchObject({ unread: true, heldUnread: told.heldUnread });+ await api("POST", `/api/bots/${botId}/read`, { threadId, reason: "open" });+ expect(await reloaded(), "opening it again").toMatchObject({ unread: false });+ expect(await reloaded()).not.toHaveProperty("heldUnread");++ await mark();+ await api("POST", `/api/bots/${botId}/read`, { threadId });+ expect(await reloaded(), "an app that says no reason reads it as before").toMatchObject({ unread: false });+ expect(await reloaded()).not.toHaveProperty("heldUnread");++ await mark();+ await answered("And the backlog?");+ expect(await reloaded(), "writing in it, then its reply").not.toHaveProperty("heldUnread");+ await api("POST", `/api/bots/${botId}/read`, { threadId, reason: "seen" });+ expect(await reloaded(), "a newer reply 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.tsnew file mode 100644index 0000000000..a5a8ea9f90--- /dev/null+++ b/server/held-unread.test.ts@@ -0,0 +1,22 @@+import { rmSync } from "node:fs";+import { beforeEach, expect, it } from "vitest";+import { DATA_DIR } from "./config.ts";+import { Store } from "./store.ts";++beforeEach(() => { rmSync(DATA_DIR, { recursive: true, force: true }); });++it("keeps a conversation's mark the person made with it open until its unread mark changes another way", () => {+ 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;+ store.patchTask(bot.id, bot.threadId, { unread: true, heldUnread: "m1" });+ store.patchTask(bot.id, bot.threadId, { title: "Renamed" });+ expect(held(), "a change that leaves its unread mark alone").toBe("m1");+ expect(new Store(() => ({ instanceId: "personal", model: "claude-sonnet-5" })).taskByThread(bot.id, bot.threadId)?.heldUnread,+ "a restarted server").toBe("m1");+ store.patchTask(bot.id, bot.threadId, { unread: true });+ expect(held(), "a new reply's unread mark").toBeUndefined();+ store.patchTask(bot.id, bot.threadId, { unread: true, heldUnread: "m2" });+ store.patchTask(bot.id, bot.threadId, { unread: false });+ expect(held(), "a person's turn or an explicit read").toBeUndefined();+});diff --git a/server/host/room-reads.test.ts b/server/host/room-reads.test.tsindex 8f2e111f0a..058ebc8fd2 100644--- a/server/host/room-reads.test.ts+++ b/server/host/room-reads.test.ts@@ -5,7 +5,7 @@ import { expect, it } from "vitest";import type { WireGroup } from "../../shared/wire.ts";import { personKey } from "../person-key.ts";-import { createPersonRooms, createRoomReads, roomUnreadFor } from "./room-reads.ts";+import { createPersonRooms, createRoomReads, roomUnreadFor, stillHeldUnread } from "./room-reads.ts";const path = [{ id: "m1", role: "user" }, { id: "m2", role: "bot" }, { id: "m3", role: "user" }];@@ -21,6 +21,16 @@ it("counts only a bot's replies, not its tool or status lines", () => {expect(roomUnreadFor([...working, { id: "m4", role: "bot", kind: "text" }], "m1", false)).toBe(true);});+it("holds a conversation marked unread with it open until a reply follows the message newest then", () => {+ expect(stillHeldUnread(path, "m3")).toBe(true);+ expect(stillHeldUnread([...path, { id: "m4", role: "bot", kind: "activity" }], "m3"), "a tool line is no reply").toBe(true);+ expect(stillHeldUnread([...path, { id: "m4", role: "bot" }], "m3")).toBe(false);+ expect(stillHeldUnread(path, undefined), "never marked").toBe(false);+ expect(stillHeldUnread(path, "edited away"), "its message left the path").toBe(false);+ expect(stillHeldUnread([], ""), "marked with no message yet").toBe(true);+ expect(stillHeldUnread(path, ""), "a reply came after an empty conversation was marked").toBe(false);+});+it("reads a line no longer on the path as read up to the last message at or before it", () => {const timed = [{ id: "m1", role: "user", at: 1 }, { id: "m2", role: "bot", at: 2 }, { id: "m4", role: "bot", at: 4 }];expect(roomUnreadFor(timed, "edited", true, () => 3), "only the reply after it is unread").toBe(true);@@ -101,7 +111,16 @@ it("reads a bot's shared chat per person, leaves a private chat's one mark aloneexpect(rooms.taskForPerson(main, cleoKey).unread).toBe(true);expect(frames, "told to Ada's streams alone").toEqual([{ person: adaKey }]);expect(rooms.personMarkThread!(ada, "main", true)).toBe(true);- expect(rooms.taskForPerson(main, adaKey)).toEqual({ threadId: "main", unread: true, lastReadMessageId: "m3" });+ expect(rooms.taskForPerson(main, adaKey)).toEqual({ threadId: "main", unread: true, lastReadMessageId: "m3", heldUnread: "m4" });+ expect(rooms.personHeldUnread!(ada, "main"), "held for Ada while nothing newer came").toBe(true);+ expect(rooms.taskForPerson(main, cleoKey), "Cleo's copy carries no mark of Ada's").not.toHaveProperty("heldUnread");+ thread.push({ id: "m5", role: "bot" });+ expect(rooms.personHeldUnread!(ada, "main"), "a newer reply ends it").toBe(false);+ expect(rooms.taskForPerson(main, adaKey)).not.toHaveProperty("heldUnread");+ thread.pop();+ expect(rooms.personMarkThread!(ada, "main", false)).toBe(true);+ expect(rooms.personHeldUnread!(ada, "main"), "reading it ends it").toBe(false);+ expect(rooms.personHeldUnread!(ada, "mine"), "a private chat keeps the conversation's own mark").toBeNull();const own = { threadId: "mine", unread: true, lastReadMessageId: "m2" };expect(rooms.personMarkThread!(ada, "mine", false), "a private chat keeps its one mark").toBe(false);expect(rooms.taskForPerson(own, adaKey)).toBe(own);diff --git a/server/host/room-reads.ts b/server/host/room-reads.tsindex af959cad46..8c7c2fdd87 100644--- a/server/host/room-reads.ts+++ b/server/host/room-reads.ts@@ -29,6 +29,14 @@ export function roomUnreadFor(path: readonly PathMessage[], readUpTo: string | ureturn path.slice(from).some(isReply);}+/** A conversation marked unread with `held` its newest message ("" for none) stays held until a reply comes after it. 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 at = held === "" ? -1 : path.findIndex((message) => message.id === held);+ return (held === "" || at >= 0) && !path.slice(at + 1).some(isReply);+}+/** `alsoForget`: a person's other marks of their own (their bots' order, their notification reads), which go with* their read lines when they leave the team. */export function createRoomReads(dataDir: string, alsoForget?: (person: string) => void) {@@ -83,6 +91,8 @@ export type RoomReads = ReturnType<typeof createRoomReads>;/** A bot's shared conversation's key in `room-reads.json`, apart from every room's id. */export const threadReadKey = (threadId: string) => `thread:${threadId}`;+/** A person's "marked unread with it open" on a bot's shared conversation: the newest message then. */+const threadHoldKey = (threadId: string) => `held:${threadId}`;/** One stream frame's `group` payload as a person's own room, built once per person for that frame; null: theirs is the* room as it is. */@@ -127,13 +137,14 @@ export function createPersonRooms(deps: PersonRoomsDeps) {}/** A bot's shared conversation's unread mark and read line as this person read it, on a Team Cloud; the task as it is* anywhere else and for a private chat. Nobody's read line but their own goes out. */- function taskForPerson<T extends { threadId: string; unread?: boolean; lastReadMessageId?: string }>(task: T, person: string): T {+ 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 readUpTo = reads.readUpTo(threadReadKey(task.threadId), person);- const unread = roomUnreadFor(deps.store().activePath(task.threadId), readUpTo, task.unread === true, atOf(task.threadId));- if (unread === (task.unread === true) && readUpTo === task.lastReadMessageId) return task;- const { lastReadMessageId: _shared, ...rest } = task;- return { ...rest, unread, ...(readUpTo ? { lastReadMessageId: readUpTo } : {}) } as T;+ 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;+ 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;}return {reads,@@ -142,7 +153,7 @@ export function createPersonRooms(deps: PersonRoomsDeps) {/** A deleted room's or conversation's read lines go with it. */forgetDeleted(change: { type: string; groupId?: string; threadId?: string }): void {if (change.type === "group.deleted" && change.groupId) reads?.forgetRoom(change.groupId);- else if (change.type === "thread.deleted" && change.threadId) reads?.forgetRoom(threadReadKey(change.threadId));+ else if (change.type === "thread.deleted" && change.threadId) for (const key of [threadReadKey, threadHoldKey]) reads?.forgetRoom(key(change.threadId));},groupForAuth: (auth: RequestAuth, group: WireGroup): WireGroup => groupForPerson(group, auth.kind === "session" ? personKey(auth.session) : null),/** A `group` frame as `person`'s own room (`frameOf` writes the stream's frame for a payload), kept in `ownGroups` for@@ -175,18 +186,25 @@ export function createPersonRooms(deps: PersonRoomsDeps) {* a private chat, which keeps its one mark. Unread reads up to just before the conversation's newest reply. */personMarkThread: (auth: RequestAuth, threadId: string, unread: boolean): boolean => {if (auth.kind !== "session" || !deps.shared(threadId)) return false;- const person = personKey(auth.session), key = threadReadKey(threadId);+ const person = personKey(auth.session), key = threadReadKey(threadId), newest = deps.newestMessageId(threadId);if (unread) {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, newest ?? "");} else {- const newest = deps.newestMessageId(threadId);+ reads.forget(threadHoldKey(threadId), person);if (newest) reads.read(key, person, newest);}const bot = deps.store().botByThread(threadId), frame = bot ? deps.wireBot(bot.id) : null;if (frame) deps.broadcast({ kind: "bot", bot: frame }, { person });return true;+ },+ /** Whether this person's mark on a bot's shared conversation still holds; null for a private chat, which keeps the+ * 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)));} } : {}),};}diff --git a/server/index.ts b/server/index.tsindex 1157980893..0cccbb82ae 100644--- a/server/index.ts+++ b/server/index.ts@@ -12003,7 +12003,7 @@ ROUTES.push(createBotSettingsRoutes({cloudHome: Boolean(CLOUD_HOME), cloudOwnerProfileFields: CLOUD_OWNER_PROFILE_FIELDS,hostedModels, supportsApprovalMode, directTurnBots, broadcast, notificationListed, wireBot, cloudOwnerSession, storedAvatarExists,requestedTaskBot, threadBusy, activeGroupTurnForBot, checkedModelSelection, engineSwitchNeedsAsk, readCursor,- canManageCommandAllowlist, commandAllowlistResponse, cardAnswerRefusal, threadRead: teamMessages.seen, levelOf, personMarkThread: personRooms.personMarkThread,+ canManageCommandAllowlist, commandAllowlistResponse, cardAnswerRefusal, threadRead: teamMessages.seen, levelOf, personMarkThread: personRooms.personMarkThread, personHeldUnread: personRooms.personHeldUnread,}));const botOrderRoutes = createBotOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(botOrders ? { own: { person: botOrders.personOf, order: botOrders, told: (person, botIds) => broadcast({ kind: "bots.order", botIds }, { person }) } } : {}) }); ROUTES.push(createGroupOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)) }), botOrderRoutes, createBotAccessRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, levelOf, wireBot, publicGroupState, broadcast, audienceChanged, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), shared: createShareNotice({ people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, store: () => store, inbox: () => teamMessages.inbox }) }), accessRequests.routes);const botPatchRoutes = createBotPatchRoutes({ turnBots: directTurnBots, modelSwitched: noTerminal.modelSwitched,diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.tsindex 842778f58b..75d8b95e0e 100644--- a/server/routes/bot-patch.ts+++ b/server/routes/bot-patch.ts@@ -717,6 +717,9 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {bot = store.patchBot(m[1], patch);}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 });+ }if (body.applyToAllThreads === true && requestedApprovalMode !== "custom") store.setAllThreadApprovalMode(bot.id, requestedApprovalMode);if (body.memoryUpkeep === false || body.memoryEnabled === false) memoryUpkeep.dropBot(bot.id);if (body.cacheKeepWarm !== undefined) cacheKeepWarm.refresh();diff --git a/server/routes/bot-settings.ts b/server/routes/bot-settings.tsindex 611680b2f9..1b0d360b9b 100644--- a/server/routes/bot-settings.ts+++ b/server/routes/bot-settings.ts@@ -20,6 +20,7 @@ import type { ModelSelectionCheck } from "./bots-create.ts";import { PASS, type RouteHandler } from "./table.ts";import { pinnedClientThreadGuard } from "./pinned-client-thread.ts";import { sawThread } from "../thread-presence.ts";+import { stillHeldUnread } from "../host/room-reads.ts";import { refusalBody, refusalText, userError } from "../user-errors.ts";import { readThreadNotifications, type NotificationListed } from "./notifications.ts";@@ -55,6 +56,8 @@ export interface BotSettingsRouteDeps {/** A Team Cloud: marks a bot's shared conversation read or unread for this person alone (host/room-reads.ts); false* for a private chat, which keeps its one mark. */personMarkThread?(auth: RequestAuth, threadId: string, unread: boolean): boolean;+ /** A Team Cloud: whether this person's unread mark on a bot's shared conversation still holds; null for a private chat. */+ personHeldUnread?(auth: RequestAuth, threadId: string): boolean | null;/** A bot's model changed (host/no-terminal.ts). */modelSwitched?(botId: string, threadId: string, before: ModelSelection, after: ModelSelection, routinesFollow: boolean): void;}@@ -172,6 +175,11 @@ export function createBotSettingsRoutes(deps: BotSettingsRouteDeps): RouteHandleconst body = await readBody(req);requirePinnedClientThread(m[1], body?.threadId);const 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))) {+ return json(res, 200, { bot: wireBot(store.bot(current.id)!) });+ }sawThread(current.threadId);deps.threadRead?.(auth, current.threadId);if (deps.personMarkThread?.(auth, current.threadId, false)) {@@ -179,7 +187,7 @@ export function createBotSettingsRoutes(deps: BotSettingsRouteDeps): RouteHandlereturn json(res, 200, { bot: wireBot(store.bot(current.id)!) });}const task = store.taskByThread(current.id, current.threadId), cursor = readCursor(current.threadId);- const changed = Boolean(task?.unread) || (cursor.lastReadMessageId !== undefined && task?.lastReadMessageId !== cursor.lastReadMessageId);+ const changed = Boolean(task?.unread) || task?.heldUnread !== undefined || (cursor.lastReadMessageId !== undefined && task?.lastReadMessageId !== cursor.lastReadMessageId);if (changed) store.patchTask(current.id, current.threadId, { unread: false, ...cursor });readThreadNotifications(current.threadId, broadcast, notificationListed(auth));const visible = wireBot(store.bot(current.id)!);diff --git a/server/store.ts b/server/store.tsindex 8d6cf32eb4..1ac6cfc836 100644--- a/server/store.ts+++ b/server/store.ts@@ -112,7 +112,7 @@ const ASK_NOW = { approvalMode: "ask" as const, autoApprove: false, alwaysAllow:const TASK_PATCH_FIELDS = ["title", "projectId", "modelSelection", "approvalMode", "autoApprove", "alwaysAllow",- "unread", "lastReadMessageId", "rewound", "archivedAt", "pinned", "pinnedMessageId", "resumeCursors", "lastInstanceId", "cwd",+ "unread", "heldUnread", "lastReadMessageId", "rewound", "archivedAt", "pinned", "pinnedMessageId", "resumeCursors", "lastInstanceId", "cwd","routineRunId", "surface", "surfaceSource", "snoozedUntil", "link", "linkAuto", "appliedCompactionId", "contextFloor", "lastContextModel", "usage", "setupRequest", "botApi", "botApiAsOwner", "outside",] as const satisfies readonly (keyof TaskRecord)[];export type TaskPatch = Partial<Pick<TaskRecord, typeof TASK_PATCH_FIELDS[number]>>;@@ -2012,10 +2012,9 @@ export class Store {const revocation = keptRevocation(threadApproval(task, bot), threadApproval({ ...task, ...patch }, bot), patch);this.commitBotChange(bot, "the thread change", () => {for (const key of TASK_PATCH_FIELDS) {- if (Object.prototype.hasOwnProperty.call(patch, key)) {- Object.assign(task, { [key]: structuredClone(patch[key]) });- }+ if (Object.prototype.hasOwnProperty.call(patch, key)) Object.assign(task, { [key]: structuredClone(patch[key]) });}+ if (patch.unread !== undefined && !Object.prototype.hasOwnProperty.call(patch, "heldUnread")) delete task.heldUnread;if (task.snoozedUntil === 0 && patch.unread === true) task.snoozedUntil = undefined;if (typeof patch.title === "string") task.title = patch.title.trim().slice(0, 80) || UNTITLED_THREAD;if (Object.prototype.hasOwnProperty.call(patch, "pinned") && task.pinned !== true) delete task.pinned;diff --git a/src/state/read-visible.test.ts b/src/state/read-visible.test.tsindex bdfb08672b..0a5697eab5 100644--- a/src/state/read-visible.test.ts+++ b/src/state/read-visible.test.ts@@ -133,25 +133,51 @@ describe("a conversation marked unread while it is open", () => {expect(shownChatHeldUnread(state)).toBe(false);});- // The hold lives in this page's memory and the server keeps one unread flag per conversation: nothing below is held.- describe("known limits", () => {- it("is forgotten by a reloaded page, which reads the conversation at its next announcement", async () => {- const state = open();- mark(state);+ describe("held by the server", () => {+ const heldBy = (updatedAt = 10) => ({ id: "bot", unread: true, tasks: [{ threadId: "main", unread: true, updatedAt, heldUnread: "m1" }] }) as unknown as BotAnnouncement;+ const reloadedPage = async (state: AppState) => {vi.resetModules();- const reloaded = await import("./read-visible");- const read: string[] = [];- reloaded.markVisibleBotThreadsRead(state, announced(), true, (_path, threadId) => read.push(threadId));- expect(read).toEqual(["main"]);- act({ type: "select", id: "bot" }, state);+ const page = await import("./read-visible");+ const reasons: string[] = [];+ const see = (bot: BotAnnouncement) => {+ page.markVisibleBotThreadsRead(state, bot, true, (_path, threadId, _updatedAt, reason) => reasons.push(`${threadId}:${reason}`));+ return { reasons: [...reasons], unread: bot.unread };+ };+ return { page, see };+ };+ const showing = (bot: BotAnnouncement) => ({ ...open(), bots: [{ id: "bot", threadId: "main", tasks: bot.tasks }] }) as unknown as AppState;++ it("survives a reloaded page and reaches another window that shows the conversation", async () => {+ const state = showing(heldBy());+ const { page, see } = await reloadedPage(state);+ expect(see(heldBy())).toEqual({ reasons: [], unread: true });+ expect(see(heldBy())).toEqual({ reasons: [], unread: true });+ expect(page.shownChatHeldUnread(state), "getting focus back does not read it").toBe(true);+ });++ it("is read once the person opens it again in that page, saying so to the server", async () => {+ const state = showing(heldBy());+ const { page, see } = await reloadedPage(state);+ page.holdMarkedUnread({ type: "select", id: "bot" } as Action, state);+ expect(page.shownChatHeldUnread(state)).toBe(false);+ expect(see(heldBy()).reasons).toEqual(["main: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);+ const { page, see } = await reloadedPage(state);+ expect(page.shownChatHeldUnread(state)).toBe(false);+ expect(see(after)).toEqual({ reasons: ["main:seen"], unread: false });});- it("is cleared when another window that shows the conversation reads it", () => {- const state = open();- mark(state);- const readElsewhere = { id: "bot", unread: false, tasks: [{ threadId: "main", unread: false, updatedAt: 10 }] } as unknown as BotAnnouncement;- expect(seen(state, readElsewhere)).toEqual({ read: [], unread: false, thread: false });- act({ type: "select", id: "bot" }, state);+ it("is held again when marked again after being opened", async () => {+ const state = showing(heldBy());+ const { page, see } = await reloadedPage(state);+ page.holdMarkedUnread({ type: "select", id: "bot" } as Action, state);+ page.holdMarkedUnread({ type: "markUnread", botId: "bot" } as Action, state);+ expect(see(heldBy()).reasons).toEqual([]);+ page.holdMarkedUnread({ type: "select", id: "bot" } as Action, state);});});});diff --git a/src/state/read-visible.ts b/src/state/read-visible.tsindex 7f633a0ce0..48db087bb1 100644--- a/src/state/read-visible.ts+++ b/src/state/read-visible.ts@@ -2,14 +2,19 @@ import { botShowsUnread } from "@/lib/bot-unread";import type { Action, AppState, BotAnnouncement, Group } from "./store";import { serverFetch } from "@/lib/relay-server";-type SendRead = (path: string, threadId: string, updatedAt: number) => void;-const sendRead: SendRead = (path, threadId) => {- void serverFetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {});+/** "seen": only on screen, which a conversation the person marked unread with it open holds against; "open": the person+ * opened it again, which ends that mark. */+export type ReadReason = "seen" | "open";+type SendRead = (path: string, threadId: string, updatedAt: number, reason: ReadReason) => void;+const sendRead: SendRead = (path, threadId, _updatedAt, reason) => {+ void serverFetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId, reason }) }).catch(() => {});};-/** Conversations the person marked unread while looking at them, with their newest message then (unknown until the- * server next announces them). Being on screen reads none of them again until a newer message arrives. */+/** Conversations the person marked unread in this page while looking at them, with their newest message then (unknown+ * until the server next announces them), until the server's own mark (`heldUnread`) reaches the page. */const markedUnread = new Map<string, number | undefined>();+/** Conversations the server holds unread that the person opened again here, read once their mark is next announced. */+const reopened = new Set<string>();const OPENS_A_CONVERSATION: ReadonlySet<Action["type"]> = new Set(["select", "openDataResult", "switchTask", "newTask", "send"]);function shownBotThread(state: AppState): string | undefined {@@ -21,19 +26,26 @@ function shownBotThread(state: AppState): string | undefined {/** "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. */export function holdMarkedUnread(action: Action, state: AppState): void {- const shown = shownBotThread(state);- if (OPENS_A_CONVERSATION.has(action.type) || !shown || !markedUnread.has(shown)) markedUnread.clear();+ 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);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);+ reopened.delete(shown);}+const serverHolds = (task: { threadId: string; heldUnread?: string } | undefined) =>+ task?.heldUnread !== undefined && !reopened.has(task.threadId);+/** Whether the shown conversation is still held unread: marked by the person, and nothing newer has arrived in it. */export function shownChatHeldUnread(state: AppState): boolean {const shown = shownBotThread(state);- if (!shown || !markedUnread.has(shown)) return false;- const marked = markedUnread.get(shown);- const newest = state.bots.find((candidate) => candidate.id === state.selectedId)?.tasks?.find((task) => task.threadId === shown)?.updatedAt;+ if (!shown) return false;+ const task = state.bots.find((candidate) => candidate.id === state.selectedId)?.tasks?.find((candidate) => candidate.threadId === shown);+ if (serverHolds(task)) return true;+ if (!markedUnread.has(shown)) return false;+ const marked = markedUnread.get(shown), newest = task?.updatedAt;return marked === undefined || newest === undefined || newest <= marked;}@@ -51,7 +63,12 @@ export function markVisibleBotThreadsRead(state: AppState, bot: BotAnnouncement,let held = false;for (const threadId of visibleThreads) {const task = bot.tasks?.find((candidate) => candidate.threadId === threadId);+ if (task && task.heldUnread === undefined) reopened.delete(threadId);if (!task?.unread && (bot.tasks || !bot.unread)) continue;+ if (serverHolds(task)) {+ held = true;+ continue;+ }if (markedUnread.has(threadId)) {const newest = task?.updatedAt ?? 0, marked = markedUnread.get(threadId) ?? newest;if (newest <= marked) {@@ -62,7 +79,7 @@ export function markVisibleBotThreadsRead(state: AppState, bot: BotAnnouncement,markedUnread.delete(threadId);}if (task) task.unread = false;- post(`/api/bots/${bot.id}/read`, threadId, task?.updatedAt ?? 0);+ post(`/api/bots/${bot.id}/read`, threadId, task?.updatedAt ?? 0, task?.heldUnread !== undefined ? "open" : "seen");}if (bot.tasks) bot.unread = botShowsUnread(bot);else if (!held) bot.unread = false;@@ -77,7 +94,7 @@ export function markVisibleGroupThreadsRead(state: AppState, group: Partial<Grouconst task = group.tasks?.find((candidate) => candidate.threadId === threadId);if (!task?.unread && (group.tasks || !group.unread)) continue;if (task) task.unread = false;- post(`/api/groups/${group.id}/read`, threadId, task?.updatedAt ?? 0);+ post(`/api/groups/${group.id}/read`, threadId, task?.updatedAt ?? 0, "seen");}group.unread = group.tasks ? group.tasks.some((task) => task.unread) : false;}diff --git a/src/state/store.tsx b/src/state/store.tsxindex f48aa0be59..8ab892ccb4 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -50,7 +50,7 @@ import {import type { Routine, RoutineInput, RoutineRun, RoutineRunStatusFilter } from "@/lib/routines";import type { WebhookAttempt, WebhookIngressStatus, WebhookTrigger } from "@/lib/webhooks";import { duplicateBotProfile, restrictedCopyRequest } from "@/lib/bot-duplicate";-import { holdMarkedUnread, markVisibleBotThreadsRead, markVisibleGroupThreadsRead } from "./read-visible";+import { holdMarkedUnread, markVisibleBotThreadsRead, markVisibleGroupThreadsRead, type ReadReason } from "./read-visible";import { applyWindowPref } from "@/lib/window-prefs"; import { applyThemeFrame } from "@/lib/theme/runtime"; import { appCatalogAnnounced } from "@/lib/app-catalog-signal";import { placeUnreadDivider, threadOpensUnread, threadReadCursor, unreadDividerFor, type UnreadDivider } from "@/lib/unread-divider";import type { ComputerStart } from "@/lib/computer-start";@@ -216,7 +216,7 @@ export interface ModelSelection {variant?: string;}-export interface Task extends Pick<WireTask, "private" | "shared" | "sharedWith" | "setupRequest" | "inbox" | "openAsks" | "askedBy" | "handoff"> {+export interface Task extends Pick<WireTask, "heldUnread" | "private" | "shared" | "sharedWith" | "setupRequest" | "inbox" | "openAsks" | "askedBy" | "handoff"> {waitingForTeammates?: boolean; sharedChat?: true;threadId: string;origin?: import("../../shared/wire").ForkOrigin;@@ -3024,12 +3024,12 @@ export function StoreProvider({ children }: { children: ReactNode }) {// One read per conversation at a time, covering its newest message (the task's updatedAt). An unread frame meanwhile// with a newer message asks for exactly one more once it finishes; one re-announcing what the read covers does not.- const readsInFlight = new Map<string, { covers: number; again: boolean }>();- const sendRead = (botId: string, threadId: string | undefined, key: string, covers: number): void => {- readsInFlight.set(key, { covers, again: false });- void serverFetch(`/api/bots/${botId}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {}).finally(() => {+ const readsInFlight = new Map<string, { covers: number; again: boolean; reason: ReadReason }>();+ const sendRead = (botId: string, threadId: string | undefined, key: string, covers: number, reason: ReadReason): void => {+ readsInFlight.set(key, { covers, again: false, reason });+ void serverFetch(`/api/bots/${botId}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId, reason }) }).catch(() => {}).finally(() => {const open = readsInFlight.get(key); readsInFlight.delete(key);- if (open?.again && alive) sendRead(botId, threadId, key, open.covers);+ if (open?.again && alive) sendRead(botId, threadId, key, open.covers, open.reason);});};const stopFrames = store.handleFrames((frame) => { handleFrame(frame); stateRef.current = store.getState(); });@@ -3082,10 +3082,10 @@ export function StoreProvider({ children }: { children: ReactNode }) {break;case "bot": {const bot = frame.bot as BotAnnouncement, serverUnread = bot.unread;- markVisibleBotThreadsRead(stateRef.current, bot, document.hasFocus(), (_path, threadId, newest) => {+ markVisibleBotThreadsRead(stateRef.current, bot, document.hasFocus(), (_path, threadId, newest, reason) => {const read = `${bot.id}:${threadId}`, open = readsInFlight.get(read);- if (!open) sendRead(bot.id, threadId, read, newest);- else if (newest > open.covers) readsInFlight.set(read, { covers: newest, again: true });+ if (!open) sendRead(bot.id, threadId, read, newest, reason);+ else if (newest > open.covers || reason !== open.reason) readsInFlight.set(read, { covers: Math.max(newest, open.covers), again: true, reason });});if (frame.tasksPartial && serverUnread && !bot.unread) bot.unread = unreadBeyondFrame(stateRef.current.bots.find((known) => known.id === bot.id), bot);rawDispatch({ type: "botPatched", bot: withTaskWrites({ ...bot, ...botPatchQueue.overlayFor(bot.id) }), ...(frame.tasksPartial ? { tasksPartial: true as const } : {}) });