Skip to content

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

Threads as sub-labels under the bot in Simple mode's sidebar (#7006)

Milind Soni3d0fea1af6b7
diff --git a/DESIGN.md b/DESIGN.md
index 70e626add1..e335e8d90c 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -44,7 +44,9 @@ where they belong instead of adding new places.
screen; Advanced mode's composer shows the model under its field instead. Anything else goes in the bot panel, a menu or the command palette.
A button that exists only while the conversation has what it shows (its
pinned message) is fine: it opens a menu and is gone when there is nothing
- to show.
+ to show. One exception: **New thread** (a plus, also ⌘T) sits at the end of the
+ header in both modes, because starting a thread is an everyday action people
+ look for at the top.
- **No count badges and no "needs you" summaries** above the sidebar list or
in the header. A status mark on the row it belongs to is fine.
- **Settings for one bot live in its bot panel.** App-wide settings live in
@@ -351,8 +353,9 @@ on. Simple is the default for new installs.
place in both modes. Advanced may show more rows or more detail.
One exception: where Advanced already shows something in place (a bot's
threads as a tree under its row), Simple may offer a shortcut to the same
- thing there instead of a second copy of it: a menu that opens on a click
- of a small chevron, never on hover. A second: Advanced mode's composer puts
+ thing there instead of a second copy of it: a menu, or the threads unfolded
+ under the bot's row, that opens on a click of a small chevron, never on
+ hover. A second: Advanced mode's composer puts
the field on its own line with a footer row under it, and the model and
effort picker sits in that footer, next to the + menu both modes share.
- **Switching modes never loses data.**
diff --git a/src/App.tsx b/src/App.tsx
index 7009109711..06b48b1349 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -227,9 +227,10 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
if (!mod) return;
const bots = shortcutBots(state.bots.filter((b) => !b.hidden), shownBotIds(document.querySelector("[data-sidebar-root]")));
const step = e.shiftKey ? botCycleStep(e) : null;
- if (e.key.toLowerCase() === "n" && !e.altKey) {
+ const newThreadKey = e.key.toLowerCase() === "t" && !e.shiftKey && !e.altKey;
+ if ((e.key.toLowerCase() === "n" || newThreadKey) && !e.altKey) {
e.preventDefault();
- if (e.shiftKey) {
+ if (e.shiftKey || newThreadKey) {
const selected = state.bots.find((bot) => bot.id === state.selectedId && !bot.hidden);
if (!e.repeat && selected && selected.yourAccess !== "view") dispatch({ type: "newTask", botId: selected.id });
} else {
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 73378e5d1c..677294dd9f 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -89,7 +89,7 @@ import { ScreenFrame } from "./ScreenFrame";
import { CompactionChip, DigestChip } from "./DigestChip";
import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffBadge } from "./BotRole";
import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { HeaderShare } from "./bot-access/HeaderShare"; import { ThreadPresenceFaces } from "./TeamPresence"; import { useStoreRef } from "@/state/store-ref"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { sameDrawnBots } from "@/lib/drawn-bots"; import { ChatActivityControls, chatActivityMessages, useChatActivity } from "./ChatActivity";
-import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";
+import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated"; import { NewThreadHeaderButton } from "./NewThreadHeaderButton";
import { ModelPicker } from "./ModelPicker"; import { useFailedTurnFix } from "./FailedTurnFix";
import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine"; import { ownChatStarted } from "@/state/team-chats"; import { isNewChatThread } from "@/state/new-chat";
import { useChatFindRequests, useChatFindShortcut } from "@/lib/chat-find";
@@ -1057,7 +1057,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
>
<Monitor size={16} />{busy && place === "browser" && <span aria-hidden="true" className="absolute right-1 top-1 size-1.5 animate-pulse rounded-full bg-success" data-testid="computer-button-live" />}
</button>}
- <HeaderShare bot={bot} />{phoneMenu ? <ChatMoreMenu bot={bot} phoneHeader /> : (advanced || remoteClient) && <ChatHeaderMenu key={`menu:${bot.threadId}`} bot={bot} />}
+ <HeaderShare bot={bot} />{!inForkPanel && <NewThreadHeaderButton botId={bot.id} />}{phoneMenu ? <ChatMoreMenu bot={bot} phoneHeader /> : (advanced || remoteClient) && <ChatHeaderMenu key={`menu:${bot.threadId}`} bot={bot} />}
</div>
</div>
</div>
diff --git a/src/components/MenuMotion.tsx b/src/components/MenuMotion.tsx
index 15401a497b..ec3ab6a2af 100644
--- a/src/components/MenuMotion.tsx
+++ b/src/components/MenuMotion.tsx
@@ -3,7 +3,7 @@ import { useLayoutEffect, useRef, useState } from "react";
/** Same length as `--animate-pop-in` in styles.css. */
export const MENU_MOTION_MS = 200;
-function reducedMotion(): boolean {
+export function reducedMotion(): boolean {
if (typeof document === "undefined") return false;
if (document.documentElement.dataset.reducedMotion === "true") return true;
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
diff --git a/src/components/NewThreadHeaderButton.tsx b/src/components/NewThreadHeaderButton.tsx
new file mode 100644
index 0000000000..251957aaa7
--- /dev/null
+++ b/src/components/NewThreadHeaderButton.tsx
@@ -0,0 +1,20 @@
+import { Plus } from "lucide-react";
+import { t } from "@/lib/i18n";
+import { useStoreDispatch } from "@/state/store-select";
+
+export function NewThreadHeaderButton({ botId }: { botId: string }) {
+ const dispatch = useStoreDispatch();
+ return (
+ <button
+ type="button"
+ data-new-thread
+ onClick={() => dispatch({ type: "newTask", botId })}
+ aria-label={t("task.newShort")}
+ aria-keyshortcuts="Meta+T Control+T"
+ title={t("task.newShort")}
+ className="flex size-9 shrink-0 items-center justify-center rounded-full text-ink-secondary transition-colors duration-[120ms] hover:bg-ink/[0.06] hover:text-ink active:bg-ink/[0.08] motion-reduce:transition-none"
+ >
+ <Plus size={16} aria-hidden="true" />
+ </button>
+ );
+}
diff --git a/src/components/Sidebar.advanced-back.test.ts b/src/components/Sidebar.advanced-back.test.ts
index 10e9516aab..15d48c5ebe 100644
--- a/src/components/Sidebar.advanced-back.test.ts
+++ b/src/components/Sidebar.advanced-back.test.ts
@@ -45,8 +45,8 @@ async function draw() {
await settle();
}
// Simple mode's hover list carries the same name as the tree's disclosure, so the tree's is the one that is not the list's.
-const expand = () => document.querySelector<HTMLButtonElement>(`button[aria-label="${t("task.expandNamed", { name: "Atlas" })}"]:not([data-bot-threads-peek])`);
-const peek = () => document.querySelector('[data-bot-threads-peek="atlas"]');
+const expand = () => document.querySelector<HTMLButtonElement>(`button[aria-label="${t("task.expandNamed", { name: "Atlas" })}"]:not([data-bot-threads-fold])`);
+const peek = () => document.querySelector('[data-bot-threads-fold="atlas"]');
const folder = () => document.querySelector('[data-sidebar-folder-row="taxes"]');
beforeAll(() => {
@@ -78,7 +78,7 @@ describe("thread folders after Advanced mode comes back", () => {
await draw();
expect(folder()).toBeNull();
expect(expand()).toBeNull();
- expect(peek(), "the hover list stands in for the tree").not.toBeNull();
+ expect(peek(), "the chevron unfolds the threads under the row instead").not.toBeNull();
flushSync(() => setAdvancedMode(true));
await draw();
expect(peek()).toBeNull();
diff --git a/src/components/Sidebar.simple-mode.test.ts b/src/components/Sidebar.simple-mode.test.ts
index de97d7804a..59de0cb14d 100644
--- a/src/components/Sidebar.simple-mode.test.ts
+++ b/src/components/Sidebar.simple-mode.test.ts
@@ -561,7 +561,7 @@ describe("bot-first sidebar", () => {
]);
});
- it.each(densities)("lists the bot with no thread tree in Simple mode, only a row for each thread that waits on the person, keeping its dots, in %s density", (density) => {
+ it.each(densities)("lists the bot with no thread tree in Simple mode, only a row for each thread that waits on the person or is going, keeping its dots, in %s density", (density) => {
// Its threads were left expanded in Advanced mode.
fixture.advanced = true;
let tree: ReactNode;
@@ -576,18 +576,21 @@ describe("bot-first sidebar", () => {
expect(markup).toContain(`data-sidebar-bot-row="${bot.id}"`);
expect(markup).not.toContain("data-sidebar-thread-row");
expect(markup).not.toContain("data-sidebar-folder-row");
- expect(markup).not.toContain('aria-label="Atlas threads"');
- if (density === "icons") expect(markup).not.toContain("data-sidebar-bot-activity");
- else {
- // It asks the person something, or has a reply they have not read; running, queued and idle threads stay out.
- expect([...markup.matchAll(/data-sidebar-activity-row="([^"]+)"/g)].map((match) => match[1]).sort()).toEqual(["approval", "unread"]);
+ if (density === "icons") {
+ expect(markup).not.toContain("data-sidebar-bot-activity");
+ expect(markup).not.toContain('aria-label="Atlas threads"');
+ } else {
+ // Folded: what asks the person something, is going or queued, or has a reply they have not read; idle threads stay out.
+ expect(markup).toContain('data-bot-threads-fold="atlas" aria-expanded="false"');
+ expect([...markup.matchAll(/data-sidebar-activity-row="([^"]+)"/g)].map((match) => match[1]).sort()).toEqual(["approval", "queued", "unread", "working"]);
}
expect(markup).toContain('data-testid="waiting-dot"');
}
const unread = renderToStaticMarkup(createElement(BotListItem, rowProps(density, { ...bot, tasks: [bot.tasks![0]!, bot.tasks![5]!] })));
expect(unread.includes('data-sidebar-activity-row="unread"')).toBe(density !== "icons");
const read = renderToStaticMarkup(createElement(BotListItem, rowProps(density, { ...bot, unread: false, tasks: [bot.tasks![0]!, bot.tasks![1]!, bot.tasks![3]!] })));
- expect(read).not.toContain("data-sidebar-activity-row");
+ // Nothing unread, but a thread still running keeps its row while the bot is folded.
+ expect([...read.matchAll(/data-sidebar-activity-row="([^"]+)"/g)].map((match) => match[1])).toEqual(density === "icons" ? [] : ["working"]);
expect(unread).toContain(density === "icons" ? "rounded-full border border-panel bg-accent" : density === "comfortable" ? 'data-testid="unread-dot"' : 'aria-label="Unread threads"');
forgetSearchDisclosuresForTests();
});
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index ddc47d8676..6a5d1a9ef0 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -22,7 +22,7 @@ import { copyText } from "@/lib/copy-text";
import type { LocaleKey } from "@/locales";
import { ConfirmDialog } from "./ConfirmDialog";
import { BulkSelectFilters, ThreadListFooter, deleteThreadsInBulk, retitleThreadsInBulk, useBulkSelect } from "./BulkSelectBar";
-import { SidebarBotThreadsPeek } from "./SidebarBotThreadsPeek";
+import { SidebarThreadLabels, ThreadFoldChevron, useRowUnfolded } from "./SidebarThreadLabels";
import { RoomMark, StackedMauses } from "./StackedMauses";
import { LocalComputerAutoWarning } from "./LocalComputerAutoWarning";
import { nextRename } from "@/lib/rename";
@@ -707,7 +707,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {
const iconOnly = density === "icons";
const expanded = showThreads && !iconOnly && threadsOpen && hasThreadList;
useEffect(() => { if (iconOnly) setRenaming(false); }, [iconOnly]);
- const simpleRow = !advanced && !showThreads && density === "comfortable";
+ const simpleRow = !advanced && !showThreads && density === "comfortable", unfolded = useRowUnfolded(bot, props.drafting) && simpleRow, rowSelected = selected && !unfolded;
const simpleList = !advanced && !iconOnly;
const railTile = iconOnly && !advanced;
const avatarSize = iconOnly ? (railTile ? 36 : 44) : showThreads ? 32 : simpleRow ? 36 : 44;
@@ -723,8 +723,8 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {
: simpleRow ? "gap-2.5 rounded-xl p-2 md:h-[54px] md:py-0"
: cn(showThreads ? "gap-2 py-2" : "gap-3 py-2", showThreads ? "pl-6 pr-9 group-hover:pr-[5.75rem] group-focus-within:pr-[5.75rem] max-md:pr-9 touch:pr-[5.75rem]" : "pl-2.5 pr-9"),
!iconOnly && "max-md:rounded-2xl max-md:py-2.5",
- selected ? rowSelectedSurface : "hover:bg-ink/[0.06]",
- simpleRow && rowSurface(selected),
+ rowSelected ? rowSelectedSurface : "hover:bg-ink/[0.06]",
+ simpleRow && rowSurface(rowSelected),
);
const { waiting, working, failed, teammateWait, queued } = sidebarBotStatus(bot, pendingQueued, visible);
const { unread, noticing } = useBotUnread(bot);
@@ -865,7 +865,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {
: undefined
}
aria-busy={deleting || undefined} aria-keyshortcuts={drag ? "Alt+ArrowUp Alt+ArrowDown" : undefined}
- aria-current={selected && !expanded && !renaming ? "page" : undefined}
+ aria-current={rowSelected && !expanded && !renaming ? "page" : undefined}
data-sidebar-bot-row={bot.id} data-look="sidebar-bot"
title={renaming ? undefined : tooltip}
onClick={onSelect}
@@ -900,7 +900,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {
<button type="button" data-bot-actions={bot.id} aria-label={t("sidebar.bot.actions", { name: bot.name })} title={t("sidebar.bot.actions", { name: bot.name })} aria-haspopup="menu" onClick={(event) => { const rect = event.currentTarget.getBoundingClientRect(); onMenu({ botId: bot.id, x: rect.left, y: rect.bottom }); }}
className={cn("absolute top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded text-ink-secondary hover:bg-raised hover:text-ink", simpleRow ? "end-[3px] top-1.5 size-6 translate-y-0 rounded-lg" : "right-1",
selected && !simpleRow ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 max-md:pointer-events-auto max-md:opacity-70 touch:pointer-events-auto touch:opacity-70")}><MoreHorizontal size={16} /></button>
- </>}{!renaming && !deleting && simpleRow && <SidebarBotThreadsPeek bot={bot} onScreen={selected} dispatch={dispatch} />}
+ </>}{!renaming && !deleting && simpleRow && <ThreadFoldChevron bot={bot} dispatch={dispatch} />}
{deleting && iconOnly && (
<span className="pointer-events-none absolute bottom-1 right-1 rounded-full bg-card p-1 text-ink-secondary">
<Loader2 size={12} className="animate-spin" />
@@ -910,7 +910,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {
{advanced && !iconOnly && threadsOpen && hasThreadList && <BotThreadList {...props} hidden={!showThreads}
activityLabel={liveActivityLabel(sidebarMessage(last))}
query={bot.name.toLowerCase().includes(query.toLowerCase()) || bot.title.toLowerCase().includes(query.toLowerCase()) ? "" : query} />}
- {(advanced || (!iconOnly && (waiting || unread || bot.tasks?.some(runningRoutineRun)))) && <SidebarBotActivity bot={bot} rowThreadId={selected ? bot.threadId : botOpensTo(bot, showThreads)} density={density} pendingQueued={pendingQueued} dispatch={dispatch} waitingOnly={!advanced} runsOnly={expanded} />}
+ {simpleRow ? <SidebarThreadLabels bot={bot} selected={selected} drafting={props.drafting} rowThreadId={selected ? bot.threadId : botOpensTo(bot, showThreads)} pendingQueued={pendingQueued} dispatch={dispatch} /> : (advanced || (!iconOnly && (waiting || unread || bot.tasks?.some(runningRoutineRun)))) && <SidebarBotActivity bot={bot} rowThreadId={selected ? bot.threadId : botOpensTo(bot, showThreads)} density={density} pendingQueued={pendingQueued} dispatch={dispatch} waitingOnly={!advanced} runsOnly={expanded} />}
{showThreads && creatingProject && <BotProjectDialog bot={bot} onClose={() => setCreatingProject(false)} />}
</>
);
diff --git a/src/components/SidebarBotThreadsPeek.dom.test.ts b/src/components/SidebarBotThreadsPeek.dom.test.ts
deleted file mode 100644
index f3d6536d92..0000000000
--- a/src/components/SidebarBotThreadsPeek.dom.test.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-// @vitest-environment happy-dom
-import { act, createElement } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { TYPEAHEAD_RESET_MS } from "@/lib/menu-keys";
-import type { Action, Task } from "@/state/store";
-import { SidebarBotThreadsPeek } from "./SidebarBotThreadsPeek";
-
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-const task = (threadId: string, extra: Partial<Task> = {}): Task => ({ threadId, title: threadId, createdAt: 1, ...extra });
-
-let row: HTMLElement;
-let scroller: HTMLElement;
-let chat: HTMLElement;
-let root: Root;
-const dispatch = vi.fn<(action: Action) => void>();
-
-const show = async (tasks: Task[], shown: { threadId?: string; onScreen?: boolean } = {}) => {
- await act(async () => {
- root.render(createElement("div", { "data-row": "" },
- createElement(SidebarBotThreadsPeek, { bot: { id: "atlas", name: "Atlas", threadId: shown.threadId ?? "main", mainThreadId: "main", tasks: [task("main"), ...tasks] }, onScreen: shown.onScreen, dispatch })));
- });
-};
-const mount = async (tasks: Task[], shown: { threadId?: string; onScreen?: boolean } = {}) => {
- scroller = document.createElement("div");
- chat = document.createElement("div");
- document.body.append(scroller, chat);
- root = createRoot(scroller);
- await show(tasks, shown);
- row = scroller.querySelector<HTMLElement>("[data-row]")!;
-};
-const chevron = () => row.querySelector<HTMLButtonElement>("[data-bot-threads-peek]")!;
-const sheet = () => document.querySelector<HTMLElement>("[data-bot-threads-sheet]:not([inert])");
-const open = async () => { await act(async () => { chevron().click(); }); };
-const pointer = (type: string, target: Element, relatedTarget: Element) =>
- target.dispatchEvent(new PointerEvent(type, { pointerType: "mouse", relatedTarget, bubbles: !/enter|leave/.test(type) }));
-// The order a browser reports one crossing in: out and leave on the old element, then over and enter on the new one.
-const cross = async (from: Element, to: Element) => {
- await act(async () => { for (const [type, target, related] of [["pointerout", from, to], ["pointerleave", from, to], ["pointerover", to, from], ["pointerenter", to, from]] as const) pointer(type, target, related); });
-};
-const wait = async (ms: number) => { await act(async () => { vi.advanceTimersByTime(ms); }); };
-const action = (threadId: string, kind: string) => sheet()!.querySelector(`[data-peek-thread="${threadId}"]`)!.parentElement!.querySelector<HTMLButtonElement>(`[data-peek-action="${kind}"]`)!;
-
-beforeEach(() => { vi.useFakeTimers(); dispatch.mockClear(); });
-afterEach(async () => {
- await act(async () => { root.unmount(); });
- document.body.innerHTML = "";
- vi.useRealTimers();
-});
-
-describe("the sheet of a bot's other conversations", () => {
- it("opens on a click of the chevron only, never on hover, and stays open when the pointer moves away", async () => {
- await mount([task("a")]);
- await cross(chat, row);
- await wait(5_000);
- expect(chevron().getAttribute("aria-expanded")).toBe("false");
- expect(sheet()).toBeNull();
-
- await open();
- expect(chevron().getAttribute("aria-expanded")).toBe("true");
- await cross(row, chat);
- await wait(5_000);
- expect(chevron().getAttribute("aria-expanded")).toBe("true");
-
- await open();
- expect(chevron().getAttribute("aria-expanded")).toBe("false");
- });
-
- it("drops the disclosure's tooltip while the sheet is open", async () => {
- await mount([task("a")]);
- expect(chevron().title).toBe("Expand Atlas threads");
- await open();
- expect(chevron().hasAttribute("title")).toBe(false);
- expect(chevron().getAttribute("aria-label")).toBe("Expand Atlas threads");
- });
-
- it("closes when the list holding its row scrolls, not when anything else does", async () => {
- await mount([task("a")]);
- await open();
- await act(async () => { chat.dispatchEvent(new Event("scroll")); });
- expect(chevron().getAttribute("aria-expanded")).toBe("true");
- await act(async () => { scroller.dispatchEvent(new Event("scroll")); });
- expect(chevron().getAttribute("aria-expanded")).toBe("false");
- });
-
- it("lists the main conversation first, with no way to archive or delete it, and opens it", async () => {
- await mount([task("a")], { threadId: "a", onScreen: true });
- await open();
- const rows = [...sheet()!.querySelectorAll<HTMLElement>("[data-peek-thread]")];
- expect(rows.map((entry) => entry.dataset.peekThread)).toEqual(["main", "a"]);
- expect(rows[0].querySelector("[role=img]")?.getAttribute("aria-label")).toBe("Main thread");
- expect(rows[0].parentElement!.querySelector("[data-peek-action]")).toBeNull();
- await act(async () => { rows[0].click(); });
- expect(dispatch.mock.calls).toEqual([[{ type: "switchTask", botId: "atlas", threadId: "main" }]]);
- });
-
- it("marks the conversation on screen, and none for a bot that is not on screen", async () => {
- const marked = () => [...sheet()!.querySelectorAll<HTMLElement>("[data-peek-thread]")].filter((entry) => entry.getAttribute("aria-current") === "page" && entry.querySelector("svg.lucide-check")).map((entry) => entry.dataset.peekThread);
- await mount([task("a"), task("b")], { threadId: "a", onScreen: true });
- await open();
- expect(marked()).toEqual(["a"]);
- expect(sheet()!.querySelectorAll("svg.lucide-check")).toHaveLength(1);
- await act(async () => { root.unmount(); });
- await mount([task("a"), task("b")], { threadId: "a" });
- await open();
- expect(sheet()!.querySelector("[aria-current], svg.lucide-check")).toBeNull();
- });
-
- it("keeps the conversation on screen in the list when newer ones fill it", async () => {
- await mount([task("old", { updatedAt: 1 }), task("b", { updatedAt: 4 }), task("c", { updatedAt: 3 }), task("d", { updatedAt: 2 })], { threadId: "old", onScreen: true });
- await open();
- expect([...sheet()!.querySelectorAll<HTMLElement>("[data-peek-thread]")].map((entry) => entry.dataset.peekThread)).toEqual(["main", "b", "c", "d", "old"]);
- expect(sheet()!.querySelector('[data-peek-thread="old"]')!.getAttribute("aria-current")).toBe("page");
- });
-
- it("archives a conversation from its row without opening it or closing the sheet", async () => {
- await mount([task("a"), task("b")]);
- await open();
- const archive = action("a", "archive");
- expect(archive.getAttribute("aria-labelledby")!.split(" ").map((id) => document.getElementById(id)?.textContent || document.getElementById(id)?.getAttribute("aria-label"))).toEqual(["Archive", "a"]);
- await act(async () => { archive.click(); });
- expect(dispatch.mock.calls).toEqual([[{ type: "updateTask", botId: "atlas", threadId: "a", patch: { archivedAt: expect.any(Number) } }]]);
- expect(chevron().getAttribute("aria-expanded")).toBe("true");
- });
-
- it("deletes a conversation only after the same confirmation its thread row asks", async () => {
- await mount([task("a")]);
- await open();
- await act(async () => { action("a", "delete").click(); });
- expect(dispatch).not.toHaveBeenCalled();
- const dialog = document.querySelector<HTMLElement>("[role=alertdialog], [role=dialog]")!;
- expect(dialog.textContent).toContain("Delete thread?");
- expect(dialog.textContent).toContain("“a” and its conversation will be deleted.");
- await act(async () => { [...dialog.querySelectorAll("button")].find((button) => button.textContent === "Delete thread")!.click(); });
- expect(dispatch.mock.calls).toEqual([[{ type: "deleteTask", botId: "atlas", threadId: "a" }]]);
- });
-
- it("does not delete a conversation that started working while the confirmation was open", async () => {
- await mount([task("a")]);
- await open();
- await act(async () => { action("a", "delete").click(); });
- await show([task("a", { busy: true })]);
- const dialog = document.querySelector<HTMLElement>("[role=alertdialog], [role=dialog]")!;
- await act(async () => { [...dialog.querySelectorAll("button")].find((button) => button.textContent === "Delete thread")!.click(); });
- expect(dispatch).not.toHaveBeenCalled();
- });
-
- it("stays inside the window when its rows are taller than a mouse's, as on a touch screen", async () => {
- await mount([task("a"), task("b"), task("c")]);
- row.getBoundingClientRect = () => ({ left: 8, right: 300, top: window.innerHeight - 20 }) as DOMRect;
- const height = vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(185);
- await open();
- height.mockRestore();
- expect(sheet()!.style.top).toBe(`${window.innerHeight - 185 - 8}px`);
- });
-
- it("moves up when it grows taller while open, and stops watching its height once closed", async () => {
- const watchers: { resized: () => void; target?: Element; live: boolean }[] = [];
- vi.stubGlobal("ResizeObserver", class {
- private entry: (typeof watchers)[number];
- constructor(resized: () => void) { this.entry = { resized, live: true }; watchers.push(this.entry); }
- observe(target: Element) { this.entry.target = target; }
- disconnect() { this.entry.live = false; }
- });
- await mount([task("a"), task("b"), task("c")]);
- row.getBoundingClientRect = () => ({ left: 8, right: 300, top: window.innerHeight - 20 }) as DOMRect;
- const height = vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(180);
- await open();
- expect(sheet()!.style.top).toBe(`${window.innerHeight - 180 - 8}px`);
-
- height.mockReturnValue(225);
- const watching = watchers.filter((entry) => entry.live);
- expect(watching.map((entry) => entry.target)).toEqual([sheet()]);
- await act(async () => { watching[0].resized(); });
- expect(sheet()!.style.top).toBe(`${window.innerHeight - 225 - 8}px`);
-
- await open();
- height.mockRestore();
- vi.unstubAllGlobals();
- expect(chevron().getAttribute("aria-expanded")).toBe("false");
- expect(watchers.filter((entry) => entry.live)).toEqual([]);
- });
-
- it("lists a snoozed conversation once its snooze ends, with nothing else changing", async () => {
- const tasks = [task("a", { snoozedUntil: Date.now() + 60_000 })];
- await mount(tasks);
- expect(row.querySelector("[data-bot-new-thread]")).not.toBeNull();
- expect(row.querySelector("[data-bot-threads-peek]")).toBeNull();
- await wait(60_000);
- expect(row.querySelector("[data-bot-threads-peek]")).toBeNull();
- await wait(1);
- expect(row.querySelector("[data-bot-new-thread]")).toBeNull();
- await open();
- expect([...sheet()!.querySelectorAll<HTMLElement>("[data-peek-thread]")].map((entry) => entry.dataset.peekThread)).toEqual(["main", "a"]);
- });
-
- it("offers neither action for a conversation that is working", async () => {
- await mount([task("a", { busy: true })]);
- await open();
- expect(action("a", "archive").disabled).toBe(true);
- expect(action("a", "delete").disabled).toBe(true);
- });
-
- it("reaches a row's actions with the arrow keys and moves on to the next row", async () => {
- await mount([task("a"), task("b")]);
- await open();
- const key = async (name: string) => { await act(async () => { document.activeElement!.dispatchEvent(new KeyboardEvent("keydown", { key: name, bubbles: true })); }); };
- const thread = (id: string) => sheet()!.querySelector<HTMLElement>(`[data-peek-thread="${id}"]`)!;
- thread("a").focus();
- await key("ArrowRight");
- expect(document.activeElement).toBe(action("a", "archive"));
- await key("ArrowRight");
- expect(document.activeElement).toBe(action("a", "delete"));
- await key("ArrowRight");
- expect(document.activeElement).toBe(thread("a"));
- await key("ArrowLeft");
- expect(document.activeElement).toBe(action("a", "delete"));
- await key("ArrowDown");
- expect(document.activeElement).toBe(thread("b"));
- });
-
- it("jumps to the conversation whose title starts with the letters typed", async () => {
- await mount([task("a", { title: "Pricing review" }), task("b", { title: "Supplier follow-up" }), task("c", { title: "Price list" })]);
- await open();
- const type = async (text: string) => {
- for (const key of text) {
- const event = new KeyboardEvent("keydown", { key, bubbles: true });
- Object.defineProperty(event, "timeStamp", { value: Date.now() });
- await act(async () => { document.activeElement!.dispatchEvent(event); });
- }
- };
- const thread = (id: string) => sheet()!.querySelector<HTMLElement>(`[data-peek-thread="${id}"]`)!;
- sheet()!.querySelector<HTMLElement>("[role=menuitem]")!.focus();
- await type("s");
- expect(document.activeElement).toBe(thread("b"));
- await wait(TYPEAHEAD_RESET_MS);
- await type("pric");
- expect(document.activeElement).toBe(thread("c"));
- await type("i");
- expect(document.activeElement).toBe(thread("a"));
- action("a", "archive").focus();
- await wait(TYPEAHEAD_RESET_MS);
- await type("n");
- expect(document.activeElement?.textContent).toBe("New thread");
- });
-});
diff --git a/src/components/SidebarBotThreadsPeek.test.ts b/src/components/SidebarBotThreadsPeek.test.ts
deleted file mode 100644
index 4ca2a8b57d..0000000000
--- a/src/components/SidebarBotThreadsPeek.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { createElement } from "react";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vitest";
-import type { Task } from "@/state/store";
-import { PEEK_LIMIT, peekPlace, peekThreads, SidebarBotThreadsPeek } from "./SidebarBotThreadsPeek";
-
-const task = (threadId: string, extra: Partial<Task> = {}): Task => ({ threadId, title: threadId, createdAt: 1, ...extra });
-const bot = (tasks: Task[], threadId = "main") => ({ threadId, mainThreadId: "main", tasks: [task("main"), ...tasks] });
-
-describe("peekThreads", () => {
- const ids = (listed: Task[]) => listed.map((entry) => entry.threadId);
- const four = [task("a", { updatedAt: 10 }), task("b", { updatedAt: 40 }), task("c", { updatedAt: 30 }), task("d", { updatedAt: 20 })];
-
- it("is only the main conversation for a bot with nothing else open", () => {
- expect(ids(peekThreads(bot([])))).toEqual(["main"]);
- });
-
- it("lists the main conversation first, then the newest open ones up to the limit", () => {
- const listed = peekThreads(bot([task("new", { updatedAt: 50 }), ...four]));
- expect(ids(listed)).toEqual(["main", "new", "b", "c"]);
- expect(listed).toHaveLength(PEEK_LIMIT + 1);
- });
-
- it("lists the main conversation first while another one is on screen", () => {
- expect(ids(peekThreads(bot([task("a", { updatedAt: 10 })], "a"), "a"))).toEqual(["main", "a"]);
- });
-
- it("keeps the conversation on screen when newer ones fill the limit", () => {
- expect(ids(peekThreads(bot(four, "a"), "a"))).toEqual(["main", "b", "c", "d", "a"]);
- expect(ids(peekThreads(bot(four, "a")))).toEqual(["main", "b", "c", "d"]);
- });
-
- it("leaves out routine runs, burst helpers and closed, archived or snoozed conversations", () => {
- const closed = [
- task("run", { routineRunId: "r1" }),
- task("burst", { openedBy: { botId: "x", name: "X", at: 1, burstId: "b1" } }),
- task("closed", { closedBy: { botId: "x", name: "X", at: 1 } }),
- task("archived", { archivedAt: 5 }),
- task("snoozed", { snoozedUntil: Date.now() + 60_000 }),
- ];
- expect(ids(peekThreads(bot([...closed, task("open")])))).toEqual(["main", "open"]);
- });
-
- it("leads with the conversation in view for a bot without a main one", () => {
- expect(ids(peekThreads({ threadId: "a", tasks: [task("a"), task("b")] }))).toEqual(["a", "b"]);
- });
-});
-
-describe("peekPlace", () => {
- const viewport = { width: 1440, height: 900 };
-
- it("sits beside the row, level with its top", () => {
- expect(peekPlace({ left: 8, right: 300, top: 200 }, 4, viewport, false)).toEqual({ left: 300, top: 200 });
- });
-
- it("stays inside the window near its bottom and right edges", () => {
- expect(peekPlace({ left: 8, right: 1400, top: 880 }, 4, viewport, false)).toEqual({ left: 1192, top: 748 });
- });
-
- it("opens on the other side in a right-to-left layout", () => {
- expect(peekPlace({ left: 1140, right: 1432, top: 200 }, 4, viewport, true)).toEqual({ left: 900, top: 200 });
- });
-});
-
-describe("SidebarBotThreadsPeek", () => {
- const render = (tasks: Task[]) => renderToStaticMarkup(createElement(SidebarBotThreadsPeek, { bot: { id: "atlas", name: "Atlas", ...bot(tasks) }, dispatch: () => {} }));
-
- it("offers only a new conversation for a bot with nothing else open", () => {
- const markup = render([]);
- expect(markup).toContain('data-bot-new-thread="atlas" aria-label="New thread"');
- expect(markup).not.toContain("aria-expanded");
- });
-
- it("discloses the other open conversations, closed until pressed", () => {
- const markup = render([task("a")]);
- expect(markup).toContain('data-bot-threads-peek="atlas" aria-haspopup="menu" aria-expanded="false" aria-label="Expand Atlas threads"');
- expect(markup).not.toContain('role="menu"');
- expect(markup).not.toContain("data-bot-new-thread");
- });
-
- it("hides its control on phones and shows it without hover on other touch screens", () => {
- expect(render([])).toMatch(/class="[^"]*\bmax-md:hidden touch:pointer-events-auto touch:opacity-70\b/);
- });
-});
diff --git a/src/components/SidebarBotThreadsPeek.tsx b/src/components/SidebarBotThreadsPeek.tsx
deleted file mode 100644
index 54090a8935..0000000000
--- a/src/components/SidebarBotThreadsPeek.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-import { Archive, Check, ChevronRight, Plus, Star, Trash2 } from "lucide-react";
-import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type Dispatch, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent } from "react";
-import { createPortal } from "react-dom";
-import { cn } from "@/lib/cn";
-import { t } from "@/lib/i18n";
-import { isTypeaheadKey, typeaheadMatch, typeaheadText, type Typeahead } from "@/lib/menu-keys";
-import { localizedTaskTitle } from "@/lib/task-title";
-import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";
-import type { Action, Bot, Task } from "@/state/store";
-import { botOpensTo } from "@/state/thread-navigation";
-import { ConfirmDialog } from "./ConfirmDialog";
-import { MENU_GUTTER, MENU_ICON, MENU_META, MENU_ROW, MENU_SEPARATOR, MENU_SHEET } from "./menu-recipe";
-import { useHeldMenuMotion } from "./MenuMotion";
-import { isArchived, isSnoozed, isWorking, nextSnoozeExpiry, threadRecency, threadRowActions, threadUpdatedLabel, useSnoozeExpiry } from "./SidebarThreadRow";
-
-export const PEEK_LIMIT = 3;
-const SHEET_WIDTH = 240;
-const EDGE = 8;
-
-type PeekBot = Pick<Bot, "id" | "name" | "threadId" | "switchingTo" | "mainThreadId" | "tasks">;
-
-export function peekThreads(bot: Pick<PeekBot, "threadId" | "mainThreadId" | "tasks">, current?: string): Task[] {
- const main = botOpensTo(bot, false);
- const others = (bot.tasks ?? [])
- .filter((task) => task.threadId !== main && !task.routineRunId && !task.openedBy?.burstId && !task.closedBy && !isArchived(task) && !isSnoozed(task))
- .sort((a, b) => threadRecency(b) - threadRecency(a));
- return [
- ...(bot.tasks ?? []).filter((task) => task.threadId === main),
- ...others.filter((task, index) => index < PEEK_LIMIT || task.threadId === current),
- ];
-}
-
-type Place = { left: number; top: number };
-
-export function peekPlace(row: Pick<DOMRect, "left" | "right" | "top">, rows: number, viewport: { width: number; height: number }, rtl: boolean): Place {
- const height = rows * 30 + 24;
- const left = rtl ? row.left - SHEET_WIDTH : row.right;
- return {
- left: Math.max(EDGE, Math.min(left, viewport.width - SHEET_WIDTH - EDGE)),
- top: Math.max(EDGE, Math.min(row.top, viewport.height - height - EDGE)),
- };
-}
-
-const SLOT = "pointer-events-none absolute end-[30px] top-1.5 flex size-6 items-center justify-center rounded-lg text-ink-secondary opacity-0 transition-opacity hover:bg-raised hover:text-ink group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 max-md:hidden touch:pointer-events-auto touch:opacity-70 motion-reduce:transition-none";
-
-const ROW_ACTIONS = "pointer-events-none absolute end-2 top-1/2 flex -translate-y-1/2 items-center gap-1 opacity-0 transition-opacity group-hover/peek:pointer-events-auto group-hover/peek:opacity-100 group-focus-within/peek:pointer-events-auto group-focus-within/peek:opacity-100 touch:pointer-events-auto touch:opacity-100 motion-reduce:transition-none";
-const ROW_ACTION = "flex size-6 items-center justify-center rounded-md text-ink-secondary hover:bg-ink/[0.06] hover:text-ink focus-visible:bg-ink/[0.06] focus-visible:text-ink active:bg-ink/[0.08] disabled:cursor-default disabled:opacity-50 disabled:hover:bg-transparent disabled:hover:text-ink-secondary touch:size-10";
-const ROW_TIME = "min-w-13 text-end tabular-nums";
-const ROW_TIME_YIELDS = "transition-opacity group-hover/peek:opacity-0 group-focus-within/peek:opacity-0 touch:min-w-21 touch:opacity-0 motion-reduce:transition-none";
-
-export function SidebarBotThreadsPeek({ bot, onScreen = false, dispatch }: { bot: PeekBot; onScreen?: boolean; dispatch: Dispatch<Action> }) {
- const main = botOpensTo(bot, false), current = onScreen ? bot.switchingTo ?? bot.threadId : undefined;
- const tasks = bot.tasks ?? [];
- useSnoozeExpiry(tasks);
- // A snooze ends by the clock alone, so the nearest deadline still ahead stands in for it.
- const wake = nextSnoozeExpiry(tasks);
- const threads = useMemo(() => peekThreads(bot, current), [bot.tasks, bot.mainThreadId, bot.threadId, current, wake]);
- const others = threads.filter((task) => task.threadId !== main).length;
- const [place, setPlace] = useState<Place | null>(null);
- const motion = useHeldMenuMotion(place);
- const anchor = useRef<HTMLButtonElement>(null);
- const sheet = useRef<HTMLDivElement>(null);
- const focusSheet = useRef(false);
- const focusAnchor = useRef(false);
- const typed = useRef<Typeahead | null>(null);
- const [deletingId, setDeletingId] = useState<string | null>(null);
- const deleting = deletingId ? bot.tasks?.find((task) => task.threadId === deletingId) : undefined;
- const labels = useId();
- const has = others > 0;
- const open = place !== null;
-
- // Opened by a click on the chevron only: resting the pointer on a row opens nothing.
- const close = () => setPlace(null);
- const show = () => {
- const row = anchor.current?.parentElement;
- if (!row) return;
- setPlace(peekPlace(row.getBoundingClientRect(), threads.length + 1, { width: window.innerWidth, height: window.innerHeight }, getComputedStyle(row).direction === "rtl"));
- };
-
- useEffect(() => {
- if (has) return;
- close();
- if (focusAnchor.current) anchor.current?.focus();
- focusAnchor.current = false;
- }, [has]);
- // Rows are taller on a touch screen, so the sheet's own height decides how far up it has to sit.
- useLayoutEffect(() => {
- const menu = sheet.current;
- if (!place || !menu) return;
- const fit = () => {
- const height = menu.offsetHeight;
- if (!height) return;
- const top = Math.max(EDGE, Math.min(place.top, window.innerHeight - height - EDGE));
- if (top !== place.top) setPlace({ ...place, top });
- };
- fit();
- const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(fit);
- observer?.observe(menu);
- return () => observer?.disconnect();
- }, [place, threads.length]);
- useEffect(() => {
- if (!open) return;
- if (focusSheet.current) { focusSheet.current = false; sheet.current?.querySelector<HTMLElement>("[role=menuitem]")?.focus(); }
- const away = (event: Event) => { if (!(event.target instanceof Node) || event.target.contains(anchor.current)) close(); };
- window.addEventListener("resize", close);
- window.addEventListener("scroll", away, true);
- return () => { window.removeEventListener("resize", close); window.removeEventListener("scroll", away, true); };
- }, [open]);
- const root = useRef({ contains: (target: unknown) => target instanceof Node && Boolean(sheet.current?.contains(target) || anchor.current?.contains(target)) });
- usePopoverDismiss(open, root, () => {
- if (sheet.current?.contains(document.activeElement)) anchor.current?.focus();
- close();
- });
-
- const actions = threadRowActions(bot.id, dispatch);
- const confirm = <ConfirmDialog open={deleting !== undefined} title={t("task.deleteConfirm")} body={t("task.deleteBody", { title: deleting?.title ?? "" })} confirmLabel={t("task.deleteAria")}
- onCancel={() => setDeletingId(null)} onConfirm={() => { if (deleting && !isWorking(deleting)) actions.onDelete(deleting); setDeletingId(null); }} returnFocusRef={anchor} />;
- const slot = cn(SLOT, open && "pointer-events-auto opacity-100");
- if (!has) {
- return <><button ref={anchor} type="button" data-bot-new-thread={bot.id} aria-label={t("task.newShort")} title={t("task.newShort")}
- onClick={() => dispatch({ type: "newTask", botId: bot.id })} className={slot}><Plus size={14} /></button>{confirm}</>;
- }
-
- const pick = (action: Action) => { close(); dispatch(action); };
- const archive = (task: Task, event: ReactMouseEvent) => {
- if (event.detail === 0) {
- if (others === 1) focusAnchor.current = true;
- else sheet.current?.querySelector<HTMLElement>("[role=menuitem]")?.focus();
- }
- actions.onArchive(task, Date.now());
- };
- const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
- const items = Array.from(sheet.current?.querySelectorAll<HTMLElement>("[role=menuitem]:not([data-peek-action])") ?? []);
- const focused = document.activeElement as HTMLElement | null;
- const row = focused?.closest("[data-peek-row]");
- const at = items.indexOf(row?.querySelector<HTMLElement>("[data-peek-thread]") ?? focused!);
- if (row && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
- event.preventDefault();
- const across = Array.from(row.querySelectorAll<HTMLElement>("[role=menuitem]:not(:disabled)"));
- const forward = (event.key === "ArrowRight") !== (getComputedStyle(row).direction === "rtl");
- across[(across.indexOf(focused!) + (forward ? 1 : across.length - 1)) % across.length]?.focus();
- } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
- event.preventDefault();
- items[(at + (event.key === "ArrowDown" ? 1 : items.length - 1)) % items.length]?.focus();
- } else if (event.key === "Home" || event.key === "End") {
- event.preventDefault();
- items[event.key === "Home" ? 0 : items.length - 1]?.focus();
- } else if (event.key === "Tab") {
- anchor.current?.focus();
- close();
- } else if (isTypeaheadKey(event)) {
- typed.current = typeaheadText(typed.current, event.key, event.timeStamp);
- const match = typeaheadMatch(items.map((item) => item.textContent ?? ""), at, typed.current.text);
- if (match !== null) {
- event.preventDefault();
- items[match]?.focus();
- }
- }
- };
- const now = Date.now();
- const shown = motion.value;
- return (
- <>
- <button ref={anchor} type="button" data-bot-threads-peek={bot.id} aria-haspopup="menu" aria-expanded={open}
- aria-label={t("task.expandNamed", { name: bot.name })} title={open ? undefined : t("task.expandNamed", { name: bot.name })}
- onClick={(event) => { if (open) { close(); return; } focusSheet.current = event.detail === 0; show(); }} className={slot}>
- <ChevronRight size={14} className="rtl:-scale-x-100" />
- </button>
- {motion.shown && shown && createPortal(
- <div ref={sheet} role="menu" aria-label={bot.name} data-bot-threads-sheet={bot.id} style={{ left: shown.left, top: shown.top, width: SHEET_WIDTH }}
- onKeyDown={onKeyDown}
- className={cn(MENU_SHEET, "fixed z-[60] gap-0", motion.className)} {...motion.exitProps}>
- <button type="button" role="menuitem" className={MENU_ROW} onClick={() => pick({ type: "newTask", botId: bot.id })}>
- <span className={MENU_GUTTER}><Plus size={14} className={MENU_ICON} /></span>
- <span className="min-w-0 flex-1 truncate">{t("task.newShort")}</span>
- </button>
- <div role="separator" className={MENU_SEPARATOR} />
- {threads.map((task) => {
- const waiting = task.activity === "waiting-on-you";
- const mark = waiting ? t("sidebar.preview.waiting") : task.unread ? t("task.unread") : undefined;
- const isMain = task.threadId === main, isCurrent = task.threadId === current;
- const working = isWorking(task);
- const titleId = `${labels}${task.threadId}`;
- return (
- <div key={task.threadId} role="none" data-peek-row="" className="group/peek relative shrink-0 rounded-md hover:bg-ink/[0.06] focus-within:bg-ink/[0.06]">
- <button type="button" role="menuitem" data-peek-thread={task.threadId} aria-current={isCurrent ? "page" : undefined}
- className={cn(MENU_ROW, "hover:bg-transparent focus:bg-transparent")} onClick={() => pick({ type: "switchTask", botId: bot.id, threadId: task.threadId })}>
- <span className={MENU_GUTTER}>
- {isCurrent ? <Check size={14} className="text-accent" aria-hidden="true" />
- : mark ? <span role="img" aria-label={mark} title={mark} className={cn("size-1.5 rounded-full", waiting ? "bg-warning" : "bg-accent")} />
- : isMain && <span role="img" aria-label={t("sidebar.bot.simple.mainThread")} title={t("sidebar.bot.simple.mainThread")}><Star size={14} className={MENU_ICON} aria-hidden="true" /></span>}
- </span>
- <span id={titleId} className="min-w-0 flex-1 truncate">{localizedTaskTitle(task.title) || t("task.untitledConversation")}</span>
- <span className={cn(MENU_META, ROW_TIME, !isMain && ROW_TIME_YIELDS)}>{threadUpdatedLabel(threadRecency(task), now)}</span>
- </button>
- {!isMain && <span className={ROW_ACTIONS}>
- <button type="button" role="menuitem" data-peek-action="archive" id={`${titleId}a`} aria-label={t("task.archive")} aria-labelledby={`${titleId}a ${titleId}`} title={t("task.archive")}
- disabled={working} className={ROW_ACTION} onClick={(event) => archive(task, event)}><Archive size={14} aria-hidden="true" /></button>
- <button type="button" role="menuitem" data-peek-action="delete" id={`${titleId}d`} aria-label={t("task.deleteAria")} aria-labelledby={`${titleId}d ${titleId}`} title={t("task.deleteAria")}
- disabled={working} className={cn(ROW_ACTION, "hover:text-danger focus-visible:text-danger")} onClick={() => { close(); setDeletingId(task.threadId); }}><Trash2 size={14} aria-hidden="true" /></button>
- </span>}
- </div>
- );
- })}
- </div>,
- document.body,
- )}
- {confirm}
- </>
- );
-}
diff --git a/src/components/SidebarThreadLabels.tsx b/src/components/SidebarThreadLabels.tsx
new file mode 100644
index 0000000000..9c052b04a0
--- /dev/null
+++ b/src/components/SidebarThreadLabels.tsx
@@ -0,0 +1,215 @@
+import { useEffect, useLayoutEffect, useRef, useState, type Dispatch, type KeyboardEvent as ReactKeyboardEvent } from "react";
+import { createPortal } from "react-dom";
+import { ChevronRight, Clock3, Loader2, Plus, X } from "lucide-react";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { nextRename } from "@/lib/rename";
+import { localizedTaskTitle } from "@/lib/task-title";
+import { setThreadsUnfolded, useThreadsUnfolded } from "@/lib/thread-fold-preferences";
+import type { Action, AppState, Bot } from "@/state/store";
+import { botOpensTo } from "@/state/thread-navigation";
+import { canUnfold, threadLabels, type LabelRow } from "./sidebar-thread-labels";
+import { isWorking } from "./SidebarThreadRow";
+import { showAllConversations } from "./bot-panel/Conversations";
+import { reducedMotion } from "./MenuMotion";
+
+const SLOT = "pointer-events-none absolute end-[30px] top-1.5 flex size-6 items-center justify-center rounded-lg text-ink-secondary opacity-0 transition-opacity hover:bg-raised hover:text-ink group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 max-md:hidden touch:pointer-events-auto touch:opacity-70 motion-reduce:transition-none";
+const ROW = "group/label relative flex h-8 w-full min-w-0 items-center gap-2 rounded-lg ps-2.5 pe-2 text-start text-[13px] leading-[18px] outline-none transition-colors duration-[120ms] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus motion-reduce:transition-none";
+/** Below tablet width a row's hover controls show at rest, so the fold chevron does too, under the row's ⋯ (its time
+ * sits where it is on a wide row): a bot unfolded in a wide window can still be folded after the window narrows. */
+const FOLD_SLOT = cn(SLOT, "max-md:flex max-md:pointer-events-auto max-md:opacity-70 max-md:top-auto max-md:bottom-1.5 max-md:end-[3px]");
+const FOLD_MS = 200;
+const STAGGER_MS = 25;
+/** Rows past the fourth arrive with it, so the slide stays near 250ms however many there are. */
+const STAGGER_STEPS = 3;
+const YIELDS = "group-hover/label:[mask-image:linear-gradient(to_left,transparent_20px,black_36px)] rtl:group-hover/label:[mask-image:linear-gradient(to_right,transparent_20px,black_36px)]";
+
+type FoldBot = Pick<Bot, "id" | "name" | "tasks">;
+
+export const threadLabelsId = (botId: string) => `thread-labels-${botId}`;
+
+/** Simple mode's chevron on a bot row: unfolds the bot's threads under it. A bot with one thread gets New thread here. */
+export function ThreadFoldChevron({ bot, dispatch }: { bot: FoldBot; dispatch: Dispatch<Action> }) {
+ const unfolded = useThreadsUnfolded(bot.id);
+ if (!canUnfold(bot)) {
+ return <button type="button" data-bot-new-thread={bot.id} aria-label={t("task.newShort")} title={t("task.newShort")}
+ onClick={() => dispatch({ type: "newTask", botId: bot.id })} className={SLOT}><Plus size={14} /></button>;
+ }
+ const label = t(unfolded ? "task.collapseNamed" : "task.expandNamed", { name: bot.name });
+ return (
+ <button type="button" data-bot-threads-fold={bot.id} aria-expanded={unfolded} aria-controls={unfolded ? threadLabelsId(bot.id) : undefined}
+ aria-label={label} title={label} onClick={() => setThreadsUnfolded(bot.id, !unfolded)}
+ className={cn(FOLD_SLOT, unfolded && "pointer-events-auto opacity-100")}>
+ <ChevronRight size={14} aria-hidden="true" className={cn("transition-transform duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none rtl:-scale-x-100", unfolded && "rotate-90 rtl:-rotate-90")} />
+ </button>
+ );
+}
+
+/** Whether one of the bot's unfolded rows carries the selected fill instead of its row: not while its blank New thread
+ * chat (`drafting`) is open, which has no row of its own yet. */
+export function useRowUnfolded(bot: FoldBot, drafting = false): boolean {
+ return useThreadsUnfolded(bot.id) && canUnfold(bot) && !drafting;
+}
+
+function StatusMark({ row }: { row: LabelRow }) {
+ switch (row.status) {
+ case "waiting": return <span className="shrink-0 text-[12px] leading-4 text-warning">{t("task.waiting")}</span>;
+ case "working": return <Loader2 size={14} role="img" aria-label={t("chat.activity.working")} className="shrink-0 animate-spin text-success motion-reduce:animate-none" />;
+ case "teammate": return <Clock3 size={14} role="img" aria-label={t("task.waitingOnTeammate")} className="shrink-0 text-warning" />;
+ case "queued": return <Clock3 size={14} role="img" aria-label={t("task.queued")} className="shrink-0 text-ink-tertiary" />;
+ case "unread": return <span role="img" aria-label={t("task.unread")} className="size-1.5 shrink-0 rounded-full bg-accent" />;
+ default: return null;
+ }
+}
+
+type Toast = { text: string; undo: () => void };
+
+/** The rows under a bot in Simple mode's sidebar: what is going on while folded, the bot's active threads unfolded. */
+export function SidebarThreadLabels({ bot, selected, drafting = false, rowThreadId, pendingQueued, dispatch }: {
+ bot: Bot; selected: boolean; drafting?: boolean; rowThreadId: string; pendingQueued: AppState["pendingQueued"]; dispatch: Dispatch<Action>;
+}) {
+ const unfolded = useThreadsUnfolded(bot.id) && canUnfold(bot);
+ const current = selected && !drafting ? bot.switchingTo ?? bot.threadId : undefined;
+ const { rows, more, runningMore } = threadLabels(bot, pendingQueued, { unfolded, current, rowThreadId, now: Date.now() });
+ const [renaming, setRenaming] = useState<string | null>(null);
+ const [draft, setDraft] = useState("");
+ const [toast, setToast] = useState<Toast | null>(null);
+ const [focusAt, setFocusAt] = useState<number | null>(null);
+ const finishing = useRef(false);
+ const tree = useRef<HTMLDivElement>(null);
+ // Folding plays the unfold backwards: the rows that go fade out in place before the list shortens.
+ const shown = useRef({ unfolded, rows, more });
+ const [leaving, setLeaving] = useState<{ rows: LabelRow[]; gone: ReadonlySet<string>; more: number } | null>(null);
+ useLayoutEffect(() => {
+ const was = shown.current;
+ if (!was.unfolded || unfolded || reducedMotion()) { setLeaving(null); return; }
+ const kept = new Set(rows.map((row) => row.task.threadId));
+ setLeaving({ rows: was.rows, gone: new Set(was.rows.filter((row) => !kept.has(row.task.threadId)).map((row) => row.task.threadId)), more: was.more });
+ const timer = window.setTimeout(() => setLeaving(null), FOLD_MS);
+ return () => window.clearTimeout(timer);
+ }, [unfolded]);
+ useLayoutEffect(() => { shown.current = { unfolded, rows, more }; });
+ useEffect(() => {
+ if (!toast) return;
+ const timer = window.setTimeout(() => setToast(null), 6000);
+ return () => window.clearTimeout(timer);
+ }, [toast]);
+ if (!rows.length && !more && !runningMore && !toast && !leaving) return null;
+
+ const items = () => Array.from(tree.current?.querySelectorAll<HTMLElement>("[role=treeitem]") ?? []);
+ const focusItem = (index: number) => { setFocusAt(index); items()[index]?.focus(); };
+ const open = (threadId: string) => dispatch({ type: "switchTask", botId: bot.id, threadId });
+ const openPanel = () => {
+ showAllConversations(bot.id);
+ dispatch({ type: "toggleSettings", open: true, botId: bot.id });
+ requestAnimationFrame(() => requestAnimationFrame(() => document.querySelector('[data-panel-card="conversations"]')?.scrollIntoView({ block: "nearest" })));
+ };
+ const hideable = (row: LabelRow) => !row.main && !row.task.sharedChat && !isWorking(row.task);
+ const hide = (row: LabelRow) => {
+ if (!hideable(row)) return;
+ if (row.current) open(botOpensTo(bot, false));
+ dispatch({ type: "updateTask", botId: bot.id, threadId: row.task.threadId, patch: { archivedAt: Date.now() } });
+ setToast({ text: t("sidebar.threads.hidden"), undo: () => dispatch({ type: "updateTask", botId: bot.id, threadId: row.task.threadId, patch: { archivedAt: null } }) });
+ };
+ const startRename = (row: LabelRow) => {
+ if (row.task.sharedChat) return;
+ finishing.current = false;
+ setDraft(row.task.title);
+ setRenaming(row.task.threadId);
+ };
+ const finishRename = (row: LabelRow, save: boolean, refocus: boolean) => {
+ if (finishing.current) return;
+ finishing.current = true;
+ const title = save ? nextRename(row.task.title, draft) : null;
+ setRenaming(null);
+ if (title) dispatch({ type: "renameTask", botId: bot.id, threadId: row.task.threadId, title });
+ if (refocus) requestAnimationFrame(() => tree.current?.querySelector<HTMLElement>(`[data-thread-label="${CSS.escape(row.task.threadId)}"]`)?.focus());
+ };
+ const onKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (renaming || event.target instanceof HTMLInputElement) return;
+ const list = items(), at = list.indexOf(document.activeElement as HTMLElement);
+ if (at < 0) return;
+ const to = event.key === "ArrowDown" ? Math.min(at + 1, list.length - 1) : event.key === "ArrowUp" ? Math.max(at - 1, 0)
+ : event.key === "Home" ? 0 : event.key === "End" ? list.length - 1 : null;
+ if (to !== null) { event.preventDefault(); focusItem(to); return; }
+ if (event.key === "Enter" || event.key === " ") { event.preventDefault(); list[at]?.click(); return; }
+ if (event.key === "ArrowLeft" && unfolded) {
+ event.preventDefault();
+ setThreadsUnfolded(bot.id, false);
+ document.querySelector<HTMLElement>(`[data-bot-threads-fold="${CSS.escape(bot.id)}"]`)?.focus();
+ return;
+ }
+ const row = rows[at];
+ if (!row) return;
+ if (event.key === "F2") { event.preventDefault(); startRename(row); }
+ else if (event.key === "Delete") { event.preventDefault(); hide(row); }
+ };
+ const stop = Math.min(focusAt ?? Math.max(0, rows.findIndex((row) => row.current)), rows.length + Number(more > 0) + Number(runningMore > 0) - 1);
+ const roving = (index: number) => (index === stop ? 0 : -1);
+ const stagger = (index: number) => ({ animationDelay: `${Math.min(index, STAGGER_STEPS) * STAGGER_MS}ms` });
+ const FOLDING = "pointer-events-none animate-pop-out motion-reduce:animate-none";
+ const QUIET = cn(ROW, "animate-msg-in text-ink-tertiary [animation-fill-mode:backwards] hover:bg-ink/[0.06] hover:text-ink-secondary motion-reduce:animate-none");
+
+ return <>
+ <div ref={tree} id={threadLabelsId(bot.id)} role="tree" aria-label={t("task.namedList", { name: bot.name })} data-thread-labels={bot.id}
+ onKeyDown={onKey} className="mb-1 ms-11 me-1 flex flex-col gap-0.5">
+ {(leaving?.rows ?? rows).map((row, index) => {
+ const title = localizedTaskTitle(row.task.title);
+ const gone = leaving?.gone.has(row.task.threadId) === true;
+ return (
+ <div key={row.task.threadId} role="treeitem" aria-hidden={gone || undefined} inert={gone || undefined} aria-level={1} aria-selected={row.current} aria-current={row.current ? "page" : undefined}
+ data-thread-label={row.task.threadId} data-sidebar-activity-row={row.task.threadId} tabIndex={roving(index)} title={title}
+ onClick={() => { if (renaming !== row.task.threadId) open(row.task.threadId); }}
+ onDoubleClick={() => startRename(row)} onFocus={() => setFocusAt(index)} style={stagger(index)}
+ className={cn(ROW, gone ? FOLDING : "animate-msg-in cursor-default [animation-fill-mode:backwards] motion-reduce:animate-none",
+ row.current ? "bg-raised font-medium text-ink" : "text-ink-secondary hover:bg-ink/[0.06] hover:text-ink",
+ row.status === "waiting" && !row.current && "text-warning")}>
+ {renaming === row.task.threadId ? (
+ <input autoFocus dir="auto" value={draft} maxLength={80} aria-label={t("task.renameAria")}
+ onFocus={(event) => event.currentTarget.select()} onChange={(event) => setDraft(event.target.value)}
+ onBlur={() => finishRename(row, true, false)} onClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.nativeEvent.isComposing) { event.preventDefault(); finishRename(row, true, true); }
+ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); finishRename(row, false, true); }
+ }}
+ className="-ms-1.5 h-7 min-w-0 flex-1 rounded-md border border-focus bg-transparent px-1.5 text-[13px] text-ink outline-none" />
+ ) : <>
+ <span dir="auto" className={cn("min-w-0 flex-1 truncate", hideable(row) && YIELDS)}>{title}</span>
+ <span className={cn("flex shrink-0 items-center", hideable(row) && "transition-opacity duration-[120ms] group-hover/label:opacity-0 motion-reduce:transition-none")}><StatusMark row={row} /></span>
+ {hideable(row) && (
+ <button type="button" tabIndex={-1} aria-label={t("sidebar.threads.hide", { title })} title={t("sidebar.threads.hideShort")}
+ onClick={(event) => { event.stopPropagation(); hide(row); }}
+ className="pointer-events-none absolute end-1 flex size-6 items-center justify-center rounded-md text-ink-tertiary opacity-0 hover:bg-ink/[0.06] hover:text-ink group-hover/label:pointer-events-auto group-hover/label:opacity-100 group-focus-within/label:opacity-100">
+ <X size={14} aria-hidden="true" />
+ </button>
+ )}
+ </>}
+ </div>
+ );
+ })}
+ {runningMore > 0 && (
+ <div role="treeitem" aria-level={1} aria-selected={false} tabIndex={roving(rows.length)} onClick={openPanel} onFocus={() => setFocusAt(rows.length)}
+ style={stagger(rows.length)} className={QUIET}>
+ <span className="min-w-0 flex-1 truncate">{t("sidebar.threads.running", { count: runningMore })}</span>
+ <Loader2 size={14} aria-hidden="true" className="shrink-0 animate-spin text-success motion-reduce:animate-none" />
+ </div>
+ )}
+ {leaving && leaving.more > 0 && (
+ <div aria-hidden="true" className={cn(ROW, FOLDING, "text-ink-tertiary")}><span className="truncate">{t("sidebar.threads.more", { count: leaving.more })}</span></div>
+ )}
+ {!leaving && more > 0 && (
+ <div role="treeitem" aria-level={1} aria-selected={false} tabIndex={roving(rows.length + Number(runningMore > 0))} onClick={openPanel}
+ onFocus={() => setFocusAt(rows.length + Number(runningMore > 0))} style={stagger(rows.length + Number(runningMore > 0))} className={QUIET}>
+ <span className="truncate">{t("sidebar.threads.more", { count: more })}</span>
+ </div>
+ )}
+ </div>
+ {toast && createPortal(
+ <div role="status" className="fixed bottom-4 start-[calc(var(--rail-beside,0px)_+_1rem)] z-[60] flex max-w-[340px] items-center gap-3 rounded-xl border border-hairline/50 bg-card px-3.5 py-2.5 text-[13px] text-ink shadow-xl animate-fade-in motion-reduce:animate-none">
+ <span className="min-w-0 line-clamp-2">{toast.text}</span>
+ <button type="button" onClick={() => { toast.undo(); setToast(null); }} className="shrink-0 rounded-md px-1.5 py-0.5 font-medium text-accent-text hover:bg-ink/[0.06]">{t("common.undo")}</button>
+ </div>,
+ document.body,
+ )}
+ </>;
+}
diff --git a/src/components/bot-panel/Conversations.tsx b/src/components/bot-panel/Conversations.tsx
index c707e97789..a247ad2dda 100644
--- a/src/components/bot-panel/Conversations.tsx
+++ b/src/components/bot-panel/Conversations.tsx
@@ -49,6 +49,14 @@ function useRecentMessages(bot: Bot, threads: readonly { threadId: string; updat
return (threadId) => threadId === bot.threadId ? open : fetched.get(byThread.get(threadId) ?? "");
}
+/** 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>();
+export function showAllConversations(botId: string): void {
+ showAllNext = botId;
+ for (const listener of showAllListeners) listener(botId);
+}
+
/** Tests only. */
export function forgetConversationLines(): void {
fetched.clear();
@@ -61,7 +69,16 @@ export function BotConversations({ bot }: { bot: Bot }) {
const phone = !useMediaQuery(SIDEBAR_INLINE, true);
const [query, setQuery] = useState("");
const [searching, setSearching] = useState(false);
- const [expanded, setExpanded] = useState(false);
+ const [expanded, setExpanded] = useState(() => {
+ const asked = showAllNext === bot.id;
+ if (asked) showAllNext = null;
+ return asked;
+ });
+ useEffect(() => {
+ const listener = (botId: string) => { if (botId !== bot.id) return; showAllNext = null; setExpanded(true); };
+ showAllListeners.add(listener);
+ return () => { showAllListeners.delete(listener); };
+ }, [bot.id]);
const [showArchived, setShowArchived] = useState(false);
const actions = useMemo(() => {
const { onRename, onRegenerateTitle, onDelete, onMove, onPin, onArchive } = threadRowActions(bot.id, dispatch);
diff --git a/src/components/sidebar-thread-labels.test.ts b/src/components/sidebar-thread-labels.test.ts
new file mode 100644
index 0000000000..374d8c6f17
--- /dev/null
+++ b/src/components/sidebar-thread-labels.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+import type { Task } from "@/state/store";
+import { canUnfold, threadLabels } from "./sidebar-thread-labels";
+
+const DAY = 24 * 60 * 60 * 1000;
+const NOW = 100 * DAY;
+const thread = (threadId: string, daysAgo: number, extra: Partial<Task> = {}): Task => ({ threadId, title: threadId, createdAt: NOW - daysAgo * DAY, updatedAt: NOW - daysAgo * DAY, ...extra });
+const bot = (tasks: Task[], threadId = tasks[0]!.threadId) => ({ threadId, tasks });
+const ids = (labels: ReturnType<typeof threadLabels>) => labels.rows.map((row) => row.task.threadId);
+
+describe("a bot's threads under its sidebar row", () => {
+ it("unfolds only for a bot with more than one open thread of the person's own", () => {
+ expect(canUnfold(bot([thread("main", 9)]))).toBe(false);
+ expect(canUnfold(bot([thread("main", 9), thread("routine", 1, { routineRunId: "r" }), thread("old", 2, { archivedAt: 3 })]))).toBe(false);
+ expect(canUnfold(bot([thread("main", 9), thread("nda", 1)]))).toBe(true);
+ });
+
+ it("folded, lists only what is going on, never the thread the row opens", () => {
+ const tasks = [thread("main", 9, { unread: true }), thread("nda", 1), thread("lease", 2, { busy: true, activity: "working" }), thread("brief", 3, { unread: true })];
+ const folded = threadLabels(bot(tasks), {}, { unfolded: false, rowThreadId: "main", now: NOW });
+ expect(ids(folded)).toEqual(["lease", "brief"]);
+ expect(folded.rows.map((row) => row.status)).toEqual(["working", "unread"]);
+ expect(folded.more).toBe(0);
+ });
+
+ it("unfolded, lists the active ones (open, going on, or used this week), newest first, at most four, and counts the rest", () => {
+ const tasks = [thread("main", 30), thread("a", 1), thread("b", 2), thread("c", 3), thread("d", 4), thread("e", 5), thread("old", 20), thread("going", 40, { unread: true })];
+ const open = threadLabels(bot(tasks, "main"), {}, { unfolded: true, current: "main", rowThreadId: "main", now: NOW });
+ // An old thread with an unread reply is listed too, as it is while folded.
+ expect(ids(open)).toEqual(["a", "b", "c", "main", "going"]);
+ expect(open.rows.find((row) => row.task.threadId === "main")?.current).toBe(true);
+ expect(open.more).toBe(3);
+ });
+
+ it("leaves a week-old thread nobody touched in the count, not the list", () => {
+ const labels = threadLabels(bot([thread("main", 1), thread("stale", 8)]), {}, { unfolded: true, rowThreadId: "main", now: NOW });
+ expect(ids(labels)).toEqual(["main"]);
+ expect(labels.more).toBe(1);
+ });
+
+ it("lists a thread a bot started on its own only while it runs", () => {
+ const tasks = [thread("main", 1), thread("nda", 2), thread("burst", 1, { openedBy: { botId: "x", name: "X", at: 1 } }), thread("run", 1, { routineRunId: "r", busy: true })];
+ expect(ids(threadLabels(bot(tasks), {}, { unfolded: true, rowThreadId: "main", now: NOW }))).toEqual(["main", "nda", "run"]);
+ });
+
+ it("shows three running threads and counts the others as running", () => {
+ const working = { busy: true, activity: "working" as const };
+ const tasks = [thread("main", 1), ...["w1", "w2", "w3", "w4", "w5"].map((id, index) => thread(id, index + 1, working))];
+ const folded = threadLabels(bot(tasks), {}, { unfolded: false, rowThreadId: "main", now: NOW });
+ expect(folded.rows).toHaveLength(3);
+ expect(folded.runningMore).toBe(2);
+ });
+});
diff --git a/src/components/sidebar-thread-labels.ts b/src/components/sidebar-thread-labels.ts
new file mode 100644
index 0000000000..3ef74d5a77
--- /dev/null
+++ b/src/components/sidebar-thread-labels.ts
@@ -0,0 +1,75 @@
+import type { Bot, Task } from "@/state/store";
+import { botOpensTo } from "@/state/thread-navigation";
+import { runningRoutineRuns, sidebarBotActivityTasks } from "./SidebarBotActivity";
+import { isArchived, isSnoozed, isWorking, threadRecency } from "./SidebarThreadRow";
+
+export const ACTIVE_DAYS = 7;
+export const ACTIVE_LIMIT = 4;
+export const RUNNING_LIMIT = 3;
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+export type LabelStatus = "waiting" | "working" | "teammate" | "queued" | "unread" | null;
+export type LabelTask = Task & { queued?: boolean };
+export interface LabelRow { task: LabelTask; status: LabelStatus; current: boolean; main: boolean }
+export interface ThreadLabels { rows: LabelRow[]; more: number; runningMore: number }
+
+type LabelBot = Pick<Bot, "threadId"> & Partial<Pick<Bot, "mainThreadId" | "tasks" | "busy" | "activity" | "unread" | "waitingForTeammates">>;
+
+/** The person started it: not a routine run, and not opened by a bot (its own new thread, a burst or a hand-off). */
+export const ownThread = (task: Pick<Task, "routineRunId" | "openedBy">): boolean => !task.routineRunId && !task.openedBy;
+
+const ownOpen = (bot: Pick<LabelBot, "tasks">) => (bot.tasks ?? []).filter((task) => ownThread(task) && !isArchived(task) && !isSnoozed(task));
+
+/** Only a bot with more than one thread of the person's own has anything to unfold. */
+export const canUnfold = (bot: Pick<LabelBot, "tasks">): boolean => ownOpen(bot).length > 1;
+
+export function labelStatus(task: LabelTask): LabelStatus {
+ if (task.activity === "waiting-on-you") return "waiting";
+ if (isWorking(task)) return "working";
+ if (task.waitingForTeammates === true) return "teammate";
+ if (task.queued) return "queued";
+ return task.unread ? "unread" : null;
+}
+
+/** Beyond `RUNNING_LIMIT` working threads, the rest are counted, not listed. */
+function capRunning(tasks: LabelTask[]): { kept: LabelTask[]; runningMore: number } {
+ let running = 0, runningMore = 0;
+ const kept = tasks.filter((task) => {
+ if (labelStatus(task) !== "working") return true;
+ running += 1;
+ if (running <= RUNNING_LIMIT) return true;
+ runningMore += 1;
+ return false;
+ });
+ return { kept, runningMore };
+}
+
+/**
+ * The rows under a bot in Simple mode's sidebar. Folded: its threads that are working, wait on the person or have an
+ * unread reply, except the one its row opens. Unfolded: also its active threads of the person's own (the open one, any
+ * still going, and those used in the last week), at most `ACTIVE_LIMIT`, and how many more the bot panel lists.
+ */
+export function threadLabels(
+ bot: LabelBot,
+ queued: Record<string, unknown[]>,
+ { unfolded, current, rowThreadId, now }: { unfolded: boolean; current?: string; rowThreadId: string; now: number },
+): ThreadLabels {
+ const main = botOpensTo(bot, false);
+ const attention: LabelTask[] = [...sidebarBotActivityTasks(bot as Bot, queued), ...runningRoutineRuns(bot as Bot)];
+ const row = (task: LabelTask): LabelRow => ({ task, status: labelStatus(task), current: task.threadId === current, main: task.threadId === main });
+ if (!unfolded) {
+ const { kept, runningMore } = capRunning(attention.filter((task) => task.threadId !== rowThreadId));
+ return { rows: kept.map(row), more: 0, runningMore };
+ }
+ const own = ownOpen(bot).map((task) => ({ ...task, queued: Boolean(queued[task.threadId]?.length) }));
+ const recent = (task: LabelTask) => now - threadRecency(task) < ACTIVE_DAYS * DAY_MS;
+ const active = own.filter((task) => task.threadId === current || labelStatus(task) !== null || recent(task))
+ .sort((a, b) => threadRecency(b) - threadRecency(a));
+ let shown = active.slice(0, ACTIVE_LIMIT);
+ const open = active.find((task) => task.threadId === current);
+ if (open && !shown.includes(open)) shown = [...shown.slice(0, ACTIVE_LIMIT - 1), open];
+ const listed = new Set(shown.map((task) => task.threadId));
+ const { kept, runningMore } = capRunning([...shown, ...attention.filter((task) => !listed.has(task.threadId))]);
+ const rows = new Set(kept.map((task) => task.threadId));
+ return { rows: kept.map(row), more: own.filter((task) => !rows.has(task.threadId)).length, runningMore };
+}
diff --git a/src/components/touch-actions.test.ts b/src/components/touch-actions.test.ts
index 5ec276712f..98554e42aa 100644
--- a/src/components/touch-actions.test.ts
+++ b/src/components/touch-actions.test.ts
@@ -27,6 +27,9 @@ const notActions: Array<{ file: string; snippet: string; why: string }> = [
{ file: "components/ChatHeadPill.tsx", snippet: "-ml-2 flex w-0 shrink-0 overflow-hidden opacity-0", why: "decorative chevron in the Simple bot badge; the whole badge is the tap target" },
{ file: "components/RoomHeader.tsx", snippet: "-ml-1 w-0 shrink-0 text-ink-secondary", why: "decorative chevron on the Simple room name; the whole name is the tap target" },
{ file: "components/SidebarConnectApps.tsx", snippet: "opacity-60 grayscale", why: "decorative app logos, already visible at 60% without hover; the whole Apps row is the tap target" },
+ { file: "components/SidebarThreadLabels.tsx", snippet: "pointer-events-none absolute end-1 flex size-6", why: "hiding a thread on a touch screen goes through the bot panel's thread list; a ✕ on every sub-row would crowd the sidebar" },
+ { file: "components/SidebarThreadLabels.tsx", snippet: "group-hover/label:[mask-image", why: "the title fading under the hover ✕; nothing to tap" },
+ { file: "components/SidebarThreadLabels.tsx", snippet: "transition-opacity duration-[120ms] group-hover/label:opacity-0", why: "the status mark making room for the hover ✕; nothing to tap" },
{ file: "components/PlacesRail.tsx", snippet: "h-2 opacity-0 group-hover/tile:opacity-100", why: "decorative pill beside a rail tile on hover; the tile is the tap target and has its own focus ring" },
];
diff --git a/src/lib/thread-fold-preferences.ts b/src/lib/thread-fold-preferences.ts
new file mode 100644
index 0000000000..7aa46b15c3
--- /dev/null
+++ b/src/lib/thread-fold-preferences.ts
@@ -0,0 +1,64 @@
+import { useEffect, useState } from "react";
+
+/** The bots whose threads the person unfolded under their sidebar row, on this device. Folded is the default. */
+export const UNFOLDED_THREADS_KEY = "omb-unfolded-threads";
+const LIMIT = 200;
+const NONE: ReadonlySet<string> = new Set();
+let cache: { raw: string | null; ids: ReadonlySet<string> } | undefined;
+const listeners = new Set<() => void>();
+
+function storage(): Storage | undefined {
+ try {
+ return globalThis.localStorage;
+ } catch {
+ return undefined;
+ }
+}
+
+export function unfoldedThreadBots(): ReadonlySet<string> {
+ let raw: string | null;
+ try {
+ const store = storage();
+ if (!store) return cache?.ids ?? NONE;
+ raw = store.getItem(UNFOLDED_THREADS_KEY);
+ } catch {
+ return cache?.ids ?? NONE;
+ }
+ if (cache && cache.raw === raw) return cache.ids;
+ let ids: string[] = [];
+ try {
+ const parsed: unknown = raw ? JSON.parse(raw) : [];
+ if (Array.isArray(parsed)) ids = parsed.filter((id): id is string => typeof id === "string");
+ } catch {
+ }
+ cache = { raw, ids: new Set(ids) };
+ return cache.ids;
+}
+
+export function setThreadsUnfolded(botId: string, unfolded: boolean): void {
+ const ids = [...unfoldedThreadBots()].filter((id) => id !== botId);
+ if (unfolded) ids.push(botId);
+ const kept = ids.slice(-LIMIT);
+ const raw = JSON.stringify(kept);
+ cache = { raw, ids: new Set(kept) };
+ try {
+ storage()?.setItem(UNFOLDED_THREADS_KEY, raw);
+ } catch {
+ }
+ for (const listener of listeners) listener();
+}
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+export function useThreadsUnfolded(botId: string): boolean {
+ const [unfolded, setUnfolded] = useState(() => unfoldedThreadBots().has(botId));
+ useEffect(() => {
+ const read = () => setUnfolded(unfoldedThreadBots().has(botId));
+ read();
+ return subscribe(read);
+ }, [botId]);
+ return unfolded;
+}
diff --git a/src/locales/de.json b/src/locales/de.json
index a47f3f0bc2..e855894fb7 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -4123,5 +4123,10 @@
"botAccess.cloud.serverPickHint": "Wähle einen benannten Server oder gib einen anderen SSH-Alias ein.",
"botAccess.cloud.serverPickDefault": "Standardserver ({alias})",
"botAccess.cloud.serverPickNone": "Kein Server gewählt",
- "botAccess.cloud.serverPickOther": "Anderer SSH-Alias …"
+ "botAccess.cloud.serverPickOther": "Anderer SSH-Alias …",
+ "sidebar.threads.hidden": "Thread ausgeblendet",
+ "sidebar.threads.hide": "{title} ausblenden",
+ "sidebar.threads.hideShort": "Ausblenden",
+ "sidebar.threads.running": "+{count} laufen",
+ "sidebar.threads.more": "{count} weitere"
}
diff --git a/src/locales/en.json b/src/locales/en.json
index e0f6b32641..4a62b6686e 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -11512,5 +11512,10 @@
"chat.handoffExchange.back": "Back",
"chat.handoffExchange.loading": "Loading the conversation…",
"chat.handoffExchange.failed": "Couldn't load the conversation.",
- "chat.handoffExchange.empty": "No messages yet."
+ "chat.handoffExchange.empty": "No messages yet.",
+ "sidebar.threads.hidden": "Thread hidden",
+ "sidebar.threads.hide": "Hide {title}",
+ "sidebar.threads.hideShort": "Hide",
+ "sidebar.threads.running": "+{count} running",
+ "sidebar.threads.more": "{count} more"
}
diff --git a/src/locales/es.json b/src/locales/es.json
index fb9913dfe3..4b5b168d07 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -6423,5 +6423,10 @@
"imageGen.higgsfield.help": "{app} crea imágenes con la cuenta de Higgsfield en la que inicias sesión en Plugins. Cada imagen gasta créditos de esa cuenta.",
"imageGen.higgsfield.open": "Abrir Plugins",
"inbox.settled.title": "Terminado",
- "inbox.settled.read": "Leído"
+ "inbox.settled.read": "Leído",
+ "sidebar.threads.hidden": "Hilo oculto",
+ "sidebar.threads.hide": "Ocultar {title}",
+ "sidebar.threads.hideShort": "Ocultar",
+ "sidebar.threads.running": "+{count} en curso",
+ "sidebar.threads.more": "{count} más"
}
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 6dab18f064..97b1e0ed0e 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -3826,5 +3826,10 @@
"imageGen.higgsfield.help": "{app} crée des images avec le compte Higgsfield auquel vous vous connectez sous Plugins. Chaque image consomme des crédits de ce compte.",
"imageGen.higgsfield.open": "Ouvrir Plugins",
"inbox.settled.title": "Terminé",
- "inbox.settled.read": "Lu"
+ "inbox.settled.read": "Lu",
+ "sidebar.threads.hidden": "Fil masqué",
+ "sidebar.threads.hide": "Masquer {title}",
+ "sidebar.threads.hideShort": "Masquer",
+ "sidebar.threads.running": "+{count} en cours",
+ "sidebar.threads.more": "{count} de plus"
}
diff --git a/src/locales/hi.json b/src/locales/hi.json
index 29c9cc340e..84ea15619b 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -3678,5 +3678,10 @@
"imageGen.higgsfield.help": "{app} उस Higgsfield खाते से तस्वीरें बनाता है जिससे आप प्लगइन में साइन इन करते हैं। हर तस्वीर उस खाते के क्रेडिट खर्च करती है।",
"imageGen.higgsfield.open": "प्लगइन खोलें",
"inbox.settled.title": "पूर्ण",
- "inbox.settled.read": "पढ़ा गया"
+ "inbox.settled.read": "पढ़ा गया",
+ "sidebar.threads.hidden": "थ्रेड छिपाया गया",
+ "sidebar.threads.hide": "{title} छिपाएँ",
+ "sidebar.threads.hideShort": "छिपाएँ",
+ "sidebar.threads.running": "+{count} चल रहे",
+ "sidebar.threads.more": "{count} और"
}
diff --git a/src/locales/it.json b/src/locales/it.json
index 6c8a6d7376..305838293e 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -11313,5 +11313,10 @@
"insights.other": "Altro",
"insights.breakdown": "Ripartizione",
"insights.byHour": "Per ora",
- "insights.share": "Quota"
+ "insights.share": "Quota",
+ "sidebar.threads.hidden": "Conversazione nascosta",
+ "sidebar.threads.hide": "Nascondi {title}",
+ "sidebar.threads.hideShort": "Nascondi",
+ "sidebar.threads.running": "+{count} in corso",
+ "sidebar.threads.more": "altre {count}"
}
diff --git a/src/locales/ja.json b/src/locales/ja.json
index 31ff6ed551..17f1571d60 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -7959,5 +7959,10 @@
"imageGen.higgsfield.help": "{app} は、プラグインでサインインした Higgsfield アカウントで画像を作ります。画像 1 枚ごとにそのアカウントのクレジットを消費します。",
"imageGen.higgsfield.open": "プラグインを開く",
"inbox.settled.title": "完了",
- "inbox.settled.read": "既読"
+ "inbox.settled.read": "既読",
+ "sidebar.threads.hidden": "スレッドを非表示にしました",
+ "sidebar.threads.hide": "{title} を非表示",
+ "sidebar.threads.hideShort": "非表示",
+ "sidebar.threads.running": "+{count} 件実行中",
+ "sidebar.threads.more": "他 {count} 件"
}
diff --git a/src/locales/ko.json b/src/locales/ko.json
index fb1a3056fa..b2df1fa617 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -7649,5 +7649,10 @@
"imageGen.higgsfield.help": "{app}은(는) 플러그인에서 로그인한 Higgsfield 계정으로 이미지를 만듭니다. 이미지마다 그 계정의 크레딧이 소모됩니다.",
"imageGen.higgsfield.open": "플러그인 열기",
"inbox.settled.title": "완료됨",
- "inbox.settled.read": "읽음"
+ "inbox.settled.read": "읽음",
+ "sidebar.threads.hidden": "스레드를 숨겼어요",
+ "sidebar.threads.hide": "{title} 숨기기",
+ "sidebar.threads.hideShort": "숨기기",
+ "sidebar.threads.running": "+{count}개 실행 중",
+ "sidebar.threads.more": "{count}개 더"
}
diff --git a/src/locales/pl.json b/src/locales/pl.json
index 451b7c3723..b7a3b05d95 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -7119,5 +7119,10 @@
"imageGen.higgsfield.help": "{app} tworzy obrazy na koncie Higgsfield, na które logujesz się w sekcji Wtyczki. Każdy obraz zużywa kredyty z tego konta.",
"imageGen.higgsfield.open": "Otwórz Wtyczki",
"inbox.settled.title": "Zakończone",
- "inbox.settled.read": "Przeczytane"
+ "inbox.settled.read": "Przeczytane",
+ "sidebar.threads.hidden": "Wątek ukryty",
+ "sidebar.threads.hide": "Ukryj {title}",
+ "sidebar.threads.hideShort": "Ukryj",
+ "sidebar.threads.running": "+{count} w toku",
+ "sidebar.threads.more": "jeszcze {count}"
}
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 039e2bfbfd..bfe6c2c50a 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -11512,5 +11512,10 @@
"chat.handoffExchange.back": "Voltar",
"chat.handoffExchange.loading": "Carregando a conversa…",
"chat.handoffExchange.failed": "Não foi possível carregar a conversa.",
- "chat.handoffExchange.empty": "Nenhuma mensagem ainda."
+ "chat.handoffExchange.empty": "Nenhuma mensagem ainda.",
+ "sidebar.threads.hidden": "Conversa oculta",
+ "sidebar.threads.hide": "Ocultar {title}",
+ "sidebar.threads.hideShort": "Ocultar",
+ "sidebar.threads.running": "+{count} em andamento",
+ "sidebar.threads.more": "mais {count}"
}
diff --git a/src/locales/ru.json b/src/locales/ru.json
index f8c982c37f..8c43168a01 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -7173,5 +7173,10 @@
"imageGen.higgsfield.help": "{app} создаёт изображения через аккаунт Higgsfield, в который вы входите в разделе «Плагины». Каждое изображение расходует кредиты этого аккаунта.",
"imageGen.higgsfield.open": "Открыть «Плагины»",
"inbox.settled.title": "Завершено",
- "inbox.settled.read": "Прочитано"
+ "inbox.settled.read": "Прочитано",
+ "sidebar.threads.hidden": "Ветка скрыта",
+ "sidebar.threads.hide": "Скрыть {title}",
+ "sidebar.threads.hideShort": "Скрыть",
+ "sidebar.threads.running": "+{count} в работе",
+ "sidebar.threads.more": "ещё {count}"
}
diff --git a/src/locales/tr.json b/src/locales/tr.json
index 10d65bd745..169b98621f 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -5918,5 +5918,10 @@
"imageGen.higgsfield.help": "{app}, Eklentiler bölümünde oturum açtığınız Higgsfield hesabıyla görsel oluşturur. Her görsel o hesaptan kredi harcar.",
"imageGen.higgsfield.open": "Eklentileri aç",
"inbox.settled.title": "Tamamlandı",
- "inbox.settled.read": "Okundu"
+ "inbox.settled.read": "Okundu",
+ "sidebar.threads.hidden": "Konu gizlendi",
+ "sidebar.threads.hide": "{title} gizle",
+ "sidebar.threads.hideShort": "Gizle",
+ "sidebar.threads.running": "+{count} çalışıyor",
+ "sidebar.threads.more": "{count} tane daha"
}
diff --git a/src/locales/uk.json b/src/locales/uk.json
index 6534585587..9fd31b60c8 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -4098,5 +4098,10 @@
"imageGen.higgsfield.help": "{app} створює зображення через акаунт Higgsfield, у який ви входите в розділі «Плагіни». Кожне зображення витрачає кредити цього акаунта.",
"imageGen.higgsfield.open": "Відкрити «Плагіни»",
"inbox.settled.title": "Завершено",
- "inbox.settled.read": "Прочитано"
+ "inbox.settled.read": "Прочитано",
+ "sidebar.threads.hidden": "Гілку приховано",
+ "sidebar.threads.hide": "Сховати {title}",
+ "sidebar.threads.hideShort": "Сховати",
+ "sidebar.threads.running": "+{count} у роботі",
+ "sidebar.threads.more": "ще {count}"
}
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 192388c530..5c4de7b472 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -5918,5 +5918,10 @@
"imageGen.higgsfield.help": "{app} tạo ảnh bằng tài khoản Higgsfield mà bạn đăng nhập trong Plugin. Mỗi ảnh tốn tín dụng của tài khoản đó.",
"imageGen.higgsfield.open": "Mở Plugin",
"inbox.settled.title": "Đã xong",
- "inbox.settled.read": "Đã đọc"
+ "inbox.settled.read": "Đã đọc",
+ "sidebar.threads.hidden": "Đã ẩn luồng",
+ "sidebar.threads.hide": "Ẩn {title}",
+ "sidebar.threads.hideShort": "Ẩn",
+ "sidebar.threads.running": "+{count} đang chạy",
+ "sidebar.threads.more": "thêm {count}"
}
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 7e45ff466d..1a13c22fb4 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -10209,5 +10209,10 @@
"imageGen.higgsfield.help": "{app} 使用你在「外掛」中登入的 Higgsfield 帳號產生圖片。每張圖片都會消耗該帳號的額度。",
"imageGen.higgsfield.open": "開啟外掛",
"inbox.settled.title": "已完成",
- "inbox.settled.read": "已讀"
+ "inbox.settled.read": "已讀",
+ "sidebar.threads.hidden": "已隱藏對話",
+ "sidebar.threads.hide": "隱藏 {title}",
+ "sidebar.threads.hideShort": "隱藏",
+ "sidebar.threads.running": "+{count} 個執行中",
+ "sidebar.threads.more": "還有 {count} 個"
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index fa1aa21aa7..bbcfaa1bfd 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -10110,5 +10110,10 @@
"imageGen.higgsfield.connected": "已连接到你的 Higgsfield 账号",
"imageGen.higgsfield.notConnected": "未连接,或登录已失效",
"imageGen.higgsfield.help": "{app} 使用你在“插件”中登录的 Higgsfield 账号生成图片。每张图片都会消耗该账号的额度。",
- "imageGen.higgsfield.open": "打开插件"
+ "imageGen.higgsfield.open": "打开插件",
+ "sidebar.threads.hidden": "已隐藏对话",
+ "sidebar.threads.hide": "隐藏 {title}",
+ "sidebar.threads.hideShort": "隐藏",
+ "sidebar.threads.running": "+{count} 个运行中",
+ "sidebar.threads.more": "还有 {count} 个"
}