: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
import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { isUUIDLike } from 'lib/utils/guards'
import { hogql } from 'lib/utils/hogql'
import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
import { Survey } from '~/types'
import { aiObservabilityTraceDataLogic } from '../aiObservabilityTraceDataLogic'
import { getSurveyIdFromEvent } from './survey-responses/utils'
export interface FeedbackViewLogicProps {
traceId: string
}
/**
* Collects the survey IDs to look up from the trace's survey events.
*
* Feedback surveys on a trace are captured by the app under test, so `$survey_id` holds
* whatever that app sent. The surveys API filters on a list of UUIDs and rejects the whole
* list when one entry is malformed, which would leave the tab with no feedback at all, so
* drop the IDs that cannot belong to a survey.
*/
export function extractValidSurveyIds(surveyEvents: LLMTraceEvent[] | null): string[] {
if (!surveyEvents) {
return []
}
const ids = new Set<string>()
for (const event of surveyEvents) {
const surveyId = getSurveyIdFromEvent(event)
if (surveyId && isUUIDLike(surveyId)) {
ids.add(surveyId)
}
}
return Array.from(ids)
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface feedbackViewLogicValues {
trace: LLMTrace | undefined // aiObservabilityTraceDataLogic
hasLoadingError: boolean
surveyEvents: LLMTraceEvent[] | null
surveyEventsLoading: boolean
surveyIds: string[]
surveys: Record<string, Survey>
surveysLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface feedbackViewLogicActions {
loadSurveyEvents: (createdAt: string) => string
loadSurveyEventsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadSurveyEventsSuccess: (
surveyEvents: {
createdAt: any
event: any
id: any
properties: any
}[],
payload?: string
) => {
surveyEvents: {
createdAt: any
event: any
id: any
properties: any
}[]
payload?: string
}
loadSurveys: () => any
loadSurveysFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadSurveysSuccess: (
surveys: {
[k: string]: Survey
},
payload?: any
) => {
surveys: {
[k: string]: Survey
}
payload?: any
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface feedbackViewLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
surveyIds: (surveyEvents: LLMTraceEvent[] | null) => string[]
}
}
export type feedbackViewLogicType = MakeLogicType<
feedbackViewLogicValues,
feedbackViewLogicActions,
FeedbackViewLogicProps,
feedbackViewLogicMeta
>
export const feedbackViewLogic = kea<feedbackViewLogicType>([
path(['scenes', 'ai-observability', 'feedbackViewLogic']),
props({} as FeedbackViewLogicProps),
key((props) => props.traceId),
connect({
values: [aiObservabilityTraceDataLogic, ['trace']],
}),
loaders(({ props, values }) => ({
surveyEvents: [
null as LLMTraceEvent[] | null,
{
loadSurveyEvents: async (createdAt: string) => {
const date = dayjs(createdAt)
const response = await api.queryHogQL(
hogql`
SELECT uuid, event, timestamp, properties
FROM events
WHERE (event = 'survey sent' OR event = 'survey shown')
AND properties.$ai_trace_id = ${props.traceId}
AND timestamp >= ${date}
ORDER BY if(event = 'survey sent', 0, 1)
LIMIT 1 BY properties.$survey_id
`,
{ productKey: 'llm_analytics' }
)
return response.results.map(([uuid, event, timestamp, properties]: any) => ({
id: uuid,
event,
createdAt: timestamp,
properties: typeof properties === 'string' ? JSON.parse(properties) : properties,
}))
},
},
],
surveys: [
{} as Record<string, Survey>,
{
loadSurveys: async () => {
const surveyIds = values.surveyIds
if (surveyIds.length === 0) {
return {}
}
const response = await api.surveys.list({ ids: surveyIds.join(','), limit: surveyIds.length })
return Object.fromEntries(response.results.map((survey) => [survey.id, survey]))
},
},
],
})),
reducers({
hasLoadingError: [
false,
{
loadSurveyEventsFailure: () => true,
loadSurveysFailure: () => true,
loadSurveyEvents: () => false,
},
],
}),
selectors({
// Inline so kea-typegen can infer the selector; a bare function reference drops
// `surveyIds` from the generated values.
surveyIds: [
(s) => [s.surveyEvents],
(surveyEvents: LLMTraceEvent[] | null): string[] => extractValidSurveyIds(surveyEvents),
],
}),
listeners(({ actions }) => ({
loadSurveyEventsSuccess: () => {
actions.loadSurveys()
},
})),
subscriptions(({ actions, values }) => ({
trace: (trace: LLMTrace | undefined) => {
if (trace?.createdAt && values.surveyEvents === null && !values.surveyEventsLoading) {
actions.loadSurveyEvents(trace.createdAt)
}
},
})),
afterMount(({ actions, values }) => {
const trace = values.trace
if (trace?.createdAt && values.surveyEvents === null && !values.surveyEventsLoading) {
actions.loadSurveyEvents(trace.createdAt)
}
}),
])