Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(today): select space feed sessions with row checkboxes (#110174)

Shy Alterf90e487ec002
diff --git a/frontend/src/layout/today/TodayChatRow.tsx b/frontend/src/layout/today/TodayChatRow.tsx
index fb345cf688bf..84b2f262f9ab 100644
--- a/frontend/src/layout/today/TodayChatRow.tsx
+++ b/frontend/src/layout/today/TodayChatRow.tsx
@@ -35,6 +35,7 @@ export function TodayChatRow({ item, dataAttr }: TodayChatRowProps): JSX.Element
to={urls.ai(item.id)}
active={location.pathname.endsWith('/ai') && searchParams.chat === item.id}
dataAttr={dataAttr}
+ weight="regular"
/>
</TodayPreviewTrigger>
</ContextMenuTrigger>
diff --git a/frontend/src/layout/today/TodaySessionBulkArchiveDialog.tsx b/frontend/src/layout/today/TodaySessionBulkArchiveDialog.tsx
index 7395df3e96c7..85fa2a3e78d1 100644
--- a/frontend/src/layout/today/TodaySessionBulkArchiveDialog.tsx
+++ b/frontend/src/layout/today/TodaySessionBulkArchiveDialog.tsx
@@ -1,5 +1,3 @@
-import { useActions, useValues } from 'kea'
-
import {
AlertDialog,
AlertDialogContent,
@@ -11,44 +9,55 @@ import {
} from '@posthog/quill'
import { bulkArchiveWarning, sessionsLabel } from './todaySessionSelection'
-import { todaySessionSelectionLogic } from './todaySessionSelectionLogic'
+import { TodayBulkArchiveConfirm } 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'
+interface TodaySessionBulkArchiveDialogProps {
+ confirm: TodayBulkArchiveConfirm
+ archiving: boolean
+ onCancel: () => void
+ onConfirm: () => void
+ /** Starts each button's `data-attr`, so every surface counts on its own. */
+ dataAttrPrefix: string
+}
+/** One confirm for the whole selection, shown when any of it is still running. */
+export function TodaySessionBulkArchiveDialog({
+ confirm,
+ archiving,
+ onCancel,
+ onConfirm,
+ dataAttrPrefix,
+}: TodaySessionBulkArchiveDialogProps): JSX.Element {
return (
<AlertDialog
- open={bulkArchiveConfirm.open}
+ open={confirm.open}
onOpenChange={(open: boolean) => {
if (!open && !archiving) {
- closeBulkArchiveConfirm()
+ onCancel()
}
}}
>
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>{`Archive ${sessionsLabel(bulkArchiveConfirm.count)}?`}</AlertDialogTitle>
+ <AlertDialogTitle>{`Archive ${sessionsLabel(confirm.count)}?`}</AlertDialogTitle>
<AlertDialogDescription>
- {bulkArchiveWarning(bulkArchiveConfirm.count, bulkArchiveConfirm.running)}
+ {bulkArchiveWarning(confirm.count, confirm.running)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<Button
variant="outline"
- onClick={closeBulkArchiveConfirm}
+ onClick={onCancel}
disabled={archiving}
- data-attr="today-session-bulk-archive-cancel"
+ data-attr={`${dataAttrPrefix}-archive-cancel`}
>
Cancel
</Button>
<Button
variant="destructive-outline"
loading={archiving}
- onClick={archiveSelected}
- data-attr="today-session-bulk-archive-confirm"
+ onClick={onConfirm}
+ data-attr={`${dataAttrPrefix}-archive-confirm`}
>
Archive
</Button>
diff --git a/frontend/src/layout/today/TodaySessionBulkBar.tsx b/frontend/src/layout/today/TodaySessionBulkBar.tsx
index 59c3e9b67c52..7e49a34f7ce5 100644
--- a/frontend/src/layout/today/TodaySessionBulkBar.tsx
+++ b/frontend/src/layout/today/TodaySessionBulkBar.tsx
@@ -56,8 +56,16 @@ function BulkButton({ label, action, icon, dataAttr, onClick, wrap }: BulkButton
}
export function TodaySessionBulkBar(): JSX.Element {
- const { selectedSessionIds, bulkPinDirection } = useValues(todaySessionSelectionLogic)
- const { pinSelected, fileSelectedTo, requestBulkArchive, clearSelection } = useActions(todaySessionSelectionLogic)
+ const { selectedSessionIds, bulkPinDirection, bulkArchiveConfirm, bulkAction } =
+ useValues(todaySessionSelectionLogic)
+ const {
+ pinSelected,
+ fileSelectedTo,
+ requestBulkArchive,
+ clearSelection,
+ closeBulkArchiveConfirm,
+ archiveSelected,
+ } = useActions(todaySessionSelectionLogic)
const { spaces } = useValues(todaySpacesLogic)
const count = selectedSessionIds.length
const sessions = sessionsLabel(count)
@@ -126,7 +134,13 @@ export function TodaySessionBulkBar(): JSX.Element {
</div>
</div>
)}
- <TodaySessionBulkArchiveDialog />
+ <TodaySessionBulkArchiveDialog
+ confirm={bulkArchiveConfirm}
+ archiving={bulkAction === 'archive'}
+ onCancel={closeBulkArchiveConfirm}
+ onConfirm={archiveSelected}
+ dataAttrPrefix="today-session-bulk"
+ />
</>
)
}
diff --git a/frontend/src/layout/today/todaySessionBulkRequests.ts b/frontend/src/layout/today/todaySessionBulkRequests.ts
new file mode 100644
index 000000000000..5feded4bfce6
--- /dev/null
+++ b/frontend/src/layout/today/todaySessionBulkRequests.ts
@@ -0,0 +1,46 @@
+import { toast } from '@posthog/quill'
+
+import { tasksPartialUpdate, tasksPinCreate, tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'
+
+import { TodayBulkVerb, bulkResultToast } from './todaySessionSelection'
+import { TodayWorkItem, activeCloudRunId } from './todayWorkItems'
+
+/** One request per session, like Desktop, since there is no bulk endpoint. Returns the ids that failed. */
+async function runEach(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')
+}
+
+export function reportBulkResult(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 })
+ }
+}
+
+export function pinSessions(teamId: string, ids: string[], pinned: boolean): Promise<string[]> {
+ return runEach(ids, (id) => tasksPinCreate(teamId, id, { pinned }))
+}
+
+export function fileSessions(teamId: string, ids: string[], spaceId: string): Promise<string[]> {
+ return runEach(ids, (id) => tasksPartialUpdate(teamId, id, { channel: spaceId }))
+}
+
+export function archiveSessions(teamId: string, sessions: TodayWorkItem[]): Promise<string[]> {
+ const runIds = new Map(sessions.map((item) => [item.id, activeCloudRunId(item)]))
+ return runEach([...runIds.keys()], 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 })
+ })
+}
+
+export function restoreSessions(teamId: string, ids: string[]): Promise<string[]> {
+ return runEach(ids, (id) => tasksPartialUpdate(teamId, id, { archived: false }))
+}
diff --git a/frontend/src/layout/today/todaySessionSelection.ts b/frontend/src/layout/today/todaySessionSelection.ts
index 2cc9db169cc9..d3459c196d02 100644
--- a/frontend/src/layout/today/todaySessionSelection.ts
+++ b/frontend/src/layout/today/todaySessionSelection.ts
@@ -21,6 +21,13 @@ const PAST_TENSE: Record<TodayBulkVerb, string> = {
export const EMPTY_SELECTION: TodaySessionSelection = { ids: [], anchorId: null }
+export function isEditableTarget(target: EventTarget | null): boolean {
+ return (
+ target instanceof HTMLElement &&
+ (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName))
+ )
+}
+
export function selectionClick(event: Pick<MouseEvent, 'shiftKey' | 'metaKey' | 'ctrlKey'>): TodaySelectionClick {
return event.shiftKey ? 'range' : event.metaKey || event.ctrlKey ? 'toggle' : 'open'
}
diff --git a/frontend/src/layout/today/todaySessionSelectionLogic.ts b/frontend/src/layout/today/todaySessionSelectionLogic.ts
index 1138938e2809..ed764b9edcaa 100644
--- a/frontend/src/layout/today/todaySessionSelectionLogic.ts
+++ b/frontend/src/layout/today/todaySessionSelectionLogic.ts
@@ -2,20 +2,22 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, redu
import { 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 {
+ archiveSessions,
+ fileSessions,
+ pinSessions,
+ reportBulkResult,
+ restoreSessions,
+} from './todaySessionBulkRequests'
import {
EMPTY_SELECTION,
- TodayBulkVerb,
TodaySessionSelection,
- bulkResultToast,
computeBulkPinDirection,
computeRangeSelection,
+ isEditableTarget,
orderedVisibleSessionIds,
pruneToVisible,
toggleSelection,
@@ -32,14 +34,7 @@ export interface TodayBulkArchiveConfirm {
running: number
}
-const CLOSED_CONFIRM: TodayBulkArchiveConfirm = { open: false, count: 0, running: 0 }
-
-function isEditableTarget(target: EventTarget | null): boolean {
- return (
- target instanceof HTMLElement &&
- (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName))
- )
-}
+export const CLOSED_BULK_ARCHIVE_CONFIRM: TodayBulkArchiveConfirm = { open: false, count: 0, running: 0 }
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todaySessionSelectionLogicValues {
@@ -193,7 +188,7 @@ export const todaySessionSelectionLogic = kea<todaySessionSelectionLogicType>([
},
],
bulkArchiveConfirm: [
- CLOSED_CONFIRM,
+ CLOSED_BULK_ARCHIVE_CONFIRM,
{
openBulkArchiveConfirm: (_, { count, running }) => ({ open: true, count, running }),
closeBulkArchiveConfirm: (state) => ({ ...state, open: false }),
@@ -264,22 +259,6 @@ 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()
@@ -290,14 +269,14 @@ export const todaySessionSelectionLogic = kea<todaySessionSelectionLogicType>([
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)
+ const failed = await pinSessions(teamId(), ids, pinned)
+ reportBulkResult(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)
+ const failed = await fileSessions(teamId(), ids, spaceId)
+ reportBulkResult('file', ids.length, failed.length)
finish(failed)
},
requestBulkArchive: () => {
@@ -308,24 +287,16 @@ export const todaySessionSelectionLogic = kea<todaySessionSelectionLogicType>([
}
},
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 ids = values.selectedSessions.map((item) => item.id)
+ const failed = await archiveSessions(teamId(), values.selectedSessions)
const archivedIds = ids.filter((id) => !failed.includes(id))
- report('archive', ids.length, failed.length, () => actions.restoreSessions(archivedIds))
+ reportBulkResult('archive', ids.length, failed.length, () => actions.restoreSessions(archivedIds))
finish(failed)
},
restoreSessions: async ({ sessionIds }) => {
- const failed = await runEach(sessionIds, (id) => tasksPartialUpdate(teamId(), id, { archived: false }))
+ const failed = await restoreSessions(teamId(), sessionIds)
if (failed.length) {
- report('restore', sessionIds.length, failed.length)
+ reportBulkResult('restore', sessionIds.length, failed.length)
}
actions.loadPinnedTasks()
actions.loadRecentTasks()
diff --git a/products/tasks/frontend/spaces/SpaceFeed.tsx b/products/tasks/frontend/spaces/SpaceFeed.tsx
index c1750cad1ce1..663433d0427d 100644
--- a/products/tasks/frontend/spaces/SpaceFeed.tsx
+++ b/products/tasks/frontend/spaces/SpaceFeed.tsx
@@ -11,6 +11,7 @@ import { SpaceFeedControls } from './SpaceFeedControls'
import { SPACE_FEED_TYPES, SpaceFeedType } from './spaceFeedEntries'
import { SpaceFeedListRow } from './SpaceFeedListRow'
import { SpaceFeedPullRequestRow } from './SpaceFeedPullRequestRow'
+import { SpaceFeedSelectionBar } from './SpaceFeedSelectionBar'
import { SpaceFeedSkeleton } from './SpaceFeedSkeleton'
import { spaceFeedViewLogic } from './spaceFeedViewLogic'
import { SpaceFeedWelcome } from './SpaceFeedWelcome'
@@ -52,6 +53,7 @@ export function SpaceFeed({ id }: { id: string }): JSX.Element {
// No gap: the cards' own margins and the separators' padding space the feed, like PostHog Desktop.
<div className="flex flex-col">
<SpaceFeedControls sourceOptions={feedSourceOptions} />
+ <SpaceFeedSelectionBar spaceId={id} />
{feedStatus.sessions === 'failed' && (
<div className="flex flex-col items-start gap-2 px-2 pt-4">
<Text size="sm" variant="muted">
@@ -174,6 +176,7 @@ export function SpaceFeed({ id }: { id: string }): JSX.Element {
return listRows ? (
<div key={entry.key} className={rowClassName}>
<SpaceFeedListRow
+ spaceId={id}
task={task}
pinned={pinnedIds.has(task.id)}
unread={unreadSessionIds.has(task.id)}
@@ -182,6 +185,7 @@ export function SpaceFeed({ id }: { id: string }): JSX.Element {
) : (
<SpaceFeedCard
key={entry.key}
+ spaceId={id}
task={task}
pinned={pinnedIds.has(task.id)}
unread={unreadSessionIds.has(task.id)}
diff --git a/products/tasks/frontend/spaces/SpaceFeedCanvasRow.tsx b/products/tasks/frontend/spaces/SpaceFeedCanvasRow.tsx
index 336bea4ccc5d..751ab1fd7cba 100644
--- a/products/tasks/frontend/spaces/SpaceFeedCanvasRow.tsx
+++ b/products/tasks/frontend/spaces/SpaceFeedCanvasRow.tsx
@@ -59,6 +59,7 @@ export function SpaceFeedCanvasRow({ canvas, listRow }: SpaceFeedCanvasRowProps)
if (listRow) {
return (
<div className="relative flex h-8 w-full items-center gap-2 rounded-md px-2">
+ <span aria-hidden className="size-3.5 shrink-0" />
{icon}
{name('flex-1 text-sm font-medium')}
{avatar}
@@ -71,6 +72,7 @@ export function SpaceFeedCanvasRow({ canvas, listRow }: SpaceFeedCanvasRowProps)
return (
<Card size="sm" className="relative my-1.5 gap-0 rounded-xl px-4 pt-3.5 pb-3">
<div className="flex min-w-0 items-center gap-3">
+ <span aria-hidden className="size-3.5 shrink-0" />
<div className="flex min-w-0 flex-1 items-baseline gap-1.5">
<span className="flex translate-y-0.5">{icon}</span>
{name('text-sm leading-snug font-semibold')}
diff --git a/products/tasks/frontend/spaces/SpaceFeedCard.tsx b/products/tasks/frontend/spaces/SpaceFeedCard.tsx
index d20faaa99f8e..9f2b908d7721 100644
--- a/products/tasks/frontend/spaces/SpaceFeedCard.tsx
+++ b/products/tasks/frontend/spaces/SpaceFeedCard.tsx
@@ -34,6 +34,7 @@ import { getOriginProductMeta } from 'products/posthog_ai/frontend/api/taskSourc
import { TaskListItemApi } from '../generated/api.schemas'
import { SpaceFeedCardPrompt } from './SpaceFeedCardPrompt'
import { spaceFeedPreview } from './spaceFeedPreview'
+import { SpaceFeedSelectCheckbox } from './SpaceFeedSelectCheckbox'
import { spaceFeedStatus } from './spaceFeedStatus'
import { SpaceFeedStatusIcon } from './SpaceFeedStatusIcon'
import { TaskFile, VISIBLE_FILE_COUNT, taskFiles } from './taskFiles'
@@ -59,6 +60,7 @@ function TaskFileChip({ file }: { file: TaskFile }): JSX.Element {
}
interface SpaceFeedCardProps {
+ spaceId: string
task: TaskListItemApi
pinned: boolean
unread: boolean
@@ -66,7 +68,7 @@ interface SpaceFeedCardProps {
repository: string | null
}
-export function SpaceFeedCard({ task, pinned, unread, repository }: SpaceFeedCardProps): JSX.Element {
+export function SpaceFeedCard({ spaceId, task, pinned, unread, repository }: SpaceFeedCardProps): JSX.Element {
const { renaming } = useValues(todaySessionMenuLogic)
const { user } = useValues(userLogic)
const { pullRequestStates } = useValues(todaySpacesLogic)
@@ -90,6 +92,11 @@ export function SpaceFeedCard({ task, pinned, unread, repository }: SpaceFeedCar
className="group/card relative my-1.5 gap-0 rounded-xl px-4 pt-3.5 pb-3 transition hover:bg-fill-hover hover:ring-1 hover:ring-input"
>
<div className="flex min-w-0 items-center gap-3">
+ <SpaceFeedSelectCheckbox
+ spaceId={spaceId}
+ sessionId={task.id}
+ title={item.title || 'Untitled session'}
+ />
{renaming?.sessionId === task.id && renaming.surface === 'feed' ? (
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<SpaceFeedStatusIcon item={item} />
diff --git a/products/tasks/frontend/spaces/SpaceFeedListRow.tsx b/products/tasks/frontend/spaces/SpaceFeedListRow.tsx
index cba2906f28e7..cc9a88644681 100644
--- a/products/tasks/frontend/spaces/SpaceFeedListRow.tsx
+++ b/products/tasks/frontend/spaces/SpaceFeedListRow.tsx
@@ -18,18 +18,20 @@ import { sessionItem, sessionMenuTarget, shortTimeAgo } from '~/layout/today/tod
import { getOriginProductMeta } from 'products/posthog_ai/frontend/api/taskSource'
import { TaskListItemApi } from '../generated/api.schemas'
+import { SpaceFeedSelectCheckbox } from './SpaceFeedSelectCheckbox'
import { spaceFeedStatus } from './spaceFeedStatus'
import { SpaceFeedStatusIcon } from './SpaceFeedStatusIcon'
import { TaskUserAvatar, taskUserName } from './TaskUserAvatar'
interface SpaceFeedListRowProps {
+ spaceId: string
task: TaskListItemApi
pinned: boolean
unread: boolean
}
/** A session as one compact row of the feed's list view, like PostHog Desktop's. */
-export function SpaceFeedListRow({ task, pinned, unread }: SpaceFeedListRowProps): JSX.Element {
+export function SpaceFeedListRow({ spaceId, task, pinned, unread }: SpaceFeedListRowProps): JSX.Element {
const { renaming } = useValues(todaySessionMenuLogic)
const { user } = useValues(userLogic)
const { pullRequestStates } = useValues(todaySpacesLogic)
@@ -44,6 +46,7 @@ export function SpaceFeedListRow({ task, pinned, unread }: SpaceFeedListRowProps
if (renaming?.sessionId === task.id && renaming.surface === 'feed') {
return (
<div className="flex h-8 items-center gap-2 px-2">
+ <span aria-hidden className="size-3.5 shrink-0" />
<SpaceFeedStatusIcon item={item} />
<div className="min-w-0 flex-1">
<TodaySessionRenameInput sessionId={task.id} title={task.title} />
@@ -55,6 +58,11 @@ export function SpaceFeedListRow({ task, pinned, unread }: SpaceFeedListRowProps
<>
<TodaySessionContextMenu target={menu} surface="feed">
<div className="group/row relative flex h-8 w-full items-center gap-2 rounded-md px-2 transition-colors hover:bg-fill-selected">
+ <SpaceFeedSelectCheckbox
+ spaceId={spaceId}
+ sessionId={task.id}
+ title={item.title || 'Untitled session'}
+ />
<SpaceFeedStatusIcon item={item} />
<LinkPrimitive
to={urls.aiTask(task.id)}
diff --git a/products/tasks/frontend/spaces/SpaceFeedPullRequestRow.tsx b/products/tasks/frontend/spaces/SpaceFeedPullRequestRow.tsx
index 8cb7de2597b6..02c206a026db 100644
--- a/products/tasks/frontend/spaces/SpaceFeedPullRequestRow.tsx
+++ b/products/tasks/frontend/spaces/SpaceFeedPullRequestRow.tsx
@@ -70,6 +70,7 @@ export function SpaceFeedPullRequestRow({
if (listRow) {
return (
<div className="relative flex h-8 w-full items-center gap-2 rounded-md px-2 transition-colors hover:bg-fill-selected">
+ <span aria-hidden className="size-3.5 shrink-0" />
{icon}
{number}
{link('flex-1 text-sm font-medium')}
@@ -94,6 +95,7 @@ export function SpaceFeedPullRequestRow({
className="relative my-1.5 gap-0 rounded-xl px-4 pt-3.5 pb-3 transition-colors hover:bg-fill-hover"
>
<div className="flex min-w-0 items-center gap-3">
+ <span aria-hidden className="size-3.5 shrink-0" />
<div className="flex min-w-0 flex-1 items-baseline gap-1.5">
<span className="flex translate-y-0.5">{icon}</span>
{number}
diff --git a/products/tasks/frontend/spaces/SpaceFeedSelectCheckbox.tsx b/products/tasks/frontend/spaces/SpaceFeedSelectCheckbox.tsx
new file mode 100644
index 000000000000..37b5401aeeeb
--- /dev/null
+++ b/products/tasks/frontend/spaces/SpaceFeedSelectCheckbox.tsx
@@ -0,0 +1,41 @@
+import { useActions, useValues } from 'kea'
+
+import { Checkbox, cn } from '@posthog/quill'
+
+import { spaceFeedSelectionLogic } from './spaceFeedSelectionLogic'
+
+interface SpaceFeedSelectCheckboxProps {
+ spaceId: string
+ sessionId: string
+ title: string
+}
+
+/** Picks a session for the feed's bulk actions, like a row checkbox in Gmail. Shift-click picks a range. */
+export function SpaceFeedSelectCheckbox({ spaceId, sessionId, title }: SpaceFeedSelectCheckboxProps): JSX.Element {
+ const { selectedSessionIds } = useValues(spaceFeedSelectionLogic({ id: spaceId }))
+ const { toggleSessionSelection, selectSessionRange } = useActions(spaceFeedSelectionLogic({ id: spaceId }))
+ const selecting = selectedSessionIds.length > 0
+
+ return (
+ <Checkbox
+ size="sm"
+ checked={selectedSessionIds.includes(sessionId)}
+ onCheckedChange={(_, { event }) => {
+ if (event instanceof MouseEvent && event.shiftKey) {
+ selectSessionRange(sessionId)
+ } else {
+ toggleSessionSelection(sessionId)
+ }
+ }}
+ onClick={(event) => event.stopPropagation()}
+ aria-label={`Select ${title}`}
+ // Above the row link's overlay, so a click picks the session instead of opening it.
+ className={cn(
+ 'z-1 transition-opacity',
+ !selecting &&
+ 'opacity-0 group-focus-within/card:opacity-100 group-focus-within/row:opacity-100 group-hover/card:opacity-100 group-hover/row:opacity-100'
+ )}
+ data-attr="today-space-feed-select"
+ />
+ )
+}
diff --git a/products/tasks/frontend/spaces/SpaceFeedSelectionBar.tsx b/products/tasks/frontend/spaces/SpaceFeedSelectionBar.tsx
new file mode 100644
index 000000000000..0cfd467ae093
--- /dev/null
+++ b/products/tasks/frontend/spaces/SpaceFeedSelectionBar.tsx
@@ -0,0 +1,164 @@
+import { useActions, useValues } from 'kea'
+
+import { IconArchive, IconFolder, IconPin, IconPinFilled, IconX } from '@posthog/icons'
+import {
+ Button,
+ Checkbox,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+ Text,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@posthog/quill'
+
+import { TodaySessionBulkArchiveDialog } from '~/layout/today/TodaySessionBulkArchiveDialog'
+import { sessionsLabel } from '~/layout/today/todaySessionSelection'
+import { TodayBulkAction } from '~/layout/today/todaySessionSelectionLogic'
+import { TodaySpaceFileList } from '~/layout/today/TodaySpaceFileList'
+import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'
+
+import { spaceFeedSelectionLogic } from './spaceFeedSelectionLogic'
+
+const BUSY_REASON = 'Wait for the current change to finish'
+
+interface BulkButtonProps {
+ spaceId: string
+ label: string
+ action: TodayBulkAction
+ 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
+}
+
+function BulkButton({ spaceId, label, action, icon, dataAttr, onClick, wrap }: BulkButtonProps): JSX.Element {
+ const { bulkAction } = useValues(spaceFeedSelectionLogic({ id: spaceId }))
+ const loading = bulkAction === action
+ const busy = bulkAction !== null && !loading
+ const button = (
+ <Button variant="outline" size="sm" loading={loading} disabled={busy} onClick={onClick} data-attr={dataAttr} />
+ )
+ return (
+ <Tooltip disabled={!busy}>
+ <TooltipTrigger delay={0} render={wrap ? wrap(button) : button}>
+ {icon}
+ {label}
+ </TooltipTrigger>
+ <TooltipContent>{BUSY_REASON}</TooltipContent>
+ </Tooltip>
+ )
+}
+
+/** Shows above the feed while sessions are picked, with the same bulk actions as the sidebar's selection bar. */
+export function SpaceFeedSelectionBar({ spaceId }: { spaceId: string }): JSX.Element {
+ const logic = spaceFeedSelectionLogic({ id: spaceId })
+ const { selectedSessionIds, selectAll, bulkPinDirection, bulkArchiveConfirm, bulkAction } = useValues(logic)
+ const {
+ toggleSelectAll,
+ pinSelected,
+ fileSelectedTo,
+ requestBulkArchive,
+ clearSelection,
+ closeBulkArchiveConfirm,
+ archiveSelected,
+ } = useActions(logic)
+ const { spaces } = useValues(todaySpacesLogic)
+ const count = selectedSessionIds.length
+ const pin = bulkPinDirection === 'pin'
+
+ return (
+ <>
+ {/* The bar unmounts with an empty selection, so the announcement lives outside it. */}
+ <span aria-live="polite" className="sr-only">
+ {count > 0 ? `${sessionsLabel(count)} selected` : ''}
+ </span>
+ {count > 0 && (
+ <div
+ className="mb-1 flex flex-wrap items-center gap-x-3 gap-y-1 rounded-md bg-fill-selected px-2 py-1"
+ data-attr="today-space-feed-bulk-bar"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <Checkbox
+ size="sm"
+ checked={selectAll === 'all'}
+ indeterminate={selectAll === 'some'}
+ onCheckedChange={toggleSelectAll}
+ aria-label="Select all sessions"
+ data-attr="today-space-feed-select-all"
+ />
+ <Text size="sm" weight="medium" render={<span />} className="shrink-0">
+ {`${count} selected`}
+ </Text>
+ <Text size="xs" variant="muted" render={<span />} className="truncate">
+ Esc to clear
+ </Text>
+ </div>
+ <div className="ml-auto flex flex-wrap items-center gap-1">
+ <BulkButton
+ spaceId={spaceId}
+ label={pin ? 'Pin' : 'Unpin'}
+ action="pin"
+ icon={pin ? <IconPin /> : <IconPinFilled />}
+ onClick={pinSelected}
+ dataAttr="today-space-feed-bulk-pin"
+ />
+ {spaces.length > 1 && (
+ <DropdownMenu>
+ <BulkButton
+ spaceId={spaceId}
+ label="File to…"
+ action="file"
+ icon={<IconFolder />}
+ wrap={(button) => <DropdownMenuTrigger render={button} />}
+ dataAttr="today-space-feed-bulk-file"
+ />
+ <DropdownMenuContent align="end" className="max-h-80 w-64">
+ <TodaySpaceFileList
+ currentSpaceId={spaceId}
+ onSelect={fileSelectedTo}
+ itemDataAttr="today-space-feed-bulk-file-space"
+ searchDataAttr="today-space-feed-bulk-file-search"
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ <BulkButton
+ spaceId={spaceId}
+ label="Archive"
+ action="archive"
+ icon={<IconArchive />}
+ onClick={requestBulkArchive}
+ dataAttr="today-space-feed-bulk-archive"
+ />
+ <Tooltip>
+ <TooltipTrigger
+ delay={0}
+ render={
+ <Button
+ size="icon-sm"
+ aria-label="Clear selection"
+ onClick={clearSelection}
+ data-attr="today-space-feed-bulk-clear"
+ />
+ }
+ >
+ <IconX />
+ </TooltipTrigger>
+ <TooltipContent>Clear selection</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ )}
+ <TodaySessionBulkArchiveDialog
+ confirm={bulkArchiveConfirm}
+ archiving={bulkAction === 'archive'}
+ onCancel={closeBulkArchiveConfirm}
+ onConfirm={archiveSelected}
+ dataAttrPrefix="today-space-feed-bulk"
+ />
+ </>
+ )
+}
diff --git a/products/tasks/frontend/spaces/spaceFeedSelection.test.ts b/products/tasks/frontend/spaces/spaceFeedSelection.test.ts
new file mode 100644
index 000000000000..bf0853984bfc
--- /dev/null
+++ b/products/tasks/frontend/spaces/spaceFeedSelection.test.ts
@@ -0,0 +1,42 @@
+import { TodaySessionSelection } from '~/layout/today/todaySessionSelection'
+import { TodayWorkItem } from '~/layout/today/todayWorkItems'
+
+import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'
+
+import { SpaceFeedSection } from './spaceFeedEntries'
+import { spaceFeedSessions, toggleAllSelection } from './spaceFeedSelection'
+
+function item(id: string): TodayWorkItem {
+ return { id, kind: 'session' } as TodayWorkItem
+}
+
+describe('spaceFeedSelection', () => {
+ it('lists only session rows, in feed order across sections', () => {
+ const sections: SpaceFeedSection[] = [
+ {
+ key: 'today',
+ label: 'Today',
+ entries: [
+ { kind: 'task', key: 't2', item: item('t2') },
+ {
+ kind: 'pr',
+ key: 'pr:1',
+ item: item('t2'),
+ pullRequest: { url: 'https://github.com/acme/web/pull/1', number: 1, repository: 'acme/web' },
+ },
+ { kind: 'canvas', key: 'canvas:c1', canvas: { id: 'c1' } as CanvasApi },
+ ],
+ },
+ { key: 'older', label: 'Older', entries: [{ kind: 'task', key: 't1', item: item('t1') }] },
+ ]
+
+ expect(spaceFeedSessions(sections).map((session) => session.id)).toEqual(['t2', 't1'])
+ })
+
+ it.each<[string, string[], TodaySessionSelection]>([
+ ['selects every session from a partial pick', ['t2'], { ids: ['t1', 't2', 't3'], anchorId: null }],
+ ['clears a full pick', ['t3', 't1', 't2'], { ids: [], anchorId: null }],
+ ])('select all %s', (_, selected, expected) => {
+ expect(toggleAllSelection(selected, ['t1', 't2', 't3'])).toEqual(expected)
+ })
+})
diff --git a/products/tasks/frontend/spaces/spaceFeedSelection.ts b/products/tasks/frontend/spaces/spaceFeedSelection.ts
new file mode 100644
index 000000000000..b6f9bbce3c11
--- /dev/null
+++ b/products/tasks/frontend/spaces/spaceFeedSelection.ts
@@ -0,0 +1,24 @@
+import { EMPTY_SELECTION, TodaySessionSelection } from '~/layout/today/todaySessionSelection'
+import { TodayWorkItem } from '~/layout/today/todayWorkItems'
+
+import { SpaceFeedSection } from './spaceFeedEntries'
+
+export type SpaceFeedSelectAllState = 'none' | 'some' | 'all'
+
+/** The sessions the feed shows, top to bottom. PR and canvas rows are not sessions, so they are skipped. */
+export function spaceFeedSessions(sections: SpaceFeedSection[]): TodayWorkItem[] {
+ return sections.flatMap((section) => section.entries.flatMap((entry) => (entry.kind === 'task' ? entry.item : [])))
+}
+
+export function selectAllState(selectedIds: string[], orderedIds: string[]): SpaceFeedSelectAllState {
+ if (!selectedIds.length) {
+ return 'none'
+ }
+ const selected = new Set(selectedIds)
+ return orderedIds.every((id) => selected.has(id)) ? 'all' : 'some'
+}
+
+/** A partial selection grows to every session in view; a full one clears. */
+export function toggleAllSelection(selectedIds: string[], orderedIds: string[]): TodaySessionSelection {
+ return selectAllState(selectedIds, orderedIds) === 'all' ? EMPTY_SELECTION : { ids: orderedIds, anchorId: null }
+}
diff --git a/products/tasks/frontend/spaces/spaceFeedSelectionLogic.test.ts b/products/tasks/frontend/spaces/spaceFeedSelectionLogic.test.ts
new file mode 100644
index 000000000000..3327c4033b24
--- /dev/null
+++ b/products/tasks/frontend/spaces/spaceFeedSelectionLogic.test.ts
@@ -0,0 +1,86 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { DEFAULT_SPACE_FEED_FILTERS } from './spaceFeedEntries'
+import { spaceFeedSelectionLogic } from './spaceFeedSelectionLogic'
+import { spaceFeedViewLogic } from './spaceFeedViewLogic'
+import { spaceSceneLogic } from './spaceSceneLogic'
+
+describe('spaceFeedSelectionLogic', () => {
+ let logic: ReturnType<typeof spaceFeedSelectionLogic.build>
+ let archivedIds: string[]
+
+ beforeEach(async () => {
+ archivedIds = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/task_channels/': [],
+ '/api/projects/:team_id/task_channels/:id/': ({ params }) => [200, { id: params.id, name: 'Space' }],
+ '/api/projects/:team_id/task_activity/': { results: [] },
+ '/api/projects/:team_id/canvases/': { results: [], count: 0 },
+ '/api/projects/:team_id/tasks/': ({ request }) => {
+ const channel = new URL(request.url).searchParams.get('channel')
+ const results = ['task-1', 'task-2', 'task-3'].map((id, index) => ({
+ id,
+ title: id,
+ channel,
+ archived: archivedIds.includes(id),
+ last_activity_at: `2026-09-2${8 - index}T12:00:00Z`,
+ latest_run: null,
+ }))
+ return [200, { results: channel ? results : [], count: channel ? results.length : 0 }]
+ },
+ },
+ patch: {
+ '/api/projects/:team_id/tasks/:id/': async ({ params, request }) => {
+ if (((await request.json()) as { archived?: boolean }).archived) {
+ archivedIds.push(String(params.id))
+ }
+ return [200, {}]
+ },
+ },
+ })
+ initKeaTests()
+ logic = spaceFeedSelectionLogic({ id: 'space-a' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('selects a Shift-click range in feed order from the last toggled session', () => {
+ expect(logic.values.orderedSessionIds).toEqual(['task-1', 'task-2', 'task-3'])
+
+ logic.actions.toggleSessionSelection('task-3')
+ logic.actions.selectSessionRange('task-1')
+
+ expect(logic.values.selectedSessionIds).toEqual(['task-3', 'task-1', 'task-2'])
+ expect(logic.values.selectAll).toBe('all')
+ })
+
+ it('archives the selection and drops it from the feed', async () => {
+ logic.actions.setSelection({ ids: ['task-1', 'task-2'], anchorId: 'task-2' })
+ logic.actions.requestBulkArchive()
+ await expectLogic(logic).toDispatchActions(['bulkActionFinished'])
+ await expectLogic(spaceSceneLogic({ id: 'space-a' })).toDispatchActions(['loadSessionsSuccess'])
+
+ expect(archivedIds.sort()).toEqual(['task-1', 'task-2'])
+ expect(logic.values.orderedSessionIds).toEqual(['task-3'])
+ expect(logic.values.selectedSessionIds).toEqual([])
+ })
+
+ it.each([
+ ['the view changes', () => spaceFeedViewLogic.actions.setView('list')],
+ ['the types change', () => spaceFeedViewLogic.actions.setTypes(['task'])],
+ [
+ 'the filters change',
+ () => spaceFeedViewLogic.actions.setFilters({ ...DEFAULT_SPACE_FEED_FILTERS, pinned: 'pinned' }),
+ ],
+ ['Escape is pressed', () => window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))],
+ ])('clears the selection when %s', (_, clear) => {
+ logic.actions.setSelection({ ids: ['task-1', 'task-2'], anchorId: 'task-2' })
+ clear()
+
+ expect(logic.values.selection.ids).toEqual([])
+ })
+})
diff --git a/products/tasks/frontend/spaces/spaceFeedSelectionLogic.ts b/products/tasks/frontend/spaces/spaceFeedSelectionLogic.ts
new file mode 100644
index 000000000000..0418a6ff40ac
--- /dev/null
+++ b/products/tasks/frontend/spaces/spaceFeedSelectionLogic.ts
@@ -0,0 +1,357 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { router } from 'kea-router'
+import type { LocationChangedPayload } from 'kea-router/lib/types'
+
+import {
+ archiveSessions,
+ fileSessions,
+ pinSessions,
+ reportBulkResult,
+ restoreSessions,
+} from '~/layout/today/todaySessionBulkRequests'
+import {
+ EMPTY_SELECTION,
+ TodaySessionSelection,
+ computeBulkPinDirection,
+ computeRangeSelection,
+ isEditableTarget,
+ pruneToVisible,
+ toggleSelection,
+} from '~/layout/today/todaySessionSelection'
+import {
+ CLOSED_BULK_ARCHIVE_CONFIRM,
+ TodayBulkAction,
+ TodayBulkArchiveConfirm,
+} from '~/layout/today/todaySessionSelectionLogic'
+import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'
+import { TodayWorkItem, activeCloudRunId } from '~/layout/today/todayWorkItems'
+
+import { SpaceFeedFilters, SpaceFeedSection, SpaceFeedType, SpaceFeedView } from './spaceFeedEntries'
+import { SpaceFeedSelectAllState, selectAllState, spaceFeedSessions, toggleAllSelection } from './spaceFeedSelection'
+import { spaceFeedViewLogic } from './spaceFeedViewLogic'
+import { spaceSceneLogic } from './spaceSceneLogic'
+
+export interface SpaceFeedSelectionLogicProps {
+ id: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface spaceFeedSelectionLogicValues {
+ currentTeamId: number | null // spaceSceneLogic
+ feedSections: SpaceFeedSection[] // spaceSceneLogic
+ pinnedItems: TodayWorkItem[] // todaySpacesLogic
+ bulkAction: TodayBulkAction | null
+ bulkArchiveConfirm: TodayBulkArchiveConfirm
+ bulkPinDirection: 'pin' | 'unpin'
+ feedSessions: TodayWorkItem[]
+ orderedSessionIds: string[]
+ runningSelectedCount: number
+ selectAll: SpaceFeedSelectAllState
+ selectedSessionIds: string[]
+ selectedSessions: TodayWorkItem[]
+ selection: TodaySessionSelection
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface spaceFeedSelectionLogicActions {
+ locationChanged: ({
+ method,
+ pathname,
+ search,
+ searchParams,
+ hash,
+ hashParams,
+ initial,
+ url,
+ routerState,
+ }: LocationChangedPayload) => {
+ hash: string
+ hashParams: Record<string, any>
+ initial: boolean
+ method: 'POP' | 'PUSH' | 'REPLACE'
+ pathname: string
+ routerState: Record<string, any>
+ search: string
+ searchParams: Record<string, any>
+ url: string
+ } // router
+ clearFilters: () => {
+ value: true
+ } // spaceFeedViewLogic
+ setFilters: (filters: SpaceFeedFilters) => {
+ filters: SpaceFeedFilters
+ } // spaceFeedViewLogic
+ setTypes: (types: SpaceFeedType[]) => {
+ types: SpaceFeedType[]
+ } // spaceFeedViewLogic
+ setView: (view: SpaceFeedView) => {
+ view: SpaceFeedView
+ } // spaceFeedViewLogic
+ loadSessions: () => any // spaceSceneLogic
+ 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
+ }
+ setSelection: (selection: TodaySessionSelection) => {
+ selection: TodaySessionSelection
+ }
+ toggleSelectAll: () => {
+ value: true
+ }
+ toggleSessionSelection: (sessionId: string) => {
+ sessionId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface spaceFeedSelectionLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ feedSessions: (feedSections: SpaceFeedSection[]) => TodayWorkItem[]
+ orderedSessionIds: (feedSessions: TodayWorkItem[]) => string[]
+ selectedSessionIds: (selection: TodaySessionSelection, orderedSessionIds: string[]) => string[]
+ selectedSessions: (selectedSessionIds: string[], feedSessions: TodayWorkItem[]) => TodayWorkItem[]
+ selectAll: (selectedSessionIds: string[], orderedSessionIds: string[]) => SpaceFeedSelectAllState
+ bulkPinDirection: (selectedSessionIds: string[], pinnedItems: TodayWorkItem[]) => 'pin' | 'unpin'
+ runningSelectedCount: (selectedSessions: TodayWorkItem[]) => number
+ }
+}
+
+export type spaceFeedSelectionLogicType = MakeLogicType<
+ spaceFeedSelectionLogicValues,
+ spaceFeedSelectionLogicActions,
+ SpaceFeedSelectionLogicProps,
+ spaceFeedSelectionLogicMeta
+>
+
+/** The sessions picked in a space's feed for a bulk change. Separate from the sidebar's pick, which spans spaces. */
+export const spaceFeedSelectionLogic: LogicWrapper<spaceFeedSelectionLogicType> = kea<spaceFeedSelectionLogicType>([
+ props({} as SpaceFeedSelectionLogicProps),
+ key((props) => props.id),
+ path((id) => ['products', 'tasks', 'spaces', 'spaceFeedSelectionLogic', id]),
+ connect((props: SpaceFeedSelectionLogicProps) => ({
+ values: [spaceSceneLogic(props), ['currentTeamId', 'feedSections'], todaySpacesLogic, ['pinnedItems']],
+ actions: [
+ router,
+ ['locationChanged'],
+ spaceSceneLogic(props),
+ ['loadSessions'],
+ spaceFeedViewLogic,
+ ['clearFilters', 'setFilters', 'setTypes', 'setView'],
+ todaySpacesLogic,
+ ['loadPinnedTasks', 'loadRecentTasks'],
+ ],
+ })),
+ actions({
+ setSelection: (selection: TodaySessionSelection) => ({ selection }),
+ toggleSessionSelection: (sessionId: string) => ({ sessionId }),
+ selectSessionRange: (sessionId: string) => ({ sessionId }),
+ toggleSelectAll: true,
+ 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: [
+ EMPTY_SELECTION,
+ {
+ setSelection: (_, { selection }) => selection,
+ toggleSessionSelection: (state, { sessionId }) => toggleSelection(state, sessionId),
+ clearSelection: () => EMPTY_SELECTION,
+ // A partial failure keeps only the failures selected, so a retry is one click.
+ bulkActionFinished: (state, { failedIds }) =>
+ failedIds.length ? { ids: failedIds, anchorId: state.anchorId } : EMPTY_SELECTION,
+ locationChanged: () => EMPTY_SELECTION,
+ setView: () => EMPTY_SELECTION,
+ setTypes: () => EMPTY_SELECTION,
+ setFilters: () => EMPTY_SELECTION,
+ clearFilters: () => EMPTY_SELECTION,
+ },
+ ],
+ bulkAction: [
+ null as TodayBulkAction | null,
+ {
+ pinSelected: () => 'pin',
+ fileSelectedTo: () => 'file',
+ archiveSelected: () => 'archive',
+ bulkActionFinished: () => null,
+ },
+ ],
+ bulkArchiveConfirm: [
+ CLOSED_BULK_ARCHIVE_CONFIRM,
+ {
+ openBulkArchiveConfirm: (_, { count, running }) => ({ open: true, count, running }),
+ closeBulkArchiveConfirm: (state) => ({ ...state, open: false }),
+ bulkActionFinished: (state) => ({ ...state, open: false }),
+ },
+ ],
+ }),
+ selectors({
+ feedSessions: [
+ (s) => [s.feedSections],
+ (feedSections: SpaceFeedSection[]): TodayWorkItem[] => spaceFeedSessions(feedSections),
+ ],
+ orderedSessionIds: [
+ (s) => [s.feedSessions],
+ (feedSessions: TodayWorkItem[]): string[] => feedSessions.map((item) => item.id),
+ ],
+ // Sessions that leave the feed, like archived ones, drop out of the selection.
+ selectedSessionIds: [
+ (s) => [s.selection, s.orderedSessionIds],
+ (selection: TodaySessionSelection, orderedSessionIds: string[]): string[] =>
+ pruneToVisible(selection.ids, orderedSessionIds),
+ ],
+ selectedSessions: [
+ (s) => [s.selectedSessionIds, s.feedSessions],
+ (selectedSessionIds: string[], feedSessions: TodayWorkItem[]): TodayWorkItem[] => {
+ const items = new Map(feedSessions.map((item) => [item.id, item]))
+ return selectedSessionIds.flatMap((id) => items.get(id) ?? [])
+ },
+ ],
+ selectAll: [
+ (s) => [s.selectedSessionIds, s.orderedSessionIds],
+ (selectedSessionIds: string[], orderedSessionIds: string[]): SpaceFeedSelectAllState =>
+ selectAllState(selectedSessionIds, orderedSessionIds),
+ ],
+ 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 }) => {
+ const teamId = (): string => String(values.currentTeamId)
+
+ const finish = (failedIds: string[]): void => {
+ actions.bulkActionFinished(failedIds)
+ actions.loadSessions()
+ actions.loadPinnedTasks()
+ actions.loadRecentTasks()
+ }
+
+ return {
+ selectSessionRange: ({ sessionId }) => {
+ actions.setSelection(
+ computeRangeSelection(
+ values.selection.anchorId,
+ sessionId,
+ values.orderedSessionIds,
+ values.selectedSessionIds
+ )
+ )
+ },
+ toggleSelectAll: () => {
+ actions.setSelection(toggleAllSelection(values.selectedSessionIds, values.orderedSessionIds))
+ },
+ pinSelected: async () => {
+ const ids = values.selectedSessionIds
+ const pinned = values.bulkPinDirection === 'pin'
+ const failed = await pinSessions(teamId(), ids, pinned)
+ reportBulkResult(pinned ? 'pin' : 'unpin', ids.length, failed.length)
+ finish(failed)
+ },
+ fileSelectedTo: async ({ spaceId }) => {
+ const ids = values.selectedSessionIds
+ const failed = await fileSessions(teamId(), ids, spaceId)
+ reportBulkResult('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 ids = values.selectedSessions.map((item) => item.id)
+ const failed = await archiveSessions(teamId(), values.selectedSessions)
+ const archivedIds = ids.filter((id) => !failed.includes(id))
+ reportBulkResult('archive', ids.length, failed.length, () => actions.restoreSessions(archivedIds))
+ finish(failed)
+ },
+ restoreSessions: async ({ sessionIds }) => {
+ const failed = await restoreSessions(teamId(), sessionIds)
+ if (failed.length) {
+ reportBulkResult('restore', sessionIds.length, failed.length)
+ }
+ actions.loadSessions()
+ actions.loadPinnedTasks()
+ actions.loadRecentTasks()
+ },
+ }
+ }),
+ afterMount(({ actions, values, cache }) => {
+ cache.disposables.add(() => {
+ const onKeyDown = (event: KeyboardEvent): void => {
+ // 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()
+ }
+ }
+ window.addEventListener('keydown', onKeyDown)
+ return () => window.removeEventListener('keydown', onKeyDown)
+ }, 'clearSelectionOnEscape')
+ }),
+])