:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(posthog-ai): show message time and copy under chat messages (#107452)
Vojta Bartoš6e6c261a7a9f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex fe64f4933868..64a55de013c0 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6797,17 +6797,17 @@ snapshots:products-posthog-ai-runalertactivity--connection-lost-narrow--light:hash: v1.k794b7964.8555bf34acfd36c149b40599f32ca9aba1e2e746b94e43abea582710b3c2dd3f.a8iigoMwFpLemT0mLL8QoBjdFHkg_IZ1uvvSireyP9Uproducts-posthog-ai-startup-chat--queued-sidebar--dark:- hash: v1.k794b7964.09044ddb515744099eabe2881689812c0586ce88b5165a3849464ddad9b3ae3f.VlpRnuqPgJZC6rVD37-9cjVUD9O6ZZk4kzAfPvIFOqU+ hash: v1.k794b7964.0a1993d5279625a3c91f074c8cf7e34bd88db074bd8a1e241ff2280b4c99c380.UnOJ3mwJBduMfTDI0o9MBSXKXI3Of0NlpXg0A9B5Sqkproducts-posthog-ai-startup-chat--queued-sidebar--light:- hash: v1.k794b7964.81581b9f5819cb15acf16ae5aad14b9473a4aee528125a4ad1e46cf4ad93a82d.XCVMzmQ6kHE_Lw06Q0ZdgJ0zBcxESrvQQ2O5I2HcsnU+ hash: v1.k794b7964.24e27e42e198eab5417623a6bd6cc67f109115783304a848b15d562b15442e72.rq_1rN6SrmbB5MSkWKq22omx3glxTF93ePJUkH6jkKQproducts-posthog-ai-startup-chat--queued-wide--dark:- hash: v1.k794b7964.5db40206f864b58e4a84d954fa58639fdec43bc178e008191d410cbeb6053608.cFgGJK6e7olWV45z3ekjUoGPbAMP2EablOmWNqLsACI+ hash: v1.k794b7964.1612ffa89db1d040d7c8e2e0b73dc4ca3fea5d748c1ef6eae8f9ab760ad320ee.gDt7zEWuodf70YZlceluzagHV1aZ-OkYW8SOpstR2g0products-posthog-ai-startup-chat--queued-wide--light:- hash: v1.k794b7964.10bc533e5bca118de3428e4040970188ae5d7798f12e28d01ba4ed88db5c7881.hZvOyfRUVLf0xLYzv1YWZtHEi64XS8BFdrkWRkSGAEY+ hash: v1.k794b7964.df0dcf1bd5170245ccb356550072b7b6a1b225eb712737facb2f80055bed4c0b.HdNbQUawyGOc40nZoySxq4V6efzYAE36bGtYLU_3GEAproducts-posthog-ai-startup-chat--sidebar--dark:- hash: v1.k794b7964.9df1a431eabd0d314ea291036288e31d351d785e5f511f64fcd255ba86c04c16.YtLvYRZ_hIFGA6PPEN-wZgi5tq85gR0OluUYChuz2KU+ hash: v1.k794b7964.bf70cafd8550ef959af03157b31ad15ad6f48f261c72f08f415dc391c19c239e.BEN66-_baZ3W_c674D62PJ9dDXf1q2FITRUyQRkOmtIproducts-posthog-ai-startup-chat--sidebar--light:- hash: v1.k794b7964.e1316b144028fa93a29a2486b18e01e22274d3102e903619af020206b72ad385.u3M3m5PjmzT0G_e7ydqErsz0iMq2LUZSBPu0h0EWA3Q+ hash: v1.k794b7964.c0a9609201b7203bf988fbd0653777ff584c5e365ba70c1c8207a5cf97683e83.6tTqQNajhHQV7dCG7lzQP1cJyxOG70VGZ7VYg9Mqk0Iproducts-posthog-ai-taskassigneefiltermenu--non-staff--dark:hash: v1.k794b7964.054d05f7ef960ff884a3a325564585e3fcd4aaddccafe7fe05576c4a1f300737.RK0f_iJ30LfZp1s3ONdVO_74aI7AQBYwwTR-lOGnfBYproducts-posthog-ai-taskassigneefiltermenu--non-staff--light:@@ -6852,6 +6852,10 @@ snapshots:hash: v1.k794b7964.056f88152e13f9df1228665f670fa21156d2ae25331189069860fc4cf0277bb3._ccmzZyJGWprmT_pQzBm6zVVSm1XWf95e4k2RAtETRgproducts-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+ products-posthog-ai-threadview--message-footers--light:+ hash: v1.k794b7964.e4840008ba9134a23f57c6c8a3ae714ed0f931adb828ace42410c8e9c2432687.yULknrQ7l7OiGWrFYkbCJ6SToSfqw9ClK1JTPQqjzm8products-posthog-ai-threadview--saved-insight-query--dark:hash: v1.k794b7964.ff266ce4b007479bd8156db3c4b65a91a8b987d226bfd7622b20085df50d5d1c.2IsZbL1hVZEqsqWd22bNC0XJvJSqSlXHKCc0LGtJzJcproducts-posthog-ai-threadview--saved-insight-query--light:diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxindex f96827a882e3..5302d8272026 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -225,6 +225,7 @@ function RunSurfaceThread({run={feedbackRun}traceId={trailer.traceId}turnText={trailer.turnText}+ timestamp={trailer.timestamp}/>) : null,[feedbackSessionId, feedbackRun]diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsxindex 909b9c4e09f1..85c5745f1daf 100644--- a/products/posthog_ai/frontend/components/ThreadRow.tsx+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx@@ -1,6 +1,10 @@import { memo } from 'react'-import { IconWrench } from '@posthog/icons'+import { IconCopy, IconWrench } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { copyToClipboard } from 'lib/utils/copyToClipboard'import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'@@ -106,6 +110,28 @@ export interface ThreadRowProps {runEnded?: boolean}+/** Hidden at rest so a long thread does not repeat a row under every message. */+function HumanMessageFooter({ startedAt, text }: { startedAt?: number; text?: string }): JSX.Element {+ return (+ <div className="flex items-center gap-1 mt-1.5 mr-1 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">+ {startedAt !== undefined && (+ // A fresh dayjs object every render would defeat TZLabel's memo; a string compares by value.+ <TZLabel time={new Date(startedAt).toISOString()} className="text-xs text-muted" />+ )}+ {text && (+ <LemonButton+ icon={<IconCopy />}+ type="tertiary"+ size="xsmall"+ tooltip="Copy message"+ data-attr="posthog-ai-human-message-copy"+ onClick={() => void copyToClipboard(text)}+ />+ )}+ </div>+ )+}+/*** Renders a single sandbox thread item by type. Memoized and keyed by stable `item.id` so a re-projected* `threadItems` array only re-renders rows whose data actually changed.@@ -121,7 +147,11 @@ export const ThreadRow = memo(function ThreadRow({}: ThreadRowProps): JSX.Element | null {if (item.type === 'human_message') {return (- <MessageTemplate type="human">+ <MessageTemplate+ type="human"+ className="group"+ action={<HumanMessageFooter startedAt={item.startedAt} text={item.text} />}+ ><MarkdownMessage content={item.text || '*No text.*'} id={item.id} />{item.attachments && <ThreadAttachments attachments={item.attachments} />}</MessageTemplate>diff --git a/products/posthog_ai/frontend/components/ThreadView.stories.tsx b/products/posthog_ai/frontend/components/ThreadView.stories.tsxindex ddb5c5bc87d0..05450d118798 100644--- a/products/posthog_ai/frontend/components/ThreadView.stories.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.stories.tsx@@ -5,7 +5,10 @@ import { useEffect } from 'react'import { mswDecorator } from '~/mocks/browser'import { runStreamLogic } from '../logics/runStreamLogic'+import type { StoredLogEntry } from '../types/wireTypes'+import type { TurnTrailer } from '../utils/turnTrailers'import { ThreadView } from './ThreadView'+import { TurnFeedbackActions } from './TurnFeedbackActions'interface ThreadFixtureProps {streamKey: string@@ -156,3 +159,60 @@ export const ExecuteSqlWithVariables: Story = {},},}++function timedNotification(timestamp: string, method: string, params: Record<string, unknown>): StoredLogEntry {+ return { type: 'notification', timestamp, notification: { method, params } }+}++const MESSAGE_FOOTER_ENTRIES: StoredLogEntry[] = [+ timedNotification('2024-03-11T14:02:10Z', '_client/human_message', {+ content: 'How many users signed up last week?',+ }),+ timedNotification('2024-03-11T14:02:18Z', 'session/update', {+ update: {+ sessionUpdate: 'agent_message_chunk',+ messageId: 'synthetic-answer',+ content: { type: 'text', text: 'Signups grew week over week. See the trend below.' },+ },+ }),+ timedNotification('2024-03-11T14:02:20Z', '_posthog/turn_complete', {}),+]++function renderSyntheticTurnTrailer(trailer: TurnTrailer): JSX.Element {+ return (+ <TurnFeedbackActions+ sessionId="synthetic-task"+ turnIndex={trailer.turnIndex}+ run={{ taskId: 'synthetic-task' }}+ turnText={trailer.turnText}+ timestamp={trailer.timestamp}+ />+ )+}++export const MessageFooters: Story = {+ args: { streamKey: 'synthetic-message-footers' },+ parameters: {+ mockDate: '2024-03-11T14:05:00Z',+ },+ render: ({ streamKey }) => {+ useEffect(() => {+ const logic = runStreamLogic({ streamKey })+ const unmount = logic.mount()+ // Human messages do not dedupe, and strict mode reruns this effect.+ if (logic.values.threadItems.length === 0) {+ for (const entry of MESSAGE_FOOTER_ENTRIES) {+ logic.actions.ingestAcpFrame(entry, 'replay')+ }+ }+ return unmount+ }, [streamKey])+ return (+ <div className="w-180 max-w-full h-160 border rounded">+ <BindLogic logic={runStreamLogic} props={{ streamKey }}>+ <ThreadView renderTurnTrailer={renderSyntheticTurnTrailer} />+ </BindLogic>+ </div>+ )+ },+}diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsxindex a2c0846c57a6..ce56794db99f 100644--- a/products/posthog_ai/frontend/components/ThreadView.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.tsx@@ -9,7 +9,8 @@ import type { ThreadItem } from '../types/streamTypes'import { groupThreadActivity, type ThreadDisplayItem } from '../utils/groupThreadActivity'import { getRandomThinkingMessage } from '../utils/thinkingMessages'import { resolveToolCall } from '../utils/toolResolver'-import { type TurnTrailer, computeTurnTrailers } from '../utils/turnTrailers'+import { TurnHoverStore } from '../utils/turnHoverStore'+import { type TurnTrailer, computeTurnTrailers, mapRowsToTurnSeparator } from '../utils/turnTrailers'import { ContextUsageChip } from './ContextUsageChip'import { PullRequestCard } from './PullRequestCard'import { RunAlertActivity } from './RunAlertActivity'@@ -17,6 +18,7 @@ import { RunContext } from './RunContext'import { ThreadActivityGroup } from './ThreadActivityGroup'import { ThreadRow } from './ThreadRow'import { lookupToolRenderer } from './tool/toolRegistry'+import { TurnReveal } from './TurnReveal'import { VirtualizedThread } from './VirtualizedThread'/** Stable row key — defined at module scope so `getItemKey` never changes identity across renders. */@@ -131,10 +133,14 @@ export function ThreadView({[threadItems])// Only computed when a trailer renderer is supplied — bare ThreadViews pay nothing.- const turnTrailers = useMemo(- () => (renderTurnTrailer ? computeTurnTrailers(threadItems) : null),- [threadItems, renderTurnTrailer]+ const turns = useMemo(+ () =>+ renderTurnTrailer+ ? { trailers: computeTurnTrailers(threadItems), rowTurnIds: mapRowsToTurnSeparator(displayItems) }+ : null,+ [threadItems, displayItems, renderTurnTrailer])+ const [turnHoverStore] = useState(() => new TurnHoverStore())// Header/footer are kept as memoized leaf components with stable element identity so they don't rebuild// `VirtualizedThread`'s `renderRow` (and re-sweep visible rows) on every streamed frame. Each is wrapped@@ -197,45 +203,53 @@ export function ThreadView({const isLast = index === displayItems.length - 1return (<VirtualizedThread.Row className={rowClassName}>- <ThreadActivityGroup- group={item}- toolInvocations={toolInvocations}- active={isLast && isThinking}- waitingForInput={isLast && !!pendingPermissionRequest}- cancelled={isLast && (turnCancelled || currentRunStatus === 'failed')}- renderItem={(activity) => (- <ThreadRow- item={activity}- isLast={false}- isThinking={false}- toolInvocations={toolInvocations}- turnComplete={turnComplete}- turnCancelled={turnCancelled}- />- )}- />+ <TurnReveal store={turnHoverStore} turnId={turns?.rowTurnIds.get(item.id)}>+ <ThreadActivityGroup+ group={item}+ toolInvocations={toolInvocations}+ active={isLast && isThinking}+ waitingForInput={isLast && !!pendingPermissionRequest}+ cancelled={isLast && (turnCancelled || currentRunStatus === 'failed')}+ renderItem={(activity) => (+ <ThreadRow+ item={activity}+ isLast={false}+ isThinking={false}+ toolInvocations={toolInvocations}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )}+ />+ </TurnReveal></VirtualizedThread.Row>)}if (item.type === 'turn_separator' && renderTurnTrailer) {- const trailer = turnTrailers?.get(item.id)+ const trailer = turns?.trailers.get(item.id)return (<VirtualizedThread.Row className={rowClassName}>- {trailer ? renderTurnTrailer(trailer) : null}+ {trailer ? (+ <TurnReveal store={turnHoverStore} turnId={item.id}>+ {renderTurnTrailer(trailer)}+ </TurnReveal>+ ) : null}</VirtualizedThread.Row>)}return (<VirtualizedThread.Row className={rowClassName}>- <ThreadRow- item={item}- isLast={index === displayItems.length - 1}- isThinking={isThinking}- toolInvocations={toolInvocations}- turnComplete={turnComplete}- turnCancelled={turnCancelled}- runEnded={runEnded}- />+ <TurnReveal store={turnHoverStore} turnId={turns?.rowTurnIds.get(item.id)}>+ <ThreadRow+ item={item}+ isLast={index === displayItems.length - 1}+ isThinking={isThinking}+ toolInvocations={toolInvocations}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ runEnded={runEnded}+ />+ </TurnReveal></VirtualizedThread.Row>)},@@ -247,7 +261,8 @@ export function ThreadView({turnCancelled,rowClassName,renderTurnTrailer,- turnTrailers,+ turns,+ turnHoverStore,pendingPermissionRequest,currentRunStatus,runEnded,diff --git a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsxindex 1af2bb2276e8..ded93892870b 100644--- a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx+++ b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx@@ -1,15 +1,18 @@+import clsx from 'clsx'import { useActions, useValues } from 'kea'-import { useState, memo } from 'react'+import { useContext, useState, memo } from 'react'import { IconCopy, IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled, IconX } from '@posthog/icons'import { LemonButton, LemonInput } from '@posthog/lemon-ui'+import { TZLabel } from 'lib/components/TZLabel'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { stripMarkdown } from 'lib/utils/markdown'import { messageRatingsLogic } from '../logics/messageRatingsLogic'import { MessageTemplate } from '../messages/MessageTemplate'import { RunRef, captureTurnFeedbackText, captureTurnRating } from '../utils/feedbackEvents'+import { TurnRevealContext } from './TurnRevealContext'export interface TurnFeedbackActionsProps {/** Task id backing the sandbox conversation. Lands in `$ai_session_id`. */@@ -20,11 +23,13 @@ export interface TurnFeedbackActionsProps {/** The turn's gateway trace id, when the run reported one. Lands in `$ai_trace_id`. */traceId?: stringturnText: string+ /** When the turn completed, in milliseconds. */+ timestamp?: number}/**- * 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+ * Feedback actions under a completed turn: copy, thumbs up/down, the completion time, 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 const TurnFeedbackActions = memo(function TurnFeedbackActions({@@ -33,9 +38,11 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({run,traceId,turnText,+ timestamp,}: TurnFeedbackActionsProps): JSX.Element {const { ratingForKey } = useValues(messageRatingsLogic)const { setRating } = useActions(messageRatingsLogic)+ const turnHovered = useContext(TurnRevealContext)const ratingKey = `${sessionId}:turn-${turnIndex}`const rating = ratingForKey(ratingKey)@@ -63,7 +70,7 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({return (<>- <div className="flex items-center ml-1">+ <div className="group flex items-center ml-1">{turnText && (<LemonButtonicon={<IconCopy />}@@ -94,6 +101,15 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({onClick={() => submitRating('bad')}/>)}+ {timestamp !== undefined && (+ <TZLabel+ time={new Date(timestamp).toISOString()}+ className={clsx(+ 'text-xs text-muted ml-1 transition-opacity group-focus-within:opacity-100',+ !turnHovered && 'opacity-0'+ )}+ />+ )}</div>{feedbackInputStatus !== 'hidden' && (<MessageTemplate type="ai">diff --git a/products/posthog_ai/frontend/components/TurnReveal.test.tsx b/products/posthog_ai/frontend/components/TurnReveal.test.tsxnew file mode 100644index 000000000000..bcf706e349c5--- /dev/null+++ b/products/posthog_ai/frontend/components/TurnReveal.test.tsx@@ -0,0 +1,48 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { TurnHoverStore } from '../utils/turnHoverStore'+import { TurnReveal } from './TurnReveal'++describe('TurnReveal', () => {+ let store: TurnHoverStore++ function wrapper(label: string): JSX.Element {+ return (+ <TurnReveal key={label} store={store} turnId="turn-1">+ <span>{label}</span>+ </TurnReveal>+ )+ }++ beforeEach(() => {+ jest.useFakeTimers()+ store = new TurnHoverStore()+ })++ afterEach(() => {+ cleanup()+ jest.useRealTimers()+ })++ // The virtualizer recycles rows out of the DOM, and removing a hovered node fires no mouseleave.+ test.each([+ ['the pointer is inside it', 'row', null],+ ['the pointer is on the trailer of the same turn', 'trailer', 'turn-1'],+ ])('unmounting a row clears the hovered turn when %s', (_name, hovered, expected) => {+ const { rerender } = render(+ <>+ {wrapper('row')}+ {wrapper('trailer')}+ </>+ )+ fireEvent.mouseEnter(screen.getByText(hovered).parentElement!)+ expect(store.getHoveredTurnId()).toBe('turn-1')++ rerender(<>{wrapper('trailer')}</>)+ jest.runOnlyPendingTimers()++ expect(store.getHoveredTurnId()).toBe(expected)+ })+})diff --git a/products/posthog_ai/frontend/components/TurnReveal.tsx b/products/posthog_ai/frontend/components/TurnReveal.tsxnew file mode 100644index 000000000000..858710853101--- /dev/null+++ b/products/posthog_ai/frontend/components/TurnReveal.tsx@@ -0,0 +1,48 @@+import { type ReactNode, useEffect, useRef, useSyncExternalStore } from 'react'++import type { TurnHoverStore } from '../utils/turnHoverStore'+import { TurnRevealContext } from './TurnRevealContext'++/** Hovering the trailer itself counts as hovering the turn, so the time does not vanish as the pointer reaches it. */+export function TurnReveal({+ store,+ turnId,+ children,+}: {+ store: TurnHoverStore+ turnId: string | undefined+ children: ReactNode+}): JSX.Element {+ const revealed = useSyncExternalStore(store.subscribe, () => !!turnId && store.getHoveredTurnId() === turnId)+ // Removing a hovered node fires no mouseleave, so a row the virtualizer recycles out would leave its turn+ // revealed. Only the wrapper the pointer is inside may clear it, or unmounting a row would hide the time+ // while the pointer rests on the same turn's trailer.+ const pointerInside = useRef(false)+ useEffect(+ () => () => {+ if (pointerInside.current) {+ store.leave()+ }+ },+ [store]+ )+ if (!turnId) {+ return <>{children}</>+ }+ return (+ <TurnRevealContext.Provider value={revealed}>+ <div+ onMouseEnter={() => {+ pointerInside.current = true+ store.enter(turnId)+ }}+ onMouseLeave={() => {+ pointerInside.current = false+ store.leave()+ }}+ >+ {children}+ </div>+ </TurnRevealContext.Provider>+ )+}diff --git a/products/posthog_ai/frontend/components/TurnRevealContext.ts b/products/posthog_ai/frontend/components/TurnRevealContext.tsnew file mode 100644index 000000000000..7681dd562713--- /dev/null+++ b/products/posthog_ai/frontend/components/TurnRevealContext.ts@@ -0,0 +1,4 @@+import { createContext } from 'react'++/** True while the pointer is over any row of the turn that this trailer closes. */+export const TurnRevealContext = createContext(false)diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex ed3f76d7ea1c..43225e7e50a8 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -1142,7 +1142,7 @@ describe('runStreamLogic', () => {})describe('pushHumanMessage', () => {- it('appends a human_message item ordered before subsequently ingested assistant frames', async () => {+ it('appends a timestamped human_message item ordered before subsequently ingested assistant frames', async () => {await expectLogic(logic, () => {logic.actions.pushHumanMessage('hello agent')// The agent takes the send up and echoes it, which is what places the message.@@ -1159,6 +1159,7 @@ describe('runStreamLogic', () => {type: 'human_message',text: 'hello agent',complete: true,+ startedAt: expect.any(Number),})expect(logic.values.threadItems[1].type).toEqual('assistant_message')})diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex c686dba7e35f..0f2e393dcdb6 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -4429,6 +4429,8 @@ export const runStreamLogic = kea<runStreamLogicType>([{entry: {type: 'notification',+ // The wire echo of this send is deduped against this entry, so the send time can only come from here.+ timestamp: new Date().toISOString(),notification: {method: '_client/human_message',params: {diff --git a/products/posthog_ai/frontend/utils/turnHoverStore.ts b/products/posthog_ai/frontend/utils/turnHoverStore.tsnew file mode 100644index 000000000000..de8ed565cae8--- /dev/null+++ b/products/posthog_ai/frontend/utils/turnHoverStore.ts@@ -0,0 +1,43 @@+/** The pointer crosses the gap between two rows of the same turn. The delay stops the reveal from flickering there. */+const LEAVE_DELAY_MS = 100++/** A turn renders as several virtualized rows, so CSS `group-hover` cannot span it and `useState` would re-render every row. */+export class TurnHoverStore {+ private hoveredTurnId: string | null = null+ private clearTimer: ReturnType<typeof setTimeout> | null = null+ private readonly listeners = new Set<() => void>()++ subscribe = (listener: () => void): (() => void) => {+ this.listeners.add(listener)+ return () => {+ this.listeners.delete(listener)+ }+ }++ getHoveredTurnId = (): string | null => this.hoveredTurnId++ enter(turnId: string): void {+ this.cancelClear()+ this.setHoveredTurnId(turnId)+ }++ leave(): void {+ this.cancelClear()+ this.clearTimer = setTimeout(() => this.setHoveredTurnId(null), LEAVE_DELAY_MS)+ }++ private cancelClear(): void {+ if (this.clearTimer !== null) {+ clearTimeout(this.clearTimer)+ this.clearTimer = null+ }+ }++ private setHoveredTurnId(turnId: string | null): void {+ if (this.hoveredTurnId === turnId) {+ return+ }+ this.hoveredTurnId = turnId+ this.listeners.forEach((listener) => listener())+ }+}diff --git a/products/posthog_ai/frontend/utils/turnTrailers.test.ts b/products/posthog_ai/frontend/utils/turnTrailers.test.tsindex 0061ebcc3b1a..22726909f71a 100644--- a/products/posthog_ai/frontend/utils/turnTrailers.test.ts+++ b/products/posthog_ai/frontend/utils/turnTrailers.test.ts@@ -1,16 +1,16 @@import type { ThreadItem } from '../types/streamTypes'-import { computeTurnTrailers } from './turnTrailers'+import { computeTurnTrailers, mapRowsToTurnSeparator } from './turnTrailers'function item(type: ThreadItem['type'], id: string, text?: string): ThreadItem {return { id, type, text }}-describe('computeTurnTrailers', () => {- it('assigns stable ordinals, per-turn text, and per-turn trace ids across multiple turns', () => {+describe('turnTrailers', () => {+ it('assigns stable ordinals, per-turn text, trace ids, and timestamps across multiple turns', () => {const trailers = computeTurnTrailers([item('human_message', 'h0', 'q1'),item('assistant_message', 'a0', 'first answer'),- { ...item('turn_separator', 'turn-0'), traceId: 'trace-a' },+ { ...item('turn_separator', 'turn-0'), traceId: 'trace-a', startedAt: 1700000000000 },item('human_message', 'h1', 'q2'),item('assistant_thought', 't0', 'thinking'),item('assistant_message', 'a1', 'second answer'),@@ -23,6 +23,7 @@ describe('computeTurnTrailers', () => {isLastTurn: false,turnText: 'first answer',traceId: 'trace-a',+ timestamp: 1700000000000,})expect(trailers.get('turn-1')).toEqual({turnIndex: 1,@@ -64,4 +65,20 @@ describe('computeTurnTrailers', () => {])expect(trailers.size).toBe(0)})++ it('maps answer rows to the separator of their own turn, and skips human and unfinished rows', () => {+ const membership = mapRowsToTurnSeparator([+ item('human_message', 'h0'),+ item('assistant_message', 'a0'),+ item('turn_separator', 'turn-0'),+ item('human_message', 'h1'),+ item('assistant_thought', 't1'),+ item('assistant_message', 'a1'),+ item('turn_separator', 'turn-1'),+ item('human_message', 'h2'),+ item('assistant_message', 'a2'),+ ])++ expect(Object.fromEntries(membership)).toEqual({ a0: 'turn-0', t1: 'turn-1', a1: 'turn-1' })+ })})diff --git a/products/posthog_ai/frontend/utils/turnTrailers.ts b/products/posthog_ai/frontend/utils/turnTrailers.tsindex 283a6f63553b..b119a4230d2d 100644--- a/products/posthog_ai/frontend/utils/turnTrailers.ts+++ b/products/posthog_ai/frontend/utils/turnTrailers.ts@@ -11,6 +11,8 @@ export interface TurnTrailer {turnText: string/** The turn's gateway trace id — `$ai_trace_id` on its generations and its feedback. */traceId?: string+ /** When the turn completed, in milliseconds. Absent for imported or untimed history. */+ timestamp?: number}/**@@ -40,6 +42,7 @@ export function computeTurnTrailers(threadItems: ThreadItem[]): Map<string, TurnisLastTurn: false,turnText: textParts.join('\n\n'),traceId: item.traceId,+ timestamp: item.startedAt,})lastSeparatorId = item.idturnIndex += 1@@ -54,3 +57,22 @@ export function computeTurnTrailers(threadItems: ThreadItem[]): Map<string, Turn}return trailers}++/** Human messages keep their own footer, and rows of an unfinished turn have no separator yet, so neither gets an entry. */+export function mapRowsToTurnSeparator(items: ReadonlyArray<{ id: string; type: string }>): Map<string, string> {+ const membership = new Map<string, string>()+ let pending: string[] = []+ for (const item of items) {+ if (item.type === 'human_message') {+ pending = []+ } else if (item.type === 'turn_separator') {+ for (const id of pending) {+ membership.set(id, item.id)+ }+ pending = []+ } else {+ pending.push(item.id)+ }+ }+ return membership+}