Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(chat): keep a manual unread mark across window focus, drop it on any way out of the chat
luishron12347a60f8fccfa
diff --git a/src/hooks/use-read-shown-chat.dom.test.ts b/src/hooks/use-read-shown-chat.dom.test.tsindex 54312303f7..57ea5a0194 100644--- a/src/hooks/use-read-shown-chat.dom.test.ts+++ b/src/hooks/use-read-shown-chat.dom.test.ts@@ -8,11 +8,12 @@ import { initialState, type Action, type AppState, type Bot } from "@/state/storconst store = vi.hoisted(() => ({ state: null as unknown as AppState, dispatch: (_action: unknown) => {} }));vi.mock("@/state/store", async (original) => ({ ...(await original<typeof import("@/state/store")>()), useStore: () => store }));const { useReadShownChatOnFocus } = await import("./use-read-shown-chat");+const { holdMarkedUnread } = await import("@/state/read-visible");-const bot = (unread: boolean): Bot => ({+const bot = (unread: boolean, updatedAt = 10): Bot => ({id: "reviewer", threadId: "shown", name: "Reviewer", title: "", description: "", notifications: true,color: "green", unread, messages: [], modelSelection: { instanceId: "fake", model: "test" },- tasks: [{ threadId: "shown", title: "Shown", createdAt: 1, unread }],+ tasks: [{ threadId: "shown", title: "Shown", createdAt: 1, updatedAt, unread }],});function Shell() {@@ -40,3 +41,23 @@ it("reads the shown chat when the window gets focus back, and only while it is uwindow.dispatchEvent(new Event("focus"));expect(dispatched).toHaveLength(1);});++it("leaves a chat the person marked unread alone when the window gets focus back, until a newer reply is in it", () => {+ const dispatched: Action[] = [];+ store.dispatch = (action) => dispatched.push(action as Action);+ store.state = { ...initialState, activeView: "chat", selectedId: "reviewer", bots: [bot(false)] };+ holdMarkedUnread({ type: "markUnread", botId: "reviewer" }, store.state);+ store.state = { ...store.state, bots: [bot(true)] };+ root = createRoot(document.createElement("div"));+ flushSync(() => root!.render(createElement(Shell)));+ window.dispatchEvent(new Event("blur"));+ window.dispatchEvent(new Event("focus"));+ window.dispatchEvent(new Event("focus"));+ expect(dispatched).toEqual([]);++ store.state = { ...store.state, bots: [bot(true, 11)] };+ flushSync(() => root!.render(createElement(Shell)));+ window.dispatchEvent(new Event("focus"));+ expect(dispatched).toEqual([{ type: "select", id: "reviewer" }]);+ holdMarkedUnread({ type: "select", id: "reviewer" }, store.state);+});diff --git a/src/hooks/use-read-shown-chat.ts b/src/hooks/use-read-shown-chat.tsindex b139375bcf..4702a36e69 100644--- a/src/hooks/use-read-shown-chat.ts+++ b/src/hooks/use-read-shown-chat.ts@@ -1,9 +1,11 @@import { useEffect, useRef } from "react";import { shownChatIsUnread } from "@/lib/shown-chat-unread";+import { shownChatHeldUnread } from "@/state/read-visible";import { useStore } from "@/state/store";/** Replies that reached the shown chat while the window was in the background stay unread; once the window has focus- * again, that chat is read through `select`, which also puts the "New" divider above them. */+ * again, that chat is read through `select`, which also puts the "New" divider above them. A chat the person marked+ * unread stays so when nothing newer reached it. */export function useReadShownChatOnFocus(): void {const { state, dispatch } = useStore();const latest = useRef(state);@@ -11,7 +13,7 @@ export function useReadShownChatOnFocus(): void {useEffect(() => {const readShownChat = () => {const { selectedId, newChat } = latest.current;- if (selectedId && newChat?.botId !== selectedId && shownChatIsUnread(latest.current)) dispatch({ type: "select", id: selectedId });+ if (selectedId && newChat?.botId !== selectedId && shownChatIsUnread(latest.current) && !shownChatHeldUnread(latest.current)) dispatch({ type: "select", id: selectedId });};window.addEventListener("focus", readShownChat);return () => window.removeEventListener("focus", readShownChat);diff --git a/src/state/mark-unread-hold.test.ts b/src/state/mark-unread-hold.test.tsnew file mode 100644index 0000000000..d7cd9dab73--- /dev/null+++ b/src/state/mark-unread-hold.test.ts@@ -0,0 +1,118 @@+// @vitest-environment happy-dom+// The real provider and its live stream: what the person does after "Mark as unread" on the open chat decides whether+// the next announcement of that chat is read.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, beforeEach, expect, it, vi } from "vitest";+import type { Action, AppState, Bot } from "./store";++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }+}++const profile: Bot = {+ id: "B", name: "B", threadId: "main", title: "", description: "", color: "green", unread: false, notifications: true,+ messages: [], modelSelection: { instanceId: "fake", model: "test" },+ tasks: [{ threadId: "main", title: "Main", createdAt: 1, updatedAt: 10 }],+};+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));+const { initialState, StoreProvider, useStore } = await import("./store");+const original = { bots: initialState.bots, selectedId: initialState.selectedId };++let seen!: AppState;+let dispatch!: (action: Action) => void;+function Probe() {+ ({ state: seen, dispatch } = useStore());+ return null;+}+let root: Root;+let cursor = 0;+let reads: string[] = [];+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 10; i++) await task(); };+const paints: FrameRequestCallback[] = [];+const paint = async () => {+ for (const callback of paints.splice(0)) callback(performance.now());+ await settle();+};+const act = async (action: Action) => {+ flushSync(() => dispatch(action));+ await paint();+};+/** The server announcing the chat as unread, as it does after the mark and whenever the bot changes. */+const announceUnread = async (updatedAt = 10) => {+ const bot = { id: "B", unread: true, tasks: [{ threadId: "main", title: "Main", createdAt: 1, updatedAt, unread: true }] };+ FixtureEventSource.opened[0]!.send({ kind: "bot", bot, seq: ++cursor }, `run:${cursor}`);+ await paint();+};++beforeAll(async () => {+ Object.assign(initialState, { bots: [profile], selectedId: "B" });+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => paints.push(callback));+ vi.stubGlobal("cancelAnimationFrame", () => {});+ vi.spyOn(document, "hasFocus").mockReturnValue(true);+ vi.stubGlobal("fetch", (input: string, init?: RequestInit) => {+ const path = String(input).replace(/\?.*$/, "");+ if (path.endsWith("/read") && init?.method === "POST") reads.push(path);+ if (path === "/api/bots") return json({ bots: [profile], groups: [] });+ if (path === "/api/routines") return json({ routines: [], runs: [] });+ if (path === "/api/webhooks") return json({ webhooks: [], attempts: [] });+ return json({});+ });+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));+ await settle();+ FixtureEventSource.opened[0]!.send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ await paint();+});+beforeEach(async () => {+ await act({ type: "showChat" });+ await act({ type: "select", id: "B" });+ await act({ type: "markUnread", botId: "B" });+ reads = [];+});+afterAll(() => {+ root.unmount();+ Object.assign(initialState, original);+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++it("keeps the open chat unread while the server announces it", async () => {+ await announceUnread();+ await announceUnread();+ expect(reads).toEqual([]);+ expect(seen.bots[0]?.unread).toBe(true);+});++it("reads it again once a newer message arrives", async () => {+ await announceUnread(11);+ expect(reads).toEqual(["/api/bots/B/read"]);+});++it("stops holding it once the person opens a blank new chat", async () => {+ await act({ type: "newTask", botId: "B" });+ expect(seen.newChat?.botId).toBe("B");+ await announceUnread();+ expect(reads).toEqual(["/api/bots/B/read"]);+});++it("reads it again after the person went to Files and came back", async () => {+ await act({ type: "showFiles" });+ await announceUnread();+ expect(reads).toEqual([]);+ await act({ type: "showChat" });+ await announceUnread();+ expect(reads).toEqual(["/api/bots/B/read"]);+});diff --git a/src/state/read-visible.test.ts b/src/state/read-visible.test.tsindex 7d36ec6ba6..bdfb08672b 100644--- a/src/state/read-visible.test.ts+++ b/src/state/read-visible.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from "vitest";-import { holdMarkedUnread, markVisibleBotThreadsRead, markVisibleGroupThreadsRead } from "./read-visible";+import { describe, expect, it, vi } from "vitest";+import { holdMarkedUnread, markVisibleBotThreadsRead, markVisibleGroupThreadsRead, shownChatHeldUnread } from "./read-visible";import type { Action, AppState, BotAnnouncement, Group } from "./store";it("marks both visible bot threads read while leaving a hidden task unread", () => {@@ -99,4 +99,59 @@ describe("a conversation marked unread while it is open", () => {mark(state);expect(seen(open(), announced()).read).toEqual(["main"]);});++ it("stays unread through what the person does without leaving it", () => {+ const state = open();+ mark(state);+ act({ type: "toggleSidebar" }, state);+ act({ type: "markUnread", botId: "other" }, state);+ expect(seen(state, announced()).read).toEqual([]);+ expect(shownChatHeldUnread(state)).toBe(true);+ act({ type: "select", id: "bot" }, state);+ });++ it.each([+ ["Files", { activeView: "files" }],+ ["Routines", { activeView: "routines" }],+ ["a blank new conversation", { newChat: { session: 1, botId: "bot", held: [] } }],+ ])("is read as before once the person comes back from %s", (_where, away) => {+ const state = open();+ mark(state);+ act({ type: "showChat" }, { ...state, ...away } as unknown as AppState);+ expect(shownChatHeldUnread(state)).toBe(false);+ expect(seen(state, announced())).toEqual({ read: ["main"], unread: false, thread: false });+ });++ it("is held for the window getting focus back only until a newer message is in it", () => {+ const state = open();+ expect(shownChatHeldUnread(state)).toBe(false);+ mark(state);+ expect(shownChatHeldUnread(state)).toBe(true);+ expect(shownChatHeldUnread(open(11))).toBe(false);+ expect(shownChatHeldUnread({ ...state, activeView: "files" } as unknown as AppState)).toBe(false);+ act({ type: "select", id: "bot" }, state);+ 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);+ 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);+ });++ 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);+ });+ });});diff --git a/src/state/read-visible.ts b/src/state/read-visible.tsindex 0c66500139..7f633a0ce0 100644--- a/src/state/read-visible.ts+++ b/src/state/read-visible.ts@@ -10,16 +10,31 @@ const sendRead: SendRead = (path, threadId) => {/** 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. */const markedUnread = new Map<string, number | undefined>();-const RESUMES_READING: ReadonlySet<Action["type"]> = new Set(["select", "openDataResult", "switchTask", "newTask", "send"]);+const OPENS_A_CONVERSATION: ReadonlySet<Action["type"]> = new Set(["select", "openDataResult", "switchTask", "newTask", "send"]);-/** "Mark as unread" on the open conversation holds until the person opens a conversation again, this one included, or- * writes in one. */+function shownBotThread(state: AppState): string | undefined {+ if (state.activeView !== "chat" || (state.newChat && state.newChat.botId === state.selectedId)) return undefined;+ const bot = state.bots.find((candidate) => candidate.id === state.selectedId);+ 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. */export function holdMarkedUnread(action: Action, state: AppState): void {- if (RESUMES_READING.has(action.type)) return markedUnread.clear();- if (action.type !== "markUnread" || action.botId !== state.selectedId || state.activeView !== "chat") return;+ const shown = shownBotThread(state);+ if (OPENS_A_CONVERSATION.has(action.type) || !shown || !markedUnread.has(shown)) markedUnread.clear();+ if (action.type !== "markUnread" || action.botId !== state.selectedId || !shown) return;const bot = state.bots.find((candidate) => candidate.id === action.botId);- const shown = bot?.switchingTo ?? bot?.threadId;- if (shown) markedUnread.set(shown, bot?.tasks?.find((task) => task.threadId === shown)?.updatedAt);+ markedUnread.set(shown, bot?.tasks?.find((task) => task.threadId === shown)?.updatedAt);+}++/** 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;+ return marked === undefined || newest === undefined || newest <= marked;}function visibleThreadIds(state: AppState, kind: "bot" | "group", ownerId: string, shown?: string): string[] {diff --git a/src/state/store.tsx b/src/state/store.tsxindex c35e2adde6..f48aa0be59 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -2192,8 +2192,8 @@ 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); if (runNewChat(action)) return;- holdMarkedUnread(action, stateRef.current);+ action = pinBotThreadAction(action, stateRef.current.bots); holdMarkedUnread(action, stateRef.current);+ 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) };if (action.type === "openForkPanel" && !action.loadId) action = { ...action, loadId: randomUuid() };