: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): bring the session menu to parity and show pr chips (#109248)
Shy Alterffc897ac87c7
diff --git a/frontend/src/layout/today/TodaySessionArchiveDialog.tsx b/frontend/src/layout/today/TodaySessionArchiveDialog.tsxnew file mode 100644index 000000000000..2645b7fbf1c7--- /dev/null+++ b/frontend/src/layout/today/TodaySessionArchiveDialog.tsx@@ -0,0 +1,63 @@+import { useActions, useValues } from 'kea'++import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Button,+} from '@posthog/quill'++import { todaySessionMenuLogic } from './todaySessionMenuLogic'++interface TodaySessionArchiveDialogProps {+ sessionId: string+ title: string+ runId: string+}++export function TodaySessionArchiveDialog({ sessionId, title, runId }: TodaySessionArchiveDialogProps): JSX.Element {+ const { pendingSessionIds } = useValues(todaySessionMenuLogic)+ const { closeArchiveConfirm, confirmArchive } = useActions(todaySessionMenuLogic)+ const pending = pendingSessionIds.includes(sessionId)++ return (+ <AlertDialog+ open+ onOpenChange={(open: boolean) => {+ if (!open && !pending) {+ closeArchiveConfirm()+ }+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Archive running session?</AlertDialogTitle>+ <AlertDialogDescription>+ {`${title ? `“${title}”` : 'This session'} is still running. Archiving it will stop its cloud run and shut down the sandbox. You can unarchive it later.`}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <Button+ variant="outline"+ onClick={closeArchiveConfirm}+ disabled={pending}+ data-attr="today-session-archive-cancel"+ >+ Cancel+ </Button>+ <Button+ variant="destructive-outline"+ loading={pending}+ onClick={() => confirmArchive(sessionId, runId)}+ data-attr="today-session-archive-confirm"+ >+ Archive+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )+}diff --git a/frontend/src/layout/today/TodaySessionMenu.tsx b/frontend/src/layout/today/TodaySessionMenu.tsxindex 27ad3dfbba3e..5f2723c0a093 100644--- a/frontend/src/layout/today/TodaySessionMenu.tsx+++ b/frontend/src/layout/today/TodaySessionMenu.tsx@@ -1,26 +1,34 @@import { useActions, useValues } from 'kea'-import { useId } from 'react'+import { ChangeEvent, useId, useState } from 'react'import {IconArchive,+ IconCopy,IconEllipsis,- IconFolderMove,+ IconExternal,+ IconFolder,IconPencil,IconPin,IconPinFilled,IconSearch,IconSend,+ IconStar,+ IconStopFilled,} from '@posthog/icons'import {Button,DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,DropdownMenuSeparator,DropdownMenuSub,DropdownMenuSubContent,DropdownMenuSubTrigger,DropdownMenuTrigger,+ Input,+ Text,Tooltip,TooltipContent,TooltipTrigger,@@ -29,36 +37,55 @@ import {import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { TodaySessionArchiveDialog } from './TodaySessionArchiveDialog'import { TodaySessionHandoffDialog } from './TodaySessionHandoffDialog'import { TodaySessionSurface, todaySessionMenuLogic } from './todaySessionMenuLogic'-import { spaceLabel, todaySpacesLogic } from './todaySpacesLogic'+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 = 5interface TodaySessionMenuProps {sessionId: string+ title: stringpinned: booleanspaceId: string | nullsurface: TodaySessionSurfacecanHandOff?: booleananalysisRunId?: string | null+ /** The latest run while it is an active cloud run: it can be stopped, and archiving asks first. */+ activeRunId?: string | null}export function TodaySessionMenu({sessionId,+ title,pinned,spaceId,surface,canHandOff = false,analysisRunId = null,+ activeRunId = null,}: TodaySessionMenuProps): JSX.Element {const menuId = useId()const { featureFlags } = useValues(featureFlagLogic)- const { sortedSpaces } = useValues(todaySpacesLogic)- const { pendingSessionIds, handoffMenuId } = useValues(todaySessionMenuLogic)- const { setSessionPinned, startRenaming, archiveSession, moveSession, openHandoff, analyzeSession } =- useActions(todaySessionMenuLogic)+ const { spaces } = useValues(todaySpacesLogic)+ const { pendingSessionIds, handoffMenuId, archiveConfirmMenuId } = useValues(todaySessionMenuLogic)+ const {+ setSessionPinned,+ startRenaming,+ requestArchive,+ moveSession,+ openHandoff,+ analyzeSession,+ openSessionInNewTab,+ copySessionLink,+ stopSession,+ } = useActions(todaySessionMenuLogic)+ const [spaceSearch, setSpaceSearch] = useState('')const runId = featureFlags[FEATURE_FLAGS.POSTHOG_CODE_TASK_ANALYSIS] ? analysisRunId : nullconst saving = pendingSessionIds.includes(sessionId)- const otherSpaces = sortedSpaces.filter((space) => space.id !== spaceId)+ const fileTargets = fileToSpaces(spaces, spaceId, spaceSearch)const label = saving ? 'Saving your last change' : 'More actions'return (@@ -84,7 +111,18 @@ export function TodaySessionMenu({</TooltipTrigger><TooltipContent>{label}</TooltipContent></Tooltip>- <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuContent align="end" className="w-56">+ <DropdownMenuItem+ onClick={() => openSessionInNewTab(sessionId)}+ data-attr="today-session-open-new-tab"+ >+ <IconExternal />+ Open in new tab+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => copySessionLink(sessionId)} data-attr="today-session-copy-link">+ <IconCopy />+ Copy link+ </DropdownMenuItem><DropdownMenuItemonClick={() => setSessionPinned(sessionId, !pinned)}data-attr="today-session-pin"@@ -99,25 +137,6 @@ export function TodaySessionMenu({<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 && (<DropdownMenuItemonClick={() => analyzeSession(sessionId, runId)}@@ -127,6 +146,66 @@ export function TodaySessionMenu({Run analysis</DropdownMenuItem>)}+ {activeRunId && (+ <DropdownMenuItem+ onClick={() => stopSession(sessionId, activeRunId)}+ data-attr="today-session-stop"+ >+ <IconStopFilled />+ Stop session+ </DropdownMenuItem>+ )}+ {spaces.length > 0 && (+ <DropdownMenuSub onOpenChange={(open: boolean) => !open && setSpaceSearch('')}>+ <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>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )}{canHandOff && (<DropdownMenuItem onClick={() => openHandoff(menuId)} data-attr="today-session-handoff"><IconSend />@@ -134,13 +213,19 @@ export function TodaySessionMenu({</DropdownMenuItem>)}<DropdownMenuSeparator />- <DropdownMenuItem onClick={() => archiveSession(sessionId, true)} data-attr="today-session-archive">+ <DropdownMenuItem+ onClick={() => requestArchive(sessionId, menuId, activeRunId)}+ data-attr="today-session-archive"+ ><IconArchive />Archive</DropdownMenuItem></DropdownMenuContent></DropdownMenu>{canHandOff && handoffMenuId === menuId && <TodaySessionHandoffDialog sessionId={sessionId} />}+ {activeRunId && archiveConfirmMenuId === menuId && (+ <TodaySessionArchiveDialog sessionId={sessionId} title={title} runId={activeRunId} />+ )}</>)}diff --git a/frontend/src/layout/today/TodaySessionRow.tsx b/frontend/src/layout/today/TodaySessionRow.tsxindex 957bd31d8f63..ee6a852c5476 100644--- a/frontend/src/layout/today/TodaySessionRow.tsx+++ b/frontend/src/layout/today/TodaySessionRow.tsx@@ -4,12 +4,14 @@ import { router } from 'kea-router'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'+import { TaskPullRequestChip } from 'products/tasks/frontend/spaces/TaskPullRequestChip'+import { TodaySessionMenu } from './TodaySessionMenu'import { TodaySessionSurface, todaySessionMenuLogic } from './todaySessionMenuLogic'import { TodaySessionRenameInput } from './TodaySessionRenameInput'import { TodaySessionStatusIcon } from './TodaySessionStatusIcon'import { TodaySpacesRow } from './TodaySpacesRow'-import { TodayWorkItem, analysisRunId, canHandOff } from './todayWorkItems'+import { TodayWorkItem, activeCloudRunId, analysisRunId, canHandOff } from './todayWorkItems'interface TodaySessionRowProps {item: TodayWorkItem@@ -23,6 +25,8 @@ export function TodaySessionRow({ item, pinned, dataAttr, surface }: TodaySessioconst { location, searchParams } = useValues(router)const { user } = useValues(userLogic)+ const [pullRequest] = item.pullRequests+if (renaming?.sessionId === item.id && renaming.surface === surface) {return <TodaySessionRenameInput sessionId={item.id} title={item.title} />}@@ -33,14 +37,25 @@ export function TodaySessionRow({ item, pinned, dataAttr, surface }: TodaySessioto={urls.aiTask(item.id)}active={location.pathname.endsWith('/ai') && searchParams.task === item.id}dataAttr={dataAttr}+ badge={+ pullRequest ? (+ <TaskPullRequestChip+ pullRequest={pullRequest}+ label={`#${pullRequest.number}`}+ dataAttr="today-pr-chip-sidebar"+ />+ ) : null+ }action={<TodaySessionMenusessionId={item.id}+ title={item.title}pinned={pinned}spaceId={item.channel}surface={surface}canHandOff={canHandOff(item, user?.id)}analysisRunId={analysisRunId(item)}+ activeRunId={activeCloudRunId(item)}/>}/>diff --git a/frontend/src/layout/today/TodaySpacesRow.tsx b/frontend/src/layout/today/TodaySpacesRow.tsxindex 4b4da315dbab..07e84d48dc6c 100644--- a/frontend/src/layout/today/TodaySpacesRow.tsx+++ b/frontend/src/layout/today/TodaySpacesRow.tsx@@ -9,9 +9,11 @@ interface TodaySpacesRowProps {active: booleandataAttr: stringaction?: JSX.Element | null+ /** Stays visible at the end of the row, after the hover action. */+ badge?: JSX.Element | null}-export function TodaySpacesRow({ label, icon, to, active, dataAttr, action }: TodaySpacesRowProps): JSX.Element {+export function TodaySpacesRow({ label, icon, to, active, dataAttr, action, badge }: TodaySpacesRowProps): JSX.Element {return (<div className="group/row relative flex min-w-0 items-center"><Button@@ -23,15 +25,21 @@ export function TodaySpacesRow({ label, icon, to, active, dataAttr, action }: ToclassName={cn('min-w-0 text-muted-foreground',active && 'bg-fill-selected text-foreground',- action && 'pr-8'+ action && !badge && 'pr-8',+ badge && 'pr-24')}><span className="flex size-4 shrink-0 items-center justify-center">{icon}</span><span className="min-w-0 flex-1 truncate">{label}</span></Button>- {action && (- <div className="absolute right-1 flex opacity-0 transition-opacity group-focus-within/row:opacity-100 group-hover/row:opacity-100">- {action}+ {(action || badge) && (+ <div className="absolute right-1 flex min-w-0 items-center gap-0.5">+ {action && (+ <div className="flex opacity-0 transition-opacity group-focus-within/row:opacity-100 group-hover/row:opacity-100">+ {action}+ </div>+ )}+ {badge}</div>)}</div>diff --git a/frontend/src/layout/today/todaySessionIcon.test.ts b/frontend/src/layout/today/todaySessionIcon.test.tsindex 1b0980ff5084..d26572620a95 100644--- a/frontend/src/layout/today/todaySessionIcon.test.ts+++ b/frontend/src/layout/today/todaySessionIcon.test.ts@@ -11,9 +11,11 @@ const item = (kind: TodayWorkItem['kind'], status: string | null): TodayWorkItemchannel: null,createdById: null,latestRunId: null,+ runEnvironment: null,originProduct: null,source: null,repository: null,+ pullRequests: [],})describe('todaySessionIcon', () => {diff --git a/frontend/src/layout/today/todaySessionMenuLogic.test.ts b/frontend/src/layout/today/todaySessionMenuLogic.test.tsindex 66678c2eccdb..8cb88601881c 100644--- a/frontend/src/layout/today/todaySessionMenuLogic.test.ts+++ b/frontend/src/layout/today/todaySessionMenuLogic.test.ts@@ -1,28 +1,45 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'+import { expectLogic } from 'kea-test-utils'+import { writeToClipboard } from 'lib/utils/writeToClipboard'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { UserBasicType } from '~/types'import { todaySessionMenuLogic } from './todaySessionMenuLogic'+jest.mock('lib/utils/writeToClipboard')+const colleague = { id: 2, uuid: 'user-2', first_name: 'Sam', email: '[email protected]' } as UserBasicTypedescribe('todaySessionMenuLogic', () => {let logic: ReturnType<typeof todaySessionMenuLogic.build>+ let requests: string[]+ let writesSucceed: booleanbeforeEach(() => {+ requests = []+ writesSucceed = falseuseMocks({get: {'/api/projects/:team_id/task_channels/': [],'/api/projects/:team_id/tasks/': { results: [], count: 0 },},patch: {- '/api/projects/:team_id/tasks/:id/': () => [500, { detail: 'Server error' }],+ '/api/projects/:team_id/tasks/:id/': async ({ params, request }) => {+ requests.push(`patch ${params.id} ${JSON.stringify(await request.json())}`)+ return writesSucceed ? [200, {}] : [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.' }],+ '/api/projects/:team_id/tasks/:task_id/runs/:id/cancel/': ({ params }) => {+ requests.push(`cancel ${params.task_id} ${params.id}`)+ return writesSucceed ? [200, {}] : [409, { detail: 'Try later.' }]+ },},})initKeaTests()@@ -34,6 +51,8 @@ describe('todaySessionMenuLogic', () => {['archive', () => logic.actions.archiveSession('task-1', true)],['hand-off', () => logic.actions.handOffSession('task-1', colleague)],['analysis', () => logic.actions.analyzeSession('task-1', 'run-1')],+ ['stop', () => logic.actions.stopSession('task-1', 'run-1')],+ ['archive confirm', () => logic.actions.confirmArchive('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'])@@ -50,4 +69,50 @@ describe('todaySessionMenuLogic', () => {expect(logic.values.handoffMenuId).toEqual('menu-1')expect(logic.values.handoffUser).toEqual(colleague)})++ it('stops the run it is given and refreshes the lists', async () => {+ writesSucceed = true+ logic.actions.stopSession('task-1', 'run-2')+ await expectLogic(logic).toDispatchActions(['sessionUpdated', 'loadRecentTasks'])++ expect(requests).toEqual(['cancel task-1 run-2'])+ })++ it.each([+ ['a finished session archives straight away', null, null, ['patch task-1 {"archived":true}']],+ ['a running session asks first and writes nothing', 'run-1', 'menu-1', []],+ ])('%s', async (_, activeRunId, dialog, expected) => {+ writesSucceed = true+ logic.actions.requestArchive('task-1', 'menu-1', activeRunId)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.archiveConfirmMenuId).toEqual(dialog)+ expect(requests).toEqual(expected)+ })++ it('stops the run before it archives a running session once confirmed', async () => {+ writesSucceed = true+ logic.actions.requestArchive('task-1', 'menu-1', 'run-1')+ logic.actions.confirmArchive('task-1', 'run-1')+ await expectLogic(logic).toDispatchActions(['sessionUpdated', 'closeArchiveConfirm'])++ expect(requests).toEqual(['cancel task-1 run-1', 'patch task-1 {"archived":true}'])+ expect(logic.values.archiveConfirmMenuId).toBeNull()+ })++ it('keeps the confirm open and the session unarchived when the stop fails', async () => {+ logic.actions.requestArchive('task-1', 'menu-1', 'run-1')+ logic.actions.confirmArchive('task-1', 'run-1')+ await expectLogic(logic).toDispatchActions(['sessionUpdateFailed'])++ expect(logic.values.archiveConfirmMenuId).toEqual('menu-1')+ })++ it('copies the project-scoped session URL', async () => {+ jest.mocked(writeToClipboard).mockResolvedValue('copied')+ logic.actions.copySessionLink('task-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(writeToClipboard).toHaveBeenCalledWith(`http://localhost/project/${MOCK_TEAM_ID}/ai?task=task-1`)+ })})diff --git a/frontend/src/layout/today/todaySessionMenuLogic.ts b/frontend/src/layout/today/todaySessionMenuLogic.tsindex 49ca79970dc2..f503c80042a7 100644--- a/frontend/src/layout/today/todaySessionMenuLogic.ts+++ b/frontend/src/layout/today/todaySessionMenuLogic.ts@@ -5,6 +5,7 @@ import { toast } from '@posthog/quill'import { ApiError, readableErrorMessage } from 'lib/api-error'import { fullName } from 'lib/utils/strings'+import { writeToClipboard } from 'lib/utils/writeToClipboard'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -15,6 +16,7 @@ import {tasksPartialUpdate,tasksPinCreate,tasksRunsAnalyzeCreate,+ tasksRunsCancelCreate,} from 'products/tasks/frontend/generated/api'import { PatchedTaskWriteApi } from 'products/tasks/frontend/generated/api.schemas'@@ -22,6 +24,10 @@ import { todaySpacesLogic } from './todaySpacesLogic'export type TodaySessionSurface = 'sidebar' | 'feed'+export function sessionUrl(sessionId: string): string {+ return urls.absolute(urls.currentProject(urls.aiTask(sessionId)))+}+function serverMessage(error: unknown): string | undefined {return error instanceof ApiError ? readableErrorMessage(error.data) : undefined}@@ -29,6 +35,7 @@ function serverMessage(error: unknown): string | undefined {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface todaySessionMenuLogicValues {currentTeamId: number | null // teamLogic+ archiveConfirmMenuId: string | nullhandoffMenuId: string | nullhandoffUser: UserBasicType | nullpendingSessionIds: string[]@@ -56,9 +63,22 @@ export interface todaySessionMenuLogicActions {archived: booleansessionId: string}+ closeArchiveConfirm: () => {+ value: true+ }closeHandoff: () => {value: true}+ confirmArchive: (+ sessionId: string,+ runId: string+ ) => {+ runId: string+ sessionId: string+ }+ copySessionLink: (sessionId: string) => {+ sessionId: string+ }handOffSession: (sessionId: string,user: UserBasicType@@ -76,6 +96,9 @@ export interface todaySessionMenuLogicActions {openHandoff: (menuId: string) => {menuId: string}+ openSessionInNewTab: (sessionId: string) => {+ sessionId: string+ }renameSession: (sessionId: string,title: string@@ -83,6 +106,15 @@ export interface todaySessionMenuLogicActions {sessionId: stringtitle: string}+ requestArchive: (+ sessionId: string,+ menuId: string,+ activeRunId: string | null+ ) => {+ activeRunId: string | null+ menuId: string+ sessionId: string+ }sessionUpdateFailed: (sessionId: string) => {sessionId: string}@@ -109,6 +141,13 @@ export interface todaySessionMenuLogicActions {stopRenaming: () => {value: true}+ stopSession: (+ sessionId: string,+ runId: string+ ) => {+ runId: string+ sessionId: string+ }}export type todaySessionMenuLogicType = MakeLogicType<todaySessionMenuLogicValues, todaySessionMenuLogicActions>@@ -133,6 +172,16 @@ export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([setHandoffUser: (user: UserBasicType | null) => ({ user }),handOffSession: (sessionId: string, user: UserBasicType) => ({ sessionId, user }),analyzeSession: (sessionId: string, runId: string) => ({ sessionId, runId }),+ openSessionInNewTab: (sessionId: string) => ({ sessionId }),+ copySessionLink: (sessionId: string) => ({ sessionId }),+ stopSession: (sessionId: string, runId: string) => ({ sessionId, runId }),+ requestArchive: (sessionId: string, menuId: string, activeRunId: string | null) => ({+ sessionId,+ menuId,+ activeRunId,+ }),+ closeArchiveConfirm: true,+ confirmArchive: (sessionId: string, runId: string) => ({ sessionId, runId }),}),reducers({renaming: [@@ -150,6 +199,13 @@ export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([closeHandoff: () => null,},],+ archiveConfirmMenuId: [+ null as string | null,+ {+ requestArchive: (state, { menuId, activeRunId }) => (activeRunId ? menuId : state),+ closeArchiveConfirm: () => null,+ },+ ],handoffUser: [null as UserBasicType | null,{@@ -167,6 +223,8 @@ export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([moveSession: (state, { sessionId }) => [...state, sessionId],handOffSession: (state, { sessionId }) => [...state, sessionId],analyzeSession: (state, { sessionId }) => [...state, sessionId],+ stopSession: (state, { sessionId }) => [...state, sessionId],+ confirmArchive: (state, { sessionId }) => [...state, sessionId],sessionUpdated: (state, { sessionId }) => state.filter((id) => id !== sessionId),sessionUpdateFailed: (state, { sessionId }) => state.filter((id) => id !== sessionId),},@@ -185,6 +243,21 @@ export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([}}+ const archive = async (sessionId: string, archived: boolean): Promise<boolean> => {+ const done = await update(+ sessionId,+ { archived },+ `Couldn’t ${archived ? 'archive' : 'restore'} this session. Try again.`+ )+ if (done && archived) {+ toast.success({+ title: 'Session archived',+ action: { label: 'Undo', onClick: () => actions.archiveSession(sessionId, false) },+ })+ }+ return done+ }+return {setSessionPinned: async ({ sessionId, pinned }) => {try {@@ -199,16 +272,45 @@ export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([await update(sessionId, { title, title_manually_set: true }, 'Couldn’t rename this session. Try again.')},archiveSession: async ({ sessionId, archived }) => {- const done = await update(- sessionId,- { archived },- `Couldn’t ${archived ? 'archive' : 'restore'} this session. Try again.`- )- if (done && archived) {- toast.success({- title: 'Session archived',- action: { label: 'Undo', onClick: () => actions.archiveSession(sessionId, false) },- })+ await archive(sessionId, archived)+ },+ requestArchive: ({ sessionId, activeRunId }) => {+ if (!activeRunId) {+ actions.archiveSession(sessionId, true)+ }+ },+ confirmArchive: async ({ sessionId, runId }) => {+ // Archiving alone leaves the cloud run going, so stop it first, as the confirm says.+ try {+ await tasksRunsCancelCreate(String(values.currentTeamId), sessionId, runId)+ } catch (error) {+ toast.error({ title: serverMessage(error) ?? 'Couldn’t stop this session. Try again.' })+ actions.sessionUpdateFailed(sessionId)+ return+ }+ if (await archive(sessionId, true)) {+ actions.closeArchiveConfirm()+ }+ },+ stopSession: async ({ sessionId, runId }) => {+ try {+ await tasksRunsCancelCreate(String(values.currentTeamId), sessionId, runId)+ toast.success({ title: 'Stop requested' })+ actions.sessionUpdated(sessionId)+ } catch (error) {+ toast.error({ title: serverMessage(error) ?? 'Couldn’t stop this session. Try again.' })+ actions.sessionUpdateFailed(sessionId)+ }+ },+ openSessionInNewTab: ({ sessionId }) => {+ window.open(sessionUrl(sessionId), '_blank', 'noopener')+ },+ copySessionLink: async ({ sessionId }) => {+ const outcome = await writeToClipboard(sessionUrl(sessionId))+ if (outcome === 'copied') {+ toast.success({ title: 'Link copied' })+ } else {+ toast.error({ title: 'Couldn’t copy the link. Try again.' })}},moveSession: async ({ sessionId, spaceId }) => {diff --git a/frontend/src/layout/today/todaySpacesLogic.ts b/frontend/src/layout/today/todaySpacesLogic.tsindex 8a8ab4b7de01..f3cf5c32b168 100644--- a/frontend/src/layout/today/todaySpacesLogic.ts+++ b/frontend/src/layout/today/todaySpacesLogic.ts@@ -54,6 +54,20 @@ export function starredSpaces(spaces: ChannelDTOApi[]): ChannelDTOApi[] {]}+/** The spaces a session can be filed to: its current space first, then starred spaces, then the rest by name. */+export function fileToSpaces(spaces: ChannelDTOApi[], currentSpaceId: string | null, search = ''): ChannelDTOApi[] {+ const query = search.trim().toLowerCase()+ const starred = starredSpaces(spaces)+ const ordered = [+ ...spaces.filter((space) => space.id === currentSpaceId),+ ...starred.filter((space) => space.id !== currentSpaceId),+ ...spaces+ .filter((space) => space.id !== currentSpaceId && !starred.includes(space))+ .sort((first, second) => first.name.localeCompare(second.name)),+ ]+ return query ? ordered.filter((space) => spaceLabel(space).toLowerCase().includes(query)) : ordered+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface todaySpacesLogicValues {conversationHistory: ConversationDetail[] // maxGlobalLogicdiff --git a/frontend/src/layout/today/todayWorkItems.test.ts b/frontend/src/layout/today/todayWorkItems.test.tsindex 859c90462914..806db4935c99 100644--- a/frontend/src/layout/today/todayWorkItems.test.ts+++ b/frontend/src/layout/today/todayWorkItems.test.ts@@ -12,6 +12,7 @@ import {} from './todayRecentFilters'import { TodayRecentGrouping, TodayRecentSort, groupRecentItems, sortRecentItems } from './todayRecentOrder'import {+ activeCloudRunId,analysisRunId,buildRecentItems,canHandOff,@@ -177,4 +178,19 @@ describe('todayWorkItems', () => {expect(analysisRunId(item)).toBe(runId)})++ it.each([+ ['in_progress', 'cloud', 'run-1'],+ ['queued', 'cloud', 'run-1'],+ ['completed', 'cloud', null],+ ['in_progress', 'local', null],+ ])('treats a %s %s run as stoppable: %s', (status, environment, runId) => {+ const item = sessionItem({+ id: 's',+ title: 'Session',+ latest_run: { id: 'run-1', status, environment },+ } as TaskListItemApi)++ expect(activeCloudRunId(item)).toBe(runId)+ })})diff --git a/frontend/src/layout/today/todayWorkItems.ts b/frontend/src/layout/today/todayWorkItems.tsindex da47ec57ee12..8b2a2e70b0d9 100644--- a/frontend/src/layout/today/todayWorkItems.ts+++ b/frontend/src/layout/today/todayWorkItems.ts@@ -3,6 +3,7 @@ import { Dayjs, dayjs } from 'lib/dayjs'import { ConversationDetail } from '~/types'import { TaskListItemApi } from 'products/tasks/frontend/generated/api.schemas'+import { TaskPullRequest, taskPullRequests } from 'products/tasks/frontend/spaces/taskPullRequests'export type TodayWorkItemKind = 'session' | 'chat'@@ -16,10 +17,12 @@ export interface TodayWorkItem {channel: string | nullcreatedById: number | nulllatestRunId: string | null+ runEnvironment: string | nulloriginProduct: string | null/** What filed it: a session's origin product, or PostHog AI for a chat. */source: string | nullrepository: string | null+ pullRequests: TaskPullRequest[]}export interface TodayWorkGroup {@@ -29,6 +32,7 @@ export interface TodayWorkGroup {}const FINISHED_RUN_STATUSES = new Set(['completed', 'failed', 'cancelled'])+const ACTIVE_RUN_STATUSES = new Set(['not_started', 'queued', 'in_progress'])export function canHandOff(item: TodayWorkItem, userId: number | null | undefined): boolean {return item.kind === 'session' && item.createdById !== null && item.createdById === userId@@ -40,6 +44,16 @@ export function analysisRunId(item: TodayWorkItem): string | null {: null}+/** The latest run when it is a cloud run that is still going, so the session can be stopped. */+export function activeCloudRunId(item: TodayWorkItem): string | null {+ return item.kind === 'session' &&+ item.runEnvironment === 'cloud' &&+ item.status !== null &&+ ACTIVE_RUN_STATUSES.has(item.status)+ ? item.latestRunId+ : null+}+export function sessionItem(task: TaskListItemApi): TodayWorkItem {return {kind: 'session',@@ -51,9 +65,11 @@ export function sessionItem(task: TaskListItemApi): TodayWorkItem {channel: task.channel ?? null,createdById: task.created_by?.id ?? null,latestRunId: task.latest_run?.id ?? null,+ runEnvironment: task.latest_run?.environment ?? null,originProduct: task.origin_product ?? null,source: task.origin_product || null,repository: task.repository || null,+ pullRequests: taskPullRequests(task.latest_run?.output),}}@@ -68,9 +84,11 @@ export function chatItem(conversation: ConversationDetail): TodayWorkItem {channel: null,createdById: conversation.user?.id ?? null,latestRunId: null,+ runEnvironment: null,originProduct: null,source: 'posthog_ai',repository: null,+ pullRequests: [],}}diff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsxindex 1160bec6e255..5329ff220090 100644--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx@@ -71,7 +71,8 @@ const PINNED_SESSIONS = [title: 'Fix the flaky checkout test',archived: false,last_activity_at: '2026-09-28T17:40:00Z',- latest_run: { status: 'in_progress', environment: 'cloud', output: null },+ latest_run: { id: 'run-pinned', status: 'in_progress', environment: 'cloud', output: null },+ channel: 'space-checkout',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,6 +83,7 @@ const RECENT_SESSIONS = [...PINNED_SESSIONS,{id: 'task-1',+ channel: 'space-checkout',title: 'Add a retry to the billing webhook',archived: false,last_activity_at: '2026-09-28T18:05:00Z',@@ -97,6 +99,7 @@ const RECENT_SESSIONS = [},{id: 'task-2',+ channel: 'space-checkout',title: 'Investigate the drop in trial starts',archived: false,last_activity_at: '2026-09-27T11:20:00Z',diff --git a/products/tasks/frontend/spaces/SpaceFeedCard.tsx b/products/tasks/frontend/spaces/SpaceFeedCard.tsxindex 2811db9c32e5..c27f3a52165d 100644--- a/products/tasks/frontend/spaces/SpaceFeedCard.tsx+++ b/products/tasks/frontend/spaces/SpaceFeedCard.tsx@@ -1,7 +1,20 @@import { useValues } from 'kea'import { IconGitBranch } from '@posthog/icons'-import { Avatar, AvatarFallback, Badge, Card, Text, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'+import {+ Avatar,+ AvatarFallback,+ Badge,+ Button,+ Card,+ Popover,+ PopoverContent,+ PopoverTrigger,+ Text,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@posthog/quill'import { LinkPrimitive } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'@@ -11,11 +24,13 @@ 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 { activeCloudRunId, analysisRunId, canHandOff, sessionItem, shortTimeAgo } from '~/layout/today/todayWorkItems'import { TaskListItemApi } from '../generated/api.schemas'import { spaceFeedPreview } from './spaceFeedPreview'import { spaceFeedStatus } from './spaceFeedStatus'+import { TaskPullRequestChip } from './TaskPullRequestChip'+import { pullRequestLabel, splitPullRequests } from './taskPullRequests'interface SpaceFeedCardProps {task: TaskListItemApi@@ -27,6 +42,7 @@ export function SpaceFeedCard({ task, pinned }: SpaceFeedCardProps): JSX.Elementconst { user } = useValues(userLogic)const item = sessionItem(task)const status = spaceFeedStatus(task.latest_run)+ const pullRequests = splitPullRequests(item.pullRequests)const preview = spaceFeedPreview('description_preview' in task ? task.description_preview : task.description)const author = task.created_byconst authorName = author ? [author.first_name, author.last_name].filter(Boolean).join(' ') || author.email : null@@ -66,11 +82,13 @@ export function SpaceFeedCard({ task, pinned }: SpaceFeedCardProps): JSX.Element{status && <Badge variant={status.variant}>{status.label}</Badge>}<TodaySessionMenusessionId={task.id}+ title={item.title}pinned={pinned}spaceId={item.channel}surface="feed"canHandOff={canHandOff(item, user?.id)}analysisRunId={analysisRunId(item)}+ activeRunId={activeCloudRunId(item)}/></div></div>@@ -79,7 +97,7 @@ export function SpaceFeedCard({ task, pinned }: SpaceFeedCardProps): JSX.Element{preview}</Text>)}- {(task.repository || author) && (+ {(task.repository || author || item.pullRequests.length > 0) && (<div className="flex min-w-0 items-center gap-2 pt-1">{task.repository && (<Text@@ -92,6 +110,40 @@ export function SpaceFeedCard({ task, pinned }: SpaceFeedCardProps): JSX.Element<span className="truncate">{task.repository}</span></Text>)}+ {pullRequests.visible.map((pullRequest) => (+ <TaskPullRequestChip+ key={pullRequest.url}+ pullRequest={pullRequest}+ label={pullRequestLabel(pullRequest, task.repository)}+ dataAttr="today-pr-chip-feed"+ />+ ))}+ {pullRequests.overflow.length > 0 && (+ <Popover>+ <PopoverTrigger+ render={+ <Button+ size="xs"+ variant="outline"+ className="relative shrink-0"+ data-attr="today-pr-chip-overflow"+ />+ }+ >+ {`+${pullRequests.overflow.length} ${pullRequests.overflow.length === 1 ? 'PR' : 'PRs'}`}+ </PopoverTrigger>+ <PopoverContent align="start" className="flex max-w-72 flex-col items-start gap-1">+ {pullRequests.overflow.map((pullRequest) => (+ <TaskPullRequestChip+ key={pullRequest.url}+ pullRequest={pullRequest}+ label={pullRequestLabel(pullRequest, task.repository)}+ dataAttr="today-pr-chip-feed"+ />+ ))}+ </PopoverContent>+ </Popover>+ )}{authorName && (<Tooltip><TooltipTriggerdiff --git a/products/tasks/frontend/spaces/TaskPullRequestChip.tsx b/products/tasks/frontend/spaces/TaskPullRequestChip.tsxnew file mode 100644index 000000000000..37756c21768c--- /dev/null+++ b/products/tasks/frontend/spaces/TaskPullRequestChip.tsx@@ -0,0 +1,36 @@+import { IconPullRequest } from '@posthog/icons'+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'++import { LinkPrimitive } from 'lib/lemon-ui/Link'++import { TaskPullRequest } from './taskPullRequests'++interface TaskPullRequestChipProps {+ pullRequest: TaskPullRequest+ label: string+ dataAttr: string+}++export function TaskPullRequestChip({ pullRequest, label, dataAttr }: TaskPullRequestChipProps): JSX.Element {+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="xs"+ variant="outline"+ render={<LinkPrimitive to={pullRequest.url} target="_blank" />}+ aria-label={`Open pull request ${pullRequest.repository}#${pullRequest.number} on GitHub`}+ data-attr={dataAttr}+ // Sits above the card's full-card link, so it stays clickable.+ className="relative max-w-full shrink-0 tabular-nums"+ />+ }+ >+ <IconPullRequest className="shrink-0" />+ <span className="min-w-0 truncate">{label}</span>+ </TooltipTrigger>+ <TooltipContent>{pullRequest.url}</TooltipContent>+ </Tooltip>+ )+}diff --git a/products/tasks/frontend/spaces/taskPullRequests.test.ts b/products/tasks/frontend/spaces/taskPullRequests.test.tsnew file mode 100644index 000000000000..15277905687e--- /dev/null+++ b/products/tasks/frontend/spaces/taskPullRequests.test.ts@@ -0,0 +1,53 @@+import { TaskRunDetailDTOApi } from '../generated/api.schemas'+import { TaskPullRequest, pullRequestLabel, splitPullRequests, taskPullRequests } from './taskPullRequests'++const pr = (repository: string, number: number): TaskPullRequest => ({+ url: `https://github.com/${repository}/pull/${number}`,+ repository,+ number,+})++const prs = (count: number): TaskPullRequest[] => Array.from({ length: count }, (_, index) => pr('org/app', index + 1))++describe('taskPullRequests', () => {+ it.each<[string, TaskRunDetailDTOApi['output'] | undefined, string[]]>([+ ['a run with no output shows no chip', null, []],+ ['a malformed URL does not crash the card', { pr_url: 'not a url' }, []],+ ['a non-GitHub host is not linked as a GitHub PR', { pr_url: 'https://gitlab.com/org/app/pull/1' }, []],+ ['a GitHub issue is not shown as a PR', { pr_url: 'https://github.com/org/app/issues/1' }, []],+ ['a lookalike path on another host is rejected', { pr_url: 'https://example.com/org/app/pull/1' }, []],+ [+ 'a PR subpage and the PR itself collapse into one chip',+ { pr_url: 'https://github.com/org/app/pull/7', pr_urls: ['https://github.com/org/app/pull/7/files'] },+ ['https://github.com/org/app/pull/7'],+ ],+ [+ 'multiple PRs keep the main pr_url first and skip non-strings',+ {+ pr_url: 'https://github.com/org/web/pull/9',+ pr_urls: ['https://github.com/org/app/pull/3', 42, 'https://github.com/org/web/pull/9'],+ },+ ['https://github.com/org/web/pull/9', 'https://github.com/org/app/pull/3'],+ ],+ ])('%s', (_, output, urls) => {+ expect(taskPullRequests(output).map((pullRequest) => pullRequest.url)).toEqual(urls)+ })++ it.each<[string, TaskPullRequest, string | null, string]>([+ ['the task repository drops the repo name', pr('org/app', 12), 'Org/App', '#12'],+ ['a task repository without the owner still matches', pr('org/app', 12), 'app', '#12'],+ ['a PR in another repository names that repo', pr('org/web', 12), 'org/app', 'web#12'],+ ['a task with no repository names the repo', pr('org/web', 12), null, 'web#12'],+ ])('labels %s', (_, pullRequest, taskRepository, label) => {+ expect(pullRequestLabel(pullRequest, taskRepository)).toEqual(label)+ })++ it.each([+ [2, 2, 0],+ [3, 2, 1],+ [5, 1, 4],+ ])('splits %i PRs into %i chips and %i behind the overflow chip', (count, visible, overflow) => {+ const split = splitPullRequests(prs(count))+ expect([split.visible.length, split.overflow.length]).toEqual([visible, overflow])+ })+})diff --git a/products/tasks/frontend/spaces/taskPullRequests.ts b/products/tasks/frontend/spaces/taskPullRequests.tsnew file mode 100644index 000000000000..d6a4aed3ec72--- /dev/null+++ b/products/tasks/frontend/spaces/taskPullRequests.ts@@ -0,0 +1,66 @@+import { TaskRunDetailDTOApi } from '../generated/api.schemas'++export interface TaskPullRequest {+ url: string+ /** The `owner/repo` part of the URL. */+ repository: string+ number: number+}++const GITHUB_HOSTS = new Set(['github.com', 'www.github.com'])+const PULL_REQUEST_PATH = /^\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:\/|$)/++export function parsePullRequestUrl(raw: string): TaskPullRequest | null {+ let parsed: URL+ try {+ parsed = new URL(raw.trim())+ } catch {+ return null+ }+ if (parsed.protocol !== 'https:' || !GITHUB_HOSTS.has(parsed.hostname)) {+ return null+ }+ const match = PULL_REQUEST_PATH.exec(parsed.pathname)+ if (!match) {+ return null+ }+ const [, owner, repo, number] = match+ return {+ url: `https://github.com/${owner}/${repo}/pull/${number}`,+ repository: `${owner}/${repo}`,+ number: Number(number),+ }+}++/** Every GitHub pull request the run reported, without duplicates. The run's main `pr_url` comes first. */+export function taskPullRequests(output: TaskRunDetailDTOApi['output'] | undefined): TaskPullRequest[] {+ if (!output) {+ return []+ }+ const listed: unknown[] = Array.isArray(output.pr_urls) ? output.pr_urls : []+ const pullRequests: TaskPullRequest[] = []+ for (const candidate of [output.pr_url, ...listed]) {+ const pullRequest = typeof candidate === 'string' ? parsePullRequestUrl(candidate) : null+ if (pullRequest && !pullRequests.some((existing) => existing.url === pullRequest.url)) {+ pullRequests.push(pullRequest)+ }+ }+ return pullRequests+}++/** Like Desktop, the card shows two chips, or one when there are five or more. The rest go behind a "+N PRs" chip. */+export function splitPullRequests(pullRequests: TaskPullRequest[]): {+ visible: TaskPullRequest[]+ overflow: TaskPullRequest[]+} {+ const visibleCount = pullRequests.length >= 5 ? 1 : 2+ return { visible: pullRequests.slice(0, visibleCount), overflow: pullRequests.slice(visibleCount) }+}++/** `#123` when the pull request is in the task's repository, `repo#123` when it is in another one. */+export function pullRequestLabel(pullRequest: TaskPullRequest, taskRepository: string | null | undefined): string {+ const [, repoName] = pullRequest.repository.split('/')+ const task = taskRepository?.toLowerCase()+ const sameRepository = task === pullRequest.repository.toLowerCase() || task === repoName.toLowerCase()+ return sameRepository ? `#${pullRequest.number}` : `${repoName}#${pullRequest.number}`+}