: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(today): pin, file and archive several sidebar sessions at once (#109611)
Shy Alter7fb5d6a4229c
diff --git a/frontend/src/layout/today/TodaySessionBulkArchiveDialog.tsx b/frontend/src/layout/today/TodaySessionBulkArchiveDialog.tsxnew file mode 100644index 000000000000..7395df3e96c7--- /dev/null+++ b/frontend/src/layout/today/TodaySessionBulkArchiveDialog.tsx@@ -0,0 +1,59 @@+import { useActions, useValues } from 'kea'++import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Button,+} from '@posthog/quill'++import { bulkArchiveWarning, sessionsLabel } from './todaySessionSelection'+import { todaySessionSelectionLogic } from './todaySessionSelectionLogic'++/** One confirm for the whole selection, shown when any of it is still running. */+export function TodaySessionBulkArchiveDialog(): JSX.Element {+ const { bulkArchiveConfirm, bulkAction } = useValues(todaySessionSelectionLogic)+ const { closeBulkArchiveConfirm, archiveSelected } = useActions(todaySessionSelectionLogic)+ const archiving = bulkAction === 'archive'++ return (+ <AlertDialog+ open={bulkArchiveConfirm.open}+ onOpenChange={(open: boolean) => {+ if (!open && !archiving) {+ closeBulkArchiveConfirm()+ }+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{`Archive ${sessionsLabel(bulkArchiveConfirm.count)}?`}</AlertDialogTitle>+ <AlertDialogDescription>+ {bulkArchiveWarning(bulkArchiveConfirm.count, bulkArchiveConfirm.running)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <Button+ variant="outline"+ onClick={closeBulkArchiveConfirm}+ disabled={archiving}+ data-attr="today-session-bulk-archive-cancel"+ >+ Cancel+ </Button>+ <Button+ variant="destructive-outline"+ loading={archiving}+ onClick={archiveSelected}+ data-attr="today-session-bulk-archive-confirm"+ >+ Archive+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )+}diff --git a/frontend/src/layout/today/TodaySessionBulkBar.tsx b/frontend/src/layout/today/TodaySessionBulkBar.tsxnew file mode 100644index 000000000000..59c3e9b67c52--- /dev/null+++ b/frontend/src/layout/today/TodaySessionBulkBar.tsx@@ -0,0 +1,132 @@+import { useActions, useValues } from 'kea'++import { IconArchive, IconFolder, IconPin, IconPinFilled, IconX } from '@posthog/icons'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+ Text,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@posthog/quill'++import { TodaySessionBulkArchiveDialog } from './TodaySessionBulkArchiveDialog'+import { sessionsLabel } from './todaySessionSelection'+import { TodayBulkAction, todaySessionSelectionLogic } from './todaySessionSelectionLogic'+import { TodaySpaceFileList } from './TodaySpaceFileList'+import { todaySpacesLogic } from './todaySpacesLogic'++const BUSY_REASON = 'Wait for the current change to finish'++interface BulkButtonProps {+ label: string+ action: TodayBulkAction | null+ icon: JSX.Element+ dataAttr: string+ onClick?: () => void+ /** Wraps the button before the tooltip does, so it can open a menu. */+ wrap?: (button: JSX.Element) => JSX.Element+}++/** The sidebar is narrow, so each action is an icon button that names itself in its tooltip, like Desktop's bar. */+function BulkButton({ label, action, icon, dataAttr, onClick, wrap }: BulkButtonProps): JSX.Element {+ const { bulkAction } = useValues(todaySessionSelectionLogic)+ const loading = action !== null && bulkAction === action+ const busy = bulkAction !== null && !loading+ const button = (+ <Button+ size="icon-sm"+ aria-label={label}+ loading={loading}+ disabled={busy}+ onClick={onClick}+ data-attr={dataAttr}+ />+ )+ return (+ <Tooltip>+ <TooltipTrigger delay={0} render={wrap ? wrap(button) : button}>+ {icon}+ </TooltipTrigger>+ <TooltipContent side="top">{busy ? BUSY_REASON : label}</TooltipContent>+ </Tooltip>+ )+}++export function TodaySessionBulkBar(): JSX.Element {+ const { selectedSessionIds, bulkPinDirection } = useValues(todaySessionSelectionLogic)+ const { pinSelected, fileSelectedTo, requestBulkArchive, clearSelection } = useActions(todaySessionSelectionLogic)+ const { spaces } = useValues(todaySpacesLogic)+ const count = selectedSessionIds.length+ const sessions = sessionsLabel(count)+ const pin = bulkPinDirection === 'pin'++ return (+ <>+ {/* The bar is the only sign of a selection and unmounts below two, so the announcement lives outside it. */}+ <span aria-live="polite" className="sr-only">+ {count > 1 ? `${sessions} selected` : ''}+ </span>+ {count > 1 && (+ <div+ className="-mx-3 flex items-center justify-between gap-2 border-t border-border px-3 py-1.5"+ data-attr="today-session-bulk-bar"+ >+ <div className="flex min-w-0 items-baseline gap-1.5">+ <Text size="xs" weight="medium" render={<span />} className="shrink-0">+ {`${count} selected`}+ </Text>+ <Text size="xxs" variant="muted" render={<span />} className="truncate">+ Esc to clear+ </Text>+ </div>+ <div className="flex shrink-0 items-center gap-0.5">+ <BulkButton+ label={`${pin ? 'Pin' : 'Unpin'} ${sessions}`}+ action="pin"+ icon={pin ? <IconPin /> : <IconPinFilled />}+ onClick={pinSelected}+ dataAttr="today-session-bulk-pin"+ />+ {spaces.length > 0 && (+ <DropdownMenu>+ <BulkButton+ label={`File ${sessions} to a space`}+ action="file"+ icon={<IconFolder />}+ wrap={(button) => <DropdownMenuTrigger render={button} />}+ dataAttr="today-session-bulk-file"+ />+ <DropdownMenuContent align="end" side="top" className="max-h-80 w-64">+ <TodaySpaceFileList+ currentSpaceId={null}+ onSelect={fileSelectedTo}+ itemDataAttr="today-session-bulk-file-space"+ searchDataAttr="today-session-bulk-file-search"+ />+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ <BulkButton+ label={`Archive ${sessions}`}+ action="archive"+ icon={<IconArchive />}+ onClick={requestBulkArchive}+ dataAttr="today-session-bulk-archive"+ />+ <BulkButton+ label="Clear selection"+ action={null}+ icon={<IconX />}+ onClick={clearSelection}+ dataAttr="today-session-bulk-clear"+ />+ </div>+ </div>+ )}+ <TodaySessionBulkArchiveDialog />+ </>+ )+}diff --git a/frontend/src/layout/today/TodaySessionMenu.tsx b/frontend/src/layout/today/TodaySessionMenu.tsxindex 30b1171c88f7..b87838390151 100644--- a/frontend/src/layout/today/TodaySessionMenu.tsx+++ b/frontend/src/layout/today/TodaySessionMenu.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { ChangeEvent, useId, useState } from 'react'+import { useId } from 'react'import {IconArchive,@@ -12,7 +12,6 @@ import {IconPinFilled,IconSearch,IconSend,- IconStar,IconStopFilled,} from '@posthog/icons'import {@@ -20,15 +19,11 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,DropdownMenuSeparator,DropdownMenuSub,DropdownMenuSubContent,DropdownMenuSubTrigger,DropdownMenuTrigger,- Input,- Text,Tooltip,TooltipContent,TooltipTrigger,@@ -41,10 +36,8 @@ import { useTodayPreviewMenuReport } from './todayPreviewCardContext'import { TodaySessionArchiveDialog } from './TodaySessionArchiveDialog'import { TodaySessionHandoffDialog } from './TodaySessionHandoffDialog'import { TodaySessionSurface, todaySessionMenuLogic } from './todaySessionMenuLogic'-import { fileToSpaces, spaceLabel, todaySpacesLogic } from './todaySpacesLogic'--/** Desktop's "File to…" list gets a fixed height past this many spaces; the web adds its search there. */-const SPACE_SEARCH_THRESHOLD = 5+import { TodaySpaceFileList } from './TodaySpaceFileList'+import { todaySpacesLogic } from './todaySpacesLogic'interface TodaySessionMenuProps {sessionId: string@@ -84,10 +77,8 @@ export function TodaySessionMenu({stopSession,} = useActions(todaySessionMenuLogic)const reportMenuOpen = useTodayPreviewMenuReport()- const [spaceSearch, setSpaceSearch] = useState('')const runId = featureFlags[FEATURE_FLAGS.POSTHOG_CODE_TASK_ANALYSIS] ? analysisRunId : nullconst saving = pendingSessionIds.includes(sessionId)- const fileTargets = fileToSpaces(spaces, spaceId, spaceSearch)const label = saving ? 'Saving your last change' : 'More actions'return (@@ -158,53 +149,18 @@ export function TodaySessionMenu({</DropdownMenuItem>)}{spaces.length > 0 && (- <DropdownMenuSub onOpenChange={(open: boolean) => !open && setSpaceSearch('')}>+ <DropdownMenuSub><DropdownMenuSubTrigger><IconFolder />File to…</DropdownMenuSubTrigger><DropdownMenuSubContent className="max-h-80 w-64">- {spaces.length > SPACE_SEARCH_THRESHOLD && (- // Keep typing away from the menu's typeahead; Escape still closes the menu.- <div- className="p-1"- onKeyDown={(event) => event.key !== 'Escape' && event.stopPropagation()}- >- <Input- autoFocus- value={spaceSearch}- onChange={(event: ChangeEvent<HTMLInputElement>) =>- setSpaceSearch(event.target.value)- }- placeholder="Search spaces…"- aria-label="Search spaces"- data-attr="today-session-move-search"- />- </div>- )}- {fileTargets.length === 0 && (- <Text render={<div />} size="sm" variant="muted" className="px-2 py-1.5">- No spaces match your search- </Text>- )}- <DropdownMenuRadioGroup- value={spaceId ?? ''}- onValueChange={(value: string) => moveSession(sessionId, value)}- >- {fileTargets.map((space) => (- <DropdownMenuRadioItem- key={space.id}- value={space.id}- closeOnClick- data-attr="today-session-move"- >- <span className="truncate">{spaceLabel(space)}</span>- {space.starred && space.system_role !== 'personal' && (- <IconStar className="ml-auto text-muted-foreground" />- )}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>+ <TodaySpaceFileList+ currentSpaceId={spaceId}+ onSelect={(value) => moveSession(sessionId, value)}+ itemDataAttr="today-session-move"+ searchDataAttr="today-session-move-search"+ /></DropdownMenuSubContent></DropdownMenuSub>)}diff --git a/frontend/src/layout/today/TodaySpaceFileList.tsx b/frontend/src/layout/today/TodaySpaceFileList.tsxnew file mode 100644index 000000000000..095eb5ea8758--- /dev/null+++ b/frontend/src/layout/today/TodaySpaceFileList.tsx@@ -0,0 +1,63 @@+import { useValues } from 'kea'+import { ChangeEvent, useState } from 'react'++import { IconStar } from '@posthog/icons'+import { DropdownMenuRadioGroup, DropdownMenuRadioItem, Input, Text } from '@posthog/quill'++import { fileToSpaces, spaceLabel, todaySpacesLogic } from './todaySpacesLogic'++/** Desktop's "File to…" list gets a fixed height past this many spaces; the web adds its search there. */+const SPACE_SEARCH_THRESHOLD = 5++interface TodaySpaceFileListProps {+ /** Ticked and listed first. Null when the sessions being filed have no single space. */+ currentSpaceId: string | null+ onSelect: (spaceId: string) => void+ itemDataAttr: string+ searchDataAttr: string+}++/** The "File to…" menu body. The menu unmounts it on close, which also clears the search. */+export function TodaySpaceFileList({+ currentSpaceId,+ onSelect,+ itemDataAttr,+ searchDataAttr,+}: TodaySpaceFileListProps): JSX.Element {+ const { spaces } = useValues(todaySpacesLogic)+ const [search, setSearch] = useState('')+ const targets = fileToSpaces(spaces, currentSpaceId, search)++ return (+ <>+ {spaces.length > SPACE_SEARCH_THRESHOLD && (+ // Keep typing away from the menu's typeahead; Escape still closes the menu.+ <div className="p-1" onKeyDown={(event) => event.key !== 'Escape' && event.stopPropagation()}>+ <Input+ autoFocus+ value={search}+ onChange={(event: ChangeEvent<HTMLInputElement>) => setSearch(event.target.value)}+ placeholder="Search spaces…"+ aria-label="Search spaces"+ data-attr={searchDataAttr}+ />+ </div>+ )}+ {targets.length === 0 && (+ <Text render={<div />} size="sm" variant="muted" className="px-2 py-1.5">+ No spaces match your search+ </Text>+ )}+ <DropdownMenuRadioGroup value={currentSpaceId ?? ''} onValueChange={(value: string) => onSelect(value)}>+ {targets.map((space) => (+ <DropdownMenuRadioItem key={space.id} value={space.id} closeOnClick data-attr={itemDataAttr}>+ <span className="truncate">{spaceLabel(space)}</span>+ {space.starred && space.system_role !== 'personal' && (+ <IconStar className="ml-auto text-muted-foreground" />+ )}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </>+ )+}diff --git a/frontend/src/layout/today/TodaySpacesSidebar.tsx b/frontend/src/layout/today/TodaySpacesSidebar.tsxindex 7e9452221548..655bb378c077 100644--- a/frontend/src/layout/today/TodaySpacesSidebar.tsx+++ b/frontend/src/layout/today/TodaySpacesSidebar.tsx@@ -15,6 +15,7 @@ import { TodayPaneSection, TodayPaneSectionProps } from './TodayPaneSection'import { TodayPreviewTrigger } from './TodayPreviewTrigger'import { TodayRecentFilterMenu } from './TodayRecentFilterMenu'import { TodayRecentSearchField } from './TodayRecentSearchField'+import { TodaySessionBulkBar } from './TodaySessionBulkBar'import { TodaySessionRow } from './TodaySessionRow'import { selectionClick } from './todaySessionSelection'import { todaySessionSelectionLogic } from './todaySessionSelectionLogic'@@ -335,6 +336,7 @@ export function TodaySpacesSidebar(): JSX.Element {)}</TodayPaneSection></div>+ <TodaySessionBulkBar /></div></TooltipProvider>)diff --git a/frontend/src/layout/today/todaySessionSelection.test.ts b/frontend/src/layout/today/todaySessionSelection.test.tsindex b91889fc9191..800c0787b535 100644--- a/frontend/src/layout/today/todaySessionSelection.test.ts+++ b/frontend/src/layout/today/todaySessionSelection.test.ts@@ -1,5 +1,7 @@import {TodaySessionSelection,+ bulkArchiveWarning,+ computeBulkPinDirection,computeRangeSelection,orderedVisibleSessionIds,toggleSelection,@@ -46,4 +48,27 @@ describe('todaySessionSelection', () => {const recent = [item('r1'), item('chat', 'chat'), item('r2')]expect(orderedVisibleSessionIds([item('p1')], recent, collapsed)).toEqual(expected)})++ it.each<[string, string[], 'pin' | 'unpin']>([+ ['pins when nothing is pinned', ['t1', 't2'], 'pin'],+ ['pins a mixed selection', ['t1', 'p1'], 'pin'],+ ['unpins when all are pinned', ['p1', 'p2'], 'unpin'],+ ])('bulk pin %s', (_, ids, expected) => {+ expect(computeBulkPinDirection(ids, new Set(['p1', 'p2']))).toEqual(expected)+ })++ it.each([+ [+ 3,+ 1,+ '1 of these 3 sessions is still running. Archiving it will stop its cloud run and shut down the sandbox. You can unarchive them later.',+ ],+ [+ 2,+ 2,+ 'These 2 sessions are still running. Archiving them will stop their cloud runs and shut down the sandboxes. You can unarchive them later.',+ ],+ ])('names the count when archiving %i sessions with %i running', (count, running, expected) => {+ expect(bulkArchiveWarning(count, running)).toEqual(expected)+ })})diff --git a/frontend/src/layout/today/todaySessionSelection.ts b/frontend/src/layout/today/todaySessionSelection.tsindex 79d095f68460..56727ee8eef0 100644--- a/frontend/src/layout/today/todaySessionSelection.ts+++ b/frontend/src/layout/today/todaySessionSelection.ts@@ -9,6 +9,16 @@ export interface TodaySessionSelection {export type TodaySelectionClick = 'toggle' | 'range' | 'open'+export type TodayBulkVerb = 'pin' | 'unpin' | 'file' | 'archive' | 'restore'++const PAST_TENSE: Record<TodayBulkVerb, string> = {+ pin: 'pinned',+ unpin: 'unpinned',+ file: 'filed',+ archive: 'archived',+ restore: 'restored',+}+export const EMPTY_SELECTION: TodaySessionSelection = { ids: [], anchorId: null }export function selectionClick(event: Pick<MouseEvent, 'shiftKey' | 'metaKey' | 'ctrlKey'>): TodaySelectionClick {@@ -56,3 +66,39 @@ export function pruneToVisible(ids: string[], visibleIds: string[]): string[] {const visible = new Set(visibleIds)return ids.filter((id) => visible.has(id))}++/** Pinning wins a mixed selection, so the group ends up in one section instead of split across two. */+export function computeBulkPinDirection(ids: string[], pinnedIds: ReadonlySet<string>): 'pin' | 'unpin' {+ return ids.length > 0 && ids.every((id) => pinnedIds.has(id)) ? 'unpin' : 'pin'+}++export function sessionsLabel(count: number): string {+ return `${count} ${count === 1 ? 'session' : 'sessions'}`+}++export function bulkArchiveWarning(count: number, running: number): string {+ const who =+ running === count+ ? `${count === 1 ? 'This session is' : `These ${count} sessions are`} still running.`+ : `${running} of these ${count} sessions ${running === 1 ? 'is' : 'are'} still running.`+ const what =+ running === 1+ ? 'Archiving it will stop its cloud run and shut down the sandbox.'+ : 'Archiving them will stop their cloud runs and shut down the sandboxes.'+ return `${who} ${what} You can unarchive them later.`+}++export function bulkResultToast(+ verb: TodayBulkVerb,+ succeeded: number,+ failed: number+): { kind: 'success' | 'error'; title: string; description?: string } {+ if (failed === 0) {+ return { kind: 'success', title: `${sessionsLabel(succeeded)} ${PAST_TENSE[verb]}` }+ }+ return {+ kind: 'error',+ title: `Couldn’t ${verb} ${failed} of ${sessionsLabel(succeeded + failed)}`,+ description: verb === 'restore' ? 'Try again.' : 'They’re still selected, so you can try again.',+ }+}diff --git a/frontend/src/layout/today/todaySessionSelectionLogic.test.ts b/frontend/src/layout/today/todaySessionSelectionLogic.test.tsindex fcee4a1c52ed..37ee48aaacca 100644--- a/frontend/src/layout/today/todaySessionSelectionLogic.test.ts+++ b/frontend/src/layout/today/todaySessionSelectionLogic.test.ts@@ -1,6 +1,8 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { toast } from '@posthog/quill'+import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'@@ -9,22 +11,33 @@ import { initKeaTests } from '~/test/init'import { todaySessionSelectionLogic } from './todaySessionSelectionLogic'import { todaySpacesLogic } from './todaySpacesLogic'-const session = (id: string, lastActivityAt: string): object => ({+const session = (id: string, lastActivityAt: string, run: Record<string, unknown> | null = null): object => ({id,title: id,archived: false,channel: null,last_activity_at: lastActivityAt,- latest_run: null,+ latest_run: run,})-const PINNED = [session('task-p', '2026-09-28T12:00:00Z')]+const PINNED = [session('task-p', '2026-09-28T12:00:00Z', { id: 'run-p', status: 'in_progress', environment: 'cloud' })]const RECENT = [session('task-a', '2026-09-28T11:00:00Z'), session('task-b', '2026-09-28T10:00:00Z')]describe('todaySessionSelectionLogic', () => {let logic: ReturnType<typeof todaySessionSelectionLogic.build>+ let requests: string[]+ let failingId: string | null++ const write = (label: string, id: string): [number, object] => {+ requests.push(`${label} ${id}`)+ return id === failingId ? [500, { detail: 'Server error' }] : [200, {}]+ }beforeEach(async () => {+ requests = []+ failingId = null+ jest.spyOn(toast, 'success')+ jest.spyOn(toast, 'error')useMocks({get: {'/api/projects/:team_id/task_channels/': [],@@ -34,6 +47,15 @@ describe('todaySessionSelectionLogic', () => {return [200, { results: pinned ? PINNED : [...PINNED, ...RECENT], count: 3 }]},},+ patch: {+ '/api/projects/:team_id/tasks/:id/': async ({ params, request }) =>+ write(`patch ${JSON.stringify(await request.json())}`, String(params.id)),+ },+ post: {+ '/api/projects/:team_id/tasks/:id/pin/': ({ params }) => write('pin', String(params.id)),+ '/api/projects/:team_id/tasks/:task_id/runs/:id/cancel/': ({ params }) =>+ write(`cancel ${params.id}`, String(params.task_id)),+ },})initKeaTests()logic = todaySessionSelectionLogic()@@ -41,6 +63,47 @@ describe('todaySessionSelectionLogic', () => {await expectLogic(todaySpacesLogic).toDispatchActions(['loadPinnedTasksSuccess', 'loadRecentTasksSuccess'])})+ afterEach(() => {+ jest.restoreAllMocks()+ })++ it.each([+ ['pin', () => logic.actions.pinSelected()],+ ['file', () => logic.actions.fileSelectedTo('space-1')],+ ['archive', () => logic.actions.requestBulkArchive()],+ ])('keeps only the failed sessions selected and shows one toast when a bulk %s partly fails', async (_, run) => {+ failingId = 'task-b'+ logic.actions.setSelection({ ids: ['task-a', 'task-b'], anchorId: 'task-b' })+ run()+ await expectLogic(logic).toDispatchActions(['bulkActionFinished'])++ expect(logic.values.selectedSessionIds).toEqual(['task-b'])+ expect(logic.values.bulkAction).toBeNull()+ expect(toast.error).toHaveBeenCalledTimes(1)+ expect(toast.success).not.toHaveBeenCalled()+ })++ it('asks before archiving a running session, then stops its run before archiving it', async () => {+ logic.actions.setSelection({ ids: ['task-p', 'task-a'], anchorId: 'task-a' })+ logic.actions.requestBulkArchive()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.bulkArchiveConfirm).toEqual({ open: true, count: 2, running: 1 })+ expect(requests).toEqual([])++ logic.actions.archiveSelected()+ await expectLogic(logic).toDispatchActions(['bulkActionFinished'])++ expect([...requests].sort()).toEqual([+ 'cancel run-p task-p',+ 'patch {"archived":true} task-a',+ 'patch {"archived":true} task-p',+ ])+ expect(requests.indexOf('cancel run-p task-p')).toBeLessThan(requests.indexOf('patch {"archived":true} task-p'))+ expect(logic.values.selectedSessionIds).toEqual([])+ expect(logic.values.bulkArchiveConfirm.open).toBe(false)+ })+it('starts a Shift-click range at the open session when nothing was clicked yet, across Pinned and Recent', async () => {router.actions.push(urls.aiTask('task-p'))logic.actions.selectSessionRange('task-b')diff --git a/frontend/src/layout/today/todaySessionSelectionLogic.ts b/frontend/src/layout/today/todaySessionSelectionLogic.tsindex d6da3fd7c8d5..1138938e2809 100644--- a/frontend/src/layout/today/todaySessionSelectionLogic.ts+++ b/frontend/src/layout/today/todaySessionSelectionLogic.ts@@ -2,17 +2,37 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reduimport { router } from 'kea-router'import type { LocationChangedPayload } from 'kea-router/lib/types'+import { toast } from '@posthog/quill'++import { teamLogic } from 'scenes/teamLogic'++import { tasksPartialUpdate, tasksPinCreate, tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'+import { TodayRecentSection } from './todayRecentOrder'import {EMPTY_SELECTION,+ TodayBulkVerb,TodaySessionSelection,+ bulkResultToast,+ computeBulkPinDirection,computeRangeSelection,orderedVisibleSessionIds,pruneToVisible,toggleSelection,} from './todaySessionSelection'import { TodayWorkSectionId, todaySpacesLogic } from './todaySpacesLogic'-import { TodayWorkItem } from './todayWorkItems'+import { TodayWorkItem, activeCloudRunId } from './todayWorkItems'++export type TodayBulkAction = 'pin' | 'file' | 'archive'++/** Counted when the confirm opens, so the closing dialog doesn't retitle itself as the selection clears. */+export interface TodayBulkArchiveConfirm {+ open: boolean+ count: number+ running: number+}++const CLOSED_CONFIRM: TodayBulkArchiveConfirm = { open: false, count: 0, running: 0 }function isEditableTarget(target: EventTarget | null): boolean {return (@@ -23,11 +43,17 @@ function isEditableTarget(target: EventTarget | null): boolean {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface todaySessionSelectionLogicValues {+ currentTeamId: number | null // teamLogiccollapsedSections: TodayWorkSectionId[] // todaySpacesLogicpinnedItems: TodayWorkItem[] // todaySpacesLogicrecentGroups: TodayRecentSection[] // todaySpacesLogic+ bulkAction: TodayBulkAction | null+ bulkArchiveConfirm: TodayBulkArchiveConfirm+ bulkPinDirection: 'pin' | 'unpin'orderedSessionIds: string[]+ runningSelectedCount: numberselectedSessionIds: string[]+ selectedSessions: TodayWorkItem[]selection: TodaySessionSelection}@@ -54,9 +80,39 @@ export interface todaySessionSelectionLogicActions {searchParams: Record<string, any>url: string} // router+ loadPinnedTasks: () => any // todaySpacesLogic+ loadRecentTasks: () => any // todaySpacesLogic+ archiveSelected: () => {+ value: true+ }+ bulkActionFinished: (failedIds: string[]) => {+ failedIds: string[]+ }clearSelection: () => {value: true}+ closeBulkArchiveConfirm: () => {+ value: true+ }+ fileSelectedTo: (spaceId: string) => {+ spaceId: string+ }+ openBulkArchiveConfirm: (+ count: number,+ running: number+ ) => {+ count: number+ running: number+ }+ pinSelected: () => {+ value: true+ }+ requestBulkArchive: () => {+ value: true+ }+ restoreSessions: (sessionIds: string[]) => {+ sessionIds: string[]+ }selectSessionRange: (sessionId: string) => {sessionId: string}@@ -77,6 +133,13 @@ export interface todaySessionSelectionLogicMeta {collapsedSections: TodayWorkSectionId[]) => string[]selectedSessionIds: (selection: TodaySessionSelection, orderedSessionIds: string[]) => string[]+ selectedSessions: (+ selectedSessionIds: string[],+ pinnedItems: TodayWorkItem[],+ recentGroups: TodayRecentSection[]+ ) => TodayWorkItem[]+ bulkPinDirection: (selectedSessionIds: string[], pinnedItems: TodayWorkItem[]) => 'pin' | 'unpin'+ runningSelectedCount: (selectedSessions: TodayWorkItem[]) => number}}@@ -90,14 +153,22 @@ export type todaySessionSelectionLogicType = MakeLogicType<export const todaySessionSelectionLogic = kea<todaySessionSelectionLogicType>([path(['layout', 'today', 'todaySessionSelectionLogic']),connect(() => ({- values: [todaySpacesLogic, ['collapsedSections', 'pinnedItems', 'recentGroups']],- actions: [router, ['locationChanged']],+ values: [teamLogic, ['currentTeamId'], todaySpacesLogic, ['collapsedSections', 'pinnedItems', 'recentGroups']],+ actions: [router, ['locationChanged'], todaySpacesLogic, ['loadPinnedTasks', 'loadRecentTasks']],})),actions({setSelection: (selection: TodaySessionSelection) => ({ selection }),toggleSessionSelection: (sessionId: string) => ({ sessionId }),selectSessionRange: (sessionId: string) => ({ sessionId }),clearSelection: true,+ pinSelected: true,+ fileSelectedTo: (spaceId: string) => ({ spaceId }),+ requestBulkArchive: true,+ openBulkArchiveConfirm: (count: number, running: number) => ({ count, running }),+ closeBulkArchiveConfirm: true,+ archiveSelected: true,+ bulkActionFinished: (failedIds: string[]) => ({ failedIds }),+ restoreSessions: (sessionIds: string[]) => ({ sessionIds }),}),reducers({selection: [@@ -106,9 +177,29 @@ export const todaySessionSelectionLogic = kea<todaySessionSelectionLogicType>([setSelection: (_, { selection }) => selection,toggleSessionSelection: (state, { sessionId }) => toggleSelection(state, sessionId),clearSelection: () => EMPTY_SELECTION,+ // Full success clears the selection; a partial one keeps only the failures, so a retry is one click.+ bulkActionFinished: (state, { failedIds }) =>+ failedIds.length ? { ids: failedIds, anchorId: state.anchorId } : EMPTY_SELECTION,locationChanged: () => EMPTY_SELECTION,},],+ bulkAction: [+ null as TodayBulkAction | null,+ {+ pinSelected: () => 'pin',+ fileSelectedTo: () => 'file',+ archiveSelected: () => 'archive',+ bulkActionFinished: () => null,+ },+ ],+ bulkArchiveConfirm: [+ CLOSED_CONFIRM,+ {+ openBulkArchiveConfirm: (_, { count, running }) => ({ open: true, count, running }),+ closeBulkArchiveConfirm: (state) => ({ ...state, open: false }),+ bulkActionFinished: (state) => ({ ...state, open: false }),+ },+ ],}),selectors({orderedSessionIds: [@@ -130,6 +221,29 @@ export const todaySessionSelectionLogic = kea<todaySessionSelectionLogicType>([(selection: TodaySessionSelection, orderedSessionIds: string[]): string[] =>pruneToVisible(selection.ids, orderedSessionIds),],+ selectedSessions: [+ (s) => [s.selectedSessionIds, s.pinnedItems, s.recentGroups],+ (+ selectedSessionIds: string[],+ pinnedItems: TodayWorkItem[],+ recentGroups: TodayRecentSection[]+ ): TodayWorkItem[] => {+ const items = new Map(+ [...pinnedItems, ...recentGroups.flatMap((group) => group.items)].map((item) => [item.id, item])+ )+ return selectedSessionIds.flatMap((id) => items.get(id) ?? [])+ },+ ],+ bulkPinDirection: [+ (s) => [s.selectedSessionIds, s.pinnedItems],+ (selectedSessionIds: string[], pinnedItems: TodayWorkItem[]): 'pin' | 'unpin' =>+ computeBulkPinDirection(selectedSessionIds, new Set(pinnedItems.map((item) => item.id))),+ ],+ runningSelectedCount: [+ (s) => [s.selectedSessions],+ (selectedSessions: TodayWorkItem[]): number =>+ selectedSessions.filter((item) => activeCloudRunId(item) !== null).length,+ ],}),listeners(({ actions, values }) => ({selectSessionRange: ({ sessionId }) => {@@ -147,10 +261,87 @@ export const todaySessionSelectionLogic = kea<todaySessionSelectionLogicType>([)},})),+ listeners(({ actions, values }) => {+ const teamId = (): string => String(values.currentTeamId)++ /** One request per session, like Desktop, since there is no bulk endpoint. Returns the ids that failed. */+ const runEach = async (ids: string[], request: (id: string) => Promise<unknown>): Promise<string[]> => {+ const results = await Promise.allSettled(ids.map(request))+ return ids.filter((_, index) => results[index].status === 'rejected')+ }++ const report = (verb: TodayBulkVerb, total: number, failed: number, onUndo?: () => void): void => {+ const result = bulkResultToast(verb, total - failed, failed)+ const action = onUndo && total > failed ? { label: 'Undo', onClick: onUndo } : undefined+ if (result.kind === 'success') {+ toast.success({ title: result.title, action })+ } else {+ toast.error({ title: result.title, description: result.description, action })+ }+ }++ const finish = (failedIds: string[]): void => {+ actions.bulkActionFinished(failedIds)+ actions.loadPinnedTasks()+ actions.loadRecentTasks()+ }++ return {+ pinSelected: async () => {+ const ids = values.selectedSessionIds+ const pinned = values.bulkPinDirection === 'pin'+ const failed = await runEach(ids, (id) => tasksPinCreate(teamId(), id, { pinned }))+ report(pinned ? 'pin' : 'unpin', ids.length, failed.length)+ finish(failed)+ },+ fileSelectedTo: async ({ spaceId }) => {+ const ids = values.selectedSessionIds+ const failed = await runEach(ids, (id) => tasksPartialUpdate(teamId(), id, { channel: spaceId }))+ report('file', ids.length, failed.length)+ finish(failed)+ },+ requestBulkArchive: () => {+ if (values.runningSelectedCount > 0) {+ actions.openBulkArchiveConfirm(values.selectedSessionIds.length, values.runningSelectedCount)+ } else {+ actions.archiveSelected()+ }+ },+ archiveSelected: async () => {+ const runIds = new Map(values.selectedSessions.map((item) => [item.id, activeCloudRunId(item)]))+ const ids = [...runIds.keys()]+ const failed = await runEach(ids, async (id) => {+ const runId = runIds.get(id)+ // Archiving alone leaves the cloud run going, so stop it first, as the confirm says.+ if (runId) {+ await tasksRunsCancelCreate(teamId(), id, runId)+ }+ await tasksPartialUpdate(teamId(), id, { archived: true })+ })+ const archivedIds = ids.filter((id) => !failed.includes(id))+ report('archive', ids.length, failed.length, () => actions.restoreSessions(archivedIds))+ finish(failed)+ },+ restoreSessions: async ({ sessionIds }) => {+ const failed = await runEach(sessionIds, (id) => tasksPartialUpdate(teamId(), id, { archived: false }))+ if (failed.length) {+ report('restore', sessionIds.length, failed.length)+ }+ actions.loadPinnedTasks()+ actions.loadRecentTasks()+ },+ }+ }),afterMount(({ actions, values, cache }) => {cache.disposables.add(() => {const onKeyDown = (event: KeyboardEvent): void => {- if (event.key === 'Escape' && !isEditableTarget(event.target) && values.selection.ids.length) {+ // The archive confirm answers Escape itself, and the selection it names has to stay.+ if (+ event.key === 'Escape' &&+ !isEditableTarget(event.target) &&+ !values.bulkArchiveConfirm.open &&+ values.selection.ids.length+ ) {actions.clearSelection()}}