: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(posthog-ai): port the periodic feedback prompt to the sandbox runtime (#88185)
Jake Ruth0b1f6e1e6b96
diff --git a/frontend/src/scenes/max/FeedbackPrompt.tsx b/frontend/src/scenes/max/FeedbackPrompt.tsxindex 9fec71bd985a..ba92790b5245 100644--- a/frontend/src/scenes/max/FeedbackPrompt.tsx+++ b/frontend/src/scenes/max/FeedbackPrompt.tsx@@ -19,6 +19,7 @@ interface FeedbackPromptProps {traceId: string | null}+// Duplicated for the sandbox runtime in products/posthog_ai/frontend/components/FeedbackPromptDetails.tsx; this copy is deleted with the LangGraph runtime./*** Detailed feedback form shown after user clicks "Bad" rating.* Allows text feedback submission or escalation to support ticket.diff --git a/frontend/src/scenes/max/components/FeedbackDisplay.tsx b/frontend/src/scenes/max/components/FeedbackDisplay.tsxindex 44f3412a43d6..dd12a1575189 100644--- a/frontend/src/scenes/max/components/FeedbackDisplay.tsx+++ b/frontend/src/scenes/max/components/FeedbackDisplay.tsx@@ -10,6 +10,7 @@ export interface FeedbackDisplayProps {conversationId: string}+// Duplicated for the sandbox runtime in products/posthog_ai/frontend/components/FeedbackPromptRating.tsx; this copy is deleted with the LangGraph runtime.export function FeedbackDisplay({ conversationId }: FeedbackDisplayProps): JSX.Element | null {const { isPromptVisible } = useValues(feedbackPromptLogic({ conversationId }))const { submitRating } = useActions(feedbackPromptLogic({ conversationId }))diff --git a/frontend/src/scenes/max/feedbackPromptLogic.ts b/frontend/src/scenes/max/feedbackPromptLogic.tsindex 458d39031887..53cefa710e9b 100644--- a/frontend/src/scenes/max/feedbackPromptLogic.ts+++ b/frontend/src/scenes/max/feedbackPromptLogic.ts@@ -117,6 +117,7 @@ export type feedbackPromptLogicType = MakeLogicType<feedbackPromptLogicMeta>+// Duplicated for the sandbox runtime in products/posthog_ai/frontend/logics/feedbackPromptLogic.ts; this copy is deleted with the LangGraph runtime.export const feedbackPromptLogic = kea<feedbackPromptLogicType>([path(['scenes', 'max', 'feedbackPromptLogic']),diff --git a/frontend/src/scenes/max/ticketUtils.ts b/frontend/src/scenes/max/ticketUtils.tsindex 7b905c0ac73b..52b955cae084 100644--- a/frontend/src/scenes/max/ticketUtils.ts+++ b/frontend/src/scenes/max/ticketUtils.ts@@ -183,6 +183,7 @@ export function composeTicketBody({ note, summary }: { note: string; summary?: sreturn trimmedNote}+// Duplicated for the sandbox runtime in products/posthog_ai/frontend/utils/ticketMetadata.ts; this copy is deleted with the LangGraph runtime./*** Appends the conversation and trace identifiers to a ticket body. Returns an empty string when* the body is empty, so metadata alone can never be submitted as a ticket.diff --git a/frontend/src/scenes/max/useFeedback.ts b/frontend/src/scenes/max/useFeedback.tsindex c5d8c4d3f757..344d1a162bdf 100644--- a/frontend/src/scenes/max/useFeedback.ts+++ b/frontend/src/scenes/max/useFeedback.ts@@ -11,6 +11,7 @@ export interface UseFeedbackResult {traceId: string | null}+// Duplicated for the sandbox runtime in products/posthog_ai/frontend/hooks/useFeedbackPrompt.ts; this copy is deleted with the LangGraph runtime.export function useFeedback(conversationId: string | null): UseFeedbackResult {const { threadGrouped, streamingActive, traceId, retryCount, cancelCount } = useValues(maxThreadLogic)diff --git a/products/posthog_ai/frontend/components/FeedbackPromptDetails.tsx b/products/posthog_ai/frontend/components/FeedbackPromptDetails.tsxnew file mode 100644index 000000000000..2e96c35d20bd--- /dev/null+++ b/products/posthog_ai/frontend/components/FeedbackPromptDetails.tsx@@ -0,0 +1,235 @@+import { useActions, useValues } from 'kea'+import { useEffect, useRef, useState, memo } from 'react'++import { IconDocument } from '@posthog/icons'+import { LemonButton, LemonInput, LemonModal, lemonToast } from '@posthog/lemon-ui'++import { SupportForm } from 'lib/components/Support/SupportForm'+import { supportLogic } from 'lib/components/Support/supportLogic'+import { userLogic } from 'scenes/userLogic'++import { FeedbackPromptLogicProps, feedbackPromptLogic } from '../logics/feedbackPromptLogic'+import { runStreamLogic } from '../logics/runStreamLogic'+import { MessageTemplate } from '../messages/MessageTemplate'+import { FeedbackSessionKind, appendTicketMetadata } from '../utils/ticketMetadata'++/**+ * The detailed form shown after a "Bad" rating on the periodic prompt: free-text feedback, or escalation+ * to a support ticket through the in-app support form.+ */+export const FeedbackPromptDetails = memo(function FeedbackPromptDetails({+ sessionId,+ sessionKind,+ streamKey,+}: FeedbackPromptLogicProps & { sessionKind: FeedbackSessionKind }): JSX.Element {+ const logicProps = { sessionId, streamKey }+ const { submitDetailedFeedback, completeDetailedFeedback } = useActions(feedbackPromptLogic(logicProps))+ const { traceId } = useValues(runStreamLogic)+ const [feedbackText, setFeedbackText] = useState('')+ const [status, setStatus] = useState<'feedback' | 'ticket_preview' | 'done'>('feedback')+ const [hasSubmittedTicket, setHasSubmittedTicket] = useState(false)+ const [isSupportModalOpen, setIsSupportModalOpen] = useState(false)+ const submitInFlightRef = useRef(false)++ const { sendSupportRequest, lastSubmittedTicketId } = useValues(supportLogic)+ const { resetSendSupportRequest } = useActions(supportLogic)+ const { user } = useValues(userLogic)++ const [pendingTicketSubmission, setPendingTicketSubmission] = useState(false)+ const [ticketIdBeforeSubmission, setTicketIdBeforeSubmission] = useState<string | null>(null)+ const [ticketMessageText, setTicketMessageText] = useState<string>('')++ useEffect(() => {+ // The ticket id only exists once the send resolves; a new id means the submit succeeded.+ if (pendingTicketSubmission && lastSubmittedTicketId && lastSubmittedTicketId !== ticketIdBeforeSubmission) {+ submitDetailedFeedback(ticketMessageText || undefined)+ submitInFlightRef.current = false+ setHasSubmittedTicket(true)+ setIsSupportModalOpen(false)+ setPendingTicketSubmission(false)+ completeDetailedFeedback()+ }+ }, [+ lastSubmittedTicketId,+ pendingTicketSubmission,+ ticketIdBeforeSubmission,+ submitDetailedFeedback,+ completeDetailedFeedback,+ ticketMessageText,+ ])++ function submitFeedback(): void {+ submitDetailedFeedback(feedbackText)+ setStatus('done')+ setTimeout(completeDetailedFeedback, 2000)+ }++ function showTicketPreviewOrOpenModal(): void {+ if (feedbackText.trim().length > 0) {+ setStatus('ticket_preview')+ } else {+ openSupportModalWithPrefill()+ }+ }++ function openSupportModalWithPrefill(): void {+ if (hasSubmittedTicket) {+ return+ }+ resetSendSupportRequest({+ name: '',+ email: '',+ kind: 'feedback',+ message: feedbackText,+ ai_conversation_id: sessionId,+ ai_trace_id: traceId,+ ai_feedback_rating: 'bad',+ })+ setIsSupportModalOpen(true)+ }++ async function handleSupportFormSubmit(): Promise<void> {+ if (submitInFlightRef.current || hasSubmittedTicket) {+ return+ }+ const finalMessage = appendTicketMetadata(sendSupportRequest.message, { sessionId, sessionKind, traceId })+ if (!finalMessage) {+ lemonToast.error('Please add a description before creating a ticket.')+ return+ }++ submitInFlightRef.current = true+ setTicketMessageText(sendSupportRequest.message)+ setTicketIdBeforeSubmission(supportLogic.values.lastSubmittedTicketId)+ setPendingTicketSubmission(true)+ try {+ await supportLogic.asyncActions.submitSupportTicket({+ ...sendSupportRequest,+ name: user?.first_name ?? sendSupportRequest.name ?? 'name not set',+ email: user?.email ?? sendSupportRequest.email ?? '',+ message: finalMessage,+ })+ } catch {+ // Failure is detected below via the unchanged ticket id+ }+ // Success closes the modal via the effect above. An unchanged id means the submit failed: clear+ // the pending state so the modal doesn't hang (the error toast already showed, the text stays).+ if (supportLogic.values.lastSubmittedTicketId === ticketIdBeforeSubmission) {+ submitInFlightRef.current = false+ setPendingTicketSubmission(false)+ }+ }++ function handleSupportModalCancel(): void {+ // The in-flight request cannot be aborted; closing now would allow a duplicate ticket.+ if (submitInFlightRef.current) {+ return+ }+ setIsSupportModalOpen(false)+ setPendingTicketSubmission(false)+ }++ const supportModal = (+ <LemonModal+ isOpen={isSupportModalOpen}+ onClose={handleSupportModalCancel}+ title="Give feedback"+ footer={+ <div className="flex items-center gap-2">+ <LemonButton+ type="secondary"+ onClick={handleSupportModalCancel}+ disabledReason={pendingTicketSubmission ? 'Submitting your ticket…' : undefined}+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ data-attr="submit"+ onClick={() => void handleSupportFormSubmit()}+ loading={pendingTicketSubmission}+ disabledReason={hasSubmittedTicket ? 'Ticket already created' : undefined}+ >+ Submit+ </LemonButton>+ </div>+ }+ >+ <SupportForm />+ </LemonModal>+ )++ if (status === 'done') {+ return (+ <MessageTemplate type="ai">+ <p className="m-0 text-sm text-secondary">Thanks for making PostHog AI better!</p>+ </MessageTemplate>+ )+ }++ if (status === 'feedback') {+ return (+ <>+ <MessageTemplate type="ai">+ <div className="flex flex-col gap-2">+ <p className="m-0 font-medium">What could we improve?</p>+ <LemonInput+ placeholder="Help us improve PostHog AI..."+ value={feedbackText}+ onChange={setFeedbackText}+ onPressEnter={submitFeedback}+ fullWidth+ autoFocus+ />+ <div className="flex gap-2">+ <LemonButton type="primary" size="small" onClick={submitFeedback}>+ Submit+ </LemonButton>+ <LemonButton+ type="secondary"+ size="small"+ onClick={showTicketPreviewOrOpenModal}+ disabledReason={hasSubmittedTicket ? 'Ticket already created' : undefined}+ >+ Open support ticket+ </LemonButton>+ </div>+ </div>+ </MessageTemplate>+ {supportModal}+ </>+ )+ }++ return (+ <>+ <MessageTemplate type="ai">+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-2">+ <IconDocument className="text-secondary" />+ <span className="font-medium">Support ticket ready for review</span>+ </div>+ <p className="m-0 text-sm text-secondary">+ Here's a draft of your support ticket. Please review and submit it to get help from PostHog+ support.+ </p>+ <div className="bg-bg-light border rounded p-3">+ <div className="text-xs font-medium text-secondary uppercase mb-1">Ticket description</div>+ <p className="m-0 text-sm whitespace-pre-wrap">{feedbackText}</p>+ </div>+ <div>+ <LemonButton+ type="primary"+ size="small"+ onClick={openSupportModalWithPrefill}+ disabledReason={hasSubmittedTicket ? 'Ticket already created' : undefined}+ >+ Review support ticket+ </LemonButton>+ </div>+ </div>+ </MessageTemplate>+ {supportModal}+ </>+ )+})diff --git a/products/posthog_ai/frontend/components/FeedbackPromptRating.tsx b/products/posthog_ai/frontend/components/FeedbackPromptRating.tsxnew file mode 100644index 000000000000..9eb55ae72e22--- /dev/null+++ b/products/posthog_ai/frontend/components/FeedbackPromptRating.tsx@@ -0,0 +1,48 @@+import { useActions, useValues } from 'kea'+import { useEffect, memo } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { FeedbackPromptLogicProps, feedbackPromptLogic } from '../logics/feedbackPromptLogic'+import { FeedbackPromptRating as Rating } from '../utils/feedbackEvents'++/** The prompt's Good / Okay / Bad / Dismiss row, with 1 / 2 / 3 / x keyboard shortcuts while open. */+export const FeedbackPromptRating = memo(function FeedbackPromptRating(props: FeedbackPromptLogicProps): JSX.Element {+ const { isPromptVisible } = useValues(feedbackPromptLogic(props))+ const { submitRating } = useActions(feedbackPromptLogic(props))++ // Capture phase, so the shortcuts win over a focused composer.+ useEffect(() => {+ if (!isPromptVisible) {+ return+ }+ const keyToRating: Record<string, Rating> = { '1': 'good', '2': 'okay', '3': 'bad', x: 'dismissed' }+ const handleGlobalKeyDown = (e: KeyboardEvent): void => {+ const rating = keyToRating[e.key]+ if (rating) {+ e.preventDefault()+ e.stopPropagation()+ submitRating(rating)+ }+ }+ window.addEventListener('keydown', handleGlobalKeyDown, true)+ return () => window.removeEventListener('keydown', handleGlobalKeyDown, true)+ }, [isPromptVisible, submitRating])++ return (+ <div className="flex items-center gap-1">+ <LemonButton size="xsmall" type="secondary" onClick={() => submitRating('good')}>+ Good <span className="text-muted ml-0.5">1</span>+ </LemonButton>+ <LemonButton size="xsmall" type="secondary" onClick={() => submitRating('okay')}>+ Okay <span className="text-muted ml-0.5">2</span>+ </LemonButton>+ <LemonButton size="xsmall" type="secondary" onClick={() => submitRating('bad')}>+ Bad <span className="text-muted ml-0.5">3</span>+ </LemonButton>+ <LemonButton size="xsmall" type="secondary" onClick={() => submitRating('dismissed')}>+ Dismiss <span className="text-muted ml-0.5">x</span>+ </LemonButton>+ </div>+ )+})diff --git a/products/posthog_ai/frontend/components/FeedbackPromptTrailer.tsx b/products/posthog_ai/frontend/components/FeedbackPromptTrailer.tsxnew file mode 100644index 000000000000..5fa8e96c2656--- /dev/null+++ b/products/posthog_ai/frontend/components/FeedbackPromptTrailer.tsx@@ -0,0 +1,44 @@+import { memo } from 'react'++import { useFeedbackPrompt } from '../hooks/useFeedbackPrompt'+import { FeedbackPromptLogicProps } from '../logics/feedbackPromptLogic'+import { MessageTemplate } from '../messages/MessageTemplate'+import { FeedbackSessionKind } from '../utils/ticketMetadata'+import { FeedbackPromptDetails } from './FeedbackPromptDetails'+import { FeedbackPromptRating } from './FeedbackPromptRating'++/** The periodic feedback prompt at the bottom of a live thread: rating row, detailed form, or thank-you. */+export const FeedbackPromptTrailer = memo(function FeedbackPromptTrailer({+ sessionId,+ sessionKind,+ streamKey,+}: FeedbackPromptLogicProps & { sessionKind: FeedbackSessionKind }): JSX.Element | null {+ const { isPromptVisible, isDetailedFeedbackVisible, isThankYouVisible, streamingActive } = useFeedbackPrompt(+ sessionId,+ streamKey+ )+ if (streamingActive) {+ return null+ }+ if (isPromptVisible) {+ return (+ <MessageTemplate type="ai">+ <div className="flex flex-col gap-2">+ <span className="text-xs text-muted">How is PostHog AI doing? (optional)</span>+ <FeedbackPromptRating sessionId={sessionId} streamKey={streamKey} />+ </div>+ </MessageTemplate>+ )+ }+ if (isDetailedFeedbackVisible) {+ return <FeedbackPromptDetails sessionId={sessionId} sessionKind={sessionKind} streamKey={streamKey} />+ }+ if (isThankYouVisible) {+ return (+ <MessageTemplate type="ai">+ <p className="m-0 text-sm text-secondary">Thanks for your feedback and using PostHog AI!</p>+ </MessageTemplate>+ )+ }+ return null+})diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxindex df7de4bc6178..90b83850456e 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -1,5 +1,5 @@import { BindLogic, useActions, useValues } from 'kea'-import { createContext, type ReactNode, useCallback, useContext, useEffect } from 'react'+import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo } from 'react'import { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'@@ -8,6 +8,7 @@ import { taskLogic } from '../logics/taskLogic'import { isPiTaskRuntime, OriginProduct } from '../types/taskTypes'import { type TurnTrailer } from '../utils/turnTrailers'import { ContextUsageBar } from './ContextUsageBar'+import { FeedbackPromptTrailer } from './FeedbackPromptTrailer'import { PermissionInput } from './PermissionInput'import { QuestionInput } from './QuestionInput'import { ResourcesBar } from './ResourcesBar'@@ -197,10 +198,23 @@ function RunSurfaceThread({listClassName,rowClassName,}: { className?: string; listClassName?: string; rowClassName?: string } = {}): JSX.Element {- const { interaction, isScout, taskId, conversationId } = useRunSurfaceContext()+ const { interaction, isScout, taskId, conversationId, runId } = useRunSurfaceContext()const { bootstrapLoading, threadItems } = useValues(runStreamLogic)// Feedback identity: the conversation where one exists (Max chats), else the task.const feedbackSessionId = conversationId ?? taskId+ const collectsFeedback = interaction === 'live' && !isScout && !!feedbackSessionId+ // Memoized so the footer keeps a stable element identity across streamed frames.+ const feedbackPrompt = useMemo(+ () =>+ collectsFeedback ? (+ <FeedbackPromptTrailer+ sessionId={feedbackSessionId}+ sessionKind={conversationId ? 'conversation' : 'task'}+ streamKey={runId}+ />+ ) : undefined,+ [collectsFeedback, feedbackSessionId, conversationId, runId]+ )const renderTurnTrailer = useCallback((trailer: TurnTrailer): JSX.Element | null =>feedbackSessionId ? (@@ -226,7 +240,8 @@ function RunSurfaceThread({listClassName={listClassName}rowClassName={rowClassName}showContextUsage={interaction === 'live' && !isScout}- renderTurnTrailer={interaction === 'live' && !isScout && feedbackSessionId ? renderTurnTrailer : undefined}+ renderTurnTrailer={collectsFeedback ? renderTurnTrailer : undefined}+ footerExtra={feedbackPrompt}/>)}diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsxindex a3712c61893d..2463365a1895 100644--- a/products/posthog_ai/frontend/components/ThreadView.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.tsx@@ -1,5 +1,5 @@import { useValues } from 'kea'-import { memo, useCallback, useEffect, useMemo, useState } from 'react'+import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from 'react'import { inStorybookTestRunner } from 'lib/utils/dom'@@ -59,6 +59,8 @@ interface ThreadViewProps {showContextUsage?: boolean/** Renders per-turn UI (e.g. feedback actions) at each completed turn's end. */renderTurnTrailer?: (trailer: TurnTrailer) => JSX.Element | null+ /** Extra footer content below the thinking / PR / context-usage rows (e.g. the feedback prompt). */+ footerExtra?: ReactNodeclassName?: stringlistClassName?: stringrowClassName?: string@@ -79,6 +81,7 @@ export function ThreadView({virtualized = true,showContextUsage = false,renderTurnTrailer,+ footerExtra,className,listClassName,rowClassName,@@ -143,7 +146,7 @@ export function ThreadView({const showContextUsageFooter = showContextUsage && !isThinking && !!contextUsageconst footer = useMemo(() =>- showThinking || pullRequestUrl || showContextUsageFooter || showConnectionStatus ? (+ showThinking || pullRequestUrl || showContextUsageFooter || showConnectionStatus || footerExtra ? (<VirtualizedThread.Row className={rowClassName}><ThreadFootershowThinking={showThinking}@@ -152,6 +155,7 @@ export function ThreadView({prBranch={branch}showContextUsage={showContextUsageFooter}showConnectionStatus={showConnectionStatus}+ extra={footerExtra}/></VirtualizedThread.Row>) : undefined,@@ -162,6 +166,7 @@ export function ThreadView({branch,showContextUsageFooter,showConnectionStatus,+ footerExtra,rowClassName,])@@ -251,6 +256,7 @@ const ThreadFooter = memo(function ThreadFooter({prBranch,showContextUsage,showConnectionStatus,+ extra,}: {showThinking: booleanthinkingPhase: 'thinking' | 'provisioning'@@ -258,6 +264,7 @@ const ThreadFooter = memo(function ThreadFooter({prBranch?: stringshowContextUsage?: booleanshowConnectionStatus?: boolean+ extra?: ReactNode}): JSX.Element {// `runConnectionState` is self-subscribed here (like `currentProgress`) so the frequently-updating// reconnect attempt counter stays isolated to this leaf and never destabilizes `ThreadView`'s footer.@@ -270,6 +277,7 @@ const ThreadFooter = memo(function ThreadFooter({{showThinking && <ThinkingIndicator progress={currentProgress} phase={thinkingPhase} />}{pullRequestUrl && <PullRequestCard prUrl={pullRequestUrl} branch={prBranch} />}{showContextUsage && <ContextUsageBar />}+ {extra}</div>)})diff --git a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsxindex 5fbaf1324599..4cc7b85dfd7a 100644--- a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx+++ b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx@@ -1,5 +1,5 @@import { useActions, useMountedLogic, useValues } from 'kea'-import { useState } from 'react'+import { useState, memo } from 'react'import { IconCopy, IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled, IconX } from '@posthog/icons'import { LemonButton, LemonInput } from '@posthog/lemon-ui'@@ -26,7 +26,7 @@ export interface TurnFeedbackActionsProps {* thumbs-down. Counterpart of the legacy thread's `SuccessActions` — same events* (`$ai_metric` quality / `$ai_feedback`), plus runtime/task/run properties.*/-export function TurnFeedbackActions({+export const TurnFeedbackActions = memo(function TurnFeedbackActions({sessionId,turnIndex,isLastTurn,@@ -142,4 +142,4 @@ export function TurnFeedbackActions({)}</>)-}+})diff --git a/products/posthog_ai/frontend/hooks/useFeedbackPrompt.ts b/products/posthog_ai/frontend/hooks/useFeedbackPrompt.tsnew file mode 100644index 000000000000..fcd18f679ef6--- /dev/null+++ b/products/posthog_ai/frontend/hooks/useFeedbackPrompt.ts@@ -0,0 +1,59 @@+import { useActions, useValues } from 'kea'+import { useEffect, useMemo, useRef } from 'react'++import { feedbackPromptLogic } from '../logics/feedbackPromptLogic'+import { runStreamLogic } from '../logics/runStreamLogic'++export interface UseFeedbackPromptResult {+ isPromptVisible: boolean+ isDetailedFeedbackVisible: boolean+ isThankYouVisible: boolean+ streamingActive: boolean+}++/**+ * Drives the periodic feedback prompt off the bound `runStreamLogic`: checks the trigger rules each time a+ * turn finishes, and treats a new message sent while the prompt is open as an implicit dismissal.+ */+export function useFeedbackPrompt(sessionId: string, streamKey: string): UseFeedbackPromptResult {+ const { threadItems, streamPhase } = useValues(runStreamLogic)+ const logic = feedbackPromptLogic({ sessionId, streamKey })+ const { isPromptVisible, isDetailedFeedbackVisible, isThankYouVisible } = useValues(logic)+ const { checkShouldShowPrompt, implicitDismissPrompt, implicitDismissDetailedFeedback } = useActions(logic)++ const streamingActive = streamPhase !== 'idle'+ const humanMessageCount = useMemo(+ () => threadItems.filter((item) => item.type === 'human_message').length,+ [threadItems]+ )+ const prevMessageCountRef = useRef(humanMessageCount)+ const prevStreamingActiveRef = useRef(streamingActive)++ useEffect(() => {+ const wasStreaming = prevStreamingActiveRef.current+ const prevCount = prevMessageCountRef.current++ if (wasStreaming && !streamingActive && humanMessageCount > 0) {+ checkShouldShowPrompt(humanMessageCount)+ }+ if (isPromptVisible && humanMessageCount > prevCount && streamingActive) {+ implicitDismissPrompt()+ }+ if (isDetailedFeedbackVisible && humanMessageCount > prevCount && streamingActive) {+ implicitDismissDetailedFeedback()+ }++ prevMessageCountRef.current = humanMessageCount+ prevStreamingActiveRef.current = streamingActive+ }, [+ humanMessageCount,+ streamingActive,+ isPromptVisible,+ isDetailedFeedbackVisible,+ checkShouldShowPrompt,+ implicitDismissPrompt,+ implicitDismissDetailedFeedback,+ ])++ return { isPromptVisible, isDetailedFeedbackVisible, isThankYouVisible, streamingActive }+}diff --git a/products/posthog_ai/frontend/logics/feedbackPromptLogic.test.ts b/products/posthog_ai/frontend/logics/feedbackPromptLogic.test.tsnew file mode 100644index 000000000000..4c298bc06f83--- /dev/null+++ b/products/posthog_ai/frontend/logics/feedbackPromptLogic.test.ts@@ -0,0 +1,121 @@+import { expectLogic } from 'kea-test-utils'++import * as featureFlagLogic from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { feedbackPromptLogic } from './feedbackPromptLogic'+import { runStreamLogic } from './runStreamLogic'++const PROPS = { sessionId: 'session-1', streamKey: 'stream-1' }++const DEFAULT_CONFIG = {+ cooldownMs: 86400000,+ messageInterval: 10,+ samplingRate: 0.05,+ retryThreshold: 2,+ cancelThreshold: 3,+}++describe('feedbackPromptLogic (sandbox)', () => {+ let logic: ReturnType<typeof feedbackPromptLogic.build>++ beforeEach(() => {+ initKeaTests()+ localStorage.clear()+ jest.spyOn(featureFlagLogic, 'getFeatureFlagPayload').mockReturnValue(DEFAULT_CONFIG)+ // Sampling would otherwise fire nondeterministically on every check.+ jest.spyOn(Math, 'random').mockReturnValue(0.9)+ logic = feedbackPromptLogic(PROPS)+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ localStorage.clear()+ })++ describe('checkShouldShowPrompt', () => {+ it.each([+ ['no config', () => jest.spyOn(featureFlagLogic, 'getFeatureFlagPayload').mockReturnValue(null), 10],+ [+ 'cooldown active',+ () => localStorage.setItem('posthog_ai_feedback_last_shown', Date.now().toString()),+ 10,+ ],+ ['message count off the interval', () => {}, 7],+ ])('does not show the prompt with %s', async (_, arrange, messageCount) => {+ arrange()+ await expectLogic(logic, () => {+ logic.actions.checkShouldShowPrompt(messageCount)+ }).toMatchValues({ isPromptVisible: false })+ })++ it('does not change an already visible prompt', async () => {+ logic.actions.showPrompt('manual')+ await expectLogic(logic, () => {+ logic.actions.checkShouldShowPrompt(10)+ }).toMatchValues({ isPromptVisible: true, currentTriggerType: 'manual' })+ })++ it('triggers on the message interval once per interval, then again at the next', async () => {+ await expectLogic(logic, () => {+ logic.actions.checkShouldShowPrompt(10)+ }).toMatchValues({+ isPromptVisible: true,+ currentTriggerType: 'message_interval',+ lastTriggeredIntervalIndex: 1,+ })++ logic.actions.hidePrompt()+ await expectLogic(logic, () => {+ logic.actions.checkShouldShowPrompt(10)+ }).toMatchValues({ isPromptVisible: false, lastTriggeredIntervalIndex: 1 })++ await expectLogic(logic, () => {+ logic.actions.checkShouldShowPrompt(20)+ }).toMatchValues({+ isPromptVisible: true,+ currentTriggerType: 'message_interval',+ lastTriggeredIntervalIndex: 2,+ })+ })++ it('counts cancelled runs from the bound stream and triggers at the threshold', async () => {+ const stream = runStreamLogic({ streamKey: PROPS.streamKey })+ stream.mount()+ stream.actions.cancelRun()+ stream.actions.cancelRun()+ stream.actions.cancelRun()++ await expectLogic(logic, () => {+ logic.actions.checkShouldShowPrompt(5)+ }).toMatchValues({ cancelCount: 3, isPromptVisible: true, currentTriggerType: 'cancel' })+ stream.unmount()+ })++ it('triggers on random sampling when nothing else does', async () => {+ jest.spyOn(Math, 'random').mockReturnValue(0.01)+ await expectLogic(logic, () => {+ logic.actions.checkShouldShowPrompt(3)+ }).toMatchValues({ isPromptVisible: true, currentTriggerType: 'random_sample' })+ })+ })++ it('records the cooldown timestamp when feedback is shown', () => {+ const before = Date.now()+ logic.actions.recordFeedbackShown()+ const stored = parseInt(localStorage.getItem('posthog_ai_feedback_last_shown') || '0', 10)+ expect(stored).toBeGreaterThanOrEqual(before)+ })++ it('keeps state separate per session', () => {+ const other = feedbackPromptLogic({ sessionId: 'session-2', streamKey: 'stream-2' })+ other.mount()+ logic.actions.showPrompt('cancel')+ expect(logic.values.isPromptVisible).toBe(true)+ expect(other.values.isPromptVisible).toBe(false)+ other.unmount()+ })+})diff --git a/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts b/products/posthog_ai/frontend/logics/feedbackPromptLogic.tsnew file mode 100644index 000000000000..5f7790df72a5--- /dev/null+++ b/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts@@ -0,0 +1,380 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'++import { FeedbackPromptRating, FeedbackPromptTrigger, RunRef, capturePromptFeedback } from '../utils/feedbackEvents'+import { computeTurnTrailers } from '../utils/turnTrailers'+import { runStreamLogic } from './runStreamLogic'++export interface FeedbackPromptConfig {+ cooldownMs: number+ messageInterval: number+ samplingRate: number+ cancelThreshold: number+}++// Shared with the legacy prompt on purpose: one cooldown per browser, whichever runtime showed it.+const LAST_SHOWN_STORAGE_KEY = 'posthog_ai_feedback_last_shown'++export interface FeedbackPromptLogicProps {+ /** Conversation id where one exists, else the task id. Lands in `$ai_session_id`. */+ sessionId: string+ /** Key of the live `runStreamLogic` instance this prompt observes. */+ streamKey: string+}++/** What the capture needs from the stream at the moment of rating. */+interface StreamSnapshot {+ traceId: string | null+ turnIndex: number | null+ humanMessageCount: number+ run: RunRef | undefined+}++function readStream(streamKey: string): StreamSnapshot {+ const stream = runStreamLogic.findMounted({ streamKey })+ if (!stream) {+ return { traceId: null, turnIndex: null, humanMessageCount: 0, run: undefined }+ }+ const items = stream.values.threadItems+ const trailers = computeTurnTrailers(items)+ const lastTurn = [...trailers.values()].find((trailer) => trailer.isLastTurn)+ return {+ traceId: stream.values.traceId,+ turnIndex: lastTurn?.turnIndex ?? null,+ humanMessageCount: items.filter((item) => item.type === 'human_message').length,+ run: stream.cache.activeRun as RunRef | undefined,+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface feedbackPromptLogicValues {+ canShowPrompt: boolean+ cancelCount: number+ currentTriggerType: FeedbackPromptTrigger+ feedbackConfig: FeedbackPromptConfig | null+ isDetailedFeedbackVisible: boolean+ isPromptVisible: boolean+ isThankYouVisible: boolean+ lastTriggeredIntervalIndex: number+ messageInterval: number+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface feedbackPromptLogicActions {+ cancelRun: (+ run?:+ | {+ runId: string+ taskId: string+ }+ | undefined+ ) => {+ run:+ | {+ runId: string+ taskId: string+ }+ | undefined+ } // runStreamLogic+ checkShouldShowPrompt: (messageCount: number) => {+ messageCount: number+ }+ completeDetailedFeedback: () => {+ value: true+ }+ hideDetailedFeedback: () => {+ value: true+ }+ hidePrompt: () => {+ value: true+ }+ hideThankYou: () => {+ value: true+ }+ implicitDismissDetailedFeedback: () => {+ value: true+ }+ implicitDismissPrompt: () => {+ value: true+ }+ recordFeedbackShown: () => {+ value: true+ }+ setLastTriggeredIntervalIndex: (index: number) => {+ index: number+ }+ showDetailedFeedback: () => {+ value: true+ }+ showPrompt: (triggerType: FeedbackPromptTrigger) => {+ triggerType: FeedbackPromptTrigger+ }+ showThankYou: () => {+ value: true+ }+ submitDetailedFeedback: (feedbackText?: string) => {+ feedbackText: string | undefined+ }+ submitRating: (rating: FeedbackPromptRating) => {+ rating: FeedbackPromptRating+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface feedbackPromptLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ canShowPrompt: (feedbackConfig: FeedbackPromptConfig | null) => boolean+ messageInterval: (feedbackConfig: FeedbackPromptConfig | null) => number+ }+}++export type feedbackPromptLogicType = MakeLogicType<+ feedbackPromptLogicValues,+ feedbackPromptLogicActions,+ FeedbackPromptLogicProps,+ feedbackPromptLogicMeta+>++/**+ * The periodic "how is PostHog AI doing?" prompt for the sandbox runtime. Same trigger rules and flag+ * config as the legacy Max prompt: every Nth human message, a random sample, or a run of+ * cancelled turns, throttled by a per-browser cooldown. The retry trigger has no sandbox equivalent.+ */+export const feedbackPromptLogic = kea<feedbackPromptLogicType>([+ path(['products', 'posthog_ai', 'frontend', 'logics', 'feedbackPromptLogic']),+ props({} as FeedbackPromptLogicProps),+ key((props) => props.sessionId),++ connect((props: FeedbackPromptLogicProps) => ({+ actions: [runStreamLogic({ streamKey: props.streamKey }), ['cancelRun']],+ })),++ actions({+ submitRating: (rating: FeedbackPromptRating) => ({ rating }),+ submitDetailedFeedback: (feedbackText?: string) => ({ feedbackText }),+ completeDetailedFeedback: true,+ checkShouldShowPrompt: (messageCount: number) => ({ messageCount }),+ showPrompt: (triggerType: FeedbackPromptTrigger) => ({ triggerType }),+ hidePrompt: true,+ showDetailedFeedback: true,+ hideDetailedFeedback: true,+ showThankYou: true,+ hideThankYou: true,+ implicitDismissPrompt: true,+ implicitDismissDetailedFeedback: true,+ recordFeedbackShown: true,+ setLastTriggeredIntervalIndex: (index: number) => ({ index }),+ }),++ reducers({+ isPromptVisible: [+ false,+ {+ showPrompt: () => true,+ hidePrompt: () => false,+ implicitDismissPrompt: () => false,+ showDetailedFeedback: () => false,+ showThankYou: () => false,+ },+ ],+ isDetailedFeedbackVisible: [+ false,+ {+ showDetailedFeedback: () => true,+ hideDetailedFeedback: () => false,+ implicitDismissDetailedFeedback: () => false,+ hidePrompt: () => false,+ },+ ],+ isThankYouVisible: [+ false,+ {+ showThankYou: () => true,+ hideThankYou: () => false,+ showPrompt: () => false,+ },+ ],+ currentTriggerType: [+ 'manual' as FeedbackPromptTrigger,+ {+ showPrompt: (_, { triggerType }) => triggerType,+ hidePrompt: () => 'manual' as FeedbackPromptTrigger,+ },+ ],+ lastTriggeredIntervalIndex: [+ 0,+ {+ setLastTriggeredIntervalIndex: (_, { index }) => index,+ },+ ],+ // Cancelled turns in this session since the prompt was last answered.+ cancelCount: [+ 0,+ {+ cancelRun: (state) => state + 1,+ submitRating: () => 0,+ completeDetailedFeedback: () => 0,+ },+ ],+ }),++ selectors({+ feedbackConfig: [+ () => [],+ (): FeedbackPromptConfig | null => {+ const payload = getFeatureFlagPayload(FEATURE_FLAGS.POSTHOG_AI_CONVERSATION_FEEDBACK_CONFIG)+ if (!payload || typeof payload !== 'object') {+ posthog.captureException(+ new Error('POSTHOG_AI_CONVERSATION_FEEDBACK_CONFIG feature flag is not set'),+ { tags: { product: 'max_ai' } }+ )+ return null+ }+ return {+ cooldownMs: payload.cooldownMs,+ messageInterval: payload.messageInterval,+ samplingRate: payload.samplingRate,+ cancelThreshold: payload.cancelThreshold,+ }+ },+ ],+ canShowPrompt: [+ (s) => [s.feedbackConfig],+ (feedbackConfig: FeedbackPromptConfig | null): boolean => {+ if (!feedbackConfig) {+ return false+ }+ const lastShown = localStorage.getItem(LAST_SHOWN_STORAGE_KEY)+ if (!lastShown) {+ return true+ }+ return Date.now() - parseInt(lastShown, 10) > feedbackConfig.cooldownMs+ },+ ],+ messageInterval: [+ (s) => [s.feedbackConfig],+ (feedbackConfig: FeedbackPromptConfig | null): number => feedbackConfig?.messageInterval ?? 10,+ ],+ }),++ listeners(({ actions, values, props, cache }) => ({+ submitRating: ({ rating }) => {+ const { currentTriggerType, messageInterval } = values+ const stream = readStream(props.streamKey)++ // "bad" opens the detailed form; the capture happens on submit.+ if (rating === 'bad') {+ actions.showDetailedFeedback()+ return+ }++ capturePromptFeedback(+ props.sessionId,+ stream.traceId,+ rating,+ currentTriggerType,+ stream.turnIndex,+ stream.run+ )+ actions.recordFeedbackShown()++ // Pin the interval index so the same message count cannot re-trigger the prompt.+ actions.setLastTriggeredIntervalIndex(Math.floor(stream.humanMessageCount / messageInterval))++ if (rating === 'dismissed') {+ actions.hidePrompt()+ } else {+ actions.showThankYou()+ cache.disposables.add((): (() => void) => {+ const timer = window.setTimeout(() => actions.hideThankYou(), 2000)+ return () => clearTimeout(timer)+ }, 'hide-thank-you')+ }+ },++ submitDetailedFeedback: ({ feedbackText }) => {+ const stream = readStream(props.streamKey)+ capturePromptFeedback(+ props.sessionId,+ stream.traceId,+ 'bad',+ values.currentTriggerType,+ stream.turnIndex,+ stream.run,+ feedbackText+ )+ actions.recordFeedbackShown()+ },++ checkShouldShowPrompt: ({ messageCount }) => {+ const { feedbackConfig } = values+ if (!feedbackConfig || values.isPromptVisible) {+ return+ }++ // Read the cooldown directly: the selector is not reactive to localStorage.+ const lastShown = localStorage.getItem(LAST_SHOWN_STORAGE_KEY)+ if (lastShown && Date.now() - parseInt(lastShown, 10) < feedbackConfig.cooldownMs) {+ return+ }++ if (values.cancelCount >= feedbackConfig.cancelThreshold) {+ actions.showPrompt('cancel')+ return+ }++ if (messageCount > 0 && messageCount % feedbackConfig.messageInterval === 0) {+ const currentIntervalIndex = Math.floor(messageCount / feedbackConfig.messageInterval)+ if (currentIntervalIndex > values.lastTriggeredIntervalIndex) {+ actions.setLastTriggeredIntervalIndex(currentIntervalIndex)+ actions.showPrompt('message_interval')+ return+ }+ }++ if (Math.random() < feedbackConfig.samplingRate) {+ actions.showPrompt('random_sample')+ }+ },++ recordFeedbackShown: () => {+ localStorage.setItem(LAST_SHOWN_STORAGE_KEY, Date.now().toString())+ },++ implicitDismissPrompt: () => {+ const stream = readStream(props.streamKey)+ capturePromptFeedback(+ props.sessionId,+ stream.traceId,+ 'implicit_dismiss',+ values.currentTriggerType,+ stream.turnIndex,+ stream.run+ )+ actions.recordFeedbackShown()+ },++ implicitDismissDetailedFeedback: () => {+ const stream = readStream(props.streamKey)+ capturePromptFeedback(+ props.sessionId,+ stream.traceId,+ 'bad',+ values.currentTriggerType,+ stream.turnIndex,+ stream.run+ )+ actions.recordFeedbackShown()+ },++ completeDetailedFeedback: () => {+ const stream = readStream(props.streamKey)+ actions.setLastTriggeredIntervalIndex(Math.floor(stream.humanMessageCount / values.messageInterval))+ actions.hideDetailedFeedback()+ },+ })),+])diff --git a/products/posthog_ai/frontend/utils/feedbackEvents.ts b/products/posthog_ai/frontend/utils/feedbackEvents.tsindex a9d4a1f54992..1e067845b17f 100644--- a/products/posthog_ai/frontend/utils/feedbackEvents.ts+++ b/products/posthog_ai/frontend/utils/feedbackEvents.ts@@ -45,3 +45,33 @@ export function captureTurnFeedbackText(...feedbackContext(sessionId, traceId, run),})}++export type FeedbackPromptRating = 'bad' | 'okay' | 'good' | 'dismissed' | 'implicit_dismiss'+export type FeedbackPromptTrigger = 'message_interval' | 'random_sample' | 'manual' | 'cancel'++/** The periodic prompt's rating (and optional text) — the legacy `captureFeedback` shape plus runtime properties. */+export function capturePromptFeedback(+ sessionId: string,+ traceId: string | null,+ rating: FeedbackPromptRating,+ trigger: FeedbackPromptTrigger,+ turnIndex: number | null,+ run?: RunRef,+ feedbackText?: string+): void {+ posthog.capture('$ai_metric', {+ $ai_metric_name: 'feedback',+ $ai_metric_value: rating,+ feedback_trigger_type: trigger,+ turn_index: turnIndex,+ ...feedbackContext(sessionId, traceId, run),+ })+ if (feedbackText) {+ posthog.capture('$ai_feedback', {+ $ai_feedback_text: feedbackText,+ ai_product: 'posthog_ai',+ turn_index: turnIndex,+ ...feedbackContext(sessionId, traceId, run),+ })+ }+}diff --git a/products/posthog_ai/frontend/utils/ticketMetadata.ts b/products/posthog_ai/frontend/utils/ticketMetadata.tsnew file mode 100644index 000000000000..1060189835ed--- /dev/null+++ b/products/posthog_ai/frontend/utils/ticketMetadata.ts@@ -0,0 +1,15 @@+export type FeedbackSessionKind = 'conversation' | 'task'++/** Appends the session and trace ids to a support ticket body so support can find the run. */+export function appendTicketMetadata(+ body: string,+ { sessionId, sessionKind, traceId }: { sessionId: string; sessionKind: FeedbackSessionKind; traceId: string | null }+): string {+ const trimmedBody = body.trim()+ if (!trimmedBody) {+ return ''+ }+ const idLabel = sessionKind === 'task' ? 'Task ID' : 'Conversation ID'+ const metadataLines = [`${idLabel}: ${sessionId}`, traceId ? `Trace ID: ${traceId}` : null].filter(Boolean)+ return `${trimmedBody}\n\n----\n${metadataLines.join('\n')}`+}diff --git a/products/posthog_ai/frontend/utils/turnTrailers.test.ts b/products/posthog_ai/frontend/utils/turnTrailers.test.tsindex 81810c98e166..770f3e6df370 100644--- a/products/posthog_ai/frontend/utils/turnTrailers.test.ts+++ b/products/posthog_ai/frontend/utils/turnTrailers.test.ts@@ -40,6 +40,17 @@ describe('computeTurnTrailers', () => {expect(trailers.get('turn-0')).toEqual({ turnIndex: 0, isLastTurn: true, turnText: 'clean answer' })})+ it('ignores a duplicate turn-end marker with no answer behind it', () => {+ const trailers = computeTurnTrailers([+ item('human_message', 'h0', 'q1'),+ item('assistant_message', 'a0', 'answer'),+ item('turn_separator', 'turn-0'),+ item('turn_separator', 'turn-1'),+ ])+ expect([...trailers.keys()]).toEqual(['turn-0'])+ expect(trailers.get('turn-0')?.isLastTurn).toBe(true)+ })+it('returns an empty map for a thread with no completed turns', () => {const trailers = computeTurnTrailers([item('human_message', 'h0', 'q1'),diff --git a/products/posthog_ai/frontend/utils/turnTrailers.ts b/products/posthog_ai/frontend/utils/turnTrailers.tsindex d8bf61c971c2..f875b8bc9c0b 100644--- a/products/posthog_ai/frontend/utils/turnTrailers.ts+++ b/products/posthog_ai/frontend/utils/turnTrailers.ts@@ -28,6 +28,11 @@ export function computeTurnTrailers(threadItems: ThreadItem[]): Map<string, Turn// A crashed turn never emits its separator; its text must not leak into the next turn.textParts = []} else if (item.type === 'turn_separator') {+ // A separator with no answer behind it is a duplicate turn-end marker (the history/live+ // seam can leak one); it is not a turn and gets no trailer.+ if (textParts.length === 0) {+ continue+ }trailers.set(item.id, { turnIndex, isLastTurn: false, turnText: textParts.join('\n\n') })lastSeparatorId = item.idturnIndex += 1