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(posthog-ai): fold turn suggestion frames into the run projection (#106434)

Rafael Audibertbcd15ac2306f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 19d265cca984..454b88c6c7cf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7207,9 +7207,9 @@ snapshots:
products-posthog-ai-threadview--execute-sql-with-variables--light:
hash: v1.k794b7964.7fc04cb62a05ca664d0a2520e44c2197502ae7bdcbebd5e65c6e1dc5aed12abe.pC_Qk-HoW9e7e1g1Vyn25RI91BJ1KrBuzn-E7zCDPkM
products-posthog-ai-threadview--message-footers--dark:
- hash: v1.k794b7964.98a468d1aceba1d27aec2233c7bb4a52f1dfd240d187c22a0824c0a85861de35.4sAdAbluBjr-spzgTlQ_9dkxnHsTU_NKSDYvxhx1i-Y
+ hash: v1.k794b7964.15817cfec2529b8ab4ec1175d2c5298d3fad0745d9e50fb4ca699b79b2facb3e.j_KPsiZmgkEa7qTomzkA74jV_HgUF2lJbX2IkVHUiLQ
products-posthog-ai-threadview--message-footers--light:
- hash: v1.k794b7964.e4840008ba9134a23f57c6c8a3ae714ed0f931adb828ace42410c8e9c2432687.yULknrQ7l7OiGWrFYkbCJ6SToSfqw9ClK1JTPQqjzm8
+ hash: v1.k794b7964.2c5c53c16a80a8a26d8b4da2d8f2747433cb0b2cb45c4cbf67d993a1f0a6ec17.ZVd7ZdV92JUzk5YZ9U2zAx3cgh20s9ylhUE1KK1UDS0
products-posthog-ai-threadview--saved-insight-query--dark:
hash: v1.k794b7964.ff266ce4b007479bd8156db3c4b65a91a8b987d226bfd7622b20085df50d5d1c.2IsZbL1hVZEqsqWd22bNC0XJvJSqSlXHKCc0LGtJzJc
products-posthog-ai-threadview--saved-insight-query--light:
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 888eaa34bf2f..157edc38884b 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -81,7 +81,7 @@ import {
ReasoningAnswer,
RecordingsWidget,
ThreadView,
- TurnFeedbackActions,
+ TurnTrailerActions,
type TurnTrailer,
useThreadSkin,
} from 'products/posthog_ai/frontend/api/primitives'
@@ -158,13 +158,7 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
const renderTurnTrailer = useCallback(
(trailer: TurnTrailer): JSX.Element | null =>
feedbackTaskId ? (
- <TurnFeedbackActions
- sessionId={feedbackTaskId}
- turnIndex={trailer.turnIndex}
- run={feedbackRun}
- traceId={trailer.traceId}
- turnText={trailer.turnText}
- />
+ <TurnTrailerActions trailer={trailer} sessionId={feedbackTaskId} run={feedbackRun} />
) : null,
[feedbackTaskId, feedbackRun]
)
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index 72d18fba4531..7a56f217cb50 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -46,7 +46,7 @@ export { ThreadView } from '../components/ThreadView'
export type { ThreadSkin } from '../components/quill/quillThreadContext'
export { useThreadSkin } from '../hooks/useThreadSkin'
export type { TurnTrailer } from '../utils/turnTrailers'
-export { TurnFeedbackActions } from '../components/TurnFeedbackActions'
+export { TurnTrailerActions } from '../components/TurnTrailerActions'
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 3ce0bba75cf5..939a844383fb 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -15,7 +15,7 @@ import { QuestionInput } from './QuestionInput'
import { QuillRunSurfaceInputs } from './quill/QuillRunSurfaceInputs'
import { RunLogSkeleton } from './RunLogSkeleton'
import { ThreadView } from './ThreadView'
-import { TurnFeedbackActions } from './TurnFeedbackActions'
+import { TurnTrailerActions } from './TurnTrailerActions'
export interface RunSurfaceProps {
taskId: string
@@ -229,14 +229,7 @@ function RunSurfaceThread({
const renderTurnTrailer = useCallback(
(trailer: TurnTrailer): JSX.Element | null =>
feedbackSessionId ? (
- <TurnFeedbackActions
- sessionId={feedbackSessionId}
- turnIndex={trailer.turnIndex}
- run={feedbackRun}
- traceId={trailer.traceId}
- turnText={trailer.turnText}
- timestamp={trailer.timestamp}
- />
+ <TurnTrailerActions trailer={trailer} sessionId={feedbackSessionId} run={feedbackRun} />
) : null,
[feedbackSessionId, feedbackRun]
)
diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsx
index 7cd4105ae847..c410f645e4aa 100644
--- a/products/posthog_ai/frontend/components/ThreadRow.tsx
+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx
@@ -8,14 +8,12 @@ import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'
-import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
-
import { DebugMessage } from '../messages/DebugMessage'
import { MarkdownMessage } from '../messages/MarkdownMessage'
import { MessageTemplate } from '../messages/MessageTemplate'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
import type { ProgressStep, ThreadItem, ToolInvocation } from '../types/streamTypes'
-import { resolveToolCall } from '../utils/toolResolver'
+import { toolInvocationToMessage } from '../utils/toolCallMessage'
import { userMessageDisplayText } from '../utils/userMessageDisplay'
import { Activity } from './ActivityPrimitives'
import { QuillAssistantMessage, QuillHumanMessage } from './quill/QuillMessages'
@@ -26,31 +24,6 @@ import { ThreadAttachments } from './ThreadAttachments'
import { CompactBoundaryItem, ConversationClearedItem, StatusItem, TaskNotificationItem } from './ThreadItems'
import { ToolCallCard } from './tool/ToolCallCard'
-/** Maps a raw merged `ToolInvocation` into the flat `ToolCallMessage` the registry renderers read. */
-function toolInvocationToMessage(invocation: ToolInvocation | undefined): ToolCallMessage | null {
- if (!invocation) {
- return null
- }
- const resolved = resolveToolCall(invocation)
- return {
- id: invocation.toolCallId,
- resolvedKey: resolved.resolvedKey,
- rawServerName: invocation.rawServerName,
- rawToolName: invocation.rawToolName,
- innerToolName: resolved.innerToolName,
- claudeToolName: resolved.claudeToolName,
- rawInput: invocation.input,
- innerInput: resolved.innerInput,
- rawOutput: invocation.output,
- content: invocation.contentBlocks,
- status: invocation.status,
- title: invocation.title,
- kind: invocation.kind,
- locations: invocation.locations,
- error: invocation.error,
- }
-}
-
function progressStepText(step: ProgressStep): string {
return step.detail ? `${step.label}\n\n${step.detail}` : step.label
}
diff --git a/products/posthog_ai/frontend/components/ThreadView.stories.tsx b/products/posthog_ai/frontend/components/ThreadView.stories.tsx
index 05450d118798..3934fa3321b9 100644
--- a/products/posthog_ai/frontend/components/ThreadView.stories.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.stories.tsx
@@ -165,7 +165,7 @@ function timedNotification(timestamp: string, method: string, params: Record<str
}
const MESSAGE_FOOTER_ENTRIES: StoredLogEntry[] = [
- timedNotification('2024-03-11T14:02:10Z', '_client/human_message', {
+ timedNotification('2024-03-11T14:02:10Z', '_posthog/user_message', {
content: 'How many users signed up last week?',
}),
timedNotification('2024-03-11T14:02:18Z', 'session/update', {
diff --git a/products/posthog_ai/frontend/components/TurnTrailerActions.tsx b/products/posthog_ai/frontend/components/TurnTrailerActions.tsx
new file mode 100644
index 000000000000..5f90393db27f
--- /dev/null
+++ b/products/posthog_ai/frontend/components/TurnTrailerActions.tsx
@@ -0,0 +1,28 @@
+import { memo } from 'react'
+
+import type { RunRef } from '../utils/feedbackEvents'
+import type { TurnTrailer } from '../utils/turnTrailers'
+import { TurnFeedbackActions } from './TurnFeedbackActions'
+
+export interface TurnTrailerActionsProps {
+ trailer: TurnTrailer
+ sessionId: string
+ run: RunRef
+}
+
+export const TurnTrailerActions = memo(function TurnTrailerActions({
+ trailer,
+ sessionId,
+ run,
+}: TurnTrailerActionsProps): JSX.Element {
+ return (
+ <TurnFeedbackActions
+ sessionId={sessionId}
+ turnIndex={trailer.turnIndex}
+ run={run}
+ traceId={trailer.traceId}
+ turnText={trailer.turnText}
+ timestamp={trailer.timestamp}
+ />
+ )
+})
diff --git a/products/posthog_ai/frontend/components/useTurnRating.ts b/products/posthog_ai/frontend/components/useTurnRating.ts
index a0af5b3a655a..d3f863669e12 100644
--- a/products/posthog_ai/frontend/components/useTurnRating.ts
+++ b/products/posthog_ai/frontend/components/useTurnRating.ts
@@ -18,7 +18,8 @@ export function useTurnRating({ sessionId, turnIndex, run, traceId }: TurnRating
} {
const { ratingForKey } = useValues(messageRatingsLogic)
const { setRating } = useActions(messageRatingsLogic)
- const ratingKey = `${sessionId}:turn-${turnIndex}`
+ // A trace id names one turn however the thread numbers its turns, so a stored rating stays on its answer.
+ const ratingKey = traceId ?? `${sessionId}:turn-${turnIndex}`
const rating = ratingForKey(ratingKey)
const [feedback, setFeedback] = useState<string>('')
const [feedbackInputStatus, setFeedbackInputStatus] = useState<TurnFeedbackInputStatus>('hidden')
diff --git a/products/posthog_ai/frontend/logics/messageRatingsLogic.ts b/products/posthog_ai/frontend/logics/messageRatingsLogic.ts
index 2d2a1d8bef16..d13dc7d29d89 100644
--- a/products/posthog_ai/frontend/logics/messageRatingsLogic.ts
+++ b/products/posthog_ai/frontend/logics/messageRatingsLogic.ts
@@ -47,8 +47,7 @@ export type messageRatingsLogicType = MakeLogicType<
/**
* 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>`.
+ * Keys are trace ids. A sandbox turn without a trace id uses `<conversationId>:turn-<n>`.
*/
export const messageRatingsLogic = kea<messageRatingsLogicType>([
path(['scenes', 'max', 'logics', 'messageRatingsLogic']),
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index d951a4835ea1..10b1691f5010 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -18,6 +18,7 @@ import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.
import { lookupToolRenderer, toolRegistry } from '../components/tool/toolRegistry'
import { extractQueryResult } from '../components/tool/widgets/extractors'
+import { turnSuggestionsStateRetrieve } from '../generated/api'
import { defaultPermissionDecision } from '../policy/toolPolicy'
import type { AttachedContextItem } from '../types/contextTypes'
import type { ThreadItem } from '../types/streamTypes'
@@ -25,6 +26,7 @@ import { TaskRunEnvironment, TaskRunStatus } from '../types/taskTypes'
import type { PermissionRequestFrame, StoredLogEntry } from '../types/wireTypes'
import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'
import { resolveToolCall } from '../utils/toolResolver'
+import { SUGGESTION_FRAMES } from '../utils/turnSuggestionFixtures'
import { computeTurnTrailers } from '../utils/turnTrailers'
import { attachedContextLogic } from './attachedContextLogic'
import {
@@ -51,6 +53,10 @@ import {
} from './runStreamLogic'
import { toolStreamEventsLogic } from './toolStreamEventsLogic'
+jest.mock('../generated/api', () => ({
+ turnSuggestionsStateRetrieve: jest.fn(),
+}))
+
jest.mock('products/tasks/frontend/generated/api', () => ({
tasksRunsRetrieve: jest.fn(),
tasksRunsCommandCreate: jest.fn(),
@@ -242,6 +248,7 @@ describe('runStreamLogic', () => {
.mockReset()
.mockResolvedValue({ status: 'in_progress' } as TaskRunDetailDTOApi)
jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
+ jest.mocked(turnSuggestionsStateRetrieve).mockReset().mockResolvedValue({ muted: false, resolved_turns: [] })
projectLogic.mount()
projectLogic.actions.loadCurrentProjectSuccess({ id: 997 } as any)
;(tasksRunsCommandCreate as jest.Mock)
@@ -290,6 +297,8 @@ describe('runStreamLogic', () => {
[sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'first answer' } }), 'replay'],
[notification('_client/human_message', { content: 'queued follow-up' }), 'live'],
[notification('_posthog/turn_complete', { traceId: 'trace-1' }), 'live'],
+ [notification('_posthog/turn_suggestion', SUGGESTION_FRAMES.scout), 'live'],
+ [notification('_posthog/turn_suggestion_resolved', { turnIndex: 0, outcome: 'accepted' }), 'live'],
[notification('_posthog/user_message', { content: 'queued follow-up' }), 'live'],
[sessionUpdate({ sessionUpdate: 'user_message_chunk', content: { text: 'queued follow-up' } }), 'live'],
[sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'slow', status: 'completed' }), 'live'],
@@ -318,6 +327,7 @@ describe('runStreamLogic', () => {
expect(resumed.folded).toEqual(foldLogToThread(log.entries, options))
})
expect(checkpoint!.entries.at(-1)?.entry.notification.params).toEqual({ traceId: 'trace-2' })
+ expect(foldLogToThread(log.entries, options).turnSuggestions.outcomes.get(0)).toEqual('accepted')
})
it.each([
@@ -5164,6 +5174,177 @@ describe('runStreamLogic', () => {
})
})
+ describe('_posthog/turn_suggestion', () => {
+ const suggestionParams = {
+ turnIndex: 0,
+ kind: 'scout',
+ intent: 'metric_state',
+ confidence: 0.9,
+ title: 'Get this in Slack every week',
+ description: 'A scout runs this analysis again every week and posts the results to Slack.',
+ scout: { displayName: 'Weekly signups', description: '', body: '# Weekly signups', cadence: 'weekly' },
+ }
+ const askAndOffer = (): void => {
+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'How many signups?' }))
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_suggestion', suggestionParams))
+ }
+
+ it('shows the newest valid offer and drops it on reset', async () => {
+ await expectLogic(logic, () => {
+ askAndOffer()
+ logic.actions.ingestAcpFrame(
+ notification('_posthog/turn_suggestion', { kind: 'notebook', turnIndex: 0 })
+ )
+ }).toFinishAllListeners()
+
+ expect(logic.values.turnSuggestion).toMatchObject({ kind: 'scout', scout: { cadence: 'weekly' } })
+
+ const shown = logic.values.turnSuggestion
+ logic.actions.ingestAcpFrame(
+ notification('session/update', {
+ update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'More' } },
+ })
+ )
+ expect(logic.values.turnSuggestion).toBe(shown)
+
+ logic.actions.reset()
+ expect(logic.values.turnSuggestion).toBeNull()
+ })
+
+ it('closes the offer when the conversation moves on and ignores frames for a passed turn', async () => {
+ await expectLogic(logic, askAndOffer).toFinishAllListeners()
+ expect(logic.values.turnSuggestion).toMatchObject({ kind: 'scout' })
+
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'And last month?' }))
+ }).toFinishAllListeners()
+ expect(logic.values.turnSuggestion).toBeNull()
+
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_suggestion', suggestionParams))
+ }).toFinishAllListeners()
+ expect(logic.values.turnSuggestion).toBeNull()
+
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(
+ notification('_posthog/turn_suggestion', { ...suggestionParams, turnIndex: 1 })
+ )
+ }).toFinishAllListeners()
+ expect(logic.values.turnSuggestion).toMatchObject({ turnIndex: 1 })
+ })
+
+ it.each([
+ { outcome: 'accepted', acceptedHere: true, shown: true, muted: false },
+ { outcome: 'accepted', acceptedHere: false, shown: false, muted: false },
+ { outcome: 'dismissed', acceptedHere: false, shown: false, muted: true },
+ ] as const)(
+ 'an $outcome frame (accepted in this tab: $acceptedHere) leaves the card shown: $shown, mutes: $muted',
+ async ({ outcome, acceptedHere, shown, muted }) => {
+ await expectLogic(logic, () => {
+ askAndOffer()
+ if (acceptedHere) {
+ logic.actions.markTurnSuggestionAccepted(0)
+ }
+ logic.actions.ingestAcpFrame(
+ notification('_posthog/turn_suggestion_resolved', { turnIndex: 0, outcome })
+ )
+ }).toFinishAllListeners()
+
+ expect(logic.values.turnSuggestion !== null).toBe(shown)
+ expect(logic.values.turnSuggestionsMuted).toBe(muted)
+ }
+ )
+
+ it.each([
+ ['the ledger resolved the turn', { muted: false, resolvedTurns: [0] }, null],
+ ['the ledger is muted', { muted: true, resolvedTurns: [] }, null],
+ ['this tab dismissed it before the ledger loaded', null, 'dismissed'],
+ [
+ 'this tab dismissed it and the ledger read landed after',
+ { muted: false, resolvedTurns: [] },
+ 'dismissed',
+ ],
+ ] as const)('hides the offer when %s', async (_label, ledger, localOutcome) => {
+ await expectLogic(logic, askAndOffer).toFinishAllListeners()
+ if (localOutcome) {
+ logic.actions.recordTurnSuggestionOutcome(0, localOutcome)
+ }
+ if (ledger) {
+ logic.actions.setTurnSuggestionLedger({
+ taskId: 'task-1',
+ ...ledger,
+ resolvedTurns: [...ledger.resolvedTurns],
+ })
+ }
+
+ expect(logic.values.turnSuggestion).toBeNull()
+ })
+
+ it('reads the server ledger once per task when the first offer arrives', async () => {
+ jest.mocked(turnSuggestionsStateRetrieve).mockResolvedValue({ muted: false, resolved_turns: [0] })
+
+ await expectLogic(logic, () => {
+ askAndOffer()
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_suggestion', suggestionParams))
+ }).toFinishAllListeners()
+
+ expect(turnSuggestionsStateRetrieve).toHaveBeenCalledTimes(1)
+ expect(turnSuggestionsStateRetrieve).toHaveBeenCalledWith('997', { task_id: 'task-1' })
+ expect(logic.values.turnSuggestion).toBeNull()
+ })
+
+ it('rereads the ledger when the tab returns, so a card resolved in another tab closes', async () => {
+ jest.mocked(turnSuggestionsStateRetrieve).mockResolvedValueOnce({ muted: false, resolved_turns: [] })
+ await expectLogic(logic, () => askAndOffer()).toDispatchActions(['setTurnSuggestionLedger'])
+ expect(logic.values.turnSuggestion).toMatchObject({ turnIndex: 0 })
+
+ jest.mocked(turnSuggestionsStateRetrieve).mockResolvedValueOnce({ muted: false, resolved_turns: [0] })
+ await expectLogic(logic, () => {
+ document.dispatchEvent(new Event('visibilitychange'))
+ }).toDispatchActions(['loadTurnSuggestionLedger', 'setTurnSuggestionLedger'])
+
+ expect(logic.values.turnSuggestion).toBeNull()
+ })
+
+ it('ignores an older ledger read that lands after a newer one', async () => {
+ jest.mocked(turnSuggestionsStateRetrieve).mockResolvedValueOnce({ muted: false, resolved_turns: [] })
+ await expectLogic(logic, () => askAndOffer()).toDispatchActions(['setTurnSuggestionLedger'])
+ let finishOlderRead: (state: { muted: boolean; resolved_turns: number[] }) => void = () => {}
+ jest.mocked(turnSuggestionsStateRetrieve)
+ .mockReturnValueOnce(new Promise((resolve) => (finishOlderRead = resolve)))
+ .mockResolvedValueOnce({ muted: false, resolved_turns: [0] })
+
+ await expectLogic(logic, () => {
+ document.dispatchEvent(new Event('visibilitychange'))
+ document.dispatchEvent(new Event('visibilitychange'))
+ }).toDispatchActions(['setTurnSuggestionLedger'])
+ finishOlderRead({ muted: false, resolved_turns: [] })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(turnSuggestionsStateRetrieve).toHaveBeenCalledTimes(3)
+ expect(logic.values.turnSuggestion).toBeNull()
+ })
+
+ it('keeps the offer hidden until the ledger loads, and retries a failed read', async () => {
+ jest.useFakeTimers()
+ try {
+ jest.mocked(turnSuggestionsStateRetrieve).mockRejectedValueOnce(new Error('offline'))
+
+ askAndOffer()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(logic.values.turnSuggestion).toBeNull()
+
+ await jest.advanceTimersByTimeAsync(1000)
+
+ expect(turnSuggestionsStateRetrieve).toHaveBeenCalledTimes(2)
+ expect(logic.values.turnSuggestion).toMatchObject({ kind: 'scout', turnIndex: 0 })
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+ })
+
describe('_posthog/sdk_session handling', () => {
it('stashes the adapter/session identity without rendering UI', async () => {
await expectLogic(logic, () => {
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index b0dc1dd0c561..508c69e9f5e7 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -22,6 +22,7 @@ import type {
import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'
import type { UserType } from '../../../../frontend/src/types'
+import { turnSuggestionsStateRetrieve } from '../generated/api'
import { deliverPermissionResponse, isPermissionTargetEnded } from '../policy/permissionDelivery'
import { isPlanPermissionRequest } from '../policy/permissionUtils'
import { parseSandboxQuestions } from '../policy/questionUtils'
@@ -50,6 +51,7 @@ import type {
ToolStreamEvent,
ToolStreamPhase,
TurnCompleteEvent,
+ TurnSuggestion,
} from '../types/streamTypes'
import {
type PermissionOption,
@@ -75,6 +77,7 @@ import {
import { extractContextBlockLines } from '../utils/posthogContextBlock'
import { reconcileThreadItems, reconcileToolInvocations } from '../utils/reconcileFoldedThread'
import { extractAgentToolName, getClaudeCodeMeta, resolveToolCall } from '../utils/toolResolver'
+import { parseTurnSuggestionParams } from '../utils/turnSuggestions'
import { computeTurnTrailers } from '../utils/turnTrailers'
import { attachedContextLogic } from './attachedContextLogic'
import { debugLogsLogic } from './debugLogsLogic'
@@ -1473,9 +1476,34 @@ function invocationFromToolCallUpdate(
}
}
+// Log entries are append-only, so a frame's params object is stable across folds; caching on it keeps
+// the offer's identity stable and the memoized trailer rows from re-rendering on every streamed frame.
+const TURN_SUGGESTION_LEDGER_ATTEMPTS = 3
+const TURN_SUGGESTION_LEDGER_RETRY_MS = 1000
+
+const parsedTurnSuggestions = new WeakMap<object, TurnSuggestion | null>()
+function parseTurnSuggestionFrame(params: object): TurnSuggestion | null {
+ if (!parsedTurnSuggestions.has(params)) {
+ parsedTurnSuggestions.set(params, parseTurnSuggestionParams(params))
+ }
+ return parsedTurnSuggestions.get(params) ?? null
+}
+
+export interface TurnSuggestionFold {
+ latest: TurnSuggestion | null
+ outcomes: Map<number, string>
+}
+
export interface FoldedThread {
threadItems: ThreadItem[]
toolInvocations: Map<string, ToolInvocation>
+ turnSuggestions: TurnSuggestionFold
+}
+
+export interface TurnSuggestionLedger {
+ taskId: string
+ muted: boolean
+ resolvedTurns: number[]
}
export interface PendingRunMessage {
@@ -1511,6 +1539,7 @@ export interface FoldCheckpoint {
options: FoldOptions
items: ThreadItem[]
invocations: Map<string, ToolInvocation>
+ turnSuggestions: TurnSuggestionFold
rememberedHumanTexts: Map<string, number>
waitingSends: { id: string; text: string; turns: number }[]
pairedSends: Map<string, number>
@@ -1586,6 +1615,10 @@ export function foldLogFromCheckpoint(
let nextCheckpoint = resume && resume.entries.length - 1 === checkpointIndex ? resume : null
let items: ThreadItem[] = resume ? [...resume.items] : []
const invocations = new Map<string, ToolInvocation>(resume?.invocations)
+ const turnSuggestions: TurnSuggestionFold = {
+ latest: resume?.turnSuggestions.latest ?? null,
+ outcomes: new Map(resume?.turnSuggestions.outcomes),
+ }
// Texts already rendered by a `_posthog/user_message`, so a later identical `user_message_chunk`
// (resume chains persist the same turn in both forms) is consumed once rather than doubled.
const rememberedHumanTexts = new Map<string, number>(resume?.rememberedHumanTexts)
@@ -1687,6 +1720,7 @@ export function foldLogFromCheckpoint(
options,
items: [...items],
invocations: new Map(invocations),
+ turnSuggestions: { latest: turnSuggestions.latest, outcomes: new Map(turnSuggestions.outcomes) },
rememberedHumanTexts: new Map(rememberedHumanTexts),
waitingSends: waitingSends.map((send) => ({ ...send })),
pairedSends: new Map(pairedSends),
@@ -1960,6 +1994,16 @@ export function foldLogFromCheckpoint(
)
continue
}
+ if (method === '_posthog/turn_suggestion') {
+ turnSuggestions.latest = parseTurnSuggestionFrame(params) ?? turnSuggestions.latest
+ continue
+ }
+ if (method === '_posthog/turn_suggestion_resolved') {
+ if (typeof params.turnIndex === 'number' && typeof params.outcome === 'string') {
+ turnSuggestions.outcomes.set(params.turnIndex, params.outcome)
+ }
+ continue
+ }
if (method === '_posthog/turn_complete') {
const traceId = typeof params.traceId === 'string' ? params.traceId : undefined
items.push({
@@ -2212,7 +2256,10 @@ export function foldLogFromCheckpoint(
complete: true,
})
}
- return { folded: { threadItems: items, toolInvocations: invocations }, checkpoint: nextCheckpoint }
+ return {
+ folded: { threadItems: items, toolInvocations: invocations, turnSuggestions },
+ checkpoint: nextCheckpoint,
+ }
}
/**
@@ -2292,6 +2339,11 @@ export interface runStreamLogicValues {
toolInvocations: Map<string, ToolInvocation>
traceId: string | null
turnComplete: boolean
+ turnSuggestion: TurnSuggestion | null
+ turnSuggestionAcceptedHere: number | null
+ turnSuggestionLedger: TurnSuggestionLedger | null
+ turnSuggestionOutcomesHere: Record<number, string>
+ turnSuggestionsMuted: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -2405,6 +2457,13 @@ export interface runStreamLogicActions {
record: PermissionRequestRecord
replayedFromHistory: boolean
}
+ loadTurnSuggestionLedger: (
+ taskId: string,
+ attempt?: number
+ ) => {
+ attempt: number
+ taskId: string
+ }
markBootstrapResumeRun: (value: boolean) => {
value: boolean
}
@@ -2423,6 +2482,9 @@ export interface runStreamLogicActions {
markTurnStarted: () => {
value: true
}
+ markTurnSuggestionAccepted: (turnIndex: number) => {
+ turnIndex: number
+ }
mergeRunArtifacts: (partial: Partial<RunArtifacts>) => {
partial: Partial<RunArtifacts>
}
@@ -2458,6 +2520,13 @@ export interface runStreamLogicActions {
content: string
stagedAttachments: StagedAttachment[] | undefined
}
+ recordTurnSuggestionOutcome: (
+ turnIndex: number,
+ outcome: string
+ ) => {
+ outcome: string
+ turnIndex: number
+ }
recoveryProgress: (
phase: RecoveryPhase,
attempt: number,
@@ -2536,6 +2605,9 @@ export interface runStreamLogicActions {
setStreamHasEnded: (ended: boolean) => {
ended: boolean
}
+ setTurnSuggestionLedger: (ledger: TurnSuggestionLedger) => {
+ ledger: TurnSuggestionLedger
+ }
sseConnecting: () => {
value: true
}
@@ -2582,6 +2654,20 @@ export interface runStreamLogicMeta {
bootstrappedTaskId: string | null
) => FoldedThread
errorTraceIds: (threadItems: ThreadItem[]) => Map<string, string>
+ turnSuggestionsMuted: (
+ foldedThread: FoldedThread,
+ turnSuggestionLedger: TurnSuggestionLedger | null,
+ turnSuggestionOutcomesHere: Record<number, string>
+ ) => boolean
+ turnSuggestion: (
+ foldedThread: FoldedThread,
+ threadItems: ThreadItem[],
+ turnSuggestionLedger: TurnSuggestionLedger | null,
+ turnSuggestionOutcomesHere: Record<number, string>,
+ turnSuggestionAcceptedHere: number | null,
+ turnSuggestionsMuted: boolean,
+ bootstrappedTaskId: string | null
+ ) => TurnSuggestion | null
latestTurnTraceId: (threadItems: ThreadItem[]) => string | null
threadItems: (foldedThread: FoldedThread, showDebugLogs: boolean) => ThreadItem[]
hasThreadItems: (threadItems: ThreadItem[]) => boolean
@@ -2817,6 +2903,11 @@ export const runStreamLogic = kea<runStreamLogicType>([
/** Records the agent's `/clear` capability, read off each `_posthog/run_started` frame. */
setConversationClearSupported: (supported: boolean) => ({ supported }),
markTurnComplete: (isReplay: boolean = false) => ({ isReplay }),
+ setTurnSuggestionLedger: (ledger: TurnSuggestionLedger) => ({ ledger }),
+ loadTurnSuggestionLedger: (taskId: string, attempt: number = 0) => ({ taskId, attempt }),
+ /** Records an outcome this tab sent to the server, so the card closes before the frame echoes back. */
+ recordTurnSuggestionOutcome: (turnIndex: number, outcome: string) => ({ turnIndex, outcome }),
+ markTurnSuggestionAccepted: (turnIndex: number) => ({ turnIndex }),
/**
* Reopens the turn for a follow-up that started outside this composer, such as one sent from Slack
* or from another tab. Dispatched from a user turn seen on the wire, and from the agent's first
@@ -3189,6 +3280,31 @@ export const runStreamLogic = kea<runStreamLogicType>([
setConversationClearSupported: (_, { supported }) => supported,
},
],
+ turnSuggestionLedger: [
+ null as TurnSuggestionLedger | null,
+ {
+ setTurnSuggestionLedger: (_, { ledger }) => ledger,
+ reset: () => null,
+ },
+ ],
+ // Kept apart from the ledger because the ledger read can land after this tab resolved a card,
+ // and replacing the ledger then must not drop the outcome.
+ turnSuggestionOutcomesHere: [
+ {} as Record<number, string>,
+ {
+ recordTurnSuggestionOutcome: (state, { turnIndex, outcome }) => ({ ...state, [turnIndex]: outcome }),
+ reset: () => ({}),
+ },
+ ],
+ // The turn whose card this tab accepted. That card stays up to show what it created, while
+ // every other tab hides it so a second accept cannot create a duplicate.
+ turnSuggestionAcceptedHere: [
+ null as number | null,
+ {
+ markTurnSuggestionAccepted: (_, { turnIndex }) => turnIndex,
+ reset: () => null,
+ },
+ ],
turnComplete: [
false,
{
@@ -3271,6 +3387,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
const reconciled: FoldedThread = {
threadItems: reconcileThreadItems(previous?.threadItems, folded.threadItems),
toolInvocations: reconcileToolInvocations(previous?.toolInvocations, folded.toolInvocations),
+ turnSuggestions: folded.turnSuggestions,
}
if (checkpoint && checkpoint !== previousCheckpoint) {
checkpoint.items = reconcileThreadItems(reconciled.threadItems, checkpoint.items)
@@ -3310,6 +3427,58 @@ export const runStreamLogic = kea<runStreamLogicType>([
return result
},
],
+ turnSuggestionsMuted: [
+ (s) => [s.foldedThread, s.turnSuggestionLedger, s.turnSuggestionOutcomesHere],
+ (
+ foldedThread: FoldedThread,
+ ledger: TurnSuggestionLedger | null,
+ outcomesHere: Record<number, string>
+ ): boolean =>
+ !!ledger?.muted ||
+ [...foldedThread.turnSuggestions.outcomes.values(), ...Object.values(outcomesHere)].includes(
+ 'dismissed'
+ ),
+ ],
+ turnSuggestion: [
+ (s) => [
+ s.foldedThread,
+ s.threadItems,
+ s.turnSuggestionLedger,
+ s.turnSuggestionOutcomesHere,
+ s.turnSuggestionAcceptedHere,
+ s.turnSuggestionsMuted,
+ s.bootstrappedTaskId,
+ ],
+ (
+ foldedThread: FoldedThread,
+ threadItems: ThreadItem[],
+ ledger: TurnSuggestionLedger | null,
+ outcomesHere: Record<number, string>,
+ acceptedHere: number | null,
+ muted: boolean,
+ taskId: string | null
+ ): TurnSuggestion | null => {
+ const offer = foldedThread.turnSuggestions.latest
+ // The classifier runs after the answer, so an offer can land once the user already sent
+ // the next message; it belongs to the answer above it and closes when the thread moves on.
+ const latestPromptIndex = threadItems.filter((item) => item.type === 'human_message').length - 1
+ if (!offer || offer.turnIndex !== latestPromptIndex) {
+ return null
+ }
+ if (acceptedHere === offer.turnIndex) {
+ return offer
+ }
+ // Resolutions reach the log only while a tab is open, so a replayed offer waits for the ledger.
+ if (!ledger || (taskId !== null && ledger.taskId !== taskId)) {
+ return null
+ }
+ const resolved =
+ foldedThread.turnSuggestions.outcomes.has(offer.turnIndex) ||
+ offer.turnIndex in outcomesHere ||
+ ledger.resolvedTurns.includes(offer.turnIndex)
+ return muted || resolved ? null : offer
+ },
+ ],
latestTurnTraceId: [
(s) => [s.threadItems],
(threadItems: ThreadItem[]): string | null => {
@@ -3837,6 +4006,39 @@ export const runStreamLogic = kea<runStreamLogicType>([
cache.recoveryStartedAt = Date.now()
actions.bootstrapRun({ taskId: previous.taskId, runId: previous.runId })
},
+ loadTurnSuggestionLedger: async ({ taskId, attempt }) => {
+ const projectId = values.currentProjectId
+ if (!projectId || values.bootstrappedTaskId !== taskId) {
+ return
+ }
+ // The first read and a visibility refresh can overlap, and an older snapshot that lands
+ // last would bring back a card the newer one resolved.
+ const request = (cache.turnSuggestionLedgerRequest = (cache.turnSuggestionLedgerRequest ?? 0) + 1)
+ try {
+ const state = await turnSuggestionsStateRetrieve(String(projectId), { task_id: taskId })
+ if (request !== cache.turnSuggestionLedgerRequest) {
+ return
+ }
+ if (values.bootstrappedTaskId === taskId) {
+ actions.setTurnSuggestionLedger({
+ taskId,
+ muted: state.muted,
+ resolvedTurns: state.resolved_turns,
+ })
+ }
+ } catch {
+ // The card stays hidden while the ledger is unknown, so a failed read retries a few times.
+ if (attempt + 1 < TURN_SUGGESTION_LEDGER_ATTEMPTS && values.bootstrappedTaskId === taskId) {
+ cache.disposables.add(() => {
+ const timer = setTimeout(
+ () => actions.loadTurnSuggestionLedger(taskId, attempt + 1),
+ TURN_SUGGESTION_LEDGER_RETRY_MS * 2 ** attempt
+ )
+ return () => clearTimeout(timer)
+ }, 'turnSuggestionLedgerRetry')
+ }
+ }
+ },
openSseForRun: ({ taskId, runId }) => {
if (props.replayOnly) {
return
@@ -4496,6 +4698,9 @@ export const runStreamLogic = kea<runStreamLogicType>([
// `log` clears via its own reducer on `reset`, so the projection empties with it. The
// per-frame invocation tracker mirrors the log, so it must clear alongside it.
cache.trackedToolInvocations = undefined
+ cache.turnSuggestionLedgerTaskId = null
+ cache.disposables.dispose('turnSuggestionLedgerRetry')
+ cache.disposables.dispose('turnSuggestionLedgerRefresh')
cache.permissionRunId = undefined
cache.activeRun = undefined
cache.turnStartedAtMs = undefined
@@ -4704,6 +4909,35 @@ export const runStreamLogic = kea<runStreamLogicType>([
actions.markRunStarted()
return
}
+ if (method === '_posthog/turn_suggestion') {
+ // The log holds only outcomes this tab saw live; the ledger adds the ones sent while
+ // no tab of this conversation was open. Read once per task, when it first has an offer.
+ const taskId = values.bootstrappedTaskId
+ if (taskId && cache.turnSuggestionLedgerTaskId !== taskId) {
+ cache.turnSuggestionLedgerTaskId = taskId
+ actions.loadTurnSuggestionLedger(taskId)
+ // Another tab's resolution reaches this one only as a live frame, which can be
+ // lost, so a returning tab rereads the ledger while it shows a card.
+ cache.disposables.add(
+ () => {
+ const onVisibilityChange = (): void => {
+ if (
+ document.visibilityState === 'visible' &&
+ values.turnSuggestion &&
+ values.bootstrappedTaskId === taskId
+ ) {
+ actions.loadTurnSuggestionLedger(taskId)
+ }
+ }
+ document.addEventListener('visibilitychange', onVisibilityChange)
+ return () => document.removeEventListener('visibilitychange', onVisibilityChange)
+ },
+ 'turnSuggestionLedgerRefresh',
+ { pauseOnPageHidden: false }
+ )
+ }
+ return
+ }
if (method === '_posthog/turn_complete') {
if (!isReplay) {
actions.emitTurnCompleteEvent({ streamKey: props.streamKey })
diff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.ts
index 30e853a9796c..4439010445ad 100644
--- a/products/posthog_ai/frontend/types/streamTypes.ts
+++ b/products/posthog_ai/frontend/types/streamTypes.ts
@@ -283,3 +283,93 @@ export interface PermissionRequestRecord {
*/
questions?: AgentQuestion[]
}
+
+export const SCOUT_CADENCES = ['daily', 'weekly'] as const
+export type ScoutSuggestionCadence = (typeof SCOUT_CADENCES)[number]
+
+export const SCOUT_MODES = ['report', 'watch', 'investigate', 'digest'] as const
+export type ScoutSuggestionMode = (typeof SCOUT_MODES)[number]
+
+export const ALERT_DIRECTIONS = ['decrease', 'increase'] as const
+export type AlertSuggestionDirection = (typeof ALERT_DIRECTIONS)[number]
+
+export interface ScoutSuggestionDraft {
+ mode: ScoutSuggestionMode
+ displayName: string
+ description: string
+ body: string
+ cadence: ScoutSuggestionCadence
+}
+
+export interface IncidentOutline {
+ timeline: string
+ cause: string
+ fix: string
+}
+
+export interface NotebookSuggestionDraft {
+ title: string
+ summary: string
+ /** Present when the notebook is laid out as an incident write-up rather than the conversation as is. */
+ incident: IncidentOutline | null
+}
+
+export interface SuggestedInsightRef {
+ insightShortId: string
+ insightId: number | null
+ insightName: string
+}
+
+export interface AlertSuggestionDraft extends SuggestedInsightRef {
+ direction: AlertSuggestionDirection
+ changePercent: number
+}
+
+export interface SubscriptionSuggestionDraft extends SuggestedInsightRef {
+ cadence: ScoutSuggestionCadence
+}
+
+export interface ErrorAlertSuggestionDraft {
+ issueId: string
+ issueName: string
+}
+
+interface TurnSuggestionBase {
+ turnIndex: number
+ intent: string
+ confidence: number
+ title: string
+ description: string
+}
+
+export interface ScoutTurnSuggestion extends TurnSuggestionBase {
+ kind: 'scout'
+ scout: ScoutSuggestionDraft
+}
+
+export interface NotebookTurnSuggestion extends TurnSuggestionBase {
+ kind: 'notebook'
+ notebook: NotebookSuggestionDraft
+}
+
+export interface AlertTurnSuggestion extends TurnSuggestionBase {
+ kind: 'alert'
+ alert: AlertSuggestionDraft
+}
+
+export interface SubscriptionTurnSuggestion extends TurnSuggestionBase {
+ kind: 'subscription'
+ subscription: SubscriptionSuggestionDraft
+}
+
+export interface ErrorAlertTurnSuggestion extends TurnSuggestionBase {
+ kind: 'error_alert'
+ errorAlert: ErrorAlertSuggestionDraft
+}
+
+export type TurnSuggestion =
+ | ScoutTurnSuggestion
+ | NotebookTurnSuggestion
+ | AlertTurnSuggestion
+ | SubscriptionTurnSuggestion
+ | ErrorAlertTurnSuggestion
diff --git a/products/posthog_ai/frontend/types/wireTypes.test.ts b/products/posthog_ai/frontend/types/wireTypes.test.ts
index f130db648bc5..dbee5fe29188 100644
--- a/products/posthog_ai/frontend/types/wireTypes.test.ts
+++ b/products/posthog_ai/frontend/types/wireTypes.test.ts
@@ -130,6 +130,23 @@ const NOTIFICATION_PARAMS_BY_METHOD: { [M in keyof PosthogNotificationParamsByMe
'_posthog/permission_resolved': [{ requestId: 'perm-1', toolCallId: 'toolu_01', optionId: 'allow_once' }],
'_posthog/run_started': [{ sessionId: 'sess_a1b2c3', runId: RUN_ID, taskId: TASK_ID, agentVersion: '1.42.0' }],
'_posthog/turn_complete': [{ sessionId: 'sess_a1b2c3', stopReason: 'end_turn' }],
+ '_posthog/turn_suggestion': [
+ {
+ turnIndex: 0,
+ kind: 'scout',
+ intent: 'metric_state',
+ confidence: 0.92,
+ title: 'Get this in Slack every week',
+ description: 'A scout runs this analysis again every week and posts the results to Slack.',
+ scout: {
+ displayName: 'Weekly signups',
+ description: 'Counts signed_up events for the last 7 days.',
+ body: '# Weekly signups\n\nCount signed_up events for the last 7 days.',
+ cadence: 'weekly',
+ },
+ },
+ ],
+ '_posthog/turn_suggestion_resolved': [{ turnIndex: 0, outcome: 'dismissed' }],
}
const KNOWN_POSTHOG_METHODS = Object.keys(NOTIFICATION_PARAMS_BY_METHOD) as (keyof PosthogNotificationParamsByMethod)[]
diff --git a/products/posthog_ai/frontend/types/wireTypes.ts b/products/posthog_ai/frontend/types/wireTypes.ts
index 1c6b78dc200e..654b86c0aaab 100644
--- a/products/posthog_ai/frontend/types/wireTypes.ts
+++ b/products/posthog_ai/frontend/types/wireTypes.ts
@@ -445,6 +445,42 @@ export interface PosthogTurnCompleteParams {
traceId?: string
}
+export interface SuggestedInsightRefParams {
+ insightShortId?: string
+ insightId?: number | null
+ insightName?: string
+}
+
+/** Loose on purpose: the fold validates it. */
+export interface PosthogTurnSuggestionParams {
+ turnIndex?: number
+ kind?: string
+ intent?: string
+ confidence?: number
+ title?: string
+ description?: string
+ scout?: {
+ mode?: string
+ displayName?: string
+ description?: string
+ body?: string
+ cadence?: string
+ }
+ notebook?: {
+ title?: string
+ summary?: string
+ incident?: { timeline?: string; cause?: string; fix?: string } | null
+ }
+ alert?: SuggestedInsightRefParams & { direction?: string; changePercent?: number }
+ subscription?: SuggestedInsightRefParams & { cadence?: string }
+ errorAlert?: { issueId?: string; issueName?: string }
+}
+
+export interface PosthogTurnSuggestionResolvedParams {
+ turnIndex?: number
+ outcome?: string
+}
+
export interface PosthogNotificationParamsByMethod {
'_posthog/console': PosthogConsoleParams
'_posthog/progress': PosthogProgressParams
@@ -462,6 +498,8 @@ export interface PosthogNotificationParamsByMethod {
'_posthog/permission_resolved': PosthogPermissionResolvedParams
'_posthog/run_started': PosthogRunStartedParams
'_posthog/turn_complete': PosthogTurnCompleteParams
+ '_posthog/turn_suggestion': PosthogTurnSuggestionParams
+ '_posthog/turn_suggestion_resolved': PosthogTurnSuggestionResolvedParams
}
/**
diff --git a/products/posthog_ai/frontend/utils/toolCallMessage.ts b/products/posthog_ai/frontend/utils/toolCallMessage.ts
new file mode 100644
index 000000000000..df45d6a80d43
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/toolCallMessage.ts
@@ -0,0 +1,28 @@
+import type { ToolInvocation } from '../types/streamTypes'
+import type { ToolCallMessage } from '../types/toolTypes'
+import { resolveToolCall } from './toolResolver'
+
+/** Maps a raw merged `ToolInvocation` into the flat `ToolCallMessage` the registry renderers read. */
+export function toolInvocationToMessage(invocation: ToolInvocation | undefined): ToolCallMessage | null {
+ if (!invocation) {
+ return null
+ }
+ const resolved = resolveToolCall(invocation)
+ return {
+ id: invocation.toolCallId,
+ resolvedKey: resolved.resolvedKey,
+ rawServerName: invocation.rawServerName,
+ rawToolName: invocation.rawToolName,
+ innerToolName: resolved.innerToolName,
+ claudeToolName: resolved.claudeToolName,
+ rawInput: invocation.input,
+ innerInput: resolved.innerInput,
+ rawOutput: invocation.output,
+ content: invocation.contentBlocks,
+ status: invocation.status,
+ title: invocation.title,
+ kind: invocation.kind,
+ locations: invocation.locations,
+ error: invocation.error,
+ }
+}
diff --git a/products/posthog_ai/frontend/utils/turnSuggestionFixtures.ts b/products/posthog_ai/frontend/utils/turnSuggestionFixtures.ts
new file mode 100644
index 000000000000..80e081d795f3
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/turnSuggestionFixtures.ts
@@ -0,0 +1,33 @@
+import type { TurnSuggestion } from '../types/streamTypes'
+
+export const BASE = {
+ turnIndex: 0,
+ intent: 'metric_state',
+ confidence: 0.9,
+ title: 'Get this in Slack every week',
+ description: 'A scout runs this analysis again every week and posts the results to Slack.',
+}
+
+export const SCOUT = {
+ mode: 'report',
+ displayName: 'Weekly signups',
+ description: 'Counts signed_up events for the last 7 days.',
+ body: '# Weekly signups\n\nQuery signed_up for the last 7 days.',
+ cadence: 'weekly',
+}
+
+export const INSIGHT = { insightShortId: 'abc123', insightId: 42, insightName: 'Signups' }
+
+export const INCIDENT_NOTEBOOK = {
+ title: 'Why signups dropped on Tuesday',
+ summary: 'A checkout error was the cause.',
+ incident: { timeline: '- 14:10 release', cause: 'Checkout error.', fix: 'Rolled back.' },
+}
+
+export const SUGGESTION_FRAMES: Record<TurnSuggestion['kind'], Record<string, unknown>> = {
+ scout: { ...BASE, kind: 'scout', scout: SCOUT },
+ notebook: { ...BASE, kind: 'notebook', notebook: INCIDENT_NOTEBOOK },
+ alert: { ...BASE, kind: 'alert', alert: { ...INSIGHT, direction: 'decrease', changePercent: 20.4 } },
+ subscription: { ...BASE, kind: 'subscription', subscription: { ...INSIGHT, cadence: 'weekly' } },
+ error_alert: { ...BASE, kind: 'error_alert', errorAlert: { issueId: 'issue-1', issueName: 'Checkout error' } },
+}
diff --git a/products/posthog_ai/frontend/utils/turnSuggestions.test.ts b/products/posthog_ai/frontend/utils/turnSuggestions.test.ts
new file mode 100644
index 000000000000..e285eea0abb1
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/turnSuggestions.test.ts
@@ -0,0 +1,58 @@
+import type { TurnSuggestion } from '../types/streamTypes'
+import { BASE, INCIDENT_NOTEBOOK, INSIGHT, SCOUT, SUGGESTION_FRAMES } from './turnSuggestionFixtures'
+import { parseTurnSuggestionParams } from './turnSuggestions'
+
+describe('turnSuggestions', () => {
+ test.each([
+ ['an unknown kind', { ...SUGGESTION_FRAMES.scout, kind: 'dashboard' }],
+ ['a notebook without a title', { ...SUGGESTION_FRAMES.notebook, notebook: { title: ' ', summary: 'x' } }],
+ ['a missing turn index', { ...SUGGESTION_FRAMES.scout, turnIndex: undefined }],
+ ['an empty title', { ...SUGGESTION_FRAMES.scout, title: ' ' }],
+ ['a missing description', { ...SUGGESTION_FRAMES.scout, description: undefined }],
+ ['an empty scout prompt', { ...SUGGESTION_FRAMES.scout, scout: { ...SCOUT, body: ' ' } }],
+ ['an unknown cadence', { ...SUGGESTION_FRAMES.scout, scout: { ...SCOUT, cadence: 'hourly' } }],
+ [
+ 'an alert without an insight',
+ { ...SUGGESTION_FRAMES.alert, alert: { direction: 'decrease', changePercent: 20 } },
+ ],
+ [
+ 'an alert with an unknown direction',
+ { ...SUGGESTION_FRAMES.alert, alert: { ...INSIGHT, direction: 'either' } },
+ ],
+ [
+ 'an alert without a positive bound',
+ { ...SUGGESTION_FRAMES.alert, alert: { ...INSIGHT, direction: 'decrease', changePercent: 0 } },
+ ],
+ [
+ 'an alert whose bound rounds to zero',
+ { ...SUGGESTION_FRAMES.alert, alert: { ...INSIGHT, direction: 'decrease', changePercent: 0.3 } },
+ ],
+ ['a subscription without a cadence', { ...SUGGESTION_FRAMES.subscription, subscription: INSIGHT }],
+ ['an error alert without an issue', { ...SUGGESTION_FRAMES.error_alert, errorAlert: { issueName: 'x' } }],
+ ['a non-object frame', 'scout'],
+ ])('parseTurnSuggestionParams drops a frame with %s', (_label, params) => {
+ expect(parseTurnSuggestionParams(params)).toBeNull()
+ })
+
+ test.each<[TurnSuggestion['kind'], Record<string, unknown>]>([
+ ['scout', { scout: SCOUT }],
+ ['notebook', { notebook: INCIDENT_NOTEBOOK }],
+ ['alert', { alert: { ...INSIGHT, direction: 'decrease', changePercent: 20 } }],
+ ['subscription', { subscription: { ...INSIGHT, cadence: 'weekly' } }],
+ ['error_alert', { errorAlert: { issueId: 'issue-1', issueName: 'Checkout error' } }],
+ ])('parseTurnSuggestionParams keeps a %s frame with its draft', (kind, draft) => {
+ expect(parseTurnSuggestionParams(SUGGESTION_FRAMES[kind])).toEqual({ ...BASE, kind, ...draft })
+ })
+
+ it('parseTurnSuggestionParams fills in the scout mode, and needs a cause for an incident', () => {
+ expect(
+ parseTurnSuggestionParams({ ...SUGGESTION_FRAMES.scout, scout: { ...SCOUT, mode: undefined } })
+ ).toMatchObject({ scout: { mode: 'report' } })
+ expect(
+ parseTurnSuggestionParams({
+ ...SUGGESTION_FRAMES.notebook,
+ notebook: { title: 'Why', summary: '', incident: { timeline: '- 14:10', cause: '', fix: '' } },
+ })
+ ).toMatchObject({ notebook: { incident: null } })
+ })
+})
diff --git a/products/posthog_ai/frontend/utils/turnSuggestions.ts b/products/posthog_ai/frontend/utils/turnSuggestions.ts
new file mode 100644
index 000000000000..a64e29d77b6d
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/turnSuggestions.ts
@@ -0,0 +1,186 @@
+import {
+ ALERT_DIRECTIONS,
+ type AlertSuggestionDirection,
+ type AlertSuggestionDraft,
+ type ErrorAlertSuggestionDraft,
+ type IncidentOutline,
+ type NotebookSuggestionDraft,
+ SCOUT_CADENCES,
+ SCOUT_MODES,
+ type ScoutSuggestionCadence,
+ type ScoutSuggestionDraft,
+ type ScoutSuggestionMode,
+ type SubscriptionSuggestionDraft,
+ type SuggestedInsightRef,
+ type TurnSuggestion,
+} from '../types/streamTypes'
+import type { PosthogTurnSuggestionParams, SuggestedInsightRefParams } from '../types/wireTypes'
+
+export const CADENCE_OPTIONS: { value: ScoutSuggestionCadence; label: string }[] = [
+ { value: 'daily', label: 'Every day' },
+ { value: 'weekly', label: 'Every week' },
+]
+
+export const ALERT_DIRECTION_OPTIONS: { value: AlertSuggestionDirection; label: string }[] = [
+ { value: 'decrease', label: 'Drops' },
+ { value: 'increase', label: 'Rises' },
+]
+
+export const SCOUT_MODE_HINTS: Record<ScoutSuggestionMode, string | null> = {
+ report: null,
+ watch: 'Posts only when the number crosses a threshold.',
+ investigate: 'When the metric drops, runs this investigation again and posts what it finds.',
+ digest: 'Posts every metric from this conversation together.',
+}
+
+function isOneOf<T extends string>(table: readonly T[], value: unknown): value is T {
+ return typeof value === 'string' && (table as readonly string[]).includes(value)
+}
+
+function nonEmptyString(value: unknown): value is string {
+ return typeof value === 'string' && value.trim().length > 0
+}
+
+const TURN_SUGGESTION_KINDS: readonly TurnSuggestion['kind'][] = [
+ 'scout',
+ 'notebook',
+ 'alert',
+ 'subscription',
+ 'error_alert',
+]
+
+function parseScoutDraft(scout: PosthogTurnSuggestionParams['scout']): ScoutSuggestionDraft | null {
+ if (
+ !scout ||
+ !nonEmptyString(scout.displayName) ||
+ !nonEmptyString(scout.body) ||
+ !isOneOf(SCOUT_CADENCES, scout.cadence)
+ ) {
+ return null
+ }
+ return {
+ // Frames persisted before scouts had modes carry none; those were all plain reports.
+ mode: isOneOf(SCOUT_MODES, scout.mode) ? scout.mode : 'report',
+ displayName: scout.displayName,
+ description: nonEmptyString(scout.description) ? scout.description : '',
+ body: scout.body,
+ cadence: scout.cadence,
+ }
+}
+
+function parseIncident(
+ incident: NonNullable<PosthogTurnSuggestionParams['notebook']>['incident']
+): IncidentOutline | null {
+ if (!incident || !nonEmptyString(incident.cause)) {
+ return null
+ }
+ return {
+ timeline: nonEmptyString(incident.timeline) ? incident.timeline : '',
+ cause: incident.cause,
+ fix: nonEmptyString(incident.fix) ? incident.fix : '',
+ }
+}
+
+function parseNotebookDraft(notebook: PosthogTurnSuggestionParams['notebook']): NotebookSuggestionDraft | null {
+ if (!notebook || !nonEmptyString(notebook.title)) {
+ return null
+ }
+ return {
+ title: notebook.title,
+ summary: nonEmptyString(notebook.summary) ? notebook.summary : '',
+ incident: parseIncident(notebook.incident),
+ }
+}
+
+function parseInsightRef(insight: SuggestedInsightRefParams | undefined): SuggestedInsightRef | null {
+ if (!insight || !nonEmptyString(insight.insightShortId)) {
+ return null
+ }
+ return {
+ insightShortId: insight.insightShortId,
+ insightId: typeof insight.insightId === 'number' ? insight.insightId : null,
+ insightName: nonEmptyString(insight.insightName) ? insight.insightName : 'this insight',
+ }
+}
+
+function parseAlertDraft(alert: PosthogTurnSuggestionParams['alert']): AlertSuggestionDraft | null {
+ const insight = parseInsightRef(alert)
+ if (!insight || !alert || !isOneOf(ALERT_DIRECTIONS, alert.direction)) {
+ return null
+ }
+ const changePercent = typeof alert.changePercent === 'number' ? Math.round(alert.changePercent) : NaN
+ if (!(changePercent > 0)) {
+ return null
+ }
+ return { ...insight, direction: alert.direction, changePercent }
+}
+
+function parseSubscriptionDraft(
+ subscription: PosthogTurnSuggestionParams['subscription']
+): SubscriptionSuggestionDraft | null {
+ const insight = parseInsightRef(subscription)
+ if (!insight || !subscription || !isOneOf(SCOUT_CADENCES, subscription.cadence)) {
+ return null
+ }
+ return { ...insight, cadence: subscription.cadence }
+}
+
+function parseErrorAlertDraft(errorAlert: PosthogTurnSuggestionParams['errorAlert']): ErrorAlertSuggestionDraft | null {
+ if (!errorAlert || !nonEmptyString(errorAlert.issueId)) {
+ return null
+ }
+ return {
+ issueId: errorAlert.issueId,
+ issueName: nonEmptyString(errorAlert.issueName) ? errorAlert.issueName : 'this issue',
+ }
+}
+
+export function parseTurnSuggestionParams(params: unknown): TurnSuggestion | null {
+ if (!params || typeof params !== 'object') {
+ return null
+ }
+ const { turnIndex, kind, intent, confidence, title, description, ...drafts } = params as PosthogTurnSuggestionParams
+ if (
+ typeof turnIndex !== 'number' ||
+ !Number.isInteger(turnIndex) ||
+ turnIndex < 0 ||
+ !isOneOf(TURN_SUGGESTION_KINDS, kind) ||
+ !nonEmptyString(title) ||
+ !nonEmptyString(description)
+ ) {
+ return null
+ }
+ const base = {
+ turnIndex,
+ intent: typeof intent === 'string' ? intent : 'unknown',
+ confidence: typeof confidence === 'number' ? confidence : 0,
+ title,
+ description,
+ }
+ switch (kind) {
+ case 'scout': {
+ const scout = parseScoutDraft(drafts.scout)
+ return scout ? { ...base, kind, scout } : null
+ }
+ case 'notebook': {
+ const notebook = parseNotebookDraft(drafts.notebook)
+ return notebook ? { ...base, kind, notebook } : null
+ }
+ case 'alert': {
+ const alert = parseAlertDraft(drafts.alert)
+ return alert ? { ...base, kind, alert } : null
+ }
+ case 'subscription': {
+ const subscription = parseSubscriptionDraft(drafts.subscription)
+ return subscription ? { ...base, kind, subscription } : null
+ }
+ case 'error_alert': {
+ const errorAlert = parseErrorAlertDraft(drafts.errorAlert)
+ return errorAlert ? { ...base, kind, errorAlert } : null
+ }
+ }
+}
+
+export function cadenceLabel(cadence: ScoutSuggestionCadence): string {
+ return cadence === 'daily' ? 'every day' : 'every week'
+}
diff --git a/products/posthog_ai/frontend/utils/turnTrailers.test.ts b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
index f5d34f066de3..c57ff32099a5 100644
--- a/products/posthog_ai/frontend/utils/turnTrailers.test.ts
+++ b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
@@ -6,7 +6,7 @@ function item(type: ThreadItem['type'], id: string, text?: string): ThreadItem {
}
describe('turnTrailers', () => {
- it('assigns stable ordinals, per-turn text, trace ids, and timestamps across multiple turns', () => {
+ it('numbers turns by the user message they answer, with per-turn text, trace ids, and timestamps across multiple turns', () => {
const trailers = computeTurnTrailers([
item('human_message', 'h0', 'q1'),
item('assistant_message', 'a0', 'first answer'),
@@ -44,18 +44,39 @@ describe('turnTrailers', () => {
item('turn_separator', 'turn-0'),
])
- expect(trailers.get('turn-0')).toEqual({ turnIndex: 0, isLastTurn: true, turnText: 'clean answer' })
+ expect(trailers.get('turn-0')).toEqual({
+ turnIndex: 1,
+ 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.each([
+ {
+ name: 'a duplicate turn-end marker with no answer behind it',
+ items: [
+ item('human_message', 'h0', 'q1'),
+ item('assistant_message', 'a0', 'answer'),
+ item('turn_separator', 'turn-0'),
+ item('turn_separator', 'turn-1'),
+ ],
+ expected: { 'turn-0': 0 },
+ },
+ {
+ name: 'an answer to a hidden prompt before any user message',
+ items: [
+ item('assistant_message', 'a0', 'answer to a hidden prompt'),
+ item('turn_separator', 'turn-0'),
+ item('human_message', 'h0', 'q1'),
+ item('assistant_message', 'a1', 'answer'),
+ item('turn_separator', 'turn-1'),
+ ],
+ expected: { 'turn-1': 0 },
+ },
+ ])('gives no trailer to $name', ({ items, expected }) => {
+ const trailers = computeTurnTrailers(items)
+ expect(Object.fromEntries([...trailers].map(([id, trailer]) => [id, trailer.turnIndex]))).toEqual(expected)
+ expect(trailers.get(Object.keys(expected)[0])?.isLastTurn).toBe(true)
})
it('returns an empty map for a thread with no completed turns', () => {
diff --git a/products/posthog_ai/frontend/utils/turnTrailers.ts b/products/posthog_ai/frontend/utils/turnTrailers.ts
index 799a2141d482..8f28e9373bb6 100644
--- a/products/posthog_ai/frontend/utils/turnTrailers.ts
+++ b/products/posthog_ai/frontend/utils/turnTrailers.ts
@@ -2,8 +2,8 @@ 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. */
+ /** 0-based index of the user message this turn answers, the server's turn numbering. A crashed
+ * turn has no trailer but still counts, so the indexes of completed turns can skip a number. */
turnIndex: number
/** True for the most recently completed turn. */
isLastTurn: boolean
@@ -16,13 +16,13 @@ export interface TurnTrailer {
}
/**
- * Maps each `turn_separator` item id to its turn's ordinal and assistant text. A separator marks
+ * Maps each `turn_separator` item id to its turn's index 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 turnIndex = -1
let textParts: string[] = []
let lastSeparatorId: string | null = null
for (const item of threadItems) {
@@ -31,10 +31,14 @@ export function computeTurnTrailers(threadItems: ThreadItem[]): Map<string, Turn
} else if (item.type === 'human_message') {
// A crashed turn never emits its separator; its text must not leak into the next turn.
textParts = []
+ turnIndex += 1
} 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) {
+ // seam can leak one); it is not a turn and gets no trailer. Neither is an answer to a
+ // hidden prompt before any user message: the server does not number it, and every such
+ // turn would share one index.
+ if (textParts.length === 0 || turnIndex < 0) {
+ textParts = []
continue
}
trailers.set(item.id, {
@@ -45,7 +49,6 @@ export function computeTurnTrailers(threadItems: ThreadItem[]): Map<string, Turn
timestamp: item.startedAt,
})
lastSeparatorId = item.id
- turnIndex += 1
textParts = []
}
}