Skip to content

: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.

fix(desktop): act on the sidebar selection a person can see (#86012)

Adam Leith4eaff9246058
diff --git a/products/desktop/packages/core/src/sidebar/selection.test.ts b/products/desktop/packages/core/src/sidebar/selection.test.ts
index 4dac175a3447..4306b50a2eeb 100644
--- a/products/desktop/packages/core/src/sidebar/selection.test.ts
+++ b/products/desktop/packages/core/src/sidebar/selection.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vitest";
import {
computeBulkPinDirection,
- computeEffectiveBulkIds,
computeOrderedVisibleTaskIds,
computePriorTaskIds,
computeRangeSelection,
@@ -79,24 +78,6 @@ describe("pruneToVisible", () => {
});
});
-describe("computeEffectiveBulkIds", () => {
- it("returns empty when nothing selected", () => {
- expect(computeEffectiveBulkIds([], "t1")).toEqual([]);
- });
-
- it("returns selection unchanged when no active task", () => {
- expect(computeEffectiveBulkIds(["t1", "t2"], null)).toEqual(["t1", "t2"]);
- });
-
- it("prepends active task when not already selected", () => {
- expect(computeEffectiveBulkIds(["t2"], "t1")).toEqual(["t1", "t2"]);
- });
-
- it("leaves selection unchanged when active task already selected", () => {
- expect(computeEffectiveBulkIds(["t1", "t2"], "t1")).toEqual(["t1", "t2"]);
- });
-});
-
describe("computeOrderedVisibleTaskIds", () => {
it("uses flat order in chronological mode", () => {
const ids = computeOrderedVisibleTaskIds(
diff --git a/products/desktop/packages/core/src/sidebar/selection.ts b/products/desktop/packages/core/src/sidebar/selection.ts
index 4f24c0440d27..bd6f40727443 100644
--- a/products/desktop/packages/core/src/sidebar/selection.ts
+++ b/products/desktop/packages/core/src/sidebar/selection.ts
@@ -19,16 +19,6 @@ export function computeOrderedVisibleTaskIds(
return ids;
}
-export function computeEffectiveBulkIds(
- selectedTaskIds: string[],
- activeTaskId: string | null,
-): string[] {
- if (selectedTaskIds.length === 0) return [];
- if (!activeTaskId) return selectedTaskIds;
- if (selectedTaskIds.includes(activeTaskId)) return selectedTaskIds;
- return [activeTaskId, ...selectedTaskIds];
-}
-
export interface RangeSelection {
selectedTaskIds: string[];
lastClickedId: string;
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemDragPreview.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemDragPreview.tsx
index b6df0a4e304c..a551e81482a6 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemDragPreview.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemDragPreview.tsx
@@ -2,6 +2,7 @@ import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
import { cn } from "@posthog/quill";
import { ChannelItemRowView } from "@posthog/ui/features/canvas/components/ChannelItemRow";
import { useChannelTaskStatus } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";
+import { DragBatchLabel } from "@posthog/ui/features/sidebar/components/DragBatchLabel";
import { getPinDropAction } from "@posthog/ui/features/sidebar/taskListDragAndDrop";
import type { PinDrag } from "@posthog/ui/features/sidebar/usePinDrag";
import {
@@ -35,8 +36,9 @@ export function ChannelItemDragPreview({
document.querySelector<HTMLElement>(".radix-themes") ?? document.body;
// Skips the PR lookup: that is a query into git per row, and the row under
// the pointer is already paying for it.
- const status = useChannelTaskStatus(drag.item, { withPrStatus: false });
+ const status = useChannelTaskStatus(drag.items[0], { withPrStatus: false });
const action = getPinDropAction(drag.sourcePinned, drag.overPinned);
+ const draggedCount = drag.items.length;
const spring = prefersReducedMotion
? { duration: 0 }
: ({ type: "spring", stiffness: 500, damping: 34 } as const);
@@ -46,13 +48,25 @@ export function ChannelItemDragPreview({
style={{ x, y, width: drag.previewWidth }}
className="pointer-events-none fixed top-0 left-0 z-50"
>
- <div className="overflow-hidden rounded-md border border-border bg-background shadow-lg">
- <ChannelItemRowView
- item={drag.item}
- status={status}
- isActive={false}
- showPinBadge={false}
- />
+ {/* Two offset layers behind the card, so a batch looks like a stack
+ before its label is read. */}
+ {draggedCount > 1 ? (
+ <>
+ <div className="absolute inset-x-2 top-2 h-full rounded-md border border-border bg-background shadow-sm" />
+ <div className="absolute inset-x-1 top-1 h-full rounded-md border border-border bg-background shadow-sm" />
+ </>
+ ) : null}
+ <div className="relative overflow-hidden rounded-md border border-border bg-background shadow-lg">
+ {draggedCount > 1 ? (
+ <DragBatchLabel count={draggedCount} />
+ ) : (
+ <ChannelItemRowView
+ item={drag.items[0]}
+ status={status}
+ isActive={false}
+ showPinBadge={false}
+ />
+ )}
</div>
<AnimatePresence>
{action !== null ? (
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
index 62077d8b74b1..cf66f17a5c1d 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
@@ -37,6 +37,7 @@ import { ChannelItemRow } from "./ChannelItemRow";
const actions = {
open: () => {},
togglePin: () => {},
+ setPinned: () => {},
archive: () => {},
remove: () => {},
};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
index 585cda8e7b4b..8bc5941de337 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
@@ -19,6 +19,7 @@ import { formatRelativeTimeShort } from "@posthog/shared";
import { ChannelItemHoverCard } from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";
import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
import {
+ type TaskRowBulkMenu,
TaskRowContextMenu,
type TaskRowMenuProps,
} from "@posthog/ui/features/canvas/components/TaskRowMenu";
@@ -54,6 +55,8 @@ import {
export interface ChannelItemActions {
open: (item: ChannelItemModel) => void;
togglePin: (item: ChannelItemModel) => void;
+ /** Pins or unpins a whole batch, which a drag over the pinned run applies. */
+ setPinned: (items: ChannelItemModel[], pinned: boolean) => void;
archive: (item: ChannelItemModel) => void;
/** Canvases only — a task is archived, not deleted. */
remove: (item: ChannelItemModel) => void;
@@ -244,6 +247,8 @@ export function ChannelItemRow({
onEditCancel,
onDragStart,
onDragEnd,
+ bulk,
+ onContextMenuOpenChange,
}: {
item: ChannelItemModel;
/** The space this row is listed under, ticked in the menu's "File to…". */
@@ -266,6 +271,13 @@ export function ChannelItemRow({
/** Only the space sidebar passes these; they drive its pin/unpin drag. */
onDragStart?: (e: DragEvent) => void;
onDragEnd?: (e: DragEvent) => void;
+ /**
+ * Present when this row is inside a multi-session selection, which its
+ * right-click menu then acts on instead of the row alone. The confirm behind
+ * `onArchive` belongs to the list, which owns the selection.
+ */
+ bulk?: TaskRowBulkMenu | null;
+ onContextMenuOpenChange?: (open: boolean) => void;
}) {
const status = useChannelTaskStatus(item);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
@@ -352,7 +364,13 @@ export function ChannelItemRow({
// definition, so the two can't drift.
return (
<>
- <TaskRowContextMenu menu={menu}>{tipped}</TaskRowContextMenu>
+ <TaskRowContextMenu
+ menu={menu}
+ bulk={bulk}
+ onOpenChange={onContextMenuOpenChange}
+ >
+ {tipped}
+ </TaskRowContextMenu>
{/* The same confirm the artifacts grid and the canvas header show: a
canvas goes for everyone in the space, so it isn't a one-click action
however small the row is. The undo window still follows. */}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx
index 9c208ea55457..1b44310d2776 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx
@@ -18,7 +18,6 @@ import {
PINNED_SECTION_KEY,
sortChannelItems,
} from "@posthog/core/canvas/channelItems";
-import { computeEffectiveBulkIds } from "@posthog/core/sidebar/selection";
import {
Button,
cn,
@@ -57,9 +56,11 @@ import { placeTaskInCommandCenter } from "@posthog/ui/features/command-center/pl
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 { SidebarBulkActionBar } from "@posthog/ui/features/sidebar/components/SidebarBulkActionBar";
import { SidebarItem } from "@posthog/ui/features/sidebar/components/SidebarItem";
+import { taskDragSiblings } from "@posthog/ui/features/sidebar/taskDrag";
import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";
+import { useBulkArchiveConfirm } from "@posthog/ui/features/sidebar/useBulkArchiveConfirm";
import { useClearSelectionOnEscape } from "@posthog/ui/features/sidebar/useClearSelectionOnEscape";
import { useMarqueeSelection } from "@posthog/ui/features/sidebar/useMarqueeSelection";
import { usePinDrag } from "@posthog/ui/features/sidebar/usePinDrag";
@@ -68,7 +69,14 @@ import { useRenameTask } from "@posthog/ui/features/tasks/useTaskMutations";
import { logger } from "@posthog/ui/shell/logger";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { motion, useReducedMotion } from "framer-motion";
-import { Fragment, useEffect, useMemo, useRef, useState } from "react";
+import {
+ Fragment,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
const RECENTS_CAP = 30;
const log = logger.scope("channel-sidebar");
@@ -421,40 +429,49 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
const listAnchorRef = useRef<HTMLDivElement | null>(null);
const marquee = useMarqueeSelection(listAnchorRef);
const prefersReducedMotion = useReducedMotion();
+ // A drag that starts on a selected row carries the whole selection, so a pin
+ // or an unpin applies to every row the user picked, not just the grabbed one.
+ const dragSiblingsFor = useCallback(
+ (item: ChannelItemModel) =>
+ item.kind === "task"
+ ? taskDragSiblings(item.id, recentItems, (candidate) =>
+ candidate.kind === "task" ? candidate.id : null,
+ )
+ : [],
+ [recentItems],
+ );
const pinDrag = usePinDrag<ChannelItemModel>({
isPinned: (item) => item.pinned,
- togglePin: actions.togglePin,
+ setPinned: actions.setPinned,
+ getDragSiblings: dragSiblingsFor,
});
useEffect(() => {
pruneSelection(selectableTaskIds);
}, [selectableTaskIds, pruneSelection]);
- // Bulk actions include the open session, but selection styling stays tied to
- // explicit picks so selecting another row does not highlight the open row.
- // Only a task-kind active row folds in; a canvas can't join a session batch.
+ // A bulk action acts on exactly the rows that are highlighted. The open
+ // session used to be folded in as well, which told you "2 selected" after one
+ // cmd-click and archived a session you never picked.
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);
+ const selected = new Set(selectedTaskIds);
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]);
+ }, [recentItems, selectedTaskIds]);
const selectedTasksRunState = useChannelTasksRunState(selectedTasks);
const bulkActions = useSidebarBulkActions(
- effectiveBulkIds,
+ selectedTaskIds,
selectedTasksRunState,
);
+ const archiveConfirm = useBulkArchiveConfirm(bulkActions);
const handleRowClick = (item: ChannelItemModel, e: React.MouseEvent) => {
if (item.kind !== "task") {
@@ -532,64 +549,82 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
// Every row gets the wrapper, not just the dragged one. Swapping a row
// between wrapped and bare remounts it, and Chromium ends a native drag the
// moment its source leaves the DOM.
- const taskRow = (item: (typeof items)[number], showPinBadge: boolean) => (
- <motion.div
- key={item.key}
- initial={false}
- animate={
- item.key === pinDrag.drag?.item.key
- ? { height: 0, opacity: 0 }
- : { height: "auto", opacity: 1 }
- }
- transition={rowTransition}
- className="overflow-hidden"
- >
- <ChannelItemRow
- item={item}
- channelId={channelId}
- isActive={item.key === activeKey}
- isSelected={item.kind === "task" && selectedTaskIds.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
- }
- // Undefined disables the menu item: a full command centre has nowhere to
- // put the task, and an action that silently does nothing is worse than a
- // greyed-out one.
- onAddToCommandCenter={
- item.kind === "task" && !commandCenterCells.includes(item.id)
- ? commandCenterAssigner(item.id, item.title)
- : undefined
+ const taskRow = (item: (typeof items)[number], showPinBadge: boolean) => {
+ const inSelection =
+ item.kind === "task" && selectedTaskIds.includes(item.id);
+ return (
+ <motion.div
+ key={item.key}
+ initial={false}
+ animate={
+ pinDrag.drag?.items.some((dragged) => dragged.key === item.key)
+ ? { height: 0, opacity: 0 }
+ : { height: "auto", opacity: 1 }
}
- onEditSubmit={
- item.kind === "task"
- ? async (newTitle) => {
- setEditingTaskId(null);
- try {
- await renameTask({
- taskId: item.id,
- currentTitle: item.title,
- newTitle,
- });
- } catch (error) {
- log.error("Failed to rename task", error);
+ transition={rowTransition}
+ className="overflow-hidden"
+ >
+ <ChannelItemRow
+ item={item}
+ channelId={channelId}
+ isActive={item.key === activeKey}
+ isSelected={inSelection}
+ showPinBadge={showPinBadge}
+ // Right-clicking inside a selection acts on the selection; right-clicking
+ // outside it drops the selection first, so the menu that opens is about
+ // the row under the pointer and nothing else.
+ bulk={
+ inSelection && selectedTaskIds.length > 1
+ ? {
+ actions: bulkActions,
+ onArchive: archiveConfirm.requestArchive,
}
- }
- : undefined
- }
- onEditCancel={() => setEditingTaskId(null)}
- onDragStart={
- item.kind === "task"
- ? (event) => pinDrag.onItemDragStart(item, event)
- : undefined
- }
- onDragEnd={item.kind === "task" ? pinDrag.onItemDragEnd : undefined}
- />
- </motion.div>
- );
+ : null
+ }
+ onContextMenuOpenChange={(open) => {
+ if (open && !inSelection) clearSelection();
+ }}
+ actions={actions}
+ onClick={(e) => handleRowClick(item, e)}
+ isEditing={item.kind === "task" && editingTaskId === item.id}
+ onRename={
+ item.kind === "task" ? () => setEditingTaskId(item.id) : undefined
+ }
+ // Undefined disables the menu item: a full command centre has nowhere to
+ // put the task, and an action that silently does nothing is worse than a
+ // greyed-out one.
+ onAddToCommandCenter={
+ item.kind === "task" && !commandCenterCells.includes(item.id)
+ ? commandCenterAssigner(item.id, item.title)
+ : undefined
+ }
+ onEditSubmit={
+ item.kind === "task"
+ ? async (newTitle) => {
+ setEditingTaskId(null);
+ try {
+ await renameTask({
+ taskId: item.id,
+ currentTitle: item.title,
+ newTitle,
+ });
+ } catch (error) {
+ log.error("Failed to rename task", error);
+ }
+ }
+ : undefined
+ }
+ onEditCancel={() => setEditingTaskId(null)}
+ onDragStart={
+ item.kind === "task"
+ ? (event) => pinDrag.onItemDragStart(item, event)
+ : undefined
+ }
+ onDragEnd={item.kind === "task" ? pinDrag.onItemDragEnd : undefined}
+ />
+ </motion.div>
+ );
+ };
// Label comes from the shared space-page table, so a sidebar row and the
// header breadcrumb for the same page can never disagree. No icon: this is a
@@ -756,10 +791,12 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
{/* 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
+ <SidebarBulkActionBar
actions={bulkActions}
onClearSelection={clearSelection}
+ onArchive={archiveConfirm.requestArchive}
/>
+ {archiveConfirm.dialog}
{pinDrag.drag ? (
<ChannelItemDragPreview
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
index 6f37d40c4684..44773cc8e37a 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
@@ -8,6 +8,7 @@ import {
SquaresFourIcon,
TrashIcon,
} from "@phosphor-icons/react";
+import { sessionsLabel } from "@posthog/core/sidebar/selection";
import {
Button,
ContextMenu,
@@ -23,6 +24,7 @@ import { PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";
import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
import { useFileTaskToChannel } from "@posthog/ui/features/canvas/hooks/useFileTaskToChannel";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import type { SidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";
import {
type MenuFlyoutItem,
MenuSubFlyout,
@@ -168,6 +170,79 @@ function TaskRowMenuItems({
);
}
+/**
+ * What a right-click does when the row it landed on is part of a selection: the
+ * same four actions the selection bar offers, so the two paths can't drift.
+ * Archiving asks first, and the caller owns that confirm because it outlives
+ * the menu.
+ */
+export interface TaskRowBulkMenu {
+ actions: SidebarBulkActions;
+ onArchive: () => void;
+}
+
+function TaskRowBulkMenuItems({
+ parts,
+ bulk,
+}: {
+ parts: MenuParts;
+ bulk: TaskRowBulkMenu;
+}) {
+ const { Item, Sub, SubTrigger } = parts;
+ const { actions } = bulk;
+ const sessions = sessionsLabel(actions.selectedCount);
+ // No tick: a batch can span spaces, so there is no one channel to mark.
+ const channelItems: MenuFlyoutItem[] = actions.channels.map((channel) => ({
+ id: channel.id,
+ label: channel.name,
+ current: false,
+ starred: channel.starred,
+ }));
+
+ return (
+ <>
+ <Item disabled={actions.isPinning} onClick={actions.pinSelected}>
+ {actions.pinDirection === "pin" ? (
+ <PushPinIcon size={14} />
+ ) : (
+ <PushPinSlashIcon size={14} />
+ )}
+ {actions.pinLabel}
+ </Item>
+ <Item onClick={actions.addSelectedToCommandCenter}>
+ <SquaresFourIcon size={14} />
+ Add {sessions} to Command Center
+ </Item>
+ {channelItems.length > 0 && (
+ <Sub>
+ <SubTrigger>
+ <FolderSimpleIcon size={14} />
+ File {sessions} to…
+ </SubTrigger>
+ <MenuSubFlyout className="w-64 p-0">
+ <SearchableMenuFlyout
+ items={channelItems}
+ placeholder="Search spaces…"
+ emptyLabel="No spaces"
+ onSelect={(channelId) => void actions.fileSelectedTo(channelId)}
+ />
+ </MenuSubFlyout>
+ </Sub>
+ )}
+ {/* The ellipsis is the promise that a confirm follows: a bulk archive has
+ no undo toast behind it. */}
+ <Item
+ variant="destructive"
+ disabled={actions.isArchiving}
+ onClick={bulk.onArchive}
+ >
+ <ArchiveIcon size={14} />
+ Archive {sessions}…
+ </Item>
+ </>
+ );
+}
+
/**
* The same actions as a plain list, for a surface that is already open — the
* row's hover card. Rows are quill buttons rather than menu items because
@@ -238,21 +313,35 @@ export function TaskRowMenuList({
);
}
-/** The same menu on right-click, wrapping the row. */
+/**
+ * The same menu on right-click, wrapping the row. A row inside a multi-session
+ * selection gets the selection's menu instead of its own: acting on one row
+ * while four are highlighted is the surprise this avoids.
+ */
export function TaskRowContextMenu({
menu,
+ bulk,
+ onOpenChange,
children,
}: {
menu: TaskRowMenuProps;
+ bulk?: TaskRowBulkMenu | null;
+ onOpenChange?: (open: boolean) => void;
children: ReactNode;
}) {
return (
- <ContextMenu>
+ <ContextMenu onOpenChange={onOpenChange}>
<ContextMenuTrigger render={<div className="min-w-0" />}>
{children}
</ContextMenuTrigger>
- <ContextMenuContent className="w-56">
- <TaskRowMenuItems parts={CONTEXT_PARTS} menu={menu} />
+ {/* Wider for a batch: its labels carry a count and a noun ("Add 6
+ sessions to Command Center"), which the row's own labels don't. */}
+ <ContextMenuContent className={bulk ? "w-72" : "w-56"}>
+ {bulk ? (
+ <TaskRowBulkMenuItems parts={CONTEXT_PARTS} bulk={bulk} />
+ ) : (
+ <TaskRowMenuItems parts={CONTEXT_PARTS} menu={menu} />
+ )}
</ContextMenuContent>
</ContextMenu>
);
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
index 408164d2e5c3..4bb55c1a53c6 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
@@ -1,3 +1,4 @@
+import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
import { renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Channel } from "./useChannels";
@@ -22,9 +23,11 @@ const mocks = vi.hoisted(() => ({
// Stable identities, mirroring the real hooks — a fresh function per render
// would hide the very memoization this file asserts.
setPinned: vi.fn(),
+ setPinnedMany: vi.fn(),
togglePin: vi.fn(),
archiveTask: vi.fn(),
navigate: vi.fn(),
+ toastError: vi.fn(),
}));
vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
@@ -56,8 +59,17 @@ vi.mock("@posthog/ui/features/sidebar/usePinnedTasks", () => ({
usePinnedTasks: () => ({
pinnedTaskIds: new Set<string>(),
togglePin: mocks.togglePin,
+ setPinnedMany: mocks.setPinnedMany,
}),
}));
+vi.mock("@posthog/ui/primitives/toast", () => ({
+ toast: {
+ error: mocks.toastError,
+ success: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+ },
+}));
// The session facts behind the status and environment filters. All three reach
// the host — for live sessions, viewed timestamps and workspaces — and this
// suite is about which items the hook builds, not what they say.
@@ -99,6 +111,28 @@ function channel(over: Partial<Channel> = {}): Channel {
};
}
+function taskItem(id: string): ChannelItemModel {
+ return {
+ key: id,
+ kind: "task",
+ id,
+ title: id,
+ ts: 0,
+ createdAt: 0,
+ pinned: false,
+ rawStatus: null,
+ environment: null,
+ source: null,
+ needsInput: false,
+ unread: false,
+ authorUser: null,
+ authorName: null,
+ authorUuid: null,
+ templateId: null,
+ task: null,
+ };
+}
+
function canvas(id: string, createdBy?: string, createdByUuid?: string) {
return {
id,
@@ -237,4 +271,45 @@ describe("useChannelItems", () => {
rerender();
expect(result.current.items.map((item) => item.id)).toEqual(["task-1"]);
});
+
+ // A dragged session batch's pin request settles per-row and reports failures
+ // in `failed` rather than rejecting, so the action must inspect that result —
+ // a shared Promise.all would read a failed batch as success and stay silent.
+ it.each([
+ [
+ "a partial pin failure",
+ true,
+ { succeeded: ["a"], failed: ["b"] },
+ "1 pinned, 1 failed",
+ ],
+ [
+ "a partial unpin failure",
+ false,
+ { succeeded: ["a"], failed: ["b"] },
+ "1 unpinned, 1 failed",
+ ],
+ [
+ "a fully successful batch",
+ true,
+ { succeeded: ["a", "b"], failed: [] },
+ null,
+ ],
+ ] as const)(
+ "reports %s from a session batch pin",
+ async (_label, pinned, outcome, expectedMessage) => {
+ mocks.channels = { channels: [channel()], isLoading: false };
+ mocks.setPinnedMany.mockResolvedValue(outcome);
+
+ const { result } = renderHook(() => useChannelItems("c1"));
+ result.current.actions.setPinned([taskItem("a"), taskItem("b")], pinned);
+ await mocks.setPinnedMany.mock.results.at(-1)?.value;
+
+ expect(mocks.setPinnedMany).toHaveBeenCalledWith(["a", "b"], pinned);
+ if (expectedMessage === null) {
+ expect(mocks.toastError).not.toHaveBeenCalled();
+ } else {
+ expect(mocks.toastError).toHaveBeenCalledWith(expectedMessage);
+ }
+ },
+ );
});
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx
index 2c05521f7599..ff5c9a5f9dd0 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx
@@ -4,6 +4,7 @@ import {
type ChannelItemOwner,
type ChannelSessionFacts,
} from "@posthog/core/canvas/channelItems";
+import { formatBulkResult } from "@posthog/core/sidebar/selection";
import type { WorkspaceMode } from "@posthog/shared";
import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";
import { useArchiveTask } from "@posthog/ui/features/archive/useArchiveTask";
@@ -61,7 +62,7 @@ export function useChannelItems(channelId: string): {
showAllUsers: true,
});
const archivedTaskIds = useArchivedTaskIds();
- const { pinnedTaskIds, togglePin } = usePinnedTasks();
+ const { pinnedTaskIds, togglePin, setPinnedMany } = usePinnedTasks();
const { archiveTask } = useArchiveTask({ navigateSpace: "website" });
const { setPinned: setCanvasPinned, invalidateDashboards } =
useDashboardMutations();
@@ -163,6 +164,42 @@ export function useChannelItems(channelId: string): {
toast.error("Couldn't update pin");
});
},
+ // One request for the sessions and one per canvas, rather than a toggle
+ // per row: pinning is a scoped mutation, so a row-at-a-time batch waits
+ // out a round trip for each one.
+ setPinned: (items, pinned) => {
+ const taskIds = items
+ .filter((item) => item.kind === "task")
+ .map((item) => item.id);
+ const canvases = items.filter((item) => item.kind === "canvas");
+
+ // setPinnedMany settles every request itself and reports failures in
+ // `failed` rather than rejecting, so a shared Promise.all would read a
+ // failed session batch as success — check its result on its own.
+ if (taskIds.length > 0) {
+ setPinnedMany(taskIds, pinned)
+ .then(({ succeeded, failed }) => {
+ if (failed.length === 0) return;
+ const { message } = formatBulkResult(
+ pinned ? "pinned" : "unpinned",
+ { succeeded: succeeded.length, failed: failed.length },
+ );
+ toast.error(message);
+ })
+ .catch(() => {
+ toast.error(`Couldn't ${pinned ? "pin" : "unpin"} the sessions`);
+ });
+ }
+
+ const canvasPins = canvases.map((canvas) =>
+ setCanvasPinned(canvas.id, pinned),
+ );
+ if (canvasPins.length > 0) {
+ Promise.all(canvasPins).catch(() => {
+ toast.error("Couldn't update pin");
+ });
+ }
+ },
archive: (item) => {
void archiveTask({ taskId: item.id });
},
@@ -185,6 +222,7 @@ export function useChannelItems(channelId: string): {
navigate,
setCanvasPinned,
togglePin,
+ setPinnedMany,
archiveTask,
invalidateDashboards,
],
diff --git a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterGrid.tsx b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterGrid.tsx
index 4273b5f4c4b4..883d2af91c29 100644
--- a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterGrid.tsx
+++ b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterGrid.tsx
@@ -6,10 +6,12 @@ import {
} from "@posthog/core/command-center/grid";
import { Button } from "@posthog/quill";
import {
+ consumeTaskDrop,
readTaskDragData,
TASK_DRAG_TYPE,
TASK_IDS_DRAG_TYPE,
} from "@posthog/ui/features/sidebar/taskDrag";
+import { useLiveTaskIds } from "@posthog/ui/features/tasks/useLiveTaskIds";
import { destroyShellTerminal } from "@posthog/ui/features/terminal/destroyShellTerminal";
import { useCallback, useEffect, useRef, useState } from "react";
import { FOCUSABLE_SELECTOR } from "../../../utils/overlay";
@@ -91,7 +93,11 @@ function useTaskDropTarget(onTasks: (taskIds: string[]) => void) {
e.preventDefault();
setIsOver(false);
const taskIds = readTaskDragData(e.dataTransfer);
- if (taskIds.length > 0) onTasks(taskIds);
+ if (taskIds.length === 0) return;
+ // Filing is what this drop was for, so the pin drag behind the same
+ // gesture leaves the sessions pinned where they were.
+ consumeTaskDrop();
+ onTasks(taskIds);
},
};
}
@@ -173,14 +179,15 @@ function GridCell({
[markActive],
);
+ const liveTaskIds = useLiveTaskIds();
const placeInCell = useCallback(
(taskIds: string[]) => {
if (cell.terminalId) {
destroyShellTerminal(getTerminalCellStateKey(cell.terminalId));
}
- placeTasksInCommandCenterCell(taskIds, cell.cellIndex);
+ placeTasksInCommandCenterCell(taskIds, cell.cellIndex, liveTaskIds);
},
- [cell.cellIndex, cell.terminalId],
+ [cell.cellIndex, cell.terminalId, liveTaskIds],
);
const dropTarget = useTaskDropTarget(placeInCell);
@@ -254,10 +261,11 @@ function ExpandSlot({
slot: number;
placement: PlacementState;
}) {
+ const liveTaskIds = useLiveTaskIds();
const expand = useCallback(
(taskIds: string[]) =>
- expandTasksInCommandCenterInto(direction, slot, taskIds),
- [direction, slot],
+ expandTasksInCommandCenterInto(direction, slot, taskIds, liveTaskIds),
+ [direction, liveTaskIds, slot],
);
const dropTarget = useTaskDropTarget(expand);
const { cols, rows } = getGridDimensions(expanded);
diff --git a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.test.ts b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.test.ts
index d1e0b1a59862..c136e516ec7b 100644
--- a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.test.ts
+++ b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.test.ts
@@ -17,14 +17,32 @@ describe("placeTasksInCommandCenterCell", () => {
});
});
- it("places the grabbed task in the drop target and the rest in available cells", () => {
- placeTasksInCommandCenterCell(["dragged", "selected-2", "selected-3"], 0);
+ // The grabbed task is written into the drop target first, then the rest are
+ // placed around it. A live set that predates the grabbed task (unknown, or
+ // scoped so it never listed it) must not let that second pass tile over it.
+ const liveSets: Array<[string, ReadonlySet<string> | null]> = [
+ ["an unknown live set", null],
+ [
+ "a live set missing the grabbed task",
+ new Set(["existing", "selected-2", "selected-3"]),
+ ],
+ ];
- expect(useCommandCenterStore.getState().cells).toEqual([
- "dragged",
- "selected-2",
- "selected-3",
- null,
- ]);
- });
+ it.each(liveSets)(
+ "keeps the grabbed task in the drop target with %s",
+ (_label, liveTaskIds) => {
+ placeTasksInCommandCenterCell(
+ ["dragged", "selected-2", "selected-3"],
+ 0,
+ liveTaskIds,
+ );
+
+ expect(useCommandCenterStore.getState().cells).toEqual([
+ "dragged",
+ "selected-2",
+ "selected-3",
+ null,
+ ]);
+ },
+ );
});
diff --git a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts
index c90da9ab658a..28ca160a6bea 100644
--- a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts
+++ b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts
@@ -55,16 +55,33 @@ export function placeTasksInCommandCenter(
};
}
+/**
+ * The live set widened to cover a task just written into a tile. A `null` set
+ * already holds every filled tile, so the assigned task is safe there; a known
+ * set can lag behind a task created elsewhere, and without the id the batch
+ * would tile over the very cell it was just placed in.
+ */
+function withAssignedTask(
+ liveTaskIds: ReadonlySet<string> | null,
+ taskId: string,
+): ReadonlySet<string> | null {
+ return liveTaskIds == null ? null : new Set([...liveTaskIds, taskId]);
+}
+
export function placeTasksInCommandCenterCell(
taskIds: string[],
cellIndex: number,
+ liveTaskIds: ReadonlySet<string> | null,
): void {
const [firstTaskId, ...remainingTaskIds] = taskIds;
if (!firstTaskId) return;
useCommandCenterStore.getState().assignTask(cellIndex, firstTaskId);
if (remainingTaskIds.length > 0) {
- placeTasksInCommandCenter(remainingTaskIds, null);
+ placeTasksInCommandCenter(
+ remainingTaskIds,
+ withAssignedTask(liveTaskIds, firstTaskId),
+ );
}
}
@@ -72,6 +89,7 @@ export function expandTasksInCommandCenterInto(
direction: ExpandDirection,
slot: number,
taskIds: string[],
+ liveTaskIds: ReadonlySet<string> | null,
): void {
const [firstTaskId, ...remainingTaskIds] = taskIds;
if (!firstTaskId) return;
@@ -85,6 +103,9 @@ export function expandTasksInCommandCenterInto(
.getState()
.assignTask(getExpansionCellIndex(expanded, direction, slot), firstTaskId);
if (remainingTaskIds.length > 0) {
- placeTasksInCommandCenter(remainingTaskIds, null);
+ placeTasksInCommandCenter(
+ remainingTaskIds,
+ withAssignedTask(liveTaskIds, firstTaskId),
+ );
}
}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/DragBatchLabel.tsx b/products/desktop/packages/ui/src/features/sidebar/components/DragBatchLabel.tsx
new file mode 100644
index 000000000000..1ce026e5a3ea
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sidebar/components/DragBatchLabel.tsx
@@ -0,0 +1,11 @@
+import { sessionsLabel } from "@posthog/core/sidebar/selection";
+import type { ReactElement } from "react";
+
+/** What a drag preview says in place of a row once it carries a whole batch. */
+export function DragBatchLabel({ count }: { count: number }): ReactElement {
+ return (
+ <div className="px-3 py-2 font-medium text-[13px]">
+ Moving {sessionsLabel(count)}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.tsx
index dc449f8bf32f..e2dcc898689d 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.tsx
@@ -7,6 +7,7 @@ import {
XIcon,
} from "@phosphor-icons/react";
import { channelDisplayLabel } from "@posthog/core/canvas/channelName";
+import { sessionsLabel } from "@posthog/core/sidebar/selection";
import {
Button,
DropdownMenu,
@@ -91,7 +92,7 @@ export function SidebarBulkActionBar({
isFiling,
} = actions;
- const sessions = selectedCount === 1 ? "session" : "sessions";
+ const sessions = sessionsLabel(selectedCount);
return (
<>
@@ -99,7 +100,7 @@ export function SidebarBulkActionBar({
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` : ""}
+ {selectedCount > 0 ? `${sessions} selected` : ""}
</span>
{selectedCount > 0 && (
@@ -128,7 +129,7 @@ export function SidebarBulkActionBar({
</ActionButton>
<ActionButton
- label={`Add ${selectedCount} ${sessions} to Command Center`}
+ label={`Add ${sessions} to Command Center`}
disabledReason={commandCenterDisabledReason}
onClick={actions.addSelectedToCommandCenter}
>
@@ -138,7 +139,7 @@ export function SidebarBulkActionBar({
{fileDisabledReason === null ? (
<DropdownMenu>
<ActionButton
- label={`File ${selectedCount} ${sessions} to a channel`}
+ label={`File ${sessions} to a channel`}
disabledReason={null}
loading={isFiling}
wrapTrigger={(button) => (
@@ -161,7 +162,7 @@ export function SidebarBulkActionBar({
) : null}
<ActionButton
- label={`Archive ${selectedCount} ${sessions}`}
+ label={`Archive ${sessions}`}
disabledReason={archiveDisabledReason}
loading={isArchiving}
onClick={onArchive}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.tsx
deleted file mode 100644
index 379f17977715..000000000000
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-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.tsx
index 99a660cd2b08..07fb87786463 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsx
@@ -76,15 +76,19 @@ export function SidebarItem({
type="button"
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)",
+ "disabled:opacity-100",
+ // The open row keeps its neutral background on its own, and takes the
+ // accent only once it is part of a selection, a shade above the rows
+ // picked around it.
+ isActive && (isSelected ? "bg-primary/20" : "bg-fill-selected"),
+ !isActive && isSelected && "bg-primary/10",
// 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-['']",
+ "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-primary 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}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
index 33f6298df6ea..590aabefff57 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
@@ -1,9 +1,9 @@
import { findGroupFolder } from "@posthog/core/sidebar/groupTasks";
import {
- computeEffectiveBulkIds,
computeOrderedVisibleTaskIds,
computePriorTaskIds,
formatArchiveResult,
+ formatBulkResult,
} from "@posthog/core/sidebar/selection";
import { isTaskActivelyRunning } from "@posthog/core/sidebar/taskRunning";
import { resolveBulkTaskContextMenuIntent } from "@posthog/core/tasks/contextMenuActions";
@@ -22,6 +22,7 @@ import { StopCloudRunDialog } from "@posthog/ui/features/sessions/components/Sto
import { useArchivingTasksStore } from "@posthog/ui/features/sidebar/archivingTasksStore";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";
+import { useBulkArchiveConfirm } from "@posthog/ui/features/sidebar/useBulkArchiveConfirm";
import { useClearSelectionOnEscape } from "@posthog/ui/features/sidebar/useClearSelectionOnEscape";
import { useMarqueeSelection } from "@posthog/ui/features/sidebar/useMarqueeSelection";
import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
@@ -43,7 +44,7 @@ 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 { SidebarBulkActionBar } from "./SidebarBulkActionBar";
import { SidebarItem } from "./SidebarItem";
import { TaskListView } from "./TaskListView";
@@ -71,7 +72,7 @@ function SidebarMenuComponent() {
useTaskContextMenu();
const { archiveTask } = useArchiveTask();
const { renameTask } = useRenameTask();
- const { togglePin } = usePinnedTasks();
+ const { togglePin, setPinnedMany } = usePinnedTasks();
const sidebarData = useSidebarData({
activeView: view,
@@ -172,15 +173,13 @@ function SidebarMenuComponent() {
pruneSelection(allSidebarTaskIds);
}, [allSidebarTaskIds, pruneSelection]);
- // Bulk actions include the routed task, but selection styling stays tied to
- // explicit picks so selecting another row does not highlight the open row.
+ // A bulk action acts on exactly the rows that are highlighted. The routed
+ // task used to be folded in as well, which told you "2 selected" after one
+ // cmd-click and archived a session you never picked.
const activeTaskId = sidebarData.activeTaskId;
- const effectiveBulkIds = useMemo(
- () => computeEffectiveBulkIds(selectedTaskIds, activeTaskId),
- [activeTaskId, selectedTaskIds],
- );
- const bulkActions = useSidebarBulkActions(effectiveBulkIds, allSidebarTasks);
+ const bulkActions = useSidebarBulkActions(selectedTaskIds, allSidebarTasks);
+ const bulkArchiveConfirm = useBulkArchiveConfirm(bulkActions);
const handleTaskClick = (taskId: string, e: React.MouseEvent) => {
// Ignore clicks on a row that's mid-archive.
@@ -301,13 +300,16 @@ function SidebarMenuComponent() {
return;
}
- // Bulk menu when 2+ tasks are in the effective selection (active + cmd/shift-clicked)
- // and the right-clicked task is one of them. Otherwise clear and fall through.
- if (effectiveBulkIds.length > 1) {
- if (effectiveBulkIds.includes(taskId)) {
+ // Bulk menu when 2+ rows are selected and the right-clicked row is one of
+ // them. A right-click outside the selection clears it first, so the row menu
+ // that follows is about the row under the pointer — the same rule the space
+ // sidebar applies in ChannelSidebar.
+ if (selectedTaskIds.includes(taskId)) {
+ if (selectedTaskIds.length > 1) {
handleBulkContextMenu(e);
return;
}
+ } else if (selectedTaskIds.length > 0) {
clearSelection();
}
@@ -412,6 +414,33 @@ function SidebarMenuComponent() {
[togglePin],
);
+ // One request for the batch rather than a toggle per row: pinning is a scoped
+ // mutation, so a row-at-a-time batch waits out a round trip for each one.
+ const handleTasksSetPinned = useCallback(
+ async (taskIds: string[], pinned: boolean) => {
+ const archiving = useArchivingTasksStore.getState();
+ const eligible = taskIds.filter((id) => !archiving.isArchiving(id));
+ if (eligible.length === 0) return;
+ try {
+ // setPinnedMany settles every request itself and reports the failures
+ // in `failed` rather than rejecting, so surface them the same way the
+ // bulk action bar does — a bare .catch() never sees a partial failure.
+ const { succeeded, failed } = await setPinnedMany(eligible, pinned);
+ if (failed.length > 0) {
+ const { message } = formatBulkResult(pinned ? "pinned" : "unpinned", {
+ succeeded: succeeded.length,
+ failed: failed.length,
+ });
+ toast.error(message);
+ }
+ } catch (error) {
+ log.error("Failed to set pinned sessions", error);
+ toast.error(`Couldn't ${pinned ? "pin" : "unpin"} the sessions`);
+ }
+ },
+ [setPinnedMany],
+ );
+
const handleArchivePrior = useCallback(
async (taskId: string) => {
const priorTaskIds = computePriorTaskIds(allSidebarTasks, taskId);
@@ -493,6 +522,7 @@ function SidebarMenuComponent() {
onTaskContextMenu={handleTaskContextMenu}
onTaskArchive={handleTaskArchive}
onTaskTogglePin={handleTaskTogglePin}
+ onTasksSetPinned={handleTasksSetPinned}
onTaskEditSubmit={handleTaskEditSubmit}
onTaskEditCancel={handleTaskEditCancel}
onGroupContextMenu={handleGroupContextMenu}
@@ -505,10 +535,12 @@ function SidebarMenuComponent() {
{/* 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
+ <SidebarBulkActionBar
actions={bulkActions}
onClearSelection={clearSelection}
+ onArchive={bulkArchiveConfirm.requestArchive}
/>
+ {bulkArchiveConfirm.dialog}
<ArchiveRunningTaskDialog
open={archiveConfirm !== null}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx
index 4fe7c4e65869..b25c6967a925 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx
@@ -15,11 +15,16 @@ import { cn, MenuLabel, Text } from "@posthog/quill";
import { builderHog } from "@posthog/ui/assets/hedgehogs";
import { useFolders } from "@posthog/ui/features/folders/useFolders";
import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { DragBatchLabel } from "@posthog/ui/features/sidebar/components/DragBatchLabel";
import { DraggableFolder } from "@posthog/ui/features/sidebar/components/DraggableFolder";
import { GroupWorktreesSection } from "@posthog/ui/features/sidebar/components/GroupWorktreesSection";
import { SidebarSection } from "@posthog/ui/features/sidebar/components/SidebarSection";
import { TaskRow } from "@posthog/ui/features/sidebar/components/TaskRow";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
+import {
+ dragSiblingCandidates,
+ taskDragSiblings,
+} from "@posthog/ui/features/sidebar/taskDrag";
import {
getPinnedInsertionIndex,
type TaskTimestampKey,
@@ -51,6 +56,8 @@ interface TaskListViewProps {
) => void;
onTaskArchive: (taskId: string) => void;
onTaskTogglePin: (taskId: string) => void;
+ /** Pins or unpins a whole batch, which a drag over the pinned run applies. */
+ onTasksSetPinned: (taskIds: string[], pinned: boolean) => void;
onTaskEditSubmit: (
taskId: string,
currentTitle: string,
@@ -77,6 +84,7 @@ export function TaskListView({
onTaskContextMenu,
onTaskArchive,
onTaskTogglePin,
+ onTasksSetPinned,
onTaskEditSubmit,
onTaskEditCancel,
onGroupContextMenu,
@@ -103,9 +111,29 @@ export function TaskListView({
const isOnTaskInput =
view.type === "task-input" || view.type === "task-pending";
const prefersReducedMotion = useReducedMotion();
+ // A drag that starts on a selected row carries the whole selection, so a pin
+ // or an unpin applies to every row the user picked, not just the grabbed one.
+ const allTasks = useMemo(
+ () =>
+ dragSiblingCandidates(organizeMode, {
+ pinnedTasks,
+ flatTasks,
+ groupedTasks,
+ }),
+ [organizeMode, pinnedTasks, flatTasks, groupedTasks],
+ );
+ const dragSiblingsFor = useCallback(
+ (task: TaskData) => taskDragSiblings(task.id, allTasks, (t) => t.id),
+ [allTasks],
+ );
const pinDrag = usePinDrag<TaskData>({
isPinned: (task) => task.isPinned,
- togglePin: (task) => onTaskTogglePin(task.id),
+ setPinned: (tasks, pinned) =>
+ onTasksSetPinned(
+ tasks.map((task) => task.id),
+ pinned,
+ ),
+ getDragSiblings: dragSiblingsFor,
});
const dragState = pinDrag.drag;
@@ -147,8 +175,13 @@ export function TaskListView({
opacity: { duration: 0.1 },
};
+ const draggedIdSet = useMemo(
+ () => new Set(dragState?.items.map((task) => task.id) ?? []),
+ [dragState],
+ );
+
const renderTaskRow = (task: TaskData, depth = 0) => {
- const isDragged = dragState?.item.id === task.id;
+ const isDragged = draggedIdSet.has(task.id);
return (
<motion.div
key={task.id}
@@ -190,10 +223,10 @@ export function TaskListView({
};
const pinnedTasksWithoutSource = pinnedTasks.filter(
- (task) => task.id !== dragState?.item.id,
+ (task) => !draggedIdSet.has(task.id),
);
const pinnedInsertionIndex = dragState
- ? getPinnedInsertionIndex(pinnedTasks, dragState.item, timestampKey)
+ ? getPinnedInsertionIndex(pinnedTasks, dragState.items[0], timestampKey)
: -1;
const showPinnedPlaceholder = Boolean(dragState?.overPinned);
const pinnedPlaceholderBeforeTaskId =
@@ -428,22 +461,26 @@ export function TaskListView({
: "border-gray-6",
)}
>
- <TaskRow
- task={dragState.item}
- isActive={false}
- isSelected={false}
- hideHoverActions
- isEditing={false}
- onClick={() => undefined}
- onDoubleClick={() => undefined}
- onContextMenu={() => undefined}
- onArchive={() => undefined}
- onTogglePin={() => undefined}
- onEditSubmit={() => undefined}
- onEditCancel={() => undefined}
- timestamp={dragState.item[timestampKey]}
- withPrStatus={false}
- />
+ {dragState.items.length > 1 ? (
+ <DragBatchLabel count={dragState.items.length} />
+ ) : (
+ <TaskRow
+ task={dragState.items[0]}
+ isActive={false}
+ isSelected={false}
+ hideHoverActions
+ isEditing={false}
+ onClick={() => undefined}
+ onDoubleClick={() => undefined}
+ onContextMenu={() => undefined}
+ onArchive={() => undefined}
+ onTogglePin={() => undefined}
+ onEditSubmit={() => undefined}
+ onEditCancel={() => undefined}
+ timestamp={dragState.items[0][timestampKey]}
+ withPrStatus={false}
+ />
+ )}
<AnimatePresence>
{isUnpinIntent ? (
<motion.span
diff --git a/products/desktop/packages/ui/src/features/sidebar/taskDrag.test.ts b/products/desktop/packages/ui/src/features/sidebar/taskDrag.test.ts
index 1a3323cfcdee..7cb45a154efe 100644
--- a/products/desktop/packages/ui/src/features/sidebar/taskDrag.test.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/taskDrag.test.ts
@@ -1,5 +1,10 @@
+import type {
+ TaskData,
+ TaskGroup,
+} from "@posthog/core/sidebar/sidebarData.types";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
+ dragSiblingCandidates,
readTaskDragData,
TASK_DRAG_TYPE,
TASK_IDS_DRAG_TYPE,
@@ -8,6 +13,25 @@ import {
} from "./taskDrag";
import { useTaskSelectionStore } from "./taskSelectionStore";
+function task(id: string, isPinned = false): TaskData {
+ return {
+ id,
+ title: id,
+ createdAt: 0,
+ lastActivityAt: 0,
+ isGenerating: false,
+ isUnread: false,
+ isPinned,
+ needsPermission: false,
+ repository: null,
+ isSuspended: false,
+ folderPath: null,
+ cloudPrUrl: null,
+ branchName: null,
+ linkedBranch: null,
+ };
+}
+
describe("task drag data", () => {
beforeEach(() => {
useTaskSelectionStore.setState({
@@ -42,4 +66,28 @@ describe("task drag data", () => {
readTaskDragData({ getData: (type) => payload.get(type) ?? "" }),
).toEqual(["b", "a"]);
});
+
+ // by-project caps each group on its own, so "c"/"d" render in the second
+ // project yet fall outside the flat top window — resolving a batch there
+ // against flatTasks would silently drop them.
+ const lists = {
+ pinnedTasks: [task("p", true)],
+ flatTasks: [task("a"), task("b")],
+ groupedTasks: [
+ { id: "proj-1", name: "proj-1", tasks: [task("a"), task("b")] },
+ { id: "proj-2", name: "proj-2", tasks: [task("c"), task("d")] },
+ ] satisfies TaskGroup[],
+ };
+
+ it.each([
+ ["by-project", ["p", "a", "b", "c", "d"]],
+ ["chronological", ["p", "a", "b"]],
+ ] as const)(
+ "resolves batch-drag candidates against the %s rendered list",
+ (mode, expectedIds) => {
+ expect(dragSiblingCandidates(mode, lists).map((t) => t.id)).toEqual(
+ expectedIds,
+ );
+ },
+ );
});
diff --git a/products/desktop/packages/ui/src/features/sidebar/taskDrag.ts b/products/desktop/packages/ui/src/features/sidebar/taskDrag.ts
index 425dc63be19b..b02c47723dd5 100644
--- a/products/desktop/packages/ui/src/features/sidebar/taskDrag.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/taskDrag.ts
@@ -1,4 +1,8 @@
import { dedupeTaskIds } from "@posthog/core/sidebar/selection";
+import type {
+ TaskData,
+ TaskGroup,
+} from "@posthog/core/sidebar/sidebarData.types";
import { taskDragIdsSchema } from "@posthog/ui/features/sidebar/schemas";
import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";
@@ -16,6 +20,77 @@ export function taskIdsForDrag(
]);
}
+/**
+ * The other sessions a drag on `grabbedId` carries: the rest of the selection
+ * when the grabbed row belongs to one, and nothing when it doesn't. Resolved
+ * against the list that is showing, so an id the list can't place is dropped
+ * rather than travelling as a hole.
+ */
+export function taskDragSiblings<T>(
+ grabbedId: string,
+ candidates: readonly T[],
+ idOf: (item: T) => string | null,
+): T[] {
+ const siblingIds = taskIdsForDrag(
+ grabbedId,
+ useTaskSelectionStore.getState().selectedTaskIds,
+ ).filter((id) => id !== grabbedId);
+ if (siblingIds.length === 0) return [];
+
+ const byId = new Map<string, T>();
+ for (const candidate of candidates) {
+ const id = idOf(candidate);
+ if (id !== null) byId.set(id, candidate);
+ }
+ return siblingIds.flatMap((id) => {
+ const found = byId.get(id);
+ return found ? [found] : [];
+ });
+}
+
+/**
+ * The rows a batch drag resolves its siblings against: whichever list the active
+ * organize mode actually renders, plus the always-shown pinned run. by-project
+ * caps each group on its own, so a row visible there can sit past the flat
+ * window — resolving that batch against flatTasks would silently drop it.
+ */
+export function dragSiblingCandidates(
+ organizeMode: "by-project" | "chronological",
+ lists: {
+ pinnedTasks: TaskData[];
+ flatTasks: TaskData[];
+ groupedTasks: TaskGroup[];
+ },
+): TaskData[] {
+ const rendered =
+ organizeMode === "by-project"
+ ? lists.groupedTasks.flatMap((group) => group.tasks)
+ : lists.flatTasks;
+ return [...lists.pinnedTasks, ...rendered];
+}
+
+// Set by a target that takes a session drop for its own purpose, read once by
+// the pin drag that started it. A module-level flag rather than a field on the
+// event: the pin drag reads it on `dragend`, which is a different event from
+// the `drop` the target handled.
+let taskDropConsumed = false;
+
+/**
+ * Marks the session drop in flight as taken. A Command Center tile files what
+ * was dropped on it, so the pin drag behind the same gesture must not also
+ * unpin it.
+ */
+export function consumeTaskDrop(): void {
+ taskDropConsumed = true;
+}
+
+/** Reads and clears the flag, so it can't survive into the next drag. */
+export function takeConsumedTaskDrop(): boolean {
+ const consumed = taskDropConsumed;
+ taskDropConsumed = false;
+ return consumed;
+}
+
export function writeTaskDragData(
dataTransfer: Pick<DataTransfer, "setData">,
draggedTaskId: string,
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.test.tsx b/products/desktop/packages/ui/src/features/sidebar/useBulkArchiveConfirm.test.tsx
similarity index 76%
rename from products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.test.tsx
rename to products/desktop/packages/ui/src/features/sidebar/useBulkArchiveConfirm.test.tsx
index da2f3922c3fc..19fe6f1030f3 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionFooter.test.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/useBulkArchiveConfirm.test.tsx
@@ -1,8 +1,9 @@
+import { SidebarBulkActionBar } from "@posthog/ui/features/sidebar/components/SidebarBulkActionBar";
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";
+import { useBulkArchiveConfirm } from "./useBulkArchiveConfirm";
if (typeof globalThis.ResizeObserver === "undefined") {
globalThis.ResizeObserver = class {
@@ -37,13 +38,26 @@ function makeActions(
};
}
-describe("SidebarBulkActionFooter", () => {
+/** The pairing every sidebar renders: the bar asks, the dialog confirms. */
+function Harness({ actions }: { actions: SidebarBulkActions }) {
+ const confirm = useBulkArchiveConfirm(actions);
+ return (
+ <>
+ <SidebarBulkActionBar
+ actions={actions}
+ onClearSelection={vi.fn()}
+ onArchive={confirm.requestArchive}
+ />
+ {confirm.dialog}
+ </>
+ );
+}
+
+describe("useBulkArchiveConfirm", () => {
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()} />,
- );
+ render(<Harness actions={actions} />);
await user.click(screen.getByLabelText("Archive 3 sessions"));
@@ -58,20 +72,14 @@ describe("SidebarBulkActionFooter", () => {
// 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()}
- />,
- );
+ const { rerender } = render(<Harness actions={makeActions()} />);
await user.click(screen.getByLabelText("Archive 3 sessions"));
expect(await screen.findByText("Archive 3 sessions?")).toBeInTheDocument();
rerender(
- <SidebarBulkActionFooter
+ <Harness
actions={makeActions({ selectedCount: 0, isArchiving: true })}
- onClearSelection={vi.fn()}
/>,
);
@@ -80,21 +88,12 @@ describe("SidebarBulkActionFooter", () => {
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()}
- />,
- );
+ const { rerender } = render(<Harness actions={makeActions()} />);
+
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()}
- />,
- );
+ rerender(<Harness actions={makeActions({ isArchiving: true })} />);
await user.keyboard("{Escape}");
expect(screen.getByText("Archive 3 sessions?")).toBeInTheDocument();
diff --git a/products/desktop/packages/ui/src/features/sidebar/useBulkArchiveConfirm.tsx b/products/desktop/packages/ui/src/features/sidebar/useBulkArchiveConfirm.tsx
new file mode 100644
index 000000000000..dbd46ccdeb65
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sidebar/useBulkArchiveConfirm.tsx
@@ -0,0 +1,59 @@
+import { BulkArchiveConfirmDialog } from "@posthog/ui/features/sidebar/components/BulkArchiveConfirmDialog";
+import type { SidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";
+import { type ReactElement, useCallback, useState } from "react";
+
+export interface BulkArchiveConfirm {
+ /** Opens the confirm. Nothing is archived until it is accepted. */
+ requestArchive: () => void;
+ /** Render once, wherever the surface that asked for it lives. */
+ dialog: ReactElement;
+}
+
+/**
+ * The confirm a bulk archive goes through, owned by whoever owns the selection
+ * rather than by each surface that can start one. Both the action bar and a
+ * row's right-click menu ask for the same dialog, and mounting one per row
+ * would put a dialog behind every session in the list.
+ *
+ * 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.
+ */
+export function useBulkArchiveConfirm(
+ actions: SidebarBulkActions,
+): BulkArchiveConfirm {
+ // 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);
+
+ const { selectedCount, runningCount, stopsCloudSandbox } = actions;
+ const requestArchive = useCallback(() => {
+ setConfirm({
+ sessionCount: selectedCount,
+ runningCount,
+ stopsCloudSandbox,
+ });
+ }, [runningCount, selectedCount, stopsCloudSandbox]);
+
+ return {
+ requestArchive,
+ dialog: (
+ <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/usePinDrag.test.tsx b/products/desktop/packages/ui/src/features/sidebar/usePinDrag.test.tsx
index 1b7a6701154d..eab690da3d56 100644
--- a/products/desktop/packages/ui/src/features/sidebar/usePinDrag.test.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/usePinDrag.test.tsx
@@ -1,6 +1,7 @@
import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { usePinDragStore } from "./pinDragStore";
+import { consumeTaskDrop } from "./taskDrag";
import { usePinDrag } from "./usePinDrag";
vi.mock("@posthog/ui/utils/sounds", () => ({ playTrashSound: vi.fn() }));
@@ -33,7 +34,7 @@ describe("usePinDrag", () => {
const { result, unmount } = renderHook(() =>
usePinDrag<Row>({
isPinned: (row) => row.pinned,
- togglePin: vi.fn(),
+ setPinned: vi.fn(),
}),
);
@@ -49,4 +50,105 @@ describe("usePinDrag", () => {
expect(isDragging()).toBe(false);
});
+
+ // Toggling every dragged row would unpin the ones already in the run, so a
+ // batch drop has to state what it wants rather than flip each row. One call,
+ // not one per row: pinning is a scoped mutation, so a row at a time costs a
+ // round trip each.
+ it("pins every dragged row that is not pinned yet, and only those", () => {
+ const setPinned = vi.fn();
+ const rows: Row[] = [
+ { id: "a", pinned: false },
+ { id: "b", pinned: true },
+ { id: "c", pinned: false },
+ ];
+ const { result } = renderHook(() =>
+ usePinDrag<Row>({
+ isPinned: (row) => row.pinned,
+ setPinned,
+ getDragSiblings: () => rows.slice(1),
+ }),
+ );
+
+ act(() => {
+ result.current.pinnedZoneRef.current = {
+ getBoundingClientRect: () => ({
+ left: 0,
+ top: 0,
+ right: 300,
+ bottom: 300,
+ }),
+ } as unknown as HTMLDivElement;
+ result.current.onItemDragStart(rows[0] as Row, dragStartEvent());
+ });
+
+ act(() => {
+ result.current.listProps.onDrop({
+ preventDefault: vi.fn(),
+ } as unknown as React.DragEvent);
+ });
+
+ expect(setPinned).toHaveBeenCalledTimes(1);
+ expect(setPinned).toHaveBeenCalledWith([rows[0], rows[2]], true);
+ });
+
+ // The card promises "Remove from pinned" the moment the pointer leaves the
+ // run, wherever it goes, so a release nothing else claimed has to keep that
+ // promise. Escape fires no drop at all, which is what separates the two:
+ // reading `dropEffect` on `dragend` cannot, because both report "none".
+ it.each([
+ {
+ released: true,
+ consumed: false,
+ unpins: true,
+ when: "released over nothing",
+ },
+ {
+ released: true,
+ consumed: true,
+ unpins: false,
+ when: "released on a Command Center tile",
+ },
+ {
+ released: false,
+ consumed: false,
+ unpins: false,
+ when: "cancelled with Escape",
+ },
+ ])("$when, unpins=$unpins", ({ released, consumed, unpins }) => {
+ const setPinned = vi.fn();
+ const { result } = renderHook(() =>
+ usePinDrag<Row>({ isPinned: (row) => row.pinned, setPinned }),
+ );
+
+ act(() => {
+ result.current.onItemDragStart(
+ { id: "a", pinned: true },
+ dragStartEvent(),
+ );
+ });
+
+ act(() => {
+ if (released) {
+ // The main pane's file-drop handler stops propagation on every drop, so
+ // only a capture-phase listener sees the release. Dispatching on a child
+ // that stops it is how this test would catch a regression to bubble.
+ const target = document.createElement("div");
+ document.body.appendChild(target);
+ target.addEventListener("drop", (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ });
+ if (consumed) consumeTaskDrop();
+ target.dispatchEvent(
+ new Event("drop", { bubbles: true, cancelable: true }),
+ );
+ target.remove();
+ }
+ result.current.onItemDragEnd();
+ });
+
+ expect(setPinned).toHaveBeenCalledTimes(unpins ? 1 : 0);
+ expect(isDragging()).toBe(false);
+ });
});
diff --git a/products/desktop/packages/ui/src/features/sidebar/usePinDrag.ts b/products/desktop/packages/ui/src/features/sidebar/usePinDrag.ts
index 16d123df5cfb..59df217779e2 100644
--- a/products/desktop/packages/ui/src/features/sidebar/usePinDrag.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/usePinDrag.ts
@@ -1,4 +1,5 @@
import { usePinDragStore } from "@posthog/ui/features/sidebar/pinDragStore";
+import { takeConsumedTaskDrop } from "@posthog/ui/features/sidebar/taskDrag";
import {
getPinDropAction,
isPointInsideRect,
@@ -18,7 +19,12 @@ import {
const OFFSCREEN = -10_000;
export interface PinDrag<T> {
- item: T;
+ /**
+ * Everything the drop applies to, grabbed item first. Non-empty by
+ * construction: the grabbed item is prepended rather than looked up, so a
+ * selection the list can't fully resolve still drops what was grabbed.
+ */
+ items: [T, ...T[]];
/** Where the drag started, which decides whether a drop pins or unpins. */
sourcePinned: boolean;
overPinned: boolean;
@@ -56,10 +62,21 @@ export interface PinDragApi<T> {
*/
export function usePinDrag<T>({
isPinned,
- togglePin,
+ setPinned,
+ getDragSiblings,
}: {
isPinned: (item: T) => boolean;
- togglePin: (item: T) => void;
+ /**
+ * Applies the drop to everything it covers, in one call. A batch rather than
+ * a toggle per item: pinning is a scoped mutation, so N calls cost N
+ * round trips in sequence, and only a batch can report a partial failure.
+ */
+ setPinned: (items: T[], pinned: boolean) => void;
+ /**
+ * The items dragged alongside the grabbed one, excluding it. Absent, or
+ * returning nothing, keeps the drag single-item.
+ */
+ getDragSiblings?: (item: T) => T[];
}): PinDragApi<T> {
const [drag, setDrag] = useState<PinDrag<T> | null>(null);
// Native drag handlers need the live drag synchronously; a render behind is a
@@ -67,6 +84,8 @@ export function usePinDrag<T>({
const dragRef = useRef<PinDrag<T> | null>(null);
const pinnedZoneRef = useRef<HTMLDivElement | null>(null);
const pointerOffsetRef = useRef({ x: 0, y: 0 });
+ /** Whether the pointer was released this drag, as opposed to Escape. */
+ const droppedRef = useRef(false);
const previewX = useMotionValue(OFFSCREEN);
const previewY = useMotionValue(OFFSCREEN);
@@ -82,6 +101,28 @@ export function usePinDrag<T>({
previewY.set(OFFSCREEN);
}, [previewX, previewY, write]);
+ // A drop states what it wants rather than toggling: toggling every dragged
+ // item would unpin the ones already pinned, so whatever is already there is
+ // left out of the batch.
+ const applyDrop = useCallback(
+ (drag: PinDrag<T>) => {
+ const action = getPinDropAction(drag.sourcePinned, drag.overPinned);
+ if (action === null) return;
+ const changing = drag.items.filter((item) => isPinned(item) !== action);
+ if (changing.length > 0) setPinned(changing, action);
+ },
+ [isPinned, setPinned],
+ );
+
+ // The listeners below register once for the life of the hook. Re-registering
+ // tears the effect down, and its cleanup reports the drag as over while it is
+ // still under the pointer. `applyDrop` closes over callers' inline callbacks,
+ // so it changes identity every render and can't be a dep.
+ const applyDropRef = useRef(applyDrop);
+ useEffect(() => {
+ applyDropRef.current = applyDrop;
+ }, [applyDrop]);
+
const overPinnedAt = useCallback(
(x: number, y: number) =>
isPointInsideRect(
@@ -95,6 +136,14 @@ export function usePinDrag<T>({
const followPointer = (event: globalThis.DragEvent) => {
const current = dragRef.current;
if (!current) return;
+ // Every dragover, before anything else: the preview card promises an
+ // unpin wherever the pointer leaves the run, and only a `preventDefault`
+ // here makes the surface under it somewhere the drag can be released. A
+ // more specific target still sets its own `dropEffect` afterwards.
+ event.preventDefault();
+ if (event.dataTransfer) {
+ event.dataTransfer.dropEffect = current.sourcePinned ? "move" : "copy";
+ }
previewX.set(event.clientX - pointerOffsetRef.current.x);
previewY.set(event.clientY - pointerOffsetRef.current.y);
const overPinned = overPinnedAt(event.clientX, event.clientY);
@@ -103,6 +152,16 @@ export function usePinDrag<T>({
if (current.sourcePinned && !overPinned) playTrashSound();
write({ ...current, overPinned });
};
+ // Only records that a release happened. What to do about it is decided on
+ // `dragend`, once every target has had its turn.
+ //
+ // Capture, and only capture. The main pane attaches a file-drop handler
+ // that calls `preventDefault` and `stopPropagation` on every drop before
+ // finding no files, so a bubble-phase listener never sees a release there
+ // and `defaultPrevented` says nothing about whether anything took it.
+ const noteDrop = () => {
+ if (dragRef.current) droppedRef.current = true;
+ };
// A drag whose source leaves the DOM dies without a `dragend`, and the
// lists poll. Once it is dead the pointer works again, which is the signal.
const endStrandedDrag = () => {
@@ -110,11 +169,11 @@ export function usePinDrag<T>({
};
// Capture, so a drop target that stops propagation can't freeze the card.
window.addEventListener("dragover", followPointer, true);
- window.addEventListener("dragend", endStrandedDrag, true);
+ window.addEventListener("drop", noteDrop, true);
window.addEventListener("mouseup", endStrandedDrag, true);
return () => {
window.removeEventListener("dragover", followPointer, true);
- window.removeEventListener("dragend", endStrandedDrag, true);
+ window.removeEventListener("drop", noteDrop, true);
window.removeEventListener("mouseup", endStrandedDrag, true);
// The store outlives the hook. Unmounting mid-drag would strand the flag
// true, and every hover card in the sidebar reads it.
@@ -122,6 +181,20 @@ export function usePinDrag<T>({
};
}, [clear, overPinnedAt, previewX, previewY, write]);
+ // Every drag ends here, and by now the release and any target that took it
+ // have both been and gone. A release nothing claimed is the one that does
+ // what the preview card promised. Escape fires no drop at all, so a cancelled
+ // drag leaves the pin where it was.
+ const onItemDragEnd = useCallback(() => {
+ const current = dragRef.current;
+ const dropped = droppedRef.current;
+ const consumed = takeConsumedTaskDrop();
+ droppedRef.current = false;
+ if (!current) return;
+ if (dropped && !consumed) applyDropRef.current(current);
+ clear();
+ }, [clear]);
+
const onItemDragStart = useCallback(
(item: T, event: DragEvent) => {
const rect = event.currentTarget.getBoundingClientRect();
@@ -133,6 +206,8 @@ export function usePinDrag<T>({
event.dataTransfer.setDragImage(ghost, 0, 0);
window.requestAnimationFrame(() => ghost.remove());
+ droppedRef.current = false;
+ takeConsumedTaskDrop();
pointerOffsetRef.current = {
x: event.clientX - rect.left,
y: event.clientY - rect.top,
@@ -140,13 +215,13 @@ export function usePinDrag<T>({
previewX.set(rect.left);
previewY.set(rect.top);
write({
- item,
+ items: [item, ...(getDragSiblings?.(item) ?? [])],
sourcePinned: isPinned(item),
overPinned: overPinnedAt(event.clientX, event.clientY),
previewWidth: rect.width,
});
},
- [isPinned, overPinnedAt, previewX, previewY, write],
+ [getDragSiblings, isPinned, overPinnedAt, previewX, previewY, write],
);
const onListDragOver = useCallback((event: DragEvent) => {
@@ -161,12 +236,10 @@ export function usePinDrag<T>({
const current = dragRef.current;
if (!current) return;
event.preventDefault();
- if (getPinDropAction(current.sourcePinned, current.overPinned) !== null) {
- togglePin(current.item);
- }
+ applyDrop(current);
clear();
},
- [clear, togglePin],
+ [applyDrop, clear],
);
return {
@@ -174,9 +247,7 @@ export function usePinDrag<T>({
pinnedZoneRef,
listProps: { onDragOver: onListDragOver, onDrop: onListDrop },
onItemDragStart,
- // Reached by a cancelled drag, and by a drop the list didn't take (a
- // Command Center tile). A drop the list took has already cleared.
- onItemDragEnd: clear,
+ onItemDragEnd,
previewX,
previewY,
};
diff --git a/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts
index ba484d516d30..f43a86861c8f 100644
--- a/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts
@@ -19,7 +19,7 @@ import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFla
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 { useLiveTaskIds } from "@posthog/ui/features/tasks/useLiveTaskIds";
import { toast } from "@posthog/ui/primitives/toast";
import { logger } from "@posthog/ui/shell/logger";
import { useQueryClient } from "@tanstack/react-query";
@@ -93,14 +93,7 @@ export function useSidebarBulkActions(
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 liveTaskIds = useLiveTaskIds();
const [isArchiving, setIsArchiving] = useState(false);
const [isFiling, setIsFiling] = useState(false);
@@ -132,9 +125,7 @@ export function useSidebarBulkActions(
);
// 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.
+ // failures so the user can retry those.
const reconcileSelection = useCallback(
(failedIds: string[]) => {
if (failedIds.length === 0) clearSelection();
diff --git a/products/desktop/packages/ui/src/features/tasks/useLiveTaskIds.ts b/products/desktop/packages/ui/src/features/tasks/useLiveTaskIds.ts
new file mode 100644
index 000000000000..3d2f1d71f6cd
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/tasks/useLiveTaskIds.ts
@@ -0,0 +1,19 @@
+import { useTasks } from "@posthog/ui/features/tasks/useTasks";
+import { useMemo } from "react";
+
+/**
+ * The sessions that still exist, as a set.
+ *
+ * Command Center cells are persisted and only pruned when a session is
+ * archived, so a deleted one's id lingers in the array and the grid draws that
+ * tile empty. Anything reasoning about which tiles are free has to see the same
+ * empty tile the user does. `null` while the list is unknown, which callers
+ * read as "hold every non-empty cell" rather than guessing the other way.
+ */
+export function useLiveTaskIds(): ReadonlySet<string> | null {
+ const { data: liveTasks } = useTasks();
+ return useMemo(
+ () => (liveTasks ? new Set(liveTasks.map((task) => task.id)) : null),
+ [liveTasks],
+ );
+}