Skip to content

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

feat(phai): task run log styling (#66395)

Georgiy Tarasov359263fa6006
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e31574902440..b7eabb89dddf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5577,17 +5577,17 @@ snapshots:
scenes-app-inbox-detail--report-minimal--light:
hash: v1.k794b7964.0d41bcb80f75889f19bb97431a0ea86a2128d00eafd5a07c5f7ac5acc3e7d14e.7a4HLQtAa2T29HhTiXgo4hhzixjc70hJlL6tOGxN5IE
scenes-app-inbox-detail--run-failed--dark:
- hash: v1.k794b7964.c0871658ef7f3c70991579392f170e561b7e02012f25b2fb91c037e12ef2b7e5.9BuPfkNlOUsXtPDxZw0SpzHuxsFpRk0zYr1qbUSfTUE
+ hash: v1.k794b7964.7bf5ec102fe3cf7e523b8abe82aa38d120b854ab3a44a56610aea33279e184ea.R3JiyhN_djiElTD8XECw6qhErhjJ_xBa2c1XfTkUoGQ
scenes-app-inbox-detail--run-failed--light:
- hash: v1.k794b7964.44ebf07a1f6f87a9da89aaa2fb74e1fb3eab77b551fef3c53940e5241946381b.fVc4j0b_baLCed5kkBPuSCwJbUGz7yXi_G3pkWHca-8
+ hash: v1.k794b7964.f37650c6534dccb4bfc66b03fa60253b0b351eb88bd13529f0a4e26a3f4f72f4.rHzcoM0_IyR3M-Q2d9RHYOm8lp2yJT9j3jkLQcyUw-M
scenes-app-inbox-detail--run-in-progress--dark:
- hash: v1.k794b7964.ab9f9752bb67cc0ad39a4ff7d1efd848ecf14f6f71f343634283d7cc4a790ed7.hhAXCqbj1_PfpZOKUlNZASh7EdvcfqxHft4QMMIgvBo
+ hash: v1.k794b7964.f160cafe45011ce8a27d166d2b1c8c102cd26eddcb54cfe592dfeb098bec63c8.G_pEQ5ts1KwR41svCt83d7HaepQLCGCrWNZXtzGsnxU
scenes-app-inbox-detail--run-in-progress--light:
- hash: v1.k794b7964.afd17a4f6ab6b7c2da21b3516168e9dc46e16ee95f7b15f4b464f8a6079d990e.IO1ku-tgJBFhGQ0AtZWiMzK7Kljtv0R2zPLSx3u8L4c
+ hash: v1.k794b7964.fbf710b96b6c86c03594dbfc214674dfb2da25eba880ec0469cbf1f3b068225c.3H-omKdrADqcUy9CYdekw-W5am55ai9HhlNuecKjUVM
scenes-app-inbox-detail--run-ready--dark:
- hash: v1.k794b7964.9455e0021fee635cd2dc67ef2dd6f5ea0e1acb15fbe396235b7c577589cfc9cc.DIumkcqd3LeJxymXRgoiGqMXSRRQsrlSgVRozhIwWcY
+ hash: v1.k794b7964.e36695d83d6502285783b7f7030bef2d25c7e71d6385611b04236a3c683293e4.oUkVq4Fh4_s8gHq9c5cXmhUQSXFLGrvyv-dI1SGmcpA
scenes-app-inbox-detail--run-ready--light:
- hash: v1.k794b7964.1275e53ffe43ab03b0662bdce1c71ff390aca055f822bbe9ef0d1da32b3ad6ac.DwdNm96SH0AWVIw4gKzdTglfVjjs0n7WNjsvPptuMko
+ hash: v1.k794b7964.7f940d67d5626a00a6970f16a0d3baff59ce5b896e8b0c0967c3fe7f483a1045.woobfMUZ9Hz0XHCYw6w_WvNoS25BhDJr6mk8XkMb9AI
scenes-app-inbox-scene--empty--dark:
hash: v1.k794b7964.0730c341122d1d593f4e6acf7a176e05bdd79e9ca6bf5f785a909fd57ad274f1.V4Hgc6xF9-5hiq75aqzZWcbiemdqMe3fdbcMqVHbg7U
scenes-app-inbox-scene--empty--light:
@@ -6781,9 +6781,9 @@ snapshots:
scenes-app-tasks--new-task--light:
hash: v1.k794b7964.3674cdd577b0a22f9459dfd9e7c6e98c36a7bf3b9a68e8e7508ac6a0366708d7.QZSXTiTa56QfQlAsFFRfl5KniKwm0rvJdkIvjwliLmM
scenes-app-tasks--task-detail-loading--dark:
- hash: v1.k794b7964.b09744582ebfb6d0aa98cd13bad8cdcf8822be75bcae6b2cbcc629ad1f3ba6f6.4hjsH9SRmNf7A_4bXyDGyRhiP9gpMa1Hd_h9929iSNQ
+ hash: v1.k794b7964.d3643f39c3ebd6c0b4da18ee269b86373be7f8f07c65bf895e6527e69330f872.BWj6tyeJtfgZdzKGw_Yu7Kh3NPd88r3CtTORgjWowq4
scenes-app-tasks--task-detail-loading--light:
- hash: v1.k794b7964.372a0b839c9e364b8a9cb88029baf5501fab530236912036f1bb7cadad2a9f2d.ZwOyzAplL-7oLsLZhs8U80XVHSBQX2trxvpcQusiG_E
+ hash: v1.k794b7964.73d40acde6215254fd9b8d8c90bbd0a80c79ed1c1549fcaa5cc0bcc546a66c7e.sAVkYCAnXq9_ZHXAS9I_16FyMTxQeUdek46-nB4l_ik
scenes-app-tasks--task-load-error--dark:
hash: v1.k794b7964.86670a5cd725be9f8f82ae187271572354582f97b015033a674a3fe074e60078.3X4ATJf6GjVtAx40icISr3TrfHsuzqiHMYyBJjGxFHQ
scenes-app-tasks--task-load-error--light:
@@ -6793,17 +6793,17 @@ snapshots:
scenes-app-tasks--task-not-found--light:
hash: v1.k794b7964.9e2c572e5d759abb2cd78a8550c9f7947b595fbf49081c4f94b0da200371f272.iZlhOSdAT4QYkRzPpd06UeuoQqd2Qs21o6C5UPVce2Y
scenes-app-tasks--task-run-not-found--dark:
- hash: v1.k794b7964.ed230a981c24663792c1df13d16dd8461f35fe15e4aa1965894084fbab68b117.rhSCibvjYukRnr74a1jUyVEWHUygAfzKqD7aOHjPBwc
+ hash: v1.k794b7964.561dda9673b2eb99c82571bdada8c6dda4fd4ba40e573bfb023428bbc308a03e.73mFdHpavkbvsouKUVKmtelR4BXSF6uw52kr53mpsSU
scenes-app-tasks--task-run-not-found--light:
- hash: v1.k794b7964.2ba26c7d208c96437ce4d9c9a7f9fed85125b5ac37f7e901a65391ffb7a300cb.R6p-TsMtTeS78M-yuAwGoC5C_iqX26NW6w2Bvc0zxo4
+ hash: v1.k794b7964.3e507d01ccaf174c942f4729b31a9fcb8605a3078ba6b0c9cf35870db12d27c6.BVJz-NIVPvDyxmSpwA2jUbET2CaDb9aqmJG-T5V2AyA
scenes-app-tasks--task-runs-load-error--dark:
- hash: v1.k794b7964.c540707360fc3fbda25bfc57c8a0e8ef4c24074ca8baccf39ed2231b4df8b1d8.gYnxqtXSk1a31kKxA6Vek67Ytabt4BayCmKhw9FBBoU
+ hash: v1.k794b7964.d6f11eb7333242265c6d0c2be9e6ed4d80bd8770c41ac8a57240ac99bf3e300b.pwthVPG4-rLBXo_bJOsVoS1tkbXH3oiFBuvSh0rJC0U
scenes-app-tasks--task-runs-load-error--light:
- hash: v1.k794b7964.49c406248302859f8a551be6668b1a92984cbb087272d782562dba210158a8d8.LocFi59O--ouDjbYebmk1tJoXk6L4bmL4j4-KgaKYxI
+ hash: v1.k794b7964.80a1516ffc33d4332cb8d9221120a07d400a4d57c03dd4e8a99f64166faef2d8.GkjUzaQyrXhTtbals16yMBCK2rkh6p6dxFaZuyFSQbg
scenes-app-tasks--task-selected--dark:
- hash: v1.k794b7964.b3b7094f97b9140b6a58a9886a5166cfa9140870a7a907160fcf347377773b61.AKASaTJicvtjc8NQAG_SM2R2cvVEyoXYVkseLCAM_14
+ hash: v1.k794b7964.f85eae34f9cf173463a4ac0376fda2450a887e492bab2299a5606938c0ddb66b.XAzOwO5Qc4vFo8M54vgUEWFzt2lhnto6qWhlRaJzEOg
scenes-app-tasks--task-selected--light:
- hash: v1.k794b7964.7cd83d720d4daa8e45308d356b736e73177946088853cd744c86c6b6780d1a36.Ey-ysUe5bUVxNJrobBpq1pkzP9ysopvIVJgSOWyE87I
+ hash: v1.k794b7964.f23df892d0a96ffa0ae5d79d52bdcc51f483750ebd4dfc39e4d55d0cc260cc79.UYLaUsEJnBsWdg3YgNyYOHgrCGE-YE44kZYtEyUiUjQ
scenes-app-user-interviews-invite-preview-modal--emailable--dark:
hash: v1.k794b7964.0cd3e50dcd442e57712b0ebe06d6952c589a4c88c49fca26771c9e17bc07e6dc.iNYX9Up5MvnGHGT7ku7yMuFIJ0NnbSspOz6Ce0Kb2cU
scenes-app-user-interviews-invite-preview-modal--emailable--light:
diff --git a/frontend/src/lib/components/MonacoDiffEditor.tsx b/frontend/src/lib/components/MonacoDiffEditor.tsx
index a560b1650f07..6deab1e2c3c2 100644
--- a/frontend/src/lib/components/MonacoDiffEditor.tsx
+++ b/frontend/src/lib/components/MonacoDiffEditor.tsx
@@ -18,6 +18,8 @@ export interface MonacoDiffEditorProps {
className?: string | null
originalUri?: (m: typeof monaco) => monaco.Uri
modifiedUri?: (m: typeof monaco) => monaco.Uri
+ /** Optional placeholder overlaid on the editor until it has laid out its first content. */
+ loading?: React.ReactNode
}
const LINE_HEIGHT = 18
@@ -43,6 +45,7 @@ function MonacoDiffEditor(
className = null,
originalUri,
modifiedUri,
+ loading = null,
}: MonacoDiffEditorProps,
ref: React.ForwardedRef<{ editor: monaco.editor.IStandaloneDiffEditor | null }>
): JSX.Element {
@@ -190,14 +193,17 @@ function MonacoDiffEditor(
return (
<div
- ref={containerRef}
+ className="relative"
// eslint-disable-next-line react/forbid-dom-props
style={{
width: processSize(width),
height: processSize(calculatedHeight),
}}
- className="react-monaco-editor-container"
- />
+ >
+ <div ref={containerRef} className="react-monaco-editor-container w-full h-full" />
+ {/* Overlay the placeholder until Monaco reports its first content size (editor laid out). */}
+ {loading && contentHeight === null && <div className="absolute inset-0">{loading}</div>}
+ </div>
)
}
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
index 37cccfa5f62e..b8b5da5173f6 100644
--- a/products/posthog_ai/frontend/AGENTS.md
+++ b/products/posthog_ai/frontend/AGENTS.md
@@ -131,6 +131,16 @@ loosely typed — guard at the parse boundary with runtime checks; never assume
`useMemo`, wrap child callbacks in `useCallback`, and subscribe narrowly (select only what you render).
- **Keep the projection pure.** `foldLogToThread` is pure and deterministic; item ids stay stable across
re-folds. Listeners fire only side effects, each with a fire-once guard, suppressed on `source: 'replay'`.
+- **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
+ presentable information a tool produces — parsed output, commit/repo lists, file contents, diffs, raw
+ text — must go in the collapsible `body`, never the always-visible `children`.** The body is the
+ `Activity` accordion: it auto-expands while the tool runs and collapses once it completes, so the
+ thread stays scannable (one or two lines per tool) and a reader expands only the cards they care about.
+ Reserve `children` (always-visible) for genuinely interactive payloads that would be useless collapsed
+ (e.g. the `AskUserQuestion` recap the user must act on) — not for output. When in doubt, it goes in the
+ accordion.
## 5. Layout
diff --git a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
index e20741210ee1..71850f612957 100644
--- a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
+++ b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
@@ -1,8 +1,8 @@
import clsx from 'clsx'
import React, { useLayoutEffect, useState } from 'react'
-import { IconCheck, IconChevronDown, IconChevronRight, IconX } from '@posthog/icons'
-import { LemonButton, Spinner } from '@posthog/lemon-ui'
+import { IconChevronDown, IconChevronRight } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
import { MarkdownMessage } from '../messages/MarkdownMessage'
@@ -52,26 +52,13 @@ function activitySubstepText(content: string, isInProgress: boolean): string {
return content
}
-export function ActivityStatusIcon({
- status,
- showCompletionIcon = true,
- showProgressIcon = false,
- failedIcon,
-}: {
+export function ActivityStatusIcon(_props: {
status: ActivityStatus
showCompletionIcon?: boolean
showProgressIcon?: boolean
failedIcon?: React.ReactNode
}): JSX.Element | null {
- if ((status === 'pending' || status === 'in_progress') && showProgressIcon) {
- return <Spinner className="size-3" />
- }
- if (status === 'completed' && showCompletionIcon) {
- return <IconCheck className="text-success size-3" />
- }
- if (status === 'failed' && showCompletionIcon) {
- return failedIcon ? <>{failedIcon}</> : <IconX className="text-danger size-3" />
- }
+ // Intentionally renders nothing — kept as a no-op so the Activity prop chain and facade export stay stable.
return null
}
@@ -104,12 +91,15 @@ export function ActivityHeader({
const isInProgress = status === 'in_progress'
const isFailed = status === 'failed'
- const titleNode =
- isInProgress && animate ? (
- <ShimmeringContent>{title}</ShimmeringContent>
- ) : (
- <span className={clsx('inline-flex', isInProgress && 'text-muted')}>{title}</span>
- )
+ const titleNode = (
+ <div className="min-w-0 min-h-5 flex items-center">
+ {isInProgress && animate ? (
+ <ShimmeringContent>{title}</ShimmeringContent>
+ ) : (
+ <span className={clsx('inline-flex', isInProgress && 'text-muted')}>{title}</span>
+ )}
+ </div>
+ )
const statusIcon = (
<ActivityStatusIcon
status={status}
@@ -164,20 +154,20 @@ export function ActivityHeader({
)}
</div>
)}
- <div className="flex items-center gap-1 flex-1 min-w-0 h-full">
+ <div className="flex items-center gap-1 flex-1 min-w-0">
{children ? (
// The title/subtitle column grows to fill the row, so the subtitle (second line) gets the
// full available width before it truncates.
<div className="flex flex-col flex-1 min-w-0">
{/* Status icon rides the first line with the title; the second line is the subtitle. */}
<div className="flex items-center gap-1 min-w-0">
- <div className="min-w-0">{titleNode}</div>
+ {titleNode}
{statusIcon}
</div>
<div className="text-muted truncate min-w-0">{children}</div>
</div>
) : (
- <div className="min-w-0">{titleNode}</div>
+ titleNode
)}
{!children && statusIcon}
</div>
diff --git a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsx
index d2465a8d9d32..077c88e207d4 100644
--- a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsx
+++ b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsx
@@ -19,6 +19,8 @@ jest.mock('../logics/runStreamLogic', () => ({
status != null && ['completed', 'failed', 'cancelled'].includes(status),
}))
+jest.mock('../logics/taskLogic', () => ({ taskLogic: jest.fn(() => ({ __mock: 'taskLogic' })) }))
+
jest.mock('./ThreadView', () => ({ ThreadView: () => <div data-attr="thread" /> }))
jest.mock('./ResourcesBar', () => ({ ResourcesBar: () => <div data-attr="resources" /> }))
jest.mock('./ContextUsageBar', () => ({ ContextUsageBar: () => <div data-attr="context" /> }))
@@ -32,6 +34,8 @@ function setValues(overrides: Partial<{ pendingPermissionRequest: PermissionRequ
threadItems: [{ id: 'x' }],
pendingPermissionRequest: null,
currentRunStatus: 'in_progress',
+ task: null,
+ taskLoading: false,
...overrides,
})
}
@@ -39,7 +43,7 @@ function setValues(overrides: Partial<{ pendingPermissionRequest: PermissionRequ
describe('ReadonlyRunSurfaceImpl', () => {
beforeEach(() => {
jest.clearAllMocks()
- ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun: jest.fn(), reset: jest.fn() })
+ ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun: jest.fn(), reset: jest.fn(), loadTask: jest.fn() })
setValues()
})
@@ -57,11 +61,12 @@ describe('ReadonlyRunSurfaceImpl', () => {
expect(screen.queryByTestId('question')).not.toBeInTheDocument()
})
- it('renders the thread plus meta bars for a live run, but never a composer or approval prompt', () => {
+ it('renders the thread plus the resources bar for a live run, but never a composer or approval prompt', () => {
render(<ReadonlyRunSurfaceImpl taskId="task-1" runId="run-1" interaction="live" />)
expect(screen.getByTestId('thread')).toBeInTheDocument()
expect(screen.getByTestId('resources')).toBeInTheDocument()
- expect(screen.getByTestId('context')).toBeInTheDocument()
+ // Context usage now rides the thread footer (inside ThreadView), not a standalone bar.
+ expect(screen.queryByTestId('context')).not.toBeInTheDocument()
expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
expect(screen.queryByTestId('permission')).not.toBeInTheDocument()
expect(screen.queryByTestId('question')).not.toBeInTheDocument()
diff --git a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsx
index 3b6483901432..30d856175487 100644
--- a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsx
@@ -16,8 +16,8 @@ export interface ReadonlyRunSurfaceProps {
* Prepackaged read-only run surface — the common inbox embed, owned by the library. Composes the
* `RunSurface` compound and never renders `<RunSurface.Composer>`, so there is no composer and no approval
* prompt (you don't act on a run from the inbox). It still streams fresh frames while the run is in progress
- * when `interaction='live'`, surfacing the meta bars (resources + context usage); a terminal run replays the
- * snapshot once and shows only the thread.
+ * when `interaction='live'`, surfacing the resources bar (context usage rides the thread footer between
+ * turns); a terminal run replays the snapshot once and shows only the thread.
*/
export default function ReadonlyRunSurfaceImpl({
taskId,
@@ -39,7 +39,6 @@ export default function ReadonlyRunSurfaceImpl({
<RunSurface.Thread listClassName={threadListClassName} rowClassName={threadRowClassName} />
</div>
<RunSurface.Resources />
- <RunSurface.ContextUsage />
</div>
)}
</RunSurface.Root>
diff --git a/products/posthog_ai/frontend/components/RunContext.tsx b/products/posthog_ai/frontend/components/RunContext.tsx
index 3566dc43b125..188753a1595e 100644
--- a/products/posthog_ai/frontend/components/RunContext.tsx
+++ b/products/posthog_ai/frontend/components/RunContext.tsx
@@ -2,6 +2,8 @@ import { memo } from 'react'
import { IconGitBranch } from '@posthog/icons'
+import { cn } from 'lib/utils/css-classes'
+
/**
* 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
@@ -12,13 +14,18 @@ export const RunContext = memo(function RunContext({
branch,
baseBranch,
repo,
+ className,
}: {
branch: string
baseBranch?: string
repo?: string
+ className?: string
}): JSX.Element {
return (
- <div className="flex items-center gap-1.5 px-3 py-1 text-xs text-muted" data-attr="max-sandbox-run-context">
+ <div
+ className={cn('flex items-center gap-1.5 px-3 py-1 text-xs text-muted', className)}
+ data-attr="max-sandbox-run-context"
+ >
<IconGitBranch className="size-3.5 shrink-0" />
<span className="min-w-0 truncate">
Working on{' '}
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
index 729ab83516af..466e30eb01c3 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
@@ -20,6 +20,8 @@ jest.mock('../logics/runStreamLogic', () => ({
status != null && ['completed', 'failed', 'cancelled'].includes(status),
}))
+jest.mock('../logics/taskLogic', () => ({ taskLogic: jest.fn(() => ({ __mock: 'taskLogic' })) }))
+
jest.mock('./ThreadView', () => ({ ThreadView: () => <div data-attr="thread" /> }))
jest.mock('./ResourcesBar', () => ({ ResourcesBar: () => <div data-attr="resources" /> }))
jest.mock('./ContextUsageBar', () => ({ ContextUsageBar: () => <div data-attr="context" /> }))
@@ -40,6 +42,8 @@ function setValues(
threadItems: [],
pendingPermissionRequest: null,
currentRunStatus: 'in_progress',
+ task: null,
+ taskLoading: false,
...overrides,
})
}
@@ -64,7 +68,7 @@ function renderLiveWithComposer(statusOrOverrides: RunStatus | null | Parameters
describe('RunSurface', () => {
beforeEach(() => {
jest.clearAllMocks()
- ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun: jest.fn(), reset: jest.fn() })
+ ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun: jest.fn(), reset: jest.fn(), loadTask: jest.fn() })
setValues({})
})
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
index eb3e2abc6f2c..2a68e6c37783 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -1,7 +1,11 @@
import { BindLogic, useActions, useValues } from 'kea'
import { createContext, type ReactNode, useContext, useEffect } from 'react'
+import { LemonDivider } from '@posthog/lemon-ui'
+
import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'
+import { taskLogic } from '../logics/taskLogic'
+import { OriginProduct } from '../types/taskTypes'
import { ContextUsageBar } from './ContextUsageBar'
import { PermissionInput } from './PermissionInput'
import { QuestionInput } from './QuestionInput'
@@ -39,6 +43,8 @@ interface RunSurfaceContextValue {
/** Logic key (used for child stream keys). */
runId: string
interaction: 'live' | 'read-only'
+ /** Run created by a Signals scout — the context-usage line is suppressed for these. */
+ isScout: boolean
}
const RunSurfaceContext = createContext<RunSurfaceContextValue | null>(null)
@@ -72,6 +78,19 @@ function RunSurfaceRoot({
}: RunSurfaceRootProps): JSX.Element {
const replayOnly = interaction !== 'live'
const logicKey = streamKey ?? runId
+
+ // The scout flag lives on the task (not the run), so the surface owns loading it once and exposing it
+ // to the slots — the runner already has the task loaded, a live embed fetches it here. Only the
+ // context-usage line consumes this, and only in live mode, so a read-only embed never fetches.
+ const { task, taskLoading } = useValues(taskLogic({ taskId }))
+ const { loadTask } = useActions(taskLogic({ taskId }))
+ useEffect(() => {
+ if (interaction === 'live' && !task && !taskLoading) {
+ loadTask()
+ }
+ }, [interaction, task, taskLoading, loadTask])
+ const isScout = task?.origin_product === OriginProduct.SIGNALS_SCOUT
+
return (
<BindLogic logic={runStreamLogic} props={{ streamKey: logicKey, conversationId, replayOnly }}>
<RunSurfaceContext.Provider
@@ -79,6 +98,7 @@ function RunSurfaceRoot({
rawRunId: runId,
runId: logicKey,
interaction,
+ isScout,
}}
>
<RunSurfaceBootstrap taskId={taskId} />
@@ -111,13 +131,22 @@ function RunSurfaceThread({
listClassName,
rowClassName,
}: { className?: string; listClassName?: string; rowClassName?: string } = {}): JSX.Element {
+ const { interaction, isScout } = useRunSurfaceContext()
const { bootstrapLoading, threadItems } = useValues(runStreamLogic)
const showSkeleton = bootstrapLoading && threadItems.length === 0
if (showSkeleton) {
return <RunLogSkeleton className={className} listClassName={listClassName} rowClassName={rowClassName} />
}
- // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
- return <ThreadView className={className} listClassName={listClassName} rowClassName={rowClassName} />
+ // Context usage rides the thread footer for live runs (the meta bars are live-only), but never for a
+ // scout run. An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
+ return (
+ <ThreadView
+ className={className}
+ listClassName={listClassName}
+ rowClassName={rowClassName}
+ showContextUsage={interaction === 'live' && !isScout}
+ />
+ )
}
/**
@@ -139,11 +168,13 @@ function RunSurfaceComposer({ children }: { children?: ReactNode }): JSX.Element
const isQuestion = !!pendingPermissionRequest.questions && pendingPermissionRequest.questions.length > 0
return (
<div className="border-t px-4 py-3">
- {isQuestion ? (
- <QuestionInput streamKey={runId} request={pendingPermissionRequest} />
- ) : (
- <PermissionInput streamKey={runId} request={pendingPermissionRequest} />
- )}
+ <div className="mx-auto w-full max-w-180">
+ {isQuestion ? (
+ <QuestionInput streamKey={runId} request={pendingPermissionRequest} />
+ ) : (
+ <PermissionInput streamKey={runId} request={pendingPermissionRequest} />
+ )}
+ </div>
</div>
)
}
@@ -151,8 +182,9 @@ function RunSurfaceComposer({ children }: { children?: ReactNode }): JSX.Element
return null // no composer UI supplied (e.g. ReadonlyRunSurface) or pre-bootstrap
}
return (
- <div data-attr="composer" className="border-t px-4 py-3">
- {children}
+ <div data-attr="composer" className="px-4 pb-4">
+ <LemonDivider className="mt-0 mb-4" />
+ <div className="mx-auto w-full max-w-180">{children}</div>
</div>
)
}
diff --git a/products/posthog_ai/frontend/components/ThreadItems.tsx b/products/posthog_ai/frontend/components/ThreadItems.tsx
index 0da0321d1cf9..6db7dd6f047c 100644
--- a/products/posthog_ai/frontend/components/ThreadItems.tsx
+++ b/products/posthog_ai/frontend/components/ThreadItems.tsx
@@ -1,10 +1,11 @@
-import { IconCheck, IconWarning, IconX } from '@posthog/icons'
+import { IconCheck, IconCollapse, IconWarning, IconX } from '@posthog/icons'
import { Spinner } from '@posthog/lemon-ui'
-import { cn } from 'lib/utils/css-classes'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import type { ThreadItem } from '../types/streamTypes'
+import { Activity } from './ActivityPrimitives'
+import type { ActivityStatus } from './ActivityPrimitives'
/** Inline `_posthog/status` item — a spinner while compacting, a generic status line otherwise. */
export function StatusItem({ item }: { item: ThreadItem }): JSX.Element {
@@ -23,39 +24,45 @@ export function StatusItem({ item }: { item: ThreadItem }): JSX.Element {
)
}
-/** Inline `_posthog/compact_boundary` item — the post-compaction rule. */
+/** Inline `_posthog/compact_boundary` item — the post-compaction card. */
export function CompactBoundaryItem({ item }: { item: ThreadItem }): JSX.Element {
+ const parts = [
+ item.trigger ? `(${item.trigger})` : null,
+ typeof item.preTokens === 'number' ? `~${humanFriendlyNumber(item.preTokens)} tokens summarized` : null,
+ ].filter(Boolean)
+ const subtitle = parts.length > 0 ? parts.join(' · ') : undefined
return (
- <div className="flex items-center gap-2 py-1 text-xs text-muted">
- <div className="h-px grow bg-border" />
- <span className="shrink-0">
- Conversation compacted
- {item.trigger ? ` (${item.trigger})` : ''}
- {typeof item.preTokens === 'number'
- ? ` · ~${humanFriendlyNumber(item.preTokens)} tokens summarized`
- : ''}
- </span>
- <div className="h-px grow bg-border" />
- </div>
+ <Activity
+ id={item.id}
+ title="Conversation compacted"
+ subtitle={subtitle}
+ status="completed"
+ icon={<IconCollapse className="size-4" />}
+ animate={false}
+ showCompletionIcon={false}
+ />
)
}
-/** Inline `_posthog/task_notification` item — a colored rule by status (completed/failed/stopped). */
+/** Inline `_posthog/task_notification` item — a status card for a completed/failed/stopped task. */
export function TaskNotificationItem({ item }: { item: ThreadItem }): JSX.Element {
- const colorClass =
- item.status === 'completed' ? 'text-success' : item.status === 'failed' ? 'text-danger' : 'text-warning'
+ const activityStatus: ActivityStatus = item.status === 'completed' ? 'completed' : 'failed'
const icon =
item.status === 'completed' ? (
- <IconCheck className="size-3" />
+ <IconCheck className="size-4" />
) : item.status === 'failed' ? (
- <IconX className="size-3" />
+ <IconX className="size-4" />
) : (
- <IconWarning className="size-3" />
+ <IconWarning className="size-4" />
)
return (
- <div className={cn('flex items-center justify-center gap-1.5 py-1 text-xs', colorClass)}>
- {icon}
- <span>{item.summary || `Task ${item.status}`}</span>
- </div>
+ <Activity
+ id={item.id}
+ title={item.summary || `Task ${item.status}`}
+ status={activityStatus}
+ icon={icon}
+ animate={false}
+ showCompletionIcon={false}
+ />
)
}
diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsx
index 858b2556860c..5a1e3b60c69b 100644
--- a/products/posthog_ai/frontend/components/ThreadRow.tsx
+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx
@@ -8,6 +8,7 @@ import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTyp
import { runStreamLogic } from '../logics/runStreamLogic'
import { AssistantFailureMessage } from '../messages/AssistantFailureMessage'
+import { DebugMessage } from '../messages/DebugMessage'
import { MarkdownMessage } from '../messages/MarkdownMessage'
import { MessageTemplate } from '../messages/MessageTemplate'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
@@ -160,5 +161,8 @@ export const ThreadRow = memo(function ThreadRow({
if (item.type === 'progress') {
return <ProgressItem item={item} />
}
+ if (item.type === 'debug') {
+ return <DebugMessage text={item.text ?? ''} level={item.debugLevel ?? 'info'} />
+ }
return null
})
diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsx
index b3e0392c94bf..0481cc069f46 100644
--- a/products/posthog_ai/frontend/components/ThreadView.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.tsx
@@ -5,6 +5,7 @@ import { runStreamLogic } from '../logics/runStreamLogic'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
import type { ThreadItem } from '../types/streamTypes'
import { getRandomThinkingMessage } from '../utils/thinkingMessages'
+import { ContextUsageBar } from './ContextUsageBar'
import { PullRequestCard } from './PullRequestCard'
import { RunContext } from './RunContext'
import { ThreadRow } from './ThreadRow'
@@ -15,6 +16,23 @@ function getThreadItemKey(item: ThreadItem): string {
return item.id
}
+interface ThreadViewProps {
+ /**
+ * Pass `false` when an ancestor already owns scroll (the live Max column + auto-scroller) — rows then
+ * render in document flow, unchanged from the pre-virtualized layout. Defaults to virtualized.
+ */
+ virtualized?: boolean
+ /**
+ * Opts the context-usage line into the footer, shown only between turns (when the agent isn't actively
+ * working). Off by default so a bare `ThreadView` is unaffected; the run surface turns it on for live,
+ * non-scout runs.
+ */
+ showContextUsage?: boolean
+ className?: string
+ listClassName?: string
+ rowClassName?: string
+}
+
/**
* Sandbox-runtime thread presenter. Reads `runStreamLogic.values.threadItems` (assistant text,
* tool-invocation references, run separators, inline errors) from whatever `runStreamLogic`
@@ -23,18 +41,26 @@ function getThreadItemKey(item: ThreadItem): string {
* only the bound stream logic, never langgraph vs sandbox or the conversation.
*
* Rows are virtualized through `VirtualizedThread`, which owns scroll and stick-to-bottom; the leading
- * run context and trailing thinking indicator / PR card ride along as the header/footer rows. Pass
- * `virtualized={false}` when an ancestor already owns scroll (the live Max column + auto-scroller) — rows
- * then render in document flow, unchanged from the pre-virtualized layout.
+ * run context and trailing thinking indicator / PR card / context-usage line ride along as the
+ * header/footer rows.
*/
export function ThreadView({
virtualized = true,
+ showContextUsage = false,
className,
listClassName,
rowClassName,
-}: { virtualized?: boolean; className?: string; listClassName?: string; rowClassName?: string } = {}): JSX.Element {
- const { threadItems, toolInvocations, isThinking, streamPhase, runArtifacts, turnComplete, currentRunStatus } =
- useValues(runStreamLogic)
+}: ThreadViewProps): JSX.Element {
+ const {
+ threadItems,
+ toolInvocations,
+ isThinking,
+ streamPhase,
+ runArtifacts,
+ turnComplete,
+ currentRunStatus,
+ contextUsage,
+ } = useValues(runStreamLogic)
const turnCancelled = currentRunStatus === 'cancelled'
const hasActiveProgressItem = threadItems.some(
(item) => item.type === 'progress' && item.progressSteps?.some((step) => step.status === 'in_progress')
@@ -47,7 +73,7 @@ export function ThreadView({
const header = useMemo(
() =>
branch ? (
- <VirtualizedThread.Row>
+ <VirtualizedThread.Row className={rowClassName}>
<ThreadHeader branch={branch} baseBranch={baseBranch} repo={repo} />
</VirtualizedThread.Row>
) : undefined,
@@ -57,14 +83,22 @@ export function ThreadView({
const showThinking = streamPhase === 'thinking' && !hasActiveProgressItem
// Post-turn only: a reconnect refetch can fold in a pr_url mid-run, so gate on !isThinking.
const pullRequestUrl = !isThinking ? runArtifacts.prUrl : undefined
+ // Context usage rides the thread footer, but only between turns (idle) — never while the agent is
+ // working, where the thinking line takes the footer. `ContextUsageBar` self-hides without data.
+ const showContextUsageFooter = showContextUsage && !isThinking && !!contextUsage
const footer = useMemo(
() =>
- showThinking || pullRequestUrl ? (
- <VirtualizedThread.Row>
- <ThreadFooter showThinking={showThinking} pullRequestUrl={pullRequestUrl} prBranch={branch} />
+ showThinking || pullRequestUrl || showContextUsageFooter ? (
+ <VirtualizedThread.Row className={rowClassName}>
+ <ThreadFooter
+ showThinking={showThinking}
+ pullRequestUrl={pullRequestUrl}
+ prBranch={branch}
+ showContextUsage={showContextUsageFooter}
+ />
</VirtualizedThread.Row>
) : undefined,
- [showThinking, pullRequestUrl, branch]
+ [showThinking, pullRequestUrl, branch, showContextUsageFooter]
)
const renderItem = useCallback(
@@ -113,25 +147,31 @@ const ThreadHeader = memo(function ThreadHeader({
})
/**
- * Trailing row: the "what's it doing now" thinking line and/or the produced PR card. Subscribes to
- * `currentProgress` itself so the frequently-updating progress text stays isolated here — it never
- * re-renders `ThreadView` or destabilizes the footer's element identity during streaming.
+ * Trailing row: the "what's it doing now" thinking line, the produced PR card, and/or the context-usage
+ * line (between turns). Subscribes to `currentProgress` itself so the frequently-updating progress text
+ * stays isolated here — it never re-renders `ThreadView` or destabilizes the footer's element identity
+ * during streaming.
*/
const ThreadFooter = memo(function ThreadFooter({
showThinking,
pullRequestUrl,
prBranch,
+ showContextUsage,
}: {
showThinking: boolean
pullRequestUrl?: string
prBranch?: string
+ showContextUsage?: boolean
}): JSX.Element {
const { currentProgress } = useValues(runStreamLogic)
+ // `gap-1.5` matches the thread's inter-row gap (`VirtualizedThread`'s `gap` default) so stacked footer
+ // items keep the same vertical rhythm as the thread.
return (
- <>
+ <div className="flex flex-col gap-1.5">
{showThinking && <ThinkingIndicator progress={currentProgress} />}
{pullRequestUrl && <PullRequestCard prUrl={pullRequestUrl} branch={prBranch} />}
- </>
+ {showContextUsage && <ContextUsageBar />}
+ </div>
)
})
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
index 21def85d84a0..c8a261065672 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
@@ -18,6 +18,22 @@ import { cn } from 'lib/utils/css-classes'
/** Within this many px of the bottom still counts as "pinned" — absorbs iOS momentum/rubber-band jitter. */
const BOTTOM_THRESHOLD = 32
+/**
+ * At or within this many px of the bottom counts as "already there", so `maybeStickToBottom` skips re-issuing
+ * a scroll — doing so at the final position cancels macOS's native overscroll bounce and reads as a shake.
+ * Kept tiny (a scroll snaps exactly to the bottom, so a resting reader is at distance 0); just wide enough to
+ * absorb fractional-pixel scroll positions. Growth past this still re-pins to the true bottom.
+ */
+const AT_BOTTOM_EPSILON = 2
+
+/**
+ * Frames the initial settle-to-bottom keeps re-issuing the scroll. With variable row heights a single
+ * scroll on first content lands short (rows below the fold are estimated until rendered + measured), so a
+ * freshly refreshed/opened thread needs a few correction frames to reach the true bottom. Bounded so a
+ * never-settling layout can't loop forever.
+ */
+const MAX_INITIAL_SCROLL_FRAMES = 30
+
const EMPTY_STYLE: CSSProperties = {}
const EMPTY_ARIA: Record<string, unknown> = {}
@@ -108,6 +124,7 @@ function Root<T>({
const rowCount = items.length + (hasHeader ? 1 : 0) + (hasFooter ? 1 : 0)
const pinnedRef = useRef(stickToBottom)
+ const didInitialScrollRef = useRef(false)
const renderRow = useCallback(
(index: number): ReactNode => {
@@ -127,11 +144,34 @@ function Root<T>({
)
const scrollToBottom = useCallback((): void => {
- if (rowCount > 0) {
- listRef.current?.scrollToRow({ index: rowCount - 1, align: 'end' })
+ if (rowCount === 0) {
+ return
+ }
+ listRef.current?.scrollToRow({ index: rowCount - 1, align: 'end' })
+ // `scrollToRow` lands a hair short with dynamic row heights, leaving the last line a few px out of
+ // view; snap to the exact maximum (the browser clamps `scrollTop` to its valid range).
+ const el = listRef.current?.element
+ if (el) {
+ el.scrollTop = el.scrollHeight
}
}, [listRef, rowCount])
+ // Re-assert the bottom only when content has pushed it out of view (streaming growth, measurement
+ // settle, initial open) — so the open scroll converges to the true bottom as rows are measured, while
+ // a user resting at the final position is left alone. Skipping when already there is what stops the
+ // re-issued scroll from cancelling macOS's native overscroll bounce (the "shake"). No element yet (the
+ // first pass before mount) ⇒ scroll unconditionally.
+ const maybeStickToBottom = useCallback((): void => {
+ if (!stickToBottom || !pinnedRef.current) {
+ return
+ }
+ const el = listRef.current?.element
+ if (el && el.scrollHeight - el.scrollTop - el.clientHeight <= AT_BOTTOM_EPSILON) {
+ return
+ }
+ scrollToBottom()
+ }, [stickToBottom, scrollToBottom, listRef])
+
const handleScroll = useCallback(
(event: UIEvent<HTMLDivElement>): void => {
if (!stickToBottom) {
@@ -144,26 +184,51 @@ function Root<T>({
)
const handleRowsRendered = useCallback((): void => {
- // Re-assert while pinned so a growing last row (streaming) keeps the bottom in view.
- if (stickToBottom && pinnedRef.current) {
- scrollToBottom()
- }
- }, [stickToBottom, scrollToBottom])
+ maybeStickToBottom()
+ }, [maybeStickToBottom])
- // Scroll on append / last-item change while pinned — and as dynamic measurements settle. Pinned by
- // default, so this also scrolls to the bottom on open. The first scroll fires before rows are measured
- // (they start at `defaultRowHeight`) and lands short; depending on the measured average row height
- // re-fires it as ResizeObserver grows the rows, so it settles at the true bottom. The same signal keeps
- // a streaming last row pinned as it grows.
+ // Re-pin as content appends/streams and as dynamic measurements settle — gated by `maybeStickToBottom`
+ // so it scrolls only while the bottom is out of view. Pinned by default, so this also scrolls to the
+ // bottom on open: the first pass fires before rows are measured (they start at `defaultRowHeight`) and
+ // lands short, then re-fires as ResizeObserver grows the rows until it settles at the true bottom.
const lastKey = items.length > 0 ? getItemKey(items[items.length - 1], items.length - 1) : null
const measuredAverageHeight = dynamicRowHeight.getAverageRowHeight()
useEffect(() => {
if (!virtualized || !stickToBottom || !pinnedRef.current) {
return
}
- const raf = requestAnimationFrame(scrollToBottom)
+ const raf = requestAnimationFrame(maybeStickToBottom)
+ return () => cancelAnimationFrame(raf)
+ }, [virtualized, stickToBottom, maybeStickToBottom, rowCount, lastKey, measuredAverageHeight])
+
+ // First content (open / hard refresh): drive the scroll to the true bottom across a few frames. The
+ // per-dep effect above fires too few times as the list mounts and rows measure, so a single pass lands
+ // short of the last messages. Re-pin first so a stray load-time scroll event can't leave it unpinned,
+ // then re-issue until actually at the bottom (or the frame budget runs out). Runs once; streaming
+ // growth afterwards is the per-dep effect's job.
+ useEffect(() => {
+ if (!virtualized || !stickToBottom || didInitialScrollRef.current || rowCount === 0) {
+ return
+ }
+ didInitialScrollRef.current = true
+ pinnedRef.current = true
+ let frame = 0
+ let lastHeight = -1
+ let raf = requestAnimationFrame(function settle(): void {
+ scrollToBottom()
+ frame += 1
+ // Each pass snaps to the exact current bottom; keep going while measurements still grow the
+ // content, and stop once the height holds steady (we're at the true bottom) or the budget runs
+ // out. Terminating on height — not distance — is what avoids stopping a few px short before the
+ // rows below the fold have finished measuring.
+ const height = listRef.current?.element?.scrollHeight ?? 0
+ if (height !== lastHeight && frame < MAX_INITIAL_SCROLL_FRAMES) {
+ lastHeight = height
+ raf = requestAnimationFrame(settle)
+ }
+ })
return () => cancelAnimationFrame(raf)
- }, [virtualized, stickToBottom, scrollToBottom, rowCount, lastKey, measuredAverageHeight])
+ }, [virtualized, stickToBottom, rowCount, scrollToBottom, listRef])
// Mobile Safari: the soft keyboard shrinks the visual (not layout) viewport, so a pinned bottom can
// slip behind it. Re-assert on visualViewport changes.
diff --git a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsx b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsx
index 0e5f0959260d..b08b00938f0f 100644
--- a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsx
@@ -29,6 +29,15 @@ jest.mock('lib/components/MonacoDiffEditor', () => ({
),
}))
+// A newly created file renders the single-pane read view, not a diff — stand it in for a marker that
+// echoes the content + path so jsdom never instantiates real Monaco (and never pulls monaco-editor).
+jest.mock('./ReadFileContent', () => ({
+ __esModule: true,
+ ReadFileContent: ({ text, path }: { text: string; path?: string }) => (
+ <div data-attr="read-file" data-text={text} data-path={path} />
+ ),
+}))
+
// Force the lazy-mount gate open so the editor instantiates.
jest.mock('react-intersection-observer', () => ({
useInView: () => ({ ref: () => {}, inView: true }),
@@ -112,7 +121,7 @@ describe('EditDiffRenderer', () => {
expect(screen.getAllByTestId('monaco-diff')).toHaveLength(2)
})
- it('reads "Created a file" with all-added stats and an empty original for a new file (Write)', () => {
+ it('renders a single-pane read view (not a diff) with all-added stats for a new file (Write)', () => {
const message = makeMessage({
resolvedKey: 'Write',
content: [{ type: 'diff', path: 'new.py', oldText: null, newText: 'print(1)\nprint(2)' }],
@@ -121,9 +130,11 @@ describe('EditDiffRenderer', () => {
expect(screen.getByText('Created a file')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button'))
- const editor = screen.getByTestId('monaco-diff')
- expect(editor).toHaveAttribute('data-original', '')
- expect(editor).toHaveAttribute('data-language', 'python')
+ expect(screen.queryByTestId('monaco-diff')).not.toBeInTheDocument()
+ const readView = screen.getByTestId('read-file')
+ expect(readView).toHaveAttribute('data-text', 'print(1)\nprint(2)')
+ expect(readView).toHaveAttribute('data-path', 'new.py')
+ expect(screen.getByText('new.py')).toBeInTheDocument()
expect(screen.getByText('+2')).toBeInTheDocument()
})
diff --git a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx
index 263a5c8af358..3512391442cf 100644
--- a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx
+++ b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx
@@ -8,8 +8,10 @@ import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+import { EditorSkeleton } from './EditorSkeleton'
import { FilePath } from './FilePath'
import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'
+import { ReadFileContent } from './ReadFileContent'
import { ToolActivity } from './ToolActivity'
import { findAllDiffContent, getDiffStats, languageFromPath, type ToolCallDiffContent } from './toolDiffContent'
import type { ToolRendererProps } from './toolRegistry'
@@ -59,6 +61,7 @@ function DiffEditor({ diff, path }: { diff: ToolCallDiffContent; path?: string }
language={languageFromPath(path)}
theme={isDarkModeOn ? 'vs-dark' : 'vs'}
options={DIFF_EDITOR_OPTIONS}
+ loading={<EditorSkeleton />}
/>
) : (
<div className="h-24 rounded border border-border-secondary" />
@@ -78,8 +81,9 @@ function DiffStats({ added, removed }: { added: number; removed: number }): JSX.
/**
* Renderer for Edit / Write / MultiEdit / NotebookEdit. The header reads "Edited a file" / "Created a
- * file" (or "Edited N files"); expanding the card reveals the filename, line stats, and an inline visual
- * diff per file. Without `type: "diff"` content blocks it degrades to the generic card.
+ * file" (or "Edited N files"); expanding the card reveals the filename, line stats, and a per-file view:
+ * a single-pane read-only editor for a newly created file (no "before" to diff against), an inline visual
+ * diff for a real edit. Without `type: "diff"` content blocks it degrades to the generic card.
*/
export function EditDiffRenderer(props: ToolRendererProps): JSX.Element {
const { message, icon, turnComplete, turnCancelled } = props
@@ -104,7 +108,11 @@ export function EditDiffRenderer(props: ToolRendererProps): JSX.Element {
{path && <FilePath path={path} />}
<DiffStats added={stats.added} removed={stats.removed} />
</div>
- <DiffEditor diff={diff} path={path} />
+ {diff.oldText == null ? (
+ <ReadFileContent text={diff.newText ?? ''} path={path} />
+ ) : (
+ <DiffEditor diff={diff} path={path} />
+ )}
</div>
)
})}
diff --git a/products/posthog_ai/frontend/components/tool/EditorSkeleton.tsx b/products/posthog_ai/frontend/components/tool/EditorSkeleton.tsx
new file mode 100644
index 000000000000..c6d9a8661449
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/EditorSkeleton.tsx
@@ -0,0 +1,41 @@
+import { memo } from 'react'
+
+import { LemonSkeleton } from '@posthog/lemon-ui'
+
+interface EditorSkeletonProps {
+ /** Match the editor's computed height so the card keeps its shape when Monaco mounts. */
+ height?: number | string
+ /** Number of code-line rows to render. */
+ lines?: number
+}
+
+const DEFAULT_LINES = 5
+// Cycled, not random, so the placeholder is stable across re-renders during streaming.
+const LINE_WIDTHS = ['w-3/4', 'w-1/2', 'w-5/6', 'w-2/3', 'w-11/12', 'w-1/3']
+
+/**
+ * Editor-shaped loading skeleton for the Monaco-backed tool cards (read view + diff view). A
+ * `LemonSkeleton`-only leaf — no Monaco, no lazy renderers — so it's safe both as a `Suspense`
+ * fallback and inside the always-loaded built-in chunk. Renders a line-number gutter column next to
+ * varied-width code-line bars to read as "content loading" rather than an empty/spinning box.
+ */
+export const EditorSkeleton = memo(function EditorSkeleton({
+ height,
+ lines = DEFAULT_LINES,
+}: EditorSkeletonProps): JSX.Element {
+ return (
+ <div
+ className="flex flex-col gap-1.5 rounded border border-border-secondary px-2 py-1.5 overflow-hidden"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={height !== undefined ? { height } : undefined}
+ aria-hidden
+ >
+ {Array.from({ length: lines }, (_, index) => (
+ <div key={index} className="flex items-center gap-2 h-[18px]">
+ <LemonSkeleton className="h-3 w-4 shrink-0 rounded-sm" />
+ <LemonSkeleton className={`h-3 rounded-sm ${LINE_WIDTHS[index % LINE_WIDTHS.length]}`} />
+ </div>
+ ))}
+ </div>
+ )
+})
diff --git a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx
index 1bd375dce073..576c35b48675 100644
--- a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx
+++ b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx
@@ -1,11 +1,10 @@
-import clsx from 'clsx'
import { memo } from 'react'
import { IconWrench } from '@posthog/icons'
import { ToolActivity } from './ToolActivity'
import { compactInput, formatInput, getContentText, stripCodeFences } from './toolContentUtils'
-import { ToolOutput } from './ToolOutput'
+import { ToolBody, ToolBodySection, ToolOutput } from './ToolOutput'
import type { ToolRendererProps } from './toolRegistry'
/**
@@ -41,14 +40,14 @@ export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer(props
const formattedInput = hasInput ? formatInput(inputForPreview) : ''
const body =
formattedInput || output ? (
- <div className="flex flex-col gap-2 min-w-0">
+ <ToolBody>
{formattedInput && <ToolOutput>{formattedInput}</ToolOutput>}
{output && (
- <div className={clsx('min-w-0', formattedInput && 'border-t border-border-secondary pt-2')}>
+ <ToolBodySection divided={!!formattedInput}>
<ToolOutput>{output}</ToolOutput>
- </div>
+ </ToolBodySection>
)}
- </div>
+ </ToolBody>
) : undefined
return (
diff --git a/products/posthog_ai/frontend/components/tool/ReadFileContent.tsx b/products/posthog_ai/frontend/components/tool/ReadFileContent.tsx
new file mode 100644
index 000000000000..4ef532e7b6e2
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/ReadFileContent.tsx
@@ -0,0 +1,105 @@
+import { useValues } from 'kea'
+import type { editor } from 'monaco-editor'
+import { useEffect, useRef } from 'react'
+import { useInView } from 'react-intersection-observer'
+
+import 'lib/monaco/monacoEnvironment'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+
+import { EditorSkeleton } from './EditorSkeleton'
+import { languageFromPath } from './toolDiffContent'
+
+const LINE_HEIGHT = 18
+const MIN_LINES = 5
+const MAX_LINES = 30
+
+// Module-level so the object identity is stable across renders — monaco calls `updateOptions` whenever
+// this prop changes.
+const READ_EDITOR_OPTIONS: editor.IStandaloneEditorConstructionOptions = {
+ readOnly: true,
+ wordWrap: 'on',
+ fontSize: 12,
+ lineNumbers: 'on',
+ minimap: { enabled: false },
+ overviewRulerLanes: 0,
+ overviewRulerBorder: false,
+ hideCursorInOverviewRuler: true,
+ scrollBeyondLastLine: false,
+ folding: false,
+ glyphMargin: false,
+ renderLineHighlight: 'none',
+ guides: { indentation: false },
+ padding: { top: 4, bottom: 4 },
+ automaticLayout: true,
+ // Don't trap the thread's scroll when the cursor is over the editor.
+ scrollbar: { alwaysConsumeMouseWheel: false, vertical: 'auto', horizontal: 'auto' },
+}
+
+export function ReadFileContent({ text, path }: { text: string; path?: string }): JSX.Element {
+ // Lazy-mount: only instantiate the Monaco editor once the card scrolls near the viewport.
+ const { ref, inView } = useInView({ rootMargin: '500px', triggerOnce: true })
+ // Match the surrounding app theme — without this Monaco falls back to its default `vs` (white) theme.
+ const { isDarkModeOn } = useValues(themeLogic)
+ const lineCount = Math.max(MIN_LINES, Math.min(MAX_LINES, text.split('\n').length))
+ const height = lineCount * LINE_HEIGHT + 8
+
+ const containerRef = useRef<HTMLDivElement>(null)
+ const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null)
+
+ useEffect(() => {
+ if (!inView || !containerRef.current) {
+ return
+ }
+
+ const container = containerRef.current
+ let disposed = false
+
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
+ import('monaco-editor').then((monaco) => {
+ if (disposed || !container) {
+ return
+ }
+ const instance = monaco.editor.create(container, {
+ value: text,
+ language: languageFromPath(path),
+ theme: isDarkModeOn ? 'vs-dark' : 'vs',
+ ...READ_EDITOR_OPTIONS,
+ })
+ editorRef.current = instance
+ })
+
+ return () => {
+ disposed = true
+ editorRef.current?.dispose()
+ editorRef.current = null
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [inView])
+
+ useEffect(() => {
+ const model = editorRef.current?.getModel()
+ if (model) {
+ model.setValue(text)
+ }
+ }, [text])
+
+ useEffect(() => {
+ editorRef.current?.updateOptions({ theme: isDarkModeOn ? 'vs-dark' : 'vs' })
+ }, [isDarkModeOn])
+
+ return (
+ <div ref={ref} className="w-full min-w-0">
+ {inView ? (
+ <div
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ height }}
+ ref={containerRef}
+ className="w-full"
+ />
+ ) : (
+ <EditorSkeleton height={height} />
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/tool/ToolOutput.tsx b/products/posthog_ai/frontend/components/tool/ToolOutput.tsx
index a0f2c4d44352..bb14c094fd42 100644
--- a/products/posthog_ai/frontend/components/tool/ToolOutput.tsx
+++ b/products/posthog_ai/frontend/components/tool/ToolOutput.tsx
@@ -1,3 +1,4 @@
+import clsx from 'clsx'
import type { ReactNode } from 'react'
/** Monospace, scrollable output block for a tool card's collapsible body (terminal/search/fetch). */
@@ -8,3 +9,19 @@ export function ToolOutput({ children }: { children: ReactNode }): JSX.Element {
</pre>
)
}
+
+/** Vertical container stacking a tool card's body sections (input, output) with consistent spacing. */
+export function ToolBody({ children }: { children: ReactNode }): JSX.Element {
+ return <div className="flex flex-col gap-2 min-w-0">{children}</div>
+}
+
+/** A `ToolBody` section; `divided` draws a top border to separate it from the section above it. */
+export function ToolBodySection({
+ divided = false,
+ children,
+}: {
+ divided?: boolean
+ children: ReactNode
+}): JSX.Element {
+ return <div className={clsx('min-w-0', divided && 'border-t border-border-secondary pt-2')}>{children}</div>
+}
diff --git a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx
index 3dde07654e87..5291ff5a7376 100644
--- a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx
+++ b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx
@@ -1,12 +1,11 @@
-import clsx from 'clsx'
-import { memo } from 'react'
+import { Suspense, lazy, memo } from 'react'
-import { IconDocument, IconGlobe, IconSearch, IconTerminal, IconWrench } from '@posthog/icons'
+import { IconDocument, IconGlobe, IconMagicWand, IconSearch, IconTerminal, IconWrench } from '@posthog/icons'
-import { CodeSnippet } from 'lib/components/CodeSnippet/CodeSnippet'
// IconRobot is not exported from @posthog/icons — it lives only in the legacy lib icon set.
import { IconRobot } from 'lib/lemon-ui/icons'
+import { EditorSkeleton } from './EditorSkeleton'
import { FilePath } from './FilePath'
import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'
import { getPostHogExecDisplay } from './posthogExecDisplay'
@@ -14,6 +13,7 @@ import { ToolActivity } from './ToolActivity'
import {
MAX_COMMAND_LENGTH,
MAX_URL_LENGTH,
+ formatInput,
getCommandOutput,
getContentImage,
getContentText,
@@ -25,10 +25,12 @@ import {
stripCodeFences,
truncateText,
} from './toolContentUtils'
-import { languageFromPath } from './toolDiffContent'
-import { ToolOutput } from './ToolOutput'
+import { ToolBody, ToolBodySection, ToolOutput } from './ToolOutput'
import type { ToolRendererProps } from './toolRegistry'
+// Monaco-backed read-only file view, lazy so monaco stays out of the always-loaded built-in chunk.
+const ReadFileContent = lazy(() => import('./ReadFileContent').then((m) => ({ default: m.ReadFileContent })))
+
function asString(value: unknown): string {
return typeof value === 'string' ? value : ''
}
@@ -88,9 +90,9 @@ const ReadToolRenderer = memo(function ReadToolRenderer(props: ToolRendererProps
)
} else if (text) {
body = (
- <CodeSnippet language={languageFromPath(path)} compact maxLinesWithoutExpansion={20}>
- {text}
- </CodeSnippet>
+ <Suspense fallback={<EditorSkeleton />}>
+ <ReadFileContent text={text} path={path} />
+ </Suspense>
)
}
@@ -145,14 +147,14 @@ const SubagentToolRenderer = memo(function SubagentToolRenderer(props: ToolRende
const body =
prompt || showOutput ? (
- <div className="flex flex-col gap-2 min-w-0">
+ <ToolBody>
{prompt && <ToolOutput>{prompt}</ToolOutput>}
{showOutput && (
- <div className={clsx('min-w-0', prompt && 'border-t border-border-secondary pt-2')}>
+ <ToolBodySection divided={!!prompt}>
<ToolOutput>{output}</ToolOutput>
- </div>
+ </ToolBodySection>
)}
- </div>
+ </ToolBody>
) : undefined
return (
@@ -228,6 +230,90 @@ const PostHogExecRenderer = memo(function PostHogExecRenderer(props: ToolRendere
)
})
+/**
+ * Skill — a single line naming the invoked skill. Input and output stay viewable in the body exactly as
+ * the generic card renders them; falls back to the generic card entirely when `skill` isn't a string.
+ */
+const SkillToolRenderer = memo(function SkillToolRenderer(props: ToolRendererProps): JSX.Element {
+ const { message, icon, turnComplete, turnCancelled } = props
+ const skill = asString(message.rawInput.skill)
+ if (!skill) {
+ return <GenericMcpToolRenderer {...props} />
+ }
+
+ const hasInput = Object.keys(message.rawInput).length > 0
+ const formattedInput = hasInput ? formatInput(message.rawInput) : ''
+ const output = stripCodeFences(getContentText(message.content))
+ const body =
+ formattedInput || output ? (
+ <ToolBody>
+ {formattedInput && <ToolOutput>{formattedInput}</ToolOutput>}
+ {output && (
+ <ToolBodySection divided={!!formattedInput}>
+ <ToolOutput>{output}</ToolOutput>
+ </ToolBodySection>
+ )}
+ </ToolBody>
+ ) : undefined
+
+ return (
+ <ToolActivity
+ message={message}
+ icon={icon ?? <IconMagicWand />}
+ title={
+ <span>
+ Skill <span className="font-mono">{skill}</span>
+ </span>
+ }
+ body={body}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ )
+})
+
+/**
+ * ToolSearch — Claude's deferred-tool search, rendered like PostHog's MCP tool search: a "Search tools"
+ * header with the query on the second line and the matched tool schemas in the body. Falls back to the
+ * generic card when the input isn't the expected `{ query, max_results }` shape.
+ */
+const ToolSearchRenderer = memo(function ToolSearchRenderer(props: ToolRendererProps): JSX.Element {
+ const { message, icon, turnComplete, turnCancelled } = props
+ const query = asString(message.rawInput.query)
+ if (!query || typeof message.rawInput.max_results !== 'number') {
+ return <GenericMcpToolRenderer {...props} />
+ }
+ const formattedInput = formatInput(message.rawInput)
+ const output = stripCodeFences(getContentText(message.content))
+ const body =
+ formattedInput || output ? (
+ <ToolBody>
+ {formattedInput && <ToolOutput>{formattedInput}</ToolOutput>}
+ {output && (
+ <ToolBodySection divided={!!formattedInput}>
+ <ToolOutput>{output}</ToolOutput>
+ </ToolBodySection>
+ )}
+ </ToolBody>
+ ) : undefined
+
+ return (
+ <ToolActivity
+ message={message}
+ icon={icon ?? <IconSearch />}
+ title="Search tools"
+ subtitle={
+ <span className="font-mono" title={query}>
+ {truncateText(query, MAX_COMMAND_LENGTH)}
+ </span>
+ }
+ body={body}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ )
+})
+
/**
* Single lazy entry covering every Claude built-in plus the generic MCP fallback — mirrors the agent
* UI's `ToolCallBlock` dispatch. Switches on the resolved tool name; anything unrecognised renders
@@ -256,6 +342,10 @@ export const BuiltinToolRenderer = memo(function BuiltinToolRenderer(props: Tool
case 'WebFetch':
case 'WebSearch':
return <FetchToolRenderer {...props} />
+ case 'Skill':
+ return <SkillToolRenderer {...props} />
+ case 'ToolSearch':
+ return <ToolSearchRenderer {...props} />
default:
return <GenericMcpToolRenderer {...props} />
}
diff --git a/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx b/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx
new file mode 100644
index 000000000000..248f9dc66229
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx
@@ -0,0 +1,162 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
+
+import { PostHogCodeToolRenderer, POSTHOG_CODE_TOOLS_SERVER } from './posthogCodeToolRenderers'
+import { lookupToolRenderer } from './toolRegistry'
+import { resolveToolCall } from './toolResolver'
+
+function textBlock(text: string): unknown {
+ return { type: 'content', content: { type: 'text', text } }
+}
+
+function qualified(tool: string): string {
+ return `mcp__${POSTHOG_CODE_TOOLS_SERVER}__${tool}`
+}
+
+function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage {
+ return {
+ id: 'tc-1',
+ resolvedKey: qualified('git_signed_commit'),
+ rawServerName: 'posthog',
+ rawToolName: '',
+ rawInput: {},
+ content: [],
+ status: 'completed',
+ ...overrides,
+ }
+}
+
+describe('posthog-code tool renderers', () => {
+ afterEach(() => cleanup())
+
+ it('renders each signed commit as a GitHub link to its commit URL', () => {
+ render(
+ <PostHogCodeToolRenderer
+ isLastInGroup
+ message={makeMessage({
+ resolvedKey: qualified('git_signed_commit'),
+ rawInput: { message: 'fix(api): handle null series' },
+ content: [
+ textBlock(
+ 'Created 2 signed commit(s) on posthog-code/foo:\n' +
+ '- a1b2c3d https://github.com/posthog/posthog/commit/a1b2c3dabcdef\n' +
+ '- e4f5a6b https://github.com/posthog/posthog/commit/e4f5a6babcdef'
+ ),
+ ],
+ })}
+ />
+ )
+ expect(screen.getByText('Signed commits · 2 commits')).toBeInTheDocument()
+ expect(screen.getByText('fix(api): handle null series')).toBeInTheDocument()
+ // The commit links live in the collapsed accordion, not always-visible — reveal them first.
+ expect(screen.queryByRole('link', { name: /a1b2c3d/ })).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button'))
+ expect(screen.getByRole('link', { name: /a1b2c3d/ })).toHaveAttribute(
+ 'href',
+ 'https://github.com/posthog/posthog/commit/a1b2c3dabcdef'
+ )
+ expect(screen.getByRole('link', { name: /e4f5a6b/ })).toHaveAttribute(
+ 'href',
+ 'https://github.com/posthog/posthog/commit/e4f5a6babcdef'
+ )
+ })
+
+ it.each([
+ ['git_signed_commit', { message: 'fix: x', branch: 'b' }, 'fix: x'],
+ ['git_signed_merge', { base: 'master', branch: 'feature' }, 'master → feature'],
+ ['git_signed_rewrite', { branch: 'feature' }, 'feature'],
+ ])('derives the %s subtitle from its inputs', (tool, rawInput, expected) => {
+ render(
+ <PostHogCodeToolRenderer isLastInGroup message={makeMessage({ resolvedKey: qualified(tool), rawInput })} />
+ )
+ expect(screen.getByText(expected)).toBeInTheDocument()
+ })
+
+ it('falls back to the raw text when a merge reports nothing to do', () => {
+ render(
+ <PostHogCodeToolRenderer
+ isLastInGroup
+ message={makeMessage({
+ resolvedKey: qualified('git_signed_merge'),
+ rawInput: { base: 'master', branch: 'feature' },
+ content: [textBlock('feature is already up to date with master; nothing to merge.')],
+ })}
+ />
+ )
+ expect(screen.getByText('Signed merge')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button'))
+ expect(screen.getByText(/already up to date/)).toBeInTheDocument()
+ })
+
+ it('lists repositories as links to their GitHub pages', () => {
+ render(
+ <PostHogCodeToolRenderer
+ isLastInGroup
+ message={makeMessage({
+ resolvedKey: qualified('list_repos'),
+ content: [
+ textBlock('posthog/posthog: Product analytics platform\nposthog/posthog-js: JavaScript SDK'),
+ ],
+ })}
+ />
+ )
+ expect(screen.getByText('List repositories · 2')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button'))
+ expect(screen.getByText('Product analytics platform')).toBeInTheDocument()
+ expect(screen.getByRole('link', { name: /posthog-js/ })).toHaveAttribute(
+ 'href',
+ 'https://github.com/posthog/posthog-js'
+ )
+ })
+
+ it('links the cloned repo and shows the target path', () => {
+ render(
+ <PostHogCodeToolRenderer
+ isLastInGroup
+ message={makeMessage({
+ resolvedKey: qualified('clone_repo'),
+ rawInput: { repo: 'posthog/posthog', branch: 'main' },
+ content: [
+ textBlock(
+ 'Cloned posthog/posthog (posthog) to /home/user/repos/posthog/posthog on branch main.'
+ ),
+ ],
+ })}
+ />
+ )
+ expect(screen.getByText('Clone repository')).toBeInTheDocument()
+ expect(screen.getByRole('link', { name: /posthog\/posthog/ })).toHaveAttribute(
+ 'href',
+ 'https://github.com/posthog/posthog'
+ )
+ fireEvent.click(screen.getByRole('button'))
+ expect(screen.getByText(/\/home\/user\/repos\/posthog\/posthog/)).toBeInTheDocument()
+ })
+
+ // The resolver yields the qualified key on the Claude-SDK wire path and the bare key on a native MCP
+ // path; the registry must map both so neither adapter falls through to the generic wrench card.
+ it.each([
+ [
+ 'claude-sdk',
+ {
+ rawServerName: 'posthog',
+ rawToolName: '',
+ input: {},
+ meta: { claudeCode: { toolName: qualified('git_signed_commit') } },
+ },
+ qualified('git_signed_commit'),
+ ],
+ [
+ 'native-mcp',
+ { rawServerName: POSTHOG_CODE_TOOLS_SERVER, rawToolName: 'git_signed_commit', input: {}, meta: undefined },
+ 'git_signed_commit',
+ ],
+ ])('resolves the %s key shape to the signed-commit renderer', (_label, toolCall, expectedKey) => {
+ const resolved = resolveToolCall(toolCall)
+ expect(resolved.resolvedKey).toEqual(expectedKey)
+ expect(lookupToolRenderer(resolved.resolvedKey).displayName).toEqual('Signed commits')
+ })
+})
diff --git a/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.tsx b/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.tsx
new file mode 100644
index 000000000000..b046139df24f
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.tsx
@@ -0,0 +1,215 @@
+import { memo } from 'react'
+
+import { IconCommit, IconGitBranch, IconGithub } from '@posthog/icons'
+
+import { Link } from 'lib/lemon-ui/Link'
+import { pluralize } from 'lib/utils/strings'
+
+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
+
+import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'
+import { ToolActivity } from './ToolActivity'
+import { getContentText, stripCodeFences } from './toolContentUtils'
+import { ToolOutput } from './ToolOutput'
+import type { ToolRendererProps } from './toolRegistry'
+
+/**
+ * Bespoke cards for the `posthog-code-tools` MCP server (the coding agent's git/repo tools). Without
+ * these the calls fall through to the generic MCP card (`Call posthog – mcp__…__git_signed_commit
+ * (MCP)` over raw JSON); here the result text is parsed into clickable GitHub Verified-commit links
+ * and linked repo rows. Registered in `toolRegistry` under both the bare and the `mcp__<server>__`
+ * qualified key, since the resolver yields either depending on the wire adapter.
+ */
+export const POSTHOG_CODE_TOOLS_SERVER = 'posthog-code-tools'
+const QUALIFIED_PREFIX = `mcp__${POSTHOG_CODE_TOOLS_SERVER}__`
+
+type SignedGitTool = 'git_signed_commit' | 'git_signed_merge' | 'git_signed_rewrite'
+
+const SIGNED_GIT_LABELS: Record<SignedGitTool, string> = {
+ git_signed_commit: 'Signed commits',
+ git_signed_merge: 'Signed merge',
+ git_signed_rewrite: 'Signed force-update',
+}
+
+const OWNER_REPO_RE = /^[\w.-]+\/[\w.-]+$/
+// Each commit line of a signed-git result reads `- <sha> <url>`; capture the sha and the GitHub URL.
+const SIGNED_COMMIT_LINE_RE = /^-\s+([0-9a-f]{7,40})\s+(\S+)/gm
+
+interface SignedCommit {
+ sha: string
+ url: string
+}
+
+interface RepoRow {
+ nameWithOwner: string
+ description?: string
+}
+
+/** The bare tool name regardless of which wire adapter produced the frame (qualified or bare). */
+function bareCodeToolName(message: ToolCallMessage): string {
+ const candidate = message.resolvedKey || message.claudeToolName || message.rawToolName || ''
+ return candidate.startsWith(QUALIFIED_PREFIX) ? candidate.slice(QUALIFIED_PREFIX.length) : candidate
+}
+
+/** A non-empty input string, or undefined — keeps optional subtitles out of the card when absent. */
+function inputStr(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() ? value : undefined
+}
+
+function parseSignedCommits(output: string): SignedCommit[] {
+ return Array.from(output.matchAll(SIGNED_COMMIT_LINE_RE), (m) => ({ sha: m[1], url: m[2] }))
+}
+
+function parseRepoRows(output: string): RepoRow[] {
+ const rows: RepoRow[] = []
+ for (const raw of output.split('\n')) {
+ const line = raw.trim()
+ if (!line) {
+ continue
+ }
+ const sep = line.indexOf(': ')
+ const name = sep > 0 ? line.slice(0, sep).trim() : line
+ if (!OWNER_REPO_RE.test(name)) {
+ continue
+ }
+ const description = sep > 0 ? line.slice(sep + 2).trim() : ''
+ rows.push({ nameWithOwner: name, description: description || undefined })
+ }
+ return rows
+}
+
+function CommitList({ commits }: { commits: SignedCommit[] }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1 min-w-0">
+ {commits.map((commit) => (
+ <Link key={commit.sha} to={commit.url} target="_blank" targetBlankIcon className="font-mono text-xs">
+ {commit.sha.slice(0, 7)}
+ </Link>
+ ))}
+ </div>
+ )
+}
+
+function RepoList({ rows }: { rows: RepoRow[] }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1 min-w-0">
+ {rows.map((row) => (
+ <div key={row.nameWithOwner} className="flex items-baseline gap-2 min-w-0 text-xs">
+ <Link
+ to={`https://github.com/${row.nameWithOwner}`}
+ target="_blank"
+ targetBlankIcon
+ className="font-mono shrink-0"
+ >
+ {row.nameWithOwner}
+ </Link>
+ {row.description && <span className="text-muted truncate">{row.description}</span>}
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function SignedGitRenderer({
+ message,
+ icon,
+ turnComplete,
+ turnCancelled,
+ tool,
+}: ToolRendererProps & { tool: SignedGitTool }): JSX.Element {
+ const output = stripCodeFences(getContentText(message.content))
+ const commits = parseSignedCommits(output)
+ const count = commits.length
+ const title = count > 0 ? `${SIGNED_GIT_LABELS[tool]} · ${pluralize(count, 'commit')}` : SIGNED_GIT_LABELS[tool]
+
+ let subtitle: string | undefined
+ if (tool === 'git_signed_commit') {
+ subtitle = inputStr(message.rawInput.message) ?? inputStr(message.rawInput.branch)
+ } else if (tool === 'git_signed_merge') {
+ const base = inputStr(message.rawInput.base)
+ const branch = inputStr(message.rawInput.branch)
+ subtitle = base && branch ? `${base} → ${branch}` : (base ?? branch)
+ } else {
+ subtitle = inputStr(message.rawInput.branch)
+ }
+
+ // Everything beyond the two header lines goes in the collapsible body: the parsed commit links, or
+ // the raw text for idempotent / warning / unparsed responses.
+ return (
+ <ToolActivity
+ message={message}
+ icon={icon ?? (tool === 'git_signed_commit' ? <IconCommit /> : <IconGitBranch />)}
+ title={title}
+ subtitle={subtitle ? <span className="font-mono">{subtitle}</span> : undefined}
+ body={count > 0 ? <CommitList commits={commits} /> : output ? <ToolOutput>{output}</ToolOutput> : undefined}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ )
+}
+
+function CloneRepoRenderer({ message, icon, turnComplete, turnCancelled }: ToolRendererProps): JSX.Element {
+ const output = stripCodeFences(getContentText(message.content))
+ const repo = inputStr(message.rawInput.repo)
+ const branch = inputStr(message.rawInput.branch)
+ const repoHref = repo && OWNER_REPO_RE.test(repo) ? `https://github.com/${repo}` : undefined
+ const subtitle = repo ? (
+ <span className="font-mono">
+ {repoHref ? (
+ <Link to={repoHref} target="_blank" targetBlankIcon>
+ {repo}
+ </Link>
+ ) : (
+ repo
+ )}
+ {branch ? ` · ${branch}` : ''}
+ </span>
+ ) : undefined
+
+ return (
+ <ToolActivity
+ message={message}
+ icon={icon ?? <IconGithub />}
+ title="Clone repository"
+ subtitle={subtitle}
+ body={output ? <ToolOutput>{output}</ToolOutput> : undefined}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ )
+}
+
+function ListReposRenderer({ message, icon, turnComplete, turnCancelled }: ToolRendererProps): JSX.Element {
+ const output = stripCodeFences(getContentText(message.content))
+ const rows = parseRepoRows(output)
+ const filter = inputStr(message.rawInput.query) ?? inputStr(message.rawInput.owner)
+
+ return (
+ <ToolActivity
+ message={message}
+ icon={icon ?? <IconGithub />}
+ title={rows.length > 0 ? `List repositories · ${rows.length}` : 'List repositories'}
+ subtitle={filter ? <span className="font-mono">{filter}</span> : undefined}
+ body={rows.length > 0 ? <RepoList rows={rows} /> : output ? <ToolOutput>{output}</ToolOutput> : undefined}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ )
+}
+
+/** Dispatches a `posthog-code-tools` call to its bespoke card, falling back to the generic MCP card. */
+export const PostHogCodeToolRenderer = memo(function PostHogCodeToolRenderer(props: ToolRendererProps): JSX.Element {
+ const tool = bareCodeToolName(props.message)
+ switch (tool) {
+ case 'git_signed_commit':
+ case 'git_signed_merge':
+ case 'git_signed_rewrite':
+ return <SignedGitRenderer {...props} tool={tool} />
+ case 'clone_repo':
+ return <CloneRepoRenderer {...props} />
+ case 'list_repos':
+ return <ListReposRenderer {...props} />
+ default:
+ return <GenericMcpToolRenderer {...props} />
+ }
+})
diff --git a/products/posthog_ai/frontend/components/tool/toolContentUtils.test.ts b/products/posthog_ai/frontend/components/tool/toolContentUtils.test.ts
index aae22ea7d321..6980ecc8e31d 100644
--- a/products/posthog_ai/frontend/components/tool/toolContentUtils.test.ts
+++ b/products/posthog_ai/frontend/components/tool/toolContentUtils.test.ts
@@ -90,11 +90,16 @@ describe('toolContentUtils', () => {
})
describe('getReadToolContent', () => {
- it('strips system reminders, code fences, and line-number gutters', () => {
+ it('strips system reminders, code fences, and arrow line-number gutters', () => {
const raw =
'```python\n 1→import os\n 2→print(os.getcwd())\n```\n<system-reminder>be careful</system-reminder>'
expect(getReadToolContent([{ type: 'text', text: raw }])).toBe('import os\nprint(os.getcwd())')
})
+
+ it('strips tab-delimited line-number gutters (the Read tool output format)', () => {
+ const raw = '```\n1\t---\n2\ttitle: x\n3\t\n10\tconst a = 1\n```'
+ expect(getReadToolContent([{ type: 'text', text: raw }])).toBe('---\ntitle: x\n\nconst a = 1')
+ })
})
describe('getContentImage', () => {
diff --git a/products/posthog_ai/frontend/components/tool/toolContentUtils.ts b/products/posthog_ai/frontend/components/tool/toolContentUtils.ts
index a6a9e30c8141..008b21ef038f 100644
--- a/products/posthog_ai/frontend/components/tool/toolContentUtils.ts
+++ b/products/posthog_ai/frontend/components/tool/toolContentUtils.ts
@@ -145,12 +145,14 @@ export function stripAnsi(text: string): string {
}
const SYSTEM_REMINDER_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/g
-// `cat -n`-style gutter the Read tool prepends to each line: optional indent, line number, U+2192 arrow.
-const READ_LINE_MARKER_RE = /^\s*\d+→/gm
+// `cat -n`-style gutter the Read tool prepends to each line: optional indent, line number, then either a
+// U+2192 arrow (`NNN→`) or a tab (`NNN⇥`). Anchored per line so only the leading marker is stripped.
+const READ_LINE_MARKER_RE = /^\s*\d+[→\t]/gm
/**
* Cleans the Read tool's output for display: drops injected `<system-reminder>` blocks, the code
- * fences the agent wraps file contents in, and the per-line `NNN→` gutter — leaving the raw file text.
+ * fences the agent wraps file contents in, and the per-line line-number gutter (`NNN→` or tab form) —
+ * leaving the raw file text.
*/
export function getReadToolContent(content: unknown[]): string {
return stripCodeFences(getContentText(content).replace(SYSTEM_REMINDER_RE, ''))
diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
index b10757d56e3d..c4a20c2eb124 100644
--- a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
@@ -2,8 +2,11 @@ import { type ComponentType, type LazyExoticComponent, lazy } from 'react'
import {
IconAI,
+ IconCommit,
IconDocument,
IconEye,
+ IconGitBranch,
+ IconGithub,
IconGlobe,
IconListCheck,
IconMagicWand,
@@ -77,6 +80,9 @@ const BuiltinToolRenderer = lazy(() =>
)
const EditToolRenderer = lazy(() => import('./EditDiffRenderer').then((m) => ({ default: m.EditDiffRenderer })))
const QuestionRenderer = lazy(() => import('../QuestionRenderer').then((m) => ({ default: m.QuestionRenderer })))
+const PostHogCodeToolRenderer = lazy(() =>
+ import('./posthogCodeToolRenderers').then((m) => ({ default: m.PostHogCodeToolRenderer }))
+)
/**
* Single module-level registry of tool-name → renderer entry. All entries are registered at module
@@ -149,6 +155,26 @@ for (const { key, displayName, icon } of POSTHOG_EXEC_VERBS) {
toolRegistry.register({ key, displayName, icon, Renderer: BuiltinToolRenderer })
}
+// posthog-code-tools — the coding agent's git/repo MCP tools. Registered under both the bare name and
+// the `mcp__<server>__` qualified name because `resolveToolKey` yields the qualified form on the
+// Claude-SDK wire path (the name lives in `_meta.claudeCode.toolName`) and the bare form on a native
+// MCP path. Renderers live in their own lazy chunk.
+// Inlined rather than imported from the renderer module so registration stays a string-only side
+// effect — importing it would statically pull the lazy renderer chunk into this one.
+const POSTHOG_CODE_TOOLS_SERVER = 'posthog-code-tools'
+const POSTHOG_CODE_TOOLS: { name: string; displayName: string; icon: JSX.Element }[] = [
+ { name: 'git_signed_commit', displayName: 'Signed commits', icon: <IconCommit /> },
+ { name: 'git_signed_merge', displayName: 'Signed merge', icon: <IconGitBranch /> },
+ { name: 'git_signed_rewrite', displayName: 'Signed force-update', icon: <IconGitBranch /> },
+ { name: 'clone_repo', displayName: 'Clone repository', icon: <IconGithub /> },
+ { name: 'list_repos', displayName: 'List repositories', icon: <IconGithub /> },
+]
+for (const { name, displayName, icon } of POSTHOG_CODE_TOOLS) {
+ for (const key of [name, `mcp__${POSTHOG_CODE_TOOLS_SERVER}__${name}`]) {
+ toolRegistry.register({ key, displayName, icon, Renderer: PostHogCodeToolRenderer })
+ }
+}
+
// AskUserQuestion (the agent asking the user to pick between options) gets a bespoke renderer that
// lays the question + options out like the LangGraph question recap, rather than the generic JSON card.
toolRegistry.register({
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index 85973e55d483..72d9480b4274 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -8,6 +8,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { projectLogic } from 'scenes/projectLogic'
+import { userLogic } from 'scenes/userLogic'
import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'
import type { TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
@@ -686,6 +687,7 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
let statusSeq = 0
let compactSeq = 0
let taskSeq = 0
+ let consoleSeq = 0
const pushHuman = (text: string): void => {
items = insertHumanMessageAtTurnStart(items, {
@@ -944,8 +946,21 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
}
continue
}
+ if (method === '_posthog/console') {
+ const message = typeof params.message === 'string' ? params.message : ''
+ const level = typeof params.level === 'string' ? params.level : 'info'
+ if (message) {
+ items.push({
+ id: `console-${consoleSeq++}`,
+ type: 'debug',
+ text: message,
+ debugLevel: level,
+ })
+ }
+ continue
+ }
if (method?.startsWith('_posthog/')) {
- // run_started, usage_update, resources_used, sdk_session, console, sandbox_output, … — no thread item.
+ // run_started, usage_update, resources_used, sdk_session, sandbox_output, … — no thread item.
continue
}
if (method !== 'session/update') {
@@ -1019,6 +1034,23 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
return { threadItems: items, toolInvocations: invocations }
}
+/**
+ * Whether a folded item renders any content. Empty priming thoughts and step-less progress rows fold
+ * into the thread but render nothing; drop them here so a virtualized consumer never reserves an empty,
+ * gap-padded row. Tool items are always paired with an invocation (see `upsertInvocationItem`), and
+ * `debug` rows are gated separately by `showDebugItems`, so neither needs a content check here.
+ */
+function rendersThreadItemContent(item: ThreadItem): boolean {
+ switch (item.type) {
+ case 'assistant_thought':
+ return !!item.text?.trim()
+ case 'progress':
+ return (item.progressSteps?.length ?? 0) > 0
+ default:
+ return true
+ }
+}
+
/**
* Owns the SSE connection to the products/tasks stream endpoint (a `fetch` reader driven by
* `eventsource-parser`, so a reconnect can resume via a Last-Event-ID header), parses the ACP wire
@@ -1041,7 +1073,16 @@ export const runStreamLogic = kea<runStreamLogicType>([
key((props) => (props.replayOnly ? `replay:${props.streamKey}` : props.streamKey)),
path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'runStreamLogic', key]),
connect(() => ({
- values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags'], preflightLogic, ['preflight']],
+ values: [
+ projectLogic,
+ ['currentProjectId'],
+ featureFlagLogic,
+ ['featureFlags'],
+ preflightLogic,
+ ['preflight', 'isDev'],
+ userLogic,
+ ['user'],
+ ],
})),
actions({
/**
@@ -1425,7 +1466,25 @@ export const runStreamLogic = kea<runStreamLogicType>([
(s) => [s.log, s.isBootstrapResumeRun],
(log, isResumeRun): FoldedThread => foldLogToThread(log.entries, { isResumeRun }),
],
- threadItems: [(s) => [s.foldedThread], (foldedThread): ThreadItem[] => foldedThread.threadItems],
+ /**
+ * Whether `_posthog/console` debug rows should surface in the thread. Derived from the current
+ * user's staff/impersonation flag and dev environment, so debug items are filtered out of
+ * `threadItems` for non-privileged users — never reaching the virtualizer.
+ */
+ showDebugItems: [
+ (s) => [s.user, s.isDev],
+ (user, isDev): boolean => !!user?.is_staff || !!user?.is_impersonated || !!isDev,
+ ],
+ threadItems: [
+ (s) => [s.foldedThread, s.showDebugItems],
+ (foldedThread, showDebugItems): ThreadItem[] =>
+ // Filtering lives here, not in the renderer: a row the renderer would return `null` for
+ // (a content-less item, or a debug row a non-privileged user can't see) still reserves an
+ // empty, gap-padded slot in the virtualized thread. Drop them before they become rows.
+ foldedThread.threadItems.filter(
+ (item: ThreadItem) => (item.type !== 'debug' || showDebugItems) && rendersThreadItemContent(item)
+ ),
+ ],
toolInvocations: [
(s) => [s.foldedThread],
(foldedThread): Map<string, ToolInvocation> => foldedThread.toolInvocations,
diff --git a/products/posthog_ai/frontend/messages/DebugMessage.tsx b/products/posthog_ai/frontend/messages/DebugMessage.tsx
new file mode 100644
index 000000000000..86ce2c9612b4
--- /dev/null
+++ b/products/posthog_ai/frontend/messages/DebugMessage.tsx
@@ -0,0 +1,39 @@
+import { memo } from 'react'
+
+import { IconTerminal } from '@posthog/icons'
+
+import { cn } from 'lib/utils/css-classes'
+
+export interface DebugMessageProps {
+ text: string
+ level: string
+}
+
+const LEVEL_STYLES: Record<string, string> = {
+ error: 'border-l-danger text-danger',
+ warn: 'border-l-warning text-warning',
+ debug: 'border-l-muted',
+ info: 'border-l-muted',
+}
+
+/**
+ * Staff-only inline console line rendered from `_posthog/console` wire frames. Not a chat bubble —
+ * a muted, monospace debug row visually distinct from assistant failures (`AssistantFailureMessage`).
+ */
+export const DebugMessage = memo(function DebugMessage({ text, level }: DebugMessageProps): JSX.Element {
+ const levelStyle = LEVEL_STYLES[level] ?? LEVEL_STYLES.info
+ return (
+ <div
+ className={cn(
+ 'flex items-start gap-1.5 w-full min-w-0 py-1 px-2 text-xs text-muted',
+ 'border-l-2 bg-surface-tertiary/50 font-mono',
+ levelStyle
+ )}
+ data-message-type="debug"
+ data-debug-level={level}
+ >
+ <IconTerminal className="size-3 shrink-0 mt-0.5 opacity-70" />
+ <span className="min-w-0 flex-1 whitespace-pre-wrap [overflow-wrap:anywhere]">{text}</span>
+ </div>
+ )
+})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
index b8fb70baa2c6..8c57baa9326e 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
@@ -189,7 +189,7 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.E
selectedRun && <TaskRunMetadata selectedRun={selectedRun} />
)}
- <LemonDivider className="mb-0 mt-0 lg:mt-4" />
+ <LemonDivider className="mb-0 mt-0 lg:mt-2" />
</header>
<TaskRunLog taskId={taskId} />
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
index 33af5b0f1c91..0f57298af9c0 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
@@ -48,12 +48,10 @@ function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicPro
// `RunSurface.Root` binds `runStreamLogic` keyed by `runId`; `runInteractionLogic` connects to the same
// key, so the composer slot's gating reads the right stream. Don't introduce a diverging `streamKey`.
<RunSurface.Root taskId={logicProps.taskId} runId={logicProps.runId} interaction="live">
- <div className="@container/thread flex flex-col h-full overflow-hidden">
- <div className="flex-1 min-h-0">
- <RunSurface.Thread listClassName="pt-4" rowClassName="pr-4" />
- </div>
- <RunSurface.Resources />
+ <div className="@container/thread flex flex-col h-full -mx-4">
+ <RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />
<RunSurface.Composer>
+ <RunSurface.Resources />
<Composer.Root value={draft} onChange={setDraft} onSubmit={submit} loading={isSubmitting}>
{queuedMessages.length > 0 && (
<Composer.Banner>
@@ -75,7 +73,6 @@ function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicPro
<Composer.Submit data-attr="sandbox-composer-send" />
</Composer.Root>
</RunSurface.Composer>
- <RunSurface.ContextUsage />
</div>
</RunSurface.Root>
)
diff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.ts
index 3a46a6a60db6..3e87cb92671b 100644
--- a/products/posthog_ai/frontend/types/streamTypes.ts
+++ b/products/posthog_ai/frontend/types/streamTypes.ts
@@ -60,6 +60,7 @@ export type ThreadItemType =
| 'compact_boundary'
| 'task_notification'
| 'progress'
+ | 'debug'
/**
* An ordered, append-only entry the renderer consumes. Human messages, text chunks, streamed
@@ -100,6 +101,8 @@ export interface ThreadItem {
progressGroup?: string
/** For `progress` items — ordered setup/runtime progress rows. */
progressSteps?: ProgressStep[]
+ /** For `debug` items — the `_posthog/console` level (debug/info/warn/error). */
+ debugLevel?: string
}
/** One PostHog product the agent grounded an answer in, accumulated across the whole session. */
diff --git a/products/posthog_ai/frontend/types/taskTypes.ts b/products/posthog_ai/frontend/types/taskTypes.ts
index 78ba91464730..75714803dd24 100644
--- a/products/posthog_ai/frontend/types/taskTypes.ts
+++ b/products/posthog_ai/frontend/types/taskTypes.ts
@@ -17,6 +17,8 @@ export enum OriginProduct {
// Tasks kicked off from an Inbox SignalReport (Discuss / Create PR). Backend already
// accepts `signal_report` + `signal_report_task_relationship` for this origin.
SIGNAL_REPORT = 'signal_report',
+ // Runs created by a Signals scout (automated agent) — no interactive context budget to surface.
+ SIGNALS_SCOUT = 'signals_scout',
}
export enum TaskRunStatus {