Skip to content

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

feat: Bring thumbs up/down feedback to the new alpha posthog AI web interface (#88044)

Jake Ruth03e573e88b5a
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 8d6b0204d3f7..4d9b934b5aa1 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -1,7 +1,7 @@
import clsx from 'clsx'
import { BindLogic, useActions, useValues } from 'kea'
import posthog from 'posthog-js'
-import React, { useLayoutEffect, useMemo, useState } from 'react'
+import React, { useCallback, useLayoutEffect, useMemo, useState } from 'react'
import {
IconChevronRight,
@@ -68,6 +68,7 @@ import { PendingApproval, RecordingUniversalFilters, Region } from '~/types'
import {
AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM,
getThinkingMessageFromResponse,
+ messageRatingsLogic,
runStreamLogic,
useAttachedContext,
useForegroundStream,
@@ -82,6 +83,8 @@ import {
ReplayVisionScanWidget,
ResourcesBar,
ThreadView,
+ TurnFeedbackActions,
+ type TurnTrailer,
} from 'products/posthog_ai/frontend/api/primitives'
import { LogEntry } from 'products/posthog_ai/frontend/lib/parse-logs'
import { isPiTaskRuntime } from 'products/posthog_ai/frontend/types/taskTypes'
@@ -92,7 +95,6 @@ import { MaxWebAnalyticsNudge } from './components/MaxWebAnalyticsNudge'
import { ContextSummary } from './Context'
import { DangerousOperationApprovalCard } from './DangerousOperationApprovalCard'
import { FeedbackPrompt } from './FeedbackPrompt'
-import { maxMessageRatingsLogic } from './logics/maxMessageRatingsLogic'
import { EnhancedToolCall, ToolRegistration, getToolDefinitionFromToolCall } from './max-constants'
import { maxGlobalLogic } from './maxGlobalLogic'
import { SIDE_PANEL_PANEL_ID, ThreadMessage, maxLogic } from './maxLogic'
@@ -148,6 +150,19 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
className
)
+ const renderTurnTrailer = useCallback(
+ (trailer: TurnTrailer): JSX.Element | null =>
+ sandboxConversationKey ? (
+ <TurnFeedbackActions
+ sessionId={sandboxConversationKey}
+ turnIndex={trailer.turnIndex}
+ isLastTurn={trailer.isLastTurn}
+ turnText={trailer.turnText}
+ />
+ ) : null,
+ [sandboxConversationKey]
+ )
+
if (isPiTask) {
return <LemonBanner type="info">Pi session logs aren't available in PostHog yet.</LemonBanner>
}
@@ -165,7 +180,7 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}
>
{/* The live Max column owns scroll via ThreadAutoScroller — render rows in flow, not virtualized. */}
- <ThreadView virtualized={false} />
+ <ThreadView virtualized={false} renderTurnTrailer={renderTurnTrailer} />
</BindLogic>
</div>
)
@@ -185,7 +200,7 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
logic={runStreamLogic}
props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}
>
- <ThreadView virtualized={false} />
+ <ThreadView virtualized={false} renderTurnTrailer={renderTurnTrailer} />
</BindLogic>
</div>
)
@@ -1330,8 +1345,8 @@ function SuccessActions({
content?: string | null
}): JSX.Element {
const { traceId: logicTraceId } = useValues(maxThreadLogic)
- const { ratingForTraceId } = useValues(maxMessageRatingsLogic)
- const { setRatingForTraceId } = useActions(maxMessageRatingsLogic)
+ const { ratingForKey } = useValues(messageRatingsLogic)
+ const { setRating } = useActions(messageRatingsLogic)
const { retryLastMessage } = useActions(maxThreadLogic)
const { user } = useValues(userLogic)
const { isDev, preflight } = useValues(preflightLogic)
@@ -1340,7 +1355,7 @@ function SuccessActions({
// Use the context trace_id if available (for reloaded conversations), otherwise fall back to logic's traceId
const traceId = contextTraceId || logicTraceId
- const rating = ratingForTraceId(traceId)
+ const rating = ratingForKey(traceId)
const [feedback, setFeedback] = useState<string>('')
const [feedbackInputStatus, setFeedbackInputStatus] = useState<'hidden' | 'pending' | 'submitted'>('hidden')
@@ -1348,7 +1363,7 @@ function SuccessActions({
if (rating || !traceId) {
return // Already rated
}
- setRatingForTraceId({ traceId, rating: newRating })
+ setRating({ key: traceId, rating: newRating })
posthog.captureTraceMetric(traceId, 'quality', newRating)
if (newRating === 'bad') {
setFeedbackInputStatus('pending')
diff --git a/frontend/src/scenes/max/logics/maxMessageRatingsLogic.ts b/frontend/src/scenes/max/logics/maxMessageRatingsLogic.ts
deleted file mode 100644
index 98d97294a6d1..000000000000
--- a/frontend/src/scenes/max/logics/maxMessageRatingsLogic.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'
-
-export type MaxMessageRating = 'good' | 'bad'
-export type MaxMessageRatingOrNull = MaxMessageRating | null
-
-const MAX_STORED_RATINGS = 1000
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface maxMessageRatingsLogicValues {
- ratingForTraceId: (traceId: string | null | undefined) => MaxMessageRatingOrNull
- ratingsByTraceId: Record<string, MaxMessageRating>
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface maxMessageRatingsLogicActions {
- clearAllRatings: () => {
- value: true
- }
- clearRatingForTraceId: (payload: { traceId: string }) => {
- traceId: string
- }
- pruneOldRatings: () => {
- value: true
- }
- setRatingForTraceId: (payload: { rating: MaxMessageRating; traceId: string }) => {
- rating: MaxMessageRating
- traceId: string
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface maxMessageRatingsLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- ratingForTraceId: (
- ratingsByTraceId: Record<string, MaxMessageRating>
- ) => (traceId: string | null | undefined) => MaxMessageRatingOrNull
- }
-}
-
-export type maxMessageRatingsLogicType = MakeLogicType<
- maxMessageRatingsLogicValues,
- maxMessageRatingsLogicActions,
- Record<string, any>,
- maxMessageRatingsLogicMeta
->
-
-/**
- * Persists Max AI message ratings ("good"/"bad") keyed by trace ID.
- *
- * Uses Kea's localStorage plugin for automatic persistence.
- */
-export const maxMessageRatingsLogic = kea<maxMessageRatingsLogicType>([
- path(['scenes', 'max', 'logics', 'maxMessageRatingsLogic']),
-
- actions({
- setRatingForTraceId: (payload: { traceId: string; rating: MaxMessageRating }) => ({
- traceId: payload.traceId.trim(),
- rating: payload.rating,
- }),
- clearRatingForTraceId: (payload: { traceId: string }) => ({ traceId: payload.traceId.trim() }),
- clearAllRatings: true,
- pruneOldRatings: true,
- }),
-
- reducers({
- ratingsByTraceId: [
- {} as Record<string, MaxMessageRating>,
- { persist: true, storageKey: 'posthog_ai_ratings' },
- {
- setRatingForTraceId: (state, { traceId, rating }) => ({
- ...state,
- [traceId]: rating,
- }),
- clearRatingForTraceId: (state, { traceId }) => {
- if (!(traceId in state)) {
- return state
- }
- const next = { ...state }
- delete next[traceId]
- return next
- },
- clearAllRatings: () => ({}),
- pruneOldRatings: (state) => {
- const entries = Object.entries(state)
- if (entries.length <= MAX_STORED_RATINGS) {
- return state
- }
- return Object.fromEntries(entries.slice(-MAX_STORED_RATINGS))
- },
- },
- ],
- }),
-
- selectors({
- ratingForTraceId: [
- (s) => [s.ratingsByTraceId],
- (ratingsByTraceId: Record<string, MaxMessageRating>) => {
- return (traceId: string | null | undefined): MaxMessageRatingOrNull => {
- if (!traceId) {
- return null
- }
- return ratingsByTraceId[traceId] ?? null
- }
- },
- ],
- }),
-
- listeners(({ actions, values }) => ({
- setRatingForTraceId: () => {
- // Prune old ratings if we've exceeded the limit
- if (Object.keys(values.ratingsByTraceId).length > MAX_STORED_RATINGS) {
- actions.pruneOldRatings()
- }
- },
- })),
-])
diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.ts
index 7d9606242b08..a04f52a762fd 100644
--- a/products/posthog_ai/frontend/api/logics.ts
+++ b/products/posthog_ai/frontend/api/logics.ts
@@ -14,6 +14,7 @@ export type { RunStreamLogicProps, RunSseStatus, RunStatus } from '../logics/run
// --- Interaction facade (follow-up / queue) ---
export { runInteractionLogic } from '../logics/runInteractionLogic'
+export { messageRatingsLogic } from '../logics/messageRatingsLogic'
export type { RunInteractionLogicProps, QueuedMessage } from '../logics/runInteractionLogic'
// --- Thinking-message helpers ---
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index f3b8d3d9d418..3a35cc4ef8d4 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -51,6 +51,8 @@ export { DEFAULT_SUGGESTIONS_DATA } from '../components/suggestions/suggestionsD
// atoms); `ThreadView` is the prepackaged virtualized presenter (also `Thread.Root`).
export { Thread } from '../components/Thread'
export { ThreadView } from '../components/ThreadView'
+export type { TurnTrailer } from '../utils/turnTrailers'
+export { TurnFeedbackActions } from '../components/TurnFeedbackActions'
export { MessageTemplate } from '../messages/MessageTemplate'
export { MarkdownMessage } from '../messages/MarkdownMessage'
export { ReasoningAnswer } from '../messages/ReasoningAnswer'
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
index adf3efa4421c..df7de4bc6178 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -1,17 +1,19 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { createContext, type ReactNode, useContext, useEffect } from 'react'
+import { createContext, type ReactNode, useCallback, useContext, useEffect } from 'react'
import { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'
import { taskLogic } from '../logics/taskLogic'
import { isPiTaskRuntime, OriginProduct } from '../types/taskTypes'
+import { type TurnTrailer } from '../utils/turnTrailers'
import { ContextUsageBar } from './ContextUsageBar'
import { PermissionInput } from './PermissionInput'
import { QuestionInput } from './QuestionInput'
import { ResourcesBar } from './ResourcesBar'
import { RunLogSkeleton } from './RunLogSkeleton'
import { ThreadView } from './ThreadView'
+import { TurnFeedbackActions } from './TurnFeedbackActions'
export interface RunSurfaceProps {
taskId: string
@@ -49,6 +51,8 @@ interface RunSurfaceContextValue {
rawRunId: string | null
/** Logic key (used for child stream keys). */
runId: string
+ taskId: string
+ conversationId?: string
interaction: 'live' | 'read-only'
/** Run created by a Signals scout — the context-usage line is suppressed for these. */
isScout: boolean
@@ -124,6 +128,8 @@ function RunSurfaceRoot({
value={{
rawRunId: runId,
runId: logicKey,
+ taskId,
+ conversationId,
interaction,
isScout,
}}
@@ -191,20 +197,36 @@ function RunSurfaceThread({
listClassName,
rowClassName,
}: { className?: string; listClassName?: string; rowClassName?: string } = {}): JSX.Element {
- const { interaction, isScout } = useRunSurfaceContext()
+ const { interaction, isScout, taskId, conversationId } = useRunSurfaceContext()
const { bootstrapLoading, threadItems } = useValues(runStreamLogic)
+ // Feedback identity: the conversation where one exists (Max chats), else the task.
+ const feedbackSessionId = conversationId ?? taskId
+ const renderTurnTrailer = useCallback(
+ (trailer: TurnTrailer): JSX.Element | null =>
+ feedbackSessionId ? (
+ <TurnFeedbackActions
+ sessionId={feedbackSessionId}
+ turnIndex={trailer.turnIndex}
+ isLastTurn={trailer.isLastTurn}
+ turnText={trailer.turnText}
+ />
+ ) : null,
+ [feedbackSessionId]
+ )
const showSkeleton = bootstrapLoading && threadItems.length === 0
if (showSkeleton) {
return <RunLogSkeleton className={className} listClassName={listClassName} rowClassName={rowClassName} />
}
// Context usage rides the thread footer for live runs (the meta bars are live-only), but never for a
// scout run. An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
+ // Turn feedback follows the same gate: only interactive, non-scout surfaces collect ratings.
return (
<ThreadView
className={className}
listClassName={listClassName}
rowClassName={rowClassName}
showContextUsage={interaction === 'live' && !isScout}
+ renderTurnTrailer={interaction === 'live' && !isScout && feedbackSessionId ? renderTurnTrailer : undefined}
/>
)
}
diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsx
index 98eb26a90faa..a3712c61893d 100644
--- a/products/posthog_ai/frontend/components/ThreadView.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.tsx
@@ -7,6 +7,7 @@ import { runStreamLogic } from '../logics/runStreamLogic'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
import type { ThreadItem } from '../types/streamTypes'
import { getRandomThinkingMessage } from '../utils/thinkingMessages'
+import { type TurnTrailer, computeTurnTrailers } from '../utils/turnTrailers'
import { ContextUsageBar } from './ContextUsageBar'
import { PullRequestCard } from './PullRequestCard'
import { RunAlertActivity } from './RunAlertActivity'
@@ -56,6 +57,8 @@ interface ThreadViewProps {
* non-scout runs.
*/
showContextUsage?: boolean
+ /** Renders per-turn UI (e.g. feedback actions) at each completed turn's end. */
+ renderTurnTrailer?: (trailer: TurnTrailer) => JSX.Element | null
className?: string
listClassName?: string
rowClassName?: string
@@ -75,6 +78,7 @@ interface ThreadViewProps {
export function ThreadView({
virtualized = true,
showContextUsage = false,
+ renderTurnTrailer,
className,
listClassName,
rowClassName,
@@ -99,6 +103,11 @@ export function ThreadView({
() => threadItems.findLast((item) => item.type === 'human_message')?.id ?? null,
[threadItems]
)
+ // Only computed when a trailer renderer is supplied — bare ThreadViews pay nothing.
+ const turnTrailers = useMemo(
+ () => (renderTurnTrailer ? computeTurnTrailers(threadItems) : null),
+ [threadItems, renderTurnTrailer]
+ )
const hasActiveProgressItem = threadItems.some(
(item) => item.type === 'progress' && item.progressSteps?.some((step) => step.status === 'in_progress')
)
@@ -158,19 +167,38 @@ export function ThreadView({
)
const renderItem = useCallback(
- (item: ThreadItem, index: number): JSX.Element => (
- <VirtualizedThread.Row className={rowClassName}>
- <ThreadRow
- item={item}
- isLast={index === threadItems.length - 1}
- isThinking={isThinking}
- toolInvocations={toolInvocations}
- turnComplete={turnComplete}
- turnCancelled={turnCancelled}
- />
- </VirtualizedThread.Row>
- ),
- [threadItems.length, isThinking, toolInvocations, turnComplete, turnCancelled, rowClassName]
+ (item: ThreadItem, index: number): JSX.Element => {
+ if (item.type === 'turn_separator' && renderTurnTrailer) {
+ const trailer = turnTrailers?.get(item.id)
+ return (
+ <VirtualizedThread.Row className={rowClassName}>
+ {trailer ? renderTurnTrailer(trailer) : null}
+ </VirtualizedThread.Row>
+ )
+ }
+ return (
+ <VirtualizedThread.Row className={rowClassName}>
+ <ThreadRow
+ item={item}
+ isLast={index === threadItems.length - 1}
+ isThinking={isThinking}
+ toolInvocations={toolInvocations}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ </VirtualizedThread.Row>
+ )
+ },
+ [
+ threadItems.length,
+ isThinking,
+ toolInvocations,
+ turnComplete,
+ turnCancelled,
+ rowClassName,
+ renderTurnTrailer,
+ turnTrailers,
+ ]
)
return (
diff --git a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
new file mode 100644
index 000000000000..5fbaf1324599
--- /dev/null
+++ b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
@@ -0,0 +1,145 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconCopy, IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled, IconX } from '@posthog/icons'
+import { LemonButton, LemonInput } from '@posthog/lemon-ui'
+
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { stripMarkdown } from 'lib/utils/markdown'
+
+import { messageRatingsLogic } from '../logics/messageRatingsLogic'
+import { runStreamLogic } from '../logics/runStreamLogic'
+import { MessageTemplate } from '../messages/MessageTemplate'
+import { RunRef, captureTurnFeedbackText, captureTurnRating } from '../utils/feedbackEvents'
+
+export interface TurnFeedbackActionsProps {
+ /** Conversation id where one exists (Max chats), else the task id. Lands in `$ai_session_id`. */
+ sessionId: string
+ /** Ordinal of the completed turn — the rating's identity, stable across reloads. */
+ turnIndex: number
+ isLastTurn: boolean
+ turnText: string
+}
+
+/**
+ * Feedback actions under a completed turn: copy, thumbs up/down, and a free-text form on
+ * thumbs-down. Counterpart of the legacy thread's `SuccessActions` — same events
+ * (`$ai_metric` quality / `$ai_feedback`), plus runtime/task/run properties.
+ */
+export function TurnFeedbackActions({
+ sessionId,
+ turnIndex,
+ isLastTurn,
+ turnText,
+}: TurnFeedbackActionsProps): JSX.Element {
+ const { ratingForKey } = useValues(messageRatingsLogic)
+ const { setRating } = useActions(messageRatingsLogic)
+ const { traceId } = useValues(runStreamLogic)
+ const mountedStreamLogic = useMountedLogic(runStreamLogic)
+
+ const ratingKey = `${sessionId}:turn-${turnIndex}`
+ const rating = ratingForKey(ratingKey)
+ const [feedback, setFeedback] = useState<string>('')
+ const [feedbackInputStatus, setFeedbackInputStatus] = useState<'hidden' | 'pending' | 'submitted'>('hidden')
+
+ // The sandbox runtime exposes no per-turn trace ids; the client-minted id of the latest send is
+ // the only truthful value. Older turns send null rather than a synthetic id.
+ const turnTraceId = isLastTurn ? traceId : null
+
+ function activeRun(): RunRef | undefined {
+ return mountedStreamLogic.cache.activeRun as RunRef | undefined
+ }
+
+ function submitRating(newRating: 'good' | 'bad'): void {
+ if (rating) {
+ return // Already rated
+ }
+ setRating({ key: ratingKey, rating: newRating })
+ captureTurnRating(sessionId, turnTraceId, newRating, turnIndex, activeRun())
+ if (newRating === 'bad') {
+ setFeedbackInputStatus('pending')
+ }
+ }
+
+ function submitFeedback(): void {
+ if (!feedback) {
+ return // Input is empty
+ }
+ captureTurnFeedbackText(sessionId, turnTraceId, feedback, turnIndex, activeRun())
+ setFeedbackInputStatus('submitted')
+ }
+
+ return (
+ <>
+ <div className="flex items-center ml-1">
+ {turnText && (
+ <LemonButton
+ icon={<IconCopy />}
+ type="tertiary"
+ size="xsmall"
+ tooltip="Copy answer"
+ data-attr="posthog-ai-turn-copy"
+ onClick={() => void copyToClipboard(stripMarkdown(turnText))}
+ />
+ )}
+ {rating !== 'bad' && (
+ <LemonButton
+ icon={rating === 'good' ? <IconThumbsUpFilled /> : <IconThumbsUp />}
+ type="tertiary"
+ size="xsmall"
+ tooltip="Good answer"
+ data-attr="posthog-ai-turn-rating-good"
+ onClick={() => submitRating('good')}
+ />
+ )}
+ {rating !== 'good' && (
+ <LemonButton
+ icon={rating === 'bad' ? <IconThumbsDownFilled /> : <IconThumbsDown />}
+ type="tertiary"
+ size="xsmall"
+ tooltip="Bad answer"
+ data-attr="posthog-ai-turn-rating-bad"
+ onClick={() => submitRating('bad')}
+ />
+ )}
+ </div>
+ {feedbackInputStatus !== 'hidden' && (
+ <MessageTemplate type="ai">
+ <div className="flex items-center gap-1">
+ <h4 className="m-0 text-sm grow">
+ {feedbackInputStatus === 'pending'
+ ? 'What disappointed you about the answer?'
+ : 'Thank you for your feedback!'}
+ </h4>
+ <LemonButton
+ icon={<IconX />}
+ type="tertiary"
+ size="xsmall"
+ onClick={() => setFeedbackInputStatus('hidden')}
+ />
+ </div>
+ {feedbackInputStatus === 'pending' && (
+ <div className="flex w-full gap-1.5 items-center mt-1.5">
+ <LemonInput
+ placeholder="Help us improve PostHog AI…"
+ fullWidth
+ value={feedback}
+ onChange={(newValue) => setFeedback(newValue)}
+ onPressEnter={() => submitFeedback()}
+ autoFocus
+ />
+ <LemonButton
+ type="primary"
+ data-attr="posthog-ai-turn-feedback-submit"
+ onClick={() => submitFeedback()}
+ disabledReason={!feedback ? 'Please type a few words!' : undefined}
+ >
+ Submit
+ </LemonButton>
+ </div>
+ )}
+ </MessageTemplate>
+ )}
+ </>
+ )
+}
diff --git a/products/posthog_ai/frontend/logics/messageRatingsLogic.ts b/products/posthog_ai/frontend/logics/messageRatingsLogic.ts
new file mode 100644
index 000000000000..2d2a1d8bef16
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/messageRatingsLogic.ts
@@ -0,0 +1,118 @@
+import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'
+
+export type MessageRating = 'good' | 'bad'
+export type MessageRatingOrNull = MessageRating | null
+
+const MAX_STORED_RATINGS = 1000
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface messageRatingsLogicValues {
+ ratingForKey: (key: string | null | undefined) => MessageRatingOrNull
+ ratingsByKey: Record<string, MessageRating>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface messageRatingsLogicActions {
+ clearAllRatings: () => {
+ value: true
+ }
+ clearRating: (payload: { key: string }) => {
+ key: string
+ }
+ pruneOldRatings: () => {
+ value: true
+ }
+ setRating: (payload: { key: string; rating: MessageRating }) => {
+ key: string
+ rating: MessageRating
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface messageRatingsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ ratingForKey: (
+ ratingsByKey: Record<string, MessageRating>
+ ) => (key: string | null | undefined) => MessageRatingOrNull
+ }
+}
+
+export type messageRatingsLogicType = MakeLogicType<
+ messageRatingsLogicValues,
+ messageRatingsLogicActions,
+ Record<string, any>,
+ messageRatingsLogicMeta
+>
+
+/**
+ * Persists PostHog AI answer ratings ("good"/"bad") in localStorage.
+ *
+ * Keys are runtime-specific: the legacy thread uses the message's trace id, the sandbox thread
+ * uses `<conversationId>:turn-<n>`.
+ */
+export const messageRatingsLogic = kea<messageRatingsLogicType>([
+ path(['scenes', 'max', 'logics', 'messageRatingsLogic']),
+
+ actions({
+ setRating: (payload: { key: string; rating: MessageRating }) => ({
+ key: payload.key.trim(),
+ rating: payload.rating,
+ }),
+ clearRating: (payload: { key: string }) => ({ key: payload.key.trim() }),
+ clearAllRatings: true,
+ pruneOldRatings: true,
+ }),
+
+ reducers({
+ ratingsByKey: [
+ {} as Record<string, MessageRating>,
+ // storageKey predates the key-based rename — changing it would silently drop users' saved ratings.
+ { persist: true, storageKey: 'posthog_ai_ratings' },
+ {
+ setRating: (state, { key, rating }) => ({
+ ...state,
+ [key]: rating,
+ }),
+ clearRating: (state, { key }) => {
+ if (!(key in state)) {
+ return state
+ }
+ const next = { ...state }
+ delete next[key]
+ return next
+ },
+ clearAllRatings: () => ({}),
+ pruneOldRatings: (state) => {
+ const entries = Object.entries(state)
+ if (entries.length <= MAX_STORED_RATINGS) {
+ return state
+ }
+ return Object.fromEntries(entries.slice(-MAX_STORED_RATINGS))
+ },
+ },
+ ],
+ }),
+
+ selectors({
+ ratingForKey: [
+ (s) => [s.ratingsByKey],
+ (ratingsByKey: Record<string, MessageRating>) => {
+ return (key: string | null | undefined): MessageRatingOrNull => {
+ if (!key) {
+ return null
+ }
+ return ratingsByKey[key] ?? null
+ }
+ },
+ ],
+ }),
+
+ listeners(({ actions, values }) => ({
+ setRating: () => {
+ // Prune old ratings if we've exceeded the limit
+ if (Object.keys(values.ratingsByKey).length > MAX_STORED_RATINGS) {
+ actions.pruneOldRatings()
+ }
+ },
+ })),
+])
diff --git a/products/posthog_ai/frontend/utils/feedbackEvents.ts b/products/posthog_ai/frontend/utils/feedbackEvents.ts
new file mode 100644
index 000000000000..a9d4a1f54992
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/feedbackEvents.ts
@@ -0,0 +1,47 @@
+import posthog from 'posthog-js'
+
+export interface RunRef {
+ taskId?: string
+ runId?: string
+}
+
+/** Shared properties for sandbox-runtime feedback events, so dashboards can split by runtime. */
+function feedbackContext(sessionId: string, traceId: string | null, run: RunRef | undefined): Record<string, unknown> {
+ return {
+ $ai_session_id: sessionId,
+ $ai_trace_id: traceId,
+ agent_runtime: 'sandbox',
+ task_id: run?.taskId ?? null,
+ run_id: run?.runId ?? null,
+ }
+}
+
+export function captureTurnRating(
+ sessionId: string,
+ traceId: string | null,
+ rating: 'good' | 'bad',
+ turnIndex: number,
+ run?: RunRef
+): void {
+ posthog.capture('$ai_metric', {
+ $ai_metric_name: 'quality',
+ $ai_metric_value: rating,
+ turn_index: turnIndex,
+ ...feedbackContext(sessionId, traceId, run),
+ })
+}
+
+export function captureTurnFeedbackText(
+ sessionId: string,
+ traceId: string | null,
+ feedbackText: string,
+ turnIndex: number,
+ run?: RunRef
+): void {
+ 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/turnTrailers.test.ts b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
new file mode 100644
index 000000000000..81810c98e166
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
@@ -0,0 +1,50 @@
+import type { ThreadItem } from '../types/streamTypes'
+import { computeTurnTrailers } from './turnTrailers'
+
+function item(type: ThreadItem['type'], id: string, text?: string): ThreadItem {
+ return { id, type, text }
+}
+
+describe('computeTurnTrailers', () => {
+ it('assigns stable ordinals and per-turn text across multiple turns', () => {
+ const trailers = computeTurnTrailers([
+ item('human_message', 'h0', 'q1'),
+ item('assistant_message', 'a0', 'first answer'),
+ item('turn_separator', 'turn-0'),
+ item('human_message', 'h1', 'q2'),
+ item('assistant_thought', 't0', 'thinking'),
+ item('assistant_message', 'a1', 'second answer'),
+ item('assistant_message', 'a2', 'continued'),
+ item('turn_separator', 'turn-1'),
+ ])
+
+ expect(trailers.get('turn-0')).toEqual({ turnIndex: 0, isLastTurn: false, turnText: 'first answer' })
+ expect(trailers.get('turn-1')).toEqual({
+ turnIndex: 1,
+ isLastTurn: true,
+ turnText: 'second answer\n\ncontinued',
+ })
+ })
+
+ it("does not leak a crashed turn's text into the next completed turn", () => {
+ // A crashed turn never emits its separator; the next human message starts a fresh turn.
+ const trailers = computeTurnTrailers([
+ item('human_message', 'h0', 'q1'),
+ item('assistant_message', 'a0', 'crashed partial answer'),
+ item('error', 'e0'),
+ item('human_message', 'h1', 'q2'),
+ item('assistant_message', 'a1', 'clean answer'),
+ item('turn_separator', 'turn-0'),
+ ])
+
+ expect(trailers.get('turn-0')).toEqual({ turnIndex: 0, isLastTurn: true, turnText: 'clean answer' })
+ })
+
+ it('returns an empty map for a thread with no completed turns', () => {
+ const trailers = computeTurnTrailers([
+ item('human_message', 'h0', 'q1'),
+ item('assistant_message', 'a0', 'still streaming'),
+ ])
+ expect(trailers.size).toBe(0)
+ })
+})
diff --git a/products/posthog_ai/frontend/utils/turnTrailers.ts b/products/posthog_ai/frontend/utils/turnTrailers.ts
new file mode 100644
index 000000000000..d8bf61c971c2
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/turnTrailers.ts
@@ -0,0 +1,44 @@
+import type { ThreadItem } from '../types/streamTypes'
+
+/** A completed turn's identity and content, handed to `ThreadView`'s `renderTurnTrailer`. */
+export interface TurnTrailer {
+ /** 0-based ordinal of the completed turn. Stable across reloads: the stored log keeps every
+ * `_posthog/turn_complete`, so the fold re-emits separators in the same order. */
+ turnIndex: number
+ /** True for the most recently completed turn. */
+ isLastTurn: boolean
+ /** The turn's assistant text, concatenated across its message bubbles. */
+ turnText: string
+}
+
+/**
+ * Maps each `turn_separator` item id to its turn's ordinal and assistant text. A separator marks
+ * the end of a completed turn, so a consumer can render per-turn UI (e.g. feedback actions) at
+ * the separator's position without the surface knowing what that UI is.
+ */
+export function computeTurnTrailers(threadItems: ThreadItem[]): Map<string, TurnTrailer> {
+ const trailers = new Map<string, TurnTrailer>()
+ let turnIndex = 0
+ let textParts: string[] = []
+ let lastSeparatorId: string | null = null
+ for (const item of threadItems) {
+ if (item.type === 'assistant_message' && item.text) {
+ textParts.push(item.text)
+ } else if (item.type === 'human_message') {
+ // A crashed turn never emits its separator; its text must not leak into the next turn.
+ textParts = []
+ } else if (item.type === 'turn_separator') {
+ trailers.set(item.id, { turnIndex, isLastTurn: false, turnText: textParts.join('\n\n') })
+ lastSeparatorId = item.id
+ turnIndex += 1
+ textParts = []
+ }
+ }
+ if (lastSeparatorId) {
+ const last = trailers.get(lastSeparatorId)
+ if (last) {
+ trailers.set(lastSeparatorId, { ...last, isLastTurn: true })
+ }
+ }
+ return trailers
+}