Skip to content

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

feat(sidebar): show recent conversation previews (#1000)

vincentd32b70fb686f
diff --git a/src/components/Sidebar.conversation-preview.dom.test.ts b/src/components/Sidebar.conversation-preview.dom.test.ts
new file mode 100644
index 0000000000..6fa3943cca
--- /dev/null
+++ b/src/components/Sidebar.conversation-preview.dom.test.ts
@@ -0,0 +1,171 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { initialState, StoreProvider, type Bot } from "@/state/store";
+
+const network = vi.hoisted(() => vi.fn());
+vi.mock("@/state/store", async (original) => ({ ...await original<typeof import("@/state/store")>(), api: network }));
+vi.mock("./DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({}) }));
+vi.mock("@/lib/interface-mode", async (original) => ({ ...await original<typeof import("@/lib/interface-mode")>(), useAdvancedMode: () => true }));
+
+const { BotThreadList, botRowProps } = await import("./Sidebar");
+const { BotConversations, forgetConversationLines, showAllConversations } = await import("./bot-panel/Conversations");
+let report: (entries: { target: Element; isIntersecting: boolean }[]) => void;
+class Observer {
+ constructor(callback: typeof report) { report = callback; }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+const bot: Bot = {
+ id: "preview-bot", threadId: "open", name: "Maus", title: "", description: "", notifications: true,
+ color: "green", unread: false, modelSelection: { instanceId: "fake", model: "test" },
+ messages: [{ id: "open-message", role: "bot", kind: "text", text: "Open conversation", at: 10 }],
+ projects: [{ id: "folder", name: "Folder" }],
+ tasks: [
+ { threadId: "open", title: "New thread", createdAt: 10 },
+ { threadId: "first", title: "New thread", createdAt: 9 },
+ { threadId: "second", title: "New thread", createdAt: 8 },
+ { threadId: "folded", title: "Folded", createdAt: 7, projectId: "folder" },
+ ],
+};
+let host: HTMLDivElement;
+let root: Root;
+const render = async (hidden = false) => act(async () => root.render(createElement(BotThreadList, {
+ ...botRowProps(initialState, vi.fn(), bot, { density: "comfortable", query: "", onMenu: vi.fn() }), selected: true, hidden,
+})));
+const row = (id: string) => host.querySelector(`[data-sidebar-thread-row="${id}"]`)!;
+const visible = async (id: string) => act(async () => {
+ report([{ target: row(id).parentElement!.parentElement!, isIntersecting: true }]);
+});
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ vi.stubGlobal("IntersectionObserver", Observer);
+ localStorage.clear();
+ forgetConversationLines();
+ network.mockReset();
+ network.mockImplementation(async (path: string) => ({ messages: [{ id: path, role: "bot", kind: "text", text: path.includes("first") ? "First answer" : "Second answer", at: 10 }] }));
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ host.remove();
+ vi.unstubAllGlobals();
+});
+
+it("distinguishes identical titles with their visible conversation lines", async () => {
+ await render();
+ expect(network).not.toHaveBeenCalled();
+ await visible("open");
+ await visible("first");
+ await visible("second");
+ expect(row("open").textContent).toContain("Open conversation");
+ expect(row("first").textContent).toContain("First answer");
+ expect(row("second").textContent).toContain("Second answer");
+ expect(row("first").textContent).not.toContain("Untitled chat");
+ expect(row("second").textContent).not.toContain("Untitled chat");
+ expect(row("first").querySelector('[title="First answer"]')?.className).toContain("truncate");
+ expect(network.mock.calls.map(([path]) => path).sort()).toEqual(["/api/threads/first/messages?limit=8", "/api/threads/second/messages?limit=8"]);
+ await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Collapse Folder threads"]')!.click());
+ expect(host.querySelector('[data-sidebar-thread-row="folded"]')).toBeNull();
+ await render(true);
+ expect(network).toHaveBeenCalledTimes(2);
+});
+
+it("limits concurrent requests and drops queued rows when hidden", async () => {
+ const resolve: Array<(value: unknown) => void> = [];
+ network.mockImplementation(() => new Promise((done) => { resolve.push(done); }));
+ const many = { ...bot, threadId: "open", tasks: [{ threadId: "open", title: "New thread", createdAt: 20 }, ...Array.from({ length: 5 }, (_, i) => ({ threadId: `queued-${i}`, title: "New thread", createdAt: 19 - i }))] };
+ await act(async () => root.render(createElement(BotThreadList, { ...botRowProps(initialState, vi.fn(), many, { density: "comfortable", query: "", onMenu: vi.fn() }), selected: true })));
+ for (let i = 0; i < 5; i++) await visible(`queued-${i}`);
+ expect(network).toHaveBeenCalledTimes(4);
+ await render(true);
+ await act(async () => { for (const done of resolve) done({ messages: [] }); });
+ expect(network).toHaveBeenCalledTimes(4);
+});
+
+it("lets the panel load all conversations immediately and share sidebar requests", async () => {
+ const pending: Array<(page: unknown) => void> = [];
+ network.mockImplementation(() => new Promise((resolve) => { pending.push(resolve); }));
+ const many: Bot = { ...bot, tasks: [{ threadId: "open", title: "New thread", createdAt: 20 }, ...Array.from({ length: 7 }, (_, i) => ({ threadId: `shared-${i}`, title: `Thread ${i}`, createdAt: 19 - i }))] };
+ const tree = (panel: boolean, hidden = false) => createElement(StoreProvider, null,
+ createElement(BotThreadList, { ...botRowProps(initialState, vi.fn(), many, { density: "comfortable", query: "", onMenu: vi.fn() }), selected: true, hidden }),
+ panel ? createElement(BotConversations, { bot: many }) : null,
+ );
+ await act(async () => root.render(tree(false)));
+ for (let i = 0; i < 5; i++) await visible(`shared-${i}`);
+ expect(network).toHaveBeenCalledTimes(4);
+ showAllConversations(many.id);
+ await act(async () => root.render(tree(true)));
+ const paths = network.mock.calls.map(([path]) => path as string);
+ expect(paths).toHaveLength(7);
+ expect(new Set(paths).size).toBe(7);
+ const sharedSignal = network.mock.calls.find(([path]) => path.includes("shared-0"))![1].signal as AbortSignal;
+ await act(async () => root.render(tree(true, true)));
+ expect(sharedSignal.aborted).toBe(false);
+ await act(async () => { for (const resolve of pending) resolve({ messages: [{ id: "answer", role: "bot", kind: "text", text: "Panel answer", at: 10 }] }); });
+ expect(host.querySelector('[data-conversation="shared-0"]')?.textContent).toContain("Panel answer");
+});
+
+it("cancels hidden sidebar requests and retries only after a row becomes visible again", async () => {
+ const pending: Array<(page: unknown) => void> = [];
+ network.mockImplementation(() => new Promise((resolve) => { pending.push(resolve); }));
+ await render();
+ await visible("first");
+ const signal = network.mock.calls[0]![1].signal as AbortSignal;
+ await render(true);
+ expect(signal.aborted).toBe(true);
+ await act(async () => pending[0]!({ messages: [{ id: "old", role: "bot", kind: "text", text: "Old answer", at: 10 }] }));
+ await render();
+ await visible("first");
+ expect(network).toHaveBeenCalledTimes(2);
+ await act(async () => pending[1]!({ messages: [{ id: "new", role: "bot", kind: "text", text: "New answer", at: 10 }] }));
+ expect(row("first").textContent).toContain("New answer");
+ expect(row("first").textContent).not.toContain("Old answer");
+});
+
+it("waits for a cancelled request to settle before re-requesting a visible row", async () => {
+ const pending: Array<(page: unknown) => void> = [];
+ network.mockImplementation(() => new Promise((resolve) => { pending.push(resolve); }));
+ await render();
+ await visible("first");
+ await render(true);
+ await render();
+ await visible("first");
+ expect(network).toHaveBeenCalledTimes(1);
+ await act(async () => pending[0]!({ messages: [] }));
+ expect(network).toHaveBeenCalledTimes(2);
+ await act(async () => pending[1]!({ messages: [{ id: "new", role: "bot", kind: "text", text: "New answer", at: 10 }] }));
+ expect(row("first").textContent).toContain("New answer");
+});
+
+it("does not repopulate a cleared preview cache from a late response", async () => {
+ const pending: Array<(page: unknown) => void> = [];
+ network.mockImplementation(() => new Promise((resolve) => { pending.push(resolve); }));
+ await render();
+ await visible("first");
+ await render(true);
+ forgetConversationLines();
+ await act(async () => pending[0]!({ messages: [{ id: "old", role: "bot", kind: "text", text: "Old answer", at: 10 }] }));
+ await render();
+ await visible("first");
+ expect(network).toHaveBeenCalledTimes(2);
+ await act(async () => pending[1]!({ messages: [] }));
+});
+
+it("does not retry a failed sidebar request on an unrelated rerender", async () => {
+ network.mockRejectedValue(new Error("offline"));
+ await render();
+ await visible("first");
+ await render();
+ expect(network).toHaveBeenCalledTimes(1);
+ await render(true);
+ await render();
+ await visible("first");
+ expect(network).toHaveBeenCalledTimes(2);
+});
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index 2476992cb3..89a5e1a620 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -39,7 +39,8 @@ import { GroupThreadList } from "./SidebarGroupThreadList";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { draggedFolder, FOLDER_DRAG_TYPE, moveFolder, placeFolder } from "@/lib/folder-order";
import { folderUnreadThreadIds, markFolderRead } from "@/lib/folder-read";
-import { HelperThreadGroup, isArchived, orderedThreadList, partitionHelperThreads, SidebarThreadRow, stampClock, threadRecency, threadRowActions, useRelativeNow, useRevealedThreadRow, useSnoozeExpiry, visibleSidebarThreads } from "./SidebarThreadRow";
+import { HelperThreadGroup, isArchived, orderedThreadList, partitionHelperThreads, stampClock, threadRecency, threadRowActions, useRelativeNow, useRevealedThreadRow, useSnoozeExpiry, visibleSidebarThreads } from "./SidebarThreadRow";
+import { SidebarConversationRow } from "./SidebarConversationRow";
import { setSidebarDensity, useSidebarDensity, usePinnedCircles, useSidebarShowAllThreads, useUniversalPins, type SidebarDensity } from "@/lib/sidebar-preferences";
import {
ATTENTION_SECTION_ID,
@@ -448,7 +449,7 @@ export function currentArchivableBot(bots: readonly Bot[], id: string): Bot | un
const NO_FOLDERS: BotProject[] = [];
-export function BotThreadList({ bot, selected, drafting, query, pendingQueued, routineRuns, reveal, locale, dispatch, activityLabel, hidden = false }: BotRowProps & {
+export function BotThreadList({ bot, selected, drafting, query, pendingQueued, routineRuns, reveal, locale, dispatch, instances, activityLabel, hidden = false }: BotRowProps & {
activityLabel?: string;
hidden?: boolean;
}) {
@@ -512,7 +513,7 @@ export function BotThreadList({ bot, selected, drafting, query, pendingQueued, r
}), [botId, dispatch]);
const renderThread = (task: (typeof tasks)[number]) => {
const thread = currentTaskBot(bot, task.threadId);
- return <SidebarThreadRow key={task.threadId} task={{ ...task, busy: thread.busy, activity: thread.activity, waitingForTeammates: thread.waitingForTeammates }} ownerId={bot.id} current={selected && !drafting && task.threadId === bot.threadId} main={task.threadId === bot.mainThreadId} folders={projects}
+ return <SidebarConversationRow key={task.threadId} bot={bot} instances={instances} task={{ ...task, busy: thread.busy, activity: thread.activity, waitingForTeammates: thread.waitingForTeammates }} ownerId={bot.id} current={selected && !drafting && task.threadId === bot.threadId} main={task.threadId === bot.mainThreadId} folders={projects}
activityLabel={task.threadId === bot.threadId ? activityLabel : undefined} now={stampClock(threadRecency(task), now)} locale={locale} {...actions}
selectMode={bulk.active} checked={selection.has(task.threadId)} onToggleSelect={bulk.toggle} />;
};
diff --git a/src/components/SidebarConversationRow.tsx b/src/components/SidebarConversationRow.tsx
new file mode 100644
index 0000000000..d26878a8f6
--- /dev/null
+++ b/src/components/SidebarConversationRow.tsx
@@ -0,0 +1,14 @@
+import { useRef, type ComponentProps } from "react";
+import { useOnScreen } from "@/lib/on-screen";
+import { currentTaskBot, type Bot, type InstanceInfo } from "@/state/store";
+import { useSidebarRecentMessages } from "./bot-panel/Conversations";
+import { lastLine } from "./sidebar-preview";
+import { SidebarThreadRow } from "./SidebarThreadRow";
+
+export function SidebarConversationRow({ bot, instances, ...props }: ComponentProps<typeof SidebarThreadRow> & { bot: Bot; instances: InstanceInfo[] }) {
+ const ref = useRef<HTMLDivElement>(null);
+ const onScreen = useOnScreen(ref);
+ const messages = useSidebarRecentMessages(bot, props.task, onScreen);
+ const preview = messages ? lastLine(currentTaskBot(bot, props.task.threadId), messages, instances, false) : undefined;
+ return <div ref={ref}><SidebarThreadRow {...props} preview={preview} /></div>;
+}
diff --git a/src/components/SidebarThreadRow.test.ts b/src/components/SidebarThreadRow.test.ts
index dbef95fd97..ac5daa5ff1 100644
--- a/src/components/SidebarThreadRow.test.ts
+++ b/src/components/SidebarThreadRow.test.ts
@@ -254,17 +254,23 @@ describe("threads a bot closed", () => {
});
describe("formatUpdatedAt", () => {
- it("uses the runtime locale and timezone, and skips a missing stamp", () => {
- const at = Date.UTC(2026, 0, 15, 0, 30);
- expect(formatUpdatedAt(at)).toBe(new Date(at).toLocaleString([], { dateStyle: "short", timeStyle: "short" }));
- expect(formatUpdatedAt(0)).toBe("");
- expect(formatUpdatedAt(Number.NaN)).toBe("");
- const markup = renderToStaticMarkup(createElement(SidebarThreadRow, {
- task: { threadId: "t", title: "Notes", updatedAt: at },
- ownerId: "b", current: false, onSelect: vi.fn(), onRename: vi.fn(), onDelete: vi.fn(), locale: "en",
- }));
- expect(markup).toContain(formatUpdatedAt(at));
- expect(markup).toContain(new Date(at).toISOString());
+ it("uses the app and browser locale and runtime timezone, and skips a missing stamp", () => {
+ setLocale("en");
+ vi.stubGlobal("navigator", { language: "en-GB" });
+ try {
+ const at = Date.UTC(2026, 0, 15, 0, 30);
+ expect(formatUpdatedAt(at)).toBe(new Date(at).toLocaleString("en-GB", { dateStyle: "short", timeStyle: "short" }));
+ expect(formatUpdatedAt(0)).toBe("");
+ expect(formatUpdatedAt(Number.NaN)).toBe("");
+ const markup = renderToStaticMarkup(createElement(SidebarThreadRow, {
+ task: { threadId: "t", title: "Notes", updatedAt: at },
+ ownerId: "b", current: false, onSelect: vi.fn(), onRename: vi.fn(), onDelete: vi.fn(), locale: "en",
+ }));
+ expect(markup).toContain(formatUpdatedAt(at));
+ expect(markup).toContain(new Date(at).toISOString());
+ } finally {
+ vi.unstubAllGlobals();
+ }
});
});
diff --git a/src/components/SidebarThreadRow.tsx b/src/components/SidebarThreadRow.tsx
index 7ef167472c..609241c0bf 100644
--- a/src/components/SidebarThreadRow.tsx
+++ b/src/components/SidebarThreadRow.tsx
@@ -318,6 +318,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
const [renaming, setRenaming] = useState(false);
const [draft, setDraft] = useState(task.title);
const displayTitle = localizedTaskTitle(task.title);
+ const previewAsTitle = !panel && Boolean(preview) && (!task.title || task.title === "New thread");
const finishing = useRef(false);
const actionRef = useRef<HTMLButtonElement>(null);
const status = task.activity === "waiting-on-you" ? t("task.waiting") : isWaitingOnTeammate(task) ? t("task.waitingOnTeammate") : isWorking(task) ? activityLabel ?? t("chat.activity.working") : task.queued ? t("task.queued") : null;
@@ -343,7 +344,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
if (title) onRename(task, title);
};
const heading = <span className={cn("flex min-w-0 flex-1 items-baseline gap-1.5", panel && "pe-6")}>
- <span dir="auto" className={cn("min-w-0 flex-1 max-w-max truncate", task.unread && "font-semibold text-ink", (closed || archived || snoozed) && !current && "text-ink-tertiary")}>{displayTitle}</span>
+ <span dir="auto" title={previewAsTitle ? preview : undefined} className={cn("min-w-0 flex-1 max-w-max truncate", task.unread && "font-semibold text-ink", (closed || archived || snoozed) && !current && "text-ink-tertiary")}>{previewAsTitle ? preview : displayTitle}</span>
{main && <MainThreadMark className="self-center" />}
{byline && (
<span className="min-w-0 max-w-[45%] shrink truncate font-normal text-ink-tertiary">{byline}</span>
@@ -374,6 +375,9 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
{isWorking(task) && <span data-thread-working="" className="flex items-center gap-1 text-[12px] font-normal text-success">
{t("chat.activity.working")}{task.turnStartedAt ? <><span aria-hidden="true">·</span><WorkingTimer since={task.turnStartedAt} /></> : null}
</span>}
+ </span> : preview && !previewAsTitle ? <span className="flex min-w-0 flex-1 flex-col">
+ {heading}
+ <span dir="auto" title={preview} className="min-w-0 truncate text-[12px] font-normal leading-4 text-ink-tertiary">{preview}</span>
</span> : heading}
</button>}
{advanced && task.link && <a href={task.link} target="_blank" rel="noreferrer" dir="ltr" title={task.link} aria-label={t("task.openLink", { link: threadLinkLabel(task.link) ?? task.link })}
diff --git a/src/components/bot-panel/Conversations.tsx b/src/components/bot-panel/Conversations.tsx
index 888426dd3e..0c043f8908 100644
--- a/src/components/bot-panel/Conversations.tsx
+++ b/src/components/bot-panel/Conversations.tsx
@@ -21,9 +21,39 @@ const MAX_CACHED = 200;
type Page = { messages?: Message[]; activeLeafId?: string | null };
const fetched = new Map<string, Message[]>();
const asked = new Set<string>();
+const requests = new Map<string, { promise: Promise<void>; signal?: AbortSignal; promote?: () => void }>();
+let generation = 0;
const lineKey = (task: { threadId: string; updatedAt?: number; createdAt?: number }) => `${task.threadId}@${threadRecency(task)}`;
+function fetchLine(key: string, signal?: AbortSignal, promote?: () => void): Promise<void> {
+ const existing = requests.get(key);
+ if (existing) {
+ if (existing.signal?.aborted) {
+ const retry = () => signal?.aborted ? undefined : fetchLine(key, signal, promote);
+ return existing.promise.then(retry, retry);
+ }
+ if (!signal && existing.promote) {
+ const promote = existing.promote;
+ existing.promote = undefined;
+ promote();
+ }
+ return existing.promise;
+ }
+ const threadId = key.slice(0, key.lastIndexOf("@"));
+ const currentGeneration = generation;
+ const entry = { promise: Promise.resolve(), signal, promote };
+ entry.promise = api<Page>(`/api/threads/${encodeURIComponent(threadId)}/messages?limit=${LAST_LINE_PAGE}`, signal ? { background: true, signal } : { background: true })
+ .then((page) => {
+ if (currentGeneration !== generation || signal?.aborted) return;
+ fetched.set(key, visibleMessages({ messages: page.messages ?? [], activeLeafId: page.activeLeafId ?? undefined }));
+ if (fetched.size > MAX_CACHED) fetched.delete(fetched.keys().next().value!);
+ })
+ .finally(() => { if (requests.get(key) === entry) requests.delete(key); });
+ requests.set(key, entry);
+ return entry.promise;
+}
+
/** Each listed conversation's newest messages: the open one from the chat, the rest fetched once per change. */
function useRecentMessages(bot: Bot, threads: readonly { threadId: string; updatedAt?: number; createdAt?: number }[]): (threadId: string) => Message[] | undefined {
const [, settle] = useState(0);
@@ -33,15 +63,7 @@ function useRecentMessages(bot: Bot, threads: readonly { threadId: string; updat
if (!missing) return;
for (const key of missing.split(",")) {
asked.add(key);
- const threadId = key.slice(0, key.lastIndexOf("@"));
- void api<Page>(`/api/threads/${encodeURIComponent(threadId)}/messages?limit=${LAST_LINE_PAGE}`, { background: true })
- .then((page) => {
- fetched.set(key, visibleMessages({ messages: page.messages ?? [], activeLeafId: page.activeLeafId ?? undefined }));
- if (fetched.size > MAX_CACHED) fetched.delete(fetched.keys().next().value!);
- settle((count) => count + 1);
- })
- .catch(() => {})
- .finally(() => asked.delete(key));
+ void fetchLine(key).then(() => settle((count) => count + 1)).catch(() => {}).finally(() => asked.delete(key));
}
}, [missing]);
const open = visibleMessages(bot);
@@ -49,6 +71,65 @@ function useRecentMessages(bot: Bot, threads: readonly { threadId: string; updat
return (threadId) => threadId === bot.threadId ? open : fetched.get(byThread.get(threadId) ?? "");
}
+const sidebarQueue = new Map<string, Set<() => void>>();
+const sidebarActive = new Map<string, { listeners: Set<() => void>; cancel: () => void }>();
+let sidebarRunning = 0;
+
+function startSidebarLines() {
+ for (const [key, listeners] of sidebarQueue) {
+ if (sidebarRunning >= 4) break;
+ sidebarQueue.delete(key);
+ if (fetched.has(key)) { for (const notify of listeners) notify(); continue; }
+ const controller = new AbortController();
+ let released = false;
+ let promoted = false;
+ let cancelled = false;
+ sidebarRunning++;
+ const release = () => {
+ if (released) return;
+ released = true;
+ clearTimeout(timeout);
+ sidebarRunning--;
+ };
+ const timeout = setTimeout(() => controller.abort(), 15_000);
+ const promote = () => { promoted = true; release(); startSidebarLines(); };
+ const cancel = () => { if (!listeners.size && !promoted) { cancelled = true; controller.abort(); } };
+ const active = { listeners, cancel };
+ sidebarActive.set(key, active);
+ const aborted = new Promise<void>((_, reject) => controller.signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true }));
+ const existingPanelRequest = requests.has(key) && !requests.get(key)?.promote;
+ const request = fetchLine(key, controller.signal, promote);
+ if (existingPanelRequest) release();
+ void Promise.race([request, aborted]).then(() => {
+ if (!controller.signal.aborted) for (const notify of listeners) notify();
+ }).catch(() => {}).finally(() => {
+ if (sidebarActive.get(key) === active) sidebarActive.delete(key);
+ if (cancelled && listeners.size) sidebarQueue.set(key, listeners);
+ release();
+ startSidebarLines();
+ });
+ }
+}
+
+export function useSidebarRecentMessages(bot: Bot, task: { threadId: string; updatedAt?: number; createdAt?: number }, onScreen: boolean): Message[] | undefined {
+ const [, settle] = useState(0);
+ const key = lineKey(task);
+ useEffect(() => {
+ if (!onScreen || task.threadId === bot.threadId || fetched.has(key)) return;
+ const active = sidebarActive.get(key);
+ const listeners = active?.listeners ?? sidebarQueue.get(key) ?? new Set<() => void>();
+ const notify = () => settle((count) => count + 1);
+ listeners.add(notify);
+ if (!active) { sidebarQueue.set(key, listeners); startSidebarLines(); }
+ return () => {
+ listeners.delete(notify);
+ if (!listeners.size && sidebarQueue.get(key) === listeners) sidebarQueue.delete(key);
+ sidebarActive.get(key)?.cancel();
+ };
+ }, [onScreen, key, task.threadId, bot.threadId]);
+ return task.threadId === bot.threadId ? visibleMessages(bot) : fetched.get(key);
+}
+
/** The sidebar's "N more" opens this list with every conversation showing, whether or not the panel is already open. */
let showAllNext: string | null = null;
const showAllListeners = new Set<(botId: string) => void>();
@@ -59,8 +140,13 @@ export function showAllConversations(botId: string): void {
/** Tests only. */
export function forgetConversationLines(): void {
+ generation++;
fetched.clear();
asked.clear();
+ sidebarQueue.clear();
+ for (const active of sidebarActive.values()) { active.listeners.clear(); active.cancel(); }
+ sidebarActive.clear();
+ requests.clear();
}
export function BotConversations({ bot }: { bot: Bot }) {