: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): add session sidebar drag and drop (#84960)
Adam Leith0d6deaeccfaa
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemDragPreview.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemDragPreview.tsxnew file mode 100644index 000000000000..b6df0a4e304c--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemDragPreview.tsx@@ -0,0 +1,81 @@+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 { getPinDropAction } from "@posthog/ui/features/sidebar/taskListDragAndDrop";+import type { PinDrag } from "@posthog/ui/features/sidebar/usePinDrag";+import {+ AnimatePresence,+ type MotionValue,+ motion,+ useReducedMotion,+} from "framer-motion";+import { createPortal } from "react-dom";++/**+ * The card that follows the pointer during a pin drag, badged with what+ * releasing here would do, unbadged where it would do nothing.+ *+ * Portalled to the theme root for two reasons. The sidebar's panes slide on a+ * transform, which `position: fixed` would resolve against; and Radix scopes+ * the palette to that element, so a card on the body draws colours as+ * transparent.+ */+export function ChannelItemDragPreview({+ drag,+ x,+ y,+}: {+ drag: PinDrag<ChannelItemModel>;+ x: MotionValue<number>;+ y: MotionValue<number>;+}) {+ const prefersReducedMotion = useReducedMotion();+ const host =+ 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 action = getPinDropAction(drag.sourcePinned, drag.overPinned);+ const spring = prefersReducedMotion+ ? { duration: 0 }+ : ({ type: "spring", stiffness: 500, damping: 34 } as const);++ return createPortal(+ <motion.div+ 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}+ />+ </div>+ <AnimatePresence>+ {action !== null ? (+ <motion.span+ // Keyed on the action, so crossing into the run swaps the badge+ // rather than retitling the one already there.+ key={String(action)}+ initial={{ opacity: 0, y: -4 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -4 }}+ transition={spring}+ className={cn(+ "absolute top-full left-2 mt-1 rounded-full px-2 py-0.5 font-medium text-[11px] shadow-sm",+ action+ ? "bg-primary text-primary-foreground"+ : "bg-destructive text-destructive-foreground",+ )}+ >+ {action ? "Add to pinned" : "Remove from pinned"}+ </motion.span>+ ) : null}+ </AnimatePresence>+ </motion.div>,+ host,+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsxindex 2a43dc8b1267..8bee5dd20fe1 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx@@ -10,6 +10,7 @@ import {type SpacePreviewPayload,} from "@posthog/ui/features/canvas/components/SpacePreview";import type { TaskRowMenuProps } from "@posthog/ui/features/canvas/components/TaskRowMenu";+import { useIsPinDragging } from "@posthog/ui/features/sidebar/pinDragStore";import {createContext,type ReactNode,@@ -98,6 +99,13 @@ export function ChannelItemPreviewCardProvider({handle.close();}, [handle]);+ // A drag passes the pointer over row after row, each handing the card to the+ // next, until a card this size sits over the list. It stands down instead.+ const dragging = useIsPinDragging();+ useEffect(() => {+ if (dragging) close();+ }, [dragging, close]);+// Which row's keypress the open card belongs to, if any.const keyboardTrigger = useRef<string | null>(null);const card = useMemo<ChannelPreviewCard>(@@ -127,7 +135,7 @@ export function ChannelItemPreviewCardProvider({the card, which would take the menu down with it. */}<PreviewCard.Roothandle={handle}- open={open || submenuOpen}+ open={(open || submenuOpen) && !dragging}onOpenChange={setOpen}>{({ payload }) =>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.tsxindex 6dfd96448803..5a2fdee046fd 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@@ -258,16 +258,21 @@ describe("ChannelItemRow", () => {expect(screen.queryByRole("img", { name: "Pinned" })).toBeNull();});- it("makes tasks draggable into the Command Center", () => {- renderRow(item());- const setData = vi.fn();- const dataTransfer = { setData, effectAllowed: "none" };-- fireEvent.dragStart(screen.getByRole("button"), { dataTransfer });-- expect(setData).toHaveBeenCalledWith("text/x-task-id", "task-1");- expect(dataTransfer.effectAllowed).toBe("copy");- });+ // A pinned row offering only `move` resolves against the Command Center's+ // `copy` as no drop, so the tile stops accepting it with nothing to show why.+ it.each([{ pinned: false }, { pinned: true }])(+ "makes tasks draggable into the Command Center, pinned=$pinned",+ ({ pinned }) => {+ renderRow(item({ pinned }));+ const setData = vi.fn();+ const dataTransfer = { setData, effectAllowed: "none" };++ fireEvent.dragStart(screen.getByRole("button"), { dataTransfer });++ expect(setData).toHaveBeenCalledWith("text/x-task-id", "task-1");+ expect(dataTransfer.effectAllowed).toBe("copyMove");+ },+ );it("does not make canvases draggable into the Command Center", () => {renderRow(diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsxindex af7e218e22f7..c5deeb46619c 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx@@ -31,6 +31,7 @@ import {TaskStatusDot,TaskStatusTooltips,} from "@posthog/ui/features/sidebar/components/items/TaskStatusDot";+import type { TaskStatusInput } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";import {type TaskDot,taskDot,@@ -136,6 +137,97 @@ function CanvasBadgeStack({);}+/**+ * A row's leading mark, always the task-list state vocabulary. Canvases have no+ * live run, so they take the quiet dot and move their glyph to the trailing+ * stack. Deleting is the exception: that one a canvas row has to shout.+ */+function ChannelItemDot({+ item,+ status,+}: {+ item: ChannelItemModel;+ status: TaskStatusInput | null;+}) {+ const pendingDelete = useIsCanvasPendingDelete(item.id);+ const deleting = item.kind === "canvas" && pendingDelete;+ return (+ <TaskStatusDot dot={deleting ? DELETING_DOT : taskDot(status ?? {})} />+ );+}++/**+ * What a row looks like, with nothing behind it, so the drag preview can draw+ * one without wiring it. Rendering `ChannelItemRow` for that opened a second PR+ * lookup per drag, plus a hover card and a context menu nothing could reach.+ *+ * Takes `status` rather than resolving it: how much is worth resolving is the+ * caller's call, see `useChannelTaskStatus`.+ */+export function ChannelItemRowView({+ item,+ status,+ isActive,+ isSelected = false,+ showPinBadge = true,+ draggable = false,+ onClick,+ onDragStart,+ onDragEnd,+}: {+ item: ChannelItemModel;+ status: TaskStatusInput | null;+ isActive: boolean;+ isSelected?: boolean;+ showPinBadge?: boolean;+ draggable?: boolean;+ onClick?: (e: React.MouseEvent) => void;+ onDragStart?: (e: DragEvent) => void;+ onDragEnd?: (e: DragEvent) => void;+}) {+ const pinBadge = item.pinned && showPinBadge;+ return (+ <SidebarItem+ depth={0}+ icon={<ChannelItemDot item={item} status={status} />}+ // 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={draggable}+ onDragStart={onDragStart}+ onDragEnd={onDragEnd}+ onClick={onClick}+ endContent={+ <span className={TRAILING_CLASS}>+ {/* Badges take the timestamp's slot: identity (pin, source, cloud,+ PR) is what you scan a task list for, and the age is still on the+ preview card. */}+ {status ? (+ <TaskBadgeStack status={status} pinned={pinBadge} />+ ) : item.kind === "canvas" ? (+ <CanvasBadgeStack item={item} pinned={pinBadge} />+ ) : (+ <>+ {pinBadge && (+ <AvatarGroup stacked reverse size="xs" className="shrink-0">+ <PinnedBadge />+ </AvatarGroup>+ )}+ <span className={TIMESTAMP_CLASS}>+ {formatRelativeTimeShort(item.ts)}+ </span>+ </>+ )}+ </span>+ }+ />+ );+}+export function ChannelItemRow({item,channelId,@@ -149,6 +241,8 @@ export function ChannelItemRow({onAddToCommandCenter,onEditSubmit,onEditCancel,+ onDragStart,+ onDragEnd,}: {item: ChannelItemModel;/** The space this row is listed under, ticked in the menu's "File to…". */@@ -168,29 +262,24 @@ export function ChannelItemRow({onAddToCommandCenter?: () => void;onEditSubmit?: (newTitle: string) => void;onEditCancel?: () => void;+ /** Only the space sidebar passes these; they drive its pin/unpin drag. */+ onDragStart?: (e: DragEvent) => void;+ onDragEnd?: (e: DragEvent) => void;}) {const status = useChannelTaskStatus(item);- const pinBadge = item.pinned && showPinBadge;const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);- // A canvas inside its undo window stays in the list rather than vanishing and- // reappearing on Undo, so the row has to say what's happening to it.- const pendingDelete = useIsCanvasPendingDelete(item.id);- const deleting = item.kind === "canvas" && pendingDelete;const handleDragStart = useCallback((event: DragEvent) => {if (item.kind !== "task") return;event.dataTransfer.setData("text/x-task-id", item.id);- event.dataTransfer.effectAllowed = "copy";+ // Both, always. Command Center tiles ask for `copy` and the pinned run+ // asks for `move`; a source that permits only one resolves the other+ // pairing to no drop, and the tile silently stops accepting the row.+ event.dataTransfer.effectAllowed = "copyMove";+ onDragStart?.(event);},- [item.id, item.kind],- );- // The row's leading mark is always the task-list state vocabulary. Canvases- // have no live run, so they use the quiet dot and move their glyph to the- // right-side identity stack — except while one is being deleted, which is the- // one thing a canvas row has to shout.- const rowIcon = (- <TaskStatusDot dot={deleting ? DELETING_DOT : taskDot(status ?? {})} />+ [item.id, item.kind, onDragStart],);// A canvas gets the same menu with the items it actually has: pin, and delete@@ -230,7 +319,7 @@ export function ChannelItemRow({return (<InlineEditInputdepth={0}- icon={rowIcon}+ icon={<ChannelItemDot item={item} status={status} />}label={item.title}isActive={isActive}onSubmit={(newTitle) => onEditSubmit?.(newTitle)}@@ -243,44 +332,16 @@ export function ChannelItemRow({// between them doesn't re-wait the open delay. Canvas rows have neither.const row = (<ChannelItemHoverCard item={item} menu={menu}>- <SidebarItem- depth={0}- icon={rowIcon}- // A non-string label opts out of SidebarItem's truncation tooltip.- label={<span>{item.title}</span>}+ <ChannelItemRowView+ item={item}+ status={status}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 } : {})}+ showPinBadge={showPinBadge}draggable={item.kind === "task"}onDragStart={handleDragStart}+ onDragEnd={onDragEnd}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's- identity (pin, source, cloud, PR) is what you scan a task- list for, and the relative age is still in the preview- card. The pin joins whichever stack the row has, rather- than standing beside it as a badge of its own. */}- {status ? (- <TaskBadgeStack status={status} pinned={pinBadge} />- ) : item.kind === "canvas" ? (- <CanvasBadgeStack item={item} pinned={pinBadge} />- ) : (- <>- {pinBadge && (- <AvatarGroup stacked reverse size="xs" className="shrink-0">- <PinnedBadge />- </AvatarGroup>- )}- <span className={TIMESTAMP_CLASS}>- {formatRelativeTimeShort(item.ts)}- </span>- </>- )}- </span>- }/></ChannelItemHoverCard>);diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsxindex bfe809b8410c..6d8c1fd07119 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx@@ -21,6 +21,7 @@ import {import { computeEffectiveBulkIds } from "@posthog/core/sidebar/selection";import {Button,+ cn,Empty,EmptyDescription,EmptyHeader,@@ -38,6 +39,7 @@ 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 { ChannelItemDragPreview } from "@posthog/ui/features/canvas/components/ChannelItemDragPreview";import { ChannelItemRow } from "@posthog/ui/features/canvas/components/ChannelItemRow";import { ChannelsFab } from "@posthog/ui/features/canvas/components/ChannelsFab";import { cnHeaderButton } from "@posthog/ui/features/canvas/components/channelHeaderButton";@@ -60,10 +62,12 @@ import { SidebarItem } from "@posthog/ui/features/sidebar/components/SidebarItemimport { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";import { useClearSelectionOnEscape } from "@posthog/ui/features/sidebar/useClearSelectionOnEscape";import { useMarqueeSelection } from "@posthog/ui/features/sidebar/useMarqueeSelection";+import { usePinDrag } from "@posthog/ui/features/sidebar/usePinDrag";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 { motion, useReducedMotion } from "framer-motion";import { Fragment, useEffect, useMemo, useRef, useState } from "react";const RECENTS_CAP = 30;@@ -378,6 +382,17 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {[recentItems, sort, dayStart],);+ const pinnedSection = sections.find(+ (section) => section.key === PINNED_SECTION_KEY,+ );+ const datedSections = sections.filter(+ (section) => section.key !== PINNED_SECTION_KEY,+ );+ // Under "Pinned" every row wears the same badge, so the header says it once+ // instead, but only while a header below marks where the pins stop. An+ // alphabetical run carries no header, so there the badges stay.+ const showPinnedBadges = datedSections[0]?.label == null;+const narrowed = filtersActive || searchOpen;const listState = listStateOf({channelMissing,@@ -405,6 +420,11 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {useClearSelectionOnEscape();const listAnchorRef = useRef<HTMLDivElement | null>(null);const marquee = useMarqueeSelection(listAnchorRef);+ const prefersReducedMotion = useReducedMotion();+ const pinDrag = usePinDrag<ChannelItemModel>({+ isPinned: (item) => item.pinned,+ togglePin: actions.togglePin,+ });useEffect(() => {pruneSelection(selectableTaskIds);@@ -458,46 +478,117 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {const commandCenterAssigner = (taskId: string, taskTitle: string) => () =>placeTaskInCommandCenter(taskId, taskTitle);+ const rowTransition = prefersReducedMotion+ ? { duration: 0 }+ : {+ layout: { type: "spring" as const, stiffness: 520, damping: 42 },+ height: { duration: 0.16, ease: "easeOut" as const },+ opacity: { duration: 0.1 },+ };++ /**+ * The pinned run, doubling as the box that decides pin from unpin. Always+ * rendered, empty or not, and it opens on a drag rather than appearing. See+ * below for why nothing here may jump into place.+ */+ const pinnedRun = () => {+ const drag = pinDrag.drag;+ const pinnedItems = pinnedSection?.items ?? [];+ return (+ <div+ key={PINNED_SECTION_KEY}+ ref={pinDrag.pinnedZoneRef}+ className={cn(+ // `min-h-0` is the resting end of the transition. min-height starts at+ // `auto`, which is not interpolable, so without it the run snaps open.+ "flex min-h-0 flex-col gap-px rounded-md transition-[min-height,background-color] duration-150 ease-out motion-reduce:transition-none",+ // A floor, not a height, so a taller run keeps its own.+ drag && "min-h-[100px]",+ drag?.overPinned &&+ !drag.sourcePinned &&+ "bg-accent-2 ring-1 ring-accent-6",+ )}+ >+ {/* Opened by a transition rather than by appearing: a drag dies at+ birth if anything above its source jumps in the same frame as+ `dragstart`. Grid rows, so the label keeps its own height. */}+ <div+ className={cn(+ "grid transition-[grid-template-rows] duration-150 ease-out motion-reduce:transition-none",+ pinnedItems.length > 0 || drag+ ? "grid-rows-[1fr]"+ : "grid-rows-[0fr]",+ )}+ >+ <div className="overflow-hidden">+ <MenuLabel>Pinned</MenuLabel>+ </div>+ </div>+ {pinnedItems.map((item) => taskRow(item, showPinnedBadges))}+ </div>+ );+ };++ // 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) => (- <ChannelItemRow+ <motion.divkey={item.key}- 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+ initial={false}+ animate={+ item.key === pinDrag.drag?.item.key+ ? { height: 0, opacity: 0 }+ : { height: "auto", opacity: 1 }}- // 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);+ transition={rowTransition}+ className="overflow-hidden"+ >+ <ChannelItemRow+ 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+ }+ // 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)}- />+ : 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@@ -602,9 +693,14 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {/></div>)}+ {/* Pin and unpin stay reachable from the row's menu and its context+ menu, so the drag adds no keyboard-only path. */}+ {/* biome-ignore lint/a11y/noStaticElementInteractions: drag-and-drop container */}<divaria-busy={isLoading}className="scroll-mask-4 min-h-0 flex-1 overflow-y-auto px-2 pt-1 pb-2"+ onDragOver={pinDrag.listProps.onDragOver}+ onDrop={pinDrag.listProps.onDrop}>{listState === "loading" && <ChannelItemsSkeleton />}@@ -627,23 +723,18 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {<TabEmptyState tab={tab} />) : sections.length > 0 ? (<div className="flex flex-col gap-px">- {sections.map((section, index) => {- // Under "Pinned" every row would wear the same badge, so the- // header says it once instead — but only while a header below- // marks where the pins stop. An alphabetical run carries no- // header of its own, so there the badges stay.- const nextRunIsHeaded =- sections[index + 1] == null ||- sections[index + 1].label != null;- const showPinBadge =- section.key !== PINNED_SECTION_KEY || !nextRunIsHeaded;- return (- <Fragment key={section.key}>- {section.label && <MenuLabel>{section.label}</MenuLabel>}- {section.items.map((item) => taskRow(item, showPinBadge))}- </Fragment>- );- })}+ {/* Always mounted, empty or not. Inserting the run on+ dragstart restructures the list under the dragged row, and+ Chromium ends the drag on the spot: dragstart, then dragend,+ before the pointer moves. Growing one already there is+ fine. */}+ {pinnedRun()}+ {datedSections.map((section) => (+ <Fragment key={section.key}>+ {section.label && <MenuLabel>{section.label}</MenuLabel>}+ {section.items.map((item) => taskRow(item, true))}+ </Fragment>+ ))}</div>) : (<Empty className="border-0 py-6">@@ -669,6 +760,14 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {actions={bulkActions}onClearSelection={clearSelection}/>++ {pinDrag.drag ? (+ <ChannelItemDragPreview+ drag={pinDrag.drag}+ x={pinDrag.previewX}+ y={pinDrag.previewY}+ />+ ) : null}</div>);}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsxindex 40d783e2b9f2..469eec6a3183 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx@@ -470,7 +470,9 @@ function SidebarMenuComponent() {><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">+ {/* Full height, so the space under the last row still belongs to the+ list. That space is where an unpin drag is released. */}+ <Flex direction="column" className="min-h-full gap-px px-2 pb-2">{sidebarData.isLoading ? (<SidebarItemdepth={0}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.stories.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.stories.tsxnew file mode 100644index 000000000000..605346b93748--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.stories.tsx@@ -0,0 +1,112 @@+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";+import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { useState } from "react";+import { fn } from "storybook/test";+import { TaskListView } from "./TaskListView";++const createTask = (+ id: string,+ title: string,+ lastActivityAt: number,+ isPinned: boolean,+): TaskData => ({+ id,+ title,+ createdAt: lastActivityAt,+ lastActivityAt,+ isGenerating: false,+ isUnread: false,+ isPinned,+ needsPermission: false,+ repository: null,+ isSuspended: false,+ folderPath: null,+ cloudPrUrl: null,+ branchName: null,+ linkedBranch: null,+});++const pinnedTasks = [+ createTask("pinned-1", "Polish the onboarding flow", 1_750_000_000_000, true),+ createTask(+ "pinned-2",+ "Investigate checkout errors",+ 1_740_000_000_000,+ true,+ ),+];++const flatTasks = [+ createTask("task-1", "Add keyboard shortcuts", 1_730_000_000_000, false),+ createTask("task-2", "Improve dashboard loading", 1_720_000_000_000, false),+ createTask("task-3", "Update empty states", 1_710_000_000_000, false),+];++function StatefulTaskList(args: React.ComponentProps<typeof TaskListView>) {+ const [pinnedIds, setPinnedIds] = useState(+ () => new Set(pinnedTasks.map((task) => task.id)),+ );+ const withPinned = (task: TaskData): TaskData => ({+ ...task,+ isPinned: pinnedIds.has(task.id),+ });+ const all = [...pinnedTasks, ...flatTasks].map(withPinned);+ return (+ <TaskListView+ {...args}+ pinnedTasks={all.filter((task) => task.isPinned)}+ flatTasks={all.filter((task) => !task.isPinned)}+ onTaskTogglePin={(taskId) =>+ setPinnedIds((current) => {+ const next = new Set(current);+ if (!next.delete(taskId)) next.add(taskId);+ return next;+ })+ }+ />+ );+}++const meta = {+ title: "Sidebar/Task list drag and drop",+ component: TaskListView,+ render: (args) => <StatefulTaskList {...args} />,+ parameters: {+ layout: "centered",+ },+ decorators: [+ (Story) => {+ useSidebarStore.setState({+ organizeMode: "chronological",+ sortMode: "updated",+ });+ return (+ <div className="h-[460px] w-72 overflow-hidden rounded-lg border border-gray-6 bg-gray-1 p-2">+ <Story />+ </div>+ );+ },+ ],+ args: {+ pinnedTasks,+ flatTasks,+ groupedTasks: [],+ activeTaskId: "task-2",+ editingTaskId: null,+ selectedTaskIds: [],+ onTaskClick: fn(),+ onTaskDoubleClick: fn(),+ onTaskContextMenu: fn(),+ onTaskArchive: fn(),+ onTaskTogglePin: fn(),+ onTaskEditSubmit: fn(),+ onTaskEditCancel: fn(),+ hasMore: false,+ },+} satisfies Meta<typeof TaskListView>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {};diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsxindex 08ea61594f66..4fe7c4e65869 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx@@ -1,7 +1,7 @@import { PointerSensor } from "@dnd-kit/dom";import type { DragDropEvents } from "@dnd-kit/react";import { DragDropProvider } from "@dnd-kit/react";-import { GitBranch, Wrench } from "@phosphor-icons/react";+import { GitBranch, Trash, Wrench } from "@phosphor-icons/react";import {findGroupFolder,groupTasksByRelativeDate,@@ -11,22 +11,28 @@ import type {TaskData,TaskGroup,} from "@posthog/core/sidebar/sidebarData.types";-import { MenuLabel } from "@posthog/quill";+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 { useArchivingTasksStore } from "@posthog/ui/features/sidebar/archivingTasksStore";import { DraggableFolder } from "@posthog/ui/features/sidebar/components/DraggableFolder";import { GroupWorktreesSection } from "@posthog/ui/features/sidebar/components/GroupWorktreesSection";-import { TaskItem } from "@posthog/ui/features/sidebar/components/items/TaskItem";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 { useTaskPrStatus } from "@posthog/ui/features/sidebar/useTaskPrStatus";-import { useWorkspace } from "@posthog/ui/features/workspace/useWorkspace";+import {+ getPinnedInsertionIndex,+ type TaskTimestampKey,+} from "@posthog/ui/features/sidebar/taskListDragAndDrop";+import { usePinDrag } from "@posthog/ui/features/sidebar/usePinDrag";import { useAppView } from "@posthog/ui/router/useAppView";import { openTaskInput } from "@posthog/ui/router/useOpenTask";-import { Flex, Text } from "@radix-ui/themes";-import { motion } from "framer-motion";+import {+ AnimatePresence,+ LayoutGroup,+ motion,+ useReducedMotion,+} from "framer-motion";import { Fragment, useCallback, useEffect, useMemo } from "react";interface TaskListViewProps {@@ -59,82 +65,6 @@ function SectionLabel({ label }: { label: string }) {return <MenuLabel className="flex items-center py-0">{label}</MenuLabel>;}-function TaskRow({- task,- isActive,- isSelected,- hideHoverActions,- isEditing,- onClick,- onDoubleClick,- onContextMenu,- onArchive,- onTogglePin,- onEditSubmit,- onEditCancel,- timestamp,- depth = 0,-}: {- task: TaskData;- isActive: boolean;- isSelected: boolean;- hideHoverActions: boolean;- isEditing: boolean;- onClick: (e: React.MouseEvent) => void;- onDoubleClick: () => void;- onContextMenu: (e: React.MouseEvent, isPinned: boolean) => void;- onArchive: () => void;- onTogglePin: () => void;- onEditSubmit: (newTitle: string) => void;- onEditCancel: () => void;- timestamp: number;- depth?: number;-}) {- const workspace = useWorkspace(task.id);- const effectiveMode =- workspace?.mode ??- (task.taskRunEnvironment === "cloud" ? "cloud" : undefined);-- const { prState, hasDiff } = useTaskPrStatus(task);- const isArchiving = useArchivingTasksStore((s) =>- s.archivingTaskIds.has(task.id),- );-- return (- <TaskItem- depth={depth}- taskId={task.id}- label={task.title}- isActive={isActive}- isSelected={isSelected}- isArchiving={isArchiving}- hideHoverActions={hideHoverActions}- isEditing={isEditing}- workspaceMode={effectiveMode}- isSuspended={task.isSuspended}- isGenerating={task.isGenerating}- isUnread={task.isUnread}- isPinned={task.isPinned}- needsPermission={task.needsPermission}- taskRunStatus={task.taskRunStatus}- runMode={task.runMode}- originProduct={task.originProduct}- slackThreadUrl={task.slackThreadUrl}- prState={prState}- hasDiff={hasDiff}- prUrl={task.cloudPrUrl}- timestamp={timestamp}- onClick={onClick}- onDoubleClick={onDoubleClick}- onContextMenu={(e) => onContextMenu(e, task.isPinned)}- onArchive={onArchive}- onTogglePin={onTogglePin}- onEditSubmit={onEditSubmit}- onEditCancel={onEditCancel}- />- );-}-export function TaskListView({pinnedTasks,flatTasks,@@ -172,27 +102,19 @@ export function TaskListView({const view = useAppView();const isOnTaskInput =view.type === "task-input" || view.type === "task-pending";+ const prefersReducedMotion = useReducedMotion();+ const pinDrag = usePinDrag<TaskData>({+ isPinned: (task) => task.isPinned,+ togglePin: (task) => onTaskTogglePin(task.id),+ });+ const dragState = pinDrag.drag;// biome-ignore lint/correctness/useExhaustiveDependencies: reset pagination when filters changeuseEffect(() => {resetHistoryVisibleCount();}, [organizeMode, sortMode, resetHistoryVisibleCount]);- const handleDragOver: DragDropEvents["dragover"] = useCallback((event) => {- const sourceId = event.operation.source?.id;- const targetId = event.operation.target?.id;- if (!sourceId || !targetId || sourceId === targetId) return;-- const currentOrder = useSidebarStore.getState().folderOrder;- const sourceIndex = currentOrder.indexOf(String(sourceId));- const targetIndex = currentOrder.indexOf(String(targetId));- if (sourceIndex === -1 || targetIndex === -1) return;- if (sourceIndex === targetIndex) return;-- useSidebarStore.getState().reorderFolders(sourceIndex, targetIndex);- }, []);-- const timestampKey: "lastActivityAt" | "createdAt" =+ const timestampKey: TaskTimestampKey =sortMode === "updated" ? "lastActivityAt" : "createdAt";const dateGroupedTasks = useMemo(@@ -200,213 +122,349 @@ export function TaskListView({[flatTasks, timestampKey],);+ const handleFolderDragOver: DragDropEvents["dragover"] = useCallback(+ (event) => {+ const sourceId = event.operation.source?.id;+ const targetId = event.operation.target?.id;+ if (!sourceId || !targetId || sourceId === targetId) return;++ const currentOrder = useSidebarStore.getState().folderOrder;+ const sourceIndex = currentOrder.indexOf(String(sourceId));+ const targetIndex = currentOrder.indexOf(String(targetId));+ if (sourceIndex === -1 || targetIndex === -1) return;+ if (sourceIndex === targetIndex) return;++ useSidebarStore.getState().reorderFolders(sourceIndex, targetIndex);+ },+ [],+ );++ const rowTransition = prefersReducedMotion+ ? { duration: 0 }+ : {+ layout: { type: "spring" as const, stiffness: 520, damping: 42 },+ height: { duration: 0.16, ease: "easeOut" as const },+ opacity: { duration: 0.1 },+ };++ const renderTaskRow = (task: TaskData, depth = 0) => {+ const isDragged = dragState?.item.id === task.id;+ return (+ <motion.div+ key={task.id}+ layout={prefersReducedMotion ? false : "position"}+ layoutId={`sidebar-task-${task.id}`}+ initial={false}+ animate={+ isDragged+ ? { height: 0, opacity: 0, scale: 0.98 }+ : { height: "auto", opacity: 1, scale: 1 }+ }+ transition={rowTransition}+ className="overflow-hidden"+ >+ <TaskRow+ task={task}+ isActive={activeTaskId === task.id}+ isSelected={selectedIdSet.has(task.id)}+ hideHoverActions={hasMultiSelection}+ isEditing={editingTaskId === task.id}+ onClick={(event) => onTaskClick(task.id, event)}+ onDoubleClick={() => onTaskDoubleClick(task.id)}+ onContextMenu={(event, isPinned) =>+ onTaskContextMenu(task.id, event, isPinned)+ }+ onArchive={() => onTaskArchive(task.id)}+ onTogglePin={() => onTaskTogglePin(task.id)}+ onEditSubmit={(newTitle) =>+ onTaskEditSubmit(task.id, task.title, newTitle)+ }+ onEditCancel={onTaskEditCancel}+ onDragStart={(event) => pinDrag.onItemDragStart(task, event)}+ onDragEnd={pinDrag.onItemDragEnd}+ timestamp={task[timestampKey]}+ depth={depth}+ />+ </motion.div>+ );+ };++ const pinnedTasksWithoutSource = pinnedTasks.filter(+ (task) => task.id !== dragState?.item.id,+ );+ const pinnedInsertionIndex = dragState+ ? getPinnedInsertionIndex(pinnedTasks, dragState.item, timestampKey)+ : -1;+ const showPinnedPlaceholder = Boolean(dragState?.overPinned);+ const pinnedPlaceholderBeforeTaskId =+ pinnedTasksWithoutSource[pinnedInsertionIndex]?.id;+ const pinnedPlaceholder = (+ <motion.div+ key="pinned-task-placeholder"+ layout+ initial={{ height: 0, opacity: 0 }}+ animate={{ height: 28, opacity: 1 }}+ exit={{ height: 0, opacity: 0 }}+ transition={+ prefersReducedMotion+ ? { duration: 0 }+ : { type: "spring", stiffness: 520, damping: 42 }+ }+ className="mx-1 rounded-md border border-accent-6 bg-accent-3"+ />+ );+ const showPinnedSection = pinnedTasks.length > 0 || dragState !== null;+ const isUnpinIntent = Boolean(+ dragState?.sourcePinned && !dragState.overPinned,+ );+return (- <Flex direction="column">- {pinnedTasks.length > 0 && (- <>- <SectionLabel label="Pinned" />- {pinnedTasks.map((task) => (- <TaskRow- key={task.id}- task={task}- isActive={activeTaskId === task.id}- isSelected={selectedIdSet.has(task.id)}- hideHoverActions={hasMultiSelection}- isEditing={editingTaskId === task.id}- onClick={(e) => onTaskClick(task.id, e)}- onDoubleClick={() => onTaskDoubleClick(task.id)}- onContextMenu={(e, isPinned) =>- onTaskContextMenu(task.id, e, isPinned)- }- onArchive={() => onTaskArchive(task.id)}- onTogglePin={() => onTaskTogglePin(task.id)}- onEditSubmit={(newTitle) =>- onTaskEditSubmit(task.id, task.title, newTitle)- }- onEditCancel={onTaskEditCancel}- timestamp={task[timestampKey]}- />- ))}- </>- )}+ <LayoutGroup id="sidebar-task-list">+ {/* Pin and unpin stay reachable from the row's hover actions and its+ context menu, so the drag adds no keyboard-only path. */}+ {/* biome-ignore lint/a11y/noStaticElementInteractions: drag-and-drop container */}+ <div+ className="flex min-h-full flex-1 flex-col"+ onDragOver={pinDrag.listProps.onDragOver}+ onDrop={pinDrag.listProps.onDrop}+ >+ {showPinnedSection ? (+ <motion.div+ ref={pinDrag.pinnedZoneRef}+ layout+ className={cn(+ "rounded-md py-0.5 transition-colors",+ dragState && "min-h-10",+ dragState?.overPinned &&+ !dragState.sourcePinned &&+ "bg-accent-2 ring-1 ring-accent-6",+ )}+ >+ <SectionLabel label="Pinned" />+ <AnimatePresence initial={false}>+ {pinnedTasks.map((task) => (+ <Fragment key={task.id}>+ {showPinnedPlaceholder &&+ task.id === pinnedPlaceholderBeforeTaskId+ ? pinnedPlaceholder+ : null}+ {renderTaskRow(task)}+ </Fragment>+ ))}+ {showPinnedPlaceholder && !pinnedPlaceholderBeforeTaskId+ ? pinnedPlaceholder+ : null}+ </AnimatePresence>+ </motion.div>+ ) : null}- {pinnedTasks.length === 0 &&- flatTasks.length === 0 &&- groupedTasks.length === 0 ? (- <div className="flex flex-col items-center gap-1 px-4 pt-6 pb-4 text-center">- <motion.img- src={builderHog}- alt=""- className="pointer-events-none w-[72px]"- initial={{ opacity: 0, y: 8 }}- animate={{- opacity: 1,- y: [0, -4, 0],- }}- transition={{- opacity: { duration: 0.4 },- y: {- duration: 3,- repeat: Infinity,- ease: "easeInOut",- delay: 0.4,- },- }}- />- <Text className="text-[13px] text-gray-10">No tasks yet</Text>- {!isOnTaskInput && (- <motion.button- type="button"- className="mt-1 rounded-md bg-gray-3 px-3 py-1.5 text-[13px] text-gray-12"- onClick={() => openTaskInput()}- whileHover={{ scale: 1.05, backgroundColor: "var(--gray-4)" }}- whileTap={{ scale: 0.97 }}- >- Start building- </motion.button>- )}- </div>- ) : organizeMode === "by-project" ? (- <DragDropProvider- onDragOver={handleDragOver}- sensors={[- {- plugin: PointerSensor,- options: {- activationConstraints: {- distance: { value: 5 },+ {pinnedTasks.length === 0 &&+ flatTasks.length === 0 &&+ groupedTasks.length === 0 ? (+ <div className="flex flex-col items-center gap-1 px-4 pt-6 pb-4 text-center">+ <motion.img+ src={builderHog}+ alt=""+ className="pointer-events-none w-[72px]"+ initial={{ opacity: 0, y: 8 }}+ animate={{+ opacity: 1,+ y: prefersReducedMotion ? 0 : [0, -4, 0],+ }}+ transition={{+ opacity: { duration: prefersReducedMotion ? 0 : 0.4 },+ y: {+ duration: prefersReducedMotion ? 0 : 3,+ repeat: prefersReducedMotion ? 0 : Infinity,+ ease: "easeInOut",+ delay: prefersReducedMotion ? 0 : 0.4,+ },+ }}+ />+ <Text size="sm" variant="muted">+ No tasks yet+ </Text>+ {!isOnTaskInput && (+ <motion.button+ type="button"+ className="mt-1 rounded-md bg-gray-3 px-3 py-1.5 text-[13px] text-gray-12"+ onClick={() => openTaskInput()}+ whileHover={+ prefersReducedMotion+ ? undefined+ : { scale: 1.05, backgroundColor: "var(--gray-4)" }+ }+ whileTap={prefersReducedMotion ? undefined : { scale: 0.97 }}+ >+ Start building+ </motion.button>+ )}+ </div>+ ) : organizeMode === "by-project" ? (+ <DragDropProvider+ onDragOver={handleFolderDragOver}+ sensors={[+ {+ plugin: PointerSensor,+ options: {+ activationConstraints: {+ distance: { value: 5 },+ },},},- },- ]}- >- <Flex direction="column">- {groupedTasks.map((group, index) => {- const isExpanded = !collapsedSections.has(group.id);- const folder = findGroupFolder(folders, group.id);- const groupFolderId =- folder?.id ?? group.tasks.find((t) => t.folderId)?.folderId;- return (- <DraggableFolder key={group.id} id={group.id} index={index}>- <SidebarSection- id={group.id}- label={folder?.name ?? group.name}- icon={- group.id === "custom-images" ? (- <Wrench size={14} className="text-gray-10" />+ ]}+ >+ <div className="flex flex-col">+ {groupedTasks.map((group, index) => {+ const isExpanded = !collapsedSections.has(group.id);+ const folder = findGroupFolder(folders, group.id);+ const groupFolderId =+ folder?.id ??+ group.tasks.find((task) => task.folderId)?.folderId;+ return (+ <DraggableFolder key={group.id} id={group.id} index={index}>+ <SidebarSection+ id={group.id}+ label={folder?.name ?? group.name}+ icon={+ group.id === "custom-images" ? (+ <Wrench size={14} className="text-gray-10" />+ ) : (+ <GitBranch size={14} className="text-gray-10" />+ )+ }+ isExpanded={isExpanded}+ onToggle={() => toggleSection(group.id)}+ addSpacingBefore={false}+ tooltipContent={folder?.path ?? group.id}+ onNewTask={() => {+ openTaskInput({+ folderId: groupFolderId,+ // Cloud-only groups have no registered folder, and the+ // group id is the repo slug. Without it the new-task+ // screen keeps whichever repo was last used.+ folderRepository: group.id,+ folderRunEnvironment: mostRecentRunEnvironment(+ group.tasks,+ ),+ });+ }}+ newTaskTooltip={`Start new task in ${folder?.name ?? group.name}`}+ onContextMenu={+ onGroupContextMenu+ ? (event) => onGroupContextMenu(group.id, event)+ : undefined+ }+ >+ {group.tasks.length === 0 ? (+ <p className="px-4 py-2 text-[12px] text-gray-9">+ No tasks yet+ </p>) : (- <GitBranch size={14} className="text-gray-10" />- )- }- isExpanded={isExpanded}- onToggle={() => toggleSection(group.id)}- addSpacingBefore={false}- tooltipContent={folder?.path ?? group.id}- onNewTask={() => {- openTaskInput({- folderId: groupFolderId,- // Cloud-only groups have no registered folder, and the- // group id is the repo slug — without it the new-task- // screen would keep whichever repo was last used.- folderRepository: group.id,- folderRunEnvironment: mostRecentRunEnvironment(- group.tasks,- ),- });- }}- newTaskTooltip={`Start new task in ${folder?.name ?? group.name}`}- onContextMenu={- onGroupContextMenu- ? (e) => onGroupContextMenu(group.id, e)- : undefined- }- >- {group.tasks.length === 0 ? (- <p className="px-4 py-2 text-[12px] text-gray-9">- No tasks yet- </p>- ) : (- group.tasks.map((task) => (- <TaskRow- key={task.id}- task={task}- isActive={activeTaskId === task.id}- isSelected={selectedIdSet.has(task.id)}- hideHoverActions={hasMultiSelection}- isEditing={editingTaskId === task.id}- onClick={(e) => onTaskClick(task.id, e)}- onDoubleClick={() => onTaskDoubleClick(task.id)}- onContextMenu={(e, isPinned) =>- onTaskContextMenu(task.id, e, isPinned)- }- onArchive={() => onTaskArchive(task.id)}- onTogglePin={() => onTaskTogglePin(task.id)}- onEditSubmit={(newTitle) =>- onTaskEditSubmit(task.id, task.title, newTitle)- }- onEditCancel={onTaskEditCancel}- timestamp={task[timestampKey]}- depth={1}+ group.tasks.map((task) => renderTaskRow(task, 1))+ )}+ {folder && showSidebarWorktrees && (+ <GroupWorktreesSection+ groupId={group.id}+ mainRepoPath={folder.mainRepoPath ?? folder.path}/>- ))- )}- {folder && showSidebarWorktrees && (- <GroupWorktreesSection- groupId={group.id}- mainRepoPath={folder.mainRepoPath ?? folder.path}- />- )}- </SidebarSection>- </DraggableFolder>- );- })}- </Flex>- </DragDropProvider>- ) : (- <Flex direction="column" gap="1px">- {dateGroupedTasks.map((group, groupIndex) => (- <Fragment key={`${group.label ?? "today"}-${groupIndex}`}>- {group.label && <SectionLabel label={group.label} />}- {group.tasks.map((task) => (- <TaskRow- key={task.id}- task={task}- isActive={activeTaskId === task.id}- isSelected={selectedIdSet.has(task.id)}- hideHoverActions={hasMultiSelection}- isEditing={editingTaskId === task.id}- onClick={(e) => onTaskClick(task.id, e)}- onDoubleClick={() => onTaskDoubleClick(task.id)}- onContextMenu={(e, isPinned) =>- onTaskContextMenu(task.id, e, isPinned)- }- onArchive={() => onTaskArchive(task.id)}- onTogglePin={() => onTaskTogglePin(task.id)}- onEditSubmit={(newTitle) =>- onTaskEditSubmit(task.id, task.title, newTitle)- }- onEditCancel={onTaskEditCancel}- timestamp={task[timestampKey]}- />- ))}- </Fragment>- ))}- </Flex>- )}+ )}+ </SidebarSection>+ </DraggableFolder>+ );+ })}+ </div>+ </DragDropProvider>+ ) : (+ <div className="flex flex-col gap-px">+ {dateGroupedTasks.map((group, groupIndex) => (+ <Fragment key={`${group.label ?? "today"}-${groupIndex}`}>+ {group.label && <SectionLabel label={group.label} />}+ {group.tasks.map((task) => renderTaskRow(task))}+ </Fragment>+ ))}+ </div>+ )}++ {/* Rendered for both organize modes: "by-project" caps each group and+ "chronological" caps the flat list, so either can have more to load. */}+ {hasMore && (+ <div className="px-2 py-2">+ <button+ type="button"+ className="w-full rounded-md px-2 py-1 text-left text-[13px] text-gray-11 transition-colors hover:bg-gray-3"+ onClick={loadMoreHistory}+ >+ Show more+ </button>+ </div>+ )}- {/* Rendered for both organize modes: "by-project" caps each group and- "chronological" caps the flat list, so either can have more to load. */}- {hasMore && (- <div className="px-2 py-2">- <button- type="button"- className="w-full rounded-md px-2 py-1 text-left text-[13px] text-gray-11 transition-colors hover:bg-gray-3"- onClick={loadMoreHistory}+ {dragState ? (+ <motion.div+ style={{+ x: pinDrag.previewX,+ y: pinDrag.previewY,+ width: dragState.previewWidth,+ }}+ className="pointer-events-none fixed top-0 left-0 z-50">- Show more- </button>- </div>- )}- </Flex>+ <motion.div+ initial={false}+ animate={+ isUnpinIntent+ ? { rotate: 1.5, scale: 1.02 }+ : { rotate: 0, scale: 1 }+ }+ transition={+ prefersReducedMotion+ ? { duration: 0 }+ : { type: "spring", stiffness: 500, damping: 34 }+ }+ className={cn(+ "relative overflow-hidden rounded-md border bg-gray-2 shadow-lg",+ isUnpinIntent+ ? "border-red-7 bg-red-3 [&_button]:bg-red-3 [&_button]:text-red-12 [&_svg]:text-red-11"+ : "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}+ />+ <AnimatePresence>+ {isUnpinIntent ? (+ <motion.span+ initial={{ opacity: 0, scale: 0.7 }}+ animate={{ opacity: 1, scale: 1 }}+ exit={{ opacity: 0, scale: 0.7 }}+ transition={+ prefersReducedMotion+ ? { duration: 0 }+ : { type: "spring", stiffness: 560, damping: 32 }+ }+ className="-translate-y-1/2 absolute top-1/2 right-2 flex size-5 items-center justify-center rounded-full bg-red-9 text-white shadow-sm"+ >+ <Trash size={12} weight="bold" />+ </motion.span>+ ) : null}+ </AnimatePresence>+ </motion.div>+ </motion.div>+ ) : null}+ </div>+ </LayoutGroup>);}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TaskRow.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TaskRow.tsxnew file mode 100644index 000000000000..fb595c38d649--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/TaskRow.tsx@@ -0,0 +1,103 @@+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";+import { useArchivingTasksStore } from "@posthog/ui/features/sidebar/archivingTasksStore";+import { TaskItem } from "@posthog/ui/features/sidebar/components/items/TaskItem";+import { useTaskPrStatus } from "@posthog/ui/features/sidebar/useTaskPrStatus";+import { useWorkspace } from "@posthog/ui/features/workspace/useWorkspace";++interface TaskRowProps {+ task: TaskData;+ isActive: boolean;+ isSelected: boolean;+ hideHoverActions: boolean;+ isEditing: boolean;+ onClick: (event: React.MouseEvent) => void;+ onDoubleClick: () => void;+ onContextMenu: (event: React.MouseEvent, isPinned: boolean) => void;+ onArchive: () => void;+ onTogglePin: () => void;+ onEditSubmit: (newTitle: string) => void;+ onEditCancel: () => void;+ onDragStart?: (event: React.DragEvent) => void;+ onDragEnd?: (event: React.DragEvent) => void;+ timestamp: number;+ depth?: number;+ /**+ * Whether to resolve the PR's state — a query per row into the host, where it+ * hits git (and GitHub). The drag preview renders a copy of a row that is+ * still mounted, so its query is already live; leaving this off keeps the+ * preview from opening a second lookup per drag. Matches the space sidebar's+ * drag card. The PR's existence still shows through `prUrl`.+ */+ withPrStatus?: boolean;+}++export function TaskRow({+ task,+ isActive,+ isSelected,+ hideHoverActions,+ isEditing,+ onClick,+ onDoubleClick,+ onContextMenu,+ onArchive,+ onTogglePin,+ onEditSubmit,+ onEditCancel,+ onDragStart,+ onDragEnd,+ timestamp,+ depth = 0,+ withPrStatus = true,+}: TaskRowProps) {+ const workspace = useWorkspace(task.id);+ const effectiveMode =+ workspace?.mode ??+ (task.taskRunEnvironment === "cloud" ? "cloud" : undefined);+ const { prState, hasDiff } = useTaskPrStatus({+ // An empty id is the hook's own "nothing to look up", so this registers no+ // query rather than a second observer that would refetch behind the drag.+ id: withPrStatus ? task.id : "",+ cloudPrUrl: task.cloudPrUrl,+ taskRunEnvironment: task.taskRunEnvironment,+ });+ const isArchiving = useArchivingTasksStore((state) =>+ state.archivingTaskIds.has(task.id),+ );++ return (+ <TaskItem+ depth={depth}+ taskId={task.id}+ label={task.title}+ isActive={isActive}+ isSelected={isSelected}+ isArchiving={isArchiving}+ hideHoverActions={hideHoverActions}+ isEditing={isEditing}+ workspaceMode={effectiveMode}+ isSuspended={task.isSuspended}+ isGenerating={task.isGenerating}+ isUnread={task.isUnread}+ isPinned={task.isPinned}+ needsPermission={task.needsPermission}+ taskRunStatus={task.taskRunStatus}+ runMode={task.runMode}+ originProduct={task.originProduct}+ slackThreadUrl={task.slackThreadUrl}+ prState={prState}+ hasDiff={hasDiff}+ prUrl={task.cloudPrUrl}+ timestamp={timestamp}+ onClick={onClick}+ onDoubleClick={onDoubleClick}+ onContextMenu={(event) => onContextMenu(event, task.isPinned)}+ onDragStart={onDragStart}+ onDragEnd={onDragEnd}+ onArchive={onArchive}+ onTogglePin={onTogglePin}+ onEditSubmit={onEditSubmit}+ onEditCancel={onEditCancel}+ />+ );+}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 64e289c13951..6c09e7644ec9 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@@ -58,6 +58,8 @@ interface TaskItemProps {onClick: (e: React.MouseEvent) => void;onDoubleClick?: () => void;onContextMenu: (e: React.MouseEvent) => void;+ onDragStart?: (e: React.DragEvent) => void;+ onDragEnd?: (e: React.DragEvent) => void;onArchive?: () => void;onTogglePin?: () => void;onEditSubmit?: (newTitle: string) => void;@@ -131,6 +133,8 @@ export function TaskItem({onClick,onDoubleClick,onContextMenu,+ onDragStart,+ onDragEnd,onArchive,onTogglePin,onEditSubmit,@@ -190,9 +194,13 @@ export function TaskItem({const handleDragStart = useCallback((e: React.DragEvent) => {e.dataTransfer.setData("text/x-task-id", taskId);- e.dataTransfer.effectAllowed = "copy";+ // Both, always. Command Center tiles ask for `copy` and the pinned run+ // asks for `move`; a source that permits only one resolves the other+ // pairing to no drop, and the tile silently stops accepting the row.+ e.dataTransfer.effectAllowed = "copyMove";+ onDragStart?.(e);},- [taskId],+ [onDragStart, taskId],);if (isEditing) {@@ -220,6 +228,7 @@ export function TaskItem({isDimmed={isArchiving}draggable={!isArchiving}onDragStart={handleDragStart}+ onDragEnd={onDragEnd}onClick={onClick}onDoubleClick={onDoubleClick}onContextMenu={onContextMenu}diff --git a/products/desktop/packages/ui/src/features/sidebar/pinDragStore.ts b/products/desktop/packages/ui/src/features/sidebar/pinDragStore.tsnew file mode 100644index 000000000000..bbd064ebd9d2--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/pinDragStore.ts@@ -0,0 +1,20 @@+import { create } from "zustand";++interface PinDragState {+ /**+ * The flag alone, not the drag itself, which belongs to `usePinDrag`. The+ * shared preview card sits above both sidebars and reads this to stand down.+ */+ dragging: boolean;+ setDragging: (dragging: boolean) => void;+}++export const usePinDragStore = create<PinDragState>((set) => ({+ dragging: false,+ setDragging: (dragging) => set({ dragging }),+}));++/** True while a session row is being dragged, for anything that must stand down. */+export function useIsPinDragging(): boolean {+ return usePinDragStore((s) => s.dragging);+}diff --git a/products/desktop/packages/ui/src/features/sidebar/taskListDragAndDrop.test.ts b/products/desktop/packages/ui/src/features/sidebar/taskListDragAndDrop.test.tsnew file mode 100644index 000000000000..628db37963ce--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/taskListDragAndDrop.test.ts@@ -0,0 +1,83 @@+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";+import { describe, expect, it } from "vitest";+import {+ getPinDropAction,+ getPinnedInsertionIndex,+ isPointInsideRect,+} from "./taskListDragAndDrop";++const task = (+ id: string,+ createdAt: number,+ lastActivityAt = createdAt,+): TaskData => ({+ id,+ title: id,+ createdAt,+ lastActivityAt,+ isGenerating: false,+ isUnread: false,+ isPinned: true,+ needsPermission: false,+ repository: null,+ isSuspended: false,+ folderPath: null,+ cloudPrUrl: null,+ branchName: null,+ linkedBranch: null,+});++describe("task list drag and drop", () => {+ it.each([+ {+ name: "pins an unpinned session dropped over pinned",+ sourcePinned: false,+ overPinned: true,+ expected: true,+ },+ {+ name: "unpins a pinned session dropped outside pinned",+ sourcePinned: true,+ overPinned: false,+ expected: false,+ },+ {+ name: "keeps an unpinned session outside pinned",+ sourcePinned: false,+ overPinned: false,+ expected: null,+ },+ {+ name: "keeps a pinned session inside pinned",+ sourcePinned: true,+ overPinned: true,+ expected: null,+ },+ ])("$name", ({ sourcePinned, overPinned, expected }) => {+ expect(getPinDropAction(sourcePinned, overPinned)).toBe(expected);+ });++ it("opens the pinned gap at the session's final sorted position", () => {+ const dragged = task("dragged", 30, 15);+ const pinned = [task("newest", 50, 50), dragged, task("oldest", 10, 10)];++ expect(getPinnedInsertionIndex(pinned, dragged, "createdAt")).toBe(1);+ expect(getPinnedInsertionIndex(pinned, dragged, "lastActivityAt")).toBe(1);+ });++ it.each([+ { point: { x: 10, y: 10 }, expected: true },+ { point: { x: 20, y: 20 }, expected: true },+ { point: { x: 21, y: 10 }, expected: false },+ { point: { x: 10, y: 4 }, expected: false },+ ])("detects pinned bounds for $point", ({ point, expected }) => {+ expect(+ isPointInsideRect(point, {+ top: 5,+ right: 20,+ bottom: 20,+ left: 5,+ }),+ ).toBe(expected);+ });+});diff --git a/products/desktop/packages/ui/src/features/sidebar/taskListDragAndDrop.ts b/products/desktop/packages/ui/src/features/sidebar/taskListDragAndDrop.tsnew file mode 100644index 000000000000..0ebd8c10bf1a--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/taskListDragAndDrop.ts@@ -0,0 +1,39 @@+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";++export type TaskTimestampKey = "lastActivityAt" | "createdAt";++export function isPointInsideRect(+ point: { x: number; y: number },+ rect: Pick<DOMRect, "top" | "right" | "bottom" | "left"> | null,+): boolean {+ return Boolean(+ rect &&+ point.x >= rect.left &&+ point.x <= rect.right &&+ point.y >= rect.top &&+ point.y <= rect.bottom,+ );+}++export function getPinnedInsertionIndex(+ pinnedTasks: TaskData[],+ draggedTask: TaskData,+ timestampKey: TaskTimestampKey,+): number {+ const tasksWithoutSource = pinnedTasks.filter(+ (task) => task.id !== draggedTask.id,+ );+ const insertionIndex = tasksWithoutSource.findIndex(+ (task) => task[timestampKey] < draggedTask[timestampKey],+ );+ return insertionIndex === -1 ? tasksWithoutSource.length : insertionIndex;+}++export function getPinDropAction(+ sourcePinned: boolean,+ overPinned: boolean,+): boolean | null {+ if (!sourcePinned && overPinned) return true;+ if (sourcePinned && !overPinned) return false;+ return null;+}diff --git a/products/desktop/packages/ui/src/features/sidebar/usePinDrag.test.tsx b/products/desktop/packages/ui/src/features/sidebar/usePinDrag.test.tsxnew file mode 100644index 000000000000..1b7a6701154d--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/usePinDrag.test.tsx@@ -0,0 +1,52 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { usePinDragStore } from "./pinDragStore";+import { usePinDrag } from "./usePinDrag";++vi.mock("@posthog/ui/utils/sounds", () => ({ playTrashSound: vi.fn() }));++interface Row {+ id: string;+ pinned: boolean;+}++const dragStartEvent = () =>+ ({+ clientX: 10,+ clientY: 20,+ currentTarget: {+ getBoundingClientRect: () => ({ left: 0, top: 0, width: 200 }),+ },+ dataTransfer: { setDragImage: vi.fn() },+ }) as unknown as React.DragEvent;++const isDragging = (): boolean => usePinDragStore.getState().dragging;++describe("usePinDrag", () => {+ beforeEach(() => {+ usePinDragStore.getState().setDragging(false);+ });++ // The store outlives the hook, and every hover card in the sidebar reads it.+ // A flag stranded true takes them all down until the next completed drag.+ it("stops reporting a drag when the list unmounts under one", () => {+ const { result, unmount } = renderHook(() =>+ usePinDrag<Row>({+ isPinned: (row) => row.pinned,+ togglePin: vi.fn(),+ }),+ );++ act(() => {+ result.current.onItemDragStart(+ { id: "a", pinned: false },+ dragStartEvent(),+ );+ });+ expect(isDragging()).toBe(true);++ unmount();++ 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.tsnew file mode 100644index 000000000000..16d123df5cfb--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/usePinDrag.ts@@ -0,0 +1,183 @@+import { usePinDragStore } from "@posthog/ui/features/sidebar/pinDragStore";+import {+ getPinDropAction,+ isPointInsideRect,+} from "@posthog/ui/features/sidebar/taskListDragAndDrop";+import { playTrashSound } from "@posthog/ui/utils/sounds";+import { type MotionValue, useMotionValue } from "framer-motion";+import {+ type DragEvent,+ type RefObject,+ useCallback,+ useEffect,+ useRef,+ useState,+} from "react";++/** Parks the preview card off screen between drags rather than unmounting it. */+const OFFSCREEN = -10_000;++export interface PinDrag<T> {+ item: T;+ /** Where the drag started, which decides whether a drop pins or unpins. */+ sourcePinned: boolean;+ overPinned: boolean;+ previewWidth: number;+}++export interface PinDragApi<T> {+ drag: PinDrag<T> | null;+ /** Goes on the pinned run, whose box decides what counts as a pin. */+ pinnedZoneRef: RefObject<HTMLDivElement | null>;+ /** Goes on the list, which accepts the drop. */+ listProps: {+ onDragOver: (event: DragEvent) => void;+ onDrop: (event: DragEvent) => void;+ };+ onItemDragStart: (item: T, event: DragEvent) => void;+ onItemDragEnd: () => void;+ previewX: MotionValue<number>;+ previewY: MotionValue<number>;+}++/**+ * Drag a session in or out of a sidebar's pinned run.+ *+ * Native HTML drag, because these rows are already draggable onto Command+ * Center tiles and an element gets one drag. Three constraints follow, and none+ * of them show up in the code they shape:+ *+ * 1. The browser reports the cursor only in `dragover`, so a window listener+ * moves the card.+ * 2. It swallows every keystroke for the length of a drag, so a `dragend` with+ * no drop behind it is the only cancel signal.+ * 3. The list is the drop target, not the window. Releasing over a Command+ * Center tile is that tile's drop and must not also unpin what it filed.+ */+export function usePinDrag<T>({+ isPinned,+ togglePin,+}: {+ isPinned: (item: T) => boolean;+ togglePin: (item: T) => void;+}): PinDragApi<T> {+ const [drag, setDrag] = useState<PinDrag<T> | null>(null);+ // Native drag handlers need the live drag synchronously; a render behind is a+ // drop applied to the wrong state.+ const dragRef = useRef<PinDrag<T> | null>(null);+ const pinnedZoneRef = useRef<HTMLDivElement | null>(null);+ const pointerOffsetRef = useRef({ x: 0, y: 0 });+ const previewX = useMotionValue(OFFSCREEN);+ const previewY = useMotionValue(OFFSCREEN);++ const write = useCallback((next: PinDrag<T> | null) => {+ dragRef.current = next;+ setDrag(next);+ usePinDragStore.getState().setDragging(next !== null);+ }, []);++ const clear = useCallback(() => {+ write(null);+ previewX.set(OFFSCREEN);+ previewY.set(OFFSCREEN);+ }, [previewX, previewY, write]);++ const overPinnedAt = useCallback(+ (x: number, y: number) =>+ isPointInsideRect(+ { x, y },+ pinnedZoneRef.current?.getBoundingClientRect() ?? null,+ ),+ [],+ );++ useEffect(() => {+ const followPointer = (event: globalThis.DragEvent) => {+ const current = dragRef.current;+ if (!current) return;+ previewX.set(event.clientX - pointerOffsetRef.current.x);+ previewY.set(event.clientY - pointerOffsetRef.current.y);+ const overPinned = overPinnedAt(event.clientX, event.clientY);+ if (overPinned === current.overPinned) return;+ // Leaving the run with a pinned session is the destructive turn.+ if (current.sourcePinned && !overPinned) playTrashSound();+ write({ ...current, overPinned });+ };+ // 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 = () => {+ if (dragRef.current) clear();+ };+ // 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("mouseup", endStrandedDrag, true);+ return () => {+ window.removeEventListener("dragover", followPointer, true);+ window.removeEventListener("dragend", endStrandedDrag, 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.+ usePinDragStore.getState().setDragging(false);+ };+ }, [clear, overPinnedAt, previewX, previewY, write]);++ const onItemDragStart = useCallback(+ (item: T, event: DragEvent) => {+ const rect = event.currentTarget.getBoundingClientRect();+ // The browser's own ghost is stamped before the list reacts to the drag.+ // An empty one hands the job to the card.+ const ghost = document.createElement("div");+ ghost.style.cssText = "position:fixed;top:-10px;width:1px;height:1px";+ document.body.appendChild(ghost);+ event.dataTransfer.setDragImage(ghost, 0, 0);+ window.requestAnimationFrame(() => ghost.remove());++ pointerOffsetRef.current = {+ x: event.clientX - rect.left,+ y: event.clientY - rect.top,+ };+ previewX.set(rect.left);+ previewY.set(rect.top);+ write({+ item,+ sourcePinned: isPinned(item),+ overPinned: overPinnedAt(event.clientX, event.clientY),+ previewWidth: rect.width,+ });+ },+ [isPinned, overPinnedAt, previewX, previewY, write],+ );++ const onListDragOver = useCallback((event: DragEvent) => {+ const current = dragRef.current;+ if (!current) return;+ event.preventDefault();+ event.dataTransfer.dropEffect = current.sourcePinned ? "move" : "copy";+ }, []);++ const onListDrop = useCallback(+ (event: DragEvent) => {+ const current = dragRef.current;+ if (!current) return;+ event.preventDefault();+ if (getPinDropAction(current.sourcePinned, current.overPinned) !== null) {+ togglePin(current.item);+ }+ clear();+ },+ [clear, togglePin],+ );++ return {+ drag,+ 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,+ previewX,+ previewY,+ };+}diff --git a/products/desktop/packages/ui/src/utils/sounds.ts b/products/desktop/packages/ui/src/utils/sounds.tsindex 6872c3642974..9e4a69923888 100644--- a/products/desktop/packages/ui/src/utils/sounds.ts+++ b/products/desktop/packages/ui/src/utils/sounds.ts@@ -98,6 +98,12 @@ export function resolveSoundUrl(return SOUND_URLS[sound as Exclude<BuiltInCompletionSound, "none">] ?? null;}+export function playTrashSound(): void {+ const audio = new Audio(dropUrl);+ audio.volume = 0.35;+ void audio.play().catch(() => undefined);+}+export function playCompletionSound(sound: CompletionSound,volume = 80,