Skip to content

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

Unread: a reloaded page leaves the conversation it puts back on screen unread until it is opened

luishron12362574071598d
diff --git a/src/state/read-visible.ts b/src/state/read-visible.ts
index 9d8d1deb31..8b6fd1ebdb 100644
--- a/src/state/read-visible.ts
+++ b/src/state/read-visible.ts
@@ -1,4 +1,5 @@
import { botShowsUnread } from "@/lib/bot-unread";
+import { shownChatIsUnread } from "@/lib/shown-chat-unread";
import type { Action, AppState, BotAnnouncement, Group } from "./store";
import { serverFetch } from "@/lib/relay-server";
import { roomFeedShows } from "@/lib/room-feed";
@@ -17,6 +18,12 @@ 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"]);
+const 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;
function shownBotThread(state: AppState): string | undefined {
if (state.activeView !== "chat" || (state.newChat && state.newChat.botId === state.selectedId)) return undefined;
@@ -36,6 +43,10 @@ function openedBotThread(action: Action, state: AppState): string | undefined {
* 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 {
+ if (OPENS_A_CONVERSATION.has(action.type) || OPENS_A_ROOM_THREAD.has(action.type)) {
+ restoreSettled = true;
+ restoredUnread = undefined;
+ }
const shown = shownBotThread(state), leaves = OPENS_A_CONVERSATION.has(action.type) || !shown;
if (leaves || !markedUnread.has(shown)) markedUnread.clear();
const opened = OPENS_A_CONVERSATION.has(action.type) ? openedBotThread(action, state) : undefined;
@@ -46,11 +57,27 @@ export function holdMarkedUnread(action: Action, state: AppState): void {
reopened.delete(shown);
}
+function shownThread(state: AppState): string | undefined {
+ const room = state.activeView === "chat" ? state.groups.find((candidate) => candidate.id === state.selectedId) : undefined;
+ return room ? room.threadId : shownBotThread(state);
+}
+
+/** Call when a snapshot is in, before any frame on top of it; only the page's first counts: the conversation it shows by
+ * itself. */
+export function holdRestoredUnread(state: AppState): void {
+ if (restoreSettled) return;
+ restoreSettled = true;
+ const shown = shownThread(state);
+ restoredUnread = shown && shownChatIsUnread(state) ? shown : undefined;
+}
+
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. */
+/** 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;
const shown = shownBotThread(state);
if (!shown) return false;
const task = state.bots.find((candidate) => candidate.id === state.selectedId)?.tasks?.find((candidate) => candidate.threadId === shown);
@@ -67,7 +94,7 @@ const chatShows = (state: AppState, id: string) => id === state.selectedId && st
function 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));
+ .filter((threadId): threadId is string => Boolean(threadId) && threadId !== restoredUnread);
}
export function markVisibleBotThreadsRead(state: AppState, bot: BotAnnouncement, focused: boolean, post: SendRead = sendRead): void {
diff --git a/src/state/reload-unread.test.ts b/src/state/reload-unread.test.ts
new file mode 100644
index 0000000000..c4a183528e
--- /dev/null
+++ b/src/state/reload-unread.test.ts
@@ -0,0 +1,112 @@
+// @vitest-environment happy-dom
+// A reloaded page puts the last conversation back on screen by itself. Unread replies in it stay unread until the person
+// opens a conversation in that page.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { ServerFrame } from "../../shared/wire";
+import { LAST_CONVERSATION_KEY } from "@/lib/last-conversation";
+import type { Action, AppState, BotAnnouncement } 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 owner = (id: string, updatedAt: number): BotAnnouncement => ({
+ id, threadId: `${id}-thread`, name: id, title: "", description: "", notifications: true, unread: true, color: "green",
+ modelSelection: { instanceId: "fake", model: "m" },
+ tasks: [{ threadId: `${id}-thread`, title: "Thread", createdAt: 1, updatedAt, approvalMode: "ask", unread: true }],
+});
+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));
+const answers: Record<string, unknown> = {
+ "/api/instances": { instances: [] },
+ "/api/config": {},
+ "/api/routines": { routines: [], runs: [] },
+ "/api/webhooks": { webhooks: [], attempts: [] },
+};
+const reads: Array<{ path: string; body: unknown }> = [];
+
+const { StoreProvider, useStore } = await import("./store");
+const { shownChatHeldUnread } = await import("./read-visible");
+
+let seen!: AppState;
+let dispatch!: (action: Action) => void;
+function Probe() {
+ ({ state: seen, dispatch } = useStore());
+ return null;
+}
+let root: Root;
+let cursor = 0;
+const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((resolve) => setTimeout(resolve, 0)); };
+const stream = () => FixtureEventSource.opened.at(-1)!;
+const announce = (bot: BotAnnouncement) => {
+ stream().send({ kind: "bot", bot } as ServerFrame, `run:${++cursor}`);
+ flushSync(() => dispatch({ type: "connected", value: true }));
+};
+const taskOf = (id: string) => seen.bots.find((bot) => bot.id === id)?.tasks?.[0];
+
+beforeAll(async () => {
+ vi.spyOn(document, "hasFocus").mockImplementation(() => true);
+ localStorage.setItem(LAST_CONVERSATION_KEY, "shown");
+ vi.stubGlobal("EventSource", FixtureEventSource);
+ vi.stubGlobal("fetch", (path: string, init?: RequestInit) => {
+ if (/^\/api\/bots\/[\w-]+\/read$/.test(path)) {
+ reads.push({ path, body: JSON.parse(String(init?.body)) });
+ return json({});
+ }
+ return path.startsWith("/api/bots?")
+ ? json({ bots: [owner("other", 1_000), owner("shown", 2_000)], groups: [] })
+ : json(answers[path.replace(/\?since=[^&]*$/, "")] ?? { ok: true });
+ });
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));
+ await settle();
+ stream().send({ kind: "hello", resumed: false, cursor: "run:0" });
+ await settle();
+});
+afterAll(() => {
+ root.unmount();
+ localStorage.removeItem(LAST_CONVERSATION_KEY);
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe("unread conversations after the page is reloaded", () => {
+ it("leave the conversation put back on screen unread while the person has not opened one", async () => {
+ expect(seen.selectedId).toBe("shown");
+ expect(seen.activeView).toBe("chat");
+
+ announce(owner("shown", 2_000));
+ announce(owner("shown", 3_000));
+ await settle();
+ expect(reads, "no read is sent for a conversation only put back on screen").toEqual([]);
+ expect(taskOf("shown")?.unread).toBe(true);
+ expect(taskOf("other")?.unread).toBe(true);
+ expect(shownChatHeldUnread(seen), "the window getting focus does not read it either").toBe(true);
+ });
+
+ it("read it once the person opens it", async () => {
+ flushSync(() => dispatch({ type: "select", id: "shown" }));
+ await settle();
+ expect(reads.map((read) => read.path)).toEqual(["/api/bots/shown/read"]);
+ expect(taskOf("shown")?.unread).toBe(false);
+ expect(taskOf("other")?.unread, "another bot is untouched").toBe(true);
+ expect(shownChatHeldUnread(seen)).toBe(false);
+ });
+
+ it("read a reply that arrives while it is open after that, as before", async () => {
+ const start = reads.length;
+ announce(owner("shown", 4_000));
+ await settle();
+ expect(reads.slice(start)).toEqual([{ path: "/api/bots/shown/read", body: { threadId: "shown-thread", reason: "seen" } }]);
+ });
+});
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 99e99a286c..772b51392c 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -19,7 +19,7 @@ import { isNotificationFeedAction, reduceNotificationFeed, type NotificationFeed
import { bumpThreadUpdatedAt, mergeTaskStamps, rewindThreadUpdatedAt } from "./thread-stamps";
import { botOpensTo, closeTrayUnlessShown, closeUnpinnedTray, openBot, openThread, visibleNotificationThread, withRememberedTrayPin } from "./thread-navigation";
import { patchGroupTask } from "./thread-edits"; import { unreadBeyondFrame, wholeBotFrame } from "./bot-thread-frame";
-import type { EngineInstall } from "./engine-install";
+import type { EngineInstall } from "./engine-install"; import { holdRestoredUnread } from "./read-visible";
import { optimisticMessageId, optimisticUserMessage, sendArrived, sendReconciled } from "./optimistic-send";
import { patchedGroups, roomAnswers, snapshotPatch } from "./room-frames";
import { savedStateAction, type SavedOwner, type SavedSnapshot } from "./saved-state";
@@ -2994,7 +2994,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
loaded = await loadAll();
} while (alive && rehydrateRequested);
if (!alive || !loaded) return false;
- hydrated = true;
+ holdRestoredUnread(store.getState()); hydrated = true;
for (const frame of pendingFrames.splice(0)) store.enqueueFrame(frame);
store.flushFrames();
return true;