Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Unread: a launch switch neither drops the restored hold nor reads the thread on the server
luishron123835319212a89
diff --git a/server/notification-read.e2e.test.ts b/server/notification-read.e2e.test.tsindex d3ea27c28c..f39c6a81b8 100644--- a/server/notification-read.e2e.test.ts+++ b/server/notification-read.e2e.test.ts@@ -40,6 +40,13 @@ it("opening a conversation reads its notifications in the feed and tells every oawait stream.until((candidate) => candidate.kind === "bot" && candidate.bot?.name === "Sales desk", 10_000);expect(stream.frames.filter((candidate) => candidate.kind === "notifications.read")).toHaveLength(1);+ // the page showing it by itself at launch is not the person opening it+ await api("POST", `/api/bots/${other.botId}/tasks/${other.threadId}?messages=0&seen=0`);+ await api("PATCH", `/api/bots/${other.botId}`, { name: "Sales team" });+ await stream.until((candidate) => candidate.kind === "bot" && candidate.bot?.name === "Sales team", 10_000);+ expect(stream.frames.filter((candidate) => candidate.kind === "notifications.read")).toHaveLength(1);+ expect((await notifications()).filter((entry) => entry.threadId === other.threadId).some((entry) => !entry.read)).toBe(true);+// switching to a conversation opens it tooawait api("POST", `/api/bots/${other.botId}/tasks/${other.threadId}?messages=0`);await stream.until((candidate) => candidate.kind === "notifications.read" && candidate.threadId === other.threadId, 10_000);diff --git a/server/routes/tasks.ts b/server/routes/tasks.tsindex 5703b4f30e..08fef38044 100644--- a/server/routes/tasks.ts+++ b/server/routes/tasks.ts@@ -252,8 +252,8 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTaconst switched = store.switchTask(bot.id, m[2]);if (!switched) return json(res, 404, { error: "no such task" });sawThread(m[2]);- deps.threadRead?.(auth, m[2]);- readThreadNotifications(m[2], broadcast, notificationListed(auth));+ // "seen=0": the page showed it by itself at launch; what waits there for the person stays unseen until they open it.+ if (url.searchParams.get("seen") !== "0") { deps.threadRead?.(auth, m[2]); readThreadNotifications(m[2], broadcast, notificationListed(auth)); }const wiredSwitch = wireBot(switched);const switchedSettings = { ...wiredSwitch, tasks: wiredSwitch.tasks ?? [] };// "0": settings only; a positive page: that tail; omitted: the whole thread (search hits can be older than a page).diff --git a/src/state/read-visible.test.ts b/src/state/read-visible.test.tsindex e1263ec92a..27a4b19539 100644--- a/src/state/read-visible.test.ts+++ b/src/state/read-visible.test.ts@@ -213,6 +213,26 @@ describe("a conversation a reloaded page put back on screen unread", () => {expect(page.shownChatHeldUnread(showing("main")), "the person opening it ends the hold").toBe(false);});+ it("still holds the restored conversation when the launch move fails and the page shows it again", async () => {+ const page = await reloaded();+ page.holdRestoredUnread(showing("side"));+ page.launchNavigation(() => page.holdMarkedUnread({ type: "switchTask", botId: "bot", threadId: "main" }, showing("side")));+ expect(page.shownChatHeldUnread(showing("side"))).toBe(true);+ const read: string[] = [];+ page.markVisibleBotThreadsRead(showing("side"), { id: "bot", unread: true, tasks } as unknown as BotAnnouncement, true, (_path, threadId) => read.push(threadId));+ expect(read).toEqual([]);+ });++ it("tags only the page's own launch switch, which the server then leaves unseen", async () => {+ const page = await reloaded();+ const move = { type: "switchTask", botId: "bot", threadId: "main" } as const;+ let tagged: unknown;+ page.launchNavigation(() => { tagged = page.launchTagged(move); });+ expect(tagged).toEqual({ ...move, auto: true });+ expect(page.launchTagged(move)).toBe(move);+ expect(page.launchTagged({ type: "select", id: "bot" } as never)).toEqual({ type: "select", id: "bot" });+ });+it("keeps a bot announced without its conversations unread when a thread beside it is read", async () => {const page = await reloaded();const state = { selectedId: "bot", activeView: "chat", groups: [], forkPanel: { kind: "bot", ownerId: "bot", threadId: "fork" },diff --git a/src/state/read-visible.ts b/src/state/read-visible.tsindex 4d07dc786b..59055ab636 100644--- a/src/state/read-visible.ts+++ b/src/state/read-visible.ts@@ -21,13 +21,18 @@ const OPENS_A_CONVERSATION: ReadonlySet<Action["type"]> = new Set(["select", "opconst OPENS_A_ROOM_THREAD: ReadonlySet<Action["type"]> = new Set(["switchGroupTask", "newGroupTask", "sendGroup"]);/** Whether the page's first snapshot came in, or the person opened or wrote in a conversation here before it did. */let restoreSettled = false;-/** The unread conversation this page put back on screen by itself when it loaded. Nobody chose to look at it, so it- * stays unread until the person opens a conversation here. */-let restoredUnread: string | undefined;+/** The unread conversations this page put back on screen by itself when it loaded: the one it restored and, when launch+ * moved on to the bot's main thread, that one too, so a failed move that shows the first again still holds it. Nobody+ * chose to look at them, so they stay unread until the person opens a conversation here. */+const restoredUnread = new Set<string>();/** Whether the page is opening, by itself, the conversation a bot opens to at launch. */let launching = false;+/** A switch the page makes by itself at launch tells the server so: showing it is not the person opening it, so what+ * waits there for them stays unseen. */+export const launchTagged = (action: Action): Action => (launching && action.type === "switchTask" ? { ...action, auto: true } : action);+/** Runs the page's own move at launch to the conversation a bot opens to: it is not the person opening one, so a* conversation restored unread stays held, now on the thread the page moved to. */export function launchNavigation(navigate: () => void): void {@@ -60,13 +65,13 @@ function openedBotThread(action: Action, state: AppState): string | undefined {* conversation they open or write in. */export function holdMarkedUnread(action: Action, state: AppState): void {if (launching) {- // The page moving to the bot's main thread by itself at launch: the hold follows it, since nobody chose to look.- if (action.type === "switchTask") restoredUnread = threadIsUnread(state, action.botId, action.threadId) ? action.threadId : undefined;+ // The page moving to the bot's main thread by itself at launch: the hold covers it too, since nobody chose to look.+ if (action.type === "switchTask" && threadIsUnread(state, action.botId, action.threadId)) restoredUnread.add(action.threadId);return;}if (OPENS_A_CONVERSATION.has(action.type) || OPENS_A_ROOM_THREAD.has(action.type)) {restoreSettled = true;- restoredUnread = undefined;+ restoredUnread.clear();}const shown = shownBotThread(state), leaves = OPENS_A_CONVERSATION.has(action.type) || !shown;if (leaves || !markedUnread.has(shown)) markedUnread.clear();@@ -89,7 +94,7 @@ export function holdRestoredUnread(state: AppState): void {if (restoreSettled) return;restoreSettled = true;const shown = shownThread(state);- restoredUnread = shown && shownChatIsUnread(state) ? shown : undefined;+ if (shown && shownChatIsUnread(state)) restoredUnread.add(shown);}const serverHolds = (task: { threadId: string; heldUnread?: string } | undefined) =>@@ -98,7 +103,7 @@ const serverHolds = (task: { threadId: string; heldUnread?: string } | undefined/** Whether the shown conversation is still held unread: put back on screen by a page load and not opened since, or marked* by the person and nothing newer has arrived in it. */export function shownChatHeldUnread(state: AppState): boolean {- if (restoredUnread !== undefined && shownThread(state) === restoredUnread) return true;+ if (restoredUnread.size > 0 && restoredUnread.has(shownThread(state) ?? "")) return true;const shown = shownBotThread(state);if (!shown) return false;const task = state.bots.find((candidate) => candidate.id === state.selectedId)?.tasks?.find((candidate) => candidate.threadId === shown);@@ -115,7 +120,7 @@ const chatShows = (state: AppState, id: string) => id === state.selectedId && stfunction visibleThreadIds(state: AppState, kind: "bot" | "group", ownerId: string, shown?: string): string[] {const panel = state.forkPanel;return [...new Set([shown, panel?.kind === kind && panel.ownerId === ownerId ? panel.threadId : undefined])]- .filter((threadId): threadId is string => Boolean(threadId) && threadId !== restoredUnread);+ .filter((threadId): threadId is string => Boolean(threadId) && !restoredUnread.has(threadId!));}export function markVisibleBotThreadsRead(state: AppState, bot: BotAnnouncement, focused: boolean, post: SendRead = sendRead): void {@@ -147,7 +152,7 @@ export function markVisibleBotThreadsRead(state: AppState, bot: BotAnnouncement,}// Without per-thread state the aggregate mark is the shown thread's, so a restored hold on it keeps the bot unread.if (bot.tasks) bot.unread = botShowsUnread(bot);- else if (!held && shown && shown !== restoredUnread) bot.unread = false;+ else if (!held && shown && !restoredUnread.has(shown)) bot.unread = false;}export function markVisibleGroupThreadsRead(state: AppState, group: Partial<Group> & { id: string }, focused: boolean,@@ -164,5 +169,5 @@ export function markVisibleGroupThreadsRead(state: AppState, group: Partial<Groupost(`/api/groups/${group.id}/read`, threadId, task?.updatedAt ?? 0, "seen");}if (group.tasks) group.unread = group.tasks.some((task) => task.unread);- else if (shown && shown !== restoredUnread) group.unread = false;+ else if (shown && !restoredUnread.has(shown)) group.unread = false;}diff --git a/src/state/store.tsx b/src/state/store.tsxindex 8e62311f4c..20bbb7fa59 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -51,7 +51,7 @@ import {import type { Routine, RoutineInput, RoutineRun, RoutineRunLimits, RoutineRunStatusFilter } from "@/lib/routines";import type { WebhookAttempt, WebhookIngressStatus, WebhookTrigger } from "@/lib/webhooks";import { duplicateBotProfile, restrictedCopyRequest } from "@/lib/bot-duplicate";-import { holdMarkedUnread, markVisibleBotThreadsRead, markVisibleGroupThreadsRead, type ReadReason } from "./read-visible"; import { feedThreadAction, roomFeedShows } from "@/lib/room-feed";+import { holdMarkedUnread, launchTagged, markVisibleBotThreadsRead, markVisibleGroupThreadsRead, type ReadReason } from "./read-visible"; import { feedThreadAction, roomFeedShows } from "@/lib/room-feed";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";@@ -696,7 +696,7 @@ export type Action =onError?: (message: string) => void;}| { type: "newTask"; botId: string; projectId?: string; cwd?: string; onCreated?: () => void; onError?: (message: string) => void; blankChat?: number }- | { type: "switchTask"; botId: string; threadId: string; whole?: true }+ | { type: "switchTask"; botId: string; threadId: string; whole?: true; auto?: true }| { type: "switchTaskFailed"; botId: string; threadId: string }| { type: "taskSwitched"; bot: Bot }| { type: "renameTask"; botId: string; threadId: string; title: string }@@ -2194,7 +2194,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {const wrapped: React.Dispatch<Action> = (action) => {store.flushFrames(); if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles", "showWebPanel", "showPublishedApps", "showSkillBurgers", "showTeamFiles", "showAnnouncements"].includes(action.type)) selectionRevision.current++;// Pin before any await or optimistic state change.- action = pinBotThreadAction(action, stateRef.current.bots); holdMarkedUnread(action, stateRef.current); const fed = feedThreadAction(action, stateRef.current); if (!fed) return; action = fed;+ action = pinBotThreadAction(action, stateRef.current.bots); action = launchTagged(action); holdMarkedUnread(action, stateRef.current); const fed = feedThreadAction(action, stateRef.current); if (!fed) return; action = fed;if (runNewChat(action)) return;if (action.type === "taskSwitched") action = { ...action, bot: withTaskWrites(action.bot) as Bot };if (action.type === "botPatched") action = { ...action, bot: withTaskWrites(action.bot) };@@ -2724,7 +2724,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {: Promise.resolve();void ready.then(() => api<{ bot: Bot }>(action.type === "newTask"? `/api/bots/${action.botId}/tasks`- : `/api/bots/${action.botId}/tasks/${action.threadId}${action.whole ? "" : `?messages=${SWITCH_MESSAGE_COUNT}`}`, { method: "POST", body: JSON.stringify(action.type === "newTask" ? { projectId: action.projectId, cwd: action.cwd } : {}) }))+ : `/api/bots/${action.botId}/tasks/${action.threadId}${action.whole ? (action.auto ? "?seen=0" : "") : `?messages=${SWITCH_MESSAGE_COUNT}${action.auto ? "&seen=0" : ""}`}`, { method: "POST", body: JSON.stringify(action.type === "newTask" ? { projectId: action.projectId, cwd: action.cwd } : {}) })).then((r) => {if (action.type === "newTask") { settle(null); action.onCreated?.(); }if (navigation.get(action.botId) !== revision) return;