: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): show space sessions as cards and add hand off (#109193)
Shy Alter5e38d65f0e9d
diff --git a/frontend/src/layout/today/TodaySessionHandoffDialog.tsx b/frontend/src/layout/today/TodaySessionHandoffDialog.tsxnew file mode 100644index 000000000000..c4a1d80ff114--- /dev/null+++ b/frontend/src/layout/today/TodaySessionHandoffDialog.tsx@@ -0,0 +1,124 @@+import { useActions, useValues } from 'kea'++import {+ Button,+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldLabel,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@posthog/quill'++import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { fullName } from 'lib/utils/strings'+import { membersLogic } from 'scenes/organization/membersLogic'+import { userLogic } from 'scenes/userLogic'++import { todaySessionMenuLogic } from './todaySessionMenuLogic'++interface TodaySessionHandoffDialogProps {+ sessionId: string+}++export function TodaySessionHandoffDialog({ sessionId }: TodaySessionHandoffDialogProps): JSX.Element {+ const { user } = useValues(userLogic)+ const { meFirstMembers } = useValues(membersLogic)+ const { ensureAllMembersLoaded } = useActions(membersLogic)+ const { handoffUser, pendingSessionIds } = useValues(todaySessionMenuLogic)+ const { closeHandoff, setHandoffUser, handOffSession } = useActions(todaySessionMenuLogic)+ const pending = pendingSessionIds.includes(sessionId)++ useOnMountEffect(ensureAllMembersLoaded)++ const candidates = meFirstMembers.filter((member) => member.user.id !== user?.id).map((member) => member.user)+ const names = new Map(candidates.map((candidate) => [candidate.id, fullName(candidate)]))++ return (+ <Dialog+ open+ onOpenChange={(open: boolean) => {+ if (!open && !pending) {+ closeHandoff()+ }+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Hand off this session</DialogTitle>+ <DialogDescription>+ The person you choose takes over this session. They steer it and get its notifications. Only+ they can hand it back.+ </DialogDescription>+ </DialogHeader>+ <DialogBody>+ <Field>+ <FieldLabel htmlFor="today-session-handoff-user">Choose who takes over</FieldLabel>+ <Combobox+ items={candidates.map((candidate) => candidate.id)}+ value={handoffUser?.id ?? null}+ onValueChange={(userId: number | null) =>+ setHandoffUser(candidates.find((candidate) => candidate.id === userId) ?? null)+ }+ itemToStringLabel={(userId: number) => names.get(userId) ?? ''}+ >+ <ComboboxInput+ id="today-session-handoff-user"+ placeholder="Choose a person"+ data-attr="today-session-handoff-user"+ />+ <ComboboxContent>+ <ComboboxEmpty>No one matches that name.</ComboboxEmpty>+ <ComboboxList>+ {(userId: number) => (+ <ComboboxItem key={userId} value={userId}>+ {names.get(userId)}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ </Field>+ </DialogBody>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={closeHandoff}+ disabled={pending}+ data-attr="today-session-handoff-cancel"+ >+ Cancel+ </Button>+ <Tooltip disabled={!!handoffUser}>+ <TooltipTrigger+ render={+ <Button+ variant="primary"+ loading={pending}+ disabled={!handoffUser}+ onClick={() => handoffUser && handOffSession(sessionId, handoffUser)}+ data-attr="today-session-handoff-confirm"+ />+ }+ >+ Hand off+ </TooltipTrigger>+ <TooltipContent>Choose who takes over</TooltipContent>+ </Tooltip>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/layout/today/TodaySessionMenu.tsx b/frontend/src/layout/today/TodaySessionMenu.tsxindex e14b562659e7..27ad3dfbba3e 100644--- a/frontend/src/layout/today/TodaySessionMenu.tsx+++ b/frontend/src/layout/today/TodaySessionMenu.tsx@@ -1,6 +1,16 @@import { useActions, useValues } from 'kea'+import { useId } from 'react'-import { IconArchive, IconEllipsis, IconFolderMove, IconPencil, IconPin, IconPinFilled } from '@posthog/icons'+import {+ IconArchive,+ IconEllipsis,+ IconFolderMove,+ IconPencil,+ IconPin,+ IconPinFilled,+ IconSearch,+ IconSend,+} from '@posthog/icons'import {Button,DropdownMenu,@@ -16,6 +26,10 @@ import {TooltipTrigger,} from '@posthog/quill'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { TodaySessionHandoffDialog } from './TodaySessionHandoffDialog'import { TodaySessionSurface, todaySessionMenuLogic } from './todaySessionMenuLogic'import { spaceLabel, todaySpacesLogic } from './todaySpacesLogic'@@ -24,72 +38,109 @@ interface TodaySessionMenuProps {pinned: booleanspaceId: string | nullsurface: TodaySessionSurface+ canHandOff?: boolean+ analysisRunId?: string | null}-export function TodaySessionMenu({ sessionId, pinned, spaceId, surface }: TodaySessionMenuProps): JSX.Element {+export function TodaySessionMenu({+ sessionId,+ pinned,+ spaceId,+ surface,+ canHandOff = false,+ analysisRunId = null,+}: TodaySessionMenuProps): JSX.Element {+ const menuId = useId()+ const { featureFlags } = useValues(featureFlagLogic)const { sortedSpaces } = useValues(todaySpacesLogic)- const { pendingSessionIds } = useValues(todaySessionMenuLogic)- const { setSessionPinned, startRenaming, archiveSession, moveSession } = useActions(todaySessionMenuLogic)+ const { pendingSessionIds, handoffMenuId } = useValues(todaySessionMenuLogic)+ const { setSessionPinned, startRenaming, archiveSession, moveSession, openHandoff, analyzeSession } =+ useActions(todaySessionMenuLogic)+ const runId = featureFlags[FEATURE_FLAGS.POSTHOG_CODE_TASK_ANALYSIS] ? analysisRunId : nullconst saving = pendingSessionIds.includes(sessionId)const otherSpaces = sortedSpaces.filter((space) => space.id !== spaceId)const label = saving ? 'Saving your last change' : 'More actions'return (- <DropdownMenu>- <Tooltip>- <TooltipTrigger- delay={0}- render={- <DropdownMenuTrigger- render={- <Button- size="icon-xs"- aria-label={label}- loading={saving}- data-attr="today-session-menu"- />- }- />- }- >- <IconEllipsis />- </TooltipTrigger>- <TooltipContent>{label}</TooltipContent>- </Tooltip>- <DropdownMenuContent align="end" className="w-48">- <DropdownMenuItem onClick={() => setSessionPinned(sessionId, !pinned)} data-attr="today-session-pin">- {pinned ? <IconPinFilled /> : <IconPin />}- {pinned ? 'Unpin' : 'Pin'}- </DropdownMenuItem>- <DropdownMenuItem onClick={() => startRenaming(sessionId, surface)} data-attr="today-session-rename">- <IconPencil />- Rename- </DropdownMenuItem>- {otherSpaces.length > 0 && (- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <IconFolderMove />- Move to space- </DropdownMenuSubTrigger>- <DropdownMenuSubContent>- {otherSpaces.map((space) => (- <DropdownMenuItem- key={space.id}- onClick={() => moveSession(sessionId, space.id)}- data-attr="today-session-move"- >- {spaceLabel(space)}- </DropdownMenuItem>- ))}- </DropdownMenuSubContent>- </DropdownMenuSub>- )}- <DropdownMenuSeparator />- <DropdownMenuItem onClick={() => archiveSession(sessionId, true)} data-attr="today-session-archive">- <IconArchive />- Archive- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <>+ <DropdownMenu>+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ <DropdownMenuTrigger+ render={+ <Button+ size="icon-xs"+ aria-label={label}+ loading={saving}+ data-attr="today-session-menu"+ />+ }+ />+ }+ >+ <IconEllipsis />+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuItem+ onClick={() => setSessionPinned(sessionId, !pinned)}+ data-attr="today-session-pin"+ >+ {pinned ? <IconPinFilled /> : <IconPin />}+ {pinned ? 'Unpin' : 'Pin'}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => startRenaming(sessionId, surface)}+ data-attr="today-session-rename"+ >+ <IconPencil />+ Rename+ </DropdownMenuItem>+ {otherSpaces.length > 0 && (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <IconFolderMove />+ Move to space+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ {otherSpaces.map((space) => (+ <DropdownMenuItem+ key={space.id}+ onClick={() => moveSession(sessionId, space.id)}+ data-attr="today-session-move"+ >+ {spaceLabel(space)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )}+ {runId && (+ <DropdownMenuItem+ onClick={() => analyzeSession(sessionId, runId)}+ data-attr="today-session-analyze"+ >+ <IconSearch />+ Run analysis+ </DropdownMenuItem>+ )}+ {canHandOff && (+ <DropdownMenuItem onClick={() => openHandoff(menuId)} data-attr="today-session-handoff">+ <IconSend />+ Hand off…+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => archiveSession(sessionId, true)} data-attr="today-session-archive">+ <IconArchive />+ Archive+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ {canHandOff && handoffMenuId === menuId && <TodaySessionHandoffDialog sessionId={sessionId} />}+ </>)}diff --git a/frontend/src/layout/today/TodaySessionRow.tsx b/frontend/src/layout/today/TodaySessionRow.tsxindex 58ce36ad58a4..957bd31d8f63 100644--- a/frontend/src/layout/today/TodaySessionRow.tsx+++ b/frontend/src/layout/today/TodaySessionRow.tsx@@ -2,13 +2,14 @@ import { useValues } from 'kea'import { router } from 'kea-router'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { TodaySessionMenu } from './TodaySessionMenu'import { TodaySessionSurface, todaySessionMenuLogic } from './todaySessionMenuLogic'import { TodaySessionRenameInput } from './TodaySessionRenameInput'import { TodaySessionStatusIcon } from './TodaySessionStatusIcon'import { TodaySpacesRow } from './TodaySpacesRow'-import { TodayWorkItem } from './todayWorkItems'+import { TodayWorkItem, analysisRunId, canHandOff } from './todayWorkItems'interface TodaySessionRowProps {item: TodayWorkItem@@ -20,6 +21,7 @@ interface TodaySessionRowProps {export function TodaySessionRow({ item, pinned, dataAttr, surface }: TodaySessionRowProps): JSX.Element {const { renaming } = useValues(todaySessionMenuLogic)const { location, searchParams } = useValues(router)+ const { user } = useValues(userLogic)if (renaming?.sessionId === item.id && renaming.surface === surface) {return <TodaySessionRenameInput sessionId={item.id} title={item.title} />@@ -31,7 +33,16 @@ export function TodaySessionRow({ item, pinned, dataAttr, surface }: TodaySessioto={urls.aiTask(item.id)}active={location.pathname.endsWith('/ai') && searchParams.task === item.id}dataAttr={dataAttr}- action={<TodaySessionMenu sessionId={item.id} pinned={pinned} spaceId={item.channel} surface={surface} />}+ action={+ <TodaySessionMenu+ sessionId={item.id}+ pinned={pinned}+ spaceId={item.channel}+ surface={surface}+ canHandOff={canHandOff(item, user?.id)}+ analysisRunId={analysisRunId(item)}+ />+ }/>)}diff --git a/frontend/src/layout/today/todaySessionIcon.test.ts b/frontend/src/layout/today/todaySessionIcon.test.tsindex c3f4e63e2a72..65b14e8cb766 100644--- a/frontend/src/layout/today/todaySessionIcon.test.ts+++ b/frontend/src/layout/today/todaySessionIcon.test.ts@@ -8,6 +8,9 @@ const item = (kind: TodayWorkItem['kind'], status: string | null): TodayWorkItemtimestamp: null,status,channel: null,+ createdById: null,+ latestRunId: null,+ originProduct: null,})describe('todaySessionIcon', () => {diff --git a/frontend/src/layout/today/todaySessionMenuLogic.test.ts b/frontend/src/layout/today/todaySessionMenuLogic.test.tsindex 57984bdcf121..66678c2eccdb 100644--- a/frontend/src/layout/today/todaySessionMenuLogic.test.ts+++ b/frontend/src/layout/today/todaySessionMenuLogic.test.ts@@ -2,10 +2,15 @@ import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { UserBasicType } from '~/types'import { todaySessionMenuLogic } from './todaySessionMenuLogic'+const colleague = { id: 2, uuid: 'user-2', first_name: 'Sam', email: '[email protected]' } as UserBasicType+describe('todaySessionMenuLogic', () => {+ let logic: ReturnType<typeof todaySessionMenuLogic.build>+beforeEach(() => {useMocks({get: {@@ -15,17 +20,34 @@ describe('todaySessionMenuLogic', () => {patch: {'/api/projects/:team_id/tasks/:id/': () => [500, { detail: 'Server error' }],},+ post: {+ '/api/projects/:team_id/tasks/:id/handoff/': () => [400, { detail: 'Finish every run first.' }],+ '/api/projects/:team_id/tasks/:task_id/runs/:id/analyze/': () => [400, { error: 'No log yet.' }],+ },})initKeaTests()- })-- it('clears the pending state when an update fails, so the menu works again', async () => {- const logic = todaySessionMenuLogic()+ logic = todaySessionMenuLogic()logic.mount()+ })- logic.actions.archiveSession('task-1', true)- await expectLogic(logic).toDispatchActions(['archiveSession', 'sessionUpdateFailed'])+ it.each([+ ['archive', () => logic.actions.archiveSession('task-1', true)],+ ['hand-off', () => logic.actions.handOffSession('task-1', colleague)],+ ['analysis', () => logic.actions.analyzeSession('task-1', 'run-1')],+ ])('clears the pending state when the %s request fails, so the menu works again', async (_, run) => {+ run()+ await expectLogic(logic).toDispatchActions(['sessionUpdateFailed'])expect(logic.values.pendingSessionIds).toEqual([])})++ it('keeps the hand-off dialog open with the chosen person when the hand-off fails, so the user can retry', async () => {+ logic.actions.openHandoff('menu-1')+ logic.actions.setHandoffUser(colleague)+ logic.actions.handOffSession('task-1', colleague)+ await expectLogic(logic).toDispatchActions(['sessionUpdateFailed'])++ expect(logic.values.handoffMenuId).toEqual('menu-1')+ expect(logic.values.handoffUser).toEqual(colleague)+ })})diff --git a/frontend/src/layout/today/todaySessionMenuLogic.ts b/frontend/src/layout/today/todaySessionMenuLogic.tsindex f0a932128781..49ca79970dc2 100644--- a/frontend/src/layout/today/todaySessionMenuLogic.ts+++ b/frontend/src/layout/today/todaySessionMenuLogic.ts@@ -1,19 +1,36 @@import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import { router } from 'kea-router'import { toast } from '@posthog/quill'+import { ApiError, readableErrorMessage } from 'lib/api-error'+import { fullName } from 'lib/utils/strings'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'-import { tasksPartialUpdate, tasksPinCreate } from 'products/tasks/frontend/generated/api'+import { UserBasicType } from '~/types'++import {+ tasksHandoffCreate,+ tasksPartialUpdate,+ tasksPinCreate,+ tasksRunsAnalyzeCreate,+} from 'products/tasks/frontend/generated/api'import { PatchedTaskWriteApi } from 'products/tasks/frontend/generated/api.schemas'import { todaySpacesLogic } from './todaySpacesLogic'export type TodaySessionSurface = 'sidebar' | 'feed'+function serverMessage(error: unknown): string | undefined {+ return error instanceof ApiError ? readableErrorMessage(error.data) : undefined+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface todaySessionMenuLogicValues {currentTeamId: number | null // teamLogic+ handoffMenuId: string | null+ handoffUser: UserBasicType | nullpendingSessionIds: string[]renaming: {sessionId: string@@ -25,6 +42,13 @@ export interface todaySessionMenuLogicValues {export interface todaySessionMenuLogicActions {loadPinnedTasks: () => any // todaySpacesLogicloadRecentTasks: () => any // todaySpacesLogic+ analyzeSession: (+ sessionId: string,+ runId: string+ ) => {+ runId: string+ sessionId: string+ }archiveSession: (sessionId: string,archived: boolean@@ -32,6 +56,16 @@ export interface todaySessionMenuLogicActions {archived: booleansessionId: string}+ closeHandoff: () => {+ value: true+ }+ handOffSession: (+ sessionId: string,+ user: UserBasicType+ ) => {+ sessionId: string+ user: UserBasicType+ }moveSession: (sessionId: string,spaceId: string@@ -39,6 +73,9 @@ export interface todaySessionMenuLogicActions {sessionId: stringspaceId: string}+ openHandoff: (menuId: string) => {+ menuId: string+ }renameSession: (sessionId: string,title: string@@ -52,6 +89,9 @@ export interface todaySessionMenuLogicActions {sessionUpdated: (sessionId: string) => {sessionId: string}+ setHandoffUser: (user: UserBasicType | null) => {+ user: UserBasicType | null+ }setSessionPinned: (sessionId: string,pinned: boolean@@ -88,6 +128,11 @@ export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([sessionUpdateFailed: (sessionId: string) => ({ sessionId }),startRenaming: (sessionId: string, surface: TodaySessionSurface) => ({ sessionId, surface }),stopRenaming: true,+ openHandoff: (menuId: string) => ({ menuId }),+ closeHandoff: true,+ setHandoffUser: (user: UserBasicType | null) => ({ user }),+ handOffSession: (sessionId: string, user: UserBasicType) => ({ sessionId, user }),+ analyzeSession: (sessionId: string, runId: string) => ({ sessionId, runId }),}),reducers({renaming: [@@ -98,6 +143,21 @@ export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([renameSession: () => null,},],+ handoffMenuId: [+ null as string | null,+ {+ openHandoff: (_, { menuId }) => menuId,+ closeHandoff: () => null,+ },+ ],+ handoffUser: [+ null as UserBasicType | null,+ {+ openHandoff: () => null,+ closeHandoff: () => null,+ setHandoffUser: (_, { user }) => user,+ },+ ],pendingSessionIds: [[] as string[],{@@ -105,6 +165,8 @@ export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([renameSession: (state, { sessionId }) => [...state, sessionId],archiveSession: (state, { sessionId }) => [...state, sessionId],moveSession: (state, { sessionId }) => [...state, sessionId],+ handOffSession: (state, { sessionId }) => [...state, sessionId],+ analyzeSession: (state, { sessionId }) => [...state, sessionId],sessionUpdated: (state, { sessionId }) => state.filter((id) => id !== sessionId),sessionUpdateFailed: (state, { sessionId }) => state.filter((id) => id !== sessionId),},@@ -152,6 +214,34 @@ export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([moveSession: async ({ sessionId, spaceId }) => {await update(sessionId, { channel: spaceId }, 'Couldn’t move this session. Try again.')},+ handOffSession: async ({ sessionId, user }) => {+ try {+ await tasksHandoffCreate(String(values.currentTeamId), sessionId, { user: user.id })+ toast.success({ title: `Session handed off to ${fullName(user)}` })+ actions.closeHandoff()+ actions.sessionUpdated(sessionId)+ } catch (error) {+ toast.error({ title: serverMessage(error) ?? 'Couldn’t hand off this session. Try again.' })+ actions.sessionUpdateFailed(sessionId)+ }+ },+ analyzeSession: async ({ sessionId, runId }) => {+ try {+ const { analysis_task_id, created } = await tasksRunsAnalyzeCreate(+ String(values.currentTeamId),+ sessionId,+ runId+ )+ actions.sessionUpdated(sessionId)+ toast.success({+ title: created ? 'Analysis started' : 'This run already has an analysis',+ action: { label: 'Open', onClick: () => router.actions.push(urls.aiTask(analysis_task_id)) },+ })+ } catch (error) {+ toast.error({ title: serverMessage(error) ?? 'Couldn’t analyze this run. Try again.' })+ actions.sessionUpdateFailed(sessionId)+ }+ },sessionUpdated: () => {actions.loadPinnedTasks()actions.loadRecentTasks()diff --git a/frontend/src/layout/today/todayWorkItems.test.ts b/frontend/src/layout/today/todayWorkItems.test.tsindex 7b3ca3db569b..2ddae9855471 100644--- a/frontend/src/layout/today/todayWorkItems.test.ts+++ b/frontend/src/layout/today/todayWorkItems.test.ts@@ -4,7 +4,7 @@ import { ConversationDetail } from '~/types'import { TaskListItemApi } from 'products/tasks/frontend/generated/api.schemas'-import { buildRecentItems, groupByDay } from './todayWorkItems'+import { analysisRunId, buildRecentItems, canHandOff, groupByDay, sessionItem, shortTimeAgo } from './todayWorkItems'const session = (id: string, lastActivityAt: string, archived = false): TaskListItemApi =>({ id, title: `Session ${id}`, last_activity_at: lastActivityAt, archived }) as TaskListItemApi@@ -41,4 +41,38 @@ describe('todayWorkItems', () => {expect(groups.map((group) => group.label)).toEqual([label])})++ it.each([+ ['2026-03-10T11:30:00', '30m'],+ ['2026-03-01T12:00:00', '1w'],+ ['2025-12-01T12:00:00', '3mo'],+ ['2024-03-01T12:00:00', '2y'],+ ])('shortens the age of %s to %s', (timestamp, age) => {+ expect(shortTimeAgo(timestamp, dayjs('2026-03-10T12:00:00'))).toEqual(age)+ })++ it.each([+ [7, true],+ [8, false],+ [undefined, false],+ ])('offers hand off to user %s only when they created the session: %s', (userId, expected) => {+ const item = sessionItem({ id: 's', title: 'Session', created_by: { id: 7 } } as TaskListItemApi)++ expect(canHandOff(item, userId)).toBe(expected)+ })++ it.each([+ ['completed', 'task', 'run-1'],+ ['in_progress', 'task', null],+ ['failed', 'task_analysis', null],+ ])('offers analysis for a %s run of a %s session: %s', (status, originProduct, runId) => {+ const item = sessionItem({+ id: 's',+ title: 'Session',+ origin_product: originProduct,+ latest_run: { id: 'run-1', status },+ } as TaskListItemApi)++ expect(analysisRunId(item)).toBe(runId)+ })})diff --git a/frontend/src/layout/today/todayWorkItems.ts b/frontend/src/layout/today/todayWorkItems.tsindex 09f0fb2b8225..01c9b0215da5 100644--- a/frontend/src/layout/today/todayWorkItems.ts+++ b/frontend/src/layout/today/todayWorkItems.ts@@ -13,6 +13,9 @@ export interface TodayWorkItem {timestamp: string | nullstatus: string | nullchannel: string | null+ createdById: number | null+ latestRunId: string | null+ originProduct: string | null}export interface TodayWorkGroup {@@ -21,6 +24,18 @@ export interface TodayWorkGroup {items: TodayWorkItem[]}+const FINISHED_RUN_STATUSES = new Set(['completed', 'failed', 'cancelled'])++export function canHandOff(item: TodayWorkItem, userId: number | null | undefined): boolean {+ return item.kind === 'session' && item.createdById !== null && item.createdById === userId+}++export function analysisRunId(item: TodayWorkItem): string | null {+ return item.originProduct !== 'task_analysis' && item.status !== null && FINISHED_RUN_STATUSES.has(item.status)+ ? item.latestRunId+ : null+}+export function sessionItem(task: TaskListItemApi): TodayWorkItem {return {kind: 'session',@@ -29,6 +44,9 @@ export function sessionItem(task: TaskListItemApi): TodayWorkItem {timestamp: task.last_activity_at ?? task.updated_at ?? task.created_at ?? null,status: task.latest_run?.status ?? null,channel: task.channel ?? null,+ createdById: task.created_by?.id ?? null,+ latestRunId: task.latest_run?.id ?? null,+ originProduct: task.origin_product ?? null,}}@@ -40,6 +58,9 @@ export function chatItem(conversation: ConversationDetail): TodayWorkItem {timestamp: conversation.updated_at ?? conversation.created_at,status: null,channel: null,+ createdById: null,+ latestRunId: null,+ originProduct: null,}}@@ -101,10 +122,17 @@ export function shortTimeAgo(timestamp: string | null, now: Dayjs = dayjs()): stif (minutes < 60 * 24) {return `${Math.floor(minutes / 60)}h`}- if (minutes < 60 * 24 * 7) {- return `${Math.floor(minutes / (60 * 24))}d`+ const days = Math.floor(minutes / (60 * 24))+ if (days < 7) {+ return `${days}d`+ }+ if (days < 30) {+ return `${Math.floor(days / 7)}w`+ }+ if (days < 365) {+ return `${Math.floor(days / 30)}mo`}- return `${Math.floor(minutes / (60 * 24 * 7))}w`+ return `${Math.floor(days / 365)}y`}function earlierOf(first: Dayjs, second: Dayjs): Dayjs {diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex e6a9b90d3c4c..40bbe78f2143 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -454,6 +454,7 @@ export const FEATURE_FLAGS = {POSTHOG_AI_CONVERSATION_FEEDBACK_LLMA_SESSIONS: 'posthog-ai-conversation-feedback-llma-sessions', // owner: #team-posthog-aiPOSTHOG_AI_QUEUE_MESSAGES_SYSTEM: 'posthog-ai-queue-messages-system', // owner: #team-posthog-aiPOSTHOG_CODE_BILLING: 'posthog-code-billing', // owner: #team-desktop+ POSTHOG_CODE_TASK_ANALYSIS: 'posthog-code-task-analysis', // owner: #team-desktopPOSTHOG_CONNECT: 'posthog-connect', // owner: @Gilbert09, gates the "connect another PostHog project" personal integrationPOSTHOG_DESKTOP_CLOUD_COMPUTE_BILLING: 'posthog-desktop-cloud-compute-billing', // owner: #team-desktopPRODUCT_ANALYTICS_CHART_ALTERNATIVES: 'product-analytics-chart-gallery', // owner: #team-product-analyticsdiff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsxindex 9d41d63a9441..1160bec6e255 100644--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx@@ -71,7 +71,10 @@ const PINNED_SESSIONS = [title: 'Fix the flaky checkout test',archived: false,last_activity_at: '2026-09-28T17:40:00Z',- latest_run: { status: 'in_progress' },+ latest_run: { status: 'in_progress', environment: 'cloud', output: null },+ description_preview: 'The checkout test fails about once in ten runs. Find the race and make the test stable.',+ repository: 'example-org/webapp',+ created_by: { id: 1, first_name: 'Ada', last_name: 'Lovelace', email: '[email protected]' },},]@@ -82,14 +85,25 @@ const RECENT_SESSIONS = [title: 'Add a retry to the billing webhook',archived: false,last_activity_at: '2026-09-28T18:05:00Z',- latest_run: { status: 'completed' },+ latest_run: {+ id: 'run-1',+ status: 'completed',+ environment: 'cloud',+ output: { pr_url: 'https://github.com/example-org/webapp/pull/421' },+ },+ description_preview: 'Retry the billing webhook three times with a backoff before it reports a failure.',+ repository: 'example-org/webapp',+ created_by: { id: 179, first_name: 'John', last_name: 'Baker', email: '[email protected]' },},{id: 'task-2',title: 'Investigate the drop in trial starts',archived: false,last_activity_at: '2026-09-27T11:20:00Z',- latest_run: { status: 'failed' },+ latest_run: { status: 'failed', environment: 'cloud', output: null },+ description_preview: 'Trial starts dropped last week. Find the step where people leave.',+ repository: null,+ created_by: { id: 1, first_name: 'Ada', last_name: 'Lovelace', email: '[email protected]' },},]@@ -204,7 +218,7 @@ const meta: Meta = {viewMode: 'story',mockDate: '2026-09-28 18:30:00',pageUrl: urls.projectHomepage(),- featureFlags: [FEATURE_FLAGS.TODAY_RAIL_NAV],+ featureFlags: [FEATURE_FLAGS.TODAY_RAIL_NAV, FEATURE_FLAGS.POSTHOG_CODE_TASK_ANALYSIS],testOptions: { waitForLoadersToDisappear: true },},}diff --git a/products/tasks/frontend/spaces/SpaceFeed.tsx b/products/tasks/frontend/spaces/SpaceFeed.tsxindex 222a29aecf96..9ea85dad4568 100644--- a/products/tasks/frontend/spaces/SpaceFeed.tsx+++ b/products/tasks/frontend/spaces/SpaceFeed.tsx@@ -14,13 +14,13 @@ import {cn,} from '@posthog/quill'-import { TodaySessionRow } from '~/layout/today/TodaySessionRow'import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'+import { SpaceFeedCard } from './SpaceFeedCard'import { spaceSceneLogic } from './spaceSceneLogic'export function SpaceFeed({ id }: { id: string }): JSX.Element {- const { feedGroups, sessionsLoading, sessionsUnavailable } = useValues(spaceSceneLogic({ id }))+ const { feedGroups, sessionsById, sessionsLoading, sessionsUnavailable } = useValues(spaceSceneLogic({ id }))const { loadSessions } = useActions(spaceSceneLogic({ id }))const { pinnedItems } = useValues(todaySpacesLogic)const pinnedIds = new Set(pinnedItems.map((item) => item.id))@@ -69,21 +69,17 @@ export function SpaceFeed({ id }: { id: string }): JSX.Element {)}return (- <div className="flex max-w-3xl flex-col gap-px">+ <div className="flex max-w-3xl flex-col gap-2">{feedGroups.map((group, index) => (<Fragment key={group.key}>- <Text size="xs" variant="muted" className={cn('block px-2 pb-1', index === 0 ? 'pt-1' : 'pt-3')}>+ <Text size="xs" variant="muted" className={cn('block px-1', index === 0 ? 'pt-1' : 'pt-4')}>{group.label}</Text>- {group.items.map((item) => (- <TodaySessionRow- key={item.id}- item={item}- pinned={pinnedIds.has(item.id)}- dataAttr="today-space-feed-session"- surface="feed"- />- ))}+ {group.items.map((item) =>+ sessionsById[item.id] ? (+ <SpaceFeedCard key={item.id} task={sessionsById[item.id]} pinned={pinnedIds.has(item.id)} />+ ) : null+ )}</Fragment>))}</div>diff --git a/products/tasks/frontend/spaces/SpaceFeedCard.tsx b/products/tasks/frontend/spaces/SpaceFeedCard.tsxnew file mode 100644index 000000000000..2811db9c32e5--- /dev/null+++ b/products/tasks/frontend/spaces/SpaceFeedCard.tsx@@ -0,0 +1,111 @@+import { useValues } from 'kea'++import { IconGitBranch } from '@posthog/icons'+import { Avatar, AvatarFallback, Badge, Card, Text, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'++import { LinkPrimitive } from 'lib/lemon-ui/Link'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import { TodaySessionMenu } from '~/layout/today/TodaySessionMenu'+import { todaySessionMenuLogic } from '~/layout/today/todaySessionMenuLogic'+import { TodaySessionRenameInput } from '~/layout/today/TodaySessionRenameInput'+import { TodaySessionStatusIcon } from '~/layout/today/TodaySessionStatusIcon'+import { analysisRunId, canHandOff, sessionItem, shortTimeAgo } from '~/layout/today/todayWorkItems'++import { TaskListItemApi } from '../generated/api.schemas'+import { spaceFeedPreview } from './spaceFeedPreview'+import { spaceFeedStatus } from './spaceFeedStatus'++interface SpaceFeedCardProps {+ task: TaskListItemApi+ pinned: boolean+}++export function SpaceFeedCard({ task, pinned }: SpaceFeedCardProps): JSX.Element {+ const { renaming } = useValues(todaySessionMenuLogic)+ const { user } = useValues(userLogic)+ const item = sessionItem(task)+ const status = spaceFeedStatus(task.latest_run)+ const preview = spaceFeedPreview('description_preview' in task ? task.description_preview : task.description)+ const author = task.created_by+ const authorName = author ? [author.first_name, author.last_name].filter(Boolean).join(' ') || author.email : null+ const initials = authorName+ ? authorName+ .split(/\s+/)+ .slice(0, 2)+ .map((part) => part[0]?.toUpperCase())+ .join('')+ : ''++ return (+ <Card size="sm" className="group/card relative gap-2 px-3 py-3">+ <div className="flex min-w-0 items-center gap-2">+ <TodaySessionStatusIcon item={item} pinned={false} />+ {renaming?.sessionId === task.id && renaming.surface === 'feed' ? (+ <div className="min-w-0 flex-1">+ <TodaySessionRenameInput sessionId={task.id} title={task.title} />+ </div>+ ) : (+ <div className="flex min-w-0 flex-1 items-baseline gap-1.5">+ <LinkPrimitive+ to={urls.aiTask(task.id)}+ className="min-w-0 truncate font-medium text-foreground after:absolute after:inset-0 hover:underline"+ data-attr="today-space-feed-card"+ >+ {item.title || 'Untitled session'}+ </LinkPrimitive>+ {item.timestamp && (+ <Text render={<span />} size="xs" variant="muted" className="shrink-0" translate="no">+ {`· ${shortTimeAgo(item.timestamp)}`}+ </Text>+ )}+ </div>+ )}+ <div className="relative flex shrink-0 items-center gap-1">+ {status && <Badge variant={status.variant}>{status.label}</Badge>}+ <TodaySessionMenu+ sessionId={task.id}+ pinned={pinned}+ spaceId={item.channel}+ surface="feed"+ canHandOff={canHandOff(item, user?.id)}+ analysisRunId={analysisRunId(item)}+ />+ </div>+ </div>+ {preview && (+ <Text size="sm" variant="muted" className="line-clamp-2 break-words">+ {preview}+ </Text>+ )}+ {(task.repository || author) && (+ <div className="flex min-w-0 items-center gap-2 pt-1">+ {task.repository && (+ <Text+ render={<span />}+ size="xs"+ variant="muted"+ className="inline-flex min-w-0 items-center gap-1"+ >+ <IconGitBranch className="shrink-0" />+ <span className="truncate">{task.repository}</span>+ </Text>+ )}+ {authorName && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Avatar size="xs" className="relative ml-auto shrink-0" aria-label={authorName} />+ }+ >+ <AvatarFallback>{initials}</AvatarFallback>+ </TooltipTrigger>+ <TooltipContent>{authorName}</TooltipContent>+ </Tooltip>+ )}+ </div>+ )}+ </Card>+ )+}diff --git a/products/tasks/frontend/spaces/spaceFeedPreview.test.ts b/products/tasks/frontend/spaces/spaceFeedPreview.test.tsnew file mode 100644index 000000000000..5e5d65477fa3--- /dev/null+++ b/products/tasks/frontend/spaces/spaceFeedPreview.test.ts@@ -0,0 +1,35 @@+import { spaceFeedPreview } from './spaceFeedPreview'++describe('spaceFeedPreview', () => {+ it.each([+ ['an empty preview', null, ''],+ ['plain text', 'Fix the flaky test', 'Fix the flaky test'],+ [+ 'a leading space context block',+ '<channel_context name="checkout">Repo notes</channel_context>\nFix the flaky test',+ 'Fix the flaky test',+ ],+ [+ 'PostHog context blocks around the prompt',+ '<posthog_trusted_context>Rules</posthog_trusted_context>Why did signups drop?<posthog_untrusted_context>{}</posthog_untrusted_context>',+ 'Why did signups drop?',+ ],+ [+ 'a block the preview cut before its closing tag',+ 'Retry the webhook\n\n<slack_thread_context>Earlier messages',+ 'Retry the webhook',+ ],+ [+ 'saved custom instructions',+ '<user_custom_instructions>The user has saved custom instructions that apply to all of their tasks. Follow them.\nUse pnpm</user_custom_instructions>Ship it',+ 'Ship it',+ ],+ [+ 'a custom-instructions tag the person typed',+ 'Explain <user_custom_instructions>how it works</user_custom_instructions>',+ 'Explain <user_custom_instructions>how it works</user_custom_instructions>',+ ],+ ])('cleans %s', (_, text, expected) => {+ expect(spaceFeedPreview(text)).toEqual(expected)+ })+})diff --git a/products/tasks/frontend/spaces/spaceFeedPreview.ts b/products/tasks/frontend/spaces/spaceFeedPreview.tsnew file mode 100644index 000000000000..50f3693b6177--- /dev/null+++ b/products/tasks/frontend/spaces/spaceFeedPreview.ts@@ -0,0 +1,37 @@+// Blocks the agent tooling injects into a session prompt. They are instructions for the agent, not text the+// person wrote, so a feed card must not show them. Mirrors the tag list PostHog Desktop strips.+const INJECTED_TAGS = [+ 'channel_context',+ 'canvas_generation_instructions',+ 'posthog_trusted_context',+ 'posthog_untrusted_context',+ 'posthog_context',+ 'onboarding_brief',+ 'slack_thread_context',+]+const CUSTOM_INSTRUCTIONS_TAG = 'user_custom_instructions'+const CUSTOM_INSTRUCTIONS_PREAMBLE = 'The user has saved custom instructions that apply to all of their tasks.'++const COMPLETE_BLOCK = new RegExp(`<(${INJECTED_TAGS.join('|')})\\b[^>]*>[\\s\\S]*?</\\1>`, 'g')+const CUSTOM_INSTRUCTIONS_BLOCK = new RegExp(+ `<${CUSTOM_INSTRUCTIONS_TAG}\\b[^>]*>([\\s\\S]*?)</${CUSTOM_INSTRUCTIONS_TAG}>`,+ 'g'+)+// The API truncates previews, which can cut a block before its closing tag.+const TRUNCATED_BLOCK = new RegExp(+ `<(${[...INJECTED_TAGS, CUSTOM_INSTRUCTIONS_TAG].join('|')})\\b(?![\\s\\S]*</\\1>)[\\s\\S]*$`+)++export function spaceFeedPreview(text: string | null | undefined): string {+ if (!text) {+ return ''+ }+ return text+ .replace(COMPLETE_BLOCK, '')+ .replace(CUSTOM_INSTRUCTIONS_BLOCK, (block: string, inner: string) =>+ inner.trimStart().startsWith(CUSTOM_INSTRUCTIONS_PREAMBLE) ? '' : block+ )+ .replace(TRUNCATED_BLOCK, '')+ .replace(/\n{3,}/g, '\n\n')+ .trim()+}diff --git a/products/tasks/frontend/spaces/spaceFeedStatus.test.ts b/products/tasks/frontend/spaces/spaceFeedStatus.test.tsnew file mode 100644index 000000000000..7bd28db7fa81--- /dev/null+++ b/products/tasks/frontend/spaces/spaceFeedStatus.test.ts@@ -0,0 +1,31 @@+import { TaskRunDetailDTOApi } from '../generated/api.schemas'+import { spaceFeedStatus } from './spaceFeedStatus'++const run = (status: string, environment: string, output: TaskRunDetailDTOApi['output'] = null): TaskRunDetailDTOApi =>+ ({ status, environment, output }) as TaskRunDetailDTOApi++describe('spaceFeedStatus', () => {+ it.each([+ ['no run', null, 'Draft'],+ ['a cloud run in progress', run('in_progress', 'cloud'), 'In progress'],+ ['a local run in progress', run('in_progress', 'local'), null],+ ['a local run that completed', run('completed', 'local'), 'Ready'],+ [+ 'a run with a pull request',+ run('in_progress', 'local', { pr_url: 'https://example.com/pull/1' }),+ 'PR ready',+ ],+ [+ 'a run with a listed pull request',+ run('completed', 'cloud', { pr_urls: ['https://example.com/pull/2'] }),+ 'PR ready',+ ],+ [+ 'a failed run with a pull request',+ run('failed', 'cloud', { pr_url: 'https://example.com/pull/3' }),+ 'Failed',+ ],+ ])('labels %s', (_, latestRun, label) => {+ expect(spaceFeedStatus(latestRun)?.label ?? null).toEqual(label)+ })+})diff --git a/products/tasks/frontend/spaces/spaceFeedStatus.ts b/products/tasks/frontend/spaces/spaceFeedStatus.tsnew file mode 100644index 000000000000..0794f329dfe9--- /dev/null+++ b/products/tasks/frontend/spaces/spaceFeedStatus.ts@@ -0,0 +1,41 @@+import { TaskRunDetailDTOApi } from '../generated/api.schemas'++export type SpaceFeedStatusVariant = 'default' | 'info' | 'destructive' | 'success' | 'completed'++export interface SpaceFeedStatus {+ label: string+ variant: SpaceFeedStatusVariant+}++const RUN_STATUSES: Record<string, SpaceFeedStatus> = {+ not_started: { label: 'Not started', variant: 'default' },+ queued: { label: 'Queued', variant: 'default' },+ in_progress: { label: 'In progress', variant: 'info' },+ completed: { label: 'Ready', variant: 'success' },+ failed: { label: 'Failed', variant: 'destructive' },+ cancelled: { label: 'Cancelled', variant: 'default' },+}++const TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled'])++function hasPullRequest(output: TaskRunDetailDTOApi['output']): boolean {+ if (!output) {+ return false+ }+ const urls = Array.isArray(output.pr_urls) ? output.pr_urls : []+ return typeof output.pr_url === 'string' || urls.some((url) => typeof url === 'string')+}++export function spaceFeedStatus(run: TaskRunDetailDTOApi | null | undefined): SpaceFeedStatus | null {+ if (!run) {+ return { label: 'Draft', variant: 'default' }+ }+ const stopped = run.status === 'failed' || run.status === 'cancelled'+ if (!stopped && hasPullRequest(run.output)) {+ return { label: 'PR ready', variant: 'completed' }+ }+ if (run.environment !== 'cloud' && !TERMINAL_STATUSES.has(run.status)) {+ return null+ }+ return RUN_STATUSES[run.status] ?? null+}diff --git a/products/tasks/frontend/spaces/spaceSceneLogic.ts b/products/tasks/frontend/spaces/spaceSceneLogic.tsindex e317c79136b2..3745de96b981 100644--- a/products/tasks/frontend/spaces/spaceSceneLogic.ts+++ b/products/tasks/frontend/spaces/spaceSceneLogic.ts@@ -42,6 +42,7 @@ export interface spaceSceneLogicValues {membersLoading: booleansavingSpace: booleansessions: TaskListItemApi[]+ sessionsById: Record<string, TaskListItemApi>sessionsLoading: booleansessionsUnavailable: booleanspace: ChannelDTOApi | null@@ -139,6 +140,7 @@ export interface spaceSceneLogicMeta {__keaTypeGenInternalSelectorTypes: {activeTab: (location: { hash: string; pathname: string; search: string }) => SpaceTabfeedGroups: (sessions: TaskListItemApi[]) => TodayWorkGroup[]+ sessionsById: (sessions: TaskListItemApi[]) => Record<string, TaskListItemApi>breadcrumbs: (space: ChannelDTOApi | null, arg: any) => Breadcrumb[]}}@@ -235,6 +237,11 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([(sessions: TaskListItemApi[]): TodayWorkGroup[] =>groupByDay(sessions.filter((task) => !task.archived).map(sessionItem)),],+ sessionsById: [+ (s) => [s.sessions],+ (sessions: TaskListItemApi[]): Record<string, TaskListItemApi> =>+ Object.fromEntries(sessions.map((task) => [task.id, task])),+ ],breadcrumbs: [(s) => [s.space, (_, props) => props],(space: ChannelDTOApi | null, props: SpaceSceneLogicProps): Breadcrumb[] => [