Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(web,ui): 侧栏会话列表的「搜索会话」旁加批量处理

lmlihengac155cc17713
diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.ts
index b590c837..8fb887bf 100644
--- a/packages/ui/src/components/icons/icons.ts
+++ b/packages/ui/src/components/icons/icons.ts
@@ -196,6 +196,12 @@ export const ICONS = {
copy: "M9 9h9v9a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V9zM7 15H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v1",
/** A checkmark. */
check: "M5 13l4 4L19 7",
+ /**
+ * A list whose rows are each ticked: three checks on the left, three lines on the right. The
+ * mark for acting on several rows at once — the sidebar's batch selection — told apart from
+ * `check` by the rows it stands beside.
+ */
+ listChecks: "m3 17 2 2 4-4m-6-10 2 2 4-4m-6 6 2 2 4-4M13 6h8M13 12h8M13 18h8",
/** An archive box with a downward chevron. */
archive:
"M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M9.5 13.5 12 16l2.5-2.5",
diff --git a/packages/ui/src/components/shell/session-row/session-row.tsx b/packages/ui/src/components/shell/session-row/session-row.tsx
index b8e27d2b..5a182915 100644
--- a/packages/ui/src/components/shell/session-row/session-row.tsx
+++ b/packages/ui/src/components/shell/session-row/session-row.tsx
@@ -23,6 +23,9 @@
* `data-title-reveal`. The trailing slot's width is fixed per language (`timeSlot`), so the marks
* that end the title sit at one x from row to row, and the hover actions are anchored to its right
* edge so every row's icons form one column.
+ *
+ * With a `selection` the row is a batch picker's row rather than a place to go: its checkbox takes
+ * the leading edge, the row's click ticks it, and the hover actions step aside for the duration.
*/
import type { DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
import { ICON_SIZE } from "../../../icon-scale";
@@ -32,6 +35,7 @@ import {
ScheduleMark,
} from "../../icons/activity-icon/activity-icon";
import type { ActivityIconState } from "../../icons/activity-icon/activity-icon";
+import { Checkbox } from "../../forms/checkbox/checkbox";
import { AgentAvatar } from "../../icons/avatars/agent-avatar";
import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";
import { ICONS } from "../../icons/icons";
@@ -165,6 +169,12 @@ export interface SessionRowProps {
activity?: { state: ActivityIconState; label: string } | null;
/** Approvals waiting: the count in the attention ink, its hint; none at a count of 0. */
approvals?: { count: number; label: string };
+ /**
+ * Batch picking: the row carries a checkbox before its title, named by `label`, and the whole
+ * row toggles the tick instead of opening the conversation — and the hover actions step aside,
+ * since the row is being chosen rather than acted on one at a time.
+ */
+ selection?: { checked: boolean; label: string; onToggle: () => void };
/** The compact last-active time at rest; "" draws none. */
time: string;
/**
@@ -202,6 +212,7 @@ export function SessionRow({
background,
activity = null,
approvals,
+ selection,
time,
timeSlot = "narrow",
hoverActions,
@@ -264,6 +275,18 @@ export function SessionRow({
draggable ? "cursor-grab " : ""
}${active ? NAV_FILL.selected : NAV_FILL.hover}`}
>
+ {/* The tick stands outside the row's button: a checkbox inside it would be opened by the
+ same click that picks it, and a batch picker is exactly the place where that click must
+ mean one thing. */}
+ {selection !== undefined && (
+ <span className="flex shrink-0 items-center pl-2.5">
+ <Checkbox
+ checked={selection.checked}
+ onChange={selection.onToggle}
+ aria-label={selection.label}
+ />
+ </span>
+ )}
<button
type="button"
data-testid="session-row"
@@ -272,7 +295,10 @@ export function SessionRow({
// screens replay the held press as a click once the finger lifts.
onClick={() => {
if (ctx.consumeLongPressClick()) return;
- onOpen();
+ // Picking: the row is the target, so its click ticks it — landing in the open
+ // conversation mid-selection would take the list away from the reader.
+ if (selection !== undefined) selection.onToggle();
+ else onOpen();
}}
className="flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left"
>
@@ -320,16 +346,24 @@ export function SessionRow({
}`}
>
<div className="peer absolute right-0 top-1/2 flex -translate-y-1/2 items-center">
- <RowHoverActions
- actions={hoverActions.map(fromHover)}
- moreLabel={moreLabel}
- onMore={ctx.openAt}
- />
+ {selection === undefined && (
+ <RowHoverActions
+ actions={hoverActions.map(fromHover)}
+ moreLabel={moreLabel}
+ onMore={ctx.openAt}
+ />
+ )}
</div>
{time !== "" && (
<span
aria-hidden
- className="pointer-events-none whitespace-nowrap px-1 text-right text-xs tabular-nums text-fg-subtle transition-opacity duration-150 group-hover:opacity-0 peer-focus-within:opacity-0"
+ // The time gives way to the hover actions; while picking, those are absent and the
+ // time is the row's only trailing reading, so it stays put.
+ className={`pointer-events-none whitespace-nowrap px-1 text-right text-xs tabular-nums text-fg-subtle${
+ selection === undefined
+ ? " transition-opacity duration-150 group-hover:opacity-0 peer-focus-within:opacity-0"
+ : ""
+ }`}
>
{time}
</span>
diff --git a/packages/ui/test/session-row.test.ts b/packages/ui/test/session-row.test.ts
index cd7bc0e8..584582ed 100644
--- a/packages/ui/test/session-row.test.ts
+++ b/packages/ui/test/session-row.test.ts
@@ -4,6 +4,10 @@
* each name themselves, one reserved box for the live state, and a trailing slot whose time gives
* way to the hover actions. The row's menu mounts only while open, which a static render never
* is; what its wiring must keep doing is pinned against the source.
+ *
+ * With a `selection` the row is a batch picker's row: the box leads (outside the button, so ticking
+ * it cannot open the conversation), the row's own click ticks it, and the hover actions and the
+ * time's fade give way.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
@@ -134,6 +138,40 @@ describe("SessionRow", () => {
});
});
+describe("SessionRow while picking (a batch selection)", () => {
+ const picking = (checked = false) =>
+ row({
+ selection: { checked, label: "选中 Fix the build", onToggle: () => {} },
+ });
+
+ it("puts the tick before the title and outside the button that opens the conversation", () => {
+ const html = picking(true);
+ expect(html).toMatch(/<input type="checkbox"[^>]*checked=""/);
+ expect(html).toContain('aria-label="选中 Fix the build"');
+ // Siblings, not nested: ticking the box must not also open the conversation.
+ expect(html.indexOf('aria-label="选中 Fix the build"')).toBeLessThan(
+ html.indexOf('data-testid="session-row"'),
+ );
+ });
+
+ it("leaves the time standing and takes the hover actions away", () => {
+ const html = picking();
+ expect(html).toContain(">3 分钟前</span>");
+ expect(html).not.toContain('aria-label="归档"');
+ expect(html).not.toContain('aria-label="更多"');
+ expect(classTokens(html)).not.toContain("group-hover:opacity-0");
+ });
+
+ it("makes the row's own click a tick, never a way out of the list", () => {
+ expect(SOURCE).toContain("if (selection !== undefined) selection.onToggle();");
+ });
+
+ it("draws no box at all when the caller is not picking", () => {
+ expect(row()).not.toContain('type="checkbox"');
+ expect(classTokens(row())).toContain("group-hover:opacity-0");
+ });
+});
+
describe("RowHoverActions", () => {
const html = renderStatic(
createElement(RowHoverActions, {
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index d7687629..394a8644 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -22,7 +22,10 @@
* localStorage): pinned rows bubble to the top of their group's active list. Each row's
* trailing slot shows the compact last-active time at rest and swaps to archive + delete
* icon buttons on hover/focus; the full set (pin, rename, archive, delete) opens as a
- * context menu on right-click, Shift+F10, or a press-and-hold on touch
+ * context menu on right-click, Shift+F10, or a press-and-hold on touch. The header's
+ * batch control beside the search turns the rows into pickers — ticked rows raise a bar
+ * above the list that archives, unarchives or deletes them together (the requirement
+ * box's own batch bar), and leaving the mode drops the ticks.
* -> bottom user row, which opens the shared account menu (user-menu.tsx).
* In company mode the shape holds but the objects change: the organization switcher stands
* where the Project switcher stands, "New channel" where "New chat" is, the organization's
@@ -626,6 +629,17 @@ export function Sidebar({
/** Session pending delete confirmation (null = none). */
const [deletingSession, setDeletingSession] = useState<SessionInfo | null>(null);
const [deletingBusy, setDeletingBusy] = useState(false);
+ /**
+ * Batch processing (the header control beside 搜索会话): while it is on every row is a picker and
+ * the bar above the list acts on the ticked ones. Both are transient — leaving the mode drops the
+ * ticks — because a selection left behind in localStorage would act on rows the reader picked in
+ * another session of the app. The delete confirmation is the batch's own (one dialog over N rows,
+ * rather than N dialogs).
+ */
+ const [batchMode, setBatchMode] = useState(false);
+ const [batchSelected, setBatchSelected] = useState<ReadonlySet<string>>(new Set());
+ const [batchBusy, setBatchBusy] = useState(false);
+ const [batchConfirmDelete, setBatchConfirmDelete] = useState(false);
/** Parked draft conversation pending delete confirmation (null = none). */
const [deletingDraft, setDeletingDraft] = useState<DraftSessionEntry | null>(null);
/** Parked draft conversations of this user × Project, newest first (reactive module store). */
@@ -1261,12 +1275,16 @@ export function Sidebar({
}
};
- const confirmDeleteSession = async () => {
- if (!deletingSession) return;
- setDeletingBusy(true);
- const target = deletingSession;
- try {
- await api.deleteSession(target.sessionId);
+ /**
+ * Everything a deleted conversation leaves behind in this column — the store row, its composer
+ * draft, its pin and its manual-order entry — for one row or for a batch. The pins and the order
+ * are pruned from ONE pair of reads, so two removals in a single turn cannot write the first one
+ * back: both state setters would otherwise see the value they had when the turn began.
+ */
+ const forgetDeletedSessions = (targets: readonly SessionInfo[]) => {
+ let pins: ReadonlySet<string> = pinnedSessions;
+ let order: readonly string[] = sessionOrder;
+ for (const target of targets) {
// remove() also tombstones the id (see the store's isDeleted), which is what keeps the
// chat page from re-fetching the Session it is still routed at during the frames before
// the navigate() below lands. Ordering the two is deliberately NOT the mechanism: the
@@ -1277,17 +1295,27 @@ export function Sidebar({
if (user) clearDraft(sessionDraftKey(user.userId, target.sessionId));
// Prune its pin and manual-order entry as well (both helpers return the same
// reference when the id wasn't present — the write is skipped then).
- const prunedPins = removePinnedSession(pinnedSessions, target.sessionId);
- if (prunedPins !== pinnedSessions) {
- setPinnedSessions(prunedPins);
- savePinnedSessions(currentProjectId, prunedPins);
- }
+ pins = removePinnedSession(pins, target.sessionId);
forgetSession(currentProjectId, target.sessionId);
- const prunedOrder = removeFromSessionOrder(sessionOrder, target.sessionId);
- if (prunedOrder !== sessionOrder) {
- setSessionOrder(prunedOrder);
- saveSessionOrder(currentProjectId, groupMode, prunedOrder);
- }
+ order = removeFromSessionOrder(order, target.sessionId);
+ }
+ if (pins !== pinnedSessions) {
+ setPinnedSessions(pins);
+ savePinnedSessions(currentProjectId, pins);
+ }
+ if (order !== sessionOrder) {
+ setSessionOrder(order);
+ saveSessionOrder(currentProjectId, groupMode, order);
+ }
+ };
+
+ const confirmDeleteSession = async () => {
+ if (!deletingSession) return;
+ setDeletingBusy(true);
+ const target = deletingSession;
+ try {
+ await api.deleteSession(target.sessionId);
+ forgetDeletedSessions([target]);
setDeletingSession(null);
// The deleted session was the one open: jump to this Agent's next conversation, otherwise
// fall back to the chat home page. Auto-opened conversations are never archived (hidden by
@@ -1314,6 +1342,99 @@ export function Sidebar({
onNavigate?.();
};
+ /**
+ * Batch processing over the conversation list (the header control beside 搜索会话). Leaving the
+ * mode drops the ticks: a selection means nothing outside it, and it must not survive to act on
+ * rows picked in some other visit.
+ */
+ const toggleBatchMode = () => {
+ if (batchMode) {
+ setBatchMode(false);
+ setBatchSelected(new Set());
+ return;
+ }
+ setBatchMode(true);
+ };
+
+ const toggleBatchRow = (sessionId: string) => {
+ setBatchSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(sessionId)) next.delete(sessionId);
+ else next.add(sessionId);
+ return next;
+ });
+ };
+
+ /** The ticked conversations, as the objects the column already loaded (the ticks only ever come from its rows). */
+ const batchTargets = () => sessions.filter((s) => batchSelected.has(s.sessionId));
+
+ /**
+ * 批量归档 / 批量取消归档: one request per ticked conversation, the same per-row PATCH the row's own
+ * menu runs — the server has no bulk route, and a batch that fails halfway must not hide which
+ * rows landed. Archiving the conversation on screen opens the archived folder, or its row would
+ * vanish from the list with no way back (the row menu's toggle does the same).
+ */
+ const batchSetArchived = async (archived: boolean) => {
+ const targets = batchTargets();
+ if (targets.length === 0) return;
+ setBatchBusy(true);
+ try {
+ const results = await Promise.all(
+ targets.map((s) => api.patchSession(s.sessionId, { archived })),
+ );
+ for (const res of results) replace(res.session);
+ const openOne = targets.find((s) => s.sessionId === activeSessionId);
+ if (archived && openOne !== undefined) {
+ setOpenFolders((prev) =>
+ new Set(prev).add(folderKey(sessionGroupKey(openOne), "archived")),
+ );
+ }
+ toastSuccess(
+ archived
+ ? S.chat.batchArchiveDone(targets.length)
+ : S.chat.batchUnarchiveDone(targets.length),
+ );
+ setBatchSelected(new Set());
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBatchBusy(false);
+ }
+ };
+
+ /**
+ * 批量删除: the row delete's own confirmation, asked once for the whole selection, then the same
+ * DELETE per row. Deleting the conversation on screen leaves for the next one of its Agent, as the
+ * single delete does — the others are gone from the list, not from what the reader is looking at.
+ */
+ const confirmBatchDelete = async () => {
+ const targets = batchTargets();
+ if (targets.length === 0) return;
+ setBatchBusy(true);
+ try {
+ await Promise.all(targets.map((s) => api.deleteSession(s.sessionId)));
+ forgetDeletedSessions(targets);
+ setBatchConfirmDelete(false);
+ setBatchSelected(new Set());
+ const openOne = targets.find((s) => s.sessionId === activeSessionId);
+ if (openOne !== undefined) {
+ const deleted = new Set(targets.map((s) => s.sessionId));
+ const rest = (byAgent.get(openOne.agentId) ?? []).filter((s) => {
+ const category = sessionCategory(s);
+ return !deleted.has(s.sessionId) && (category === "active" || category === "schedule");
+ });
+ navigate(rest[0] ? `/chat/${rest[0].sessionId}` : "/chat");
+ }
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBatchBusy(false);
+ }
+ };
+
+ /** Clear the ticks, staying in the mode (the bar's own control — leaving is the header's toggle). */
+ const clearBatchSelection = () => setBatchSelected(new Set());
+
/**
* New chat: enters draft state (/chat/new) without creating a Session — Model / Workspace /
* approval mode are all chosen on the draft input card, and the Session is only actually
@@ -1512,7 +1633,7 @@ export function Sidebar({
dragging.id !== s.sessionId &&
pinnedSessions.has(dragging.id) === pinnedSessions.has(s.sessionId);
const drag =
- dragCtx === undefined
+ dragCtx === undefined || batchMode
? {}
: {
draggable: true,
@@ -1601,6 +1722,14 @@ export function Sidebar({
onMessaging={(x) => setMessagingSession(x)}
onDelete={(x) => setDeletingSession(x)}
onToggleArchive={(x) => void toggleArchive(x)}
+ {...(batchMode
+ ? {
+ select: {
+ checked: batchSelected.has(s.sessionId),
+ onToggle: () => toggleBatchRow(s.sessionId),
+ },
+ }
+ : {})}
/>
);
})}
@@ -2122,6 +2251,22 @@ export function Sidebar({
</p>
</ConfirmModal>
+ {/* Batch delete confirmation: the same shared ConfirmModal as the row's own, asked once for
+ the whole selection instead of once per row. */}
+ <ConfirmModal
+ open={batchConfirmDelete}
+ title={S.chat.batchDeleteTitle}
+ confirmLabel={S.common.delete}
+ cancelLabel={S.common.cancel}
+ busy={batchBusy}
+ onClose={() => (batchBusy ? undefined : setBatchConfirmDelete(false))}
+ onConfirm={() => void confirmBatchDelete()}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.chat.batchDeleteConfirm(batchSelected.size)}
+ </p>
+ </ConfirmModal>
+
{/* Remove-workspace confirmation (shared ConfirmModal, same stop as the other
destructive-looking actions): the copy is honest about the scope — sidebar
registry entry only, disk and Sessions untouched, re-addable anytime. */}
@@ -2373,6 +2518,16 @@ export function Sidebar({
onClick={() => setSearchOpen(true)}
/>
)}
+ {/* Batch processing, right beside 搜索会话 (the requirement box's own batch bar is the
+ model): while it is on the rows are pickers and the bar below acts on the ticked
+ ones. */}
+ <SidebarControl
+ label={S.chat.batchSelect}
+ glyph={ICONS.listChecks}
+ active={batchMode}
+ aria-expanded={batchMode}
+ onClick={toggleBatchMode}
+ />
<Dropdown
open={listSettingsOpen}
setOpen={setListSettingsOpen}
@@ -2497,6 +2652,46 @@ export function Sidebar({
)}
</SidebarListHeader>
+ {/* The batch bar: it stands over the list only while something is ticked, so the column
+ loses no row to a control that has nothing to act on — the same rule the requirement
+ box's batch bar follows. Every action goes through the route the row's own menu
+ already uses (one PATCH or DELETE per conversation), and the delete keeps its
+ confirmation, now asked once for the whole selection. */}
+ {batchMode && batchSelected.size > 0 && (
+ <div className="mt-2 flex flex-wrap items-center gap-1 rounded-md border border-line-emphasis px-2 py-1.5">
+ <span className="mr-auto px-0.5 text-xs text-fg-muted">
+ {S.chat.batchCount(batchSelected.size)}
+ </span>
+ <Button
+ size="xs"
+ variant="secondary"
+ disabled={batchBusy}
+ onClick={() => void batchSetArchived(true)}
+ >
+ {S.chat.batchArchive}
+ </Button>
+ <Button
+ size="xs"
+ variant="secondary"
+ disabled={batchBusy}
+ onClick={() => void batchSetArchived(false)}
+ >
+ {S.chat.batchUnarchive}
+ </Button>
+ <Button
+ size="xs"
+ variant="danger"
+ disabled={batchBusy}
+ onClick={() => setBatchConfirmDelete(true)}
+ >
+ {S.chat.batchDelete}
+ </Button>
+ <Button size="xs" variant="link" disabled={batchBusy} onClick={clearBatchSelection}>
+ {S.chat.batchClear}
+ </Button>
+ </div>
+ )}
+
{/* Parked draft conversations (unsent new chats, newest first): pinned above both
grouping modes — they belong to no Agent or Workspace until sent. Hidden
entirely while there are none; the search filter applies to their titles too. */}
@@ -2969,6 +3164,7 @@ function SidebarSessionRow({
lastActive,
locale,
agentHint,
+ select,
draggable = false,
dropEdge = null,
onDragStart,
@@ -3001,6 +3197,8 @@ function SidebarSessionRow({
locale: "zh" | "en";
/** Agent display name; when set (workspace mode) a small avatar keeps the Agent context visible on the row. */
agentHint?: string;
+ /** Batch mode: the row is a picker, ticked or not (the label names it after the conversation). */
+ select?: { checked: boolean; onToggle: () => void };
/** Manual sort: the row can be drag-reordered (the sidebar wires the handlers below). */
draggable?: boolean;
/** Drop indicator edge while another row hovers over this one (a thin accent line above/below). */
@@ -3075,6 +3273,15 @@ function SidebarSessionRow({
menuActions={sessionRowActions(contextMenuActions(canPin), rowState, run)}
moreLabel={S.chat.moreActions}
onOpen={() => onOpen(s)}
+ {...(select !== undefined
+ ? {
+ selection: {
+ checked: select.checked,
+ label: S.chat.batchSelectRow(s.title ?? S.chat.defaultSessionTitle),
+ onToggle: select.onToggle,
+ },
+ }
+ : {})}
draggable={draggable}
dropEdge={dropEdge}
{...(onDragStart ? { onDragStart } : {})}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 82cbba29..95ac9490 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -3144,6 +3144,23 @@ export const en: Strings = {
`Delete draft "${title}"? Unsent content will be discarded.`,
archiveSession: "Archive",
unarchiveSession: "Unarchive",
+ /**
+ * Batch processing on the conversation list: the header control beside Search chats turns every
+ * row into a picker, the bar above the list acts on the ticked ones, and leaving the mode
+ * drops the ticks. (Same shape as the requirement box's batch bar.)
+ */
+ batchSelect: "Batch actions",
+ batchSelectRow: (title: string) => `Select "${title}"`,
+ batchCount: (n: number) => `${n} selected`,
+ batchArchive: "Archive selected",
+ batchUnarchive: "Unarchive selected",
+ batchDelete: "Delete selected",
+ batchClear: "Clear selection",
+ batchArchiveDone: (n: number) => `Archived ${n} chats`,
+ batchUnarchiveDone: (n: number) => `Unarchived ${n} chats`,
+ batchDeleteTitle: "Delete selected chats",
+ batchDeleteConfirm: (n: number) =>
+ `Delete the ${n} selected chats? Their messages and Trace will be removed permanently.`,
/** Per-row ellipsis overflow menu (pin / rename / archive / delete live inside it) and the row-level pin. */
pinSession: "Pin",
unpinSession: "Unpin",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index c5f011aa..0592d75a 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -3197,6 +3197,23 @@ export const zh = {
deleteDraftConfirm: (title: string) => `确定删除草稿「${title}」?未发送的内容将被丢弃。`,
archiveSession: "归档",
unarchiveSession: "取消归档",
+ /**
+ * Batch processing on the conversation list: the header control beside 搜索会话 turns every
+ * row into a picker, the bar above the list acts on the ticked ones, and leaving the mode
+ * drops the ticks. (Same shape as the requirement box's batch bar.)
+ */
+ batchSelect: "批量处理",
+ batchSelectRow: (title: string) => `选中「${title}」`,
+ batchCount: (n: number) => `已选 ${n} 条`,
+ batchArchive: "批量归档",
+ batchUnarchive: "批量取消归档",
+ batchDelete: "批量删除",
+ batchClear: "取消选择",
+ batchArchiveDone: (n: number) => `已归档 ${n} 个对话`,
+ batchUnarchiveDone: (n: number) => `已取消归档 ${n} 个对话`,
+ batchDeleteTitle: "删除选中的对话",
+ batchDeleteConfirm: (n: number) =>
+ `确定删除选中的 ${n} 个对话?其消息与 Trace 将被移除,且不可恢复。`,
/** Per-row ellipsis overflow menu (pin / rename / archive / delete live inside it) and the row-level pin. */
pinSession: "置顶",
unpinSession: "取消置顶",
diff --git a/packages/web/test/sidebar-batch-sessions.test.ts b/packages/web/test/sidebar-batch-sessions.test.ts
new file mode 100644
index 00000000..50d12f4f
--- /dev/null
+++ b/packages/web/test/sidebar-batch-sessions.test.ts
@@ -0,0 +1,130 @@
+/**
+ * Batch processing on the sidebar's conversation list (components/layout/sidebar.tsx): the header
+ * control beside 搜索会话 turns every conversation row into a picker, ticking rows raise a bar over
+ * the list, and the bar archives, unarchives or deletes them together — the requirement box's own
+ * batch bar, in the column.
+ *
+ * The sidebar is a React component the Web App's tests do not render, so what is pinned here is the
+ * part a render would not show anyway: the words in both dictionaries (and the count and the
+ * permanence they admit to), where the control and the bar sit, that every action rides the route
+ * the row's own menu already uses — one request per conversation, the shared cleanup after a
+ * delete, the row delete's own confirmation asked once — and that leaving the mode drops the ticks.
+ */
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+import { zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+const read = (relative: string): string =>
+ readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");
+
+const SIDEBAR = read("../src/components/layout/sidebar.tsx");
+/** Everything the list header holds — the control must sit in it, beside the search. */
+const HEADER = SIDEBAR.slice(0, SIDEBAR.indexOf("</SidebarListHeader>"));
+/** The toggle's own body, up to the next handler. */
+const TOGGLE = SIDEBAR.slice(
+ SIDEBAR.indexOf("const toggleBatchMode = ()"),
+ SIDEBAR.indexOf("const toggleBatchRow"),
+);
+
+describe("the batch bar's words", () => {
+ it("names the mode, the count and the three actions in both dictionaries", () => {
+ expect(zh.chat.batchSelect).toBe("批量处理");
+ expect(en.chat.batchSelect).toBe("Batch actions");
+ expect(zh.chat.batchCount(2)).toBe("已选 2 条");
+ expect(en.chat.batchCount(2)).toBe("2 selected");
+ for (const dict of [zh, en]) {
+ expect(dict.chat.batchArchive).not.toBe("");
+ expect(dict.chat.batchUnarchive).not.toBe("");
+ expect(dict.chat.batchDelete).not.toBe("");
+ expect(dict.chat.batchClear).not.toBe("");
+ expect(dict.chat.batchDeleteTitle).not.toBe("");
+ }
+ expect(zh.chat.batchArchive).toBe("批量归档");
+ expect(zh.chat.batchUnarchive).toBe("批量取消归档");
+ expect(zh.chat.batchDelete).toBe("批量删除");
+ });
+
+ it("reports what an action did, with the count in it", () => {
+ expect(zh.chat.batchArchiveDone(3)).toBe("已归档 3 个对话");
+ expect(zh.chat.batchUnarchiveDone(3)).toBe("已取消归档 3 个对话");
+ expect(en.chat.batchArchiveDone(3)).toBe("Archived 3 chats");
+ expect(en.chat.batchUnarchiveDone(3)).toBe("Unarchived 3 chats");
+ });
+
+ it("keeps the delete's copy as blunt as the row's own confirmation is", () => {
+ expect(zh.chat.batchDeleteConfirm(3)).toContain("3");
+ expect(zh.chat.batchDeleteConfirm(3)).toContain("不可恢复");
+ expect(en.chat.batchDeleteConfirm(3)).toContain("3");
+ expect(en.chat.batchDeleteConfirm(3)).toContain("permanently");
+ });
+
+ it("names each row's box after the conversation it stands for", () => {
+ expect(zh.chat.batchSelectRow("修构建")).toBe("选中「修构建」");
+ expect(en.chat.batchSelectRow("Fix the build")).toBe('Select "Fix the build"');
+ });
+});
+
+describe("the batch wiring", () => {
+ it("hangs the mode off a control in the list header, beside the search", () => {
+ expect(HEADER).toContain("label={S.chat.searchSessions}");
+ expect(HEADER).toContain("label={S.chat.batchSelect}");
+ expect(HEADER).toContain("glyph={ICONS.listChecks}");
+ expect(HEADER).toContain("onClick={toggleBatchMode}");
+ expect(HEADER.indexOf("label={S.chat.searchSessions}")).toBeLessThan(
+ HEADER.indexOf("label={S.chat.batchSelect}"),
+ );
+ });
+
+ it("raises the bar only over a selection, and gives it the four controls", () => {
+ const marker = "{batchMode && batchSelected.size > 0 && (";
+ expect(SIDEBAR).toContain(marker);
+ // From the bar's own gate to the drafts below it: everything the bar is made of.
+ const bar = SIDEBAR.slice(
+ SIDEBAR.indexOf(marker),
+ SIDEBAR.indexOf("unsent new chats, newest first"),
+ );
+ expect(bar).toContain("S.chat.batchCount(batchSelected.size)");
+ expect(bar).toContain("batchSetArchived(true)");
+ expect(bar).toContain("batchSetArchived(false)");
+ expect(bar).toContain("setBatchConfirmDelete(true)");
+ expect(bar).toContain("clearBatchSelection");
+ });
+
+ it("makes every row a picker, ticked from the selection it belongs to", () => {
+ expect(SIDEBAR).toContain("checked: batchSelected.has(s.sessionId)");
+ expect(SIDEBAR).toContain("onToggle: () => toggleBatchRow(s.sessionId)");
+ // The ui row draws the box; the app hands it the label naming the conversation.
+ expect(SIDEBAR).toContain(
+ "label: S.chat.batchSelectRow(s.title ?? S.chat.defaultSessionTitle)",
+ );
+ expect(SIDEBAR).toContain("selection: {");
+ });
+
+ it("acts through the routes the row's own menu already uses, one request per conversation", () => {
+ expect(SIDEBAR).toContain("api.patchSession(s.sessionId, { archived })");
+ expect(SIDEBAR).toContain("targets.map((s) => api.deleteSession(s.sessionId))");
+ // Both the single delete and the batch leave through the one cleanup.
+ expect(SIDEBAR).toContain("forgetDeletedSessions([target]);");
+ expect(SIDEBAR).toContain("forgetDeletedSessions(targets);");
+ });
+
+ it("keeps the delete's confirmation, asked once for the whole selection", () => {
+ expect(SIDEBAR).toContain("title={S.chat.batchDeleteTitle}");
+ expect(SIDEBAR).toContain("onConfirm={() => void confirmBatchDelete()}");
+ expect(SIDEBAR).toContain("S.chat.batchDeleteConfirm(batchSelected.size)");
+ });
+
+ it("drops the ticks when the mode is left, and clears them after an action lands", () => {
+ expect(TOGGLE).toContain("setBatchMode(false)");
+ expect(TOGGLE).toContain("setBatchSelected(new Set())");
+ expect(SIDEBAR).toContain("const clearBatchSelection = () => setBatchSelected(new Set());");
+ // Archived and deleted rows are no longer the ones the reader picked.
+ expect(SIDEBAR.match(/setBatchSelected\(new Set\(\)\)/g)?.length).toBeGreaterThanOrEqual(4);
+ });
+
+ it("stops reordering rows while they are being picked", () => {
+ expect(SIDEBAR).toContain("dragCtx === undefined || batchMode");
+ });
+});