:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): select multiple sessions and act on them at once (#80839)
Gustavo H. Strassburgerb7be39046706
diff --git a/products/desktop/packages/core/src/command-center/grid.test.ts b/products/desktop/packages/core/src/command-center/grid.test.tsindex a69414fba729..3c9c9e5cd0d5 100644--- a/products/desktop/packages/core/src/command-center/grid.test.ts+++ b/products/desktop/packages/core/src/command-center/grid.test.ts@@ -8,6 +8,7 @@ import {getExpandedLayout,getExpansionCellIndex,getGridDimensions,+ getLayoutToFit,getOptimalLayout,getTerminalCellCwd,getTerminalCellId,@@ -69,6 +70,39 @@ describe("getOptimalLayout", () => {});});+describe("getLayoutToFit", () => {+ it.each([+ { current: "2x2", needed: 4, expected: "2x2" },+ { current: "2x2", needed: 2, expected: "2x2" },+ { current: "2x2", needed: 5, expected: "3x2" },+ { current: "1x1", needed: 4, expected: "2x2" },+ { current: "1x1", needed: 2, expected: "2x1" },+ { current: "3x1", needed: 5, expected: "3x2" },+ { current: "2x2", needed: 20, expected: "3x3" },+ ] as const)(+ "grows $current to $expected for $needed tiles",+ ({ current, needed, expected }) => {+ expect(getLayoutToFit(current, needed)).toBe(expected);+ },+ );++ // getOptimalLayout(5) is 3x2, which would cost 1x3 its third row on reflow.+ it.each([+ { current: "1x3", needed: 5, expected: "2x3" },+ { current: "1x2", needed: 5, expected: "3x2" },+ ] as const)(+ "never shrinks an axis: $current for $needed tiles",+ ({ current, needed, expected }) => {+ const result = getLayoutToFit(current, needed);+ expect(result).toBe(expected);+ const before = getGridDimensions(current);+ const after = getGridDimensions(result);+ expect(after.cols).toBeGreaterThanOrEqual(before.cols);+ expect(after.rows).toBeGreaterThanOrEqual(before.rows);+ },+ );+});+describe("getExpandedLayout", () => {it.each([["1x1", "horizontal", "2x1"],diff --git a/products/desktop/packages/core/src/command-center/grid.ts b/products/desktop/packages/core/src/command-center/grid.tsindex 60d3b135a9fe..42b8cb734fb9 100644--- a/products/desktop/packages/core/src/command-center/grid.ts+++ b/products/desktop/packages/core/src/command-center/grid.ts@@ -130,6 +130,43 @@ export function getOptimalLayout(count: number): LayoutPreset {return `${cols}x${rows}` as LayoutPreset;}+/**+ * Fewest tiles wins, then the squarer shape, then the wider one — matching+ * `getOptimalLayout`, which is never taller than it is wide.+ */+function isBetterFit(a: GridDimensions, b: GridDimensions): boolean {+ const [areaA, areaB] = [a.cols * a.rows, b.cols * b.rows];+ if (areaA !== areaB) return areaA < areaB;+ const [skewA, skewB] = [Math.abs(a.cols - a.rows), Math.abs(b.cols - b.rows)];+ if (skewA !== skewB) return skewA < skewB;+ return a.cols > b.cols;+}++/**+ * The smallest layout holding `needed` tiles without shrinking either axis of+ * `current`. Unlike `getOptimalLayout`, which picks the tightest shape for a+ * count in isolation, this only ever grows: dropping from 1x3 to 3x2 would fit+ * more tiles overall but `reflowCells` would discard whatever sat in row 3.+ */+export function getLayoutToFit(+ current: LayoutPreset,+ needed: number,+): LayoutPreset {+ const from = getGridDimensions(current);+ if (needed <= from.cols * from.rows) return current;++ let best: GridDimensions | null = null;+ for (let cols = from.cols; cols <= MAX_SPAN; cols++) {+ for (let rows = from.rows; rows <= MAX_SPAN; rows++) {+ if (cols * rows < needed) continue;+ if (!best || isBetterFit({ cols, rows }, best)) best = { cols, rows };+ }+ }+ // Nothing within the 3x3 ceiling fits, so grow as far as the ceiling allows.+ const { cols, rows } = best ?? { cols: MAX_SPAN, rows: MAX_SPAN };+ return `${cols}x${rows}` as LayoutPreset;+}+export function resizeCells(current: (string | null)[],newCount: number,diff --git a/products/desktop/packages/core/src/command-center/placement.test.ts b/products/desktop/packages/core/src/command-center/placement.test.tsnew file mode 100644index 000000000000..895d9ee162c9--- /dev/null+++ b/products/desktop/packages/core/src/command-center/placement.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from "vitest";+import { BRAINROT_CELL, makeTerminalCellValue } from "./grid";+import { type PlacementInput, planCommandCenterPlacement } from "./placement";++/**+ * Defaults every id on the grid to a task that still exists, which is the+ * ordinary case. Cases about deleted tasks pass `liveTaskIds` themselves.+ */+function plan(input: Omit<PlacementInput, "liveTaskIds">) {+ return planCommandCenterPlacement({+ ...input,+ liveTaskIds: new Set(input.cells.filter((c): c is string => c != null)),+ });+}++describe("planCommandCenterPlacement", () => {+ it("fills empty tiles in order without touching the layout", () => {+ const result = plan({+ cells: ["a", null, null, null],+ layout: "2x2",+ taskIds: ["b", "c"],+ });+ expect(result.layout).toBe("2x2");+ expect(result.cells).toEqual(["a", "b", "c", null]);+ expect(result.placed).toEqual(["b", "c"]);+ expect(result.overflow).toEqual([]);+ });++ it("grows the layout when the batch outgrows the empty tiles", () => {+ const result = plan({+ cells: ["a", "b", "c", null],+ layout: "2x2",+ taskIds: ["d", "e", "f"],+ });+ expect(result.layout).toBe("3x2");+ // Growing a column moves rows, so b stays beside a and c stays on row two.+ expect(result.cells).toEqual(["a", "b", "d", "c", "e", "f"]);+ expect(result.placed).toEqual(["d", "e", "f"]);+ expect(result.overflow).toEqual([]);+ });++ it("reports ids that do not fit even at the 3x3 ceiling", () => {+ const result = plan({+ cells: Array.from({ length: 9 }, (_, i) => `t${i}`),+ layout: "3x3",+ taskIds: ["new-1", "new-2"],+ });+ expect(result.layout).toBe("3x3");+ expect(result.placed).toEqual([]);+ expect(result.overflow).toEqual(["new-1", "new-2"]);+ });++ it("leaves ids already on the grid where they are", () => {+ const result = plan({+ cells: ["a", null, null, null],+ layout: "2x2",+ taskIds: ["a", "b"],+ });+ expect(result.cells).toEqual(["a", "b", null, null]);+ expect(result.alreadyPresent).toEqual(["a"]);+ expect(result.placed).toEqual(["b"]);+ });++ it("deduplicates the batch", () => {+ const result = plan({+ cells: [null, null, null, null],+ layout: "2x2",+ taskIds: ["a", "a", "b"],+ });+ expect(result.cells).toEqual(["a", "b", null, null]);+ expect(result.placed).toEqual(["a", "b"]);+ });++ it.each([+ { name: "brainrot", cell: BRAINROT_CELL },+ { name: "terminal", cell: makeTerminalCellValue("abc123") },+ ])("never overwrites the $name sentinel", ({ cell }) => {+ // Sentinels are not tasks, so they are absent from every live task list.+ const result = planCommandCenterPlacement({+ cells: [cell, null],+ layout: "2x1",+ taskIds: ["a"],+ liveTaskIds: new Set<string>(),+ });+ expect(result.cells).toEqual([cell, "a"]);+ });++ it("reuses a cell whose task was deleted, which the grid draws empty", () => {+ const result = planCommandCenterPlacement({+ cells: ["gone", "b"],+ layout: "2x1",+ taskIds: ["c"],+ liveTaskIds: new Set(["b"]),+ });+ expect(result.layout).toBe("2x1");+ expect(result.cells).toEqual(["c", "b"]);+ expect(result.overflow).toEqual([]);+ });++ it("holds every cell while the task list is unknown", () => {+ const cells = Array.from({ length: 9 }, (_, i) => `t${i}`);+ const result = planCommandCenterPlacement({+ cells,+ layout: "3x3",+ taskIds: ["new"],+ liveTaskIds: null,+ });+ expect(result.cells).toEqual(cells);+ expect(result.overflow).toEqual(["new"]);+ });++ it("is a no-op for an empty batch", () => {+ const result = plan({+ cells: ["a", null],+ layout: "2x1",+ taskIds: [],+ });+ expect(result).toEqual({+ layout: "2x1",+ cells: ["a", null],+ placed: [],+ overflow: [],+ alreadyPresent: [],+ });+ });+});diff --git a/products/desktop/packages/core/src/command-center/placement.ts b/products/desktop/packages/core/src/command-center/placement.tsnew file mode 100644index 000000000000..eca00047e637--- /dev/null+++ b/products/desktop/packages/core/src/command-center/placement.ts@@ -0,0 +1,96 @@+import {+ getCellCount,+ getLayoutToFit,+ isBrainrotCell,+ isTerminalCell,+ type LayoutPreset,+ reflowCells,+} from "./grid";++export interface PlacementPlan {+ layout: LayoutPreset;+ cells: (string | null)[];+ /** Ids that landed in a tile, in the order they were given. */+ placed: string[];+ /** Ids with nowhere to go once the grid hit its ceiling. */+ overflow: string[];+ /** Ids already on the grid, left in the tile they were in. */+ alreadyPresent: string[];+}++export interface PlacementInput {+ cells: readonly (string | null)[];+ layout: LayoutPreset;+ taskIds: readonly string[];+ /**+ * The tasks that still exist. Cells are persisted and only pruned when a task+ * is archived, so a deleted task's id lingers in the array; the grid renders+ * that tile empty, and placement has to see the same free tile the user does.+ *+ * `null` when the task list isn't known yet, which holds every non-empty cell.+ * Guessing the other way would tile over sessions that are still on the grid.+ */+ liveTaskIds: ReadonlySet<string> | null;+}++/**+ * Where a batch of sessions should sit on the command center grid: empty tiles+ * first, in display order, growing the grid when the batch outgrows them.+ *+ * Occupied tiles are never overwritten, which also covers the brainrot and+ * terminal sentinels — they hold something the grid draws, so they read as+ * occupied like any cell holding a session.+ */+export function planCommandCenterPlacement(+ input: PlacementInput,+): PlacementPlan {+ const { layout, liveTaskIds, taskIds } = input;+ const batch = new Set(taskIds);+ // A cell is occupied when it holds something the grid actually draws. The+ // batch counts as live too, so a session already tiled is left where it is+ // rather than placed a second time.+ const isOccupied = (cell: string | null): cell is string =>+ cell != null &&+ (liveTaskIds == null ||+ isBrainrotCell(cell) ||+ isTerminalCell(cell) ||+ liveTaskIds.has(cell) ||+ batch.has(cell));+ const occupants = new Set(input.cells.filter(isOccupied));++ const alreadyPresent: string[] = [];+ const queue: string[] = [];+ for (const id of batch) {+ if (occupants.has(id)) alreadyPresent.push(id);+ else queue.push(id);+ }++ if (queue.length === 0) {+ return {+ layout,+ cells: [...input.cells],+ placed: [],+ overflow: [],+ alreadyPresent,+ };+ }++ const nextLayout = getLayoutToFit(layout, occupants.size + queue.length);+ const cells =+ nextLayout === layout+ ? [...input.cells]+ : reflowCells(input.cells, layout, nextLayout);+ // reflowCells always sizes to the target, but the no-growth branch copies the+ // array as-is — and a persisted grid can be shorter than its own layout.+ while (cells.length < getCellCount(nextLayout)) cells.push(null);++ const placed: string[] = [];+ for (let i = 0; i < cells.length && queue.length > 0; i++) {+ if (isOccupied(cells[i])) continue;+ const id = queue.shift() as string;+ cells[i] = id;+ placed.push(id);+ }++ return { layout: nextLayout, cells, placed, overflow: queue, alreadyPresent };+}diff --git a/products/desktop/packages/core/src/context-menu/context-menu.test.ts b/products/desktop/packages/core/src/context-menu/context-menu.test.tsindex 764a6dc5cdef..1822f63e58b2 100644--- a/products/desktop/packages/core/src/context-menu/context-menu.test.ts+++ b/products/desktop/packages/core/src/context-menu/context-menu.test.ts@@ -1,3 +1,4 @@+import { formatBulkArchiveWarning } from "@posthog/core/sidebar/selection";import type {ContextMenuAction,ContextMenuItem,@@ -50,6 +51,15 @@ function findItem(items: ContextMenuItem[], label: string): ContextMenuAction {return item;}+function findSubmenuItem(+ items: ContextMenuItem[],+ submenuLabel: string,+ itemLabel: string,+): ContextMenuAction {+ const submenu = findItem(items, submenuLabel).submenu ?? [];+ return findItem(submenu, itemLabel);+}+function makeService(menu: IContextMenu, dialog: IDialog = dialogReturning(1)) {return new ContextMenuService(noExternalApps, dialog, menu);}@@ -183,16 +193,90 @@ describe("ContextMenuService.showTaskContextMenu", () => {});describe("ContextMenuService.showBulkTaskContextMenu", () => {- it("labels the archive action with the task count and gates on confirm", async () => {+ it("labels every action with the session count", async () => {+ const menu = new FakeContextMenu();+ const result = makeService(menu).showBulkTaskContextMenu({ taskCount: 3 });+ await menu.shown;+ expect(labels(menu.lastItems)).toEqual([+ "Pin 3 sessions",+ "Add 3 sessions to Command Center",+ "Archive 3 sessions",+ ]);+ findItem(menu.lastItems, "Add 3 sessions to Command Center").click();+ expect(await result).toEqual({ action: { type: "add-to-command-center" } });+ });++ it.each([+ { allPinned: false, expected: "Pin 3 sessions" },+ { allPinned: true, expected: "Unpin 3 sessions" },+ ])(+ "offers $expected when allPinned=$allPinned",+ async ({ allPinned, expected }) => {+ const menu = new FakeContextMenu();+ const result = makeService(menu).showBulkTaskContextMenu({+ taskCount: 3,+ allPinned,+ });+ await menu.shown;+ findItem(menu.lastItems, expected).click();+ expect(await result).toEqual({ action: { type: "pin" } });+ },+ );++ it("omits the File to submenu when there are no channels", async () => {+ const menu = new FakeContextMenu();+ makeService(menu).showBulkTaskContextMenu({ taskCount: 2, channels: [] });+ await menu.shown;+ expect(labels(menu.lastItems)).not.toContain("File to…");+ });++ it("resolves a channel from the File to submenu", async () => {+ const menu = new FakeContextMenu();+ const result = makeService(menu).showBulkTaskContextMenu({+ taskCount: 2,+ // Stored bare, shown with the hash the menu adds.+ channels: [{ id: "c1", name: "support" }],+ });+ await menu.shown;+ findSubmenuItem(menu.lastItems, "File to…", "#support").click();+ expect(await result).toEqual({+ action: { type: "file-to-channel", channelId: "c1" },+ });+ });++ it("gates archive on confirmation", async () => {const menu = new FakeContextMenu();const result = makeService(menu,- dialogReturning(1),+ dialogReturning(0),).showBulkTaskContextMenu({ taskCount: 3 });await menu.shown;- expect(labels(menu.lastItems)).toEqual(["Archive 3 tasks"]);- findItem(menu.lastItems, "Archive 3 tasks").click();- expect(await result).toEqual({ action: { type: "archive" } });+ findItem(menu.lastItems, "Archive 3 sessions").click();+ expect(await result).toEqual({ action: null });+ });++ // The native confirm and the action bar's dialog must warn about the same+ // things; both compose their detail with formatBulkArchiveWarning.+ it("warns in the archive confirm about running sessions and cloud sandboxes", async () => {+ const menu = new FakeContextMenu();+ let confirmOptions: ConfirmOptions | undefined;+ const dialog = {+ confirm: async (options: ConfirmOptions) => {+ confirmOptions = options;+ return 1;+ },+ } as IDialog;+ const result = makeService(menu, dialog).showBulkTaskContextMenu({+ taskCount: 3,+ runningCount: 2,+ stopsCloudSandbox: true,+ });+ await menu.shown;+ findItem(menu.lastItems, "Archive 3 sessions").click();+ await result;+ expect(confirmOptions?.detail).toBe(+ formatBulkArchiveWarning({ running: 2, stopsCloudSandbox: true }),+ );});});diff --git a/products/desktop/packages/core/src/context-menu/context-menu.ts b/products/desktop/packages/core/src/context-menu/context-menu.tsindex 82097978eaa4..8ec79e5bc00f 100644--- a/products/desktop/packages/core/src/context-menu/context-menu.ts+++ b/products/desktop/packages/core/src/context-menu/context-menu.ts@@ -1,3 +1,7 @@+import {+ formatBulkArchiveWarning,+ sessionsLabel,+} from "@posthog/core/sidebar/selection";import {CONTEXT_MENU_SERVICE,type ContextMenuItem,@@ -130,7 +134,9 @@ export class ContextMenuService {type: "submenu",label: "File to…",items: channels.map((c) => ({- label: c.name,+ // Channel names are stored bare; every surface that shows one+ // adds the hash.+ label: `#${c.name}`,action: {type: "file-to-channel" as const,channelId: c.id,@@ -183,7 +189,7 @@ export class ContextMenuService {title: "Archive Prior Tasks",message: "Archive all tasks older than this one?",detail:- "This will archive every task created before this one. You can unarchive them later.",+ "This will archive every task last active before this one. You can unarchive them later.",confirmLabel: "Archive",},},@@ -196,17 +202,54 @@ export class ContextMenuService {async showBulkTaskContextMenu(input: BulkTaskContextMenuInput,): Promise<{ action: BulkTaskAction | null }> {- const { taskCount } = input;- const label = `Archive ${taskCount} tasks`;+ const {+ taskCount,+ allPinned,+ runningCount = 0,+ stopsCloudSandbox = false,+ channels,+ } = input;+ const sessions = sessionsLabel(taskCount);++ // Only archive confirms — pinning, tiling, and filing are all one click to undo.return this.showMenu<BulkTaskAction>([+ this.item(allPinned ? `Unpin ${sessions}` : `Pin ${sessions}`, {+ type: "pin",+ }),+ this.separator(),+ this.item(`Add ${sessions} to Command Center`, {+ type: "add-to-command-center",+ }),+ ...(channels && channels.length > 0+ ? [+ this.separator(),+ {+ type: "submenu" as const,+ label: "File to…",+ items: channels.map((c) => ({+ // Channel names are stored bare; every surface that shows one+ // adds the hash.+ label: `#${c.name}`,+ action: {+ type: "file-to-channel" as const,+ channelId: c.id,+ },+ })),+ },+ ]+ : []),+ this.separator(),this.item(- label,+ `Archive ${sessions}`,{ type: "archive" },{confirm: {- title: "Archive Tasks",- message: `Archive ${taskCount} tasks?`,- detail: "You can unarchive them later.",+ title: "Archive sessions",+ message: `Archive ${sessions}?`,+ detail: formatBulkArchiveWarning({+ running: runningCount,+ stopsCloudSandbox,+ }),confirmLabel: "Archive",},},diff --git a/products/desktop/packages/core/src/context-menu/schemas.ts b/products/desktop/packages/core/src/context-menu/schemas.tsindex f57171cc042b..ecf76625a55f 100644--- a/products/desktop/packages/core/src/context-menu/schemas.ts+++ b/products/desktop/packages/core/src/context-menu/schemas.ts@@ -17,6 +17,14 @@ export const taskContextMenuInput = z.object({export const bulkTaskContextMenuInput = z.object({taskCount: z.number().int().min(2),+ // Every selected session is pinned, so the pin item unpins instead.+ allPinned: z.boolean().optional(),+ // How many of the selection are still running; shapes the archive confirm.+ runningCount: z.number().int().min(0).optional(),+ // Whether archiving would also shut a cloud sandbox down.+ stopsCloudSandbox: z.boolean().optional(),+ // "File to…" targets. Omit (or pass empty) to hide the submenu entirely.+ channels: z.array(z.object({ id: z.string(), name: z.string() })).optional(),});export const archivedTaskContextMenuInput = z.object({@@ -56,8 +64,13 @@ const taskAction = z.discriminatedUnion("type", [z.object({ type: z.literal("file-to-channel"), channelId: z.string() }),]);+// `pin` carries no direction: the label and the resolver both derive it from+// `allPinned`, the same way the single-task `suspend` action does.const bulkTaskAction = z.discriminatedUnion("type", [z.object({ type: z.literal("archive") }),+ z.object({ type: z.literal("pin") }),+ z.object({ type: z.literal("add-to-command-center") }),+ z.object({ type: z.literal("file-to-channel"), channelId: z.string() }),]);const archivedTaskAction = z.discriminatedUnion("type", [diff --git a/products/desktop/packages/core/src/sidebar/buildSidebarData.ts b/products/desktop/packages/core/src/sidebar/buildSidebarData.tsindex 13d650131bb8..dee8cffffaf2 100644--- a/products/desktop/packages/core/src/sidebar/buildSidebarData.ts+++ b/products/desktop/packages/core/src/sidebar/buildSidebarData.ts@@ -193,6 +193,25 @@ export function isTaskUnread();}+/**+ * Whether a session is running, and where. Split out because a surface can need+ * this without the workspace and pin lookups the rest of `TaskData` costs.+ */+export function deriveTaskRunState(+ task: Pick<SidebarTask, "id" | "latest_run">,+ session: TaskSession | undefined,+): Pick<+ TaskData,+ "id" | "isGenerating" | "taskRunStatus" | "taskRunEnvironment"+> {+ return {+ id: task.id,+ isGenerating: session?.isPromptPending ?? false,+ taskRunStatus: session?.cloudStatus ?? task.latest_run?.status ?? undefined,+ taskRunEnvironment: task.latest_run?.environment ?? undefined,+ };+}+export function deriveTaskData(task: SidebarTask,ctx: DeriveTaskDataContext,@@ -214,19 +233,16 @@ export function deriveTaskData(task.slack_thread_url ?? ctx.slackThreadUrlByTaskId.get(task.id);return {- id: task.id,+ ...deriveTaskRunState(task, session),title: task.title,createdAt,lastActivityAt,- isGenerating: session?.isPromptPending ?? false,isUnread,isPinned: ctx.pinnedIds.has(task.id),isSuspended: ctx.suspendedIds.has(task.id),needsPermission: (session?.pendingPermissions?.size ?? 0) > 0,repository: getRepositoryInfo(task, workspace?.folderPath ?? undefined),folderId: workspace?.folderId || undefined,- taskRunStatus: session?.cloudStatus ?? task.latest_run?.status ?? undefined,- taskRunEnvironment: task.latest_run?.environment ?? undefined,runMode: task.latest_run?.mode ?? undefined,// The `latest_run` fallback only matters in the `showAllUsers` view: the// default view's `filterVisibleTasks` already restricts to tasks with adiff --git a/products/desktop/packages/core/src/sidebar/marquee.test.ts b/products/desktop/packages/core/src/sidebar/marquee.test.tsnew file mode 100644index 000000000000..dec8c43d2d24--- /dev/null+++ b/products/desktop/packages/core/src/sidebar/marquee.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from "vitest";+import {+ hasDraggedFar,+ marqueeSpan,+ mergeMarqueeSelection,+ rowsInMarquee,+} from "./marquee";++const rows = [+ { id: "a", top: 0, bottom: 20 },+ { id: "b", top: 20, bottom: 40 },+ { id: "c", top: 40, bottom: 60 },+];++describe("hasDraggedFar", () => {+ it.each([+ { name: "a still press", dx: 0, dy: 0, expected: false },+ { name: "a shaky click", dx: 1, dy: 2, expected: false },+ { name: "a vertical drag", dx: 0, dy: 6, expected: true },+ { name: "an upward drag", dx: 0, dy: -6, expected: true },+ { name: "a sideways drag", dx: 9, dy: 0, expected: true },+ ])("reads $name as $expected", ({ dx, dy, expected }) => {+ expect(hasDraggedFar(dx, dy)).toBe(expected);+ });+});++describe("marqueeSpan", () => {+ it.each([+ { name: "downward", origin: 10, current: 50 },+ { name: "upward", origin: 50, current: 10 },+ ])("normalizes a $name drag", ({ origin, current }) => {+ expect(marqueeSpan(origin, current)).toEqual({ top: 10, bottom: 50 });+ });+});++describe("rowsInMarquee", () => {+ it("takes every row the span crosses", () => {+ expect(rowsInMarquee({ top: 10, bottom: 45 }, rows)).toEqual([+ "a",+ "b",+ "c",+ ]);+ });++ it("takes a row the span only grazes", () => {+ expect(rowsInMarquee({ top: 55, bottom: 80 }, rows)).toEqual(["c"]);+ });++ it("takes nothing when the span misses every row", () => {+ expect(rowsInMarquee({ top: 70, bottom: 90 }, rows)).toEqual([]);+ });+});++describe("mergeMarqueeSelection", () => {+ it("replaces the previous selection by default", () => {+ expect(mergeMarqueeSelection(["a", "b"], ["c"], false)).toEqual(["c"]);+ });++ it("keeps the previous selection when additive", () => {+ expect(mergeMarqueeSelection(["a"], ["b", "c"], true)).toEqual([+ "a",+ "b",+ "c",+ ]);+ });++ it("does not duplicate a row already selected", () => {+ expect(mergeMarqueeSelection(["a", "b"], ["b", "c"], true)).toEqual([+ "a",+ "b",+ "c",+ ]);+ });+});diff --git a/products/desktop/packages/core/src/sidebar/marquee.ts b/products/desktop/packages/core/src/sidebar/marquee.tsnew file mode 100644index 000000000000..45fd541c0b37--- /dev/null+++ b/products/desktop/packages/core/src/sidebar/marquee.ts@@ -0,0 +1,53 @@+import { dedupeTaskIds } from "./selection";++/** How far the pointer travels before a press counts as a drag rather than a click. */+export const MARQUEE_THRESHOLD_PX = 4;++export interface MarqueeSpan {+ top: number;+ bottom: number;+}++export interface MarqueeRow {+ id: string;+ top: number;+ bottom: number;+}++export function hasDraggedFar(dx: number, dy: number): boolean {+ return (+ Math.abs(dx) >= MARQUEE_THRESHOLD_PX || Math.abs(dy) >= MARQUEE_THRESHOLD_PX+ );+}++/** The span between where the drag began and where it is now, either direction. */+export function marqueeSpan(originY: number, currentY: number): MarqueeSpan {+ return originY <= currentY+ ? { top: originY, bottom: currentY }+ : { top: currentY, bottom: originY };+}++/**+ * Rows the span touches. A session list is one column, so only the vertical+ * axis decides — dragging off to the side still selects what you dragged past.+ */+export function rowsInMarquee(+ span: MarqueeSpan,+ rows: readonly MarqueeRow[],+): string[] {+ return rows+ .filter((row) => row.bottom >= span.top && row.top <= span.bottom)+ .map((row) => row.id);+}++/**+ * A drag replaces the selection, as it does in a file manager. Holding the+ * modifier keeps what was selected when the drag began and adds to it.+ */+export function mergeMarqueeSelection(+ base: readonly string[],+ hit: readonly string[],+ additive: boolean,+): string[] {+ return additive ? dedupeTaskIds([...base, ...hit]) : [...hit];+}diff --git a/products/desktop/packages/core/src/sidebar/selection.test.ts b/products/desktop/packages/core/src/sidebar/selection.test.tsindex 9663cd72f2c1..4dac175a3447 100644--- a/products/desktop/packages/core/src/sidebar/selection.test.ts+++ b/products/desktop/packages/core/src/sidebar/selection.test.ts@@ -1,11 +1,14 @@import { describe, expect, it } from "vitest";import {+ computeBulkPinDirection,computeEffectiveBulkIds,computeOrderedVisibleTaskIds,computePriorTaskIds,computeRangeSelection,dedupeTaskIds,formatArchiveResult,+ formatBulkArchiveWarning,+ formatBulkResult,pruneToVisible,} from "./selection";import type { TaskData } from "./sidebarData.types";@@ -126,32 +129,110 @@ describe("computeOrderedVisibleTaskIds", () => {});describe("computePriorTaskIds", () => {- it("returns ids created before the clicked task", () => {+ it("returns ids last active before the clicked task", () => {const all = [- { id: "t1", createdAt: 100 },- { id: "t2", createdAt: 200 },- { id: "t3", createdAt: 300 },+ { id: "t1", lastActivityAt: 100 },+ { id: "t2", lastActivityAt: 200 },+ { id: "t3", lastActivityAt: 300 },];expect(computePriorTaskIds(all, "t2")).toEqual(["t1"]);});it("returns empty when clicked task not found", () => {- expect(computePriorTaskIds([{ id: "t1", createdAt: 1 }], "x")).toEqual([]);+ expect(computePriorTaskIds([{ id: "t1", lastActivityAt: 1 }], "x")).toEqual(+ [],+ );});});-describe("formatArchiveResult", () => {- it("formats success singular", () => {- expect(formatArchiveResult({ archived: 1, failed: 0 })).toEqual({+describe("computeBulkPinDirection", () => {+ it.each([+ { name: "nothing selected", selected: [], pinned: [], expected: "pin" },+ {+ name: "none pinned",+ selected: ["t1", "t2"],+ pinned: [],+ expected: "pin",+ },+ {+ name: "some pinned",+ selected: ["t1", "t2"],+ pinned: ["t1"],+ expected: "pin",+ },+ {+ name: "all pinned",+ selected: ["t1", "t2"],+ pinned: ["t1", "t2", "t3"],+ expected: "unpin",+ },+ ])("returns $expected when $name", ({ selected, pinned, expected }) => {+ expect(computeBulkPinDirection(selected, new Set(pinned))).toBe(expected);+ });+});++describe("formatBulkResult", () => {+ it.each([+ { kind: "archived" as const, succeeded: 1, message: "1 session archived" },+ { kind: "archived" as const, succeeded: 3, message: "3 sessions archived" },+ { kind: "pinned" as const, succeeded: 4, message: "4 sessions pinned" },+ { kind: "unpinned" as const, succeeded: 2, message: "2 sessions unpinned" },+ { kind: "filed" as const, succeeded: 1, message: "1 session filed" },+ {+ kind: "added to Command Center" as const,+ succeeded: 2,+ message: "2 sessions added to Command Center",+ },+ ])("formats $succeeded $kind", ({ kind, succeeded, message }) => {+ expect(formatBulkResult(kind, { succeeded, failed: 0 })).toEqual({kind: "success",- message: "1 task archived",+ message,});});- it("formats success plural", () => {+ it("reports failures as an error", () => {+ expect(formatBulkResult("pinned", { succeeded: 2, failed: 1 })).toEqual({+ kind: "error",+ message: "2 pinned, 1 failed",+ });+ });+});++describe("formatBulkArchiveWarning", () => {+ it.each([+ {+ name: "nothing running",+ counts: { running: 0, stopsCloudSandbox: false },+ expected: "You can unarchive them later.",+ },+ {+ name: "one running",+ counts: { running: 1, stopsCloudSandbox: false },+ expected:+ "You can unarchive them later. 1 of them is still running and will be stopped.",+ },+ {+ name: "several running",+ counts: { running: 3, stopsCloudSandbox: false },+ expected:+ "You can unarchive them later. 3 of them are still running and will be stopped.",+ },+ {+ name: "a cloud sandbox",+ counts: { running: 2, stopsCloudSandbox: true },+ expected:+ "You can unarchive them later. 2 of them are still running and will be stopped. Any cloud sandbox in the selection shuts down too.",+ },+ ])("describes $name", ({ counts, expected }) => {+ expect(formatBulkArchiveWarning(counts)).toBe(expected);+ });+});++describe("formatArchiveResult", () => {+ it("formats success", () => {expect(formatArchiveResult({ archived: 3, failed: 0 })).toEqual({kind: "success",- message: "3 tasks archived",+ message: "3 sessions archived",});});diff --git a/products/desktop/packages/core/src/sidebar/selection.ts b/products/desktop/packages/core/src/sidebar/selection.tsindex 28db2431b852..4f24c0440d27 100644--- a/products/desktop/packages/core/src/sidebar/selection.ts+++ b/products/desktop/packages/core/src/sidebar/selection.ts@@ -59,6 +59,14 @@ export function dedupeTaskIds(taskIds: string[]): string[] {return Array.from(new Set(taskIds));}+/** Same ids in the same order, so a rewrite of an unchanged selection is a no-op. */+export function sameTaskIds(+ a: readonly string[],+ b: readonly string[],+): boolean {+ return a.length === b.length && a.every((id, i) => id === b[i]);+}+export function pruneToVisible(selectedTaskIds: string[],visibleTaskIds: string[],@@ -69,35 +77,94 @@ export function pruneToVisible(export interface PriorTask {id: string;- createdAt: number;+ lastActivityAt: number;}+/** Ids that went quiet before the clicked one, i.e. what "archive prior" covers. */export function computePriorTaskIds(allVisible: PriorTask[],clickedId: string,): string[] {const clicked = allVisible.find((task) => task.id === clickedId);if (!clicked) return [];- const threshold = clicked.createdAt;+ const threshold = clicked.lastActivityAt;return allVisible- .filter((task) => task.id !== clickedId && task.createdAt < threshold)+ .filter((task) => task.id !== clickedId && task.lastActivityAt < threshold).map((task) => task.id);}-export function formatArchiveResult(result: {- archived: number;+/**+ * Which way a bulk pin should go. Pinning wins a mixed selection so the result+ * is predictable — flipping each session independently would leave the group+ * split across the pinned and unpinned sections.+ */+export function computeBulkPinDirection(+ selectedTaskIds: string[],+ pinnedTaskIds: ReadonlySet<string>,+): "pin" | "unpin" {+ if (selectedTaskIds.length === 0) return "pin";+ return selectedTaskIds.every((id) => pinnedTaskIds.has(id)) ? "unpin" : "pin";+}++export function sessionsLabel(count: number): string {+ return `${count} ${count === 1 ? "session" : "sessions"}`;+}++/**+ * What archiving a selection costs beyond the archive itself. Shared so the+ * action bar's dialog and the native right-click confirm can't drift.+ */+export function formatBulkArchiveWarning(counts: {+ running: number;+ stopsCloudSandbox: boolean;+}): string {+ const parts = ["You can unarchive them later."];+ if (counts.running > 0) {+ parts.push(+ `${counts.running} of them ${counts.running === 1 ? "is" : "are"} still running and will be stopped.`,+ );+ }+ if (counts.stopsCloudSandbox) {+ parts.push("Any cloud sandbox in the selection shuts down too.");+ }+ return parts.join(" ");+}++/** Past-tense verb naming what a bulk action did, for its result toast. */+export type BulkResultKind =+ | "archived"+ | "pinned"+ | "unpinned"+ | "filed"+ | "added to Command Center";++export interface BulkResult {+ succeeded: number;failed: number;-}): { kind: "success" | "error"; message: string } {+}++export function formatBulkResult(+ kind: BulkResultKind,+ result: BulkResult,+): { kind: "success" | "error"; message: string } {if (result.failed === 0) {return {kind: "success",- message: `${result.archived} ${- result.archived === 1 ? "task" : "tasks"- } archived`,+ message: `${sessionsLabel(result.succeeded)} ${kind}`,};}return {kind: "error",- message: `${result.archived} archived, ${result.failed} failed`,+ message: `${result.succeeded} ${kind}, ${result.failed} failed`,};}++export function formatArchiveResult(result: {+ archived: number;+ failed: number;+}): { kind: "success" | "error"; message: string } {+ return formatBulkResult("archived", {+ succeeded: result.archived,+ failed: result.failed,+ });+}diff --git a/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts b/products/desktop/packages/core/src/tasks/contextMenuActions.test.tsindex 9e06ca86fec2..3ef8773661b8 100644--- a/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts+++ b/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";import {+ resolveBulkTaskContextMenuIntent,resolveExternalAppPath,resolveTaskContextMenuIntent,} from "./contextMenuActions";@@ -45,6 +46,39 @@ describe("resolveTaskContextMenuIntent", () => {});});+describe("resolveBulkTaskContextMenuIntent", () => {+ it.each([+ { allPinned: true, expected: "unpin" },+ { allPinned: false, expected: "pin" },+ { allPinned: undefined, expected: "pin" },+ ])(+ "maps pin to $expected when allPinned=$allPinned",+ ({ allPinned, expected }) => {+ expect(+ resolveBulkTaskContextMenuIntent({ type: "pin" }, { allPinned }),+ ).toEqual({ type: expected });+ },+ );++ it("passes through simple actions", () => {+ expect(resolveBulkTaskContextMenuIntent({ type: "archive" }, {})).toEqual({+ type: "archive",+ });+ expect(+ resolveBulkTaskContextMenuIntent({ type: "add-to-command-center" }, {}),+ ).toEqual({ type: "add-to-command-center" });+ });++ it("carries the channel id", () => {+ expect(+ resolveBulkTaskContextMenuIntent(+ { type: "file-to-channel", channelId: "c1" },+ {},+ ),+ ).toEqual({ type: "file-to-channel", channelId: "c1" });+ });+});+describe("resolveExternalAppPath", () => {it("prefers the worktree path", () => {expect(resolveExternalAppPath("/wt", "/folder")).toBe("/wt");diff --git a/products/desktop/packages/core/src/tasks/contextMenuActions.ts b/products/desktop/packages/core/src/tasks/contextMenuActions.tsindex a9d12056eaa5..dd4280397f19 100644--- a/products/desktop/packages/core/src/tasks/contextMenuActions.ts+++ b/products/desktop/packages/core/src/tasks/contextMenuActions.ts@@ -1,4 +1,5 @@import type {+ BulkTaskAction,ExternalAppAction,TaskAction,} from "@posthog/core/context-menu/schemas";@@ -44,6 +45,29 @@ export function resolveTaskContextMenuIntent(}}+export type BulkTaskContextMenuIntent =+ | { type: "archive" }+ | { type: "pin" }+ | { type: "unpin" }+ | { type: "add-to-command-center" }+ | { type: "file-to-channel"; channelId: string };++export function resolveBulkTaskContextMenuIntent(+ action: BulkTaskAction,+ flags: { allPinned?: boolean },+): BulkTaskContextMenuIntent {+ switch (action.type) {+ case "archive":+ return { type: "archive" };+ case "pin":+ return flags.allPinned ? { type: "unpin" } : { type: "pin" };+ case "add-to-command-center":+ return { type: "add-to-command-center" };+ case "file-to-channel":+ return { type: "file-to-channel", channelId: action.channelId };+ }+}+export function resolveExternalAppPath(worktreePath: string | undefined,folderPath: string | undefined,diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsxindex 57fbb9ae604e..4def1ad4702b 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx@@ -36,6 +36,7 @@ import {taskDot,} from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";import { SidebarItem } from "@posthog/ui/features/sidebar/components/SidebarItem";+import { SESSION_ROW_ATTRIBUTE } from "@posthog/ui/features/sidebar/useMarqueeSelection";import { type DragEvent, type ReactNode, useCallback, useState } from "react";/**@@ -133,8 +134,10 @@ export function ChannelItemRow({item,channelId,isActive,+ isSelected = false,actions,isEditing = false,+ onClick,showPinBadge = true,onRename,onAddToCommandCenter,@@ -145,8 +148,12 @@ export function ChannelItemRow({/** The space this row is listed under, ticked in the menu's "File to…". */channelId?: string;isActive: boolean;+ /** Part of a multi-session selection, so the row shows as picked. */+ isSelected?: boolean;actions: ChannelItemActions;isEditing?: boolean;+ /** Takes over the row's click, e.g. to modifier-click a selection. Falls back to opening it. */+ onClick?: (e: React.MouseEvent) => void;/** False under a "Pinned" header, which says it for every row beneath it. */showPinBadge?: boolean;/** Puts the row into inline-rename mode. Absent for canvases. */@@ -229,9 +236,13 @@ export function ChannelItemRow({// A non-string label opts out of SidebarItem's truncation tooltip.label={<span>{item.title}</span>}isActive={isActive}+ isSelected={isSelected}+ // Lets a drag-selection find the row and its session; canvases are not+ // selectable, so they stay unmarked and the marquee passes over them.+ {...(item.kind === "task" ? { [SESSION_ROW_ATTRIBUTE]: item.id } : {})}draggable={item.kind === "task"}onDragStart={handleDragStart}- onClick={() => actions.open(item)}+ onClick={(e) => (onClick ? onClick(e) : actions.open(item))}endContent={<span className={TRAILING_CLASS}>{/* Badges take the timestamp's slot on a task row: the row'sdiff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsxindex 49361c6e5ed5..ce7d47935bd3 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx@@ -8,12 +8,13 @@ const mocks = vi.hoisted(() => ({items: [] as ChannelItemModel[],isLoading: false,channelMissing: false,+ open: vi.fn(),}));vi.mock("@posthog/ui/features/canvas/hooks/useChannelItems", () => ({useChannelItems: () => ({items: mocks.items,- actions: { open: vi.fn(), togglePin: vi.fn(), archive: vi.fn() },+ actions: { open: mocks.open, togglePin: vi.fn(), archive: vi.fn() },me: { uuid: "me-uuid" },isLoading: mocks.isLoading,channelMissing: mocks.channelMissing,@@ -52,7 +53,16 @@ vi.mock("@posthog/ui/features/tasks/useTasks", () => ({vi.mock("@posthog/ui/features/canvas/hooks/useChannelTaskStatus", () => ({useChannelTaskStatus: () => null,}));+// The bulk bar's actions span the archive, pin, and filing query stacks. What+// the bar does has its own suites; this one is about the list's own states.+vi.mock("@posthog/ui/features/sidebar/useSidebarBulkActions", () => ({+ useSidebarBulkActions: () => ({ selectedCount: 0 }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useChannelTasksRunState", () => ({+ useChannelTasksRunState: () => [],+}));+import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";import { ChannelSidebar } from "./ChannelSidebar";function item(overrides: Partial<ChannelItemModel> = {}): ChannelItemModel {@@ -324,3 +334,87 @@ describe("ChannelSidebar recents list", () => {expect(screen.queryByRole("img", { name: "Pinned" })).toBeNull();});});++describe("ChannelSidebar multi-select", () => {+ beforeEach(() => {+ mocks.isLoading = false;+ mocks.channelMissing = false;+ mocks.open.mockClear();+ useTaskSelectionStore.setState({+ selectedTaskIds: [],+ lastClickedId: null,+ });+ mocks.items = [+ item({ key: "task:a", id: "a", title: "First session" }),+ item({ key: "task:b", id: "b", title: "Second session" }),+ item({ key: "canvas:c", kind: "canvas", id: "c", title: "A canvas" }),+ ];+ });++ it("opens a session on a plain click", async () => {+ const user = userEvent.setup();+ renderSidebar();++ await user.click(screen.getByText("First session"));++ expect(mocks.open).toHaveBeenCalledOnce();+ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual([]);+ });++ it.each([+ { name: "meta", modifier: "{Meta>}" },+ { name: "ctrl", modifier: "{Control>}" },+ ])("selects rather than opens on $name-click", async ({ modifier }) => {+ const user = userEvent.setup();+ renderSidebar();++ await user.keyboard(modifier);+ await user.click(screen.getByText("First session"));++ expect(mocks.open).not.toHaveBeenCalled();+ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual(["a"]);+ });++ it("selects a range on shift-click", async () => {+ const user = userEvent.setup();+ renderSidebar();++ await user.keyboard("{Meta>}");+ await user.click(screen.getByText("First session"));+ await user.keyboard("{/Meta}{Shift>}");+ await user.click(screen.getByText("Second session"));++ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual([+ "a",+ "b",+ ]);+ });++ // A canvas can't be archived, filed, or tiled like a session, so it stays out+ // of the selection and modifier-clicking one just opens it.+ it("opens a canvas even on a modifier-click", async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ renderSidebar();++ // Canvases are their own tab, so the row has to be brought into view first.+ await user.click(screen.getByRole("tab", { name: "Canvases" }));+ await user.keyboard("{Meta>}");+ await user.click(screen.getByText("A canvas"));++ expect(mocks.open).toHaveBeenCalledOnce();+ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual([]);+ });++ it("drops ids that leave the list", async () => {+ const user = userEvent.setup();+ const { rerender } = renderSidebar();+ await user.keyboard("{Meta>}");+ await user.click(screen.getByText("Second session"));+ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual(["b"]);++ mocks.items = [item({ key: "task:a", id: "a", title: "First session" })];+ rerender(sidebar());++ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual([]);+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsxindex fcb1a34c7861..232a01a16847 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx@@ -18,6 +18,7 @@ import {PINNED_SECTION_KEY,sortChannelItems,} from "@posthog/core/canvas/channelItems";+import { computeEffectiveBulkIds } from "@posthog/core/sidebar/selection";import {Button,Empty,@@ -34,6 +35,7 @@ import {TabsTrigger,} from "@posthog/quill";import { LOOPS_FLAG } from "@posthog/shared";+import type { Task } from "@posthog/shared/domain-types";import { ChannelBackRow } from "@posthog/ui/features/canvas/components/ChannelBackRow";import { ChannelFilterMenu } from "@posthog/ui/features/canvas/components/ChannelFilterMenu";import { ChannelItemRow } from "@posthog/ui/features/canvas/components/ChannelItemRow";@@ -45,6 +47,7 @@ import {} from "@posthog/ui/features/canvas/components/channelPages";import { useChannelItems } from "@posthog/ui/features/canvas/hooks/useChannelItems";import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";+import { useChannelTasksRunState } from "@posthog/ui/features/canvas/hooks/useChannelTasksRunState";import { useLocalDayStart } from "@posthog/ui/features/canvas/hooks/useLocalDayStart";import { PERSONAL_CHANNEL_NAME } from "@posthog/ui/features/canvas/hooks/useTaskChannels";import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";@@ -52,11 +55,17 @@ import { useCommandCenterStore } from "@posthog/ui/features/command-center/commaimport { placeTaskInCommandCenter } from "@posthog/ui/features/command-center/placeTaskInCommandCenter";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { SidebarKbdHint } from "@posthog/ui/features/sidebar/components/items/SidebarKbdHint";+import { MarqueeOverlay } from "@posthog/ui/features/sidebar/components/MarqueeOverlay";+import { SidebarBulkActionFooter } from "@posthog/ui/features/sidebar/components/SidebarBulkActionFooter";import { SidebarItem } from "@posthog/ui/features/sidebar/components/SidebarItem";+import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";+import { useClearSelectionOnEscape } from "@posthog/ui/features/sidebar/useClearSelectionOnEscape";+import { useMarqueeSelection } from "@posthog/ui/features/sidebar/useMarqueeSelection";+import { useSidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";import { useRenameTask } from "@posthog/ui/features/tasks/useTaskMutations";import { logger } from "@posthog/ui/shell/logger";import { useNavigate, useRouterState } from "@tanstack/react-router";-import { Fragment, useMemo, useState } from "react";+import { Fragment, useEffect, useMemo, useRef, useState } from "react";const RECENTS_CAP = 30;const log = logger.scope("channel-sidebar");@@ -367,6 +376,72 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {// emptied it — and while a tab is empty, so you can leave that tab.const showHeader = listState === "ready" || listState === "empty";+ // Only sessions take part in a bulk selection: a canvas can't be archived,+ // filed, or tiled the way a session can, so modifier-clicking one just opens it.+ const selectableTaskIds = useMemo(+ () => recentItems.filter((i) => i.kind === "task").map((i) => i.id),+ [recentItems],+ );+ const selectedTaskIds = useTaskSelectionStore((s) => s.selectedTaskIds);+ const toggleTaskSelection = useTaskSelectionStore(+ (s) => s.toggleTaskSelection,+ );+ const selectRange = useTaskSelectionStore((s) => s.selectRange);+ const clearSelection = useTaskSelectionStore((s) => s.clearSelection);+ const pruneSelection = useTaskSelectionStore((s) => s.pruneSelection);+ useClearSelectionOnEscape();+ const listAnchorRef = useRef<HTMLDivElement | null>(null);+ const marquee = useMarqueeSelection(listAnchorRef);++ useEffect(() => {+ pruneSelection(selectableTaskIds);+ }, [selectableTaskIds, pruneSelection]);++ // The open session counts as selected, the same way it does in the code+ // sidebar — a bulk action is expected to include what you're looking at. Only+ // a task-kind active row folds in; a canvas can't join a session selection.+ const activeTaskId = activeKey?.startsWith("task:")+ ? activeKey.slice("task:".length)+ : null;+ const effectiveBulkIds = useMemo(+ () => computeEffectiveBulkIds(selectedTaskIds, activeTaskId),+ [selectedTaskIds, activeTaskId],+ );++ const selectedTasks = useMemo(() => {+ const selected = new Set(effectiveBulkIds);+ return recentItems+ .filter(+ (i): i is ChannelItemModel & { task: Task } =>+ i.kind === "task" && i.task !== null && selected.has(i.id),+ )+ .map((i) => i.task);+ }, [recentItems, effectiveBulkIds]);+ const selectedTasksRunState = useChannelTasksRunState(selectedTasks);+ const bulkActions = useSidebarBulkActions(+ effectiveBulkIds,+ selectedTasksRunState,+ );++ const handleRowClick = (item: ChannelItemModel, e: React.MouseEvent) => {+ if (item.kind !== "task") {+ actions.open(item);+ return;+ }+ if (e.shiftKey) {+ e.preventDefault();+ selectRange(item.id, selectableTaskIds, activeTaskId);+ return;+ }+ if (e.metaKey || e.ctrlKey) {+ e.preventDefault();+ toggleTaskSelection(item.id);+ return;+ }+ clearSelection();+ actions.open(item);+ };+const commandCenterAssigner = (taskId: string, taskTitle: string) => () =>placeTaskInCommandCenter(taskId, taskTitle);@@ -376,8 +451,10 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {item={item}channelId={channelId}isActive={item.key === activeKey}+ isSelected={item.kind === "task" && effectiveBulkIds.includes(item.id)}showPinBadge={showPinBadge}actions={actions}+ onClick={(e) => handleRowClick(item, e)}isEditing={item.kind === "task" && editingTaskId === item.id}onRename={item.kind === "task" ? () => setEditingTaskId(item.id) : undefined@@ -484,10 +561,14 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {)}</div>- {/* Relative so the FAB can float over the list. The tabs sit above the- scroll container rather than in it: they are how you leave whatever- the list is showing, so they can't scroll away with it. */}- <div className="relative mt-2 flex min-h-0 flex-1 flex-col">+ {/* Relative so the FAB and the drag-selection band can float over the+ list. The tabs sit above the scroll container rather than in it: they+ are how you leave whatever the list is showing, so they can't scroll+ away with it. */}+ <div+ ref={listAnchorRef}+ className="relative mt-2 flex min-h-0 flex-1 flex-col"+ >{showHeader && (<div className="border-border border-b px-2"><RecentSectionHeader@@ -575,7 +656,15 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {))}</div><ChannelsFab channelId={channelId} />+ <MarqueeOverlay rect={marquee} /></div>++ {/* Below the list rather than floating over it: the bottom rows are where+ a shift-click range usually ends, and the FAB already sits there. */}+ <SidebarBulkActionFooter+ actions={bulkActions}+ onClearSelection={clearSelection}+ /></div>);}diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasksRunState.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasksRunState.tsnew file mode 100644index 000000000000..7473d69ce65a--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasksRunState.ts@@ -0,0 +1,29 @@+import {+ deriveTaskRunState,+ narrowFullTask,+ type TaskSession,+} from "@posthog/core/sidebar/buildSidebarData";+import type { Task } from "@posthog/shared/domain-types";+import type { BulkSessionInfo } from "@posthog/ui/features/sidebar/useSidebarBulkActions";+import { useSidebarSessionMap } from "@posthog/ui/features/sidebar/useSidebarSessionMap";+import { useMemo } from "react";++/**+ * Run state for a list of sessions — enough for a bulk action to know what+ * archiving would stop. Deliberately not the full `TaskData`: that would pull in+ * the workspace and pin queries for a warning sentence.+ */+export function useChannelTasksRunState(tasks: Task[]): BulkSessionInfo[] {+ const sessions = useSidebarSessionMap();++ return useMemo(+ () =>+ tasks.map((task) =>+ deriveTaskRunState(+ narrowFullTask(task),+ sessions.get(task.id) as TaskSession | undefined,+ ),+ ),+ [tasks, sessions],+ );+}diff --git a/products/desktop/packages/ui/src/features/command-center/commandCenterStore.test.ts b/products/desktop/packages/ui/src/features/command-center/commandCenterStore.test.tsindex 8b28a62ba279..9255c67b2980 100644--- a/products/desktop/packages/ui/src/features/command-center/commandCenterStore.test.ts+++ b/products/desktop/packages/ui/src/features/command-center/commandCenterStore.test.ts@@ -181,6 +181,67 @@ describe("commandCenterStore", () => {});});+ // The write every bulk placement lands through. The plan itself is covered by+ // placement.test.ts; what's here is the reconciliation only this write does.+ describe("applyPlacement", () => {+ it("follows the active task to its new index when the grid grows", () => {+ useCommandCenterStore.setState({+ layout: "2x2",+ cells: ["a", "b", "c", null],+ activeTaskId: "c",+ activeCellIndex: 2,+ });++ useCommandCenterStore.getState().applyPlacement({+ layout: "3x2",+ cells: ["a", "b", "d", "c", "e", "f"],+ });++ const state = useCommandCenterStore.getState();+ expect(state.layout).toBe("3x2");+ expect(state.activeTaskId).toBe("c");+ expect(state.activeCellIndex).toBe(3);+ });++ it("drops the active task when the placement left it off the grid", () => {+ useCommandCenterStore.setState({+ cells: ["a", null, null, null],+ activeTaskId: "a",+ activeCellIndex: 0,+ });++ useCommandCenterStore+ .getState()+ .applyPlacement({ layout: "2x2", cells: ["b", null, null, null] });++ const state = useCommandCenterStore.getState();+ expect(state.activeTaskId).toBeNull();+ expect(state.activeCellIndex).toBe(0);+ });++ // Otherwise a "creating" spinner sits on a tile that now holds a session.+ it("stops marking a filled cell as creating", () => {+ useCommandCenterStore.setState({+ cells: [null, null, null, null],+ creatingCells: [1, 2],+ });++ useCommandCenterStore+ .getState()+ .applyPlacement({ layout: "2x2", cells: [null, "a", null, null] });++ expect(useCommandCenterStore.getState().creatingCells).toEqual([2]);+ });++ it("marks the grid curated so autofill can't stuff it later", () => {+ useCommandCenterStore+ .getState()+ .applyPlacement({ layout: "2x2", cells: ["a", null, null, null] });++ expect(useCommandCenterStore.getState().hasAutofilled).toBe(true);+ });+ });+describe("pending placement", () => {it("keeps the requested task available until placement is canceled", () => {useCommandCenterStore.getState().requestPlacement("t1", "Fix signup");diff --git a/products/desktop/packages/ui/src/features/command-center/commandCenterStore.ts b/products/desktop/packages/ui/src/features/command-center/commandCenterStore.tsindex 137d66953023..d358a924f986 100644--- a/products/desktop/packages/ui/src/features/command-center/commandCenterStore.ts+++ b/products/desktop/packages/ui/src/features/command-center/commandCenterStore.ts@@ -42,6 +42,11 @@ interface CommandCenterStoreActions {terminalId: string,cwd?: string,) => void;+ /** Adopt a whole placement plan in one write — see `planCommandCenterPlacement`. */+ applyPlacement: (plan: {+ layout: LayoutPreset;+ cells: (string | null)[];+ }) => void;autofillCells: (taskIds: string[]) => void;optimizeLayout: (keepIndices: number[]) => void;clearCell: (cellIndex: number) => void;@@ -151,6 +156,35 @@ export const useCommandCenterStore = create<CommandCenterStore>()(};}),+ applyPlacement: ({ layout, cells }) =>+ set((state) => {+ const activeTaskId =+ state.activeTaskId && cells.includes(state.activeTaskId)+ ? state.activeTaskId+ : null;+ return {+ layout,+ cells,+ activeTaskId,+ // Follows the active task to its new index; with none (a terminal or+ // brainrot tile is focused) the existing highlight stays put, as in+ // setLayout, so long as it's still within bounds.+ activeCellIndex: activeTaskId+ ? cells.indexOf(activeTaskId)+ : state.activeCellIndex !== null &&+ state.activeCellIndex < cells.length+ ? state.activeCellIndex+ : null,+ creatingCells: state.creatingCells.filter(+ (i) => i < cells.length && cells[i] == null,+ ),+ // A bulk placement is the user curating the grid, so the one-shot+ // autofill must not later stuff tiles behind their back.+ hasAutofilled: true,+ pendingPlacement: null,+ };+ }),+autofillCells: (taskIds) =>set((state) => {// Grid already full: nothing to place, but the bootstrap is done.diff --git a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.tsindex b5dac10483c4..0e3101525885 100644--- a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts+++ b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts@@ -3,6 +3,7 @@ import {getExpandedLayout,getExpansionCellIndex,} from "@posthog/core/command-center/grid";+import { planCommandCenterPlacement } from "@posthog/core/command-center/placement";import { navigateToCommandCenter } from "@posthog/ui/router/navigationBridge";import { useCommandCenterStore } from "./commandCenterStore";@@ -19,6 +20,41 @@ export function placeTaskInCommandCenter(navigateToCommandCenter();}+export interface BulkPlacementResult {+ placed: number;+ overflow: number;+ alreadyPresent: number;+}++/**+ * Tiles a whole selection at once. Unlike the single-task flow there is no+ * picker — asking for a slot per session doesn't scale — so it navigates to the+ * grid instead, where a batch that had to grow the layout is self-evident.+ */+export function placeTasksInCommandCenter(+ taskIds: string[],+ liveTaskIds: ReadonlySet<string> | null,+): BulkPlacementResult {+ const state = useCommandCenterStore.getState();+ const plan = planCommandCenterPlacement({+ cells: state.cells,+ layout: state.layout,+ taskIds,+ liveTaskIds,+ });++ if (plan.placed.length > 0) {+ state.applyPlacement({ layout: plan.layout, cells: plan.cells });+ }+ navigateToCommandCenter();++ return {+ placed: plan.placed.length,+ overflow: plan.overflow.length,+ alreadyPresent: plan.alreadyPresent.length,+ };+}+/** Grows the grid by one column or row and puts the task in the slot picked. */export function expandCommandCenterInto(direction: ExpandDirection,diff --git a/products/desktop/packages/ui/src/features/sidebar/components/BulkArchiveConfirmDialog.tsx b/products/desktop/packages/ui/src/features/sidebar/components/BulkArchiveConfirmDialog.tsxnew file mode 100644index 000000000000..c52d85db3e04--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/BulkArchiveConfirmDialog.tsx@@ -0,0 +1,77 @@+import {+ formatBulkArchiveWarning,+ sessionsLabel,+} from "@posthog/core/sidebar/selection";+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Button,+} from "@posthog/quill";+import type { ReactElement } from "react";++interface BulkArchiveConfirmDialogProps {+ open: boolean;+ sessionCount: number;+ /** How many of the selection are still running, so archiving stops them. */+ runningCount: number;+ stopsCloudSandbox: boolean;+ isArchiving: boolean;+ onConfirm: () => void;+ onCancel: () => void;+}++/**+ * One confirm for a whole batch. The single-row `ArchiveRunningTaskDialog`+ * covers one session at a time; prompting per session would mean N dialogs.+ */+export function BulkArchiveConfirmDialog({+ open,+ sessionCount,+ runningCount,+ stopsCloudSandbox,+ isArchiving,+ onConfirm,+ onCancel,+}: BulkArchiveConfirmDialogProps): ReactElement {+ return (+ <AlertDialog+ open={open}+ // Escape is guarded the way the Cancel button is. Dismissing mid-archive+ // would take the progress away while the batch is still finishing.+ onOpenChange={(next) => {+ if (!next && !isArchiving) onCancel();+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ Archive {sessionsLabel(sessionCount)}?+ </AlertDialogTitle>+ <AlertDialogDescription>+ {formatBulkArchiveWarning({+ running: runningCount,+ stopsCloudSandbox,+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <Button variant="outline" onClick={onCancel} disabled={isArchiving}>+ Cancel+ </Button>+ <Button+ variant="primary"+ onClick={onConfirm}+ loading={isArchiving}+ disabled={isArchiving}+ >+ Archive+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/MarqueeOverlay.tsx b/products/desktop/packages/ui/src/features/sidebar/components/MarqueeOverlay.tsxnew file mode 100644index 000000000000..2e98304d4f6f--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/MarqueeOverlay.tsx@@ -0,0 +1,21 @@+import type { MarqueeRect } from "@posthog/ui/features/sidebar/useMarqueeSelection";+import type { ReactElement } from "react";++/**+ * The band a drag-selection sweeps. Spans the list's full width because the+ * marquee only measures vertically — see `rowsInMarquee`.+ */+export function MarqueeOverlay({+ rect,+}: {+ rect: MarqueeRect | null;+}): ReactElement | null {+ if (!rect) return null;+ return (+ <div+ aria-hidden+ className="pointer-events-none absolute inset-x-0 z-10 border-(--accent-8) border-y bg-(--accent-a4)"+ style={{ top: rect.top, height: rect.height }}+ />+ );+}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.test.tsxnew file mode 100644index 000000000000..821708ada87e--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.test.tsx@@ -0,0 +1,110 @@+import type { SidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";+import { render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { SidebarBulkActionBar } from "./SidebarBulkActionBar";++if (typeof globalThis.ResizeObserver === "undefined") {+ globalThis.ResizeObserver = class {+ observe() {}+ unobserve() {}+ disconnect() {}+ } as unknown as typeof ResizeObserver;+}++function makeActions(+ overrides: Partial<SidebarBulkActions> = {},+): SidebarBulkActions {+ return {+ selectedCount: 3,+ runningCount: 0,+ stopsCloudSandbox: false,+ pinDirection: "pin",+ pinLabel: "Pin 3 sessions",+ channels: [+ { id: "c1", name: "support", channelType: "public", starred: false },+ ],+ archiveSelected: vi.fn(),+ pinSelected: vi.fn(),+ addSelectedToCommandCenter: vi.fn(),+ fileSelectedTo: vi.fn(),+ archiveDisabledReason: null,+ pinDisabledReason: null,+ commandCenterDisabledReason: null,+ fileDisabledReason: null,+ isArchiving: false,+ isPinning: false,+ isFiling: false,+ ...overrides,+ };+}++function renderBar(overrides: Partial<SidebarBulkActions> = {}) {+ return render(+ <SidebarBulkActionBar+ actions={makeActions(overrides)}+ onClearSelection={vi.fn()}+ onArchive={vi.fn()}+ />,+ );+}++describe("SidebarBulkActionBar", () => {+ it("shows no bar with an empty selection", () => {+ renderBar({ selectedCount: 0 });++ expect(screen.queryByLabelText(/^Archive/)).not.toBeInTheDocument();+ expect(screen.queryByText(/selected$/)).not.toBeInTheDocument();+ });++ // The count is the only announcement of a selection, and a live region has to+ // predate its own text to be read out, so it outlives the bar it describes.+ it("keeps a live region across the selection appearing", () => {+ const { container, rerender } = renderBar({ selectedCount: 0 });+ const region = container.querySelector("[aria-live=polite]");+ expect(region).toHaveTextContent("");++ rerender(+ <SidebarBulkActionBar+ actions={makeActions({ selectedCount: 2 })}+ onClearSelection={vi.fn()}+ onArchive={vi.fn()}+ />,+ );++ expect(container.querySelector("[aria-live=polite]")).toBe(region);+ expect(region).toHaveTextContent("2 sessions selected");+ });++ it("shows the selected count and the actions", () => {+ renderBar();++ expect(screen.getByText("3 selected")).toBeInTheDocument();+ expect(screen.getByLabelText("Pin 3 sessions")).toBeInTheDocument();+ expect(screen.getByLabelText("Archive 3 sessions")).toBeInTheDocument();+ expect(+ screen.getByLabelText("Add 3 sessions to Command Center"),+ ).toBeInTheDocument();+ });++ it("shows the unpin label when the selection is all pinned", () => {+ renderBar({ pinDirection: "unpin", pinLabel: "Unpin 3 sessions" });++ expect(screen.getByLabelText("Unpin 3 sessions")).toBeInTheDocument();+ expect(screen.queryByLabelText("Pin 3 sessions")).not.toBeInTheDocument();+ });++ it("hides File to when the action is unavailable", () => {+ renderBar({ channels: [], fileDisabledReason: "there are no channels" });++ expect(+ screen.queryByLabelText("File 3 sessions to a channel"),+ ).not.toBeInTheDocument();+ });++ it("singularizes the labels for one session", () => {+ renderBar({ selectedCount: 1, pinLabel: "Pin 1 session" });++ expect(screen.getByText("1 selected")).toBeInTheDocument();+ expect(screen.getByLabelText("Archive 1 session")).toBeInTheDocument();+ });+});diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.tsxnew file mode 100644index 000000000000..3fae30847a91--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.tsx@@ -0,0 +1,183 @@+import {+ ArchiveIcon,+ FolderOpenIcon,+ PushPinIcon,+ PushPinSlashIcon,+ SquaresFourIcon,+ XIcon,+} from "@phosphor-icons/react";+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@posthog/quill";+import type { SidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";+import type { ReactElement, ReactNode } from "react";++interface SidebarBulkActionBarProps {+ actions: SidebarBulkActions;+ onClearSelection: () => void;+ onArchive: () => void;+}++/**+ * The sidebar is narrow and user-resizable, so the actions are icon buttons+ * with their full label in the tooltip rather than the labelled buttons the+ * inbox bar can afford.+ */+function ActionButton({+ label,+ disabledReason,+ loading,+ onClick,+ wrapTrigger,+ children,+}: {+ label: string;+ disabledReason: string | null;+ loading?: boolean;+ /** Absent when `wrapTrigger` supplies the behaviour, as a menu trigger does. */+ onClick?: () => void;+ /** Wraps the button before the tooltip does, e.g. to open a menu from it. */+ wrapTrigger?: (button: ReactElement) => ReactElement;+ children: ReactNode;+}): ReactElement {+ const disabled = disabledReason !== null || Boolean(loading);+ const button = (+ <Button+ type="button"+ size="icon-sm"+ variant="default"+ aria-label={label}+ disabled={disabled}+ loading={loading}+ onClick={onClick}+ >+ {children}+ </Button>+ );+ return (+ <Tooltip>+ <TooltipTrigger render={wrapTrigger ? wrapTrigger(button) : button} />+ <TooltipContent side="top">+ {disabledReason ? `Disabled because ${disabledReason}.` : label}+ </TooltipContent>+ </Tooltip>+ );+}++export function SidebarBulkActionBar({+ actions,+ onClearSelection,+ onArchive,+}: SidebarBulkActionBarProps): ReactElement {+ const {+ selectedCount,+ pinDirection,+ pinLabel,+ channels,+ archiveDisabledReason,+ pinDisabledReason,+ commandCenterDisabledReason,+ fileDisabledReason,+ isArchiving,+ isPinning,+ isFiling,+ } = actions;++ const sessions = selectedCount === 1 ? "session" : "sessions";++ return (+ <>+ {/* The bar is the only sign a selection exists, and it unmounts at zero.+ A live region announces reliably only if it was in the DOM before its+ text arrived, so this one sits outside the bar and outlives it. */}+ <span aria-live="polite" className="sr-only">+ {selectedCount > 0 ? `${selectedCount} ${sessions} selected` : ""}+ </span>++ {selectedCount > 0 && (+ <div className="flex items-center justify-between gap-2 border-(--gray-5) border-t bg-(--gray-2) px-2 py-1.5">+ <div className="flex min-w-0 items-center gap-1">+ <span className="shrink-0 font-medium text-(--gray-12) text-[12px]">+ {selectedCount} selected+ </span>+ <span className="truncate text-(--gray-10) text-[11px]">+ Esc to clear+ </span>+ </div>++ <div className="flex shrink-0 items-center gap-0.5">+ <ActionButton+ label={pinLabel}+ disabledReason={pinDisabledReason}+ loading={isPinning}+ onClick={actions.pinSelected}+ >+ {pinDirection === "pin" ? (+ <PushPinIcon size={13} />+ ) : (+ <PushPinSlashIcon size={13} />+ )}+ </ActionButton>++ <ActionButton+ label={`Add ${selectedCount} ${sessions} to Command Center`}+ disabledReason={commandCenterDisabledReason}+ onClick={actions.addSelectedToCommandCenter}+ >+ <SquaresFourIcon size={13} />+ </ActionButton>++ {fileDisabledReason === null ? (+ <DropdownMenu>+ <ActionButton+ label={`File ${selectedCount} ${sessions} to a channel`}+ disabledReason={null}+ loading={isFiling}+ wrapTrigger={(button) => (+ <DropdownMenuTrigger render={button} />+ )}+ >+ <FolderOpenIcon size={13} />+ </ActionButton>+ <DropdownMenuContent align="end">+ {channels.map((channel) => (+ <DropdownMenuItem+ key={channel.id}+ onClick={() => void actions.fileSelectedTo(channel.id)}+ >+ {`#${channel.name}`}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ ) : null}++ <ActionButton+ label={`Archive ${selectedCount} ${sessions}`}+ disabledReason={archiveDisabledReason}+ loading={isArchiving}+ onClick={onArchive}+ >+ <ArchiveIcon size={13} />+ </ActionButton>++ <ActionButton+ label="Clear selection"+ disabledReason={null}+ onClick={onClearSelection}+ >+ <XIcon size={13} />+ </ActionButton>+ </div>+ </div>+ )}+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.test.tsxnew file mode 100644index 000000000000..da2f3922c3fc--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.test.tsx@@ -0,0 +1,102 @@+import type { SidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { SidebarBulkActionFooter } from "./SidebarBulkActionFooter";++if (typeof globalThis.ResizeObserver === "undefined") {+ globalThis.ResizeObserver = class {+ observe() {}+ unobserve() {}+ disconnect() {}+ } as unknown as typeof ResizeObserver;+}++function makeActions(+ overrides: Partial<SidebarBulkActions> = {},+): SidebarBulkActions {+ return {+ selectedCount: 3,+ runningCount: 0,+ stopsCloudSandbox: false,+ pinDirection: "pin",+ pinLabel: "Pin 3 sessions",+ channels: [],+ archiveSelected: vi.fn().mockResolvedValue(undefined),+ pinSelected: vi.fn(),+ addSelectedToCommandCenter: vi.fn(),+ fileSelectedTo: vi.fn(),+ archiveDisabledReason: null,+ pinDisabledReason: null,+ commandCenterDisabledReason: null,+ fileDisabledReason: "this project has no channels to file to",+ isArchiving: false,+ isPinning: false,+ isFiling: false,+ ...overrides,+ };+}++describe("SidebarBulkActionFooter", () => {+ it("confirms before archiving rather than archiving on the click", async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ const actions = makeActions();+ render(+ <SidebarBulkActionFooter actions={actions} onClearSelection={vi.fn()} />,+ );++ await user.click(screen.getByLabelText("Archive 3 sessions"));++ expect(actions.archiveSelected).not.toHaveBeenCalled();+ expect(await screen.findByText("Archive 3 sessions?")).toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Archive" }));+ expect(actions.archiveSelected).toHaveBeenCalledOnce();+ });++ // Archiving clears the selection, so a dialog reading the count live would+ // retitle itself "Archive 0 sessions?" while it is still open.+ it("keeps the count it opened with after the selection empties", async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ const { rerender } = render(+ <SidebarBulkActionFooter+ actions={makeActions()}+ onClearSelection={vi.fn()}+ />,+ );++ await user.click(screen.getByLabelText("Archive 3 sessions"));+ expect(await screen.findByText("Archive 3 sessions?")).toBeInTheDocument();++ rerender(+ <SidebarBulkActionFooter+ actions={makeActions({ selectedCount: 0, isArchiving: true })}+ onClearSelection={vi.fn()}+ />,+ );++ expect(screen.getByText("Archive 3 sessions?")).toBeInTheDocument();+ });++ it("holds the dialog open when Escape lands mid-archive", async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ const { rerender } = render(+ <SidebarBulkActionFooter+ actions={makeActions()}+ onClearSelection={vi.fn()}+ />,+ );+ await user.click(screen.getByLabelText("Archive 3 sessions"));+ expect(await screen.findByText("Archive 3 sessions?")).toBeInTheDocument();++ rerender(+ <SidebarBulkActionFooter+ actions={makeActions({ isArchiving: true })}+ onClearSelection={vi.fn()}+ />,+ );+ await user.keyboard("{Escape}");++ expect(screen.getByText("Archive 3 sessions?")).toBeInTheDocument();+ });+});diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.tsxnew file mode 100644index 000000000000..379f17977715--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.tsx@@ -0,0 +1,57 @@+import { BulkArchiveConfirmDialog } from "@posthog/ui/features/sidebar/components/BulkArchiveConfirmDialog";+import { SidebarBulkActionBar } from "@posthog/ui/features/sidebar/components/SidebarBulkActionBar";+import type { SidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";+import { type ReactElement, useState } from "react";++/**+ * The bar and the archive confirm behind it, for whichever sidebar is showing+ * the session list. Both render this rather than their own copy, the same way+ * both share `useSidebarBulkActions`: a change to the confirm flow lands once.+ */+export function SidebarBulkActionFooter({+ actions,+ onClearSelection,+}: {+ actions: SidebarBulkActions;+ onClearSelection: () => void;+}): ReactElement {+ // Snapshotted rather than read live: archiving clears the selection, which+ // would otherwise retitle the still-open dialog "Archive 0 sessions?".+ const [confirm, setConfirm] = useState<{+ sessionCount: number;+ runningCount: number;+ stopsCloudSandbox: boolean;+ } | null>(null);++ return (+ <>+ <SidebarBulkActionBar+ actions={actions}+ onClearSelection={onClearSelection}+ // Always confirms. Bulk archive has no undo toast, and the running+ // count it would otherwise gate on covers only the sessions the sidebar+ // currently renders — the routed one folded into the batch may not be.+ onArchive={() =>+ setConfirm({+ sessionCount: actions.selectedCount,+ runningCount: actions.runningCount,+ stopsCloudSandbox: actions.stopsCloudSandbox,+ })+ }+ />++ <BulkArchiveConfirmDialog+ open={confirm !== null}+ sessionCount={confirm?.sessionCount ?? 0}+ runningCount={confirm?.runningCount ?? 0}+ stopsCloudSandbox={Boolean(confirm?.stopsCloudSandbox)}+ isArchiving={actions.isArchiving}+ onConfirm={async () => {+ await actions.archiveSelected();+ setConfirm(null);+ }}+ onCancel={() => setConfirm(null)}+ />+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsxindex 9611c3a45832..99a660cd2b08 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsx@@ -77,10 +77,15 @@ export function SidebarItem({className={cn("group flex w-full cursor-default text-left text-[13px] leading-snug transition-colors","disabled:opacity-100 data-active:bg-fill-selected data-selected:bg-(--gray-3)",+ // A bar on the leading edge rather than another background: the open+ // session already owns its background, and this lets it also say it is+ // part of a bulk selection.+ "relative data-in-selection:before:absolute data-in-selection:before:inset-y-0 data-in-selection:before:left-0 data-in-selection:before:w-0.5 data-in-selection:before:bg-(--accent-9) data-in-selection:before:content-['']",isDimmed && "opacity-50",)}data-active={isActive || undefined}data-selected={(isSelected && !isActive) || undefined}+ data-in-selection={isSelected || undefined}draggable={draggable}onDragStart={onDragStart}style={{diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsxindex 2186bcb80b95..26673bedbbcb 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx@@ -1,5 +1,12 @@import { findGroupFolder } from "@posthog/core/sidebar/groupTasks";+import {+ computeEffectiveBulkIds,+ computeOrderedVisibleTaskIds,+ computePriorTaskIds,+ formatArchiveResult,+} from "@posthog/core/sidebar/selection";import { isTaskActivelyRunning } from "@posthog/core/sidebar/taskRunning";+import { resolveBulkTaskContextMenuIntent } from "@posthog/core/tasks/contextMenuActions";import { useHostTRPCClient } from "@posthog/host-router/react";import type { Task } from "@posthog/shared/types";import {@@ -15,7 +22,10 @@ import { StopCloudRunDialog } from "@posthog/ui/features/sessions/components/Stoimport { useArchivingTasksStore } from "@posthog/ui/features/sidebar/archivingTasksStore";import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";+import { useClearSelectionOnEscape } from "@posthog/ui/features/sidebar/useClearSelectionOnEscape";+import { useMarqueeSelection } from "@posthog/ui/features/sidebar/useMarqueeSelection";import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";+import { useSidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";import { useSidebarData } from "@posthog/ui/features/sidebar/useSidebarData";import { useTaskViewed } from "@posthog/ui/features/sidebar/useTaskViewed";import { useTaskContextMenu } from "@posthog/ui/features/tasks/useTaskContextMenu";@@ -32,18 +42,13 @@ import { Box, Flex } from "@radix-ui/themes";import { useQueryClient } from "@tanstack/react-query";import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import { ArchiveRunningTaskDialog } from "./ArchiveRunningTaskDialog";+import { MarqueeOverlay } from "./MarqueeOverlay";+import { SidebarBulkActionFooter } from "./SidebarBulkActionFooter";import { SidebarItem } from "./SidebarItem";import { TaskListView } from "./TaskListView";const log = logger.scope("sidebar-menu");-function isEditableTarget(target: EventTarget | null): boolean {- if (!(target instanceof HTMLElement)) return false;- if (target.isContentEditable) return true;- const tag = target.tagName;- return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";-}-function SidebarMenuComponent() {const hostClient = useHostTRPCClient();const archiveCacheKeys = useArchiveCacheKeys();@@ -112,20 +117,9 @@ function SidebarMenuComponent() {runId?: string;} | null>(null);- // Escape clears any bulk task selection (moved here from the retired- // MainSidebar so it survives with the task list in the unified sidebar).- useEffect(() => {- const handler = (e: KeyboardEvent) => {- if (e.key !== "Escape") return;- if (isEditableTarget(e.target)) return;- const { selectedTaskIds, clearSelection } =- useTaskSelectionStore.getState();- if (selectedTaskIds.length === 0) return;- clearSelection();- };- window.addEventListener("keydown", handler);- return () => window.removeEventListener("keydown", handler);- }, []);+ useClearSelectionOnEscape();+ const listAnchorRef = useRef<HTMLDivElement | null>(null);+ const marquee = useMarqueeSelection(listAnchorRef);const selectedTaskIds = useTaskSelectionStore((s) => s.selectedTaskIds);const toggleTaskSelection = useTaskSelectionStore(@@ -152,24 +146,27 @@ function SidebarMenuComponent() {// index for shift-click range selection so it matches what the user sees —// in by-project mode the chronological flat order would span across project// groups and pull in unrelated tasks.- const orderedVisibleTaskIds = useMemo(() => {- const ids: string[] = sidebarData.pinnedTasks.map((t) => t.id);- if (organizeMode === "by-project") {- for (const group of sidebarData.groupedTasks) {- if (collapsedSections.has(group.id)) continue;- for (const t of group.tasks) ids.push(t.id);- }- } else {- for (const t of sidebarData.flatTasks) ids.push(t.id);- }- return ids;- }, [- sidebarData.pinnedTasks,- sidebarData.flatTasks,- sidebarData.groupedTasks,- organizeMode,- collapsedSections,- ]);+ // Depends on the three list fields rather than `sidebarData` itself, which+ // useSidebarData rebuilds as a fresh object every render.+ const orderedVisibleTaskIds = useMemo(+ () =>+ computeOrderedVisibleTaskIds(+ {+ pinnedTasks: sidebarData.pinnedTasks,+ flatTasks: sidebarData.flatTasks,+ groupedTasks: sidebarData.groupedTasks,+ },+ organizeMode,+ collapsedSections,+ ),+ [+ sidebarData.pinnedTasks,+ sidebarData.flatTasks,+ sidebarData.groupedTasks,+ organizeMode,+ collapsedSections,+ ],+ );useEffect(() => {pruneSelection(allSidebarTaskIds);@@ -178,12 +175,12 @@ function SidebarMenuComponent() {// The active (routed) task is implicitly part of any bulk selection — the// user expects to see and act on it together with cmd/shift-clicked tasks.const activeTaskId = sidebarData.activeTaskId;- const effectiveBulkIds = useMemo(() => {- if (selectedTaskIds.length === 0) return [];- if (!activeTaskId) return selectedTaskIds;- if (selectedTaskIds.includes(activeTaskId)) return selectedTaskIds;- return [activeTaskId, ...selectedTaskIds];- }, [activeTaskId, selectedTaskIds]);+ const effectiveBulkIds = useMemo(+ () => computeEffectiveBulkIds(selectedTaskIds, activeTaskId),+ [activeTaskId, selectedTaskIds],+ );++ const bulkActions = useSidebarBulkActions(effectiveBulkIds, allSidebarTasks);const handleTaskClick = (taskId: string, e: React.MouseEvent) => {// Ignore clicks on a row that's mid-archive.@@ -215,35 +212,48 @@ function SidebarMenuComponent() {};const handleBulkContextMenu = useCallback(- async (e: React.MouseEvent, taskIds: string[]) => {+ async (e: React.MouseEvent) => {e.preventDefault();e.stopPropagation();+ const allPinned = bulkActions.pinDirection === "unpin";try {const result =await hostClient.contextMenu.showBulkTaskContextMenu.mutate({- taskCount: taskIds.length,+ taskCount: bulkActions.selectedCount,+ allPinned,+ runningCount: bulkActions.runningCount,+ stopsCloudSandbox: bulkActions.stopsCloudSandbox,+ channels: bulkActions.channels.map(({ id, name }) => ({+ id,+ name,+ })),});if (!result.action) return;- if (result.action.type === "archive") {- const { archived, failed } = await archiveTasksImperative(- taskIds,- queryClient,- archiveCacheKeys,- );- clearSelection();- if (failed === 0) {- toast.success(- `${archived} ${archived === 1 ? "task" : "tasks"} archived`,- );- } else {- toast.error(`${archived} archived, ${failed} failed`);- }++ const intent = resolveBulkTaskContextMenuIntent(result.action, {+ allPinned,+ });+ switch (intent.type) {+ // The native menu confirmed already, so don't also open the dialog.+ case "archive":+ await bulkActions.archiveSelected();+ break;+ case "pin":+ case "unpin":+ await bulkActions.pinSelected();+ break;+ case "add-to-command-center":+ bulkActions.addSelectedToCommandCenter();+ break;+ case "file-to-channel":+ await bulkActions.fileSelectedTo(intent.channelId);+ break;}} catch (error) {log.error("Failed to show bulk context menu", error);}},- [hostClient, queryClient, clearSelection, archiveCacheKeys],+ [bulkActions, hostClient],);const handleGroupContextMenu = useCallback(@@ -291,7 +301,7 @@ function SidebarMenuComponent() {// and the right-clicked task is one of them. Otherwise clear and fall through.if (effectiveBulkIds.length > 1) {if (effectiveBulkIds.includes(taskId)) {- handleBulkContextMenu(e, effectiveBulkIds);+ handleBulkContextMenu(e);return;}clearSelection();@@ -400,40 +410,23 @@ function SidebarMenuComponent() {const handleArchivePrior = useCallback(async (taskId: string) => {- const allVisible = [...sidebarData.pinnedTasks, ...sidebarData.flatTasks];- const clickedTask = allVisible.find((t) => t.id === taskId);- if (!clickedTask) return;-- const threshold = clickedTask.lastActivityAt;- const priorTaskIds = allVisible- .filter((t) => t.id !== taskId && t.lastActivityAt < threshold)- .map((t) => t.id);-+ const priorTaskIds = computePriorTaskIds(allSidebarTasks, taskId);if (priorTaskIds.length === 0) {toast.info("No older tasks to archive");return;}- const { archived, failed } = await archiveTasksImperative(- priorTaskIds,- queryClient,- archiveCacheKeys,+ const result = formatArchiveResult(+ await archiveTasksImperative(+ priorTaskIds,+ queryClient,+ archiveCacheKeys,+ ),);-- if (failed === 0) {- toast.success(- `${archived} ${archived === 1 ? "task" : "tasks"} archived`,- );- } else {- toast.error(`${archived} archived, ${failed} failed`);- }+ if (result.kind === "success") toast.success(result.message);+ else toast.error(result.message);},- [- sidebarData.pinnedTasks,- sidebarData.flatTasks,- queryClient,- archiveCacheKeys,- ],+ [allSidebarTasks, queryClient, archiveCacheKeys],);const handleTaskDoubleClick = useCallback((taskId: string) => {@@ -469,7 +462,9 @@ function SidebarMenuComponent() {position="relative"id="side-bar-menu"className="flex min-h-0 flex-col"+ ref={listAnchorRef}>+ <MarqueeOverlay rect={marquee} /><div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden"><Flex direction="column" className="gap-px px-2 pb-2">{sidebarData.isLoading ? (@@ -501,6 +496,14 @@ function SidebarMenuComponent() {</Flex></div>+ {/* A sticky footer rather than an overlay: the list shrinks instead of+ having its bottom rows — where a shift-click range usually ends —+ covered up. */}+ <SidebarBulkActionFooter+ actions={bulkActions}+ onClearSelection={clearSelection}+ />+<ArchiveRunningTaskDialogopen={archiveConfirm !== null}taskTitle={archiveConfirm?.taskTitle ?? ""}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskItem.tsxindex a7d4053f4a1d..64e289c13951 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskItem.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskItem.tsx@@ -4,6 +4,7 @@ import { parseGithubUrl } from "@posthog/git/utils";import type { WorkspaceMode } from "@posthog/shared";import { formatRelativeTimeShort } from "@posthog/shared";import type { TaskRunStatus } from "@posthog/shared/domain-types";+import { SESSION_ROW_ATTRIBUTE } from "@posthog/ui/features/sidebar/useMarqueeSelection";import { navigateToPullRequestView } from "@posthog/ui/router/navigationBridge";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { DotsCircleSpinner } from "../../../../primitives/DotsCircleSpinner";@@ -214,6 +215,8 @@ export function TaskItem({label={label}isActive={isActive}isSelected={isSelected}+ // Lets a drag-selection find the row and the session it stands for.+ {...{ [SESSION_ROW_ATTRIBUTE]: taskId }}isDimmed={isArchiving}draggable={!isArchiving}onDragStart={handleDragStart}diff --git a/products/desktop/packages/ui/src/features/sidebar/taskSelectionStore.ts b/products/desktop/packages/ui/src/features/sidebar/taskSelectionStore.tsindex 4387199a16d6..44d3f9dfab5e 100644--- a/products/desktop/packages/ui/src/features/sidebar/taskSelectionStore.ts+++ b/products/desktop/packages/ui/src/features/sidebar/taskSelectionStore.ts@@ -2,6 +2,7 @@ import {computeRangeSelection,dedupeTaskIds,pruneToVisible,+ sameTaskIds,} from "@posthog/core/sidebar/selection";import { create } from "zustand";@@ -37,10 +38,23 @@ export const useTaskSelectionStore = create<TaskSelectionStore>()(selectedTaskIds: [],lastClickedId: null,+ // A marquee drag rewrites this on every pointermove, most of which land on+ // the row the last one did. Returning the same state leaves subscribers+ // alone rather than re-rendering the list at the pointer's rate.setSelectedTaskIds: (taskIds) =>- set({- selectedTaskIds: dedupeTaskIds(taskIds),- lastClickedId: taskIds.length === 1 ? taskIds[0] : get().lastClickedId,+ set((state) => {+ const deduped = dedupeTaskIds(taskIds);+ const lastClickedId =+ taskIds.length === 1 ? taskIds[0] : state.lastClickedId;+ // Both fields, so a no-op is only ever a genuine one — the anchor can+ // move while the ids stay put.+ if (+ sameTaskIds(deduped, state.selectedTaskIds) &&+ lastClickedId === state.lastClickedId+ ) {+ return state;+ }+ return { selectedTaskIds: deduped, lastClickedId };}),toggleTaskSelection: (taskId) =>diff --git a/products/desktop/packages/ui/src/features/sidebar/useClearSelectionOnEscape.ts b/products/desktop/packages/ui/src/features/sidebar/useClearSelectionOnEscape.tsnew file mode 100644index 000000000000..62a99886db0a--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/useClearSelectionOnEscape.ts@@ -0,0 +1,29 @@+import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";+import { useEffect } from "react";++function isEditableTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;+ if (target.isContentEditable) return true;+ const tag = target.tagName;+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";+}++/**+ * Escape clears a bulk session selection. Lives in a hook because each session+ * list owns its own mount — only one is on screen at a time, and whichever it+ * is has to answer Escape.+ */+export function useClearSelectionOnEscape(): void {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.key !== "Escape") return;+ if (isEditableTarget(e.target)) return;+ const { selectedTaskIds, clearSelection } =+ useTaskSelectionStore.getState();+ if (selectedTaskIds.length === 0) return;+ clearSelection();+ };+ window.addEventListener("keydown", handler);+ return () => window.removeEventListener("keydown", handler);+ }, []);+}diff --git a/products/desktop/packages/ui/src/features/sidebar/useMarqueeSelection.test.tsx b/products/desktop/packages/ui/src/features/sidebar/useMarqueeSelection.test.tsxnew file mode 100644index 000000000000..a000610188eb--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/useMarqueeSelection.test.tsx@@ -0,0 +1,187 @@+import { render } from "@testing-library/react";+import { act } from "react";+import { beforeEach, describe, expect, it } from "vitest";+import { useTaskSelectionStore } from "./taskSelectionStore";+import {+ SESSION_ROW_ATTRIBUTE,+ useMarqueeSelection,+} from "./useMarqueeSelection";++const ROW_HEIGHT = 20;++function Harness() {+ const ref = { current: null } as { current: HTMLDivElement | null };+ return <List innerRef={ref} />;+}++function List({ innerRef }: { innerRef: { current: HTMLDivElement | null } }) {+ const rect = useMarqueeSelection(innerRef);+ return (+ <div ref={innerRef} data-testid="anchor">+ <button type="button" data-testid="search">+ Search+ </button>+ {["a", "b", "c"].map((id) => (+ <button key={id} type="button" {...{ [SESSION_ROW_ATTRIBUTE]: id }}>+ {id}+ </button>+ ))}+ {rect ? <div data-testid="band" /> : null}+ </div>+ );+}++/**+ * jsdom gives every element a zero-sized box, so the rows are laid out here by+ * hand: row `i` occupies y = i*20 to (i+1)*20, and the anchor spans all three.+ */+function layout(container: HTMLElement) {+ const anchor = container.querySelector<HTMLElement>("[data-testid=anchor]");+ if (!anchor) throw new Error("anchor missing");+ anchor.getBoundingClientRect = () =>+ ({ top: 0, bottom: 60, left: 0, right: 100 }) as DOMRect;+ const rows = [+ ...container.querySelectorAll<HTMLElement>(`[${SESSION_ROW_ATTRIBUTE}]`),+ ];+ rows.forEach((row, i) => {+ row.getBoundingClientRect = () =>+ ({+ top: i * ROW_HEIGHT,+ bottom: (i + 1) * ROW_HEIGHT,+ left: 0,+ right: 100,+ }) as DOMRect;+ });+ return { anchor, rows };+}++function pointer(+ type: string,+ y: number,+ init: PointerEventInit = {},+): PointerEvent {+ return new PointerEvent(type, {+ bubbles: true,+ cancelable: true,+ clientX: 50,+ clientY: y,+ button: 0,+ buttons: 1,+ ...init,+ });+}++function drag(+ target: HTMLElement,+ fromY: number,+ toY: number,+ init: PointerEventInit = {},+) {+ act(() => {+ target.dispatchEvent(pointer("pointerdown", fromY, init));+ window.dispatchEvent(pointer("pointermove", toY, init));+ window.dispatchEvent(pointer("pointerup", toY, { ...init, buttons: 0 }));+ });+}++const selected = () => useTaskSelectionStore.getState().selectedTaskIds;++describe("useMarqueeSelection", () => {+ beforeEach(() => {+ useTaskSelectionStore.setState({+ selectedTaskIds: [],+ lastClickedId: null,+ });+ });++ it("selects every row the drag sweeps", () => {+ const { container } = render(<Harness />);+ const { anchor } = layout(container);++ drag(anchor, 58, 5);++ expect(selected()).toEqual(["a", "b", "c"]);+ });++ it("selects only the rows the drag reaches", () => {+ const { container } = render(<Harness />);+ const { anchor } = layout(container);++ drag(anchor, 58, 45);++ expect(selected()).toEqual(["c"]);+ });++ // A press on a row is that row's own: it opens the session, or drags it to a+ // command centre tile.+ it("ignores a drag that starts on a row", () => {+ const { container } = render(<Harness />);+ const { rows } = layout(container);++ drag(rows[2], 50, 5);++ expect(selected()).toEqual([]);+ });++ // Alt is the only modifier that takes a press away from its row. Cmd means+ // "add to the selection", which is the row's own click to answer.+ it("still ignores a drag from a row when Cmd is held", () => {+ const { container } = render(<Harness />);+ const { rows } = layout(container);++ drag(rows[2], 50, 5, { metaKey: true });++ expect(selected()).toEqual([]);+ });++ it("starts from a row when Alt says the drag is a selection", () => {+ const { container } = render(<Harness />);+ const { rows } = layout(container);++ drag(rows[2], 50, 5, { altKey: true });++ expect(selected()).toEqual(["a", "b", "c"]);+ });++ it("ignores a press on a control in the list", () => {+ const { container } = render(<Harness />);+ layout(container);+ const search = container.querySelector<HTMLElement>(+ "[data-testid=search]",+ ) as HTMLElement;++ drag(search, 58, 5);++ expect(selected()).toEqual([]);+ });++ it("leaves the selection alone when the pointer barely moves", () => {+ const { container } = render(<Harness />);+ const { anchor } = layout(container);+ useTaskSelectionStore.setState({ selectedTaskIds: ["b"] });++ drag(anchor, 58, 56);++ expect(selected()).toEqual(["b"]);+ });++ it("replaces what was selected before the drag", () => {+ const { container } = render(<Harness />);+ const { anchor } = layout(container);+ useTaskSelectionStore.setState({ selectedTaskIds: ["a"] });++ drag(anchor, 58, 45);++ expect(selected()).toEqual(["c"]);+ });++ it("adds to the selection when the modifier is held", () => {+ const { container } = render(<Harness />);+ const { anchor } = layout(container);+ useTaskSelectionStore.setState({ selectedTaskIds: ["a"] });++ drag(anchor, 58, 45, { metaKey: true });++ expect(selected()).toEqual(["a", "c"]);+ });+});diff --git a/products/desktop/packages/ui/src/features/sidebar/useMarqueeSelection.ts b/products/desktop/packages/ui/src/features/sidebar/useMarqueeSelection.tsnew file mode 100644index 000000000000..96befe18a275--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/useMarqueeSelection.ts@@ -0,0 +1,117 @@+import {+ hasDraggedFar,+ type MarqueeRow,+ marqueeSpan,+ mergeMarqueeSelection,+ rowsInMarquee,+} from "@posthog/core/sidebar/marquee";+import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";+import { type RefObject, useEffect, useState } from "react";++/** Marks a row as a session the marquee can sweep up; the value is its task id. */+export const SESSION_ROW_ATTRIBUTE = "data-session-id";++const ROW_SELECTOR = `[${SESSION_ROW_ATTRIBUTE}]`;+// A press on any other control is that control's, not the start of a drag.+const CONTROL_SELECTOR = "button, input, a, [role='menuitem'], [role='tab']";++export interface MarqueeRect {+ top: number;+ height: number;+}++/**+ * Drag across the session list to select what the drag passes.+ *+ * A press that lands on a row belongs to that row — it opens it, or drags it to+ * a command centre tile — so a marquee only starts from empty space, or with Alt+ * held to say the drag is a selection rather than the row's own.+ *+ * `anchorRef` must be a non-scrolling positioned ancestor of the rows: the+ * returned rect is relative to it, and the rows are read from inside it.+ */+export function useMarqueeSelection(+ anchorRef: RefObject<HTMLElement | null>,+): MarqueeRect | null {+ const [rect, setRect] = useState<MarqueeRect | null>(null);++ useEffect(() => {+ const anchor = anchorRef.current;+ if (!anchor) return;++ let origin: { x: number; y: number } | null = null;+ let baseSelection: string[] = [];+ let additive = false;+ let dragging = false;+ // Measured once the drag starts: rows don't move under it, and re-reading+ // every row's box on each pointermove is the expensive way to find out.+ let rows: MarqueeRow[] = [];++ const readRows = (): MarqueeRow[] =>+ [...anchor.querySelectorAll<HTMLElement>(ROW_SELECTOR)].flatMap((el) => {+ const id = el.getAttribute(SESSION_ROW_ATTRIBUTE);+ if (!id) return [];+ const box = el.getBoundingClientRect();+ return [{ id, top: box.top, bottom: box.bottom }];+ });++ const stop = () => {+ window.removeEventListener("pointermove", onPointerMove);+ window.removeEventListener("pointerup", stop);+ origin = null;+ dragging = false;+ setRect(null);+ };++ const onPointerMove = (e: PointerEvent) => {+ if (!origin) return;+ if (!dragging) {+ if (!hasDraggedFar(e.clientX - origin.x, e.clientY - origin.y)) return;+ dragging = true;+ rows = readRows();+ }+ // Stops the drag from turning into a text selection over the labels.+ e.preventDefault();++ const span = marqueeSpan(origin.y, e.clientY);+ const anchorTop = anchor.getBoundingClientRect().top;+ setRect({+ top: span.top - anchorTop,+ height: span.bottom - span.top,+ });+ useTaskSelectionStore+ .getState()+ .setSelectedTaskIds(+ mergeMarqueeSelection(+ baseSelection,+ rowsInMarquee(span, rows),+ additive,+ ),+ );+ };++ const onPointerDown = (e: PointerEvent) => {+ if (e.button !== 0) return;+ const target = e.target as Element | null;+ if (!target) return;+ const onRow = target.closest(ROW_SELECTOR);+ if (onRow && !e.altKey) return;+ if (!onRow && target.closest(CONTROL_SELECTOR)) return;++ origin = { x: e.clientX, y: e.clientY };+ additive = e.metaKey || e.ctrlKey;+ baseSelection = useTaskSelectionStore.getState().selectedTaskIds;+ dragging = false;+ window.addEventListener("pointermove", onPointerMove);+ window.addEventListener("pointerup", stop);+ };++ anchor.addEventListener("pointerdown", onPointerDown);+ return () => {+ anchor.removeEventListener("pointerdown", onPointerDown);+ stop();+ };+ }, [anchorRef]);++ return rect;+}diff --git a/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.test.tsx b/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.test.tsxindex fa3ae96c2d90..fcf4cbabe9ad 100644--- a/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.test.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.test.tsx@@ -68,6 +68,80 @@ describe("usePinnedTasks", () => {await waitFor(() => expect(result.current.isPinned("task-1")).toBe(false));});+ describe("setPinnedMany", () => {+ it("pins a whole batch in one pass", async () => {+ authClient.getPinnedTaskIds.mockResolvedValue([]);+ mockedApi.setPinned.mockImplementation(async (taskId) => ({+ taskId,+ isPinned: true,+ }));+ const { result } = renderPinnedTasks();+ await waitFor(() => expect(result.current.isLoading).toBe(false));++ await act(async () => {+ const outcome = await result.current.setPinnedMany(+ ["task-1", "task-2"],+ true,+ );+ expect(outcome.succeeded).toEqual(["task-1", "task-2"]);+ expect(outcome.failed).toEqual([]);+ });++ await waitFor(() => {+ expect(result.current.isPinned("task-1")).toBe(true);+ expect(result.current.isPinned("task-2")).toBe(true);+ });+ });++ // The optimistic write pins everything up front, so a failure has to be+ // walked back or the row keeps showing pinned while the server disagrees.+ it("rolls the optimistic write back for ids that failed", async () => {+ authClient.getPinnedTaskIds.mockResolvedValue([]);+ mockedApi.setPinned.mockImplementation(async (taskId) => {+ if (taskId === "task-2") throw new Error("nope");+ return { taskId, isPinned: true };+ });+ const { result } = renderPinnedTasks();+ await waitFor(() => expect(result.current.isLoading).toBe(false));++ await act(async () => {+ const outcome = await result.current.setPinnedMany(+ ["task-1", "task-2"],+ true,+ );+ expect(outcome.failed).toEqual(["task-2"]);+ });++ await waitFor(() => {+ expect(result.current.isPinned("task-1")).toBe(true);+ expect(result.current.isPinned("task-2")).toBe(false);+ });+ });++ it("unpins a whole batch", async () => {+ authClient.getPinnedTaskIds.mockResolvedValue(["task-1", "task-2"]);+ mockedApi.setPinned.mockImplementation(async (taskId) => ({+ taskId,+ isPinned: false,+ }));+ const { result } = renderPinnedTasks();+ await waitFor(() => expect(result.current.isLoading).toBe(false));++ await act(() =>+ result.current.setPinnedMany(["task-1", "task-2"], false),+ );++ expect(mockedApi.setPinned.mock.calls).toEqual([+ ["task-1", false],+ ["task-2", false],+ ]);+ await waitFor(() => {+ expect(result.current.isPinned("task-1")).toBe(false);+ expect(result.current.isPinned("task-2")).toBe(false);+ });+ });+ });+it("preserves rapid toggle order", async () => {authClient.getPinnedTaskIds.mockResolvedValue([]);mockedApi.setPinneddiff --git a/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.ts b/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.tsindex 51b9ae34e088..e50be8e1d529 100644--- a/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.ts+++ b/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.ts@@ -65,6 +65,62 @@ export function usePinnedTasks() {});}, []);+ // Shares the mutation scope with togglePin so a bulk write and a single-row+ // toggle queue behind each other instead of racing on the same cache entry.+ const setPinnedManyMutation = useMutation({+ scope: { id: "task-pins" },+ mutationFn: async ({+ taskIds,+ pinned,+ }: {+ taskIds: string[];+ pinned: boolean;+ }) => {+ const results = await Promise.allSettled(+ taskIds.map((taskId) => pinnedTasksApi.setPinned(taskId, pinned)),+ );+ return {+ succeeded: taskIds.filter((_, i) => results[i].status === "fulfilled"),+ failed: taskIds.filter((_, i) => results[i].status === "rejected"),+ };+ },+ onMutate: async ({ taskIds, pinned }) => {+ await queryClient.cancelQueries({ queryKey: pinnedQueryKey });+ queryClient.setQueryData<string[]>(pinnedQueryKey, (old) => {+ const batch = new Set(taskIds);+ const rest = old?.filter((id) => !batch.has(id)) ?? [];+ return pinned ? [...rest, ...taskIds] : rest;+ });+ },+ // No onError rollback: the mutationFn settles every request itself and+ // never rejects, so partial failure is reconciled here instead — undo the+ // optimistic write for whichever ids didn't make it.+ onSuccess: ({ failed }, { pinned }) => {+ if (failed.length === 0) return;+ const rolledBack = new Set(failed);+ queryClient.setQueryData<string[]>(pinnedQueryKey, (old) => {+ const rest = old?.filter((id) => !rolledBack.has(id)) ?? [];+ return pinned ? rest : [...rest, ...failed];+ });+ },+ });++ const setPinnedManyMutationRef = useRef(setPinnedManyMutation);+ setPinnedManyMutationRef.current = setPinnedManyMutation;++ const setPinnedMany = useCallback(+ async (taskIds: string[], pinned: boolean) => {+ const nextPinnedSet = new Set(pinnedSetRef.current);+ for (const taskId of taskIds) {+ if (pinned) nextPinnedSet.add(taskId);+ else nextPinnedSet.delete(taskId);+ }+ pinnedSetRef.current = nextPinnedSet;+ return setPinnedManyMutationRef.current.mutateAsync({ taskIds, pinned });+ },+ [],+ );+const unpin = useCallback(async (taskId: string) => {if (!pinnedSetRef.current.has(taskId)) return;@@ -85,6 +141,8 @@ export function usePinnedTasks() {pinnedTaskIds: pinnedSet,isLoading,togglePin,+ setPinnedMany,+ isSettingPinnedMany: setPinnedManyMutation.isPending,unpin,isPinned,};diff --git a/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.test.tsx b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.test.tsxnew file mode 100644index 000000000000..5498f874e7ae--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.test.tsx@@ -0,0 +1,371 @@+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";+import { act, renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useTaskSelectionStore } from "./taskSelectionStore";+import { useSidebarBulkActions } from "./useSidebarBulkActions";++const hoisted = vi.hoisted(() => ({+ archiveTasksImperative: vi.fn(),+ setPinnedMany: vi.fn(),+ placeTasksInCommandCenter: vi.fn(),+ fileTask: vi.fn(),+ useChannels: vi.fn(),+ useFeatureFlag: vi.fn(),+ useTasks: vi.fn(),+ pinnedTaskIds: new Set<string>(),+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ },+}));++vi.mock("@posthog/ui/features/archive/useArchiveTask", () => ({+ archiveTasksImperative: hoisted.archiveTasksImperative,+ useArchiveCacheKeys: () => ({}),+}));++vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({+ useChannels: hoisted.useChannels,+}));++vi.mock("@posthog/ui/features/canvas/hooks/useChannelTasks", () => ({+ useChannelTaskMutations: () => ({ fileTask: hoisted.fileTask }),+}));++vi.mock("@posthog/ui/features/command-center/placeTaskInCommandCenter", () => ({+ placeTasksInCommandCenter: hoisted.placeTasksInCommandCenter,+}));++vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({+ useFeatureFlag: hoisted.useFeatureFlag,+}));++vi.mock("./usePinnedTasks", () => ({+ usePinnedTasks: () => ({+ pinnedTaskIds: hoisted.pinnedTaskIds,+ setPinnedMany: hoisted.setPinnedMany,+ isSettingPinnedMany: false,+ }),+}));++vi.mock("@posthog/ui/features/tasks/useTasks", () => ({+ useTasks: hoisted.useTasks,+}));++vi.mock("@posthog/ui/primitives/toast", () => ({ toast: hoisted.toast }));++vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => ({}) }));++function makeTask(id: string, overrides: Partial<TaskData> = {}): TaskData {+ return {+ id,+ title: id,+ createdAt: 0,+ lastActivityAt: 0,+ isGenerating: false,+ isUnread: false,+ isPinned: false,+ needsPermission: false,+ repository: null,+ isSuspended: false,+ folderPath: null,+ cloudPrUrl: null,+ branchName: null,+ linkedBranch: null,+ ...overrides,+ } as TaskData;+}++const TASKS = [makeTask("t1"), makeTask("t2")];++function render(taskIds: string[] = ["t1", "t2"]) {+ return renderHook(() => useSidebarBulkActions(taskIds, TASKS));+}++describe("useSidebarBulkActions", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ hoisted.pinnedTaskIds = new Set();+ hoisted.useChannels.mockReturnValue({+ channels: [{ id: "c1", name: "support" }],+ isLoading: false,+ });+ hoisted.useFeatureFlag.mockReturnValue(true);+ hoisted.useTasks.mockReturnValue({ data: [{ id: "t1" }, { id: "t2" }] });+ hoisted.setPinnedMany.mockResolvedValue({+ succeeded: ["t1", "t2"],+ failed: [],+ });+ hoisted.archiveTasksImperative.mockResolvedValue({+ archived: 2,+ failed: 0,+ });+ hoisted.placeTasksInCommandCenter.mockReturnValue({+ placed: 2,+ overflow: 0,+ alreadyPresent: 0,+ });+ hoisted.fileTask.mockReset();+ hoisted.fileTask.mockResolvedValue(undefined);+ useTaskSelectionStore.setState({+ selectedTaskIds: ["t1", "t2"],+ lastClickedId: null,+ });+ });++ it.each([+ {+ name: "none pinned",+ pinned: [],+ direction: "pin",+ label: "Pin 2 sessions",+ },+ {+ name: "some pinned",+ pinned: ["t1"],+ direction: "pin",+ label: "Pin 2 sessions",+ },+ {+ name: "all pinned",+ pinned: ["t1", "t2"],+ direction: "unpin",+ label: "Unpin 2 sessions",+ },+ ])(+ "labels the pin action $direction when $name",+ ({ pinned, direction, label }) => {+ hoisted.pinnedTaskIds = new Set(pinned);++ const { result } = render();++ expect(result.current.pinDirection).toBe(direction);+ expect(result.current.pinLabel).toBe(label);+ },+ );++ it("pins the whole selection in the computed direction", async () => {+ hoisted.pinnedTaskIds = new Set(["t1", "t2"]);+ const { result } = render();++ await act(() => result.current.pinSelected());++ expect(hoisted.setPinnedMany).toHaveBeenCalledWith(["t1", "t2"], false);+ });++ it("clears the selection when every session succeeded", async () => {+ const { result } = render();++ await act(() => result.current.pinSelected());++ await waitFor(() =>+ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual([]),+ );+ });++ // Keeping the failures selected is what lets the user retry just those.+ it("keeps only the failures selected after a partial failure", async () => {+ hoisted.setPinnedMany.mockResolvedValue({+ succeeded: ["t1"],+ failed: ["t2"],+ });+ const { result } = render();++ await act(() => result.current.pinSelected());++ await waitFor(() =>+ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual(["t2"]),+ );+ });++ describe("addSelectedToCommandCenter", () => {+ it("reports how many landed on the grid", () => {+ const { result } = render();++ act(() => result.current.addSelectedToCommandCenter());++ expect(hoisted.toast.success).toHaveBeenCalledWith(+ "2 sessions added to Command Center",+ );+ });++ // "0 sessions added" reads as a failure when the grid is exactly as asked.+ it("says the batch was already there rather than reporting zero added", () => {+ hoisted.placeTasksInCommandCenter.mockReturnValue({+ placed: 0,+ overflow: 0,+ alreadyPresent: 2,+ });+ const { result } = render();++ act(() => result.current.addSelectedToCommandCenter());++ expect(hoisted.toast.success).not.toHaveBeenCalled();+ expect(hoisted.toast.info).toHaveBeenCalledWith(+ "2 sessions already in Command Center",+ );+ });++ // The selection survives so the leftovers can go somewhere in one click,+ // matching what archive and file do with the sessions they couldn't take.+ it("warns about sessions that didn't fit and keeps the selection", () => {+ hoisted.placeTasksInCommandCenter.mockReturnValue({+ placed: 1,+ overflow: 1,+ alreadyPresent: 0,+ });+ const { result } = render();++ act(() => result.current.addSelectedToCommandCenter());++ expect(hoisted.toast.warning).toHaveBeenCalledWith(+ "1 added to Command Center, 1 didn't fit",+ );+ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual([+ "t1",+ "t2",+ ]);+ });++ // A cell holding a deleted task draws empty, so placement needs the live+ // list to see the same free tile — and null, not an empty set, while that+ // list is still loading, or it would tile over sessions already on the grid.+ it.each([+ {+ name: "the loaded task ids",+ data: [{ id: "t9" }],+ live: new Set(["t9"]),+ },+ { name: "null before the list loads", data: undefined, live: null },+ ])("places against $name", ({ data, live }) => {+ hoisted.useTasks.mockReturnValue({ data });+ const { result } = render();++ act(() => result.current.addSelectedToCommandCenter());++ expect(hoisted.placeTasksInCommandCenter).toHaveBeenCalledWith(+ ["t1", "t2"],+ live,+ );+ });+ });++ // stopsCloudSandbox drives the warning's "Any cloud sandbox … shuts down+ // too", so it has to track the environment rather than just "running".+ it.each([+ { environment: "cloud", stopsCloudSandbox: true },+ { environment: "local", stopsCloudSandbox: false },+ ] as const)(+ "counts a running $environment session and reports stopsCloudSandbox=$stopsCloudSandbox",+ ({ environment, stopsCloudSandbox }) => {+ const tasks = [+ makeTask("t1", { isGenerating: true, taskRunEnvironment: environment }),+ makeTask("t2"),+ ];++ const { result } = renderHook(() =>+ useSidebarBulkActions(["t1", "t2"], tasks),+ );++ expect(result.current.runningCount).toBe(1);+ expect(result.current.stopsCloudSandbox).toBe(stopsCloudSandbox);+ },+ );++ describe("archiveSelected", () => {+ it("clears the selection when every session was archived", async () => {+ const { result } = render();++ await act(() => result.current.archiveSelected());++ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual([]);+ expect(hoisted.toast.success).toHaveBeenCalledWith("2 sessions archived");+ });++ // Deliberately unlike pinSelected, which narrows to the failures: archiving+ // reports counts rather than ids, so there is nothing to narrow to and the+ // whole selection stays put for a retry.+ it("keeps the whole selection after a partial failure", async () => {+ hoisted.archiveTasksImperative.mockResolvedValue({+ archived: 1,+ failed: 1,+ });+ const { result } = render();++ await act(() => result.current.archiveSelected());++ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual([+ "t1",+ "t2",+ ]);+ expect(hoisted.toast.error).toHaveBeenCalledWith("1 archived, 1 failed");+ });++ it("reports a thrown archive rather than rejecting", async () => {+ hoisted.archiveTasksImperative.mockRejectedValue(new Error("network"));+ const { result } = render();++ await act(() => result.current.archiveSelected());++ expect(hoisted.toast.error).toHaveBeenCalledWith(+ "Couldn't archive the selected sessions",+ );+ expect(result.current.isArchiving).toBe(false);+ });+ });++ it("files every selected session to the chosen channel", async () => {+ const { result } = render();++ await act(() => result.current.fileSelectedTo("c1"));++ expect(hoisted.fileTask.mock.calls).toEqual([+ ["c1", "t1"],+ ["c1", "t2"],+ ]);+ });++ // Narrowing to the failures is what makes a retry one click.+ it("keeps only the sessions that failed to file selected", async () => {+ hoisted.fileTask.mockImplementation((_channelId: string, taskId: string) =>+ taskId === "t2" ? Promise.reject(new Error("nope")) : Promise.resolve(),+ );+ const { result } = render();++ await act(() => result.current.fileSelectedTo("c1"));++ await waitFor(() =>+ expect(useTaskSelectionStore.getState().selectedTaskIds).toEqual(["t2"]),+ );+ expect(hoisted.toast.error).toHaveBeenCalledWith("1 filed, 1 failed");+ });++ // `enabled: false` stops the fetch but still hands back whatever an ungated+ // surface already put in the shared cache, so the flag has to gate the list.+ it("offers no channels when the bluebird flag is off", () => {+ hoisted.useFeatureFlag.mockReturnValue(false);+ hoisted.useChannels.mockReturnValue({+ channels: [{ id: "c1", name: "support" }],+ isLoading: false,+ });++ const { result } = render();++ expect(result.current.channels).toEqual([]);+ expect(result.current.fileDisabledReason).not.toBeNull();+ expect(hoisted.useChannels).toHaveBeenCalledWith({ enabled: false });+ });++ it.each([+ { action: "archiveDisabledReason" },+ { action: "pinDisabledReason" },+ { action: "commandCenterDisabledReason" },+ { action: "fileDisabledReason" },+ ] as const)("disables $action with nothing selected", ({ action }) => {+ const { result } = render([]);++ expect(result.current[action]).not.toBeNull();+ });+});diff --git a/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.tsnew file mode 100644index 000000000000..ba484d516d30--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts@@ -0,0 +1,284 @@+import {+ type BulkResultKind,+ computeBulkPinDirection,+ formatBulkResult,+ sessionsLabel,+} from "@posthog/core/sidebar/selection";+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";+import { isTaskActivelyRunning } from "@posthog/core/sidebar/taskRunning";+import { PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";+import {+ archiveTasksImperative,+ useArchiveCacheKeys,+} from "@posthog/ui/features/archive/useArchiveTask";+import type { Channel } from "@posthog/ui/features/canvas/hooks/useChannels";+import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";+import { useChannelTaskMutations } from "@posthog/ui/features/canvas/hooks/useChannelTasks";+import { placeTasksInCommandCenter } from "@posthog/ui/features/command-center/placeTaskInCommandCenter";+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";+import { useArchivingTasksStore } from "@posthog/ui/features/sidebar/archivingTasksStore";+import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";+import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";+import { useTasks } from "@posthog/ui/features/tasks/useTasks";+import { toast } from "@posthog/ui/primitives/toast";+import { logger } from "@posthog/ui/shell/logger";+import { useQueryClient } from "@tanstack/react-query";+import { useCallback, useMemo, useState } from "react";++const log = logger.scope("sidebar-bulk-actions");++/** Stable empty list, so a gated-off channels array keeps a steady identity. */+const EMPTY_CHANNELS: Channel[] = [];++/** Clause after "Disabled because …" (see `@posthog/ui/primitives/Button`). */+const NO_SELECTION = "you haven't selected any sessions";+const NO_CHANNELS = "this project has no channels to file to";++export interface SidebarBulkActions {+ selectedCount: number;+ /** How many of the selection are still running, so archiving would stop them. */+ runningCount: number;+ stopsCloudSandbox: boolean;+ pinDirection: "pin" | "unpin";+ pinLabel: string;+ channels: Channel[];+ archiveSelected: () => Promise<void>;+ pinSelected: () => Promise<void>;+ addSelectedToCommandCenter: () => void;+ fileSelectedTo: (channelId: string) => Promise<void>;+ archiveDisabledReason: string | null;+ pinDisabledReason: string | null;+ commandCenterDisabledReason: string | null;+ fileDisabledReason: string | null;+ isArchiving: boolean;+ isPinning: boolean;+ isFiling: boolean;+}++/**+ * What a bulk action needs to know about a session beyond its id: only enough+ * to say whether archiving it would stop something. Narrower than `TaskData` so+ * both session lists can feed this without one shape dictating the other.+ */+export type BulkSessionInfo = Pick<+ TaskData,+ "id" | "isGenerating" | "taskRunEnvironment" | "taskRunStatus"+>;++/**+ * The four bulk actions offered over a multi-session selection, shared by the+ * action bar and the bulk right-click menu so the two can't drift apart.+ */+export function useSidebarBulkActions(+ taskIds: string[],+ tasks: BulkSessionInfo[],+): SidebarBulkActions {+ const queryClient = useQueryClient();+ const archiveCacheKeys = useArchiveCacheKeys();+ const clearSelection = useTaskSelectionStore((s) => s.clearSelection);+ const setSelectedTaskIds = useTaskSelectionStore((s) => s.setSelectedTaskIds);+ const { pinnedTaskIds, setPinnedMany, isSettingPinnedMany } =+ usePinnedTasks();++ // "File to…" is a Project Bluebird feature. `enabled` only stops the fetch, and+ // an ungated surface elsewhere can still have filled the shared cache, so the+ // flag has to gate the list itself rather than just the request.+ const bluebirdEnabled = useFeatureFlag(+ PROJECT_BLUEBIRD_FLAG,+ import.meta.env.DEV,+ );+ const { channels: fetchedChannels } = useChannels({+ enabled: bluebirdEnabled,+ });+ const channels = bluebirdEnabled ? fetchedChannels : EMPTY_CHANNELS;+ const { fileTask } = useChannelTaskMutations();++ // The command centre's own task list, so a cell counts as free here exactly+ // when the grid draws it empty. Same query key the grid uses, so this is a+ // cache read rather than a second poll.+ const { data: liveTasks } = useTasks();+ const liveTaskIds = useMemo(+ () => (liveTasks ? new Set(liveTasks.map((t) => t.id)) : null),+ [liveTasks],+ );++ const [isArchiving, setIsArchiving] = useState(false);+ const [isFiling, setIsFiling] = useState(false);++ const selectedCount = taskIds.length;++ const selectedTasks = useMemo(() => {+ const ids = new Set(taskIds);+ return tasks.filter((task) => ids.has(task.id));+ }, [taskIds, tasks]);++ const runningTasks = useMemo(+ () => selectedTasks.filter(isTaskActivelyRunning),+ [selectedTasks],+ );++ const pinDirection = useMemo(+ () => computeBulkPinDirection(taskIds, pinnedTaskIds),+ [taskIds, pinnedTaskIds],+ );++ const report = useCallback(+ (kind: BulkResultKind, succeeded: number, failed: number) => {+ const result = formatBulkResult(kind, { succeeded, failed });+ if (result.kind === "success") toast.success(result.message);+ else toast.error(result.message);+ },+ [],+ );++ // Full success clears the selection; a partial one narrows it to exactly the+ // failures so the user can retry those. Setting the ids outright rather than+ // subtracting the successes matters because the routed task is folded into+ // the batch without ever being in the store — subtracting would empty it.+ const reconcileSelection = useCallback(+ (failedIds: string[]) => {+ if (failedIds.length === 0) clearSelection();+ else setSelectedTaskIds(failedIds);+ },+ [clearSelection, setSelectedTaskIds],+ );++ const archiveSelected = useCallback(async () => {+ if (selectedCount === 0 || isArchiving) return;+ setIsArchiving(true);+ const store = useArchivingTasksStore.getState();+ // Spinner the rows for the whole sequential batch, not just the current one.+ for (const id of taskIds) store.startArchiving(id);+ try {+ const { archived, failed } = await archiveTasksImperative(+ taskIds,+ queryClient,+ archiveCacheKeys,+ );+ // archiveTasks reports counts, not ids, so a partial failure can't narrow+ // the selection to the stragglers — leave it whole so a retry is one click.+ if (failed === 0) clearSelection();+ report("archived", archived, failed);+ } catch (error) {+ log.error("Failed to archive sessions", error);+ toast.error("Couldn't archive the selected sessions");+ } finally {+ const current = useArchivingTasksStore.getState();+ for (const id of taskIds) current.stopArchiving(id);+ setIsArchiving(false);+ }+ }, [+ archiveCacheKeys,+ clearSelection,+ isArchiving,+ queryClient,+ report,+ selectedCount,+ taskIds,+ ]);++ const pinSelected = useCallback(async () => {+ if (selectedCount === 0) return;+ const pinned = pinDirection === "pin";+ try {+ const { succeeded, failed } = await setPinnedMany(taskIds, pinned);+ reconcileSelection(failed);+ report(pinned ? "pinned" : "unpinned", succeeded.length, failed.length);+ } catch (error) {+ log.error("Failed to pin sessions", error);+ toast.error(`Couldn't ${pinned ? "pin" : "unpin"} the selected sessions`);+ }+ }, [+ pinDirection,+ reconcileSelection,+ report,+ selectedCount,+ setPinnedMany,+ taskIds,+ ]);++ const addSelectedToCommandCenter = useCallback(() => {+ if (selectedCount === 0) return;+ const { placed, overflow, alreadyPresent } = placeTasksInCommandCenter(+ taskIds,+ liveTaskIds,+ );+ // Selection survives an overflow so the sessions that didn't fit can go+ // somewhere else in one more click. Placement reports counts rather than+ // ids, so the whole selection stays rather than narrowing to the leftovers.+ if (overflow > 0) {+ toast.warning(+ `${placed} added to Command Center, ${overflow} didn't fit`,+ );+ return;+ }+ clearSelection();+ // Nothing moved because the whole batch was already tiled — saying "0+ // added" would read as a failure when the grid is exactly as asked.+ if (placed === 0 && alreadyPresent > 0) {+ toast.info(`${sessionsLabel(alreadyPresent)} already in Command Center`);+ return;+ }+ report("added to Command Center", placed, 0);+ }, [clearSelection, liveTaskIds, report, selectedCount, taskIds]);++ const fileSelectedTo = useCallback(+ async (channelId: string) => {+ if (selectedCount === 0 || isFiling) return;+ setIsFiling(true);+ try {+ const results = await Promise.allSettled(+ taskIds.map((taskId) => fileTask(channelId, taskId)),+ );+ const failedIds = taskIds.filter(+ (_, i) => results[i].status === "rejected",+ );+ reconcileSelection(failedIds);+ report("filed", taskIds.length - failedIds.length, failedIds.length);+ } finally {+ setIsFiling(false);+ }+ },+ [fileTask, isFiling, reconcileSelection, report, selectedCount, taskIds],+ );++ // Memoized because SidebarMenu's bulk callbacks depend on this object; a+ // fresh identity per render would defeat every useCallback downstream.+ return useMemo(() => {+ const noSelection = selectedCount === 0 ? NO_SELECTION : null;+ return {+ selectedCount,+ runningCount: runningTasks.length,+ stopsCloudSandbox: runningTasks.some(+ (task) => task.taskRunEnvironment === "cloud",+ ),+ pinDirection,+ pinLabel: `${pinDirection === "pin" ? "Pin" : "Unpin"} ${sessionsLabel(selectedCount)}`,+ channels,+ archiveSelected,+ pinSelected,+ addSelectedToCommandCenter,+ fileSelectedTo,+ archiveDisabledReason: noSelection,+ pinDisabledReason: noSelection,+ commandCenterDisabledReason: noSelection,+ fileDisabledReason:+ noSelection ?? (channels.length === 0 ? NO_CHANNELS : null),+ isArchiving,+ isPinning: isSettingPinnedMany,+ isFiling,+ };+ }, [+ addSelectedToCommandCenter,+ archiveSelected,+ channels,+ fileSelectedTo,+ isArchiving,+ isFiling,+ isSettingPinnedMany,+ pinDirection,+ pinSelected,+ runningTasks,+ selectedCount,+ ]);+}