Skip to content

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

feat(sidebar): mark a whole department as read

Azad Jagtap2317b929b595
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index b8b77ca109..2d8daa015e 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -1607,7 +1607,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {
navigateThreadMenu(event);
}}>
<TeamMenuItems
- onAddBots={() => { closeTeamMenu(); setMoveToTeam(teamMotion.value!.name); }}
+ department={teamMotion.value!.name} onRead={closeTeamMenu} onAddBots={() => { closeTeamMenu(); setMoveToTeam(teamMotion.value!.name); }}
onRename={() => { closeTeamMenu(); (advanced ? setRenameTeam : botDrag.startRename)(teamMotion.value!.name); }}
onShare={() => { closeTeamMenu(); setShareTeam(teamMotion.value!.name); }}
onDelete={() => { closeTeamMenu(); setDeletingTeam(teamMotion.value!.name); }}
diff --git a/src/components/SidebarTeamMenu.test.ts b/src/components/SidebarTeamMenu.test.ts
new file mode 100644
index 0000000000..76ba05e4f0
--- /dev/null
+++ b/src/components/SidebarTeamMenu.test.ts
@@ -0,0 +1,70 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({ state: { bots: [] as unknown[], groups: [] as unknown[] }, dispatch: vi.fn(), api: vi.fn() }));
+vi.mock("@/state/store", async (original) => ({
+ ...await original<typeof import("@/state/store")>(),
+ useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }),
+ api: fixture.api,
+}));
+
+const { TeamMenuItems } = await import("./SidebarTeamMenu");
+
+let root: Root;
+let host: HTMLElement;
+const onRead = vi.fn();
+const noop = () => {};
+const render = (department?: string) => flushSync(() => root.render(createElement(TeamMenuItems, {
+ ...(department !== undefined ? { department } : {}), onRead, onAddBots: noop, onRename: noop, onShare: noop, onDelete: noop,
+})));
+const markRead = () => host.querySelector<HTMLButtonElement>("[data-team-mark-read]");
+const settle = () => new Promise((done) => setTimeout(done, 0));
+const opsBot = (id: string, unread: boolean) => ({ id, threadId: `${id}-main`, section: "Ops", unread, tasks: [{ threadId: `${id}-main`, title: "Main", createdAt: 0, unread }] });
+
+beforeEach(() => {
+ fixture.dispatch.mockReset();
+ fixture.api.mockReset();
+ onRead.mockReset();
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => { flushSync(() => root.unmount()); host.remove(); });
+
+describe("a department's Mark all as read", () => {
+ it("is offered only while something in the department is unread", () => {
+ fixture.state = { bots: [opsBot("ada", false)], groups: [{ id: "standup", unread: false, section: "Ops" }] };
+ render("Ops");
+ expect(markRead()).toBeNull();
+ fixture.state = { bots: [opsBot("ada", true)], groups: [] };
+ render("Ops");
+ expect(markRead()?.textContent).toBe("Mark all as read");
+ render();
+ expect(markRead()).toBeNull();
+ });
+
+ it("reads the department's bots and group chats, updates the sidebar and closes the menu", async () => {
+ fixture.state = { bots: [opsBot("ada", true)], groups: [{ id: "standup", unread: true, section: "Ops" }] };
+ fixture.api.mockImplementation(async (path: string) => path.startsWith("/api/groups/") ? { group: { id: "standup", unread: false } } : { bot: { id: "ada" } });
+ render("Ops");
+ flushSync(() => markRead()!.click());
+ await settle();
+ expect(fixture.api.mock.calls.map(([path]) => path)).toEqual(["/api/bots/ada/read", "/api/groups/standup/read"]);
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "botPatched", bot: { id: "ada" } });
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "groupPatched", group: { id: "standup", unread: false } });
+ expect(onRead).toHaveBeenCalled();
+ });
+
+ it("says so when a read fails, and keeps the menu open", async () => {
+ fixture.state = { bots: [opsBot("ada", true)], groups: [] };
+ fixture.api.mockRejectedValue(new Error("offline"));
+ render("Ops");
+ flushSync(() => markRead()!.click());
+ await settle();
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "error", message: expect.stringContaining("offline") });
+ expect(onRead).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/components/SidebarTeamMenu.tsx b/src/components/SidebarTeamMenu.tsx
index 6743ac5ff3..c7b6ffdd0e 100644
--- a/src/components/SidebarTeamMenu.tsx
+++ b/src/components/SidebarTeamMenu.tsx
@@ -1,12 +1,40 @@
-import { Network, Share2, SlidersHorizontal, SquarePen, Trash2, UserRound, Users } from "lucide-react";
+import { useState } from "react";
+import { CheckCheck, Loader2, Network, Share2, SlidersHorizontal, SquarePen, Trash2, UserRound, Users } from "lucide-react";
import { cn } from "@/lib/cn";
+import { departmentUnread, markDepartmentRead } from "@/lib/folder-read";
import { t } from "@/lib/i18n";
+import { api, useStore } from "@/state/store";
import { MENU_ITEM } from "./menu-recipe";
export { showWhoReportsToWhom } from "./TeamOrgChart";
/** A department's menu, from its line's ⋯ or a right-click on its name. */
-export function TeamMenuItems({ onAddBots, onRename, onShare, onDelete, onSetForAll, onSetOwner, onSeeReports }: {
+/** Reads every conversation of the department's bots and its group chats; shown only while something there is unread. */
+function MarkDepartmentRead({ name, className, onDone }: { name: string; className: string; onDone: () => void }) {
+ const { state, dispatch } = useStore();
+ const [reading, setReading] = useState(false);
+ const unread = departmentUnread(name, state.bots, state.groups);
+ if (!reading && unread.bots.length === 0 && unread.groups.length === 0) return null;
+ const read = async () => {
+ setReading(true);
+ try {
+ await markDepartmentRead(unread, (path, init) => api(path, init), (bot) => dispatch({ type: "botPatched", bot }), (group) => dispatch({ type: "groupPatched", group }));
+ onDone();
+ } catch (error) {
+ dispatch({ type: "error", message: error instanceof Error ? `${t("sidebar.bot.markAllReadFailed")} ${error.message}` : t("sidebar.bot.markAllReadFailed") });
+ } finally {
+ setReading(false);
+ }
+ };
+ return <button type="button" role="menuitem" data-team-mark-read className={className} disabled={reading} onClick={() => void read()}>
+ {reading ? <Loader2 size={16} className="animate-spin" /> : <CheckCheck size={16} />}{reading ? t("team.markingAllRead") : t("team.markAllRead")}
+ </button>;
+}
+
+export function TeamMenuItems({ onAddBots, onRename, onShare, onDelete, onSetForAll, onSetOwner, onSeeReports, department, onRead }: {
+ /** The department this menu is for: with it, the menu offers Mark all as read. */
+ department?: string;
+ onRead?: () => void;
onAddBots: () => void;
onRename: () => void;
onShare: () => void;
@@ -19,6 +47,7 @@ export function TeamMenuItems({ onAddBots, onRename, onShare, onDelete, onSetFor
return (
<>
<button type="button" role="menuitem" autoFocus className={item} onClick={onAddBots}><Users size={16} />{t("team.addBots")}</button>
+ {department !== undefined && <MarkDepartmentRead name={department} className={cn(item, "disabled:opacity-60")} onDone={onRead ?? (() => {})} />}
{onSetOwner && <button type="button" role="menuitem" className={item} onClick={onSetOwner}><UserRound size={16} />{t("owner.setForAll")}</button>}
{onSeeReports && <button type="button" role="menuitem" className={item} onClick={onSeeReports}><Network size={16} />{t("orgChart.seeWho")}</button>}
{onSetForAll && <button type="button" role="menuitem" className={item} onClick={onSetForAll}><SlidersHorizontal size={16} />{t("teamSettings.menu")}</button>}
diff --git a/src/lib/folder-read.test.ts b/src/lib/folder-read.test.ts
index 7e664d62ab..c317569d7b 100644
--- a/src/lib/folder-read.test.ts
+++ b/src/lib/folder-read.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { initialState, reducer, type AppState, type Bot, type BotAnnouncement, type Message } from "@/state/store";
-import { folderUnreadThreadIds, markFolderRead } from "./folder-read";
+import { departmentUnread, folderUnreadThreadIds, markDepartmentRead, markFolderRead } from "./folder-read";
const bot: Bot = {
id: "maus", threadId: "elsewhere", name: "Maus", title: "", description: "", notifications: true,
@@ -75,3 +75,49 @@ describe("mark folder as read", () => {
expect(onRead).not.toHaveBeenCalled();
});
});
+
+describe("mark a department as read", () => {
+ const member = (id: string, section: string | undefined, unread: boolean, extra: Partial<Bot> = {}): Bot => ({
+ ...bot, id, threadId: `${id}-main`, section, unread, projects: [],
+ tasks: [{ threadId: `${id}-main`, title: "Main", createdAt: 0, unread }, { threadId: `${id}-side`, title: "Side", createdAt: 1, unread }],
+ ...extra,
+ });
+ const bots = [member("ada", "Ops", true), member("ben", "Ops", false), member("cara", "Sales", true), member("dan", "Ops", true, { hidden: true }), member("eve", " Ops ", true)];
+ const groups = [
+ { id: "standup", unread: true, section: "Ops" }, { id: "quiet", unread: false, section: "Ops" },
+ { id: "dm", unread: true, section: "Ops", dm: true }, { id: "deals", unread: true, section: "Sales" },
+ ];
+
+ it("covers the department's shown bots with unread conversations and its unread group chats, nothing else", () => {
+ const unread = departmentUnread("Ops", bots, groups);
+ expect(unread.bots.map((b) => b.id)).toEqual(["ada", "eve"]);
+ expect(unread.groups.map((g) => g.id)).toEqual(["standup"]);
+ expect(departmentUnread("Nowhere", bots, groups)).toEqual({ bots: [], groups: [] });
+ });
+
+ it("reads every conversation of each bot, then each group chat, one request at a time", async () => {
+ const calls: string[] = [];
+ const request = vi.fn(async (path: string, init?: RequestInit) => {
+ calls.push(`${path} ${init?.body ?? ""}`.trim());
+ return path.startsWith("/api/groups/") ? { group: { id: "standup", unread: false } } : { bot: { id: "ada" } as BotAnnouncement };
+ });
+ const read = { bots: [] as string[], groups: [] as string[] };
+ await markDepartmentRead(departmentUnread("Ops", bots, groups), request, (b) => read.bots.push(b.id), (g) => read.groups.push(g.id));
+ expect(calls).toEqual([
+ '/api/bots/ada/read {"threadId":"ada-main"}', '/api/bots/ada/read {"threadId":"ada-side"}',
+ '/api/bots/eve/read {"threadId":"eve-main"}', '/api/bots/eve/read {"threadId":"eve-side"}',
+ "/api/groups/standup/read",
+ ]);
+ expect(read.groups).toEqual(["standup"]);
+ });
+
+ it("keeps the reads before a failure and reports it", async () => {
+ const request = vi.fn(async (path: string) => {
+ if (path.includes("eve")) throw new Error("offline");
+ return { bot: { id: "ada" } as BotAnnouncement };
+ });
+ await expect(markDepartmentRead(departmentUnread("Ops", bots, groups), request, () => {}, () => {})).rejects.toThrow("offline");
+ expect(request.mock.calls.map(([path]) => path)).toEqual(["/api/bots/ada/read", "/api/bots/ada/read", "/api/bots/eve/read"]);
+ });
+});
+
diff --git a/src/lib/folder-read.ts b/src/lib/folder-read.ts
index def1848d08..ee651693fd 100644
--- a/src/lib/folder-read.ts
+++ b/src/lib/folder-read.ts
@@ -1,6 +1,8 @@
-import type { Bot, BotAnnouncement } from "@/state/store";
+import type { Bot, BotAnnouncement, Group } from "@/state/store";
type FolderBot = Pick<Bot, "id" | "threadId" | "unread" | "tasks">;
+type DepartmentBot = FolderBot & Pick<Bot, "section" | "hidden">;
+type DepartmentGroup = Pick<Group, "id" | "unread" | "section" | "dm">;
export function botUnreadThreadIds(bot: FolderBot): string[] {
if (!bot.tasks?.length) return bot.unread ? [bot.threadId] : [];
@@ -46,3 +48,25 @@ async function markThreadsRead(
onRead(result.bot);
}
}
+
+/** What a department's "Mark all as read" covers: its shown bots, each with every conversation, and its group chats. */
+export function departmentUnread(name: string, bots: readonly DepartmentBot[], groups: readonly DepartmentGroup[]): { bots: DepartmentBot[]; groups: DepartmentGroup[] } {
+ return {
+ bots: bots.filter((bot) => !bot.hidden && (bot.section?.trim() || "") === name && botUnreadThreadIds(bot).length > 0),
+ groups: groups.filter((group) => !group.dm && group.section === name && group.unread),
+ };
+}
+
+/** One request at a time, so a failure keeps every read before it. */
+export async function markDepartmentRead(
+ unread: { bots: readonly DepartmentBot[]; groups: readonly DepartmentGroup[] },
+ request: (path: string, init?: RequestInit) => Promise<{ bot?: BotAnnouncement; group?: Partial<Group> & { id: string } }>,
+ onBot: (bot: BotAnnouncement) => void,
+ onGroup: (group: Partial<Group> & { id: string }) => void,
+): Promise<void> {
+ for (const bot of unread.bots) await markBotRead(bot, request as (path: string, init?: RequestInit) => Promise<{ bot: BotAnnouncement }>, onBot);
+ for (const group of unread.groups) {
+ const result = await request(`/api/groups/${group.id}/read`, { method: "POST" });
+ if (result.group) onGroup(result.group);
+ }
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 4c4330aa86..bc459cc669 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -1701,6 +1701,8 @@
"team.moveMany": "Move {count} bots",
"team.moveSelected": "Move selected bots",
"team.addBots": "Add bots",
+ "team.markAllRead": "Mark all as read",
+ "team.markingAllRead": "Marking as read…",
"team.manageBots": "Add or remove bots",
"team.manageBotsIn": "Add or remove bots in {name}",
"team.manageIntro": "Checked bots belong to this department. Uncheck a bot to move it to General.",