: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(inbox): open report tasks in the ai sidebar (#98565)
Chris Volzer74b8169db131
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 69302aafee9b..bd23f9e0e9ef 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5852,6 +5852,10 @@ snapshots:hash: v1.k794b7964.ab407d100e82b2804ac63958c38fc48af75120b67e9158c9b280487b2245687e.kZn1-gur30DNFrP7TDua5UGXGu6HziGnAVPc9Zz3wMUproducts-posthog-ai-virtualizedthread--long-thread--light:hash: v1.k794b7964.ea4454f7d7d4dc076ff61362f178cfa010fda1c721696790f03057e864699826.drgUhmxnD0Dt_wm7kKiSeLzeU3WrrNcDJPwFY_rxnec+ products-posthog-ai-virtualizedthread--remembered-position--dark:+ hash: v1.k794b7964.4662afb072c9ec5fa3805f870c2326dd4330ceb30a58a85e4d558b1e0f67dfd3.-5QKTHs8l3O38uVL4I5qdoO2HdNu85hXd1H0pTFTxYI+ products-posthog-ai-virtualizedthread--remembered-position--light:+ hash: v1.k794b7964.fcd3d3ae2a58e891ec3fb4b224d8674f1591e349a990e0211aee29c9bf6f8d01.ThH9PVDZc4Ziy5_MNxrvijx6pRk5muGoa3ul6PgEEZwproducts-posthog-ai-virtualizedthread--streaming--dark:hash: v1.k794b7964.c4ebc83f695831769cc95475925e983a71d5909636818ff2153e2dc7df5450a1.9VcSQPoSe9fMttmpga5INPhkJySlhF35v8dHEs52L90products-posthog-ai-virtualizedthread--streaming--light:@@ -7920,14 +7924,18 @@ snapshots:hash: v1.k794b7964.6d25562ee11eb3e2bc5ecf6aedff4fe058299de21db40a241d22ec348566b5e7.1QCX8kAJWvaKf9rBXs7O4S-9Nh9tbQR6zn2IL5ehZposcenes-app-inbox-detail--run-ready--light:hash: v1.k794b7964.2a7035c21bc396a44a81e18222d5f9a50f8ca650d47bc387b27a4c8ab72db7aa.BZ_qNCVpWT1v8Ov60-xHUyKzBwvr1BPNjoLZgjobYw4+ scenes-app-inbox-discussreportbutton--sidebar--dark:+ hash: v1.k794b7964.5a357cca98a63ead6a78801c2fe9a6611e4e4fd7f5313db5949615633b8c2d1b.9DjLvoEQ9RglyBp_gJ0x7DpQIbSSeH0pBpu-vqGDP1A+ scenes-app-inbox-discussreportbutton--sidebar--light:+ hash: v1.k794b7964.92807da1196fab045c7b5f02d4b645023757f9c5eb4cc8444da3276cc25a4bed.NRJdWtDfvXvnjBPPzNSbVa7RqppNPYfhFTcbEqrqN7Ascenes-app-inbox-discussreportbutton--with-suggestions--dark:- hash: v1.k794b7964.eac6e6142d7e4691b0d21db813719df6719b507ecef84137f0df4b4bf3efe4f3.a69HoQRIbA83KFV7pEchsR08azkm0XLHON-UcYLRwf4+ hash: v1.k794b7964.0662df6c90e704d03611a915365cf5fe9be45ca6f30c00aa4b100775ed6bd06a.hmMoggpQSMfnDAA7Y1VpwOHzt82j01c-L1HnQZSdVpQscenes-app-inbox-discussreportbutton--with-suggestions--light:- hash: v1.k794b7964.1ab8d6d455b4d5ece77d779127b1b560198f64d5d6489775a806bee1645290c4.yaVzGvaYu2yvrdZX7lUR9T_4fkNPuHGb8fl6MSfEX18+ hash: v1.k794b7964.71dbaf50fdc474133868b30dbedc5b571868757a59d6262b4e3ff9213175ca4a.zCGJqcn5flN6sIZMtkM6kU-U1io1io8KU3ZBL_azDroscenes-app-inbox-discussreportbutton--without-suggestions--dark:- hash: v1.k794b7964.ccb77e3ec9d1fcde6109b59a5ffb39c8525644d2312e8dd3d1dc927e452c63d4.kz0Ttl9-0xZinC3MVz__7xrBK9mHmXbEy0NkizulnLk+ hash: v1.k794b7964.164fd5ed2f96e3ac03d7730e2632bbb6955495658d21115a3c50e422b9359ffb.KPVVlHTRxbEXamMZf902nJoYbizn9_deVkO-U9ilp-gscenes-app-inbox-discussreportbutton--without-suggestions--light:- hash: v1.k794b7964.a53bf574106e2044fed49931ee8d29c7bf8ce14fcba8ceff7d1534208f738ed2.uNVRrxR3i9gSlCtUU7zTcTmMeXjaIPzxTjUyApGT3kU+ hash: v1.k794b7964.802a762b1bb9bbe2118b6d2e5d069aca7fa400b4b56d5da1f16e2c5bbca6da7c.-RwViW4MIvryo4e14R6BHaz9j6RGsShQcrc-iYjm-LYscenes-app-inbox-hotkeyradio--with-selection--dark:hash: v1.k794b7964.ee23fd931ed2324fdc42cbb44bb06176f40e1e47d5c03f9118ccc0f5f013201b.BmJiKZm5EO6qY8tSt5oSll_wmMMWh7IJ0dqN_bSQwa8scenes-app-inbox-hotkeyradio--with-selection--light:diff --git a/frontend/src/scenes/max/Max.tsx b/frontend/src/scenes/max/Max.tsxindex 3df7a3adcf40..62587c529b74 100644--- a/frontend/src/scenes/max/Max.tsx+++ b/frontend/src/scenes/max/Max.tsx@@ -1,5 +1,5 @@import { BindLogic, useActions, useValues } from 'kea'-import React from 'react'+import React, { Suspense } from 'react'import {IconArrowLeft,@@ -10,12 +10,13 @@ import {IconShare,IconSidePanel,} from '@posthog/icons'-import { LemonBanner, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonBanner, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { cn } from 'lib/utils/css-classes'+import { lazyWithRetry } from 'lib/utils/retryImport'import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -23,12 +24,14 @@ import { urls } from 'scenes/urls'import { SidePanelPaneHeader } from '~/layout/navigation-3000/sidepanel/components/SidePanelPaneHeader'import { SidePanelContentContainer } from '~/layout/navigation-3000/sidepanel/SidePanelContentContainer'import { sidePanelLogic } from '~/layout/navigation-3000/sidepanel/sidePanelLogic'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { SidePanelTab } from '~/types'import { runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'import { DebugLogsMenu } from 'products/posthog_ai/frontend/api/primitives'+import { REPORT_AI_PANEL } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'import { AiFirstMaxInstance } from './components/AiFirstMaxInstance'import { AnimatedBackButton } from './components/AnimatedBackButton'@@ -46,6 +49,12 @@ import { MaxLogicProps, SIDE_PANEL_PANEL_ID, maxLogic } from './maxLogic'import { MaxThreadLogicProps, maxThreadLogic } from './maxThreadLogic'import { SandboxComposerSurfaces, Thread } from './Thread'+const ReportAiPanel = lazyWithRetry(() =>+ import('products/signals/frontend/inbox/components/detail/ReportAiPanel').then((module) => ({+ default: module.ReportAiPanel,+ }))+)+export const scene: SceneExport = {component: Max,logic: maxLogic,@@ -119,11 +128,15 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:const { closeSidePanel } = useActions(sidePanelLogic)+ const { selectedTabOptions } = useValues(sidePanelStateLogic)const isNewView = effectivePhaiView === 'new'- const headerBackDisabled = isNewView ? !panelCanGoBack : backButtonDisabled+ const isReportChat = !!sidePanel && selectedTabOptions === REPORT_AI_PANEL+ const isTaskView = isNewView || isReportChat+ const headerBackDisabled = isTaskView ? !panelCanGoBack : backButtonDisabled+ const headerTitle = isReportChat ? 'PostHog AI' : chatTitle || 'PostHog AI'const openAsMainFocusUrl = mainFocusUrl({- isNewView,+ isNewView: isTaskView,activeCreation: panelActiveCreation,conversationId,})@@ -133,7 +146,11 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:) : (<BindLogic logic={maxLogic} props={logicProps}><BindLogic logic={maxThreadLogic} props={threadProps}>- {effectivePhaiView === 'new' ? (+ {isReportChat ? (+ <Suspense fallback={<Spinner />}>+ <ReportAiPanel panelId={MAX_SIDE_PANEL_ID} />+ </Suspense>+ ) : isNewView ? (// Side panel only shows the new composer + thread viewer — the tasks list lives on /ai.<PhaiSidePanelChat />) : conversationHistoryVisible ? (@@ -185,10 +202,10 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:<SidePanelPaneHeader className="transition-all duration-200" showCloseButton={false}><div className="flex flex-1 min-w-0 overflow-hidden"><div className="flex items-center flex-1 min-w-0">- <AnimatedBackButton in={isNewView ? panelCanGoBack : !backButtonDisabled}>+ <AnimatedBackButton in={isTaskView ? panelCanGoBack : !backButtonDisabled}><ButtonPrimitiveiconOnly- onClick={() => (isNewView ? panelGoBack() : goBack())}+ onClick={() => (isTaskView ? panelGoBack() : goBack())}tooltip="Go back"tooltipPlacement="bottom-end"disabledReasons={headerBackDisabled ? { 'You are already at home': true } : undefined}@@ -197,11 +214,11 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:</ButtonPrimitive></AnimatedBackButton>- <Tooltip title={chatTitle || undefined} placement="bottom">- <h3 className="flex-1 font-semibold mb-0 truncate text-sm ml-2">{chatTitle || 'PostHog AI'}</h3>+ <Tooltip title={headerTitle} placement="bottom">+ <h3 className="flex-1 font-semibold mb-0 truncate text-sm ml-2">{headerTitle}</h3></Tooltip></div>- {conversationId && !conversationHistoryVisible && !threadVisible && (+ {!isReportChat && conversationId && !conversationHistoryVisible && !threadVisible && (<LemonButtonsize="small"icon={<IconPlus />}@@ -211,7 +228,7 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:tooltipPlacement="bottom"/>)}- {conversationId && (+ {!isReportChat && conversationId && (<ButtonPrimitiveonClick={() => {copyToClipboard(@@ -228,8 +245,10 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:)}{/* The new view is the runner (always sandbox); legacy view only shows debug rows on asandbox conversation, so the menu stays hidden on LangGraph threads. */}- {(isNewView || conversation?.agent_runtime === 'sandbox') && <DebugLogsMenu variant="primitive" />}- <PhaiViewToggle variant="primitive" />+ {(isTaskView || conversation?.agent_runtime === 'sandbox') && <DebugLogsMenu variant="primitive" />}+ {/* Report mode renders the runner whichever view is selected, so in it the toggle would+ only flip the persisted default for the user's next PostHog AI session. */}+ {!isReportChat && <PhaiViewToggle variant="primitive" />}<LinkbuttonProps={{iconOnly: true,@@ -255,7 +274,7 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:content must stay clamped to the panel height — without `min-h-0` its `min-height: auto`grows it to fit the whole thread and no scroller ever engages. The legacy view is theopposite: it relies on this container growing so the outer viewport scrolls it. */}- <SidePanelContentContainer contentClassName={cn('flex flex-col flex-1', isNewView && 'min-h-0')}>+ <SidePanelContentContainer contentClassName={cn('flex flex-col flex-1', isTaskView && 'min-h-0')}>{header}{content}</SidePanelContentContainer>diff --git a/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx b/frontend/src/scenes/max/components/PhaiSidePanelChat.tsxindex b7f29477921e..4111635fb3cc 100644--- a/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx+++ b/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx@@ -18,7 +18,6 @@ export const MAX_SIDE_PANEL_ID = 'max-side-panel'export function PhaiSidePanelChat(): JSX.Element {// Bridges the legacy `initialMaxPrompt` side-panel option into this panel's new composer (see the logic).useMountedLogic(phaiSidePanelComposerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }))-return (// `flex-1 min-h-0`, NOT `h-full`: the side panel hosts this inside a ScrollArea whose content// grows with its children (`min-height: auto`), so a percentage height resolves against thediff --git a/frontend/src/scenes/max/maxLogic.test.ts b/frontend/src/scenes/max/maxLogic.test.tsindex 8deac1a6e41c..107d6b410e9c 100644--- a/frontend/src/scenes/max/maxLogic.test.ts+++ b/frontend/src/scenes/max/maxLogic.test.ts@@ -13,6 +13,8 @@ import { AgentMode } from '~/queries/schema/schema-assistant-messages'import { initKeaTests } from '~/test/init'import { ConversationDetail, SidePanelTab } from '~/types'+import { REPORT_AI_PANEL } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'+import {PENDING_MAX_CONTEXT_KEY,QUESTION_SUGGESTIONS_DATA,@@ -76,21 +78,22 @@ describe('maxLogic', () => {expect(actionsRequestCount).toBe(0)})- it('sets the question when URL has hash param #panel=max:Foo', async () => {- // Set up sidePanelStateLogic with the options before mounting maxLogic+ it.each([+ ['Foo', 'Foo'],+ [REPORT_AI_PANEL, ''],+ ])('seeds the question from side panel option %s', async (options, question) => {sidePanelStateLogic.mount()await expectLogic(sidePanelStateLogic, () => {- sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, 'Foo')+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, options)}).toDispatchActions(['openSidePanel'])- // Mount maxLogic after setting up the sidePanelStateLogic statelogic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })logic.mount()- // Check that the question has been set to "Foo"- await expectLogic(logic).toMatchValues({- question: 'Foo',- })+ await expectLogic(logic).toMatchValues({ question, autoRun: false })+ logic.actions.setQuestion('Existing draft')+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, REPORT_AI_PANEL)+ expect(logic.values.question).toBe('Existing draft')})it('sets autoRun and question when URL has hash param #panel=max:!Foo', async () => {diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsxindex d14f8053201e..f310a7bcdd9f 100644--- a/frontend/src/scenes/max/maxLogic.tsx+++ b/frontend/src/scenes/max/maxLogic.tsx@@ -26,6 +26,8 @@ import {SidePanelTab,} from '~/types'+import { REPORT_AI_PANEL } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'+import type { ToolRegistration } from './max-constants'import { PENDING_AI_PROMPT_KEY } from './max-storage-keys'import { maxContextLogic } from './maxContextLogic'@@ -111,6 +113,9 @@ export function parseCommandString(options: string): ParsedCommand {}function handleCommandString(options: string, actions: maxLogicType['actions'], effectivePhaiView: PhaiViewMode): void {+ if (options === REPORT_AI_PANEL) {+ return+ }const parsed = parseCommandString(options)// Note: The mode parameter is handled directly by maxThreadLogic in its afterMountdiff --git a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.ts b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.tsindex fcceefd7d15b..4d4d18c9a827 100644--- a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.ts+++ b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.ts@@ -4,6 +4,7 @@ import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePaneimport { SidePanelTab } from '~/types'import { ComposerSeed, composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'+import { REPORT_AI_PANEL } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'import { maxGlobalLogic } from './maxGlobalLogic'import { parseCommandString } from './maxLogic'@@ -21,7 +22,7 @@ function forwardSeed(dataProcessingAccepted: boolean,setSeed: (seed: ComposerSeed) => void): void {- if (typeof options !== 'string') {+ if (typeof options !== 'string' || options === REPORT_AI_PANEL) {return}const { autoRun, question } = parseCommandString(options)diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.tsindex c409545e064b..2ba7156574d7 100644--- a/products/posthog_ai/frontend/api/logics.ts+++ b/products/posthog_ai/frontend/api/logics.ts@@ -38,7 +38,7 @@ export { useWelcomeOverride } from '../hooks/useWelcomeOverride'export type { UseWelcomeOverrideOptions } from '../hooks/useWelcomeOverride'// The standing "act via tool calls" instruction the sidebar surfaces attach while the user watches a// run — the prompt-side half of `useMcpToolApplyBack` (hidden from chips, deduped once per task).-export { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM } from '../utils/posthogContextBlock'+export { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM, wrapWithPosthogContext } from '../utils/posthogContextBlock'// --- User-picked context (the composer's @-affordance, headless half) ---// `contextPickerLogic` owns explicit user picks and registers them as the `user-picker` provider;diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsxindex 58ecff37614b..9dd89a3ed909 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx@@ -306,5 +306,22 @@ describe('RunSurface', () => {expect(screen.queryByTestId('run-log-skeleton')).not.toBeInTheDocument()})++ it('keeps an optimistic provisioning thread visible while task metadata loads', () => {+ setValues({ bootstrapLoading: true, threadItems: [], task: null })+ render(+ <RunSurface.Root+ taskId="task-1"+ runId="run-1"+ streamKey="report-implementation-client-stream"+ interaction="live"+ >+ <RunSurface.Thread />+ </RunSurface.Root>+ )++ expect(screen.getByTestId('thread')).toBeInTheDocument()+ expect(screen.queryByTestId('run-log-skeleton')).not.toBeInTheDocument()+ })})})diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxindex b3955739cc07..f96827a882e3 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -90,6 +90,7 @@ function RunSurfaceRoot({const replayOnly = interaction !== 'live'// A pending surface (no run id) must supply `streamKey` to key on; `runId` is the key otherwise.const logicKey = streamKey ?? runId ?? ''+ const hasOptimisticClientStream = !!streamKey && streamKey !== runIdconst { hasThreadItems } = useValues(runStreamLogic({ streamKey: logicKey, conversationId, replayOnly }))// The runtime and scout flag live on the task (not the run), so the surface owns loading it once and@@ -114,8 +115,7 @@ function RunSurfaceRoot({</LemonBanner>)}- // A created task's metadata fetch must not replace its already visible optimistic thread.- if (!hasThreadItems) {+ if (!hasThreadItems && !hasOptimisticClientStream) {return <RunLogSkeleton />}}@@ -188,11 +188,13 @@ function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {/** Thread slot: the streamed run thread, with the shared run-log skeleton during the first bootstrap. */function RunSurfaceThread({+ restoreReadPosition = false,className,listClassName,rowClassName,showContextUsage = false,}: {+ restoreReadPosition?: booleanclassName?: stringlistClassName?: stringrowClassName?: string@@ -227,7 +229,7 @@ function RunSurfaceThread({) : null,[feedbackSessionId, feedbackRun])- const showSkeleton = bootstrapLoading && !hasThreadItems+ const showSkeleton = bootstrapLoading && !hasThreadItems && streamKey === runIdif (showSkeleton) {return <RunLogSkeleton className={className} listClassName={listClassName} rowClassName={rowClassName} />}@@ -237,6 +239,7 @@ function RunSurfaceThread({// Turn feedback: only interactive, non-scout surfaces collect ratings.return (<ThreadView+ scrollRestorationKey={restoreReadPosition ? taskId : undefined}className={className}listClassName={listClassName}rowClassName={rowClassName}diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsxindex 5df751ed5745..77807d917d1f 100644--- a/products/posthog_ai/frontend/components/ThreadView.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.tsx@@ -53,6 +53,7 @@ function estimateThreadItemHeight(item: ThreadDisplayItem): number {}interface ThreadViewProps {+ scrollRestorationKey?: string/*** Pass `false` when an ancestor already owns scroll (the live Max column + auto-scroller) — rows then* render in document flow, unchanged from the pre-virtualized layout. Defaults to virtualized.@@ -85,6 +86,7 @@ interface ThreadViewProps {* header/footer rows.*/export function ThreadView({+ scrollRestorationKey,virtualized = true,showContextUsage = false,renderTurnTrailer,@@ -254,6 +256,8 @@ export function ThreadView({return (<VirtualizedThread.Root+ key={scrollRestorationKey}+ scrollRestorationKey={scrollRestorationKey}items={displayItems}getItemKey={getThreadItemKey}estimateItemHeight={estimateThreadItemHeight}diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsxindex 2e8835298644..6a37afe4e63a 100644--- a/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx+++ b/products/posthog_ai/frontend/components/VirtualizedThread.stories.tsx@@ -1,6 +1,8 @@import type { Meta, StoryObj } from '@storybook/react'import { useEffect, useRef, useState } from 'react'+import { LemonButton } from '@posthog/lemon-ui'+import { cn } from 'lib/utils/css-classes'import { inStorybookTestRunner } from 'lib/utils/dom'@@ -72,6 +74,33 @@ export const LongThread: Story = {},}+export const RememberedPosition: Story = {+ render: function RememberedPosition(): JSX.Element {+ const [visible, setVisible] = useState(true)+ const items = makeItems(80)+ return (+ <div className="flex flex-col gap-2 w-180">+ <LemonButton onClick={() => setVisible(!visible)}>{visible ? 'Close task' : 'Open task'}</LemonButton>+ <div className="h-[600px] border rounded overflow-hidden">+ {visible && (+ <VirtualizedThread.Root+ items={items}+ getItemKey={getKey}+ scrollRestorationKey="remembered-position-story"+ >+ {(item) => (+ <VirtualizedThread.Row>+ <FakeMessage role={item.role} text={item.text} />+ </VirtualizedThread.Row>+ )}+ </VirtualizedThread.Root>+ )}+ </div>+ </div>+ )+ },+}+/** Bounded embed (mirrors the inbox `h-[420px] overflow-hidden` detail panel) — the Root owns the only scroll. */export const BoundedEmbed: Story = {render: () => {diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsxindex 2094a152c6a8..5d6f901b9355 100644--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx@@ -93,6 +93,8 @@ const ROW_BASE_STYLE: CSSProperties = { position: 'absolute', top: 0, left: 0, wconst HEADER_KEY = '__vt_header__'const FOOTER_KEY = '__vt_footer__'+const lastReadItems = new Map<string, string>()+interface RootContextValue {isFollowing: boolean/** Inspecting expanded content should release automatic following, just like scrolling up. */@@ -170,6 +172,7 @@ export interface VirtualizedThreadRootProps<T> {* and follows the streaming answer; the sent message rides up naturally as the response grows.*/anchorItemKey?: string | null+ scrollRestorationKey?: string/*** True while `items` are still being assembled (a history replay in flight). Defers the once-only* opening scroll and the anchor-key adoption: partial fold commits can carry renderable items —@@ -208,6 +211,7 @@ function Root<T>({stickToBottom = true,turnActive = false,anchorItemKey,+ scrollRestorationKey,itemsLoading = false,maxWidthClassName = 'max-w-180',className,@@ -221,6 +225,7 @@ function Root<T>({const scrollRef = useRef<HTMLDivElement>(null)const didInitialScrollRef = useRef(false)+ const savedReadItem = useRef(scrollRestorationKey ? lastReadItems.get(scrollRestorationKey) : undefined)// Content growth can move the bottom before the next follow write. Track reader intent separately:// the ref updates scroll handlers immediately; state publishes the same mode to activity lists.const pinnedRef = useRef(true)@@ -403,7 +408,13 @@ function Root<T>({if (itemsLoading) {return 0}- const anchorIndex = anchorItemKey != null ? findVirtualIndexForKey(anchorItemKey) : -1+ const savedIndex = savedReadItem.current ? findVirtualIndexForKey(savedReadItem.current) : -1+ const anchorIndex =+ savedIndex >= 0+ ? savedIndex+ : anchorItemKey != null+ ? findVirtualIndexForKey(anchorItemKey)+ : -1const limit = anchorIndex >= 0 ? anchorIndex : rowCountlet total = 0for (let i = 0; i < limit; i++) {@@ -415,6 +426,34 @@ function Root<T>({: {}),})+ useEffect(() => {+ const element = scrollRef.current+ if (!scrollRestorationKey || !element || itemsLoading) {+ return+ }+ const rememberPosition = (): void => {+ if (!didInitialScrollRef.current || element.clientHeight === 0 || element.clientWidth === 0) {+ return+ }+ // `item.key`, not a re-derivation from `item.index`: the virtualizer produced that key from+ // its current `getItemKey`, while this listener is only re-bound in the passive phase, so a+ // scroll event arriving after an append can otherwise map a new index through the old `items`.+ const firstVisibleItem = virtualizer.getVirtualItems().find((item) => {+ const itemKey = String(item.key)+ return item.end > element.scrollTop && itemKey !== HEADER_KEY && !itemKey.startsWith(FOOTER_KEY)+ })+ if (firstVisibleItem) {+ lastReadItems.delete(scrollRestorationKey)+ lastReadItems.set(scrollRestorationKey, String(firstVisibleItem.key))+ if (lastReadItems.size > 100) {+ lastReadItems.delete(lastReadItems.keys().next().value!)+ }+ }+ }+ element.addEventListener('scroll', rememberPosition, { passive: true })+ return () => element.removeEventListener('scroll', rememberPosition)+ }, [scrollRestorationKey, virtualizer, itemsLoading])+// The only way to flip pinning. Two pins have to move together and in the same tick as the gesture:// ours, and the core's at-end growth compensation, which is a second pin we do not otherwise control.// Writing the option here is not a duplicate of the render-time value — it is the bridge across one@@ -547,7 +586,9 @@ function Root<T>({return}didInitialScrollRef.current = true- const anchorIndex = anchorItemKey != null ? findVirtualIndexForKey(anchorItemKey) : -1+ const savedIndex = savedReadItem.current ? findVirtualIndexForKey(savedReadItem.current) : -1+ const anchorIndex =+ savedIndex >= 0 ? savedIndex : anchorItemKey != null ? findVirtualIndexForKey(anchorItemKey) : -1const el = scrollRef.currentif (anchorIndex >= 0) {// Provisional anchor landing — this commit only has estimates for the rows under the anchor,@@ -562,7 +603,9 @@ function Root<T>({setPinned(false)bottomRepinBlockedUntilRef.current = performance.now() + BOTTOM_REPIN_BLOCK_MSscheduleAnchorSettle(anchorIndex)- scheduleOpenDecision(anchorIndex)+ if (savedIndex < 0) {+ scheduleOpenDecision(anchorIndex)+ }return}if (turnActive && el) {diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsxindex b3091c695849..e3b516b34c3c 100644--- a/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx+++ b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx@@ -53,8 +53,9 @@ function labelForItem(item: AttachedContextItem): string {* The composer's context affordance: an @-button (TaxonomicPopover) that attaches entity refs to* `contextPickerLogic`, plus removable chips for everything currently in* `attachedContextLogic.contextItems` — picked items and auto-registered providers (e.g. the scene- * bridge) alike. Closing a picked chip removes it from the picker; closing any other provider's chip- * dismisses its key, which sticks even when the provider re-registers the item.+ * bridge) alike. Closing a dismissible picked chip removes it from the picker; closing any other+ * dismissible provider's chip dismisses its key, which sticks even when the provider re-registers+ * the item. Providers can keep mandatory context visible with `dismissible: false`.*/export function AttachedContextBar(): JSX.Element {const { contextItems, hasContext } = useValues(attachedContextLogic)@@ -90,15 +91,21 @@ export function AttachedContextBar(): JSX.Element {.map((item) => {const key = attachedContextItemKey(item)const label = labelForItem(item)+ const dismissible = item.dismissible !== falsereturn (<Tooltip key={key} title={label}><LemonTagicon={iconForType(item.type)}- onClose={() =>- pickedKeys.has(key) ? removePickedItem(key) : dismissContext(key, item.dismissGroup)+ onClose={+ dismissible+ ? () =>+ pickedKeys.has(key)+ ? removePickedItem(key)+ : dismissContext(key, item.dismissGroup)+ : undefined}- closable- closeOnClick+ closable={dismissible}+ closeOnClick={dismissible}className="flex items-center text-secondary max-w-48"><span className="truncate min-w-0 flex-1">{label}</span>diff --git a/products/posthog_ai/frontend/components/suggestions/Suggestions.tsx b/products/posthog_ai/frontend/components/suggestions/Suggestions.tsxindex f97ffb37fc80..cfdaa8efcfaf 100644--- a/products/posthog_ai/frontend/components/suggestions/Suggestions.tsx+++ b/products/posthog_ai/frontend/components/suggestions/Suggestions.tsx@@ -18,6 +18,7 @@ export interface SuggestionItem {content: string/** When true the caller should fill the input and let the user finish typing; otherwise submit directly. */requiresUserInput?: boolean+ dataAttr?: string}export interface SuggestionGroup {@@ -159,6 +160,7 @@ function SuggestionsButtons({icon={group.icon}tooltip={disabled ? undefined : group.tooltip}disabled={disabled}+ data-attr={group.suggestions.length === 1 ? group.suggestions[0]?.dataAttr : undefined}>{group.label}</LemonButton>@@ -217,6 +219,7 @@ function SuggestionsDropdown({ className }: SuggestionsDropdownProps): JSX.Elemetype="tertiary"fullWidthonClick={() => handleSelect(suggestion)}+ data-attr={suggestion.dataAttr}><span className="font-normal">{suggestion.content}</span></LemonButton>diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsxnew file mode 100644index 000000000000..c9714942fa79--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsx@@ -0,0 +1,63 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import { useActions, useValues } from 'kea'++import type { ActiveCreation } from '../../../logics/runnerPanelLogic'+import { SidePanelRunnerImpl } from './SidePanelRunnerImpl'++jest.mock('kea', () => ({+ ...jest.requireActual('kea'),+ BindLogic: ({ children }: { children: React.ReactNode }) => children,+ useActions: jest.fn(),+ useValues: jest.fn(),+}))++jest.mock('../taskTrackerSceneLogic', () => ({ taskTrackerSceneLogic: jest.fn(() => ({ __mock: 'scene' })) }))+jest.mock('../../../hooks/useForegroundStream', () => ({ useForegroundStream: jest.fn() }))+jest.mock('../../../hooks/useAttachedContext', () => ({ useAttachedContext: jest.fn() }))+jest.mock('./TaskComposer', () => ({ TaskComposer: () => <div data-attr="task-composer" /> }))+jest.mock('./TaskRunChat', () => ({ TaskRunChat: () => <div data-attr="task-run-chat" /> }))+jest.mock('./StartupRunChat', () => ({ StartupRunChat: () => <div data-attr="startup-run-chat" /> }))+jest.mock('./TaskHistory', () => ({+ TaskHistoryList: () => <div data-attr="task-history-list" />,+ TaskHistoryPreview: () => <div data-attr="task-history-preview" />,+}))++describe('SidePanelRunnerImpl', () => {+ beforeEach(() => {+ ;(useActions as jest.Mock).mockReturnValue({+ toggleHistory: jest.fn(),+ updateActiveCreationRun: jest.fn(),+ setStartupDraft: jest.fn(),+ })+ })++ afterEach(() => {+ cleanup()+ jest.clearAllMocks()+ })++ function setValues(activeCreation: ActiveCreation | null, historyExpanded: boolean): void {+ ;(useValues as jest.Mock).mockReturnValue({ activeCreation, historyExpanded })+ }++ it('keeps a host composer on screen when the shared panel left history expanded', () => {+ // The report panel supplies its own composer and offers no way into the history list, so an+ // expanded history from the PostHog AI panel must not take the composer's place.+ setValues(null, true)++ render(<SidePanelRunnerImpl panelId="panel" composer={<div data-attr="host-composer" />} />)++ expect(screen.getByTestId('host-composer')).toBeInTheDocument()+ expect(screen.queryByTestId('task-history-list')).not.toBeInTheDocument()+ })++ it('still shows history for a host that has no composer of its own', () => {+ setValues(null, true)++ render(<SidePanelRunnerImpl panelId="panel" />)++ expect(screen.getByTestId('task-history-list')).toBeInTheDocument()+ })+})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsxindex 51a21d2bc2cc..f1a1576c6dc1 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx@@ -1,5 +1,5 @@import { BindLogic, useActions, useValues } from 'kea'-import { useRef } from 'react'+import { ReactNode, useRef } from 'react'import { IconArrowLeft } from '@posthog/icons'import { LemonButton, LemonDivider } from '@posthog/lemon-ui'@@ -16,6 +16,7 @@ import { TaskRunChat } from './TaskRunChat'export interface SidePanelRunnerImplProps {/** Embedded `taskTrackerSceneLogic` key — keeps this instance independent of the `/tasks` scene singleton. */panelId: string+ composer?: ReactNode}/**@@ -25,15 +26,15 @@ export interface SidePanelRunnerImplProps {* `TaskTrackerSceneLogicProps`) so `TaskComposer` — which reads the unbound `taskTrackerSceneLogic` — resolves* this instance instead of the scene's own singleton.*/-export function SidePanelRunnerImpl({ panelId }: SidePanelRunnerImplProps): JSX.Element {+export function SidePanelRunnerImpl({ panelId, composer }: SidePanelRunnerImplProps): JSX.Element {return (<BindLogic logic={taskTrackerSceneLogic} props={{ panelId }}>- <SidePanelRunnerContent />+ <SidePanelRunnerContent composer={composer} /></BindLogic>)}-function SidePanelRunnerContent(): JSX.Element {+function SidePanelRunnerContent({ composer }: { composer?: ReactNode }): JSX.Element {const { activeCreation, historyExpanded } = useValues(taskTrackerSceneLogic)const { toggleHistory, updateActiveCreationRun, setStartupDraft } = useActions(taskTrackerSceneLogic)const startupFocusedRef = useRef(false)@@ -49,7 +50,10 @@ function SidePanelRunnerContent(): JSX.Element {// unlike the foreground stream above, the instruction must ride the FIRST send, before a run exists.useAttachedContext([AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM])- if (!activeCreation && historyExpanded) {+ // `!composer`: a host that supplies its own composer offers no way into the history list, and the+ // panel state is shared across hosts — so an expanded history left behind by another one must not+ // take the place of that composer.+ if (!activeCreation && historyExpanded && !composer) {return (<div className="flex flex-col h-full min-h-0"><div className="flex items-center shrink-0 border-b border-primary px-2 py-1">@@ -65,6 +69,9 @@ function SidePanelRunnerContent(): JSX.Element {}if (!activeCreation) {+ if (composer) {+ return <div className="flex-1 min-h-0 overflow-y-auto">{composer}</div>+ }// Mirrors the legacy Max welcome layout: a centered composer with the recent-tasks// history pinned as a sibling at the bottom of the panel, not inside the composer column.return (diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex 2e0aef5816b0..1ba03e32d419 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -156,7 +156,12 @@ function TaskRunChatContent({disabled={readOnly}className="@container/thread flex flex-col h-full -mx-4">- <RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />+ <RunSurface.Thread+ restoreReadPosition+ className="flex-1 min-h-0"+ listClassName="py-4"+ rowClassName="px-4"+ />{/* Stay live (stream keeps flowing) but omit the composer entirely for a read-only viewer. */}{!readOnly && (<RunSurface.Composer isStopping={!!cancellationState}>diff --git a/products/posthog_ai/frontend/types/contextTypes.ts b/products/posthog_ai/frontend/types/contextTypes.tsindex 34dd8bfc11ed..23120b147822 100644--- a/products/posthog_ai/frontend/types/contextTypes.ts+++ b/products/posthog_ai/frontend/types/contextTypes.ts@@ -19,6 +19,8 @@ export interface AttachedContextItem {value?: string/** Rendered into the context blocks as usual but never shown as a composer chip (so not dismissable either). */hidden?: boolean+ /** Whether the user can dismiss the item from the composer. Defaults to true. */+ dismissible?: boolean/*** Items sharing a `dismissGroup` are dismissed together: closing any chip in the group also* detaches the group's hidden items, so a chip never claims control it doesn't have. Dismissaldiff --git a/products/signals/frontend/inbox/components/detail/DiscussReportButton.stories.tsx b/products/signals/frontend/inbox/components/detail/DiscussReportButton.stories.tsxindex 3f1d3dc6b5fe..9d788f412b4f 100644--- a/products/signals/frontend/inbox/components/detail/DiscussReportButton.stories.tsx+++ b/products/signals/frontend/inbox/components/detail/DiscussReportButton.stories.tsx@@ -1,56 +1,71 @@import type { Meta, StoryObj } from '@storybook/react'-import { waitFor, within } from '@testing-library/dom'-import userEvent from '@testing-library/user-event'+import { useValues } from 'kea'+import { Suspense } from 'react'++import { Spinner } from '@posthog/lemon-ui'++import { SidePanelMax } from '~/layout/navigation-3000/sidepanel/panels/max/SidePanelMax'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'++import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'import { makeReport } from '../../__mocks__/inboxMocks'import { DiscussReportButton } from './DiscussReportButton'+import { ReportDiscussionComposer } from './ReportDiscussionComposer'++const report = makeReport({+ title: 'Exceptions increased after a release',+ suggested_prompts: [+ 'Which pages have the most exceptions?',+ 'Did the error rate change after the release?',+ 'Add the missing null check and open a pull request',+ ],+})-const meta: Meta<typeof DiscussReportButton> = {+const meta: Meta<typeof ReportDiscussionComposer> = {title: 'Scenes-App/Inbox/DiscussReportButton',- component: DiscussReportButton,- parameters: { layout: 'centered', testOptions: { snapshotTargetSelector: '.Popover' } },+ component: ReportDiscussionComposer,+ parameters: { layout: 'centered' },+ decorators: [+ function ReportContext(Story, context): JSX.Element {+ useAttachedContext([{ type: 'signal_report', key: report.id, label: `Report: ${report.title}` }])+ return (+ <div className={context.name === 'Sidebar' ? 'w-[960px] max-w-[calc(100vw-2rem)]' : 'w-96 max-w-full'}>+ <Story />+ </div>+ )+ },+ ],+ args: { report, reportUrl: 'https://example.com/project/1/inbox/report-1' },}export default meta-type Story = StoryObj<typeof DiscussReportButton>--// The popover is closed until the trigger is pressed, so each story opens it — otherwise every-// snapshot is of the same small button and the thing under review never renders. `findByText`-// rather than `getByText`: the trigger mounts a kea logic chain reaching organization and user-// state, so on a slow runner the play function can reach an empty canvas and fail the story.-const openPopover: Story['play'] = async ({ canvasElement }) => {- await userEvent.click(await within(canvasElement).findByText('Ask AI'))- await waitFor(() => {- if (!document.querySelector('.Popover')) {- throw new Error('popover not open yet')- }- })-}+type Story = StoryObj<typeof ReportDiscussionComposer>-export const WithSuggestions: Story = {- render: () => (- <DiscussReportButton- report={makeReport({- title: 'Exceptions spiked after the 18 June deploy',- suggested_prompts: [- 'Which teams are hitting this exception the most?',- 'Did the error rate change after the 18 June deploy?',- 'Add the missing null check and open a pull request',- ],- })}- reportUrl="https://app.posthog.com/project/1/inbox/report-1"- />- ),- play: openPopover,-}+export const WithSuggestions: Story = {}-/** A pipeline report, and every report written before suggestions existed. Must look untouched. */export const WithoutSuggestions: Story = {- render: () => (- <DiscussReportButton- report={makeReport({ title: 'Exceptions spiked after the 18 June deploy' })}- reportUrl="https://app.posthog.com/project/1/inbox/report-1"- />- ),- play: openPopover,+ args: { report: { ...report, suggested_prompts: [] } },+}++export const Sidebar: Story = {+ render: function Sidebar(): JSX.Element {+ const { sidePanelOpen } = useValues(sidePanelStateLogic)+ return (+ <div className="flex h-[650px] border border-primary rounded overflow-hidden">+ <div className="flex-1 min-w-0 p-4">+ <h2>{report.title}</h2>+ <p>A null value causes an exception when a user submits the form.</p>+ <DiscussReportButton report={report} reportUrl="https://example.com/project/1/inbox/report-1" />+ </div>+ {sidePanelOpen && (+ <div className="flex flex-col w-96 min-w-0 border-l border-primary">+ <Suspense fallback={<Spinner />}>+ <SidePanelMax />+ </Suspense>+ </div>+ )}+ </div>+ )+ },}diff --git a/products/signals/frontend/inbox/components/detail/DiscussReportButton.test.tsx b/products/signals/frontend/inbox/components/detail/DiscussReportButton.test.tsxindex 54a983b775a8..47e35aa2bcf2 100644--- a/products/signals/frontend/inbox/components/detail/DiscussReportButton.test.tsx+++ b/products/signals/frontend/inbox/components/detail/DiscussReportButton.test.tsx@@ -1,14 +1,23 @@import '@testing-library/jest-dom'-import { cleanup, render, screen } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { initKeaTests } from '~/test/init'+import { SidePanelTab } from '~/types'++import { attachedContextLogic } from 'products/posthog_ai/frontend/api/logics'import { captureInboxReportAction } from '../../inboxAnalytics'-import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'+import {+ inboxTaskKickoffLogic,+ REPORT_AI_PANEL,+ REPORT_DISCUSSION_QUESTION_MAX_LENGTH,+} from '../../inboxTaskKickoffLogic'import { SignalReport, SignalReportStatus } from '../../types'import { DiscussReportButton } from './DiscussReportButton'+import { ReportDiscussionComposer } from './ReportDiscussionComposer'jest.mock('../../inboxAnalytics', () => ({...jest.requireActual('../../inboxAnalytics'),@@ -50,10 +59,15 @@ describe('DiscussReportButton', () => {jest.restoreAllMocks()})- async function openPopover(report: SignalReport): Promise<ReturnType<typeof userEvent.setup>> {+ async function openPanel(report: SignalReport): Promise<ReturnType<typeof userEvent.setup>> {const user = userEvent.setup()render(<DiscussReportButton report={report} reportUrl="https://app/report-1" />)await user.click(screen.getByText('Ask AI'))+ expect(sidePanelStateLogic.values.selectedTab).toBe(SidePanelTab.Max)+ expect(sidePanelStateLogic.values.selectedTabOptions).toBe(REPORT_AI_PANEL)+ expect(inboxTaskKickoffLogic.values.reportChatContext?.report.id).toBe(report.id)+ expect(discussReport).not.toHaveBeenCalled()+ render(<ReportDiscussionComposer report={report} reportUrl="https://app/report-1" />)return user}@@ -61,58 +75,54 @@ describe('DiscussReportButton', () => {return jest.mocked(captureInboxReportAction).mock.calls[call][0].extra?.question_source}- it('fills the textarea from a suggestion without asking AI', async () => {- // The whole point of the row: it is a starting draft, not a send button. Submitting on click- // would spend a paid Opus run on a mis-click and take away the chance to edit the question.- const user = await openPopover(makeReport([SUGGESTION]))+ it('sends a suggestion with one click from the report sidebar', async () => {+ const user = await openPanel(makeReport([SUGGESTION]))await user.click(screen.getByText(SUGGESTION))- expect(screen.getByRole('textbox')).toHaveValue(SUGGESTION)- expect(discussReport).not.toHaveBeenCalled()- expect(captureInboxReportAction).not.toHaveBeenCalled()+ expect(discussReport).toHaveBeenCalledTimes(1)+ expect(discussReport).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'report-1' }),+ 'https://app/report-1',+ SUGGESTION+ )+ expect(questionSourceOf()).toBe('suggested')+ })++ it('shows multiple report suggestions in the current suggestions menu', async () => {+ const secondSuggestion = 'Which release introduced the exception?'+ const user = await openPanel(makeReport([SUGGESTION, secondSuggestion]))++ await user.click(screen.getByText('Report suggestions'))++ expect(screen.getAllByTestId('inbox-report-ask-ai-suggestion')).toHaveLength(2)+ await user.click(screen.getByText(secondSuggestion))+ expect(discussReport).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'report-1' }),+ 'https://app/report-1',+ secondSuggestion+ )+ expect(questionSourceOf()).toBe('suggested')})it.each([[- 'sending a suggestion as written',- 'suggested',- async (user: ReturnType<typeof userEvent.setup>) => await user.click(screen.getByText(SUGGESTION)),- ],- [- 'narrowing a suggestion before sending',- 'edited_suggestion',- async (user: ReturnType<typeof userEvent.setup>) => {- await user.click(screen.getByText(SUGGESTION))- await user.type(screen.getByRole('textbox'), ' Last 7 days only.')- },- ],- [- 'emptying the box and writing another question',+ 'writing a question','typed',async (user: ReturnType<typeof userEvent.setup>) => {- await user.click(screen.getByText(SUGGESTION))- await user.clear(screen.getByRole('textbox'))await user.type(screen.getByRole('textbox'), 'Something else entirely?')},],[- 'selecting the filled box and typing over it',+ 'replacing a draft','typed',async (user: ReturnType<typeof userEvent.setup>) => {- // Select-all-and-replace never empties the box, so provenance can't be tracked from an- // intermediate value: the question that arrives keeps nothing of the suggestion.- await user.click(screen.getByText(SUGGESTION))- await user.click(screen.getByRole('textbox'))+ await user.type(screen.getByRole('textbox'), 'A first draft')await user.keyboard('{Control>}a{/Control}Something else entirely?')},],])('reports question_source after %s', async (_name, expected, act) => {- // This property is the only way to tell whether the suggestions are worth offering. Collapsing- // any of the three into another makes the readout lie about it: crediting an edited question as- // `suggested` overstates them, and crediting a cleared box as `edited_suggestion` understates- // the questions readers write for themselves.- const user = await openPopover(makeReport([SUGGESTION]))+ const user = await openPanel(makeReport([SUGGESTION]))await act(user)await user.click(screen.getByTestId('inbox-report-ask-ai-submit'))@@ -121,10 +131,91 @@ describe('DiscussReportButton', () => {expect(discussReport).toHaveBeenCalledTimes(1)})+ it('sends a typed question with Enter from the standard sidebar input', async () => {+ const user = await openPanel(makeReport())++ await user.type(screen.getByTestId('max-chat-input'), 'Who is affected?')+ await user.keyboard('{Enter}')++ expect(discussReport).toHaveBeenCalledTimes(1)+ expect(discussReport).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'report-1' }),+ 'https://app/report-1',+ 'Who is affected?'+ )+ })++ it('keeps the report context attached', async () => {+ attachedContextLogic.actions.registerContext('report', [+ {+ type: 'signal_report',+ key: 'report-1',+ label: 'Report: Exceptions spiked',+ dismissible: false,+ },+ ])+ const user = await openPanel(makeReport())++ await user.click(screen.getByText('Report: Exceptions spiked'))++ expect(attachedContextLogic.values.contextItems).toEqual([+ expect.objectContaining({ type: 'signal_report', key: 'report-1' }),+ ])+ })++ it('blocks another submission while the report task is starting', async () => {+ jest.spyOn(inboxTaskKickoffLogic.selectors, 'isCreatingPr').mockReturnValue(true)+ const user = userEvent.setup()+ render(<ReportDiscussionComposer report={makeReport([SUGGESTION])} reportUrl="https://app/report-1" />)+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Who is affected?' } })++ expect(screen.getByTestId('inbox-report-ask-ai-submit')).toHaveAttribute('aria-disabled', 'true')+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter', code: 'Enter' })+ await user.click(screen.getByText(SUGGESTION))++ expect(discussReport).not.toHaveBeenCalled()+ })++ it('sends a slash command as plain text instead of treating it as a command', async () => {+ const user = await openPanel(makeReport())++ await user.type(screen.getByTestId('max-chat-input'), '/usage')+ await user.keyboard('{Enter}')++ expect(discussReport).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'report-1' }),+ 'https://app/report-1',+ '/usage'+ )+ })++ it('does not offer slash commands it cannot run', async () => {+ await openPanel(makeReport())++ expect(screen.queryByText(/for commands/)).not.toBeInTheDocument()+ })++ it('blocks a question longer than the task API accepts', async () => {+ // The question field is capped server-side, so sending an over-long one only ever comes back+ // as a bare 400 with no task started.+ render(<ReportDiscussionComposer report={makeReport()} reportUrl="https://app/report-1" />)+ fireEvent.change(screen.getByRole('textbox'), {+ target: { value: 'x'.repeat(REPORT_DISCUSSION_QUESTION_MAX_LENGTH + 1) },+ })++ await waitFor(() =>+ expect(screen.getByTestId('inbox-report-ask-ai-submit')).toHaveAttribute('aria-disabled', 'true')+ )+ expect(screen.getByText('4,001 / 4,000')).toBeInTheDocument()+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter', code: 'Enter' })++ expect(discussReport).not.toHaveBeenCalled()+ })+it('carries the suggestion count so a typed question can be read in context', async () => {// A `typed` question on a report that offered nothing is not evidence against suggestions, so// the count is what makes the source readable.- const user = await openPopover(makeReport())+ const user = await openPanel(makeReport())await user.type(screen.getByRole('textbox'), 'Who is affected?')await user.click(screen.getByTestId('inbox-report-ask-ai-submit'))@@ -142,16 +233,16 @@ describe('DiscussReportButton', () => {{ ...makeReport([SUGGESTION]), status: SignalReportStatus.RESOLVED },],])('renders no suggestion rows for %s', async (_name, report) => {- await openPopover(report)+ await openPanel(report)- expect(screen.queryByText('Suggestions')).not.toBeInTheDocument()+ expect(screen.queryByTestId('inbox-report-ask-ai-suggestion')).not.toBeInTheDocument()})it('does not invite actions where the kickoff wrapper would only answer', async () => {// The kickoff prompt pins the agent to answering on a resolved report, so a placeholder// saying "tell AI what to do next" would promise an action the run won't carry out.- await openPopover({ ...makeReport(), status: SignalReportStatus.RESOLVED })+ await openPanel({ ...makeReport(), status: SignalReportStatus.RESOLVED })- expect(screen.getByPlaceholderText('Ask a question about this report')).toBeInTheDocument()+ expect(screen.getByText(/Ask a question/)).toBeInTheDocument()})})diff --git a/products/signals/frontend/inbox/components/detail/DiscussReportButton.tsx b/products/signals/frontend/inbox/components/detail/DiscussReportButton.tsxindex 80c6f254c825..ee237b9d886c 100644--- a/products/signals/frontend/inbox/components/detail/DiscussReportButton.tsx+++ b/products/signals/frontend/inbox/components/detail/DiscussReportButton.tsx@@ -1,180 +1,26 @@import { useActions, useValues } from 'kea'-import { useRef, useState } from 'react'import { IconSparkles } from '@posthog/icons'-import { LemonButton, lemonToast } from '@posthog/lemon-ui'+import { LemonButton } from '@posthog/lemon-ui'-import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'-import { Popover } from 'lib/lemon-ui/Popover'--import { InboxQuestionSource, captureInboxReportAction, discussQuestionProperties } from '../../inboxAnalytics'-import { inboxTaskKickoffLogic, isActionCapableReport } from '../../inboxTaskKickoffLogic'+import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'import { SignalReport } from '../../types'-// How much of a suggestion a draft has to keep, at one end or the other, to still count as an edit-// of it. Long enough that two suggestions opening on the same few words ("Which teams…", "Why did…")-// don't read as one, short enough that a heavy rewrite around a kept phrase still does.-const RECOGNIZABLE_RUN = 10--/** Whether a submitted draft is still the suggestion it was filled from, rather than a fresh question. */-function isEditOf(draft: string, suggestion: string): boolean {- if (draft.length < RECOGNIZABLE_RUN || suggestion.length < RECOGNIZABLE_RUN) {- return draft === suggestion- }- return (- draft.slice(0, RECOGNIZABLE_RUN) === suggestion.slice(0, RECOGNIZABLE_RUN) ||- draft.slice(-RECOGNIZABLE_RUN) === suggestion.slice(-RECOGNIZABLE_RUN)- )-}-export function DiscussReportButton({ report, reportUrl }: { report: SignalReport; reportUrl: string }): JSX.Element {- const { isDiscussing, aiConsentDisabledReason } = useValues(inboxTaskKickoffLogic)- const { discussReport } = useActions(inboxTaskKickoffLogic)- const buttonRef = useRef<HTMLButtonElement>(null)- const textAreaRef = useRef<HTMLTextAreaElement>(null)- const [isOpen, setIsOpen] = useState(false)- const [question, setQuestion] = useState('')- // The suggestion the textarea was last filled from, so a submitted question can be reported as- // sent as written, edited first, or written from scratch. Null until a row is clicked.- const [filledFrom, setFilledFrom] = useState<string | null>(null)-- // Suggestions can be action requests, and the kickoff wrapper only carries actions out on- // action-capable reports — on any other report a stored suggestion would invite an action the- // run then merely answers, so none are offered.- const actionCapable = isActionCapableReport(report)- const suggestions = actionCapable ? (report.suggested_prompts ?? []) : []-- const questionSource = (trimmed: string): InboxQuestionSource => {- if (filledFrom === null) {- return 'typed'- }- if (trimmed === filledFrom) {- return 'suggested'- }- // Selecting the filled box and typing over it leaves nothing of the suggestion, so the- // question is the reader's own. Counting it as an edit would read as adoption.- return isEditOf(trimmed, filledFrom) ? 'edited_suggestion' : 'typed'- }-- const fillFromSuggestion = (suggestion: string): void => {- setQuestion(suggestion)- setFilledFrom(suggestion)- // Fills the box and stops. The reader still presses Ask AI, so a mis-click costs nothing and- // a suggestion that is nearly right can be edited before it spends a run.- textAreaRef.current?.focus()- }-- const submit = (): void => {- const trimmed = question.trim()- // Cmd/Ctrl + Enter submits straight from the textarea, so it never sees the button's- // `loading`/`disabledReason` – each guard has to hold here too, or an impatient second- // press fires another paid task run for the same report.- if (!trimmed || isDiscussing) {- return- }- if (aiConsentDisabledReason) {- lemonToast.error(aiConsentDisabledReason)- return- }- captureInboxReportAction({- report,- actionType: 'discuss',- surface: 'detail_pane',- extra: discussQuestionProperties({- source: questionSource(trimmed),- suggestionCount: suggestions.length,- }),- })- // The popover stays open on its spinner until the run is created and we navigate to it, so- // the request is visibly in flight and a failure leaves the draft question to retry with.- discussReport(report, reportUrl, trimmed)- }+ const { isDiscussing, isCreatingPr, aiConsentDisabledReason } = useValues(inboxTaskKickoffLogic)+ const { openReportDiscussion } = useActions(inboxTaskKickoffLogic)return (- <Popover- visible={isOpen}- onClickOutside={(event) => {- if (event.target instanceof Node && buttonRef.current?.contains(event.target)) {- return- }- setIsOpen(false)- }}- placement="bottom-end"- overlay={- <div className="flex flex-col gap-2 p-2 w-[22rem]">- {suggestions.length > 0 && (- <div className="flex flex-col gap-1">- <span className="text-xs font-semibold text-tertiary">Suggestions</span>- {suggestions.map((suggestion) => (- <LemonButton- key={suggestion}- // Secondary, not tertiary: these sit above a textarea rather than- // in a menu, so with no border at rest they read as a bulleted- // list and the reader never learns the rows are clickable.- type="secondary"- size="small"- fullWidth- disabledReason={isDiscussing ? 'Already asking AI' : undefined}- onClick={() => fillFromSuggestion(suggestion)}- data-attr="inbox-report-suggested-prompt"- >- {suggestion}- </LemonButton>- ))}- </div>- )}- <LemonTextArea- ref={textAreaRef}- value={question}- onChange={setQuestion}- onPressCmdEnter={submit}- placeholder={- suggestions.length > 0- ? 'Pick a suggestion above, or write your own'- : // Only invite actions where the kickoff wrapper will actually carry- // them out — on other reports the agent is pinned to answering.- actionCapable- ? 'Ask a question, or tell AI what to do next'- : 'Ask a question about this report'- }- maxLength={4000}- rows={4}- // Focusing the textarea scrolls it into view, which on a short viewport pushes- // the suggestions above the popover's visible area — so a report that offers- // questions opens on the questions, and one that doesn't opens ready to type.- autoFocus={suggestions.length === 0}- rightFooter={<span className="text-xs text-tertiary">Cmd/Ctrl + Enter to ask AI</span>}- />- <div className="flex justify-end">- <LemonButton- type="primary"- size="small"- onClick={submit}- loading={isDiscussing}- disabledReason={- aiConsentDisabledReason ?? (question.trim() ? undefined : 'Enter a question first')- }- data-attr="inbox-report-ask-ai-submit"- >- Ask AI- </LemonButton>- </div>- </div>- }+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconSparkles />}+ loading={isDiscussing}+ disabledReason={aiConsentDisabledReason ?? (isCreatingPr ? 'An implementation is starting.' : undefined)}+ onClick={() => openReportDiscussion(report, reportUrl)}+ tooltip="Ask PostHog AI about this report in the sidebar">- <LemonButton- ref={buttonRef}- type="secondary"- size="small"- icon={<IconSparkles />}- sideIcon={null}- active={isOpen}- loading={isDiscussing}- onClick={() => setIsOpen((open) => !open)}- tooltip="Ask AI about this report"- >- Ask AI- </LemonButton>- </Popover>+ Ask AI+ </LemonButton>)}diff --git a/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsx b/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsxindex bcbdf5534ea2..75786a18a8ed 100644--- a/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsx+++ b/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsx@@ -2,13 +2,19 @@ import '@testing-library/jest-dom'import { cleanup, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { expectLogic } from 'kea-test-utils'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { initKeaTests } from '~/test/init'+import { runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'+import { TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'++import { mockTask } from '../../__mocks__/inboxMocks'import { captureInboxReportAction } from '../../inboxAnalytics'-import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'+import { inboxTaskKickoffLogic, REPORT_AI_PANEL_ID } from '../../inboxTaskKickoffLogic'+import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'import { SignalReport, SignalReportStatus } from '../../types'import { ImplementButton } from './ImplementButton'@@ -72,6 +78,32 @@ describe('ImplementButton', () => {expect(jest.mocked(captureInboxReportAction).mock.calls[0][0].extra).toEqual({ has_feedback: false })})+ it.each([TaskRunStatus.QUEUED, TaskRunStatus.IN_PROGRESS])(+ 'opens the existing %s task instead of starting another',+ async (status) => {+ const user = userEvent.setup()+ const report = makeReport()+ const detail = inboxReportDetailLogic({ reportId: report.id, report })+ detail.mount()+ await expectLogic(detail).toFinishAllListeners()+ const task = mockTask('implementation-task', status)+ detail.actions.loadReportTasksSuccess([+ { task, purpose: 'implementation', purposeLabel: 'Implementation', startedAt: task.created_at },+ ])+ render(<ImplementButton report={report} />)++ expect(screen.queryByTestId('inbox-report-create-pr')).not.toBeInTheDocument()+ await user.click(screen.getByTestId('inbox-report-open-task'))++ expect(createPrFromReport).not.toHaveBeenCalled()+ expect(runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID }).values.activeCreation).toMatchObject({+ taskId: task.id,+ runId: task.latest_run.id,+ })+ detail.unmount()+ }+ )+it('opens both implementation options without starting work', async () => {await openMenu()diff --git a/products/signals/frontend/inbox/components/detail/ImplementButton.tsx b/products/signals/frontend/inbox/components/detail/ImplementButton.tsxindex 09af8df15f96..94df3d2f2ba7 100644--- a/products/signals/frontend/inbox/components/detail/ImplementButton.tsx+++ b/products/signals/frontend/inbox/components/detail/ImplementButton.tsx@@ -21,18 +21,21 @@ const SLOT_CLAIM_DISABLED_REASON: Record<ImplementationSlotClaim, string> = {}export function ImplementButton({ report }: { report: SignalReport }): JSX.Element {- const { isCreatingPr, createPrDisabledReason } = useValues(inboxTaskKickoffLogic)- const { implementationSlotClaim } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))- const { createPrFromReport } = useActions(inboxTaskKickoffLogic)+ const { isCreatingPr, isDiscussing, createPrDisabledReason } = useValues(inboxTaskKickoffLogic)+ const { implementationSlotClaim, reportTaskToOpen } = useValues(+ inboxReportDetailLogic({ reportId: report.id, report })+ )+ const { createPrFromReport, openReportTask } = useActions(inboxTaskKickoffLogic)const [instructions, setInstructions] = useState('')const reportUrl = `${window.location.origin}${addProjectIdIfMissing(urls.inboxReport('reports', report.id))}`const disabledReason =createPrDisabledReason ??+ (isDiscussing ? 'Wait for the discussion task to start.' : undefined) ??(implementationSlotClaim ? SLOT_CLAIM_DISABLED_REASON[implementationSlotClaim] : undefined)const submit = (note: string): void => {- if (isCreatingPr || implementationSlotClaim) {+ if (isCreatingPr || isDiscussing || implementationSlotClaim) {return}if (createPrDisabledReason) {@@ -63,6 +66,26 @@ export function ImplementButton({ report }: { report: SignalReport }): JSX.Eleme}}+ if (reportTaskToOpen?.task.latest_run) {+ const task = reportTaskToOpen.task+ const run = task.latest_run!+ return (+ <LemonButton+ type="primary"+ size="small"+ to={urls.taskDetail(task.id)}+ onClick={(event) => {+ event.preventDefault()+ openReportTask(report, task.id, run.id)+ }}+ tooltip="Open this task in the PostHog AI sidebar"+ data-attr="inbox-report-open-task"+ >+ View task+ </LemonButton>+ )+ }+return (<LemonButtontype="primary"diff --git a/products/signals/frontend/inbox/components/detail/ReportAiPanel.test.tsx b/products/signals/frontend/inbox/components/detail/ReportAiPanel.test.tsxnew file mode 100644index 000000000000..9effb819212f--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportAiPanel.test.tsx@@ -0,0 +1,51 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { initKeaTests } from '~/test/init'++import { makeReport } from '../../__mocks__/inboxMocks'+import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'+import { ReportAiPanel } from './ReportAiPanel'++jest.mock('./ReportDiscussionComposer', () => ({+ ReportDiscussionComposer: () => <div data-attr="report-composer" />,+}))+// Mirrors the runner's own fallback: with no composer supplied it renders the generic task composer.+jest.mock('products/posthog_ai/frontend/api/runner', () => ({+ SidePanelRunner: ({ composer }: { composer?: React.ReactNode }) => (+ <div>{composer ?? <div data-attr="generic-task-composer" />}</div>+ ),+}))++describe('ReportAiPanel', () => {+ let logic: ReturnType<typeof inboxTaskKickoffLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = inboxTaskKickoffLogic()+ logic.mount()+ })++ afterEach(() => {+ cleanup()+ logic.unmount()+ })++ it('offers a way back instead of the generic composer when the report is gone', () => {+ // A reload keeps the `inbox-report` panel option in the URL but not the report it was about.+ render(<ReportAiPanel panelId="panel" />)++ expect(screen.getByText('No report selected')).toBeInTheDocument()+ expect(screen.queryByTestId('generic-task-composer')).not.toBeInTheDocument()+ })++ it('shows the report composer once a report is open', () => {+ logic.actions.openReportDiscussion(makeReport({ id: 'report-1' }), 'https://app/report-1')++ render(<ReportAiPanel panelId="panel" />)++ expect(screen.getByTestId('report-composer')).toBeInTheDocument()+ expect(screen.queryByText('No report selected')).not.toBeInTheDocument()+ })+})diff --git a/products/signals/frontend/inbox/components/detail/ReportAiPanel.tsx b/products/signals/frontend/inbox/components/detail/ReportAiPanel.tsxnew file mode 100644index 000000000000..7e3b1db903f5--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportAiPanel.tsx@@ -0,0 +1,49 @@+import { useValues } from 'kea'++import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'++import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { SidePanelRunner } from 'products/posthog_ai/frontend/api/runner'++import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'+import { ReportDiscussionComposer } from './ReportDiscussionComposer'++export function ReportAiPanel({ panelId }: { panelId: string }): JSX.Element {+ const { reportChatContext } = useValues(inboxTaskKickoffLogic)+ const report = reportChatContext?.report+ useAttachedContext(+ report+ ? [+ {+ type: 'signal_report',+ key: report.id,+ label: `Report: ${report.title || 'Untitled report'}`,+ dismissible: false,+ },+ ]+ : null+ )++ return (+ <div className="flex flex-col flex-1 min-h-0 min-w-0">+ <SidePanelRunner+ panelId={panelId}+ composer={+ reportChatContext ? (+ <ReportDiscussionComposer key={reportChatContext.report.id} {...reportChatContext} />+ ) : (+ // `reportChatContext` is in-memory, but the `inbox-report` panel option round-trips+ // through the URL hash, so a reload lands here knowing the panel is a report chat but+ // not which report. Always filling the composer slot is what keeps the runner's+ // generic task composer out: a send from that would spend a run on a question the+ // agent cannot tie to any report.+ <EmptyMessage+ title="No report selected"+ description="Reloading the page clears which report this chat was about. Select Ask AI on the report to start a new chat."+ />+ )+ }+ />+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx b/products/signals/frontend/inbox/components/detail/ReportDetail.tsxindex 072458cbb97a..84ab80289732 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetail.tsx@@ -224,6 +224,7 @@ export function InboxDetailFrame({chartPlacements,trailingCharts,detailTab,+ reportTaskToOpen,} = useValues(inboxReportDetailLogic(logicProps))const { setDetailTab, expandEvidence, collapseEvidence } = useActions(inboxReportDetailLogic(logicProps))const { evidenceRailCollapsed } = useValues(inboxDetailLayoutLogic)@@ -256,7 +257,7 @@ export function InboxDetailFrame({const reportActions = useReportDetailActions(report)const showCreatePr = canCreateImplementationPr(report)- const implementButton = showCreatePr ? <ImplementButton report={report} /> : null+ const implementButton = showCreatePr || reportTaskToOpen ? <ImplementButton report={report} /> : nullconst summaryHasSolution = parseReportSummary(report.summary).sections.some((section) => section.kind === 'solution')diff --git a/products/signals/frontend/inbox/components/detail/ReportDiscussionComposer.tsx b/products/signals/frontend/inbox/components/detail/ReportDiscussionComposer.tsxnew file mode 100644index 000000000000..a443516a694f--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportDiscussionComposer.tsx@@ -0,0 +1,145 @@+import { useActions, useValues } from 'kea'+import { useMemo, useRef, useState } from 'react'++import { IconSparkles } from '@posthog/icons'++import { cn } from 'lib/utils/css-classes'++import {+ AttachedContextBar,+ Composer,+ pickHeadline,+ type SuggestionGroup,+ type SuggestionItem,+ Suggestions,+ Welcome,+} from 'products/posthog_ai/frontend/api/primitives'++import { captureInboxReportAction, discussQuestionProperties } from '../../inboxAnalytics'+import {+ inboxTaskKickoffLogic,+ isActionCapableReport,+ REPORT_DISCUSSION_QUESTION_MAX_LENGTH,+} from '../../inboxTaskKickoffLogic'+import type { SignalReport } from '../../types'++export function ReportDiscussionComposer({+ report,+ reportUrl,+}: {+ report: SignalReport+ reportUrl: string+}): JSX.Element {+ const { isDiscussing, isCreatingPr, aiConsentDisabledReason } = useValues(inboxTaskKickoffLogic)+ const { discussReport } = useActions(inboxTaskKickoffLogic)+ const textAreaRef = useRef<HTMLTextAreaElement>(null)+ const [draft, setDraft] = useState('')+ const [activeSuggestionGroup, setActiveSuggestionGroup] = useState<SuggestionGroup | null>(null)+ const [headline] = useState(() => pickHeadline())+ const suggestions = isActionCapableReport(report) ? (report.suggested_prompts ?? []) : []+ const loading = isDiscussing || isCreatingPr+ const promptLength = useMemo(+ () => (draft.length >= REPORT_DISCUSSION_QUESTION_MAX_LENGTH * 0.9 ? Array.from(draft.trim()).length : null),+ [draft]+ )+ const isOverLengthLimit = promptLength !== null && promptLength > REPORT_DISCUSSION_QUESTION_MAX_LENGTH+ const suggestionGroups = useMemo<SuggestionGroup[]>(+ () =>+ suggestions.length > 0+ ? [+ {+ label: suggestions.length === 1 ? suggestions[0] : 'Report suggestions',+ icon: <IconSparkles />,+ suggestions: suggestions.map((content) => ({+ content,+ dataAttr: 'inbox-report-ask-ai-suggestion',+ })),+ },+ ]+ : [],+ [suggestions]+ )+ const disabledReason = isOverLengthLimit+ ? `Your message is too long. Shorten it to ${REPORT_DISCUSSION_QUESTION_MAX_LENGTH.toLocaleString()} characters or fewer.`+ : (aiConsentDisabledReason ?? undefined)++ const submit = (prompt: string, source: 'typed' | 'suggested'): void => {+ const trimmed = prompt.trim()+ if (+ !trimmed ||+ loading ||+ aiConsentDisabledReason ||+ Array.from(trimmed).length > REPORT_DISCUSSION_QUESTION_MAX_LENGTH+ ) {+ return+ }+ captureInboxReportAction({+ report,+ actionType: 'discuss',+ surface: 'detail_pane',+ extra: discussQuestionProperties({ source, suggestionCount: suggestions.length }),+ })+ discussReport(report, reportUrl, trimmed)+ }++ const selectSuggestion = (suggestion: SuggestionItem): void => {+ submit(suggestion.content, 'suggested')+ }++ return (+ <div className="flex flex-col h-full min-h-0 items-center justify-center overflow-y-auto p-4">+ <div className="w-full max-w-2xl flex flex-col items-center gap-4">+ <Welcome headline={headline} />+ <Suggestions.Root+ activeGroup={activeSuggestionGroup}+ onActiveGroupChange={setActiveSuggestionGroup}+ onSelectSuggestion={selectSuggestion}+ disabled={loading || !!aiConsentDisabledReason}+ disabledReason={aiConsentDisabledReason ?? (loading ? 'Wait for the task to start.' : undefined)}+ >+ <Composer.Root+ value={draft}+ onChange={setDraft}+ onSubmit={() => submit(draft, 'typed')}+ loading={loading}+ disabled={loading}+ disabledReason={disabledReason}+ textAreaRef={textAreaRef}+ >+ <Composer.Frame>+ <Composer.Header>+ <AttachedContextBar />+ </Composer.Header>+ <Composer.Field>+ <Composer.Placeholder>Ask a question</Composer.Placeholder>+ <Composer.Textarea autoFocus data-attr="max-chat-input" />+ </Composer.Field>+ {promptLength !== null && (+ <Composer.Footer>+ <div+ className={cn(+ 'text-xs text-right pr-1',+ isOverLengthLimit ? 'text-error' : 'text-secondary'+ )}+ >+ {promptLength.toLocaleString()} /{' '}+ {REPORT_DISCUSSION_QUESTION_MAX_LENGTH.toLocaleString()}+ </div>+ </Composer.Footer>+ )}+ </Composer.Frame>+ <Suggestions.Dropdown />+ <Composer.Submit data-attr="inbox-report-ask-ai-submit" />+ </Composer.Root>+ {suggestionGroups.length > 0 && (+ <Suggestions.Buttons+ data={suggestionGroups}+ tip="Suggested questions and actions"+ className="w-full"+ />+ )}+ </Suggestions.Root>+ </div>+ </div>+ )+}diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.tsindex 9e669b4390ac..ed31081e93a9 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts@@ -1,11 +1,21 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'+import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { SidePanelTab } from '~/types'++import { attachedContextLogic, runnerPanelLogic, runStreamLogic } from 'products/posthog_ai/frontend/api/logics'import { makeReport } from './__mocks__/inboxMocks'import {FREE_TRIAL_PR_DISABLED_REASON,+ REPORT_AI_PANEL,+ REPORT_AI_PANEL_ID,buildCreatePrReportPrompt,buildDiscussReportPrompt,inboxTaskKickoffLogic,@@ -13,6 +23,181 @@ import {import { SignalReportStatus } from './types'describe('inboxTaskKickoffLogic', () => {+ describe('report sidebar', () => {+ let logic: ReturnType<typeof inboxTaskKickoffLogic.build>+ let createdTasks: Record<string, unknown>[]+ let startedRuns: Record<string, unknown>[]+ // Runs while the kickoff awaits its run response, so a test can act as the reader does mid-flight.+ let onRunRequest: (() => void) | null+ const report = makeReport({ id: 'report-sidebar', status: SignalReportStatus.READY })++ beforeEach(() => {+ localStorage.clear()+ createdTasks = []+ startedRuns = []+ onRunRequest = null+ useMocks({+ get: {+ '/api/projects/:team/signals/reports/:id/': report,+ },+ post: {+ '/api/projects/:team/tasks/': async ({ request }) => {+ createdTasks.push((await request.json()) as Record<string, unknown>)+ return [201, { id: 'report-task' }]+ },+ '/api/projects/:team/tasks/:id/run/': async ({ request }) => {+ startedRuns.push((await request.json()) as Record<string, unknown>)+ onRunRequest?.()+ return [200, { id: 'report-task', latest_run: { id: 'report-run' } }]+ },+ },+ })+ initKeaTests()+ logic = inboxTaskKickoffLogic()+ logic.mount()+ })++ afterEach(() => logic.unmount())++ it.each(['implementation', 'discussion'] as const)(+ 'opens one %s run without leaving the report',+ async (relationship) => {+ const originalPath = router.values.location.pathname+ if (relationship === 'discussion') {+ attachedContextLogic.actions.registerContext('test-picker', [+ { type: 'insight', key: 'insight-one', label: 'Conversion rate' },+ ])+ }+ await expectLogic(logic, () => {+ if (relationship === 'implementation') {+ logic.actions.createPrFromReport(report)+ } else {+ logic.actions.discussReport(report, 'https://example.com/report', 'Explain the recommendation')+ }+ }).toFinishAllListeners()++ expect(createdTasks).toHaveLength(1)+ expect(createdTasks[0]).toMatchObject({+ signal_report: report.id,+ signal_report_task_relationship: relationship,+ })+ expect(startedRuns).toHaveLength(1)+ expect(startedRuns[0]).toMatchObject({+ signal_report_id: report.id,+ mode: 'interactive',+ pending_user_message: expect.any(String),+ })+ if (relationship === 'discussion') {+ expect(createdTasks[0]).toMatchObject({+ description: expect.stringContaining('- insight insight-one ("Conversion rate")'),+ signal_report_discussion_question: 'Explain the recommendation',+ })+ expect(startedRuns[0].pending_user_message).toBe(createdTasks[0].description)+ expect(attachedContextLogic.values.sentContextKeysByTask['report-task']).toContain(+ 'insight:insight-one'+ )+ }+ expect(router.values.location.pathname).toBe(originalPath)+ expect(sidePanelStateLogic.values.selectedTab).toBe(SidePanelTab.Max)+ expect(sidePanelStateLogic.values.selectedTabOptions).toBe(REPORT_AI_PANEL)+ const activeCreation = runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID }).values.activeCreation+ expect(activeCreation).toMatchObject({+ taskId: 'report-task',+ runId: 'report-run',+ })+ expect(activeCreation?.streamKey).not.toBe('report-run')+ const stream = runStreamLogic({ streamKey: activeCreation!.streamKey })+ const unmountStream = stream.mount()+ expect(stream.values.awaitingOptimisticAttach).toBe(true)+ expect(stream.values.hasThreadItems).toBe(relationship === 'discussion')+ unmountStream()+ expect(logic.values.reportChatContext?.report.id).toBe(report.id)++ logic.actions.openReportTask(report, 'report-task', 'report-run')+ expect(createdTasks).toHaveLength(1)+ expect(startedRuns).toHaveLength(1)+ }+ )++ it('shows implementation provisioning before the run request finishes and attaches the result in place', async () => {+ let optimisticStreamKey: string | undefined+ onRunRequest = () => {+ const activeCreation = runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID }).values.activeCreation+ expect(activeCreation?.taskId).toBeUndefined()+ expect(activeCreation?.runId).toBeUndefined()+ optimisticStreamKey = activeCreation?.streamKey+ expect(optimisticStreamKey).toMatch(/^report-implementation-/)++ const stream = runStreamLogic({ streamKey: optimisticStreamKey! })+ expect(stream.values.awaitingOptimisticAttach).toBe(true)+ expect(stream.values.streamPhase).toBe('provisioning')+ expect(sidePanelStateLogic.values.selectedTab).toBe(SidePanelTab.Max)+ expect(sidePanelStateLogic.values.selectedTabOptions).toBe(REPORT_AI_PANEL)+ }++ await expectLogic(logic, () => logic.actions.createPrFromReport(report)).toFinishAllListeners()++ expect(optimisticStreamKey).not.toBeUndefined()+ expect(runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID }).values.activeCreation).toEqual({+ streamKey: optimisticStreamKey,+ taskId: 'report-task',+ runId: 'report-run',+ })+ })++ it('keeps the optimistic stream when View task opens the run already shown in the panel', () => {+ const panel = runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID })+ panel.actions.setActiveCreation({+ streamKey: 'report-implementation-stream',+ taskId: 'report-task',+ runId: 'report-run',+ })++ logic.actions.openReportTask(report, 'report-task', 'report-run')++ expect(panel.values.activeCreation).toEqual({+ streamKey: 'report-implementation-stream',+ taskId: 'report-task',+ runId: 'report-run',+ })+ })++ it.each(['implementation', 'discussion'] as const)(+ 'leaves a newer pick in the sidebar when the %s kickoff lands after it',+ async (relationship) => {+ const otherReport = makeReport({ id: 'report-other', status: SignalReportStatus.READY })+ onRunRequest = () => logic.actions.openReportTask(otherReport, 'other-task', 'other-run')++ await expectLogic(logic, () => {+ if (relationship === 'implementation') {+ logic.actions.createPrFromReport(report)+ } else {+ logic.actions.discussReport(report, 'https://example.com/report', 'Explain the recommendation')+ }+ }).toFinishAllListeners()++ expect(startedRuns).toHaveLength(1)+ expect(runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID }).values.activeCreation).toMatchObject({+ taskId: 'other-task',+ runId: 'other-run',+ })+ expect(logic.values.reportChatContext?.report.id).toBe(otherReport.id)+ }+ )++ it('sends Back to the report composer even when the shared panel left history open', () => {+ const panel = runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID })+ // The PostHog AI side panel shares this panel state, so its history can already be open.+ panel.actions.setHistoryExpanded(true)++ logic.actions.openReportTask(report, 'report-task', 'report-run')+ panel.actions.goBack()++ expect(panel.values.historyExpanded).toBe(false)+ expect(panel.values.activeCreation).toBeNull()+ })+ })+describe('freeTrialDisabledReason', () => {let logic: ReturnType<typeof inboxTaskKickoffLogic.build>diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.tsindex a35470b06a98..be80ed63c94d 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts@@ -1,5 +1,4 @@import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'-import { router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'@@ -7,10 +6,25 @@ import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { uuid } from 'lib/utils/dom'+import { addProjectIdIfMissing } from 'lib/utils/kea-router'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { urls } from 'scenes/urls'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'+import { SidePanelTab } from '~/types'++import {+ attachedContextItemKey,+ attachedContextLogic,+ runnerPanelLogic,+ runStreamLogic,+ wrapWithPosthogContext,+} from 'products/posthog_ai/frontend/api/logics'+import type { ActiveCreation } from 'products/posthog_ai/frontend/api/logics'+import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'import { OriginProduct } from 'products/posthog_ai/frontend/types/taskTypes'+import type { Task, TaskRun } from 'products/posthog_ai/frontend/types/taskTypes'import {ClaudeRuntimeAdapterEnumApi,ClaudeTaskRunCreateSchemaApi,@@ -30,10 +44,15 @@ import {import { aiConsentDisabledReason } from './utils/aiConsent'import { reportPullRequests } from './utils/reportPullRequests'-// Cloud-adapted port of desktop `useDiscussReport` / `useCreatePrReport`. These are-// task-kickoff actions (create a cloud Task linked to the report, then navigate to it) –-// NOT a live chat surface. The created task carries the SignalReport linkage so the-// backend's agent pipeline can pick it up.+export const REPORT_AI_PANEL = 'inbox-report'+export const REPORT_AI_PANEL_ID = 'max-side-panel'++const OPTIMISTIC_REPORT_STREAM = 'optimistic-report-stream'++export interface ReportChatContext {+ report: SignalReport+ reportUrl: string+}// Mirrors the server's `FREE_TRIAL_PR_MESSAGE`, so the disabled button and a refused call read the same.export const FREE_TRIAL_PR_DISABLED_REASON =@@ -182,6 +201,11 @@ function handleKickoffError(captureInboxReportActionCompleted({ report, actionType, outcome: 'failure' })}+// Mirrors `signal_report_discussion_question`'s `max_length` in the tasks `TaskCreateSerializer`+// (`@maxLength 4000` in the generated tasks schema); keep the two in sync. Over it, task creation+// comes back as a 400 on a field the reader never sees named.+export const REPORT_DISCUSSION_QUESTION_MAX_LENGTH = 4000+async function createReportTask(report: SignalReport,relationship: SignalReportTaskRelationship,@@ -189,7 +213,7 @@ async function createReportTask(fallbackTitle: string,runtimeSelection?: ClaudeRuntimeSelection,discussionQuestion?: string-): Promise<void> {+): Promise<{ task: Task; run: TaskRun }> {// `repository` is intentionally omitted: the backend resolves it for signal_report tasks.const task = await api.tasks.create({title: report.title?.trim() || fallbackTitle,@@ -208,7 +232,7 @@ async function createReportTask(const runOptions = {run_source: RunSourceEnumApi.SignalReport,signal_report_id: report.id,- // Interactive, not the default background: the user lands on the run page right away, and the+ // Interactive, not the default background: the user follows the run in the sidebar, and the// agent-server only relays AskUserQuestion (and other approval prompts) to the client on// non-background runs — a background run's questions are parked and never rendered as a form.mode: TaskExecutionModeEnumApi.Interactive,@@ -217,25 +241,68 @@ async function createReportTask(// ACP runtime, so without this the sandbox boots with no first turn and the run just idles.pending_user_message: prompt,}- await api.tasks.run(task.id, runtimeSelection ? { ...runOptions, ...runtimeSelection } : runOptions)+ const runningTask = await api.tasks.run(+ task.id,+ runtimeSelection ? { ...runOptions, ...runtimeSelection } : runOptions+ )+ if (!runningTask.latest_run) {+ throw new Error('The task has no run. Open the task list to check its status.')+ }+ return { task: runningTask, run: runningTask.latest_run }+}- router.actions.push(urls.taskDetail(task.id))+/**+ * Whether the AI panel is still about this report, so a finished kickoff may open its task.+ *+ * Creating the task and starting its run take two round trips, so the reader can open another+ * report's run while this one is in flight. The panel state is shared, so opening unconditionally+ * would pull the sidebar off that newer pick. The run starts either way and remains in the report's+ * Runs section.+ */+function panelStillOnReport(context: ReportChatContext | null, reportId: string): boolean {+ return !context || context.report.id === reportId}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxTaskKickoffLogicValues {dataProcessingAccepted: boolean // aiConsentLogicdataProcessingApprovalDisabledReason: string | null // aiConsentLogic+ contextItems: AttachedContextItem[] // attachedContextLogicfeatureFlags: FeatureFlagsSet // featureFlagLogic+ activeCreation: ActiveCreation | null // runnerPanelLogicaiConsentDisabledReason: string | nullcreatePrDisabledReason: string | nullfreeTrialDisabledReason: string | nullisCreatingPr: booleanisDiscussing: boolean+ reportChatContext: ReportChatContext | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxTaskKickoffLogicActions {+ markContextSent: (+ taskId: string,+ keys: string[]+ ) => {+ keys: string[]+ taskId: string+ } // attachedContextLogic+ clearActiveCreation: () => {+ value: true+ } // runnerPanelLogic+ setActiveCreation: (creation: ActiveCreation) => {+ creation: ActiveCreation+ } // runnerPanelLogic+ setHistoryExpanded: (expanded: boolean) => {+ expanded: boolean+ } // runnerPanelLogic+ openSidePanel: (+ tab: SidePanelTab,+ options?: string | undefined+ ) => {+ options: string | undefined+ tab: SidePanelTab+ } // sidePanelStateLogiccreatePrFailure: () => {value: true}@@ -264,6 +331,24 @@ export interface inboxTaskKickoffLogicActions {discussReportSuccess: () => {value: true}+ openReportDiscussion: (+ report: SignalReport,+ reportUrl: string+ ) => {+ report: SignalReport+ reportUrl: string+ }+ openReportTask: (+ report: SignalReport,+ taskId: string,+ runId: string,+ streamKey?: string+ ) => {+ report: SignalReport+ runId: string+ streamKey: string | undefined+ taskId: string+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -291,16 +376,36 @@ export type inboxTaskKickoffLogicType = MakeLogicType<export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([path(['scenes', 'inbox', 'inboxTaskKickoffLogic']),- connect({+ // Lazy, so the keyed `runnerPanelLogic` is built when this logic mounts, not when the module loads.+ connect(() => ({+ actions: [+ attachedContextLogic,+ ['markContextSent'],+ runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID }),+ ['setActiveCreation', 'clearActiveCreation', 'setHistoryExpanded'],+ sidePanelStateLogic,+ ['openSidePanel'],+ ],values: [+ attachedContextLogic,+ ['contextItems'],+ runnerPanelLogic({ panelId: REPORT_AI_PANEL_ID }),+ ['activeCreation'],aiConsentLogic,['dataProcessingAccepted', 'dataProcessingApprovalDisabledReason'],featureFlagLogic,['featureFlags'],],- }),+ })),actions({+ openReportDiscussion: (report: SignalReport, reportUrl: string) => ({ report, reportUrl }),+ openReportTask: (report: SignalReport, taskId: string, runId: string, streamKey?: string) => ({+ report,+ taskId,+ runId,+ streamKey,+ }),discussReport: (report: SignalReport, reportUrl: string, question: string) => ({ report, reportUrl, question }),createPrFromReport: (report: SignalReport, feedback?: string) => ({ report, feedback }),discussReportSuccess: true,@@ -310,6 +415,16 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([}),reducers({+ reportChatContext: [+ null as ReportChatContext | null,+ {+ openReportDiscussion: (_, { report, reportUrl }) => ({ report, reportUrl }),+ openReportTask: (_, { report }) => ({+ report,+ reportUrl: `${window.location.origin}${addProjectIdIfMissing(urls.inboxReport('reports', report.id))}`,+ }),+ },+ ],isDiscussing: [false,{@@ -350,7 +465,30 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, cache, values }) => ({+ openReportDiscussion: () => {+ cache.disposables.dispose(OPTIMISTIC_REPORT_STREAM)+ actions.clearActiveCreation()+ actions.setHistoryExpanded(false)+ actions.openSidePanel(SidePanelTab.Max, REPORT_AI_PANEL)+ },+ openReportTask: ({ taskId, runId, streamKey }) => {+ const currentStreamKey =+ values.activeCreation?.taskId === taskId && values.activeCreation.runId === runId+ ? values.activeCreation.streamKey+ : undefined+ const resolvedStreamKey = streamKey ?? currentStreamKey+ if (!resolvedStreamKey) {+ cache.disposables.dispose(OPTIMISTIC_REPORT_STREAM)+ }+ // The panel is shared with the PostHog AI side panel, where the task history can be left+ // expanded. Collapse it first, like the discussion entry point does: `setActiveCreation`+ // would otherwise record the run as opened from history, and Back would land on the+ // generic task list instead of this report's composer.+ actions.setHistoryExpanded(false)+ actions.setActiveCreation({ streamKey: resolvedStreamKey ?? runId, taskId, runId })+ actions.openSidePanel(SidePanelTab.Max, REPORT_AI_PANEL)+ },discussReport: async ({ report, reportUrl, question }) => {// The CTAs carry this as a `disabledReason`, but Discuss also submits on Enter, and the// run endpoint enforces no consent of its own.@@ -365,7 +503,8 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([actions.discussReportFailure()return}- // The popover renders from a snapshot that can go stale between load and submit (the+ const contextItems = values.contextItems+ // The composer renders from a snapshot that can go stale between load and submit (the// report resolves, fails, or gets suppressed meanwhile), so the action-vs-answer framing// is derived from the report's current server-side state. A failed refetch fails closed:// `null` pins the run to answering.@@ -383,14 +522,31 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([lemonToast.info('This report can no longer take actions, so AI will answer instead.')}try {- await createReportTask(+ const prompt = wrapWithPosthogContext(+ buildDiscussReportPrompt(currentReport, reportUrl, question),+ contextItems+ )+ const { task, run } = await createReportTask(report,SIGNAL_REPORT_TASK_DISCUSSION_RELATIONSHIP,- buildDiscussReportPrompt(currentReport, reportUrl, question),+ prompt,'Ask AI about report',DISCUSS_RUNTIME,question)+ const sentContextKeys = contextItems.filter((item) => item.type !== 'text').map(attachedContextItemKey)+ if (sentContextKeys.length > 0) {+ actions.markContextSent(task.id, sentContextKeys)+ }+ if (panelStillOnReport(values.reportChatContext, report.id)) {+ const streamKey = `report-discussion-${uuid()}`+ const stream = runStreamLogic({ streamKey })+ cache.disposables.add(() => stream.mount(), OPTIMISTIC_REPORT_STREAM, {+ pauseOnPageHidden: false,+ })+ stream.actions.startOptimisticRun(question)+ actions.openReportTask(report, task.id, run.id, streamKey)+ }captureInboxReportActionCompleted({ report, actionType: 'discuss', outcome: 'success' })actions.discussReportSuccess()} catch (error: any) {@@ -410,17 +566,40 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([actions.createPrFailure()return}+ actions.openReportDiscussion(+ report,+ `${window.location.origin}${addProjectIdIfMissing(urls.inboxReport('reports', report.id))}`+ )+ const streamKey = `report-implementation-${uuid()}`+ const stream = runStreamLogic({ streamKey })+ const disposables = cache.disposables+ disposables.add(() => stream.mount(), OPTIMISTIC_REPORT_STREAM, { pauseOnPageHidden: false })+ stream.actions.startOptimisticRun()+ actions.setActiveCreation({ streamKey })try {- await createReportTask(+ const { task, run } = await createReportTask(report,SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP,buildCreatePrReportPrompt(report, feedback),'Implement report fix',CREATE_PR_RUNTIME)+ if (disposables.isDisposed) {+ return+ }+ if (panelStillOnReport(values.reportChatContext, report.id)) {+ actions.openReportTask(report, task.id, run.id, streamKey)+ }captureInboxReportActionCompleted({ report, actionType: 'create_pr', outcome: 'success' })actions.createPrSuccess()} catch (error: any) {+ if (disposables.isDisposed) {+ return+ }+ if (values.activeCreation?.streamKey === streamKey) {+ disposables.dispose(OPTIMISTIC_REPORT_STREAM)+ actions.clearActiveCreation()+ }handleKickoffError(error, report, 'create_pr', "Couldn't start the PR task. Try again.")actions.createPrFailure()}diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.tsindex b945499aee0e..7636230f3eb8 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts@@ -395,38 +395,72 @@ describe('inboxReportDetailLogic', () => {logic.unmount()})- // `ready` is not one of the active statuses, so the report's own status never starts the poll.- // An implementation run under it still settles, and a failed or cancelled one hands the Create PR- // slot back, so the run has to hold the poll open by itself or the action stays disabled until the- // pane is reopened. A completed run must not hold it open: it keeps the slot for good, and polling- // past it would never observe a change.it.each([- { label: 'no linked tasks', tasks: [], polls: false },- { label: 'an implementation with no run yet', tasks: [linkedTask('implementation', null)], polls: true },+ { label: 'no linked tasks', tasks: [], polls: false, openTaskIndex: null },+ {+ label: 'an implementation with no run yet',+ tasks: [linkedTask('implementation', null)],+ polls: true,+ openTaskIndex: null,+ },{label: 'an implementation in progress',tasks: [linkedTask('implementation', TaskRunStatus.IN_PROGRESS)],polls: true,+ openTaskIndex: 0,},{label: 'a completed implementation',tasks: [linkedTask('implementation', TaskRunStatus.COMPLETED)],polls: false,+ openTaskIndex: null,+ },+ {+ label: 'a completed implementation with a PR',+ tasks: [+ linkedTask('implementation', TaskRunStatus.COMPLETED, 'https://github.com/example/repo/pull/1'),+ ],+ polls: false,+ openTaskIndex: 0,},{label: 'a failed implementation',tasks: [linkedTask('implementation', TaskRunStatus.FAILED)],polls: false,+ openTaskIndex: null,},{label: 'a research task in progress',tasks: [linkedTask('research', TaskRunStatus.IN_PROGRESS)],+ polls: true,+ openTaskIndex: null,+ },+ {+ label: 'a discussion in progress',+ tasks: [linkedTask('other', TaskRunStatus.IN_PROGRESS)],+ polls: true,+ openTaskIndex: null,+ },+ {+ label: 'a completed discussion',+ tasks: [linkedTask('other', TaskRunStatus.COMPLETED)],polls: false,+ openTaskIndex: null,+ },+ {+ label: 'a discussion and an implementation in progress',+ tasks: [+ linkedTask('other', TaskRunStatus.IN_PROGRESS),+ linkedTask('implementation', TaskRunStatus.IN_PROGRESS),+ ],+ polls: true,+ openTaskIndex: 1,},- ])('a ready report with $label polls: $polls', ({ tasks, polls }) => {+ ])('a ready report with $label polls: $polls', ({ tasks, polls, openTaskIndex }) => {logic.actions.loadReportTasksSuccess(tasks)expect(logic.values.shouldPollReportTasks).toBe(polls)+ expect(logic.values.reportTaskToOpen).toEqual(openTaskIndex === null ? null : tasks[openTaskIndex])})it('refreshes the artefact log once a PR task starts', async () => {diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex fb02ed83ec9b..16b97724099e 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -145,6 +145,20 @@ export function implementationRunInFlight(reportTasks: ReportTaskEntry[] | null))}+/**+ * Whether any linked run is still moving, which is what the View task button waits on.+ *+ * A task with no run yet does not count: the button only opens a task that already has a run, so a+ * task that never gets one would hold the poll open for nothing. That is the opposite of the Create+ * PR gate above, where the task itself claims the slot before its run exists.+ */+export function openableRunInFlight(reportTasks: ReportTaskEntry[] | null): boolean {+ return (reportTasks ?? []).some((entry) => {+ const status = entry.task.latest_run?.status+ return !!status && !TERMINAL_RUN_STATUSES.includes(status)+ })+}+// While the report is still being worked, poll linked tasks every 5s. Mirrors desktop.const ACTIVE_STATUSES: SignalReportStatus[] = [SignalReportStatus.CANDIDATE,@@ -295,6 +309,7 @@ export interface inboxReportDetailLogicValues {reportSignals: SignalNode[] | nullreportSignalsLoading: booleanreportSummary: string | null+ reportTaskToOpen: ReportTaskEntry | nullreportTasks: ReportTaskEntry[] | nullreportTasksLoading: booleanselectedPullRequest: ReportPullRequest@@ -310,6 +325,9 @@ export interface inboxReportDetailLogicActions {createPrSuccess: () => {value: true} // inboxTaskKickoffLogic+ discussReportSuccess: () => {+ value: true+ } // inboxTaskKickoffLogiccloseDraftThread: () => {value: true}@@ -569,6 +587,7 @@ export interface inboxReportDetailLogicMeta {isReResearch: (reportTasks: ReportTaskEntry[] | null) => booleanimplementationSlotClaim: (reportTasks: ReportTaskEntry[] | null) => ImplementationSlotClaim | nullprimaryTask: (reportTasks: ReportTaskEntry[] | null) => ReportTaskEntry | null+ reportTaskToOpen: (reportTasks: ReportTaskEntry[] | null) => ReportTaskEntry | nullselectedTask: (reportTasks: ReportTaskEntry[] | null,selectedTaskId: string | null,@@ -598,7 +617,7 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([// Personal GitHub connection state gates the inline comment composer (comments post as the user).values: [personalIntegrationsLogic, ['integrations as personalIntegrations']],// Starting a PR task writes to the artefact log, which is where the Create PR gate reads from.- actions: [inboxTaskKickoffLogic, ['createPrSuccess']],+ actions: [inboxTaskKickoffLogic, ['createPrSuccess', 'discussReportSuccess']],})),actions({@@ -1004,10 +1023,12 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([// hands the Create PR slot back. Without this clause the action stays disabled on a ready report// until the pane is reopened, and the server's 429 cannot correct it because the failure runs the// other way: the press is refused in the UI that the server would now accept.+ // Discussion and research runs hold it open too so their status in the Runs section settles+ // without requiring the reader to reopen the report.shouldPollReportTasks: [(s) => [s.isReportActive, s.reportTasks],(isReportActive: boolean, reportTasks: ReportTaskEntry[] | null): boolean =>- isReportActive || implementationRunInFlight(reportTasks),+ isReportActive || implementationRunInFlight(reportTasks) || openableRunInFlight(reportTasks),],// Whether the report has a shipped implementation PR — gates the PR checks/comments fetch + poll.selectedPullRequest: [@@ -1231,6 +1252,25 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([})[0]},],+ reportTaskToOpen: [+ (s) => [s.reportTasks],+ (reportTasks: ReportTaskEntry[] | null): ReportTaskEntry | null => {+ const activeImplementation = (reportTasks ?? [])+ .filter(+ (entry) =>+ entry.purpose === 'implementation' &&+ entry.task.latest_run &&+ !TERMINAL_RUN_STATUSES.includes(entry.task.latest_run.status)+ )+ .sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime())[0]+ if (activeImplementation) {+ return activeImplementation+ }+ return (+ reportTasks?.find((entry) => entry.purpose === 'implementation' && getTaskPrUrl(entry.task)) ?? null+ )+ },+ ],// The linked task the viewer renders: the explicit selection if it still exists, else `primaryTask`.selectedTask: [(s) => [s.reportTasks, s.selectedTaskId, s.primaryTask],@@ -1556,6 +1596,9 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([createPrSuccess: () => {actions.loadReportArtefacts()},+ discussReportSuccess: () => {+ actions.loadReportArtefacts()+ },selectPullRequest: () => {actions.loadPrChecksSuccess(null)actions.loadPrCommentsSuccess(null)