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.

fix(posthog-ai): match desktop grouping and row chrome in the quill chat (#109806)

Adam Leithcf477025fff7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5bbc433ed48a..e5bf56aa402b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7059,13 +7059,17 @@ snapshots:
products-posthog-ai-threadview-quill--compared-with-lemon--light:
hash: v1.k794b7964.c7a5ffd2925080a181b740d34b2c27b38ad09f50892b11d14ceceba7e336a968.6xFkSM46Y-L3sx2EzN4vegRwjUqUwaxMc4usQN_1Bcw
products-posthog-ai-threadview-quill--completed-turn--dark:
- hash: v1.k794b7964.bd9bb2903f370c2f1030c1b31e69f004007f3aeb9c1be958381f91ecfc1aeca0.RxgqjdEnZ5RANGV5fD3rSvbYHYRo-6M7N2L-KS4oGNk
+ hash: v1.k794b7964.18e0af3b40dd5dff18d7d9f35711a38735850eb1f40edb62250c12dc57138857.0QpvMwB4_kWqBkYx-UFabEDT7gjUyyUCRt53i7ekBu4
products-posthog-ai-threadview-quill--completed-turn--light:
- hash: v1.k794b7964.7814b44a7cdb67fe04b11c0b67cd29da9df560fdd443a6a049127785b87eaddb.Ms_Zza_5d6X6oEsJVYbLuYXaZDqrN80vHn7E9nSP_bw
+ hash: v1.k794b7964.aaffd4821833cbd7be9d8c7cd77e9f0809e71ffcc3e5084dd838907c9a4555c7.TK23ojxPSurDuQlaipSd9dkwMzO20ChsfIc1mUjYTts
+ products-posthog-ai-threadview-quill--long-run--dark:
+ hash: v1.k794b7964.649d59f9d5e3d4dda17e70d3328394cee09f2cfdef39250ec1bfbfefc876b476.0YWMro0yyOCP9-2KChyQ3IqVUigeNmVYfRzoS1ijTZc
+ products-posthog-ai-threadview-quill--long-run--light:
+ hash: v1.k794b7964.d86e7871a7a187ef1637cb1434b4baefdf7695f68abe3f0adaebdc39ff8e220a.NK0Pld_NMcqp8eaGZhDeuLYcNb69l5kYYstVtK3r2HE
products-posthog-ai-threadview-quill--streaming-turn--dark:
- hash: v1.k794b7964.dc0c5375f7622aa8755a424c981f16489ca45e0b178a147a1ef45f1bf85d4c4a.PmyP1cKLntqhPrftuHkvd3HvPYcS7iE9spSH9NXVbho
+ hash: v1.k794b7964.01bd9095cf2448a061749878dfe6b7987084fbcbbc8fbb666ed4289e7087e332.AMVJTk5ixhgsTacK3PZ4heII47WXHCgGBohPR2DaO1s
products-posthog-ai-threadview-quill--streaming-turn--light:
- hash: v1.k794b7964.ab821f2b11da4c0a45f57411e64e6a420e09d024c3580da2b24f465810606212.-muSpXCIxCIulLSskbyWyNXWTqn16CR6ZXl03tuiwLo
+ hash: v1.k794b7964.caabab4d290dda51a4d3c302bfdcd4f16a6a54cc9f613da835afab3b8f2c60d3.6KgDrcJZ1u-Sm9NkUS-sUti399TsxKBCytKuU_A-EmU
products-posthog-ai-virtualizedthread--anchored-open--dark:
hash: v1.k794b7964.eecc3dde9e8475fb8f20f259880edae96e2750529897fc326c44d33ce20e0885.hQlXYcfwZ9CiFajcBHUg9oY6h2QcGrm91CkXVIht-OE
products-posthog-ai-virtualizedthread--anchored-open--light:
@@ -12998,6 +13002,10 @@ snapshots:
hash: v1.k794b7964.7eef9b267cd20f210bf5f20c395acbd04f412df23a4e5591fb5513ffd82334e8.igtYZYdMAjdMTWuPyiI8UjcKM2v2atwlbdF2GcbufqU
scenes-app-tasks--new-task--light:
hash: v1.k794b7964.318e9c80dc685a794981c4718212c0ff1529a62113f0fe53b1babb86e990ab6e.lc7xztqxXpgNPLRIPef1RY3WwIquiwVm64iyEciqcUg
+ scenes-app-tasks--new-task-quill--dark:
+ hash: v1.k794b7964.8cd8e701c13df761d9ba1d08b279e64b94678066aed4304b2eeb32c1c956203a.fDdtlf4c5GL9F3YlxR3_x_tAJEVQznyJzpabKxbtECc
+ scenes-app-tasks--new-task-quill--light:
+ hash: v1.k794b7964.6e2cf93013fbef02c8e2940abcde2e309a6e84a06d54890f51743d5ce7763212.Zm-mjYbWHC6sCEYuAVqmHaP2-EbushTDRwqCZQwHPFw
scenes-app-tasks--new-task-with-repository--dark:
hash: v1.k794b7964.183b80968dd176e810833f6237d50559eb2b45905a12715d7615b79dd3987304.glKUf15z01yE2oekRT1Y_QLcT87dpxpWCTxnUOh4a-M
scenes-app-tasks--new-task-with-repository--light:
diff --git a/frontend/src/layout/navigation-3000/Navigation.tsx b/frontend/src/layout/navigation-3000/Navigation.tsx
index c75b5ed34543..f4b27bd7d5e5 100644
--- a/frontend/src/layout/navigation-3000/Navigation.tsx
+++ b/frontend/src/layout/navigation-3000/Navigation.tsx
@@ -185,11 +185,13 @@ export function Navigation({
<div
className={cn(
- '@container/main-content-container main-content-container flex overflow-hidden lg:rounded border-t lg:border border-primary relative lg:mr-1 lg:mb-1 lg:mt-1',
- {
- 'rounded border mr-1 mb-1 mt-1': todayRail,
- 'rounded-r-none': sidePanelOpen,
- }
+ '@container/main-content-container main-content-container flex overflow-hidden border-primary relative',
+ todayRail
+ ? 'border-l'
+ : [
+ 'lg:rounded border-t lg:border lg:mr-1 lg:mb-1 lg:mt-1',
+ sidePanelOpen && 'rounded-r-none',
+ ]
)}
{...(todayDrawerOpen ? { inert: '' } : {})}
>
diff --git a/frontend/src/layout/today/TodaySpacesRow.tsx b/frontend/src/layout/today/TodaySpacesRow.tsx
index e2788eb22c1a..8679ef4dda97 100644
--- a/frontend/src/layout/today/TodaySpacesRow.tsx
+++ b/frontend/src/layout/today/TodaySpacesRow.tsx
@@ -72,7 +72,7 @@ export function TodaySpacesRow({
}
onBlur={ticker ? () => setKeyboardFocused(false) : undefined}
className={cn(
- 'min-w-0 text-xs text-foreground',
+ 'min-w-0 text-foreground',
weight === 'medium' && 'font-medium',
// Desktop's two-line row: the second line outgrows the fixed row height, so padding stands in for it.
details.length > 0 && 'h-auto py-1',
diff --git a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
index dab4bff3aa4a..f2280644b85a 100644
--- a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
+++ b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
@@ -11,7 +11,7 @@ import { urls } from 'scenes/urls'
import { SceneName } from '~/layout/scenes/components/SceneTitleSection'
-import { DebugLogsMenu } from 'products/posthog_ai/frontend/api/primitives'
+import { DebugLogsMenu, useThreadSkin } from 'products/posthog_ai/frontend/api/primitives'
import { EmbeddedRunner } from 'products/posthog_ai/frontend/api/runner'
import { aiSceneView } from '../aiSceneView'
@@ -113,6 +113,7 @@ export function AiFirstMaxInstance({ tabId, taskId, chatId }: AiFirstMaxInstance
const { threadVisible, threadLogicKey, conversation, conversationId } = useValues(maxLogic({ panelId: tabId }))
const { startNewConversation } = useActions(maxLogic({ panelId: tabId }))
const { isMaxAvailable, effectivePhaiView } = useValues(maxGlobalLogic)
+ const skin = useThreadSkin()
if (aiSceneView({ taskId, chatId, effectivePhaiView }) === 'runner') {
return (
@@ -126,7 +127,11 @@ export function AiFirstMaxInstance({ tabId, taskId, chatId }: AiFirstMaxInstance
)}
<div className="flex flex-col flex-1 min-h-0">
<BindLogic logic={phaiAiComposerSeedLogic} props={{}}>
- <EmbeddedRunner taskId={taskId} titleActions={<DebugLogsMenu variant="lemon" />} />
+ {/* The quill task header carries the debug logs switch in its own overflow menu. */}
+ <EmbeddedRunner
+ taskId={taskId}
+ titleActions={skin === 'lemon' ? <DebugLogsMenu variant="lemon" /> : undefined}
+ />
</BindLogic>
</div>
</div>
diff --git a/packages/quill/packages/primitives/src/tabs.css b/packages/quill/packages/primitives/src/tabs.css
index 8b47b4a8a100..68e07b34b0b2 100644
--- a/packages/quill/packages/primitives/src/tabs.css
+++ b/packages/quill/packages/primitives/src/tabs.css
@@ -51,8 +51,9 @@
border-radius: var(--radius-sm);
}
+ /* Above the triggers: the active trigger paints an opaque fill down to 1px above the list's edge. */
.quill-tabs__indicator--variant-line {
- z-index: 0;
+ z-index: 2;
background-color: var(--primary);
}
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
index 65580465f907..d9a002b4535e 100644
--- a/products/posthog_ai/frontend/AGENTS.md
+++ b/products/posthog_ai/frontend/AGENTS.md
@@ -215,10 +215,15 @@ ingestion).
re-folds. Listeners fire only side effects, each with a fire-once guard, suppressed on `source: 'replay'`.
- **A shared presenter renders in both thread skins.** `ThreadView`'s `skin` prop (`'lemon' | 'quill'`) sets
`ThreadSkinContext`; `quill` is the PostHog Desktop chat layout, on behind the `phai-quill` flag (and `today-rail-nav`).
- `Activity`, `ThreadRow` message rows, `ThreadActivityGroup`, `RunAlertActivity`, `PullRequestCard` and
+ `Activity`, `ThreadRow` message and separator rows, `ThreadActivityGroup`, `RunAlertActivity`, `PullRequestCard`, `RunContext` and
`TurnFeedbackActions` read `useQuillThread()` and dispatch to their `components/quill/` skin at the top of the
component. Behavior both skins need (open state, group windowing, ratings) lives in a shared hook
(`useActivityDisclosure`, `useActivityGroup`, `useTurnRating`), never in one skin. Tool renderers never branch on skin.
+ Grouping is the one rule that differs by skin, and `ThreadView` picks it.
+ The lemon thread folds every activity run (`groupThreadActivity`).
+ The quill thread folds only runs of two or more calls, like Desktop (`groupToolRuns`).
+ A registry entry marked `pinned` (a plan, a question) never folds.
+ A `keepVisible` widget result folds in quill, except the last finished call of a closed run.
- **A tool card is two header lines plus an accordion — overflow goes in the accordion.** Every tool
renderer wraps its content in `ToolActivity`, which exposes exactly two always-visible header lines:
the `title` and the `subtitle` (the one salient input — a command, path, repo, branch). **Any other
diff --git a/products/posthog_ai/frontend/components/RunContext.tsx b/products/posthog_ai/frontend/components/RunContext.tsx
index 47a2d4bff773..780e72fd80ac 100644
--- a/products/posthog_ai/frontend/components/RunContext.tsx
+++ b/products/posthog_ai/frontend/components/RunContext.tsx
@@ -4,6 +4,9 @@ import { IconGitBranch } from '@posthog/icons'
import { cn } from 'lib/utils/css-classes'
+import { QuillRunContextRow } from './quill/QuillRunContextRow'
+import { useQuillThread } from './quill/quillThreadContext'
+
/**
* Pre-turn header for a sandbox coding run: a one-line "Working on <repo> · <branch> → <base>"
* summary. Plain props, `React.memo`'d — `branch` is required, so the caller decides whether to mount
@@ -21,6 +24,9 @@ export const RunContext = memo(function RunContext({
repo?: string
className?: string
}): JSX.Element {
+ if (useQuillThread()) {
+ return <QuillRunContextRow branch={branch} baseBranch={baseBranch} repo={repo} />
+ }
return (
<div
className={cn(
diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsx
index bd041f1b2306..f6dddf87dfd2 100644
--- a/products/posthog_ai/frontend/components/ThreadRow.tsx
+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx
@@ -20,6 +20,7 @@ import { resolveToolCall } from '../utils/toolResolver'
import { userMessageDisplayText } from '../utils/userMessageDisplay'
import { Activity } from './ActivityPrimitives'
import { QuillAssistantMessage, QuillHumanMessage } from './quill/QuillMessages'
+import { QuillSeparatorRow } from './quill/QuillSeparatorRow'
import { useQuillThread } from './quill/quillThreadContext'
import { RunErrorRow } from './RunErrorRow'
import { ThreadAttachments } from './ThreadAttachments'
@@ -196,6 +197,9 @@ export const ThreadRow = memo(function ThreadRow({
if (item.type === 'error') {
return <RunErrorRow item={item} isLast={isLast && runEnded} />
}
+ if (quill && (item.type === 'status' || item.type === 'compact_boundary' || item.type === 'conversation_cleared')) {
+ return <QuillSeparatorRow item={item} live={isLast && isThinking} />
+ }
if (item.type === 'status') {
return <StatusItem item={item} />
}
diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsx
index 02a0d471545a..557a68dd5564 100644
--- a/products/posthog_ai/frontend/components/ThreadView.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.tsx
@@ -6,12 +6,18 @@ import { inStorybookTestRunner } from 'lib/utils/dom'
import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
-import type { ThreadItem } from '../types/streamTypes'
-import { groupThreadActivity, type ThreadDisplayItem } from '../utils/groupThreadActivity'
+import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
+import {
+ groupThreadActivity,
+ groupToolRuns,
+ isRunningStatus,
+ isStartupStatus,
+ type ThreadDisplayItem,
+} from '../utils/groupThreadActivity'
import { getRandomThinkingMessage } from '../utils/thinkingMessages'
import { resolveToolCall } from '../utils/toolResolver'
import { TurnHoverStore } from '../utils/turnHoverStore'
-import { type TurnTrailer, computeTurnTrailers, mapRowsToTurnSeparator } from '../utils/turnTrailers'
+import { type TurnTrailer, computeTurnTrailers, mapRowsToRevealGroup } from '../utils/turnTrailers'
import { ContextUsageChip } from './ContextUsageChip'
import { PullRequestCard } from './PullRequestCard'
import { type ThreadSkin, ThreadSkinContext } from './quill/quillThreadContext'
@@ -49,6 +55,23 @@ const THREAD_ITEM_HEIGHT_ESTIMATES: Partial<Record<ThreadItem['type'], number>>
debug: 30,
}
+/** The quill thread leaves a lone call or thought outside a group, and such a row shows its own live state. */
+function quillRowShowsProgress(item: ThreadDisplayItem, toolInvocations: ReadonlyMap<string, ToolInvocation>): boolean {
+ switch (item.type) {
+ case 'assistant_thought':
+ // An empty thought renders nothing, so the bottom indicator still has to show.
+ return !!item.text?.trim()
+ case 'tool_invocation': {
+ const status = item.toolCallId ? toolInvocations.get(item.toolCallId)?.status : undefined
+ return status === 'pending' || status === 'in_progress'
+ }
+ case 'status':
+ return isStartupStatus(item) || isRunningStatus(item)
+ default:
+ return false
+ }
+}
+
function estimateThreadItemHeight(item: ThreadDisplayItem): number {
if (item.type === 'activity_group') {
return 48
@@ -129,15 +152,22 @@ export function ThreadView({
// still going, so it keeps the softer title.
const runEnded = isTerminalRunStatus(currentRunStatus)
const displayItems = useMemo(() => {
- const standaloneToolIds = new Set<string>()
+ const pinnedToolIds = new Set<string>()
+ const widgetToolIds = new Set<string>()
for (const [id, invocation] of toolInvocations) {
const resolved = resolveToolCall(invocation)
- if (lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName).keepVisible) {
- standaloneToolIds.add(id)
+ const entry = lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName)
+ if (entry.pinned) {
+ pinnedToolIds.add(id)
+ } else if (entry.keepVisible) {
+ widgetToolIds.add(id)
}
}
- return groupThreadActivity(threadItems, standaloneToolIds)
- }, [threadItems, toolInvocations])
+ if (skin === 'quill') {
+ return groupToolRuns(threadItems, toolInvocations, { pinnedToolIds, widgetToolIds, settled: !isThinking })
+ }
+ return groupThreadActivity(threadItems, new Set([...pinnedToolIds, ...widgetToolIds]))
+ }, [threadItems, toolInvocations, skin, isThinking])
// The last human message anchors the thread. Reopening a saved conversation lands on it — the last
// meaningful turn, response below — when at least a viewport of content follows it (otherwise the
// bottom); a fresh send (a new key) pins the thread to the bottom to follow the streaming response.
@@ -146,13 +176,11 @@ export function ThreadView({
[threadItems]
)
// Only computed when a trailer renderer is supplied — bare ThreadViews pay nothing.
- const turns = useMemo(
- () =>
- renderTurnTrailer
- ? { trailers: computeTurnTrailers(threadItems), rowTurnIds: mapRowsToTurnSeparator(displayItems) }
- : null,
- [threadItems, displayItems, renderTurnTrailer]
+ const trailers = useMemo(
+ () => (renderTurnTrailer ? computeTurnTrailers(threadItems) : null),
+ [threadItems, renderTurnTrailer]
)
+ const revealGroups = useMemo(() => mapRowsToRevealGroup(displayItems), [displayItems])
const [turnHoverStore] = useState(() => new TurnHoverStore())
// Header/footer are kept as memoized leaf components with stable element identity so they don't rebuild
@@ -172,11 +200,12 @@ export function ThreadView({
// The connection banner (reconnecting / connection-failed) owns the footer line when present, so it
// takes precedence over the thinking indicator (a mid-run reconnect otherwise reads as normal thinking).
const showConnectionStatus = !!runConnectionState
+ const lastItem = displayItems.at(-1)
+ const lastRowShowsProgress =
+ lastItem?.type === 'activity_group' ||
+ (skin === 'quill' && !!lastItem && quillRowShowsProgress(lastItem, toolInvocations))
const showThinking =
- showThinkingIndicator &&
- !showConnectionStatus &&
- !pendingPermissionRequest &&
- displayItems.at(-1)?.type !== 'activity_group'
+ showThinkingIndicator && !showConnectionStatus && !pendingPermissionRequest && !lastRowShowsProgress
const thinkingPhase = streamPhase === 'provisioning' ? 'provisioning' : 'thinking'
// Post-turn only: a reconnect refetch can fold in a pr_url mid-run, so gate on !isThinking.
const pullRequestUrl = !isThinking ? runArtifacts.prUrl : undefined
@@ -216,7 +245,7 @@ export function ThreadView({
const isLast = index === displayItems.length - 1
return (
<VirtualizedThread.Row className={rowClassName}>
- <TurnReveal store={turnHoverStore} turnId={turns?.rowTurnIds.get(item.id)}>
+ <TurnReveal store={turnHoverStore} turnId={revealGroups.get(item.id)}>
<ThreadActivityGroup
group={item}
toolInvocations={toolInvocations}
@@ -239,7 +268,7 @@ export function ThreadView({
)
}
if (item.type === 'turn_separator' && renderTurnTrailer) {
- const trailer = turns?.trailers.get(item.id)
+ const trailer = trailers?.get(item.id)
return (
<VirtualizedThread.Row className={rowClassName}>
{trailer ? (
@@ -252,7 +281,7 @@ export function ThreadView({
}
return (
<VirtualizedThread.Row className={rowClassName}>
- <TurnReveal store={turnHoverStore} turnId={turns?.rowTurnIds.get(item.id)}>
+ <TurnReveal store={turnHoverStore} turnId={revealGroups.get(item.id)}>
<ThreadRow
item={item}
isLast={index === displayItems.length - 1}
@@ -274,7 +303,8 @@ export function ThreadView({
turnCancelled,
rowClassName,
renderTurnTrailer,
- turns,
+ trailers,
+ revealGroups,
turnHoverStore,
pendingPermissionRequest,
currentRunStatus,
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
index f827f0369557..8897af7ccbcf 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
@@ -1004,8 +1004,9 @@ function Row({ children, className }: { children: ReactNode; className?: string
// child. Border-box measurement is transform-safe, so the imperative positioning does not distort it.
return (
<div ref={measureRef} style={ROW_BASE_STYLE}>
+ {/* A row whose content renders nothing (such as the trailing row between turns) takes no space, so the thread does not jump. */}
<div
- className={cn('w-full mx-auto @container/thread', maxWidthClassName, className)}
+ className={cn('w-full mx-auto @container/thread empty:hidden', maxWidthClassName, className)}
style={{ paddingBottom: index === lastIndex ? 0 : gap }}
>
{children}
diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx
index d45c8b008269..fd7474088238 100644
--- a/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx
+++ b/products/posthog_ai/frontend/components/composer/AttachedContextPicker.tsx
@@ -7,16 +7,7 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
import { attachedContextLogic } from '../../logics/attachedContextLogic'
-import { contextPickerLogic } from '../../logics/contextPickerLogic'
-
-const PICKER_GROUP_TYPES: TaxonomicFilterGroupType[] = [
- TaxonomicFilterGroupType.Events,
- TaxonomicFilterGroupType.Actions,
- TaxonomicFilterGroupType.Insights,
- TaxonomicFilterGroupType.Dashboards,
- TaxonomicFilterGroupType.Notebooks,
- TaxonomicFilterGroupType.ErrorTrackingIssues,
-]
+import { CONTEXT_PICKER_GROUP_TYPES, contextPickerLogic } from '../../logics/contextPickerLogic'
export interface AttachedContextPickerProps {
className?: string
@@ -37,7 +28,7 @@ export function AttachedContextPicker({ className = 'flex-shrink-0 border' }: At
type="tertiary"
className={className}
groupType={TaxonomicFilterGroupType.Events}
- groupTypes={PICKER_GROUP_TYPES}
+ groupTypes={CONTEXT_PICKER_GROUP_TYPES}
onChange={handleTaxonomicFilterChange}
icon={<IconAtSign className="text-secondary" />}
placeholder={hasContext ? null : 'Add context'}
diff --git a/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx
index 3216276603fe..cb2cf8ecdc3a 100644
--- a/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx
+++ b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx
@@ -1,5 +1,7 @@
import { useEffect } from 'react'
+import { useThreadSkin } from '../../hooks/useThreadSkin'
+
export interface ComposerModeShortcutProps {
/** Fired on Shift+Tab — cycle to the next permission mode. */
onCycle: () => void
@@ -11,14 +13,16 @@ export interface ComposerModeShortcutProps {
* where the shortcut is global. Mount it inside the composer subtree so it detaches with the composer —
* e.g. while a pending plan approval replaces the composer slot, whose selector owns Tab itself. Yields to
* anything that already handled the key (`defaultPrevented`) and to open menus/dialogs, which own Tab for
- * their internal focus order.
+ * their internal focus order. Off in the quill skin, where Shift+Tab keeps its normal job of moving focus back.
*/
export function ComposerModeShortcut({ onCycle, disabled = false }: ComposerModeShortcutProps): null {
+ const skin = useThreadSkin()
+ const off = disabled || skin === 'quill'
// No dep array on purpose: re-attaching keeps the listener's `onCycle` closure current (callers pass
// inline arrows over the selected mode) — same pattern as the plan-approval selector's shortcuts.
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent): void => {
- if (disabled || e.key !== 'Tab' || !e.shiftKey || e.defaultPrevented) {
+ if (off || e.key !== 'Tab' || !e.shiftKey || e.defaultPrevented) {
return
}
if (e.target instanceof HTMLElement && e.target.closest('[role="menu"],[role="dialog"]')) {
diff --git a/products/posthog_ai/frontend/components/quill/QuillActivity.tsx b/products/posthog_ai/frontend/components/quill/QuillActivity.tsx
index d2e347d15e20..4ebea68979c5 100644
--- a/products/posthog_ai/frontend/components/quill/QuillActivity.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillActivity.tsx
@@ -38,8 +38,9 @@ export function QuillActivity({
<div className="flex min-w-0 flex-col gap-1">
<ThreadMarker
icon={status === 'failed' && failedIcon ? failedIcon : icon}
- running={isRunning && animate}
+ running={isRunning}
spinner={showProgressIcon}
+ shimmer={animate}
failed={status === 'failed'}
body={body}
open={open}
diff --git a/products/posthog_ai/frontend/components/quill/QuillActivityGroup.tsx b/products/posthog_ai/frontend/components/quill/QuillActivityGroup.tsx
index ce9ee50c7ab7..c5a7c1fcd5e1 100644
--- a/products/posthog_ai/frontend/components/quill/QuillActivityGroup.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillActivityGroup.tsx
@@ -1,33 +1,45 @@
import { IconWrench } from '@posthog/icons'
-import { Button } from '@posthog/quill-primitives'
+import { Button, cn } from '@posthog/quill-primitives'
-import { ActivityElapsedTime } from '../ActivityElapsedTime'
+import type { ToolInvocation } from '../../types/streamTypes'
+import { resolveToolCall } from '../../utils/toolResolver'
+import { summarizeToolRun } from '../../utils/toolRunSummary'
import { ActivityGroupRows } from '../ActivityGroupRows'
+import { lookupToolRenderer } from '../tool/toolRegistry'
import { type ActivityGroupProps, useActivityGroup } from '../useActivityGroup'
import { ThreadMarker } from './ThreadMarker'
+function describeCall(call: ToolInvocation): { name: string; detail?: string; icon: JSX.Element } {
+ const resolved = resolveToolCall(call)
+ const { displayName, icon } = lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName)
+ // The PostHog MCP asks the agent for a one-sentence `context` on every call, and its `exec` title says nothing.
+ const intent = typeof call.input.context === 'string' ? call.input.context.trim() : ''
+ if (intent || resolved.innerToolName || !call.title) {
+ return { name: displayName, detail: intent || undefined, icon }
+ }
+ // A title such as "Read digest/scheduler.py" already names the tool.
+ if (call.title.toLowerCase().startsWith(displayName.toLowerCase())) {
+ return { name: call.title, icon }
+ }
+ return { name: displayName, detail: call.title, icon }
+}
+
+const isRunning = (call: ToolInvocation): boolean => call.status === 'pending' || call.status === 'in_progress'
+
export function QuillActivityGroup(props: ActivityGroupProps): JSX.Element {
- const { group, toolInvocations, active, waitingForInput = false, renderItem } = props
- const {
- label,
- currentLabel,
- calls,
- thoughtsOnly,
- expanded,
- setExpanded,
- window,
- showMiddle,
- toggleMiddle,
- visibleThoughtsOnly,
- newCount,
- showNew,
- } = useActivityGroup(props)
+ const { group, toolInvocations, active, cancelled, waitingForInput = false, renderItem } = props
+ const { calls, expanded, setExpanded, window, showMiddle, toggleMiddle, visibleThoughtsOnly, newCount, showNew } =
+ useActivityGroup(props)
const rowProps = { thoughtsOnly: visibleThoughtsOnly, toolInvocations, active, renderItem }
const running = active && !waitingForInput
+ const thinking = running && group.items.at(-1)?.type === 'assistant_thought'
+ const current = calls.findLast(isRunning) ?? calls.at(-1)
+ const lead = current ? describeCall(current) : undefined
+ const failedCount = calls.filter((call) => call.status === 'failed').length
return (
<ThreadMarker
- icon={<IconWrench />}
+ icon={lead?.icon ?? <IconWrench />}
running={running}
spinner
open={expanded}
@@ -63,17 +75,34 @@ export function QuillActivityGroup(props: ActivityGroupProps): JSX.Element {
</div>
}
>
- <span className="shrink-0 font-medium" data-attr="thread-activity-toggle">
- {running && !thoughtsOnly ? currentLabel : label}
- </span>
- {waitingForInput && <span className="truncate">Review the request below</span>}
- {!waitingForInput && (
- <ActivityElapsedTime startedAt={group.startedAt} endedAt={group.endedAt} active={active} />
- )}
- {calls.length > 0 && (
- <span className="shrink-0 tabular-nums">
- · {calls.length} tool {calls.length === 1 ? 'call' : 'calls'}
- </span>
+ {waitingForInput ? (
+ <>
+ <span className="shrink-0 font-medium" data-attr="thread-activity-toggle">
+ Waiting for you
+ </span>
+ <span className="truncate">Review the request below</span>
+ </>
+ ) : running ? (
+ <>
+ <span
+ className={cn('truncate font-medium', !thinking && lead?.detail ? 'shrink-0' : 'min-w-0')}
+ data-attr="thread-activity-toggle"
+ >
+ {thinking || !lead ? 'Thinking…' : lead.name}
+ </span>
+ {!thinking && lead?.detail && <span className="truncate opacity-70">{lead.detail}</span>}
+ </>
+ ) : (
+ <>
+ {/* A collapsed group still has to say the run stopped, or that a call in it failed. */}
+ {cancelled && <span className="shrink-0 font-medium">Stopped</span>}
+ <span className="truncate" data-attr="thread-activity-toggle">
+ {summarizeToolRun(calls)}
+ </span>
+ {failedCount > 0 && (
+ <span className="shrink-0 text-(--destructive-foreground)">{failedCount} failed</span>
+ )}
+ </>
)}
</ThreadMarker>
)
diff --git a/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsx b/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsx
new file mode 100644
index 000000000000..7693563f4416
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsx
@@ -0,0 +1,68 @@
+import { useActions, useValues } from 'kea'
+import { useId, useState } from 'react'
+
+import { IconAtSign } from '@posthog/icons'
+import {
+ Button,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@posthog/quill-primitives'
+
+import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { attachedContextLogic } from '../../logics/attachedContextLogic'
+import { CONTEXT_PICKER_GROUP_TYPES, contextPickerLogic } from '../../logics/contextPickerLogic'
+
+export function QuillAttachedContextPicker(): JSX.Element {
+ const [open, setOpen] = useState(false)
+ const filterKey = `posthog-ai-context-picker-${useId()}`
+ const { hasContext } = useValues(attachedContextLogic)
+ const { handleTaxonomicFilterChange } = useActions(contextPickerLogic)
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <PopoverTrigger
+ render={
+ <Button
+ variant="default"
+ size={hasContext ? 'icon-sm' : 'sm'}
+ aria-label="Add context"
+ data-attr="posthog-ai-context-picker"
+ >
+ <IconAtSign />
+ {!hasContext && 'Add context'}
+ </Button>
+ }
+ />
+ }
+ />
+ <TooltipContent>Add context to help PostHog AI answer your question</TooltipContent>
+ </Tooltip>
+ <PopoverContent side="top" align="start" className="w-auto p-0">
+ {/* The filter is Lemon, so it keeps Lemon's colors inside the quill popover. */}
+ <div data-not-quill>
+ <TaxonomicFilter
+ taxonomicFilterLogicKey={filterKey}
+ groupType={TaxonomicFilterGroupType.Events}
+ taxonomicGroupTypes={CONTEXT_PICKER_GROUP_TYPES}
+ onChange={({ type }, value, item) => {
+ if (value !== null) {
+ handleTaxonomicFilterChange(value, type, item)
+ }
+ setOpen(false)
+ }}
+ onClose={() => setOpen(false)}
+ width={450}
+ />
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx b/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx
index 88f297f15dcd..322efff13ae9 100644
--- a/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillComposerLayout.tsx
@@ -33,7 +33,8 @@ export function QuillComposerLayout({
className={
// The textarea is Lemon's, so quill's own focus rule, keyed to its input slot, never fires here.
'h-auto cursor-text bg-[var(--card)] focus-within:border-[color-mix(in_oklab,var(--ring)_50%,transparent)] focus-within:shadow-[0_0_0_3px_color-mix(in_oklab,var(--ring)_30%,transparent)] ' +
- '[&_[data-slot=composer-placeholder]]:top-2.5 [&_[data-slot=composer-placeholder]]:left-3.5 [&_textarea]:min-h-[37px]'
+ // LemonTextArea puts the composer's padding on both its wrapper and the textarea. The wrapper keeps it, so the textarea drops it. The textarea keeps 2px on the left because it clips the caret at x=0.
+ '[&_[data-slot=composer-placeholder]]:top-2 [&_[data-slot=composer-placeholder]]:left-2.5 [&_textarea]:min-h-[37px] [&_textarea]:p-0 [&_textarea]:pl-0.5'
}
>
<InputGroupAddon align="block-start" className="flex-wrap">
diff --git a/products/posthog_ai/frontend/components/quill/QuillFooterTimestamp.tsx b/products/posthog_ai/frontend/components/quill/QuillFooterTimestamp.tsx
new file mode 100644
index 000000000000..595dd18c3f98
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillFooterTimestamp.tsx
@@ -0,0 +1,6 @@
+import { TZLabel } from 'lib/components/TZLabel'
+
+export function QuillFooterTimestamp({ time }: { time: number }): JSX.Element {
+ // A fresh dayjs object every render would defeat TZLabel's memo; a string compares by value.
+ return <TZLabel time={new Date(time).toISOString()} hoverOpenDelayMs={500} className="text-xs text-foreground" />
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillMessages.tsx b/products/posthog_ai/frontend/components/quill/QuillMessages.tsx
index a79a552d192e..1d4c23f9fcc9 100644
--- a/products/posthog_ai/frontend/components/quill/QuillMessages.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillMessages.tsx
@@ -1,4 +1,4 @@
-import { memo, type ReactNode, useEffect, useRef, useState } from 'react'
+import { memo, type ReactNode, useContext, useEffect, useRef, useState } from 'react'
import { IconChevronDown } from '@posthog/icons'
import {
@@ -10,13 +10,14 @@ import {
cn,
} from '@posthog/quill-primitives'
-import { TZLabel } from 'lib/components/TZLabel'
-
import { MarkdownMessage } from '../../messages/MarkdownMessage'
import type { ThreadItem } from '../../types/streamTypes'
import { userMessageDisplayText } from '../../utils/userMessageDisplay'
import { ThreadAttachments } from '../ThreadAttachments'
+import { TurnRevealContext } from '../TurnRevealContext'
+import { footerRevealClass } from './footerReveal'
import { QuillCopyButton } from './QuillFooterButton'
+import { QuillFooterTimestamp } from './QuillFooterTimestamp'
/**
* Clamps a user bubble to five lines with a Show more toggle. Overflow depends on wrapping width, so it
@@ -66,8 +67,9 @@ function ClampedContent({ children }: { children: ReactNode }): JSX.Element {
export const QuillHumanMessage = memo(function QuillHumanMessage({ item }: { item: ThreadItem }): JSX.Element {
const text = userMessageDisplayText(item.text ?? '')
+ const revealed = useContext(TurnRevealContext)
return (
- <ChatMessage align="end" className="group" data-attr="posthog-ai-human-message">
+ <ChatMessage align="end" data-attr="posthog-ai-human-message">
<ChatMessageContent className="gap-1">
{item.attachments && (
<div className="self-end">
@@ -81,11 +83,8 @@ export const QuillHumanMessage = memo(function QuillHumanMessage({ item }: { ite
</ClampedContent>
</ChatBubbleContent>
</ChatBubble>
- <ChatMessageFooter className="min-h-5 items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
- {item.startedAt !== undefined && (
- // A fresh dayjs object every render would defeat TZLabel's memo; a string compares by value.
- <TZLabel time={new Date(item.startedAt).toISOString()} className="text-xs text-foreground" />
- )}
+ <ChatMessageFooter className={cn('min-h-5 items-center gap-1', footerRevealClass(revealed))}>
+ {item.startedAt !== undefined && <QuillFooterTimestamp time={item.startedAt} />}
{text && (
<QuillCopyButton value={text} label="Copy message" dataAttr="posthog-ai-human-message-copy" />
)}
diff --git a/products/posthog_ai/frontend/components/quill/QuillModePicker.tsx b/products/posthog_ai/frontend/components/quill/QuillModePicker.tsx
index 122c226e5b35..c35292436ba9 100644
--- a/products/posthog_ai/frontend/components/quill/QuillModePicker.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillModePicker.tsx
@@ -1,4 +1,4 @@
-import { useRef, useState } from 'react'
+import { useState } from 'react'
import {
Button,
@@ -29,23 +29,12 @@ export interface QuillModePickerProps {
export function QuillModePicker({ selectedMode, onModeChange, modes }: QuillModePickerProps): JSX.Element {
const [open, setOpen] = useState(false)
- // Applied once the menu has closed, so the toolbar doesn't relayout under the closing menu.
- const pendingModeRef = useRef<PermissionMode | null>(null)
const options = modes.flatMap((mode) => MODE_OPTIONS.filter((option) => option.value === mode))
const selectedLabel = getModeOption(selectedMode)?.label ?? 'Mode'
const unsupervised = UNSUPERVISED_MODES.includes(selectedMode)
return (
- <DropdownMenu
- open={open}
- onOpenChange={setOpen}
- onOpenChangeComplete={(isOpen) => {
- if (!isOpen && pendingModeRef.current !== null) {
- onModeChange(pendingModeRef.current)
- pendingModeRef.current = null
- }
- }}
- >
+ <DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger
render={
<Button
@@ -63,8 +52,10 @@ export function QuillModePicker({ selectedMode, onModeChange, modes }: QuillMode
<MenuLabel>Mode</MenuLabel>
<DropdownMenuRadioGroup
value={selectedMode}
+ // Applied on pick, not after the menu closes: a message sent during the close would
+ // otherwise still run in the old mode, which may skip the approval just chosen.
onValueChange={(value) => {
- pendingModeRef.current = value as PermissionMode
+ onModeChange(value as PermissionMode)
setOpen(false)
}}
>
diff --git a/products/posthog_ai/frontend/components/quill/QuillOnboardingReplayButton.tsx b/products/posthog_ai/frontend/components/quill/QuillOnboardingReplayButton.tsx
new file mode 100644
index 000000000000..61cb28df340f
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillOnboardingReplayButton.tsx
@@ -0,0 +1,39 @@
+import { useActions } from 'kea'
+
+import { IconInfo } from '@posthog/icons'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill-primitives'
+
+import { aiOnboardingLogic } from '../../logics/aiOnboardingLogic'
+
+export interface QuillOnboardingReplayButtonProps {
+ panelId?: string
+ className?: string
+}
+
+/**
+ * Quill skin of `OnboardingReplayButton`: an icon-only trigger for the composer toolbar. Temporary for the same
+ * reason, so delete it with that component once the migration to the new PostHog AI is done.
+ */
+export function QuillOnboardingReplayButton({ panelId, className }: QuillOnboardingReplayButtonProps): JSX.Element {
+ const { openOnboarding } = useActions(aiOnboardingLogic({ panelId }))
+
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label="What's new in PostHog AI"
+ onClick={() => openOnboarding(true)}
+ className={className}
+ data-attr="posthog-ai-onboarding-replay"
+ >
+ <IconInfo />
+ </Button>
+ }
+ />
+ <TooltipContent>What's new in PostHog AI</TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.test.tsx b/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.test.tsx
index c49211d2f607..29d3e10dd84f 100644
--- a/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.test.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.test.tsx
@@ -26,29 +26,62 @@ const OPTIONS: ApprovalCardOption[] = [
},
]
+const WITH_REQUIRED_NOTE: ApprovalCardOption[] = [
+ ...OPTIONS,
+ {
+ optionId: 'redirect',
+ label: 'Do it differently',
+ decision: 'declined',
+ primary: false,
+ remembered: false,
+ requiresFeedback: true,
+ supportsFeedback: false,
+ },
+]
+
describe('QuillPermissionQuestionnaire', () => {
afterEach(() => {
cleanup()
})
test.each([
- { answer: 'the approve choice', pick: () => fireEvent.click(screen.getByText('Yes')), expected: ['allow'] },
- { answer: 'the plain decline', pick: () => fireEvent.click(screen.getByText('No')), expected: ['reject'] },
+ {
+ answer: 'the approve choice',
+ options: OPTIONS,
+ pick: () => fireEvent.click(screen.getByText('Yes')),
+ expected: ['allow'],
+ },
+ {
+ answer: 'the plain decline',
+ options: OPTIONS,
+ pick: () => fireEvent.click(screen.getByText('No')),
+ expected: ['reject'],
+ },
{
answer: 'a typed note',
+ options: OPTIONS,
pick: () =>
fireEvent.change(screen.getByLabelText('Tell the agent what to do differently'), {
target: { value: 'use the staging project' },
}),
expected: ['reject', 'use the staging project'],
},
- ])('sends $answer on submit', ({ pick, expected }) => {
+ {
+ answer: 'a note under its own decline when several take one',
+ options: WITH_REQUIRED_NOTE,
+ pick: () =>
+ fireEvent.change(screen.getByLabelText('Do it differently'), {
+ target: { value: 'use the staging project' },
+ }),
+ expected: ['redirect', 'use the staging project'],
+ },
+ ])('sends $answer on submit', ({ options, pick, expected }) => {
const onRespond = jest.fn()
render(
<QuillPermissionQuestionnaire
headline="Update the task summary"
evidence={null}
- options={OPTIONS}
+ options={options}
responding={false}
onRespond={onRespond}
/>
diff --git a/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.tsx b/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.tsx
index 83d6564d52a7..6f140666ffe4 100644
--- a/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillPermissionQuestionnaire.tsx
@@ -19,12 +19,17 @@ import {
QuestionnaireTitle,
} from '@posthog/quill-primitives'
-import { FEEDBACK_PLACEHOLDER, optionRowLabel, optionSublabel } from '../../policy/permissionOptionCopy'
+import {
+ FEEDBACK_PLACEHOLDER,
+ isFeedbackOption,
+ optionRowLabel,
+ optionSublabel,
+} from '../../policy/permissionOptionCopy'
import type { ApprovalCardOption } from '../../policy/permissionUtils'
const ANSWER_NAME = 'permission'
-type PermissionAnswer = { kind: 'choice'; optionId: string } | { kind: 'note'; text: string }
+type PermissionAnswer = { kind: 'choice'; optionId: string } | { kind: 'note'; optionId: string; text: string }
export interface QuillPermissionQuestionnaireProps {
headline: ReactNode
@@ -37,9 +42,13 @@ export interface QuillPermissionQuestionnaireProps {
/**
* The note row answers a decline that relays feedback, so that decline's own choice only has to say "No".
* Without that split the choice and the note row both read as "tell the agent what to do differently".
+ * With several such declines, each keeps its own label so the choices stay distinct.
*/
-function choiceCopy(option: ApprovalCardOption): { label: string; description: string | null } {
- if (option.supportsFeedback) {
+function choiceCopy(
+ option: ApprovalCardOption,
+ soleFeedbackOption: boolean
+): { label: string; description: string | null } {
+ if (option.supportsFeedback && soleFeedbackOption) {
return { label: 'No', description: 'Stops this turn.' }
}
return { label: optionRowLabel(option), description: optionSublabel(option) }
@@ -53,7 +62,8 @@ export function QuillPermissionQuestionnaire({
onRespond,
}: QuillPermissionQuestionnaireProps): JSX.Element {
const [answer, setAnswer] = useState<PermissionAnswer | null>(null)
- const feedbackOption = options.find((option) => option.requiresFeedback || option.supportsFeedback)
+ const feedbackOptions = options.filter(isFeedbackOption)
+ const soleFeedbackOption = feedbackOptions.length === 1
const choiceOptions = options.filter((option) => !option.requiresFeedback)
return (
@@ -71,10 +81,10 @@ export function QuillPermissionQuestionnaire({
if (responding || !answer) {
return
}
- if (answer.kind === 'choice') {
+ if (answer.kind === 'note') {
+ onRespond(answer.optionId, answer.text)
+ } else {
onRespond(answer.optionId)
- } else if (feedbackOption) {
- onRespond(feedbackOption.optionId, answer.text)
}
}}
>
@@ -84,7 +94,7 @@ export function QuillPermissionQuestionnaire({
<QuestionnaireTitle className="sr-only">Allow this?</QuestionnaireTitle>
<QuestionnaireChoices>
{choiceOptions.map((option) => {
- const { label, description } = choiceCopy(option)
+ const { label, description } = choiceCopy(option, soleFeedbackOption)
return (
<QuestionnaireChoice
key={option.optionId}
@@ -103,18 +113,26 @@ export function QuillPermissionQuestionnaire({
</QuestionnaireChoice>
)
})}
- {feedbackOption && (
- <QuestionnaireInput
- aria-label={FEEDBACK_PLACEHOLDER}
- placeholder={FEEDBACK_PLACEHOLDER}
- onChange={(event) => {
- const text = event.target.value.trim()
- setAnswer((current) =>
- text ? { kind: 'note', text } : current?.kind === 'note' ? null : current
- )
- }}
- />
- )}
+ {feedbackOptions.map((option) => {
+ const noteLabel = soleFeedbackOption ? FEEDBACK_PLACEHOLDER : optionRowLabel(option)
+ return (
+ <QuestionnaireInput
+ key={option.optionId}
+ aria-label={noteLabel}
+ placeholder={noteLabel}
+ onChange={(event) => {
+ const text = event.target.value.trim()
+ setAnswer((current) =>
+ text
+ ? { kind: 'note', optionId: option.optionId, text }
+ : current?.kind === 'note' && current.optionId === option.optionId
+ ? null
+ : current
+ )
+ }}
+ />
+ )
+ })}
</QuestionnaireChoices>
<QuestionnaireError />
</QuestionnaireItem>
diff --git a/products/posthog_ai/frontend/components/quill/QuillPullRequestRow.tsx b/products/posthog_ai/frontend/components/quill/QuillPullRequestRow.tsx
index ef4e1fe1ad5c..ea1918379b7b 100644
--- a/products/posthog_ai/frontend/components/quill/QuillPullRequestRow.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillPullRequestRow.tsx
@@ -8,7 +8,7 @@ import { ThreadMarker } from './ThreadMarker'
export function QuillPullRequestRow({ prUrl, branch }: { prUrl: string; branch?: string }): JSX.Element {
return (
<div className="flex items-center gap-2" data-attr="max-sandbox-pr-card">
- <ThreadMarker icon={<IconPullRequest />} className="opacity-100">
+ <ThreadMarker icon={<IconPullRequest />} className="opacity-100 text-foreground">
<span className="font-medium">Pull request opened</span>
{branch && <ChatMarkerValue className="font-mono">{branch}</ChatMarkerValue>}
</ThreadMarker>
diff --git a/products/posthog_ai/frontend/components/quill/QuillRunContextRow.tsx b/products/posthog_ai/frontend/components/quill/QuillRunContextRow.tsx
new file mode 100644
index 000000000000..6bd521663dc0
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillRunContextRow.tsx
@@ -0,0 +1,20 @@
+import { IconGitBranch } from '@posthog/icons'
+import { ChatMarkerValue } from '@posthog/quill-primitives'
+
+import { ThreadMarker } from './ThreadMarker'
+
+export interface QuillRunContextRowProps {
+ branch: string
+ baseBranch?: string
+ repo?: string
+}
+
+export function QuillRunContextRow({ branch, baseBranch, repo }: QuillRunContextRowProps): JSX.Element {
+ return (
+ <ThreadMarker icon={<IconGitBranch />}>
+ <span data-attr="max-sandbox-run-context">Working on</span>
+ {repo && <ChatMarkerValue>{repo}</ChatMarkerValue>}
+ <ChatMarkerValue className="font-mono">{baseBranch ? `${branch} → ${baseBranch}` : branch}</ChatMarkerValue>
+ </ThreadMarker>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.tsx b/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.tsx
new file mode 100644
index 000000000000..b37a3bd280e6
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.tsx
@@ -0,0 +1,63 @@
+import { ChatMarker, ChatMarkerContent } from '@posthog/quill-primitives'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { ThreadItem } from '../../types/streamTypes'
+import { isRunningStatus, isStartupStatus } from '../../utils/groupThreadActivity'
+
+const RUNNING_LABELS: Record<string, string> = {
+ compacting: 'Compacting conversation history…',
+ clearing: 'Clearing conversation…',
+ setup_hooks: 'Running repository setup…',
+ sdk_initialization: 'Starting the agent…',
+}
+
+const SETTLED_LABELS: Record<string, string> = {
+ compacting_failed: "Couldn't compact the conversation",
+ refusal: 'The model declined this request. Rephrase it, or switch models and try again.',
+ refusal_fallback: 'Request declined, retried with the fallback model',
+}
+
+function statusLabel(item: ThreadItem, live: boolean): { label: string; running: boolean } {
+ const status = item.status ?? ''
+ if (isStartupStatus(item)) {
+ return live ? { label: RUNNING_LABELS[status], running: true } : { label: 'Agent started', running: false }
+ }
+ if (isRunningStatus(item)) {
+ return { label: RUNNING_LABELS[status], running: true }
+ }
+ // A failed clear leaves the agent session closed, so the way forward is a new run, not a retry.
+ if (status === 'clearing_failed') {
+ const reason = item.errorMessage
+ ? `Couldn't clear the conversation: ${item.errorMessage}`
+ : "Couldn't clear the conversation"
+ return { label: `${reason}. Start a new run to keep going.`, running: false }
+ }
+ const label = SETTLED_LABELS[status] ?? status.replaceAll('_', ' ')
+ return { label: label.charAt(0).toUpperCase() + label.slice(1), running: false }
+}
+
+function separatorLabel(item: ThreadItem, live: boolean): { label: string; running: boolean } {
+ if (item.type === 'compact_boundary') {
+ const parts = [
+ 'Conversation compacted',
+ item.trigger,
+ typeof item.preTokens === 'number' ? `~${humanFriendlyNumber(item.preTokens)} tokens summarized` : null,
+ ]
+ return { label: parts.filter(Boolean).join(' · '), running: false }
+ }
+ if (item.type === 'conversation_cleared') {
+ return { label: 'Conversation cleared', running: false }
+ }
+ return statusLabel(item, live)
+}
+
+/** `live` keeps a startup phase reading as in progress until the agent's output follows it. */
+export function QuillSeparatorRow({ item, live }: { item: ThreadItem; live: boolean }): JSX.Element {
+ const { label, running } = separatorLabel(item, live)
+ return (
+ <ChatMarker variant="separator" status={running ? 'running' : undefined}>
+ <ChatMarkerContent>{label}</ChatMarkerContent>
+ </ChatMarker>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillThread.stories.tsx b/products/posthog_ai/frontend/components/quill/QuillThread.stories.tsx
index 4de0b0d4e6ee..e5ca3ba0b336 100644
--- a/products/posthog_ai/frontend/components/quill/QuillThread.stories.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillThread.stories.tsx
@@ -21,18 +21,32 @@ function toolCall(
id: string,
toolName: string,
title: string,
- rawInput: Record<string, unknown>
+ rawInput: Record<string, unknown>,
+ kind?: string
): StoredLogEntry {
return update(timestamp, {
sessionUpdate: 'tool_call',
toolCallId: id,
title,
+ kind,
status: 'in_progress',
rawInput,
_meta: { claudeCode: { toolName } },
})
}
+function posthogCall(timestamp: string, id: string, tool: string, args: object, context: string): StoredLogEntry {
+ return update(timestamp, {
+ sessionUpdate: 'tool_call',
+ toolCallId: id,
+ title: 'exec',
+ kind: 'other',
+ status: 'in_progress',
+ rawInput: { command: `call ${tool} ${JSON.stringify(args)}`, context },
+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },
+ })
+}
+
function toolResult(timestamp: string, id: string, status: string, text: string): StoredLogEntry {
return update(timestamp, {
sessionUpdate: 'tool_call_update',
@@ -51,13 +65,25 @@ const COMPLETED_TURN: StoredLogEntry[] = [
sessionUpdate: 'agent_thought_chunk',
content: { type: 'text', text: 'Start with the signup funnel, then compare it with the deploy log.' },
}),
- toolCall('2024-03-11T14:02:13Z', 'read-funnel', 'Read', 'Read signup_funnel.sql', {
- file_path: 'queries/signup_funnel.sql',
- }),
+ toolCall(
+ '2024-03-11T14:02:13Z',
+ 'read-funnel',
+ 'Read',
+ 'Read signup_funnel.sql',
+ { file_path: 'queries/signup_funnel.sql' },
+ 'read'
+ ),
toolResult('2024-03-11T14:02:14Z', 'read-funnel', 'completed', 'SELECT step, count() FROM funnel GROUP BY step'),
- toolCall('2024-03-11T14:02:15Z', 'grep-deploys', 'Grep', 'Search deploy log', { pattern: 'signup' }),
+ toolCall('2024-03-11T14:02:15Z', 'grep-deploys', 'Grep', 'Search deploy log', { pattern: 'signup' }, 'search'),
toolResult('2024-03-11T14:02:16Z', 'grep-deploys', 'completed', 'deploys.log:42: signup form validation changed'),
- toolCall('2024-03-11T14:02:17Z', 'run-tests', 'Bash', 'Run signup tests', { command: 'pnpm test signup' }),
+ toolCall(
+ '2024-03-11T14:02:17Z',
+ 'run-tests',
+ 'Bash',
+ 'Run signup tests',
+ { command: 'pnpm test signup' },
+ 'execute'
+ ),
toolResult('2024-03-11T14:02:19Z', 'run-tests', 'failed', '1 test failed: email validation rejects plus signs'),
update('2024-03-11T14:02:21Z', {
sessionUpdate: 'agent_message_chunk',
@@ -76,9 +102,102 @@ const STREAMING_TURN: StoredLogEntry[] = [
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: 'Can you fix the validation?' },
}),
- toolCall('2024-03-11T14:03:02Z', 'read-validator', 'Read', 'Read emailValidator.ts', {
- file_path: 'src/emailValidator.ts',
+ toolCall(
+ '2024-03-11T14:03:02Z',
+ 'read-validator',
+ 'Read',
+ 'Read emailValidator.ts',
+ { file_path: 'src/emailValidator.ts' },
+ 'read'
+ ),
+]
+
+const LONG_RUN_TURN: StoredLogEntry[] = [
+ update('2024-03-11T14:10:00Z', {
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Why did the weekly digest email go out twice on Monday?' },
+ }),
+ notification('2024-03-11T14:10:02Z', '_posthog/status', { status: 'setup_hooks' }),
+ notification('2024-03-11T14:10:09Z', '_posthog/status', { status: 'sdk_initialization' }),
+ update('2024-03-11T14:10:12Z', {
+ sessionUpdate: 'agent_message_chunk',
+ messageId: 'plan',
+ content: { type: 'text', text: "I'll check Monday's digest send events first, then the scheduler." },
+ }),
+ posthogCall(
+ '2024-03-11T14:10:13Z',
+ 'sql-sends',
+ 'execute-sql',
+ { query: "SELECT project_id, count() FROM events WHERE event = 'digest sent' GROUP BY project_id" },
+ 'Count digest sends per project on Monday'
+ ),
+ toolResult('2024-03-11T14:10:15Z', 'sql-sends', 'completed', 'project_id | count\n101 | 2\n102 | 1'),
+ posthogCall(
+ '2024-03-11T14:10:16Z',
+ 'sql-doubles',
+ 'execute-sql',
+ { query: "SELECT project_id, timestamp FROM events WHERE event = 'digest sent' ORDER BY timestamp" },
+ 'List the projects that got two sends'
+ ),
+ toolResult('2024-03-11T14:10:18Z', 'sql-doubles', 'completed', '101 | 09:00:02\n101 | 09:15:04'),
+ posthogCall(
+ '2024-03-11T14:10:19Z',
+ 'sql-scheduler',
+ 'execute-sql',
+ { query: "SELECT timestamp FROM events WHERE event = 'digest retry scheduled'" },
+ 'Compare send times with the retry job'
+ ),
+ toolResult('2024-03-11T14:10:21Z', 'sql-scheduler', 'completed', '09:15:00'),
+ update('2024-03-11T14:10:22Z', {
+ sessionUpdate: 'agent_thought_chunk',
+ content: { type: 'text', text: 'The second send lines up with the retry job. Check the scheduler code.' },
}),
+ toolCall(
+ '2024-03-11T14:10:23Z',
+ 'git-log',
+ 'Bash',
+ 'git log --oneline -5 -- digest/scheduler.py',
+ { command: 'git log --oneline -5 -- digest/scheduler.py' },
+ 'execute'
+ ),
+ toolResult('2024-03-11T14:10:24Z', 'git-log', 'completed', 'a1b2c3d Retry digests that time out'),
+ toolCall(
+ '2024-03-11T14:10:25Z',
+ 'read-scheduler',
+ 'Read',
+ 'Read digest/scheduler.py',
+ { file_path: 'digest/scheduler.py' },
+ 'read'
+ ),
+ toolResult('2024-03-11T14:10:26Z', 'read-scheduler', 'completed', 'def retry_digest(project):\n send(project)'),
+ toolCall(
+ '2024-03-11T14:10:27Z',
+ 'grep-retry',
+ 'Grep',
+ 'Search for retry_digest',
+ { pattern: 'retry_digest' },
+ 'search'
+ ),
+ toolResult('2024-03-11T14:10:28Z', 'grep-retry', 'completed', 'digest/scheduler.py:40\ndigest/jobs.py:12'),
+ toolCall(
+ '2024-03-11T14:10:29Z',
+ 'run-scheduler-tests',
+ 'Bash',
+ 'pytest digest/tests/test_scheduler.py',
+ { command: 'pytest digest/tests/test_scheduler.py' },
+ 'execute'
+ ),
+ toolResult('2024-03-11T14:10:33Z', 'run-scheduler-tests', 'failed', '1 failed: retry ignores the sent marker'),
+ update('2024-03-11T14:10:35Z', {
+ sessionUpdate: 'agent_message_chunk',
+ messageId: 'finding',
+ content: {
+ type: 'text',
+ text: 'The retry job sends the digest again when the first send is slow, because it never checks whether that send finished.',
+ },
+ }),
+ notification('2024-03-11T14:10:36Z', '_posthog/compact_boundary', { trigger: 'auto', preTokens: 152000 }),
+ notification('2024-03-11T14:10:37Z', '_posthog/turn_complete', {}),
]
function renderTrailer(trailer: TurnTrailer): JSX.Element {
@@ -140,7 +259,15 @@ export default meta
type Story = StoryObj<typeof meta>
export const CompletedTurn: Story = {}
-export const StreamingTurn: Story = { args: { streamKey: 'example-quill-streaming', entries: STREAMING_TURN } }
+export const StreamingTurn: Story = {
+ args: { streamKey: 'example-quill-streaming', entries: STREAMING_TURN },
+ // A turn that is still running shows its progress spinner for as long as the story is open.
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+}
+export const LongRun: Story = {
+ args: { streamKey: 'example-quill-long-run', entries: LONG_RUN_TURN },
+ parameters: { mockDate: '2024-03-11T14:15:00Z' },
+}
export const ComparedWithLemon: Story = {
args: { streamKey: 'example-quill-compare', skin: 'both' },
parameters: { testOptions: { skip: true } },
diff --git a/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx b/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx
index c0d2e5ecb353..b3cdc90ce84d 100644
--- a/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx
@@ -1,15 +1,16 @@
-import { useContext } from 'react'
+import { useContext, useId } from 'react'
import { IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled, IconX } from '@posthog/icons'
import { Button, ChatMessageFooter, Input, Text, cn } from '@posthog/quill-primitives'
-import { TZLabel } from 'lib/components/TZLabel'
import { stripMarkdown } from 'lib/utils/markdown'
import type { TurnFeedbackActionsProps } from '../turnFeedbackTypes'
import { TurnRevealContext } from '../TurnRevealContext'
import { useTurnRating } from '../useTurnRating'
+import { footerRevealClass } from './footerReveal'
import { QuillCopyButton, QuillFooterButton } from './QuillFooterButton'
+import { QuillFooterTimestamp } from './QuillFooterTimestamp'
export function QuillTurnFeedbackActions({
sessionId,
@@ -22,18 +23,14 @@ export function QuillTurnFeedbackActions({
const turnHovered = useContext(TurnRevealContext)
const { rating, submitRating, feedback, setFeedback, feedbackInputStatus, closeFeedback, submitFeedback } =
useTurnRating({ sessionId, turnIndex, run, traceId })
+ const feedbackPromptId = useId()
return (
<div className="flex flex-col gap-2">
<ChatMessageFooter
- className={cn(
- 'min-h-5 items-center gap-1 ps-0 transition-opacity focus-within:opacity-100',
- rating || turnHovered ? 'opacity-100' : 'opacity-0'
- )}
+ className={cn('min-h-5 items-center gap-1 ps-0', footerRevealClass(!!rating || turnHovered))}
>
- {timestamp !== undefined && (
- <TZLabel time={new Date(timestamp).toISOString()} className="text-xs text-foreground" />
- )}
+ {timestamp !== undefined && <QuillFooterTimestamp time={timestamp} />}
{turnText && (
<QuillCopyButton
value={stripMarkdown(turnText)}
@@ -63,7 +60,7 @@ export function QuillTurnFeedbackActions({
{feedbackInputStatus !== 'hidden' && (
<div className="flex max-w-4/5 flex-col gap-2 rounded-lg border border-border p-3">
<div className="flex items-center gap-1">
- <Text size="sm" weight="medium" className="grow">
+ <Text id={feedbackPromptId} size="sm" weight="medium" className="grow">
{feedbackInputStatus === 'pending'
? 'What disappointed you about the answer?'
: 'Thank you for your feedback!'}
@@ -81,6 +78,7 @@ export function QuillTurnFeedbackActions({
}}
>
<Input
+ aria-labelledby={feedbackPromptId}
placeholder="Help us improve PostHog AI…"
value={feedback}
onChange={(event) => setFeedback(event.target.value)}
diff --git a/products/posthog_ai/frontend/components/quill/ThreadMarker.tsx b/products/posthog_ai/frontend/components/quill/ThreadMarker.tsx
index 8755d8225a24..edf85114eb16 100644
--- a/products/posthog_ai/frontend/components/quill/ThreadMarker.tsx
+++ b/products/posthog_ai/frontend/components/quill/ThreadMarker.tsx
@@ -3,23 +3,25 @@ import type { ReactNode } from 'react'
import { ChatMarker, ChatMarkerContent, ChatMarkerIcon, Spinner, cn } from '@posthog/quill-primitives'
/**
- * The row chrome every quill thread row shares. Quill's interactive row bleeds its hit area past the
- * text column, fills on hover and draws an outset focus ring; a transcript is mostly these rows, so they
- * stay flush with the column. Rows read in the thread's text color, not quill's muted row color.
+ * The row chrome every quill thread row shares, matching PostHog Desktop's tool rows. Quill's interactive row
+ * bleeds its hit area past the text column, fills on hover and draws an outset focus ring; a transcript is
+ * mostly these rows, so they stay flush with the column and at half opacity next to the prose.
*/
const QUILL_THREAD_ROW_CLASS = cn(
- 'mx-0 px-0 text-foreground hover:bg-transparent focus-visible:bg-transparent',
- 'data-panel-open:bg-transparent',
+ 'mx-0 px-0 opacity-50 hover:bg-transparent focus-visible:bg-transparent',
'[&_[data-slot=marker-panel]]:pt-2 [&_[data-slot=marker-panel]]:pb-1',
// Quill parks the chevron at the row's far end, which strands it from the text it opens.
'[&>svg:last-child]:ms-0',
- 'focus-visible:shadow-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring'
+ 'focus-visible:shadow-none focus-visible:ring-(--ring)/50 focus-visible:ring-2 focus-visible:ring-inset'
)
export interface ThreadMarkerProps {
icon?: ReactNode
running?: boolean
+ /** Swaps the icon for a spinner while running. */
spinner?: boolean
+ /** Sweeps the text while running. A tool row turns this off and shows only its spinner. */
+ shimmer?: boolean
failed?: boolean
body?: ReactNode
open?: boolean
@@ -32,6 +34,7 @@ export function ThreadMarker({
icon,
running = false,
spinner = false,
+ shimmer = true,
failed = false,
body,
open,
@@ -39,16 +42,22 @@ export function ThreadMarker({
className,
children,
}: ThreadMarkerProps): JSX.Element {
+ const opens = body != null && body !== false && body !== ''
return (
<ChatMarker
- status={failed ? 'error' : running ? 'running' : undefined}
+ status={failed ? 'error' : running && shimmer ? 'running' : undefined}
body={body}
open={open}
onOpenChange={onOpenChange}
className={cn(
QUILL_THREAD_ROW_CLASS,
+ opens && 'hover:opacity-100 data-panel-open:bg-transparent data-panel-open:opacity-100',
+ // The title, argument and status label each set their own color, so the row's color loses to them.
+ failed && 'opacity-100 text-(--destructive-foreground) [&_*]:text-(--destructive-foreground)',
// A fainter base under the full-foreground sweep, so a live row reads as moving at a glance.
- running && '[--quill-shimmer-base:color-mix(in_oklab,var(--muted-foreground)_70%,transparent)]',
+ running &&
+ shimmer &&
+ '[--quill-shimmer-base:color-mix(in_oklab,var(--muted-foreground)_70%,transparent)]',
className
)}
>
diff --git a/products/posthog_ai/frontend/components/quill/footerReveal.ts b/products/posthog_ai/frontend/components/quill/footerReveal.ts
new file mode 100644
index 000000000000..b2456d67ecda
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/footerReveal.ts
@@ -0,0 +1,9 @@
+/**
+ * Classes for a message footer that fades in on hover. The footer takes pointer input only once the fade
+ * ends, so a pointer that passes over it on the way in does not open the timestamp popover early.
+ */
+export function footerRevealClass(revealed: boolean): string {
+ return revealed
+ ? '[--footer-fade:150ms] opacity-100 [transition:opacity_var(--footer-fade),pointer-events_0s_var(--footer-fade)_allow-discrete]'
+ : '[--footer-fade:150ms] pointer-events-none opacity-0 [transition:opacity_var(--footer-fade)] focus-within:pointer-events-auto focus-within:opacity-100'
+}
diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
index dcd7dd01aa47..b0c09000a355 100644
--- a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
@@ -111,7 +111,7 @@ describe('toolRegistry', () => {
const entry = toolRegistry.lookup(key)
expect(entry).not.toBeNull()
expect(entry?.displayName).toEqual(displayName)
- expect(entry?.keepVisible ?? false).toBe(['ExitPlanMode', 'AskUserQuestion'].includes(key))
+ expect(entry?.pinned ?? false).toBe(['ExitPlanMode', 'AskUserQuestion'].includes(key))
expect(lookupToolRenderer(key, false).displayName).toEqual(displayName)
})
diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
index 3d66d2607925..c9b09d43af4f 100644
--- a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
@@ -45,8 +45,10 @@ export interface ToolRendererProps {
type ToolRendererComponent = ComponentType<ToolRendererProps> | LazyExoticComponent<ComponentType<ToolRendererProps>>
export interface ToolRegistryEntry {
- /** Keep results such as charts, plans and questions outside collapsed activity groups. */
+ /** Keep results such as charts outside collapsed activity groups. Quill keeps only a closed run's last one. */
keepVisible?: boolean
+ /** Never fold into an activity group, because the user acts on it, like a plan or a question. */
+ pinned?: boolean
/**
* Registry key. For single-exec PostHog tools, this is the **inner** tool name parsed from
* `rawInput.command` (e.g. "execute-sql", "insight-create"); for `exec`'s discovery verbs,
@@ -158,7 +160,7 @@ const POSTHOG_CODE_TOOLS: { name: string; displayName: string; icon: JSX.Element
const entries = new Map<string, ToolRegistryEntry>(
[
...BUILTIN_TOOLS.flatMap(({ keys, ...entry }) =>
- keys.map((key) => ({ key, ...entry, Renderer: BuiltinToolRenderer, keepVisible: key === 'ExitPlanMode' }))
+ keys.map((key) => ({ key, ...entry, Renderer: BuiltinToolRenderer, pinned: key === 'ExitPlanMode' }))
),
...['Edit', 'Write', 'NotebookEdit', 'MultiEdit'].map((key) => ({
key,
@@ -179,7 +181,7 @@ const entries = new Map<string, ToolRegistryEntry>(
displayName: 'Question',
icon: <IconAI />,
Renderer: QuestionRenderer,
- keepVisible: true,
+ pinned: true,
},
...posthogAiToolRenderers,
].map((entry) => [entry.key, entry])
diff --git a/products/posthog_ai/frontend/logics/contextPickerLogic.ts b/products/posthog_ai/frontend/logics/contextPickerLogic.ts
index c0d7888922c3..c15c874b0b04 100644
--- a/products/posthog_ai/frontend/logics/contextPickerLogic.ts
+++ b/products/posthog_ai/frontend/logics/contextPickerLogic.ts
@@ -19,6 +19,16 @@ import { attachedContextLogic } from './attachedContextLogic'
export const PICKER_PROVIDER_ID = 'user-picker'
+/** The group types the composer's @-picker offers. Keep in sync with `taxonomicItemToAttachedContext`. */
+export const CONTEXT_PICKER_GROUP_TYPES: TaxonomicFilterGroupType[] = [
+ TaxonomicFilterGroupType.Events,
+ TaxonomicFilterGroupType.Actions,
+ TaxonomicFilterGroupType.Insights,
+ TaxonomicFilterGroupType.Dashboards,
+ TaxonomicFilterGroupType.Notebooks,
+ TaxonomicFilterGroupType.ErrorTrackingIssues,
+]
+
/** Structural subset of the taxonomic item shapes the picker consumes — no scene-tree type imports. */
export interface PickableTaxonomicItem {
id?: string | number
diff --git a/products/posthog_ai/frontend/logics/taskLogic.test.ts b/products/posthog_ai/frontend/logics/taskLogic.test.ts
index c8cf72001fd2..3eea33acb8f5 100644
--- a/products/posthog_ai/frontend/logics/taskLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/taskLogic.test.ts
@@ -122,6 +122,36 @@ describe('taskLogic', () => {
})
})
+ describe('renaming', () => {
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('shows the new title while the save is pending, and restores the saved title if it fails', async () => {
+ const saved = createMockTask('task-123')
+ jest.spyOn(api.tasks, 'list').mockResolvedValue({ results: [], count: 0, next: null } as any)
+ jest.spyOn(api.tasks, 'get').mockResolvedValue(saved)
+ let rejectUpdate: (error: Error) => void = () => {}
+ jest.spyOn(api.tasks, 'update').mockReturnValue(
+ new Promise((_, reject) => {
+ rejectUpdate = reject
+ })
+ )
+ logic = taskLogic({ taskId: 'task-123' })
+ logic.mount()
+ logic.actions.loadTaskSuccess(saved)
+
+ logic.actions.updateTask({ data: { title: 'Renamed' } })
+ expect(logic.values.task?.title).toEqual('Renamed')
+
+ await expectLogic(logic, () => {
+ rejectUpdate(new ApiError('Title is too long', 400))
+ }).toDispatchActions(['updateTaskFailure', 'loadTaskSuccess'])
+ expect(logic.values.task?.title).toEqual(saved.title)
+ expect(api.tasks.get).not.toHaveBeenCalled()
+ })
+ })
+
describe('refreshing task lists after a mutation', () => {
afterEach(() => {
jest.restoreAllMocks()
diff --git a/products/posthog_ai/frontend/logics/taskLogic.ts b/products/posthog_ai/frontend/logics/taskLogic.ts
index a447831ea9d7..877fb0fe17a8 100644
--- a/products/posthog_ai/frontend/logics/taskLogic.ts
+++ b/products/posthog_ai/frontend/logics/taskLogic.ts
@@ -22,6 +22,7 @@ export interface TaskLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskLogicValues {
+ confirmedTask: Task | null
runTaskInFlight: boolean
task: Task | null
taskError: string | null
@@ -159,6 +160,20 @@ export const taskLogic = kea<taskLogicType>([
],
})),
reducers({
+ // A rename shows its new title at once. Only `title` applies early; other fields wait for the server.
+ task: {
+ updateTask: (state, { data }) =>
+ state && data.title !== undefined ? { ...state, title: data.title } : state,
+ },
+ // The last task the server returned, so a rejected rename rolls back without another request.
+ confirmedTask: [
+ null as Task | null,
+ {
+ loadTaskSuccess: (_, { task }) => task,
+ runTaskSuccess: (_, { task }) => task,
+ updateTaskSuccess: (_, { task }) => task,
+ },
+ ],
taskNotFound: [
false,
{
@@ -185,49 +200,47 @@ export const taskLogic = kea<taskLogicType>([
},
],
}),
- listeners(({ props, values, actions }) => ({
- loadTaskSuccess: () => {
- if (values.task) {
- tasksLogic.findMounted()?.actions.updateTask(values.task)
- }
- },
- // The sidebar rename writes through tasksLogic, so mirror the result onto this detail
- // logic. Without it the header keeps the old title until the next full load.
- [tasksLogic.actionTypes.renameTaskSuccess]: ({
- tasks,
- payload,
- }: {
- tasks: Task[]
- payload?: { taskId: string; title: string }
- }) => {
- if (payload?.taskId !== props.taskId) {
- return
- }
- const renamed = tasks.find((task) => task.id === props.taskId)
- if (renamed) {
- actions.loadTaskSuccess(renamed)
- }
- },
- runTaskSuccess: () => {
- if (values.task) {
- tasksLogic.findMounted()?.actions.updateTask(values.task)
- }
- },
- runTaskFailure: ({ error, errorObject }) => {
- const message = loadErrorMessage(error, errorObject)
- lemonToast.error(message || 'Failed to start the run')
- // Previously a rejected run changed nothing on screen, so the failure rate was
- // unmeasurable — capture it rather than leaving it to session recordings.
- posthog.capture('task_run_start_failed', { task_id: props.taskId, error: message })
- },
- updateTaskSuccess: () => {
+ listeners(({ props, values, actions }) => {
+ const syncToTaskList = (): void => {
if (values.task) {
tasksLogic.findMounted()?.actions.updateTask(values.task)
}
- },
- // The title field keeps what the user typed, so without this a rejected rename reads as saved.
- updateTaskFailure: ({ error, errorObject }) => {
- lemonToast.error(loadErrorMessage(error, errorObject) || "Couldn't save the task. Try again.")
- },
- })),
+ }
+ return {
+ loadTaskSuccess: syncToTaskList,
+ // The sidebar rename writes through tasksLogic, so mirror the result onto this detail
+ // logic. Without it the header keeps the old title until the next full load.
+ [tasksLogic.actionTypes.renameTaskSuccess]: ({
+ tasks,
+ payload,
+ }: {
+ tasks: Task[]
+ payload?: { taskId: string; title: string }
+ }) => {
+ if (payload?.taskId !== props.taskId) {
+ return
+ }
+ const renamed = tasks.find((task) => task.id === props.taskId)
+ if (renamed) {
+ actions.loadTaskSuccess(renamed)
+ }
+ },
+ runTaskSuccess: syncToTaskList,
+ runTaskFailure: ({ error, errorObject }) => {
+ const message = loadErrorMessage(error, errorObject)
+ lemonToast.error(message || 'Failed to start the run')
+ // Previously a rejected run changed nothing on screen, so the failure rate was
+ // unmeasurable — capture it rather than leaving it to session recordings.
+ posthog.capture('task_run_start_failed', { task_id: props.taskId, error: message })
+ },
+ updateTask: syncToTaskList,
+ updateTaskSuccess: syncToTaskList,
+ updateTaskFailure: ({ error, errorObject }) => {
+ lemonToast.error(loadErrorMessage(error, errorObject) || "Couldn't save the task. Try again.")
+ if (values.confirmedTask) {
+ actions.loadTaskSuccess(values.confirmedTask)
+ }
+ },
+ }
+ }),
])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx
index 9b9f2fa0fb7c..f8c02a76cd25 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx
@@ -268,6 +268,13 @@ export const NewTask: Story = {
},
}
+export const NewTaskQuill: Story = {
+ parameters: {
+ pageUrl: taskNewUrl(),
+ featureFlags: [FEATURE_FLAGS.TASKS, FEATURE_FLAGS.PHAI_QUILL],
+ },
+}
+
// New-task route with a GitHub integration connected — the footer shows the repository picker chip (and,
// once a repo is auto/selected, the branch picker) instead of the "Connect GitHub" chip.
export const NewTaskWithRepository: Story = {
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskHeaderActions.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskHeaderActions.tsx
new file mode 100644
index 000000000000..5dcc53c04e3f
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskHeaderActions.tsx
@@ -0,0 +1,51 @@
+import { IconExternal, IconGithub, IconPlay } from '@posthog/icons'
+import { Button } from '@posthog/quill-primitives'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+export interface QuillTaskHeaderActionsProps {
+ /** Link that opens the task in PostHog Desktop, or `null` when the user has no desktop access. */
+ desktopUrl: string | null
+ prUrl?: string
+ /** The run button's label, or `null` when the task cannot run now. */
+ runLabel: string | null
+ onRun: () => void
+ running: boolean
+}
+
+export function QuillTaskHeaderActions({
+ desktopUrl,
+ prUrl,
+ runLabel,
+ onRun,
+ running,
+}: QuillTaskHeaderActionsProps): JSX.Element {
+ return (
+ <div data-quill className="flex flex-wrap items-center gap-1">
+ {desktopUrl && (
+ <Button
+ variant="outline"
+ size="sm"
+ nativeButton={false}
+ render={<LinkPrimitive to={desktopUrl} target="_blank" />}
+ className="hidden lg:inline-flex"
+ >
+ <IconExternal />
+ Open in PostHog Desktop
+ </Button>
+ )}
+ {prUrl && (
+ <Button variant="outline" size="sm" onClick={() => window.open(prUrl, '_blank')}>
+ <IconGithub />
+ View PR
+ </Button>
+ )}
+ {runLabel && (
+ <Button variant="primary" size="sm" onClick={onRun} loading={running}>
+ <IconPlay />
+ {runLabel}
+ </Button>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskMenu.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskMenu.tsx
new file mode 100644
index 000000000000..f07738d685b9
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskMenu.tsx
@@ -0,0 +1,106 @@
+import { useActions, useValues } from 'kea'
+import type { ReactNode } from 'react'
+
+import { IconArchive, IconEllipsis } from '@posthog/icons'
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ MenuLabel,
+} from '@posthog/quill-primitives'
+
+import { dayjs } from 'lib/dayjs'
+
+import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
+
+import { debugLogsLogic } from '../../../logics/debugLogsLogic'
+import { modelCatalogueLogic } from '../../../logics/modelCatalogueLogic'
+import type { Task } from '../../../types/taskTypes'
+import { getTaskRunMetadataFields } from './taskRunMetadataFields'
+
+export interface QuillTaskMenuProps {
+ task: Task
+ selectedRun: TaskRunDetailDTOApi | null
+ onArchive: () => void
+}
+
+function RelativeTime({ time }: { time: string }): JSX.Element {
+ return (
+ <time dateTime={time} title={dayjs(time).format('MMM D, YYYY HH:mm:ss')}>
+ {dayjs(time).fromNow()}
+ </time>
+ )
+}
+
+function FactList({ facts }: { facts: { label: string; value: ReactNode }[] }): JSX.Element {
+ return (
+ <dl className="m-0 flex flex-col gap-1 px-2 pb-1 text-xs">
+ {facts.map((fact) => (
+ <div key={fact.label} className="flex items-baseline justify-between gap-4">
+ <dt className="text-muted-foreground">{fact.label}</dt>
+ <dd className="m-0 min-w-0 truncate text-end text-foreground">{fact.value}</dd>
+ </div>
+ ))}
+ </dl>
+ )
+}
+
+export function QuillTaskMenu({ task, selectedRun, onArchive }: QuillTaskMenuProps): JSX.Element {
+ const { catalogue } = useValues(modelCatalogueLogic)
+ const { canControlDebugLogs, debugLogsEnabled } = useValues(debugLogsLogic)
+ const { setDebugLogsEnabled } = useActions(debugLogsLogic)
+
+ const taskFacts = [
+ { label: 'Task ID', value: <span className="font-mono">{task.slug}</span> },
+ ...(task.repository ? [{ label: 'Repository', value: task.repository }] : []),
+ { label: 'Created by', value: task.created_by?.first_name || task.created_by?.email || 'Unknown' },
+ { label: 'Created', value: <RelativeTime time={task.created_at} /> },
+ ]
+ const runFacts = selectedRun
+ ? getTaskRunMetadataFields(selectedRun, catalogue).map((field) => ({
+ label: field.label,
+ value: field.kind === 'time' ? <RelativeTime time={field.value} /> : field.value,
+ }))
+ : []
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button variant="default" size="icon-sm" aria-label="Task details" data-attr="run-staff-menu">
+ <IconEllipsis />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="min-w-64 max-w-80">
+ <MenuLabel>Task</MenuLabel>
+ <FactList facts={taskFacts} />
+ {runFacts.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <MenuLabel>Run</MenuLabel>
+ <FactList facts={runFacts} />
+ </>
+ )}
+ <DropdownMenuSeparator />
+ {canControlDebugLogs && (
+ <DropdownMenuCheckboxItem
+ checked={debugLogsEnabled}
+ onCheckedChange={setDebugLogsEnabled}
+ data-attr="run-toggle-debug-logs"
+ >
+ Show debug logs
+ </DropdownMenuCheckboxItem>
+ )}
+ <DropdownMenuItem variant="destructive" onClick={onArchive} data-attr="task-archive">
+ <IconArchive />
+ Archive task
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskTitle.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskTitle.tsx
new file mode 100644
index 000000000000..6e8ce03e217f
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskTitle.tsx
@@ -0,0 +1,88 @@
+import { type ReactNode, useState } from 'react'
+
+import { IconChevronLeft, IconPencil } from '@posthog/icons'
+import { Button, Heading, Input, SkeletonText } from '@posthog/quill-primitives'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+export interface QuillTaskTitleProps {
+ name: string
+ icon: ReactNode
+ isLoading: boolean
+ /** Omitting this leaves the title read-only. */
+ onRename?: (title: string) => void
+ backTo?: { label: string; path: string }
+ actions?: ReactNode
+}
+
+export function QuillTaskTitle({ name, icon, isLoading, onRename, backTo, actions }: QuillTaskTitleProps): JSX.Element {
+ const [draft, setDraft] = useState<string | null>(null)
+
+ const commit = (): void => {
+ if (draft !== null) {
+ onRename?.(draft)
+ }
+ setDraft(null)
+ }
+
+ return (
+ <div data-quill className="flex flex-wrap items-center gap-2 py-2">
+ {backTo && (
+ <Button
+ variant="default"
+ size="icon-sm"
+ nativeButton={false}
+ render={<LinkPrimitive to={backTo.path} />}
+ aria-label={`Back to ${backTo.label}`}
+ >
+ <IconChevronLeft />
+ </Button>
+ )}
+ <span className="flex size-5 shrink-0 items-center justify-center text-sm" aria-hidden>
+ {icon}
+ </span>
+ <div className="flex min-w-0 flex-1 items-center gap-1">
+ {isLoading ? (
+ <SkeletonText lines={1} className="w-60" />
+ ) : draft !== null ? (
+ <Input
+ aria-label="Task title"
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={commit}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault()
+ commit()
+ } else if (event.key === 'Escape') {
+ event.preventDefault()
+ setDraft(null)
+ }
+ }}
+ autoFocus
+ // Same height as the pencil button, and pulled left by its padding and border, so the text stays put on edit.
+ className="-ms-[calc(0.5rem+1px)] h-6 max-w-120 text-sm font-semibold"
+ />
+ ) : (
+ <>
+ <Heading size="sm" render={<h1 />} className="m-0 min-w-0 truncate">
+ {name}
+ </Heading>
+ {onRename && (
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label="Rename task"
+ onClick={() => setDraft(name)}
+ data-attr="task-rename"
+ >
+ <IconPencil />
+ </Button>
+ )}
+ </>
+ )}
+ </div>
+ {actions && <div className="ml-auto flex flex-wrap items-center gap-1">{actions}</div>}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index 7c65748db9e6..2d31480c02ae 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -11,6 +11,7 @@ import {
DEFAULT_SUGGESTIONS_DATA,
type SuggestionItem,
Suggestions,
+ useThreadSkin,
Welcome,
} from 'products/posthog_ai/frontend/api/primitives'
import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
@@ -27,6 +28,8 @@ import {
} from 'products/posthog_ai/frontend/utils/composerModes'
import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'
+import { AttachedContextChips } from '../../../components/composer/AttachedContextChips'
+import { ComposerAttachmentChips } from '../../../components/composer/ComposerAttachmentChips'
import { ComposerAttachments, useComposerAttachmentPaste } from '../../../components/composer/ComposerAttachments'
import { ComposerCodexBillingPickers } from '../../../components/composer/ComposerCodexBillingPickers'
import {
@@ -37,6 +40,11 @@ import { ComposerModePicker } from '../../../components/composer/ComposerModePic
import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'
import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'
import { OnboardingReplayButton } from '../../../components/onboarding/OnboardingReplayButton'
+import { QuillAttachedContextPicker } from '../../../components/quill/QuillAttachedContextPicker'
+import { QuillComposerAttachButton } from '../../../components/quill/QuillComposerAttachButton'
+import { QuillComposerLayout } from '../../../components/quill/QuillComposerLayout'
+import { QuillComposerSendButton } from '../../../components/quill/QuillComposerSendButton'
+import { QuillOnboardingReplayButton } from '../../../components/quill/QuillOnboardingReplayButton'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
import { RepositorySelector } from './RepositorySelector'
@@ -88,6 +96,9 @@ export function TaskComposer({ variant = 'page', focusRequest = 0, autoFocus = t
const textAreaRef = useRef<HTMLTextAreaElement>(null)
// The whole input frame is the drop target, so a file dropped anywhere on it attaches.
const frameRef = useRef<HTMLLabelElement>(null)
+ const groupRef = useRef<HTMLDivElement>(null)
+ const skin = useThreadSkin()
+ const showSuggestions = skin === 'lemon' && !composerOverride?.hideSuggestions
useEffect(() => {
if (focusRequest > 0) {
@@ -102,6 +113,21 @@ export function TaskComposer({ variant = 'page', focusRequest = 0, autoFocus = t
}
}
+ const field = (
+ <Composer.Field>
+ <Composer.Placeholder>
+ {composerOverride?.placeholder ?? 'Describe the task in detail…'}
+ </Composer.Placeholder>
+ <Composer.Textarea autoFocus={autoFocus} onPaste={onPaste} data-attr="task-composer-input" />
+ </Composer.Field>
+ )
+ const modePicker = (
+ <ComposerModePicker
+ modes={getModesForRuntimeAdapter(composerAdapter)}
+ selectedMode={newTaskData.permissionMode}
+ onModeChange={(permissionMode) => setNewTaskData({ permissionMode })}
+ />
+ )
const codexBillingEnabled = useFeatureFlag('POSTHOG_CODE_CODEX_OWN_SUBSCRIPTION_CLOUD')
const modelPickerProps: ComposerModelEffortPickersProps = {
models: offeredModels,
@@ -128,19 +154,36 @@ export function TaskComposer({ variant = 'page', focusRequest = 0, autoFocus = t
onOpenDefaultSettings: () =>
router.actions.push(urls.settings('environment-task-agents', 'task-agent-my-preference')),
}
+ const modelPicker = codexBillingEnabled ? (
+ <ComposerCodexBillingPickers {...modelPickerProps} />
+ ) : (
+ <ComposerModelEffortPickers {...modelPickerProps} />
+ )
+ const withConsent = (sendButton: JSX.Element): JSX.Element => (
+ <AIConsentPopoverWrapper
+ placement="bottom-end"
+ showArrow
+ ignoreDismissal
+ hidden={!consentBlocked}
+ onApprove={() => submitNewTask()}
+ onDismiss={() => clearConsentBlock()}
+ >
+ {sendButton}
+ </AIConsentPopoverWrapper>
+ )
return (
<div
className={
inline
? 'flex flex-col'
- : 'flex flex-col h-full min-h-0 items-center justify-center overflow-y-auto p-4'
+ : '@container/task-composer flex flex-col h-full min-h-0 items-center justify-center overflow-y-auto p-4'
}
>
<div
className={inline ? 'w-full flex flex-col gap-4' : 'w-full max-w-2xl flex flex-col items-center gap-4'}
>
- {!inline && (
+ {!inline && skin === 'lemon' && (
<Welcome headline={displayHeadline} subheadline={composerOverride?.subheadline}>
{/* Temporary migration affordance — delete with the rest of the onboarding takeover
once everyone is on the new PostHog AI. */}
@@ -176,50 +219,59 @@ export function TaskComposer({ variant = 'page', focusRequest = 0, autoFocus = t
loading={isSubmittingTask}
textAreaRef={textAreaRef}
>
- <Composer.Frame ref={frameRef}>
- <Composer.Header className="flex flex-wrap items-center gap-1">
- <AttachedContextBar />
- <ComposerAttachments attachmentsKey={attachmentsKey} dropTargetRef={frameRef} />
- </Composer.Header>
- <Composer.Field>
- <Composer.Placeholder>
- {composerOverride?.placeholder ?? 'Describe the task in detail…'}
- </Composer.Placeholder>
- <Composer.Textarea
- autoFocus={autoFocus}
- onPaste={onPaste}
- data-attr="task-composer-input"
- />
- </Composer.Field>
- <Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
- <ComposerModePicker
- modes={getModesForRuntimeAdapter(composerAdapter)}
- selectedMode={newTaskData.permissionMode}
- onModeChange={(permissionMode) => setNewTaskData({ permissionMode })}
- />
- {codexBillingEnabled ? (
- <ComposerCodexBillingPickers {...modelPickerProps} />
- ) : (
- <ComposerModelEffortPickers {...modelPickerProps} />
- )}
- </Composer.Footer>
- </Composer.Frame>
+ {skin === 'quill' ? (
+ <QuillComposerLayout
+ groupRef={groupRef}
+ textAreaRef={textAreaRef}
+ chips={
+ <>
+ <AttachedContextChips />
+ <ComposerAttachmentChips attachmentsKey={attachmentsKey} />
+ </>
+ }
+ field={field}
+ send={withConsent(<QuillComposerSendButton data-attr="task-composer-send" />)}
+ controls={
+ <>
+ <QuillComposerAttachButton
+ attachmentsKey={attachmentsKey}
+ dropTargetRef={groupRef}
+ />
+ <QuillAttachedContextPicker />
+ {modelPicker}
+ {modePicker}
+ </>
+ }
+ meta={
+ !inline &&
+ !composerOverride?.hideOnboardingReplay && (
+ <QuillOnboardingReplayButton
+ panelId={panelId}
+ className="hidden @4xl/task-composer:inline-flex"
+ />
+ )
+ }
+ />
+ ) : (
+ <Composer.Frame ref={frameRef}>
+ <Composer.Header className="flex flex-wrap items-center gap-1">
+ <AttachedContextBar />
+ <ComposerAttachments attachmentsKey={attachmentsKey} dropTargetRef={frameRef} />
+ </Composer.Header>
+ {field}
+ <Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
+ {modePicker}
+ {modelPicker}
+ </Composer.Footer>
+ </Composer.Frame>
+ )}
{/* Open-group state is shared with the side panel; a group left open there would list generic prompts here. */}
- {!composerOverride?.hideSuggestions && <Suggestions.Dropdown />}
- <AIConsentPopoverWrapper
- placement="bottom-end"
- showArrow
- ignoreDismissal
- hidden={!consentBlocked}
- onApprove={() => submitNewTask()}
- onDismiss={() => clearConsentBlock()}
- >
- <Composer.Submit data-attr="task-composer-send" />
- </AIConsentPopoverWrapper>
+ {showSuggestions && <Suggestions.Dropdown />}
+ {skin === 'lemon' && withConsent(<Composer.Submit data-attr="task-composer-send" />)}
</Composer.Root>
</div>
- {!composerOverride?.hideSuggestions && <Suggestions.Buttons data={DEFAULT_SUGGESTIONS_DATA} />}
+ {showSuggestions && <Suggestions.Buttons data={DEFAULT_SUGGESTIONS_DATA} />}
</Suggestions.Root>
</div>
</div>
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
index 46f8fbc2a3c1..7dd34311a8e8 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
@@ -7,10 +7,12 @@ import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { urls } from 'scenes/urls'
+import { useThreadSkin } from '../../../hooks/useThreadSkin'
import { nextTaskTitle } from '../../../lib/task-title'
import { isPiTaskRuntime } from '../../../types/taskTypes'
import { taskDetailSceneLogic } from '../taskDetailSceneLogic'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
+import { QuillTaskHeaderActions } from './QuillTaskHeaderActions'
import { TaskHeaderActionsSkeleton } from './taskDetailSkeletons'
import { TaskRunTabs } from './TaskRunArtifacts'
import { TaskRunLog } from './TaskRunLog'
@@ -30,6 +32,7 @@ export function TaskDetailPage({ taskId, isMobile, titleActions }: TaskDetailPag
const { activeCreation, hasDesktopAccess } = useValues(taskTrackerSceneLogic)
const isActiveCreation = activeCreation?.taskId === taskId
const artifactsTabEnabled = useFeatureFlag('TODAY_RAIL_NAV')
+ const skin = useThreadSkin()
if (taskNotFound && !task) {
return <NotFound object="task" />
@@ -50,11 +53,20 @@ export function TaskDetailPage({ taskId, isMobile, titleActions }: TaskDetailPag
updateTask({ data: { title: nextTitle } })
}
}
+ const canRun = !!task && !isPiTaskRuntime(task.runtime) && !isLatestRunInProgress && !isLatestRunCompleted
const taskActions =
isHeaderLoading || !task ? (
isActiveCreation ? undefined : (
<TaskHeaderActionsSkeleton />
)
+ ) : skin === 'quill' ? (
+ <QuillTaskHeaderActions
+ desktopUrl={hasDesktopAccess ? urls.codeTaskLink(task.id) : null}
+ prUrl={prUrl}
+ runLabel={canRun ? runButtonText : null}
+ onRun={runTask}
+ running={runTaskInFlight}
+ />
) : (
<div className="flex flex-wrap items-center gap-2">
{hasDesktopAccess && (
@@ -79,7 +91,7 @@ export function TaskDetailPage({ taskId, isMobile, titleActions }: TaskDetailPag
View PR
</LemonButton>
)}
- {!isPiTaskRuntime(task.runtime) && !isLatestRunInProgress && !isLatestRunCompleted && (
+ {canRun && (
<LemonButton
type="primary"
size="small"
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
index d91f678c015f..5abcecd9404b 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
@@ -959,8 +959,8 @@ export function TaskRunTabs({ taskId, conversation }: { taskId: string; conversa
className="flex min-h-0 flex-1 flex-col gap-0"
data-quill
>
- <div className="shrink-0 border-b border-border px-4">
- <TabsList variant="line" aria-label="Task views">
+ <div className="shrink-0 border-b border-border px-2">
+ <TabsList variant="line" aria-label="Task views" className="p-0">
<TabsTrigger value="conversation" data-attr="task-run-tab-conversation">
Conversation
</TabsTrigger>
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
index 44120f59f1ad..bbda68a44c72 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
@@ -19,7 +19,6 @@ import { ModelAccessEnumApi } from 'products/tasks/frontend/generated/api.schema
import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'
import { AttachedContextChips } from '../../../components/composer/AttachedContextChips'
-import { AttachedContextPicker } from '../../../components/composer/AttachedContextPicker'
import { CommandResultCard } from '../../../components/composer/CommandResultCard'
import { ComposerAttachmentChips } from '../../../components/composer/ComposerAttachmentChips'
import { ComposerAttachments, useComposerAttachmentPaste } from '../../../components/composer/ComposerAttachments'
@@ -33,6 +32,7 @@ import { ComposerModePicker } from '../../../components/composer/ComposerModePic
import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'
import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'
import { ContextUsageChip } from '../../../components/ContextUsageChip'
+import { QuillAttachedContextPicker } from '../../../components/quill/QuillAttachedContextPicker'
import { QuillComposerAttachButton } from '../../../components/quill/QuillComposerAttachButton'
import { QuillComposerLayout } from '../../../components/quill/QuillComposerLayout'
import { QuillComposerSendButton } from '../../../components/quill/QuillComposerSendButton'
@@ -260,10 +260,7 @@ export function TaskRunComposer({
controls={
<>
<QuillComposerAttachButton attachmentsKey={attachmentsKey} dropTargetRef={groupRef} />
- {/* The picker is Lemon, so it keeps Lemon's colors inside the quill row. */}
- <div data-not-quill className="flex">
- <AttachedContextPicker className="flex-shrink-0" />
- </div>
+ <QuillAttachedContextPicker />
{pickers(modelPicker, modePicker)}
</>
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx
index e95aa7e46f13..899ea47748a7 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx
@@ -1,13 +1,11 @@
import { useValues } from 'kea'
import { TZLabel } from 'lib/components/TZLabel'
-import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDuration } from 'lib/utils/durations'
import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
import { modelCatalogueLogic } from '../../../logics/modelCatalogueLogic'
-import { getEffortLabel, getModelLabel } from '../../../utils/composerModels'
+import { getTaskRunMetadataFields } from './taskRunMetadataFields'
/** Created / completed / duration / model row shown above the run log for the selected run. */
export function TaskRunMetadata({ selectedRun }: { selectedRun: TaskRunDetailDTOApi }): JSX.Element {
@@ -15,42 +13,14 @@ export function TaskRunMetadata({ selectedRun }: { selectedRun: TaskRunDetailDTO
return (
<div className="items-center gap-4 text-xs text-muted hidden lg:flex">
- {selectedRun.created_at && (
- <dl className="inline-flex gap-1 items-center">
- <dt className="m-0">Created:</dt>
+ {getTaskRunMetadataFields(selectedRun, catalogue).map((field) => (
+ <dl key={field.label} className="inline-flex gap-1 items-center">
+ <dt className="m-0">{field.label}:</dt>
<dd className="m-0 inline-flex items-center">
- <TZLabel time={selectedRun.created_at} showSeconds />
+ {field.kind === 'time' ? <TZLabel time={field.value} showSeconds /> : field.value}
</dd>
</dl>
- )}
- {selectedRun.completed_at && (
- <dl className="inline-flex gap-1 items-center">
- <dt className="m-0">Completed:</dt>
- <dd className="m-0 inline-flex items-center">
- <TZLabel time={selectedRun.completed_at} showSeconds />
- </dd>
- </dl>
- )}
- {/* An import run holds a chat copied from the legacy runtime and never executed, so it has no duration. */}
- {selectedRun.completed_at && selectedRun.created_at && !selectedRun.state?.imported_from && (
- <dl className="inline-flex gap-1 items-center">
- <dt className="m-0">Duration:</dt>
- <dd className="m-0 inline-flex items-center">
- {humanFriendlyDuration(dayjs(selectedRun.completed_at).diff(selectedRun.created_at, 'second'))}
- </dd>
- </dl>
- )}
- {/* What the run actually launched with, not what the composer currently has picked — a read-only
- viewer has no pickers to read, and on a resumed task the two can differ. */}
- {selectedRun.model && (
- <dl className="inline-flex gap-1 items-center">
- <dt className="m-0">Model:</dt>
- <dd className="m-0 inline-flex items-center">
- {getModelLabel(catalogue, selectedRun.model)}
- {selectedRun.reasoning_effort && ` · ${getEffortLabel(selectedRun.reasoning_effort)}`}
- </dd>
- </dl>
- )}
+ ))}
</div>
)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx
index f402968d8bab..c5292e4c574e 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx
@@ -20,7 +20,10 @@ import {
import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
import { TaskSourceIcon } from '../../../components/TaskSourceIcon'
+import { useThreadSkin } from '../../../hooks/useThreadSkin'
import type { Task } from '../../../types/taskTypes'
+import { QuillTaskMenu } from './QuillTaskMenu'
+import { QuillTaskTitle } from './QuillTaskTitle'
import { TaskDebugLogsPanelToggle } from './TaskDebugLogsPanelToggle'
import { TaskPanelSkeleton, TaskRunMetadataSkeleton } from './taskDetailSkeletons'
import { TaskErrorBanner } from './TaskErrorBanner'
@@ -65,49 +68,56 @@ export function TaskRunSceneShell({
headerDivider = true,
children,
}: TaskRunSceneShellProps): JSX.Element {
+ const skin = useThreadSkin()
+ const icon = <TaskSourceIcon originProduct={task?.origin_product} environment={task?.latest_run?.environment} />
return (
<SceneContent className="h-full min-h-0 gap-y-0">
- <ScenePanel>
- {isHeaderLoading ? (
- <TaskPanelSkeleton />
- ) : task ? (
- <>
- <ScenePanelInfoSection>
- <div className="flex flex-col gap-3">
- <div>
- <div className="text-xs text-muted mb-1">Task ID</div>
- <div className="font-mono text-sm">{task.slug}</div>
- </div>
- <div>
- <div className="text-xs text-muted mb-1">Repository</div>
- <div className="text-sm">{task.repository}</div>
- </div>
- <div>
- <div className="text-xs text-muted mb-1">Created by</div>
- <div className="text-sm">
- {task.created_by?.first_name || task.created_by?.email || 'Unknown'}
+ {/* The quill skin moves the panel's facts and actions into the title's overflow menu (QuillTaskMenu). */}
+ {skin === 'lemon' && (
+ <ScenePanel>
+ {isHeaderLoading ? (
+ <TaskPanelSkeleton />
+ ) : task ? (
+ <>
+ <ScenePanelInfoSection>
+ <div className="flex flex-col gap-3">
+ <div>
+ <div className="text-xs text-muted mb-1">Task ID</div>
+ <div className="font-mono text-sm">{task.slug}</div>
+ </div>
+ <div>
+ <div className="text-xs text-muted mb-1">Repository</div>
+ <div className="text-sm">{task.repository}</div>
+ </div>
+ <div>
+ <div className="text-xs text-muted mb-1">Created by</div>
+ <div className="text-sm">
+ {task.created_by?.first_name || task.created_by?.email || 'Unknown'}
+ </div>
+ </div>
+ <div>
+ <div className="text-xs text-muted mb-1">Created</div>
+ <div className="text-sm">
+ {dayjs(task.created_at).format('MMM D, YYYY HH:mm')}
+ </div>
</div>
</div>
- <div>
- <div className="text-xs text-muted mb-1">Created</div>
- <div className="text-sm">{dayjs(task.created_at).format('MMM D, YYYY HH:mm')}</div>
- </div>
- </div>
- </ScenePanelInfoSection>
+ </ScenePanelInfoSection>
- <ScenePanelDivider />
+ <ScenePanelDivider />
- <TaskDebugLogsPanelToggle />
+ <TaskDebugLogsPanelToggle />
- <ScenePanelActionsSection>
- <ButtonPrimitive menuItem variant="danger" onClick={onArchive}>
- <IconArchive />
- Archive task
- </ButtonPrimitive>
- </ScenePanelActionsSection>
- </>
- ) : null}
- </ScenePanel>
+ <ScenePanelActionsSection>
+ <ButtonPrimitive menuItem variant="danger" onClick={onArchive}>
+ <IconArchive />
+ Archive task
+ </ButtonPrimitive>
+ </ScenePanelActionsSection>
+ </>
+ ) : null}
+ </ScenePanel>
+ )}
{taskError && !task ? (
<TaskErrorBanner
@@ -129,46 +139,62 @@ export function TaskRunSceneShell({
/>
)}
- <header className={cn('flex flex-col gap-y-2 px-4 pt-2', taskError && 'mt-4')}>
- <SceneTitleSection
- className="-mt-2"
- name={task?.title || 'Task'}
- description={null}
- resourceType={{
- type: 'task',
- forceIcon: (
- <TaskSourceIcon
- originProduct={task?.origin_product}
- environment={task?.latest_run?.environment}
- />
- ),
- }}
- isLoading={isHeaderLoading}
- canEdit={!!onRename}
- onNameChange={onRename}
- // One write when the field is left, rather than one per keystroke.
- saveOnBlur
- renameDebounceMs={0}
- forceBackTo={
- isMobile
- ? {
- key: 'posthog-ai',
- name: 'PostHog AI',
- path: urls.ai(),
- }
- : undefined
- }
- actions={titleActions}
- />
+ {skin === 'quill' ? (
+ <header className={cn('px-2', taskError && 'mt-4')}>
+ <QuillTaskTitle
+ name={task?.title || 'Task'}
+ icon={icon}
+ isLoading={isHeaderLoading}
+ onRename={onRename}
+ backTo={isMobile ? { label: 'PostHog AI', path: urls.ai() } : undefined}
+ actions={
+ <div data-quill className="flex flex-wrap items-center gap-1">
+ {titleActions}
+ {task && (
+ <QuillTaskMenu
+ task={task}
+ selectedRun={selectedRun}
+ onArchive={onArchive}
+ />
+ )}
+ </div>
+ }
+ />
+ </header>
+ ) : (
+ <header className={cn('flex flex-col gap-y-2 px-4 pt-2', taskError && 'mt-4')}>
+ <SceneTitleSection
+ className="-mt-2"
+ name={task?.title || 'Task'}
+ description={null}
+ resourceType={{ type: 'task', forceIcon: icon }}
+ isLoading={isHeaderLoading}
+ canEdit={!!onRename}
+ onNameChange={onRename}
+ // One write when the field is left, rather than one per keystroke.
+ saveOnBlur
+ renameDebounceMs={0}
+ forceBackTo={
+ isMobile
+ ? {
+ key: 'posthog-ai',
+ name: 'PostHog AI',
+ path: urls.ai(),
+ }
+ : undefined
+ }
+ actions={titleActions}
+ />
- {isHeaderLoading ? (
- <TaskRunMetadataSkeleton />
- ) : (
- selectedRun && <TaskRunMetadata selectedRun={selectedRun} />
- )}
+ {isHeaderLoading ? (
+ <TaskRunMetadataSkeleton />
+ ) : (
+ selectedRun && <TaskRunMetadata selectedRun={selectedRun} />
+ )}
- {headerDivider && <LemonDivider className="hidden lg:block mb-0 mt-2" />}
- </header>
+ {headerDivider && <LemonDivider className="hidden lg:block mb-0 mt-2" />}
+ </header>
+ )}
{children}
</>
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/taskRunMetadataFields.ts b/products/posthog_ai/frontend/scenes/TaskTracker/components/taskRunMetadataFields.ts
new file mode 100644
index 000000000000..1d31fbf132f6
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/taskRunMetadataFields.ts
@@ -0,0 +1,43 @@
+import { dayjs } from 'lib/dayjs'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+
+import type { ModelChoiceApi, TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
+
+import { getEffortLabel, getModelLabel } from '../../../utils/composerModels'
+
+export type TaskRunMetadataField =
+ | { label: 'Created' | 'Completed'; kind: 'time'; value: string }
+ | { label: 'Duration' | 'Model'; kind: 'text'; value: string }
+
+export function getTaskRunMetadataFields(
+ run: TaskRunDetailDTOApi,
+ catalogue: ModelChoiceApi[]
+): TaskRunMetadataField[] {
+ const fields: TaskRunMetadataField[] = []
+ if (run.created_at) {
+ fields.push({ label: 'Created', kind: 'time', value: run.created_at })
+ }
+ if (run.completed_at) {
+ fields.push({ label: 'Completed', kind: 'time', value: run.completed_at })
+ }
+ // An import run holds a chat copied from the legacy runtime and never executed, so it has no duration.
+ if (run.completed_at && run.created_at && !run.state?.imported_from) {
+ fields.push({
+ label: 'Duration',
+ kind: 'text',
+ value: humanFriendlyDuration(dayjs(run.completed_at).diff(run.created_at, 'second')),
+ })
+ }
+ // What the run actually launched with, not what the composer currently has picked — a read-only
+ // viewer has no pickers to read, and on a resumed task the two can differ.
+ if (run.model) {
+ fields.push({
+ label: 'Model',
+ kind: 'text',
+ value:
+ getModelLabel(catalogue, run.model) +
+ (run.reasoning_effort ? ` · ${getEffortLabel(run.reasoning_effort)}` : ''),
+ })
+ }
+ return fields
+}
diff --git a/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts b/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts
index 72325a43ff56..3c10cf219f57 100644
--- a/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts
+++ b/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts
@@ -1,5 +1,5 @@
import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
-import { activityWindow, groupConsecutiveTools, groupThreadActivity } from './groupThreadActivity'
+import { activityWindow, groupConsecutiveTools, groupThreadActivity, groupToolRuns } from './groupThreadActivity'
describe('thread activity grouping', () => {
const tool = (id: string, startedAt = 1000): ThreadItem => ({
@@ -39,6 +39,62 @@ describe('thread activity grouping', () => {
expect(groupThreadActivity([...items, tool('last', 3200)], new Set(['chart'])).at(-1)?.id).toBe('activity-next')
})
+ it('folds tool runs like PostHog Desktop, keeping plans, lone calls and the final chart of a closed run visible', () => {
+ const calls = new Map<string, ToolInvocation>()
+ const call = (id: string, status: ToolInvocation['status'] = 'completed'): ThreadItem => {
+ calls.set(id, {
+ toolCallId: id,
+ rawServerName: 'posthog',
+ rawToolName: 'exec',
+ input: {},
+ status,
+ contentBlocks: [],
+ })
+ return tool(id)
+ }
+ const thought = (id: string): ThreadItem => ({ id, type: 'assistant_thought', text: 'Checking' })
+ const prose = (id: string): ThreadItem => ({ id, type: 'assistant_message', text: 'Found it' })
+ const items: ThreadItem[] = [
+ { id: 'human', type: 'human_message', text: 'Why did signups drop?' },
+ { id: 'setup', type: 'status', status: 'setup_hooks' },
+ { id: 'init', type: 'status', status: 'sdk_initialization' },
+ thought('plan'),
+ call('read'),
+ thought('between'),
+ call('grep'),
+ prose('first-answer'),
+ call('lone'),
+ thought('after-lone'),
+ call('plan-card'),
+ call('schema'),
+ call('chart'),
+ prose('chart-answer'),
+ { id: 'end', type: 'turn_separator' },
+ call('live-chart'),
+ ]
+ const options = { pinnedToolIds: new Set(['plan-card']), widgetToolIds: new Set(['chart', 'live-chart']) }
+ const result = groupToolRuns(items, calls, { ...options, settled: false })
+ expect(result.map((item) => item.id)).toEqual([
+ 'human',
+ 'init',
+ 'activity-read',
+ 'first-answer',
+ 'lone',
+ 'after-lone',
+ 'plan-card',
+ 'schema',
+ 'chart',
+ 'chart-answer',
+ 'end',
+ 'activity-live-chart',
+ ])
+ expect(result[2]).toMatchObject({ items: [thought('plan'), tool('read'), thought('between'), tool('grep')] })
+ expect(result.flatMap((item) => (item.type === 'activity_group' ? item.items : [item]))).toEqual(
+ items.filter((item) => item.id !== 'setup')
+ )
+ expect(groupToolRuns(items, calls, { ...options, settled: true }).at(-1)?.id).toBe('live-chart')
+ })
+
it('does not invent a duration when part of the group has no recorded start', () => {
const result = groupThreadActivity(
[tool('timed'), { id: 'imported', type: 'tool_invocation', toolCallId: 'imported' }],
diff --git a/products/posthog_ai/frontend/utils/groupThreadActivity.ts b/products/posthog_ai/frontend/utils/groupThreadActivity.ts
index 684f86c19cc2..5fe207f2e3bd 100644
--- a/products/posthog_ai/frontend/utils/groupThreadActivity.ts
+++ b/products/posthog_ai/frontend/utils/groupThreadActivity.ts
@@ -68,6 +68,90 @@ export function groupThreadActivity(items: ThreadItem[], standaloneToolIds: Read
return result
}
+const STARTUP_STATUSES = new Set(['sdk_initialization', 'setup_hooks'])
+const LONG_RUNNING_STATUSES = new Set(['compacting', 'clearing'])
+
+export function isStartupStatus(item: ThreadDisplayItem): boolean {
+ return item.type === 'status' && STARTUP_STATUSES.has(item.status ?? '')
+}
+
+export function isRunningStatus(item: ThreadDisplayItem): boolean {
+ return item.type === 'status' && !item.isComplete && LONG_RUNNING_STATUSES.has(item.status ?? '')
+}
+
+export interface ToolRunOptions {
+ pinnedToolIds: ReadonlySet<string>
+ widgetToolIds: ReadonlySet<string>
+ /** Nothing more can join the thread's last run, because the turn finished or the run stopped. */
+ settled: boolean
+}
+
+const isToolCall = (item: ThreadItem): boolean => item.type === 'tool_invocation' && !!item.toolCallId
+
+/** Thoughts and finished task notifications narrate a run, so they join it and never break it. */
+const ridesAlong = (item: ThreadItem): boolean =>
+ item.type === 'assistant_thought' || (item.type === 'task_notification' && item.status === 'completed')
+
+/**
+ * PostHog Desktop's grouping: two or more tool calls fold into a group, and a lone call keeps its row. A
+ * closed run's last call keeps its row when it is a finished widget, so the chart the agent talks about stays
+ * visible. The trailing run closes only once `settled`, so its chart cannot appear and then fold again.
+ */
+export function groupToolRuns(
+ items: ThreadItem[],
+ toolInvocations: ReadonlyMap<string, ToolInvocation>,
+ { pinnedToolIds, widgetToolIds, settled }: ToolRunOptions
+): ThreadDisplayItem[] {
+ const finalWidgetIds = new Set<string>()
+ let runLastCall: string | undefined
+ const closeRun = (): void => {
+ if (runLastCall && widgetToolIds.has(runLastCall) && toolInvocations.get(runLastCall)?.status === 'completed') {
+ finalWidgetIds.add(runLastCall)
+ }
+ runLastCall = undefined
+ }
+ for (const item of items) {
+ if (isToolCall(item) && !pinnedToolIds.has(item.toolCallId!)) {
+ runLastCall = item.toolCallId
+ } else if (!ridesAlong(item)) {
+ closeRun()
+ }
+ }
+ if (settled) {
+ closeRun()
+ }
+
+ const result: ThreadDisplayItem[] = []
+ let run: ThreadItem[] = []
+ const flush = (): void => {
+ const calls = run.filter(isToolCall)
+ if (calls.length >= 2 || calls.some((call) => widgetToolIds.has(call.toolCallId!))) {
+ result.push({ id: `activity-${calls[0].id}`, type: 'activity_group', items: run })
+ } else {
+ result.push(...run)
+ }
+ run = []
+ }
+ for (const item of items) {
+ const folds = isToolCall(item)
+ ? !pinnedToolIds.has(item.toolCallId!) && !finalWidgetIds.has(item.toolCallId!)
+ : ridesAlong(item)
+ if (folds) {
+ run.push(item)
+ continue
+ }
+ flush()
+ // The phases flip while setup hooks run; the row shows only the latest one.
+ if (isStartupStatus(item) && result.length > 0 && isStartupStatus(result[result.length - 1])) {
+ result[result.length - 1] = item
+ } else {
+ result.push(item)
+ }
+ }
+ flush()
+ return result
+}
+
/** Groups over 10 items show the first 2 and last 3; the middle opens with one click. */
export const ACTIVITY_WINDOW_LIMIT = 10
/** Identical consecutive calls fold into one row only from this many, and only in the hidden middle. */
diff --git a/products/posthog_ai/frontend/utils/toolRunSummary.test.ts b/products/posthog_ai/frontend/utils/toolRunSummary.test.ts
new file mode 100644
index 000000000000..a1f3b41f5075
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/toolRunSummary.test.ts
@@ -0,0 +1,31 @@
+import type { ToolInvocation } from '../types/streamTypes'
+import { summarizeToolRun } from './toolRunSummary'
+
+describe('summarizeToolRun', () => {
+ const call = (kind: string | undefined, toolName?: string): ToolInvocation => ({
+ toolCallId: `${kind}-${toolName}`,
+ rawServerName: 'posthog',
+ rawToolName: toolName ?? 'exec',
+ input: {},
+ status: 'completed',
+ kind,
+ contentBlocks: [],
+ meta: toolName ? { claudeCode: { toolName } } : undefined,
+ })
+
+ it.each<[string, ToolInvocation[], string]>([
+ [
+ 'counts each kind in desktop order',
+ [call('read', 'Read'), call('execute', 'Bash'), call('execute', 'Bash'), call('other'), call('other')],
+ 'Ran 2 commands, read a file, 2 tool calls',
+ ],
+ [
+ 'reads one of each in the singular',
+ [call('search', 'Grep'), call('edit', 'Edit')],
+ 'Edited a file, ran 1 search',
+ ],
+ ['counts a subagent by its tool, not its kind', [call('think', 'Task')], 'Ran 1 subagent'],
+ ])('%s', (_, calls, label) => {
+ expect(summarizeToolRun(calls)).toBe(label)
+ })
+})
diff --git a/products/posthog_ai/frontend/utils/toolRunSummary.ts b/products/posthog_ai/frontend/utils/toolRunSummary.ts
new file mode 100644
index 000000000000..7c8686cb8114
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/toolRunSummary.ts
@@ -0,0 +1,59 @@
+import type { ToolInvocation } from '../types/streamTypes'
+import { resolveToolCall } from './toolResolver'
+
+const SUBAGENT_TOOLS = new Set(['Task', 'Agent'])
+
+type CountedKind = 'execute' | 'read' | 'list' | 'edit' | 'delete' | 'move' | 'search' | 'fetch'
+
+const COUNTED_KINDS = new Set<string>(['execute', 'read', 'list', 'edit', 'delete', 'move', 'search', 'fetch'])
+
+function plural(count: number, singular: string, pluralForm: string): string {
+ return `${count} ${count === 1 ? singular : pluralForm}`
+}
+
+function files(count: number): string {
+ return count === 1 ? 'a file' : `${count} files`
+}
+
+/** PostHog Desktop's wording for a settled run, such as "Ran 5 commands, read 2 files". */
+export function summarizeToolRun(calls: ToolInvocation[]): string {
+ const counts: Record<CountedKind | 'subagents' | 'other', number> = {
+ execute: 0,
+ read: 0,
+ list: 0,
+ edit: 0,
+ delete: 0,
+ move: 0,
+ search: 0,
+ fetch: 0,
+ subagents: 0,
+ other: 0,
+ }
+ for (const call of calls) {
+ const { claudeToolName, resolvedKey } = resolveToolCall(call)
+ if (SUBAGENT_TOOLS.has(claudeToolName ?? resolvedKey)) {
+ counts.subagents += 1
+ } else if (call.kind && COUNTED_KINDS.has(call.kind)) {
+ counts[call.kind as CountedKind] += 1
+ } else {
+ counts.other += 1
+ }
+ }
+ const parts = [
+ counts.execute > 0 && `ran ${plural(counts.execute, 'command', 'commands')}`,
+ counts.read > 0 && `read ${files(counts.read)}`,
+ counts.list > 0 && `listed ${plural(counts.list, 'directory', 'directories')}`,
+ counts.edit > 0 && `edited ${files(counts.edit)}`,
+ counts.delete > 0 && `deleted ${files(counts.delete)}`,
+ counts.move > 0 && `moved ${files(counts.move)}`,
+ counts.search > 0 && `ran ${plural(counts.search, 'search', 'searches')}`,
+ counts.fetch > 0 && `fetched ${plural(counts.fetch, 'page', 'pages')}`,
+ counts.subagents > 0 && `ran ${plural(counts.subagents, 'subagent', 'subagents')}`,
+ counts.other > 0 && plural(counts.other, 'tool call', 'tool calls'),
+ ].filter((part): part is string => !!part)
+ if (parts.length === 0) {
+ return 'Worked'
+ }
+ const label = parts.join(', ')
+ return label.charAt(0).toUpperCase() + label.slice(1)
+}
diff --git a/products/posthog_ai/frontend/utils/turnTrailers.test.ts b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
index 22726909f71a..f5d34f066de3 100644
--- a/products/posthog_ai/frontend/utils/turnTrailers.test.ts
+++ b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
@@ -1,5 +1,5 @@
import type { ThreadItem } from '../types/streamTypes'
-import { computeTurnTrailers, mapRowsToTurnSeparator } from './turnTrailers'
+import { computeTurnTrailers, mapRowsToRevealGroup } from './turnTrailers'
function item(type: ThreadItem['type'], id: string, text?: string): ThreadItem {
return { id, type, text }
@@ -66,8 +66,8 @@ describe('turnTrailers', () => {
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([
+ it('maps answer rows to their turn separator, human messages to themselves, and skips unfinished rows', () => {
+ const membership = mapRowsToRevealGroup([
item('human_message', 'h0'),
item('assistant_message', 'a0'),
item('turn_separator', 'turn-0'),
@@ -79,6 +79,13 @@ describe('turnTrailers', () => {
item('assistant_message', 'a2'),
])
- expect(Object.fromEntries(membership)).toEqual({ a0: 'turn-0', t1: 'turn-1', a1: 'turn-1' })
+ expect(Object.fromEntries(membership)).toEqual({
+ h0: 'h0',
+ a0: 'turn-0',
+ h1: 'h1',
+ t1: 'turn-1',
+ a1: 'turn-1',
+ h2: 'h2',
+ })
})
})
diff --git a/products/posthog_ai/frontend/utils/turnTrailers.ts b/products/posthog_ai/frontend/utils/turnTrailers.ts
index b119a4230d2d..799a2141d482 100644
--- a/products/posthog_ai/frontend/utils/turnTrailers.ts
+++ b/products/posthog_ai/frontend/utils/turnTrailers.ts
@@ -58,12 +58,17 @@ 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> {
+/**
+ * Maps each row to the group whose hover reveals its footer. A human message is its own group. An answer row belongs
+ * to its turn's separator, so hovering any row of the turn reveals the turn's trailer. Rows of an unfinished turn
+ * have no separator yet, so they get no entry.
+ */
+export function mapRowsToRevealGroup(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') {
+ membership.set(item.id, item.id)
pending = []
} else if (item.type === 'turn_separator') {
for (const id of pending) {