:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(posthog-ai): butter round two 🧈 flatter groups, calmer failures (#98942)
Jake Ruth0f051b2b18f6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a974e390c2aa..f465daf97709 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5681,17 +5681,17 @@ snapshots:products-posthog-ai-queuedmessagelist--waiting-for-approval--light:hash: v1.k794b7964.84558994ccccfbf6b0479c05e70fa04048ecdb813a76ac4a3e689b3f3d4a3cfd.WdgXqb0eDP9c6glP6UuTXb--spzTGFym3foe4wFyEIgproducts-posthog-ai-runalertactivity--agent-crash--dark:- hash: v1.k794b7964.c24fb9cd17d324218dc3b8708de5c05f112d1c6f65c9ff44f9e74c815608c448.t54VYmu9mZwk2sWYA8TsqLHuS_-087t2Wm7NNl8qGh4+ hash: v1.k794b7964.564c24429f7c7f159a30ac1141bab57edf1a5c2b4664beed27914b0bb045e9b9.ekKvBBwcTcgUDFNqNoufRAs6MjAO_moIm_G0cFYgRekproducts-posthog-ai-runalertactivity--agent-crash--light:- hash: v1.k794b7964.766c3f16a2bbcda2654eee7dfc8027fee38a296a7cde1214a26b7ea1119a6a4d.fUbnuqNgAhx1QsJv2kWwiKWn01dSyMnwNLVao2PTgn0+ hash: v1.k794b7964.84d19d137e5a9e39cd1b0204147c4a889e196aa6dbc9e6ec9116a995f0ea9618.GWEvoY40xN7CWYB55l7y7L6_m2-eEqJUrrtfkhg3vZUproducts-posthog-ai-runalertactivity--agent-error--dark:- hash: v1.k794b7964.571b05f6b216d4a9d5c6fe9780f83e8805b51c1c3ad16e179d991a29f8105976.uk6ksOcZbGYlk7rzeqim-Rw6yigz2drj_T2qXNBOImU+ hash: v1.k794b7964.c52294065f4e85601fc8ad764912713984ae3589ec8c6ce3160e936ee0dee0f5.d4BlnKbBHTLTOEQrloQKwwSGDKvmKk-Rq0MIJ6KT96cproducts-posthog-ai-runalertactivity--agent-error--light:- hash: v1.k794b7964.cfbb0166a1696db3f63e799b1c11849f5e8f0599395e030df294894535351127.lRRmsiNgZZk9HUbjnN1h9j06GqdQKdcJq20xQtjB1Z0+ hash: v1.k794b7964.80f6609069820af2a251601dd7115b8d364ec1d891a37b74209a8d22fba81c5d._2bu60yDLcOZ8SA2_Ycwp5k_sVXZduKpQ4HyTN8Frf8products-posthog-ai-runalertactivity--connection-lost--dark:- hash: v1.k794b7964.31c7fd62daefb54216da5c53779c56e4c440441f72447fdd80a8b99190d35713.WfQlAvkYZKbboDjk-PaqhmaBt67pg8VBxAb7_8EwKOQ+ hash: v1.k794b7964.5b77068e6d403c438c0cabbece087db1a40901f7fa2942cc43d258e7eff9cb90.TpYqYzxt1UUWI4bry-_PtA1pi6I3hvnSSo4Zc_atnFYproducts-posthog-ai-runalertactivity--connection-lost--light:- hash: v1.k794b7964.0bac493951bd2047e08b842ba4476ca3853b5cf2bab2bc586375eca502b36fd8.OmwzOF2ZEibfR1C9Ta07PYWQYuLUu6Firyw6xmtwKYc+ hash: v1.k794b7964.27f84f7d7e83edba111e619a09998ef53ec204085b762cf0ead3f54eec7601c8.jv5IdH_VAMerURE_to4RCI0yn9OoZar4f-5n7Citvxsproducts-posthog-ai-startup-chat--queued-sidebar--dark:hash: v1.k794b7964.b00472829dd4a536ce873322691bcbf252f3079eb37d0614c7fa9baf9e0b3272.DObEcDsp_ZwITHJgw5jyv6_t4h1oDp1U2jI0wTthlWUproducts-posthog-ai-startup-chat--queued-sidebar--light:@@ -5705,25 +5705,25 @@ snapshots:products-posthog-ai-startup-chat--sidebar--light:hash: v1.k794b7964.21eaee49f9429125b726ca537df2609832e2d31297b0e98d8264964866f293cb.u5AJc9X9898pYhh_P0fqkrmxDZRscEkFWYiCq68frv4products-posthog-ai-threadactivitygroup--long-history--dark:- hash: v1.k794b7964.2e3de4c9920447e12ddad04f5ebdbc7aa37d8724ea2c3089f752d5476abb4d3a.8adra9j6VC2g8199P2Y4HNamG7wds2LYoefV0R-MH_s+ hash: v1.k794b7964.8b34d1e1c80e586075052512fbf6342204ac90e7e990b4b0a2216794daffe677.RbS0dZBWhHvm3zRt-7dgogNZVBloP_Oonxbo8qrZIoAproducts-posthog-ai-threadactivitygroup--long-history--light:- hash: v1.k794b7964.e3105b81b2e343041589897879e2432d06c56e822593ef51dba139544ddb10fe.ZdI1ynaQPOp1ZPL2nqFblBw22a1Mci3OE6dRB-C9By0+ hash: v1.k794b7964.0823b6b4581c981e8b383205119e3499dbd00f62a7ef91bc0be464a95211228b.MvadxN9qU9uEG9-d0XsvxHd-8j8gWAIB2JoINRWRywUproducts-posthog-ai-threadactivitygroup--narrow--dark:- hash: v1.k794b7964.eb655a55f31ed378bd406492655a2f06b6bf46d5840de6e6f928f49be7166d60.czOa1Vjr_jJ0GhohYMuQx050uaG4ctHJ85fNYI0ajEo+ hash: v1.k794b7964.9c8549304e088597d1602403e29df5bf7716c7510502458834060ee158f94522.H-6L9FSwY7-huYXKFw_eRBgwy3Z5Az9zPJpCNB8K8RQproducts-posthog-ai-threadactivitygroup--narrow--light:- hash: v1.k794b7964.2d6791a064d53f189ce73912dc95f0e71b3fb748d90f8a6a5b27e52543a00999.8SwVDhcfDi54VdC5eksSXLlkVPtWnQbjY4eFiuE8CHM+ hash: v1.k794b7964.bc2e79c18c09280e16f4be5d2d86e59306e01cd6a6cf1bdf8016d95864a46682.2GzdLPqCQCoLbG4Siz61IQjAse5CwNJB5SjA7WcgXYUproducts-posthog-ai-threadactivitygroup--short-history--dark:- hash: v1.k794b7964.9b7c599d8bc0d014aff92a39d9ea25776fa5b0b1a98844bcd61ed482fb54a662.xwAV8zDAz2Mgxx5QvLNvnzo2tYGjpPOOzqnxswWL3jc+ hash: v1.k794b7964.8cfe49a464553ee778d5ffc1c7f257c177c659934e29c3425211aa6ccfe97acc.HKIUQmrBCURGOR_Ro4DxzDY3q-tWC8eMccYT1Of7nPkproducts-posthog-ai-threadactivitygroup--short-history--light:- hash: v1.k794b7964.1d1fe51d8f925a0609cb6563ef584fca24291cd75ed7a492ed8902b218ef247c.xlMOAY6k05UlEKiNS2B5lEH2RnWszpW1QZU8TBUFavc+ hash: v1.k794b7964.78bbaccaf093acdce8e4ebe0e74fc190a128bb91e680fd9080e2b6fcab2010cc.rOoOEjO8blEtzVngfdXAC3pvUHlPSFh1aZkin--i_K0products-posthog-ai-threadactivitygroup--thought-only--dark:hash: v1.k794b7964.59f9b65f3327467b23b1b60b730af8e31db8a0420b14bbaf090cb90ad49d1ad1.mT7-Bu4Nhyci96u6AToP8iXGMUY_6L7HT29STuJ_tFMproducts-posthog-ai-threadactivitygroup--thought-only--light:hash: v1.k794b7964.f18630672f4cd6196f401bdfc8026668c370e73572820d3bbfa581538ec9a979.2cvSxyjCrolxtd2YehEopd4hKqguy-kajBmB88-qYJUproducts-posthog-ai-threadactivitygroup--unknown-timing--dark:- hash: v1.k794b7964.dd4706709f78c02664f030c478cbb840a011b1ef2c5667a24b69f2da69d080e1.nyWDTetgXbFNe5gbJh_FRvK-1VQ0IzYQ22doIIokQeA+ hash: v1.k794b7964.f8359d3e05c8abc65c36a7ca5ff080e65410c6da2d15695940cc95e40fd5a6ea.xCibKvMipw5rj-d8KQKIhjYcYeaRZso1FyoT7TOrCzYproducts-posthog-ai-threadactivitygroup--unknown-timing--light:- hash: v1.k794b7964.53f358e67f6b451f54117490d453d1a8ac9df23954e600c5136b8460ba176cdd.oPnmThRLe7TWRQMutMewFyRpHGhuYPXaEhUJN0FrWTs+ hash: v1.k794b7964.8ecc0c983e5a8059a44ed0035773dd569f23d5e1d7fd3ce84dc4ccfa1c4b5096.u5hHfwMS2ujB9P787G7wfksMdagcLqYS8MHbBAe3gy0products-posthog-ai-threadview--cold-conversation--dark:hash: v1.k794b7964.f2ea4d6244d77619efdb7bee4249207dcba1e9cb61f2c76046ccdf505b3d094d.3f7mOytsWocBUaj3zrOjwyFwJaXUwfrVoF4jfxhK7_cproducts-posthog-ai-threadview--cold-conversation--light:@@ -8437,13 +8437,13 @@ snapshots:scenes-app-marketing-analytics-cell-actions--source-cell-action-unmapped--light:hash: v1.k794b7964.c15b997111d34fb17ad2dd192b97c01d0a7ab3a320c5edf9a3e20b0b63a4ff9b.UHxcXJdZkFGXRnzIMFWO99QMD_gZm0V47g8f1j4OFS0scenes-app-max-ai-logs-query-tool--no-matches--dark:- hash: v1.k794b7964.223044926f42a8e3a756412aa03a691dd04f5a8d8654db7a325f2260917b9430.UgpMyQFFGVINJikUpS89VD4EG2z7fj76DMrOffodGGI+ hash: v1.k794b7964.c231a64a00f6dfc8bf5b88c3dab624bad88d347b96be0b2e6b0cc14e1c10e1cc.ScE515QePrAYrJB-UWn5sakLt5cKxQKQQrx_n_uJERIscenes-app-max-ai-logs-query-tool--no-matches--light:- hash: v1.k794b7964.3e04c92daba0b5f213ecd35cd4e5a5eb797b24dc69a9e3c3c0bd7b27a4cef9f9.wquRkSMZF2Iud1apiDPYDzUaoxLYDHzpJhwkwU2B3ns+ hash: v1.k794b7964.939b05d460fc5eb2451eb6277dba6730e8c44e2a4789227f5bfa83a2254508bb.XCLVTGHZKGB_40iDFPG1eWGRyGAnXLGLYPP-bSLJg3Ascenes-app-max-ai-logs-query-tool--with-rows--dark:- hash: v1.k794b7964.223044926f42a8e3a756412aa03a691dd04f5a8d8654db7a325f2260917b9430.cKHx53lUFCmAJnbAXBckDzQnwcxJ_hxsH-GgKgR-3Qg+ hash: v1.k794b7964.c231a64a00f6dfc8bf5b88c3dab624bad88d347b96be0b2e6b0cc14e1c10e1cc.BnG67ts5GXjQClduvD-tmwlqTJNG9YQ05Q4Xepns3uEscenes-app-max-ai-logs-query-tool--with-rows--light:- hash: v1.k794b7964.3e04c92daba0b5f213ecd35cd4e5a5eb797b24dc69a9e3c3c0bd7b27a4cef9f9.14ZWrizkHZvyik-SHsQC-lHUDhm-wvlxz25f_9eHfgc+ hash: v1.k794b7964.939b05d460fc5eb2451eb6277dba6730e8c44e2a4789227f5bfa83a2254508bb.MOQGu3hVz0TbCz92R7pPnrPWlRksBoNeTuT80gwSciMscenes-app-max-ai-replay-vision-scan-widget--finished--dark:hash: v1.k794b7964.1223f99370d58d32715cc85f7dcee08b5edf77d9b93095b81474c76eb3138f2f.GJOY2COZjRyTv8DY54QNd7uUJ4H7DxTz-8TdiWq3yc8scenes-app-max-ai-replay-vision-scan-widget--finished--light:diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsxindex 7483cd57c709..501087bb5826 100644--- a/frontend/src/scenes/max/Thread.tsx+++ b/frontend/src/scenes/max/Thread.tsx@@ -75,7 +75,7 @@ import {} from 'products/posthog_ai/frontend/api/logics'import {AssistantFailureMessage,- ContextUsageBar,+ ContextUsageChip,MarkdownMessage,MessageTemplate,ReasoningAnswer,@@ -405,8 +405,8 @@ export function SandboxComposerSurfaces(): JSX.Element | null {logic={runStreamLogic}props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}>- <div className="w-full max-w-180 self-center mx-auto">- <ContextUsageBar />+ <div className="w-full max-w-180 self-center mx-auto flex justify-end">+ <ContextUsageChip /></div></BindLogic>)diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.mdindex 6e9de4f32681..5921789f29bd 100644--- a/products/posthog_ai/frontend/README.md+++ b/products/posthog_ai/frontend/README.md@@ -115,7 +115,7 @@ submit again.(`.Thread/.Composer/.ContextUsage`) compose into any layout — there is no default. Omit`RunSurface.Composer` for a no-input surface (that's exactly what `ReadonlyRunSurface` does); render it withcomposer children for an interactive one. For something even more bespoke, drop to the Tier 2 primitives-(`ThreadView`, `Composer.*`, `ContextUsageBar`) and bind `runStreamLogic` yourself.+(`ThreadView`, `Composer.*`, `ContextUsageChip`) and bind `runStreamLogic` yourself.### Optimistically open a run before it existsdiff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.tsindex e10a28b5ee74..eaa50fcb2ba1 100644--- a/products/posthog_ai/frontend/api/primitives.ts+++ b/products/posthog_ai/frontend/api/primitives.ts@@ -85,7 +85,7 @@ export type { DebugLogsMenuProps } from '../components/DebugLogsMenu'export { PermissionInput } from '../components/PermissionInput'export { QuestionInput } from '../components/QuestionInput'export { parseSandboxQuestions } from '../policy/questionUtils'-export { ContextUsageBar } from '../components/ContextUsageBar'+export { ContextUsageChip } from '../components/ContextUsageChip'export { QuestionField, MultiFieldQuestion, isFieldValid } from '../components/QuestionField'export { OptionSelector } from '../components/OptionSelector'export type { Option } from '../components/OptionSelector'diff --git a/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx b/products/posthog_ai/frontend/components/ActivityElapsedTime.tsxindex 22d5fca3651c..051347b65e4d 100644--- a/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx+++ b/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx@@ -31,8 +31,7 @@ export function ActivityElapsedTime({className="tabular-nums text-muted"title="Elapsed time for this activity group, including tools and waiting, not the whole response.">- · {seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`}{' '}- elapsed+ · {seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`}</span>)}diff --git a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx b/products/posthog_ai/frontend/components/ActivityPrimitives.tsxindex 3fc79c270d13..ddce921e2e35 100644--- a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx+++ b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx@@ -90,7 +90,6 @@ export function ActivityHeader({}): JSX.Element {const isPending = status === 'pending'const isInProgress = status === 'in_progress'- const isFailed = status === 'failed'const titleNode = (<div className="min-w-0 min-h-5 flex items-center">@@ -118,8 +117,8 @@ export function ActivityHeader({// transitions (and full-document style recalcs) whenever the thread is hovered.'group/activity-header transition-colors duration-500 flex items-center gap-2 px-2 min-h-8 select-none min-w-0',isPending && 'text-muted',- isFailed && 'text-danger',- !isInProgress && !isPending && !isFailed && 'text-default',+ // A failed row keeps its title readable; the icon and status word carry the red.+ !isInProgress && !isPending && 'text-default',hasDetails ? 'cursor-pointer' : 'cursor-default',hasDetails && 'rounded hover:bg-fill-button-tertiary-hover',hasDetails && isDetailsExpanded && 'bg-fill-button-tertiary-active'diff --git a/products/posthog_ai/frontend/components/ContextUsageBar.tsx b/products/posthog_ai/frontend/components/ContextUsageBar.tsxdeleted file mode 100644index 0d32bb14333c..000000000000--- a/products/posthog_ai/frontend/components/ContextUsageBar.tsx+++ /dev/null@@ -1,68 +0,0 @@-import { useValues } from 'kea'--import { Tooltip } from '@posthog/lemon-ui'--import { humanFriendlyNumber } from 'lib/utils/numbers'--import { runStreamLogic } from '../logics/runStreamLogic'--/** Compact SVG ring showing the context-window fill percentage. */-function UsageRing({ percentage }: { percentage: number }): JSX.Element {- const radius = 7- const circumference = 2 * Math.PI * radius- const clamped = Math.max(0, Math.min(1, percentage / 100))- return (- <svg viewBox="0 0 18 18" className="size-4 shrink-0 -rotate-90">- <circle cx="9" cy="9" r={radius} fill="none" strokeWidth="2.5" className="stroke-border" />- <circle- cx="9"- cy="9"- r={radius}- fill="none"- strokeWidth="2.5"- strokeLinecap="round"- strokeDasharray={circumference}- strokeDashoffset={circumference * (1 - clamped)}- className="stroke-accent"- />- </svg>- )-}--/**- * Context-usage indicator for sandbox conversations. Reads the latest-wins `contextUsage` snapshot- * and renders a fill ring + `used / size · %` label when the numeric aggregate is present, plus the- * run cost when known. Hidden when there is nothing to show. The breakdown popover is deferred.- */-export function ContextUsageBar(): JSX.Element | null {- const { contextUsage } = useValues(runStreamLogic)-- if (!contextUsage) {- return null- }-- const { used, size, cost } = contextUsage- const hasRing = typeof used === 'number' && typeof size === 'number' && size > 0- const percentage = hasRing ? Math.round((used! / size!) * 100) : null- const hasCost = typeof cost === 'number'-- if (!hasRing && !hasCost) {- return null- }-- return (- <div className="flex items-center gap-2 px-2 text-xs text-muted" data-attr="max-sandbox-context-usage">- {hasRing && (- <Tooltip title="Context window usage">- <span className="flex items-center gap-1.5">- <UsageRing percentage={percentage!} />- <span>- {humanFriendlyNumber(used!)} / {humanFriendlyNumber(size!)} · {percentage}%- </span>- </span>- </Tooltip>- )}- {hasCost && <span>${cost!.toFixed(2)}</span>}- </div>- )-}diff --git a/products/posthog_ai/frontend/components/ContextUsageChip.tsx b/products/posthog_ai/frontend/components/ContextUsageChip.tsxnew file mode 100644index 000000000000..f7b8029e25ef--- /dev/null+++ b/products/posthog_ai/frontend/components/ContextUsageChip.tsx@@ -0,0 +1,45 @@+import { useValues } from 'kea'++import { Tooltip } from '@posthog/lemon-ui'++import { humanFriendlyNumber } from 'lib/utils/numbers'++import { runStreamLogic } from '../logics/runStreamLogic'++/**+ * Context-window fill and run cost as one line of text: "Context 66% · $12.79". The percentage turns+ * to the warning color at 80% and the danger color at 95%; the tooltip carries the exact token counts.+ * Hidden until the run reports usage or cost. Rendered in the runner's composer footer, the Max+ * sandbox panel, and the thread footer of composer-less live embeds.+ */+export function ContextUsageChip(): JSX.Element | null {+ const { contextUsage } = useValues(runStreamLogic)+ const used = contextUsage?.used+ const size = contextUsage?.size+ const hasRing = typeof used === 'number' && typeof size === 'number' && size > 0+ const cost = typeof contextUsage?.cost === 'number' ? contextUsage.cost : null+ if (!hasRing && cost === null) {+ return null+ }+ const percentage = hasRing ? Math.min(100, Math.round((used / size) * 100)) : null+ const tone =+ percentage !== null && percentage >= 95+ ? 'text-danger'+ : percentage !== null && percentage >= 80+ ? 'text-warning'+ : 'text-muted'+ const parts = [+ percentage !== null ? `Context ${percentage}%` : null,+ cost !== null ? `$${cost.toFixed(2)}` : null,+ ].filter(Boolean)+ const label = (+ <span className={`text-xs tabular-nums whitespace-nowrap px-1 ${tone}`} data-attr="max-sandbox-context-usage">+ {parts.join(' · ')}+ </span>+ )+ return hasRing ? (+ <Tooltip title={`${humanFriendlyNumber(used)} of ${humanFriendlyNumber(size)} tokens`}>{label}</Tooltip>+ ) : (+ label+ )+}diff --git a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsxindex 4ea071f87d2c..4c37e3a2cbe2 100644--- a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsx+++ b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsx@@ -24,7 +24,7 @@ jest.mock('../logics/runStreamLogic', () => ({jest.mock('../logics/taskLogic', () => ({ taskLogic: jest.fn(() => ({ __mock: 'taskLogic' })) }))jest.mock('./ThreadView', () => ({ ThreadView: () => <div data-attr="thread" /> }))-jest.mock('./ContextUsageBar', () => ({ ContextUsageBar: () => <div data-attr="context" /> }))+jest.mock('./ContextUsageChip', () => ({ ContextUsageChip: () => <div data-attr="context" /> }))jest.mock('./PermissionInput', () => ({ PermissionInput: () => <div data-attr="permission" /> }))jest.mock('./QuestionInput', () => ({ QuestionInput: () => <div data-attr="question" /> }))jest.mock('./RunLogSkeleton', () => ({ RunLogSkeleton: () => <div data-attr="run-log-skeleton" /> }))diff --git a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsxindex b9d81ebc6d8d..180b257b15da 100644--- a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsx@@ -42,7 +42,11 @@ export default function ReadonlyRunSurfaceImpl({) : (<div className={cn('@container/thread flex flex-col h-full overflow-hidden', className)}><div className="flex-1 min-h-0">- <RunSurface.Thread listClassName={threadListClassName} rowClassName={threadRowClassName} />+ <RunSurface.Thread+ listClassName={threadListClassName}+ rowClassName={threadRowClassName}+ showContextUsage+ /></div></div>)}diff --git a/products/posthog_ai/frontend/components/RunAlertActivity.test.tsx b/products/posthog_ai/frontend/components/RunAlertActivity.test.tsxindex b216fdff9c4b..d30eb8c0ac6c 100644--- a/products/posthog_ai/frontend/components/RunAlertActivity.test.tsx+++ b/products/posthog_ai/frontend/components/RunAlertActivity.test.tsx@@ -16,7 +16,9 @@ describe('RunAlertActivity', () => {it.each([['connection_failed', 'Connection lost'],- ['agent_error', 'Agent error'],+ ['agent_error', 'Run stopped'],+ ['agent_error_continued', 'Agent error'],+ ['message_undelivered', 'Message not delivered'],['agent_crash', 'Agent stopped unexpectedly'],] as const)('renders the %s title with its detail message', (kind, title) => {render(<RunAlertActivity kind={kind} message="boom" />)@@ -24,4 +26,10 @@ describe('RunAlertActivity', () => {expect(screen.getByText(title)).toBeInTheDocument()expect(screen.getByText('boom')).toBeInTheDocument()})++ it('notes the undelivered follow-up on a stopped run', () => {+ render(<RunAlertActivity kind="agent_error" message="boom" undeliveredMessage />)++ expect(screen.getByText('Your last message was not delivered.')).toBeInTheDocument()+ })})diff --git a/products/posthog_ai/frontend/components/RunAlertActivity.tsx b/products/posthog_ai/frontend/components/RunAlertActivity.tsxindex 22b9b3a93020..252159bfd7dc 100644--- a/products/posthog_ai/frontend/components/RunAlertActivity.tsx+++ b/products/posthog_ai/frontend/components/RunAlertActivity.tsx@@ -1,33 +1,48 @@import { IconWarning } from '@posthog/icons'-import { Spinner } from '@posthog/lemon-ui'+import { LemonButton, Spinner } from '@posthog/lemon-ui'++import { copyToClipboard } from 'lib/utils/copyToClipboard'import { MarkdownMessage } from '../messages/MarkdownMessage'import type { RunAlertKind, RunConnectionState } from '../types/streamTypes'import { Activity } from './ActivityPrimitives'interface RunAlertActivityProps extends RunConnectionState {- /** Stable id for the underlying `Activity` (drives markdown substep ids). Defaults per kind. */+ /** Stable id for the markdown message. Defaults per kind. */id?: string+ /** A follow-up message failed to reach the agent because of this error. */+ undeliveredMessage?: boolean+ /** Text for the "Copy details" action: run and task ids, trace id, and the reason. */+ copyDetails?: string}const TITLES: Record<RunAlertKind, string> = {reconnecting: 'Reconnecting to agent',connection_failed: 'Connection lost',- agent_error: 'Agent error',+ agent_error: 'Run stopped',+ agent_error_continued: 'Agent error',agent_crash: 'Agent stopped unexpectedly',+ message_undelivered: 'Message not delivered',}/**- * The single Activity-based card for every run stream/connection alert, used in two places:+ * The card for every run stream/connection alert, used in two places:* - the thread footer (selector-driven, `runStreamLogic.runConnectionState`) for the live `reconnecting`- * banner (attempt counter + backoff) and its terminal `connection_failed` state, and- * - inline in the thread (`ThreadRow`) for genuine agent failures (`agent_error` / `agent_crash`).+ * line (attempt counter + backoff) and its terminal `connection_failed` state, and+ * - inline in the thread (`ThreadRow` via `RunErrorRow`) for a stopped run, a crash, or an undelivered message.*- * It replaces the old inline red `AssistantFailureMessage` bubble for the sandbox runtime. A failed card's- * `Activity` body auto-collapses, so the detail message rides the always-visible `children` region (mirrors- * `ToolActivity`'s failed-error pattern) rather than the collapsible `details`.+ * Reconnecting stays a quiet `Activity` line. Every failed kind is a bordered card with the reason and+ * the actions under one left edge; red is limited to the icon.*/-export function RunAlertActivity({ kind, id, attempt, maxAttempts, message }: RunAlertActivityProps): JSX.Element {+export function RunAlertActivity({+ kind,+ id,+ attempt,+ maxAttempts,+ message,+ undeliveredMessage,+ copyDetails,+}: RunAlertActivityProps): JSX.Element {const activityId = id ?? `run-alert-${kind}`if (kind === 'reconnecting') {@@ -43,20 +58,35 @@ export function RunAlertActivity({ kind, id, attempt, maxAttempts, message }: Ru)}+ // A stopped run gets a bordered card, not a tinted banner: red only on the icon, and the reason and+ // the actions share the title's left edge.return (- <Activity- id={activityId}- title={TITLES[kind]}- status="failed"- icon={<IconWarning className="size-4 text-danger" />}- animate={false}- showCompletionIcon={false}+ <div+ className="max-w-4/5 rounded border border-border-secondary bg-surface-primary px-3 py-2.5 flex flex-col gap-1.5"+ data-attr="run-alert-card">- {message ? (- <div className="text-danger">- <MarkdownMessage content={message} id={`${activityId}-message`} />+ <div className="flex items-center gap-2 font-semibold">+ <IconWarning className="size-4 shrink-0 text-danger" />+ <span>{TITLES[kind]}</span>+ </div>+ <div className="pl-6 flex flex-col gap-1 text-secondary">+ {message ? <MarkdownMessage content={message} id={`${activityId}-message`} /> : null}+ {undeliveredMessage && kind !== 'message_undelivered' ? (+ <div>Your last message was not delivered.</div>+ ) : null}+ </div>+ {copyDetails && (+ <div className="pl-6 flex items-center">+ <LemonButton+ type="tertiary"+ size="xsmall"+ onClick={() => void copyToClipboard(copyDetails, 'run details')}+ data-attr="run-error-copy-details"+ >+ Copy details+ </LemonButton></div>- ) : null}- </Activity>+ )}+ </div>)}diff --git a/products/posthog_ai/frontend/components/RunErrorRow.tsx b/products/posthog_ai/frontend/components/RunErrorRow.tsxnew file mode 100644index 000000000000..02a7933c70a3--- /dev/null+++ b/products/posthog_ai/frontend/components/RunErrorRow.tsx@@ -0,0 +1,41 @@+import { useValues } from 'kea'++import { runStreamLogic } from '../logics/runStreamLogic'+import type { ThreadItem } from '../types/streamTypes'+import { RunAlertActivity } from './RunAlertActivity'++/**+ * An inline run error, with the ids an engineer needs to find the run attached to "Copy details".+ * The closing error reads "Run stopped"; an error the agent recovered from mid-run keeps a softer title.+ */+export function RunErrorRow({ item, isLast }: { item: ThreadItem; isLast: boolean }): JSX.Element {+ const { bootstrappedRunId, bootstrappedTaskId, errorTraceIds } = useValues(runStreamLogic)+ // A replayed error from an earlier run in the chain names that run, not the one being viewed.+ const runId = item.sourceRunId ?? bootstrappedRunId+ const traceId = errorTraceIds.get(item.id)+ const kind =+ item.variant === 'crash'+ ? 'agent_crash'+ : item.variant === 'undelivered'+ ? 'message_undelivered'+ : isLast+ ? 'agent_error'+ : 'agent_error_continued'+ const copyDetails = [+ bootstrappedTaskId ? `Task ${bootstrappedTaskId}` : null,+ runId ? `Run ${runId}` : null,+ traceId ? `Trace ${traceId}` : null,+ item.errorMessage ?? null,+ ]+ .filter(Boolean)+ .join('\n')+ return (+ <RunAlertActivity+ id={item.id}+ kind={kind}+ message={item.errorMessage}+ undeliveredMessage={item.undeliveredMessage}+ copyDetails={copyDetails || undefined}+ />+ )+}diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsxindex 60baca2c6c16..58ecff37614b 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx@@ -27,7 +27,7 @@ jest.mock('../logics/runStreamLogic', () => ({jest.mock('../logics/taskLogic', () => ({ taskLogic: jest.fn(() => ({ __mock: 'taskLogic' })) }))jest.mock('./ThreadView', () => ({ ThreadView: () => <div data-attr="thread" /> }))-jest.mock('./ContextUsageBar', () => ({ ContextUsageBar: () => <div data-attr="context" /> }))+jest.mock('./ContextUsageChip', () => ({ ContextUsageChip: () => <div data-attr="context" /> }))jest.mock('./PermissionInput', () => ({ PermissionInput: () => <div data-attr="permission" /> }))jest.mock('./QuestionInput', () => ({ QuestionInput: () => <div data-attr="question" /> }))jest.mock('./RunLogSkeleton', () => ({ RunLogSkeleton: () => <div data-attr="run-log-skeleton" /> }))diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxindex 675a1dcc69b7..b3955739cc07 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -7,7 +7,7 @@ import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'import { taskLogic } from '../logics/taskLogic'import { isPiTaskRuntime, OriginProduct } from '../types/taskTypes'import { type TurnTrailer } from '../utils/turnTrailers'-import { ContextUsageBar } from './ContextUsageBar'+import { ContextUsageChip } from './ContextUsageChip'import { FeedbackPromptTrailer } from './FeedbackPromptTrailer'import { PermissionInput } from './PermissionInput'import { QuestionInput } from './QuestionInput'@@ -191,7 +191,14 @@ function RunSurfaceThread({className,listClassName,rowClassName,-}: { className?: string; listClassName?: string; rowClassName?: string } = {}): JSX.Element {+ showContextUsage = false,+}: {+ className?: string+ listClassName?: string+ rowClassName?: string+ /** Composer-less live embeds keep the usage line in the thread footer; the runner shows it in its composer. */+ showContextUsage?: boolean+} = {}): JSX.Element {const { interaction, isScout, taskId, streamKey, runId } = useRunSurfaceContext()const { bootstrapLoading, hasThreadItems } = useValues(runStreamLogic)// Feedback identity: always the task, matching `$ai_session_id` on other surfaces.@@ -224,15 +231,16 @@ function RunSurfaceThread({if (showSkeleton) {return <RunLogSkeleton className={className} listClassName={listClassName} rowClassName={rowClassName} />}- // Context usage rides the thread footer for live runs, but never for a- // scout run. An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.- // Turn feedback follows the same gate: only interactive, non-scout surfaces collect ratings.+ // The runner shows context usage in its composer footer (`ContextUsageChip`); a surface with no+ // composer opts back into the thread footer line. Never for a scout run.+ // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.+ // Turn feedback: only interactive, non-scout surfaces collect ratings.return (<ThreadViewclassName={className}listClassName={listClassName}rowClassName={rowClassName}- showContextUsage={interaction === 'live' && !isScout}+ showContextUsage={showContextUsage && interaction === 'live' && !isScout}renderTurnTrailer={collectsFeedback ? renderTurnTrailer : undefined}footerExtra={feedbackPrompt}/>@@ -300,5 +308,5 @@ export const RunSurface = Object.assign(RunSurfaceRoot, {Root: RunSurfaceRoot,Thread: RunSurfaceThread,Composer: RunSurfaceComposer,- ContextUsage: ContextUsageBar,+ ContextUsage: ContextUsageChip,})diff --git a/products/posthog_ai/frontend/components/ThreadActivityGroup.test.tsx b/products/posthog_ai/frontend/components/ThreadActivityGroup.test.tsxindex c6d3dda08b42..dd29a165ba09 100644--- a/products/posthog_ai/frontend/components/ThreadActivityGroup.test.tsx+++ b/products/posthog_ai/frontend/components/ThreadActivityGroup.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'import { ReasoningAnswer } from '../messages/ReasoningAnswer'import type { ToolInvocation } from '../types/streamTypes'@@ -57,7 +57,6 @@ describe('ThreadActivityGroup', () => {)const { rerender } = render(renderGroup(makeGroup(count)))fireEvent.click(screen.getByTestId('thread-activity-toggle'))- fireEvent.click(screen.getAllByTestId('thread-tool-chain').at(-1)!.querySelector('[role="button"]')!)fireEvent.click(screen.getByText(`call-${count - 1}`))expect(screen.getByText(`Details for call-${count - 1}`)).toBeVisible()@@ -79,19 +78,30 @@ describe('ThreadActivityGroup', () => {expect(screen.getByText(`Details for call-${count - 1}`)).toBeVisible()})- it('collapses consecutive tools into a chain while keeping failures and individual calls accessible', () => {+ it.each([+ ['identical calls fold into one chain', () => 'execute-sql', 1, '· 8 calls· 1 failed'],+ [+ 'runs shorter than three stay flat',+ (index: number) => (index % 4 < 2 ? 'execute-sql' : 'query-trends'),+ 0,+ '',+ ],+ ])('%s, but only inside the hidden middle', (_name, toolFor, chainCount, chainText) => {const tools = new Map<string, ToolInvocation>(- ['first', 'second', 'third'].map((id, index) => [- id,- {- toolCallId: id,- rawServerName: 'posthog',- rawToolName: 'exec',- input: { command: 'call execute-sql {}' },- status: index === 1 ? 'failed' : 'completed',- contentBlocks: [],- },- ])+ Array.from({ length: 13 }, (_, index) => {+ const id = `call-${index}`+ return [+ id,+ {+ toolCallId: id,+ rawServerName: 'posthog',+ rawToolName: 'exec',+ input: { command: `call ${toolFor(index)} {}` },+ status: index === 5 ? 'failed' : 'completed',+ contentBlocks: [],+ },+ ]+ }))render(<ThreadActivityGroup@@ -103,17 +113,29 @@ describe('ThreadActivityGroup', () => {toolInvocations={tools}active={false}cancelled={false}- renderItem={(item) => <div>{item.id}</div>}+ renderItem={(item) => <div data-attr="test-activity-row">{item.id}</div>}/>)fireEvent.click(screen.getByTestId('thread-activity-toggle'))- const chain = screen.getByTestId('thread-tool-chain')- expect(chain).toHaveTextContent('SQL query· 3 calls· 1 failed')- expect(screen.queryByText('first')).not.toBeInTheDocument()- fireEvent.click(chain.querySelector('[role="button"]')!)+ expect(screen.getAllByTestId('test-activity-row').map((row) => row.textContent)).toEqual([+ 'call-0',+ 'call-1',+ 'call-10',+ 'call-11',+ 'call-12',+ ])+ expect(screen.queryByTestId('thread-tool-chain')).not.toBeInTheDocument()+ fireEvent.click(screen.getByTestId('thread-activity-more'))+ expect(screen.queryAllByTestId('thread-tool-chain')).toHaveLength(chainCount)+ if (chainCount) {+ const chain = screen.getByTestId('thread-tool-chain')+ expect(chain).toHaveTextContent(`SQL query${chainText}`)+ fireEvent.click(chain.querySelector('[role="button"]')!)+ }for (const id of tools.keys()) {expect(screen.getByText(id)).toBeVisible()}+ expect(screen.getByTestId('thread-activity-more')).toHaveTextContent('Show less')})it('reveals thought-only activity with one click and keeps streamed text readable when a tool arrives', () => {@@ -164,7 +186,7 @@ describe('ThreadActivityGroup', () => {expect(screen.getByTestId('thread-activity-refresh')).toHaveTextContent('Show 1 new activity')})- it('keeps the inspected rows stable while new calls arrive and adds hidden failures without replacing them', async () => {+ it('keeps the inspected rows stable while new calls arrive and reveals every row with one more click', () => {const tools = new Map<string, ToolInvocation>(Array.from({ length: 12 }, (_, index) => {const id = `call-${index}`@@ -209,62 +231,14 @@ describe('ThreadActivityGroup', () => {items: [...group.items, { id: 'call-11', type: 'tool_invocation', toolCallId: 'call-11' }],}rerender(renderGroup(next))- expect(screen.getByTestId('thread-activity-toggle')).toHaveTextContent('2 tool calls failed')+ expect(screen.getByTestId('thread-activity-toggle')).not.toHaveTextContent('failed')expect(screen.getByText('call-10: failed')).toBeInTheDocument()expect(screen.queryByText('call-11: in_progress')).not.toBeInTheDocument()fireEvent.click(screen.getByTestId('thread-activity-refresh'))expect(screen.getByText('call-11: in_progress')).toBeInTheDocument()- fireEvent.click(screen.getByTestId('thread-activity-failures'))- expect(screen.getAllByTestId('test-activity-row')).toHaveLength(6)- expect(screen.getByText('call-5: failed')).toBeInTheDocument()- expect(screen.getByText('call-10: failed')).toBeInTheDocument()- expect(screen.getByText('call-11: in_progress')).toBeInTheDocument()- fireEvent.click(screen.getByTestId('thread-activity-failures'))- await waitFor(() => expect(screen.queryByText('call-5: failed')).not.toBeInTheDocument())- expect(screen.getAllByTestId('test-activity-row')).toHaveLength(5)- })-- it('pages additional failures without changing the ordinary activity page or duplicating visible calls', () => {- const tools = new Map<string, ToolInvocation>(- Array.from({ length: 300 }, (_, index) => {- const id = `failure-${index}`- return [- id,- {- toolCallId: id,- rawServerName: 'example',- rawToolName: index % 2 === 0 ? 'read' : 'search',- input: {},- status: 'failed',- contentBlocks: [],- },- ]- })- )- const group: ActivityGroup = {- id: 'failures',- type: 'activity_group',- items: [...tools.keys()].map((id) => ({ id, type: 'tool_invocation', toolCallId: id })),- }- render(- <ThreadActivityGroup- group={group}- toolInvocations={tools}- active={false}- cancelled={false}- renderItem={(item) => <div data-attr="test-activity-row">{item.id}</div>}- />- )- fireEvent.click(screen.getByTestId('thread-activity-toggle'))fireEvent.click(screen.getByTestId('thread-activity-more'))- fireEvent.click(screen.getByTestId('thread-activity-next'))- const originalRows = screen.getAllByTestId('test-activity-row').map((row) => row.textContent)- fireEvent.click(screen.getByTestId('thread-activity-failures'))- expect(screen.getAllByTestId('test-activity-row')).toHaveLength(25)- fireEvent.click(screen.getByTestId('thread-activity-failures-next'))- const rows = screen.getAllByTestId('test-activity-row').map((row) => row.textContent)- expect(new Set(rows).size).toBe(25)- originalRows.forEach((text) => expect(rows).toContain(text))- expect(screen.getByText('Page 2 of 30')).toBeInTheDocument()+ expect(screen.getAllByTestId('test-activity-row').map((row) => row.textContent)).toEqual(+ [...tools.keys()].map((id) => `${id}: ${tools.get(id)?.status}`)+ )})})diff --git a/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx b/products/posthog_ai/frontend/components/ThreadActivityGroup.tsxindex ab890e18f389..7f5e1d7c0519 100644--- a/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx+++ b/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx@@ -6,6 +6,7 @@ import { LemonButton } from '@posthog/lemon-ui'import { MarkdownMessage } from '../messages/MarkdownMessage'import type { ThreadItem, ToolInvocation } from '../types/streamTypes'import {+ ACTIVITY_CHAIN_MIN,activityWindow,groupConsecutiveTools,type ThreadActivityGroup as ActivityGroup,@@ -36,10 +37,7 @@ export function ThreadActivityGroup({const isFollowing = VirtualizedThread.useIsFollowing()const [expanded, setExpanded] = useState(false)const [visibleIds, setVisibleIds] = useState<string[]>([])- const [middlePage, setMiddlePage] = useState(0)const [showMiddle, setShowMiddle] = useState(false)- const [showFailures, setShowFailures] = useState(false)- const [failurePage, setFailurePage] = useState(0)useEffect(() => {if (expanded && isFollowing) {setVisibleIds((previous) =>@@ -53,7 +51,6 @@ export function ThreadActivityGroup({const call = item.toolCallId ? toolInvocations.get(item.toolCallId) : undefinedreturn call ? [call] : []})- const failures = calls.filter((call) => call.status === 'failed')const thoughtsOnly = group.items.every((item) => item.type === 'assistant_thought')const activeLabel = thoughtsOnly ? 'Thinking' : 'Working'const finishedLabel = thoughtsOnly ? 'Thought' : 'Worked'@@ -69,21 +66,7 @@ export function ThreadActivityGroup({const visible = new Set(visibleIds)const snapshot = isFollowing ? group.items : group.items.filter((item) => visible.has(item.id))const visibleThoughtsOnly = snapshot.every((item) => item.type === 'assistant_thought')- const chainKeys = new Map(- groupConsecutiveTools(group.items, toolInvocations).flatMap((chain) =>- chain.map((item) => [item.id, chain[0].id] as const)- )- )- const window = activityWindow(snapshot, middlePage)- const displayedIds = new Set(- [...window.first, ...(showMiddle ? window.middle : []), ...window.last].map((item) => item.id)- )- const additionalFailures = snapshot.filter(- (item) =>- !displayedIds.has(item.id) && item.toolCallId && toolInvocations.get(item.toolCallId)?.status === 'failed'- )- const failurePageCount = Math.ceil(additionalFailures.length / 10)- const currentFailurePage = Math.max(0, Math.min(failurePage, failurePageCount - 1))+ const window = activityWindow(snapshot, showMiddle)const newCount = isFollowing ? 0 : group.items.filter((item) => !visible.has(item.id)).lengthconst toggle = (): void => {if (!expanded) {@@ -91,7 +74,7 @@ export function ThreadActivityGroup({}setExpanded(!expanded)}- const individualRows = (items: ThreadItem[]): ReactNode =>+ const individualRows = (items: ThreadItem[]): ReactNode[] =>items.map((item) => (<Fragment key={item.id}>{visibleThoughtsOnly ? (@@ -103,10 +86,12 @@ export function ThreadActivityGroup({)}</Fragment>))- const rows = (items: ThreadItem[]): ReactNode =>- groupConsecutiveTools(items, toolInvocations).map((chain) => {- if (chain.length === 1) {- return <Fragment key={chain[0].id}>{individualRows(chain)}</Fragment>+ // The first and last rows stay flat so a reader never opens two accordions to reach one call.+ // Flat rows keep their own item keys, so a row's expanded state survives when the window shifts.+ const rows = (items: ThreadItem[], fold: boolean): ReactNode =>+ groupConsecutiveTools(items, toolInvocations).flatMap((chain) => {+ if (!fold || chain.length < ACTIVITY_CHAIN_MIN) {+ return individualRows(chain)}const chainCalls = chain.map((item) => toolInvocations.get(item.toolCallId!)!)const resolved = resolveToolCall(chainCalls[0])@@ -115,7 +100,7 @@ export function ThreadActivityGroup({const running =active && chainCalls.some((call) => call.status === 'pending' || call.status === 'in_progress')return (- <div key={chainKeys.get(chain[0].id)} data-attr="thread-tool-chain">+ <div key={chain[0].id} data-attr="thread-tool-chain"><Activityid={`chain-${chain[0].id}`}title={@@ -177,11 +162,6 @@ export function ThreadActivityGroup({tool {calls.length === 1 ? 'call' : 'calls'}</span>)}- {failures.length > 0 && (- <span className="text-danger">- · {failures.length} tool {failures.length === 1 ? 'call' : 'calls'} failed- </span>- )}</span></LemonButton>{active && (!thoughtsOnly || waitingForInput) && (@@ -191,73 +171,7 @@ export function ThreadActivityGroup({)}<ActivityDisclosure open={expanded} id={`activity-details-${group.id}`}><div className="ml-3 pl-3 border-l border-border-secondary flex flex-col gap-1 min-w-0">- {(additionalFailures.length > 0 || showFailures) && (- <LemonButton- type="tertiary"- size="xsmall"- status="danger"- data-attr="thread-activity-failures"- aria-expanded={showFailures}- aria-controls={`activity-failures-${group.id}`}- onClick={() => {- pauseFollowing()- setShowFailures(!showFailures)- }}- >- {showFailures- ? 'Hide additional failed calls'- : `Show ${additionalFailures.length} hidden failed ${additionalFailures.length === 1 ? 'call' : 'calls'}`}- </LemonButton>- )}- <ActivityDisclosure open={showFailures} id={`activity-failures-${group.id}`}>- <div- className="flex flex-col gap-1 pb-2 border-b border-border-secondary"- data-attr="thread-activity-additional-failures"- >- {additionalFailures.length === 0 && (- <span className="text-muted">All failed calls are visible in the activity below.</span>- )}- {failurePageCount > 1 && (- <div className="flex items-center gap-2 flex-wrap text-muted">- <LemonButton- size="xsmall"- type="tertiary"- data-attr="thread-activity-failures-previous"- disabledReason={currentFailurePage === 0 ? 'First page' : undefined}- onClick={() => {- pauseFollowing()- setFailurePage(currentFailurePage - 1)- }}- >- Previous- </LemonButton>- <span>- Failed calls {currentFailurePage * 10 + 1}–- {Math.min((currentFailurePage + 1) * 10, additionalFailures.length)} of{' '}- {additionalFailures.length}- </span>- <LemonButton- size="xsmall"- type="tertiary"- data-attr="thread-activity-failures-next"- disabledReason={- currentFailurePage + 1 === failurePageCount ? 'Last page' : undefined- }- onClick={() => {- pauseFollowing()- setFailurePage(currentFailurePage + 1)- }}- >- Next- </LemonButton>- </div>- )}- {individualRows(- additionalFailures.slice(currentFailurePage * 10, (currentFailurePage + 1) * 10)- )}- </div>- </ActivityDisclosure>- {rows(window.first)}+ {rows(window.first, false)}{window.hiddenCount > 0 && (<><LemonButton@@ -271,47 +185,14 @@ export function ThreadActivityGroup({setShowMiddle(!showMiddle)}}>- {showMiddle ? 'Hide middle activity' : `Show ${window.hiddenCount} more`}+ {showMiddle ? 'Show less' : `Show ${window.hiddenCount} more`}</LemonButton><ActivityDisclosure open={showMiddle} id={`activity-middle-${group.id}`}>- <div className="flex flex-col gap-1 min-w-0">- <div className="flex items-center gap-2 flex-wrap text-muted">- <LemonButton- size="xsmall"- type="tertiary"- disabledReason={window.page === 0 ? 'First page' : undefined}- onClick={() => {- pauseFollowing()- setMiddlePage(window.page - 1)- }}- data-attr="thread-activity-previous"- >- Previous- </LemonButton>- <span>- Page {window.page + 1} of {window.pageCount}- </span>- <LemonButton- size="xsmall"- type="tertiary"- disabledReason={- window.page + 1 === window.pageCount ? 'Last page' : undefined- }- onClick={() => {- pauseFollowing()- setMiddlePage(window.page + 1)- }}- data-attr="thread-activity-next"- >- Next- </LemonButton>- </div>- {rows(window.middle)}- </div>+ <div className="flex flex-col gap-1 min-w-0">{rows(window.middle, true)}</div></ActivityDisclosure></>)}- {rows(window.last)}+ {rows(window.last, false)}{newCount > 0 && (<LemonButtontype="tertiary"diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsxindex 4ed97bea4f35..9aa63a1e65b1 100644--- a/products/posthog_ai/frontend/components/ThreadRow.tsx+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx@@ -14,7 +14,7 @@ import { ReasoningAnswer } from '../messages/ReasoningAnswer'import type { ProgressStep, ThreadItem } from '../types/streamTypes'import { resolveToolCall } from '../utils/toolResolver'import { Activity } from './ActivityPrimitives'-import { RunAlertActivity } from './RunAlertActivity'+import { RunErrorRow } from './RunErrorRow'import { CompactBoundaryItem, ConversationClearedItem, StatusItem, TaskNotificationItem } from './ThreadItems'import { ToolCallCard } from './tool/ToolCallCard'@@ -101,6 +101,8 @@ export interface ThreadRowProps {toolInvocations: ToolInvocationsturnComplete: booleanturnCancelled: boolean+ /** The current run reached a terminal status; only then is the last error the run's ending. */+ runEnded?: boolean}/**@@ -114,6 +116,7 @@ export const ThreadRow = memo(function ThreadRow({toolInvocations,turnComplete,turnCancelled,+ runEnded = true,}: ThreadRowProps): JSX.Element | null {if (item.type === 'human_message') {return (@@ -148,13 +151,7 @@ export const ThreadRow = memo(function ThreadRow({return <ToolCallCard message={message} turnComplete={turnComplete} turnCancelled={turnCancelled} />}if (item.type === 'error') {- return (- <RunAlertActivity- id={item.id}- kind={item.variant === 'crash' ? 'agent_crash' : 'agent_error'}- message={item.errorMessage}- />- )+ return <RunErrorRow item={item} isLast={isLast && runEnded} />}if (item.type === 'status') {return <StatusItem item={item} />diff --git a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsxindex 476d948d3244..afcc0f2bf590 100644--- a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx@@ -60,7 +60,7 @@ describe('ThreadView connection state', () => {})})- // A folded _posthog/error frame renders inline through ThreadRow's RunAlertActivity swap (agent_error kind).+ // A folded _posthog/error frame renders inline as an error card; the run is still live here, so it keeps the softer title.it('renders an inline agent-error card for a _posthog/error frame', async () => {logic.actions.ingestAcpFrame(notification('_posthog/error', { message: 'boom' }), 'replay')@@ -98,7 +98,7 @@ describe('ThreadView connection state', () => {act(() => logic.actions.rollbackOptimisticResume())await waitFor(() => expect(screen.getByTestId('max-sandbox-context-usage')).toBeVisible())- expect(screen.getByText('$0.04')).toBeVisible()+ expect(screen.getByTestId('max-sandbox-context-usage')).toHaveTextContent('Context 1% · $0.04')})it('uses the startup activity as the state indicator and keeps completed steps expandable', async () => {diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsxindex 4b48ceca1f59..5df751ed5745 100644--- a/products/posthog_ai/frontend/components/ThreadView.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.tsx@@ -3,14 +3,14 @@ import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } fromimport { inStorybookTestRunner } from 'lib/utils/dom'-import { runStreamLogic } from '../logics/runStreamLogic'+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 { getRandomThinkingMessage } from '../utils/thinkingMessages'import { resolveToolCall } from '../utils/toolResolver'import { type TurnTrailer, computeTurnTrailers } from '../utils/turnTrailers'-import { ContextUsageBar } from './ContextUsageBar'+import { ContextUsageChip } from './ContextUsageChip'import { PullRequestCard } from './PullRequestCard'import { RunAlertActivity } from './RunAlertActivity'import { RunContext } from './RunContext'@@ -108,6 +108,9 @@ export function ThreadView({pendingPermissionRequest,} = useValues(runStreamLogic)const turnCancelled = currentRunStatus === 'cancelled'+ // A replayed error from an earlier run in the chain is not this run's ending while a newer run is+ // still going, so it keeps the softer title.+ const runEnded = isTerminalRunStatus(currentRunStatus)const displayItems = useMemo(() => {const standaloneToolIds = new Set<string>()for (const [id, invocation] of toolInvocations) {@@ -157,7 +160,7 @@ export function ThreadView({// 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.+ // working, where the thinking line takes the footer. `ContextUsageChip` self-hides without data.const showContextUsageFooter = showContextUsage && streamPhase === 'idle' && !!contextUsageconst footer = useMemo(() =>@@ -229,6 +232,7 @@ export function ThreadView({toolInvocations={toolInvocations}turnComplete={turnComplete}turnCancelled={turnCancelled}+ runEnded={runEnded}/></VirtualizedThread.Row>)@@ -244,6 +248,7 @@ export function ThreadView({turnTrailers,pendingPermissionRequest,currentRunStatus,+ runEnded,])@@ -322,7 +327,7 @@ const ThreadFooter = memo(function ThreadFooter({/>)}{pullRequestUrl && <PullRequestCard prUrl={pullRequestUrl} branch={prBranch} />}- {showContextUsage && <ContextUsageBar />}+ {showContextUsage && <ContextUsageChip />}{extra}</div>)diff --git a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsxindex 95f6a074bc9d..97ae9cc00e2a 100644--- a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx+++ b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx@@ -1,4 +1,4 @@-import { memo } from 'react'+import { memo, type ReactNode } from 'react'import { IconWrench } from '@posthog/icons'@@ -7,8 +7,20 @@ import { formatInput, getContentText, stripCodeFences } from './toolContentUtilsimport { ToolBody, ToolBodySection, ToolOutput } from './ToolOutput'import type { ToolRendererProps } from './toolRegistry'+// ACP tool-call kinds, used as the row label when a harness sends no title and no tool name.+const KIND_LABELS: Record<string, string> = {+ read: 'Read',+ edit: 'Edit',+ delete: 'Delete',+ move: 'Move',+ search: 'Search',+ execute: 'Run command',+ think: 'Think',+ fetch: 'Web search',+}+export interface McpToolPresentation {- title: string+ title: ReactNode/** Collapsible input/output accordion body. */body: JSX.Element | undefined}@@ -35,17 +47,27 @@ export function getMcpToolPresentation(stripCodeFences(getContentText(message.content)) ||(message.rawOutput !== undefined ? formatInput(message.rawOutput) : '')- // Plain neutral title text, matching the built-in tool cards (e.g. "Read N lines"). A single text- // node is also one flex item, so the header's `inline-flex` wrapper keeps the spaces intact.- const title = isPostHogExec+ const titleText = isPostHogExec? `Call ${toolLabel}`: isMcp? `Call ${serverName} – ${toolLabel} (MCP)`- : message.title || displayName || toolLabel+ : message.title || displayName || toolLabel || (message.kind && KIND_LABELS[message.kind]) || ''+ // The PostHog MCP asks the agent for a one-sentence `context` on every call. It is the only+ // harness-independent description of intent, so it reads better in the row than the command.+ const context = typeof message.rawInput.context === 'string' ? message.rawInput.context.trim() : ''+ const title = (+ <>+ <span className={message.kind === 'execute' ? 'font-mono text-xs' : undefined}>{titleText}</span>+ {context && <span className="text-muted font-normal"> · {context}</span>}+ </>+ )const formattedInput = hasInput ? formatInput(inputForPreview) : ''+ // Some harnesses put a shell command only in `title`, which the row truncates.+ const command = !hasInput && !isMcp && message.kind === 'execute' ? message.title || '' : ''+ const outputText = output || (message.status === 'failed' ? 'No output captured' : '')const body =- formattedInput || output ? (+ formattedInput || command || outputText ? (<ToolBody>{formattedInput && (<ToolBodySection>@@ -53,10 +75,16 @@ export function getMcpToolPresentation(<ToolOutput>{formattedInput}</ToolOutput></ToolBodySection>)}- {output && (- <ToolBodySection divided={!!formattedInput}>+ {command && (+ <ToolBodySection>+ <div className="text-muted mb-1">Command</div>+ <ToolOutput>{command}</ToolOutput>+ </ToolBodySection>+ )}+ {outputText && (+ <ToolBodySection divided={!!formattedInput || !!command}><div className="text-muted mb-1">Output</div>- <ToolOutput>{output}</ToolOutput>+ <ToolOutput>{outputText}</ToolOutput></ToolBodySection>)}</ToolBody>diff --git a/products/posthog_ai/frontend/components/tool/ToolActivity.tsx b/products/posthog_ai/frontend/components/tool/ToolActivity.tsxindex 3182a7088a25..f90a1bf070d6 100644--- a/products/posthog_ai/frontend/components/tool/ToolActivity.tsx+++ b/products/posthog_ai/frontend/components/tool/ToolActivity.tsx@@ -45,6 +45,18 @@ export function ToolActivity({const pauseFollowing = VirtualizedThread.usePauseFollowing()const { isLoading, isFailed, wasCancelled } = resolveToolCallStatus(message.status, !!turnCancelled, !!turnComplete)const status: ActivityStatus = isFailed ? 'failed' : isLoading ? 'in_progress' : 'completed'+ // A finished call is the common case, so it carries no label; only exceptions get a word.+ const statusLabel = isFailed+ ? 'Failed'+ : wasCancelled+ ? 'Canceled'+ : isLoading+ ? message.status === 'pending'+ ? 'Pending'+ : 'Running'+ : message.status === 'completed'+ ? null+ : 'Incomplete'// Failures remain readable without opening the raw input/output.const errorLine =@@ -64,19 +76,11 @@ export function ToolActivity({title={<span className="flex items-center gap-2 min-w-0"><span className="truncate">{title}</span>- <span className="text-muted shrink-0 font-normal">- {isFailed- ? 'Failed'- : wasCancelled- ? 'Canceled'- : isLoading- ? message.status === 'pending'- ? 'Pending'- : 'Running'- : message.status === 'completed'- ? 'Completed'- : 'Incomplete'}- </span>+ {statusLabel && (+ <span className={`${isFailed ? 'text-danger' : 'text-muted'} shrink-0 font-normal`}>+ {statusLabel}+ </span>+ )}</span>}status={status}diff --git a/products/posthog_ai/frontend/components/tool/ToolOutput.tsx b/products/posthog_ai/frontend/components/tool/ToolOutput.tsxindex 96c81d69e711..f8a03878f3b4 100644--- a/products/posthog_ai/frontend/components/tool/ToolOutput.tsx+++ b/products/posthog_ai/frontend/components/tool/ToolOutput.tsx@@ -1,6 +1,7 @@import clsx from 'clsx'import { type ReactNode, useEffect, useRef } from 'react'+import { IconCopy, IconExternal } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import { copyToClipboard } from 'lib/utils/copyToClipboard'@@ -24,28 +25,28 @@ export function ToolOutput({ children }: { children: ReactNode }): JSX.Element {{truncated ? '\n…' : ''}</pre>{text !== undefined && (- <div className="flex gap-2 flex-wrap">+ <div className="flex gap-1"><LemonButtontype="tertiary"size="xsmall"+ icon={<IconCopy />}+ tooltip="Copy"data-attr="tool-output-copy"onClick={() => void copyToClipboard(text, 'tool text')}- >- Copy {truncated ? 'full text' : 'text'}- </LemonButton>+ />{truncated && (<LemonButtontype="tertiary"size="xsmall"+ icon={<IconExternal />}+ tooltip="Open full text in a new tab"data-attr="tool-output-open"onClick={() => {const url = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }))urls.current.push(url)window.open(url, '_blank', 'noopener,noreferrer')}}- >- Open full text in new tab- </LemonButton>+ />)}</div>)}diff --git a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsxindex 3b8e98da3fbe..efc75f897e22 100644--- a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx+++ b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx@@ -268,4 +268,57 @@ describe('builtin tool renderers', () => {expect(screen.getByText('Call read-data-schema')).toBeInTheDocument()expect(screen.queryByText(/\(MCP\)/)).not.toBeInTheDocument()})++ it('opens a failed shell call that carried no input or output to its full command and a placeholder', () => {+ const command = '/bin/bash -lc "echo \'== hogvm package ==\'; rg -n name common/hogvm/package.json"'+ render(+ <GenericMcpToolRenderer+ isLastInGroup+ message={makeMessage({+ resolvedKey: '',+ rawServerName: 'posthog',+ kind: 'execute',+ title: command,+ status: 'failed',+ })}+ />+ )+ expect(screen.getByText('Failed')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button'))+ expect(screen.getAllByText(command)).toHaveLength(2)+ expect(screen.getByText('No output captured')).toBeInTheDocument()+ })++ it('shows the exec context sentence next to the tool name', () => {+ render(+ <GenericMcpToolRenderer+ isLastInGroup+ message={makeMessage({+ resolvedKey: 'execute-sql',+ rawServerName: 'posthog',+ rawToolName: 'exec',+ innerToolName: 'execute-sql',+ rawInput: { command: 'call execute-sql {}', context: "Count yesterday's pageviews." },+ })}+ />+ )+ expect(screen.getByText('Call execute-sql')).toBeInTheDocument()+ expect(screen.getByText("· Count yesterday's pageviews.")).toBeInTheDocument()+ expect(screen.queryByText('Completed')).not.toBeInTheDocument()+ })++ it('labels a title-less call by its ACP kind', () => {+ render(+ <GenericMcpToolRenderer+ isLastInGroup+ message={makeMessage({+ resolvedKey: '',+ rawServerName: 'posthog',+ kind: 'fetch',+ status: 'in_progress',+ })}+ />+ )+ expect(screen.getByText('Web search')).toBeInTheDocument()+ })})diff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.tsindex b6d0d351f29b..4409d63d2e17 100644--- a/products/posthog_ai/frontend/e2e/run-surface.spec.ts+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts@@ -46,7 +46,7 @@ function agentMessageFrame(messageId: string, text: string): AcpFrame {}// A persisted `_posthog/error` frame — the synthetic backend/agent error the run log carries; `foldLogToThread`-// folds it into an inline error card titled "Agent error".+// folds it into an inline error card titled "Run stopped".function posthogErrorFrame(message: string): AcpFrame {return { type: 'notification', notification: { method: '_posthog/error', params: { message } } }}@@ -200,7 +200,7 @@ test.describe('Task run surface', () => {})test('terminal replay surfaces the agent error inline', async ({ page }) => {- // Regression: a terminal run's persisted `_posthog/error` frame must fold into the inline "Agent error"+ // Regression: a terminal run's persisted `_posthog/error` frame must fold into the inline "Run stopped"// card on replay — not be dropped, and not depend on a live SSE (a terminal run never opens one).await routeTasksApi(page, {runStatus: 'completed',@@ -216,7 +216,7 @@ test.describe('Task run surface', () => {await openRunDeepLink(page, workspace!.team_id)- await expect(page.getByText('Agent error')).toBeVisible({ timeout: 20000 })+ await expect(page.getByText('Run stopped')).toBeVisible({ timeout: 20000 })})test('refresh restores the startup queue as a draft without sending it when the agent becomes ready', async ({@@ -580,7 +580,7 @@ test.describe('Task run surface', () => {await expect(page.getByText('Continue with the next step.', { exact: true })).toHaveCount(1)await expect(page.getByText('Setting up sandbox', { exact: false })).toBeVisible()await expect(composer).toHaveValue('')- await expect(page.getByTestId('max-sandbox-context-usage')).toHaveCount(0)+ await expect(page.getByTestId('max-sandbox-context-usage')).toBeVisible()await expect(page.getByTestId('sandbox-composer-send')).toBeDisabled()await expect(page.getByTestId('run-log-skeleton')).toHaveCount(0)@@ -588,7 +588,7 @@ test.describe('Task run surface', () => {acceptRun()await expect(page.getByTestId('sandbox-composer-send')).toBeEnabled()await expect(composer).toHaveValue('Keep this newer draft.')- await expect(page.getByTestId('max-sandbox-context-usage')).toHaveCount(0)+ await expect(page.getByTestId('max-sandbox-context-usage')).toBeVisible()await expect(page.getByText('The earlier answer stays here.', { exact: true })).toBeVisible()await expect(page.getByText('Continue with the next step.', { exact: true })).toHaveCount(1)await expect(page.getByText('Setting up sandbox', { exact: false })).toBeVisible()diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex 3e8d41ace861..7f24eb3124f4 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -2963,6 +2963,115 @@ describe('runStreamLogic', () => {})describe('_posthog/progress handling', () => {+ it('folds a failed follow-up delivery into the preceding error card', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('session/update', {+ update: {+ sessionUpdate: 'error',+ errorType: 'agent_error',+ message: 'The agent stopped before completing this request: Model at capacity.',+ },+ })+ )+ logic.actions.ingestAcpFrame(notification('_posthog/error', { message: 'Model at capacity.' }))+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ step: 'followup_delivery',+ status: 'failed',+ label: "Couldn't deliver your message",+ group: 'followup-delivery:m1',+ detail: 'send_followup failed: Model at capacity.',+ })+ )+ })+ expect(logic.values.threadItems).toEqual([+ {+ id: 'error-0',+ type: 'error',+ errorMessage: 'Model at capacity.',+ variant: 'error',+ undeliveredMessage: true,+ },+ ])+ })++ it('folds an earlier undelivered follow-up into the error that arrives after it', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ step: 'followup_delivery',+ status: 'failed',+ label: "Couldn't deliver your message",+ group: 'followup-delivery:m3',+ detail: 'send_followup failed: Internal error: bad model',+ })+ )+ logic.actions.ingestAcpFrame(+ notification('session/update', {+ update: { sessionUpdate: 'agent_message', content: { type: 'text', text: 'bad model' } },+ })+ )+ logic.actions.ingestAcpFrame(+ notification('session/update', {+ update: {+ sessionUpdate: 'error',+ errorType: 'agent_error',+ message: 'Internal error: bad model',+ },+ })+ )+ })+ expect(logic.values.threadItems.filter((item) => item.type === 'error')).toEqual([+ {+ id: 'error-1',+ type: 'error',+ errorMessage: 'Internal error: bad model',+ variant: 'error',+ undeliveredMessage: true,+ },+ ])+ })++ it('gives an error the trace id of the turn that completes after it, and none when no turn completes', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', { traceId: 'trace-earlier' }))+ logic.actions.ingestAcpFrame(notification('_posthog/error', { message: 'mid-run' }))+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', { traceId: 'trace-of-error' }))+ logic.actions.ingestAcpFrame(+ notification('session/update', {+ update: { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'again' } },+ })+ )+ logic.actions.ingestAcpFrame(notification('_posthog/error', { message: 'stopped' }))+ })+ const errors = logic.values.threadItems.filter((item) => item.type === 'error')+ expect(errors.map((item) => logic.values.errorTraceIds.get(item.id))).toEqual(['trace-of-error', undefined])+ })++ it('turns a failed follow-up delivery on a run without an error into its own card', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ step: 'followup_delivery',+ status: 'failed',+ label: "Couldn't deliver your message",+ group: 'followup-delivery:m2',+ detail: 'There is an issue with the selected model.',+ })+ )+ })+ expect(logic.values.threadItems).toEqual([+ {+ id: 'error-0',+ type: 'error',+ errorMessage: 'There is an issue with the selected model.',+ variant: 'undelivered',+ undeliveredMessage: true,+ },+ ])+ })+it('renders the emitter label as current progress and stores a progress thread item', async () => {await expectLogic(logic, () => {logic.actions.ingestAcpFrame(diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex f20c9d4154ee..6f54295b0fd1 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -1304,6 +1304,35 @@ export function foldLogToThread(}}+ // Two frames often describe one failure with the same text; keep the shorter, cleaner one.+ const pushError = (message: string, variant: 'error' | 'crash', sourceRunId?: string): void => {+ const last = items[items.length - 1]+ if (last?.type === 'error' && last.errorMessage && variant === 'error' && last.variant !== 'crash') {+ const a = last.errorMessage.trim()+ const b = message.trim()+ if (a.includes(b) || b.includes(a)) {+ items[items.length - 1] = { ...last, errorMessage: a.length <= b.length ? a : b }+ return+ }+ }+ // A follow-up that failed to deliver earlier in this turn was a symptom of this error, so the+ // undelivered card folds into the real one instead of standing next to it.+ const turnStart = items.findLastIndex((item) => item.type === 'human_message')+ const undeliveredIdx = items.findIndex(+ (item, index) => index > turnStart && item.type === 'error' && item.variant === 'undelivered'+ )+ if (undeliveredIdx !== -1) {+ items.splice(undeliveredIdx, 1)+ }+ items.push({+ id: `error-${errorSeq++}`,+ type: 'error',+ errorMessage: message,+ variant,+ ...(undeliveredIdx !== -1 ? { undeliveredMessage: true } : {}),+ ...(sourceRunId ? { sourceRunId } : {}),+ })+ }for (const { entry, source } of entries) {entryRunId = entry.source_run_id ?? options.pendingMessage?.runIdif (@@ -1337,12 +1366,11 @@ export function foldLogToThread(continue}if (method === '_posthog/error') {- items.push({- id: `error-${errorSeq++}`,- type: 'error',- errorMessage: String(params.message ?? notification.error?.message ?? 'Agent error'),- variant: 'error',- })+ pushError(+ String(params.message ?? notification.error?.message ?? 'Agent error'),+ 'error',+ entry.source_run_id+ )continue}if (method === '_posthog/turn_complete') {@@ -1359,6 +1387,25 @@ export function foldLogToThread(const group = stringifyOptional(params.group)const step = stringifyOptional(params.step)const label = stringifyOptional(params.label)+ if (step === 'followup_delivery' && normalizeProgressStatus(params.status) === 'failed') {+ // The undelivered follow-up is a consequence of the run's error, so it rides the error+ // card instead of a second failed row. Without a preceding error it becomes the card.+ items = items.filter((item) => !(item.type === 'progress' && item.progressGroup === group))+ const last = items[items.length - 1]+ if (last?.type === 'error' && last.variant !== 'crash') {+ items[items.length - 1] = { ...last, undeliveredMessage: true }+ } else {+ items.push({+ id: `error-${errorSeq++}`,+ type: 'error',+ errorMessage: stringifyOptional(params.detail) ?? label ?? 'Message not delivered',+ variant: 'undelivered',+ undeliveredMessage: true,+ ...(entry.source_run_id ? { sourceRunId: entry.source_run_id } : {}),+ })+ }+ continue+ }if (group && step && label) {const detail = stringifyOptional(params.detail)const nextStep: ProgressStep = {@@ -1486,6 +1533,16 @@ export function foldLogToThread(}continue}+ if (sessionUpdate === 'error') {+ // The Claude adapter reports a stopped run only through this frame; Codex sends it and a+ // `_posthog/error` with the same text, which `pushError` folds into one card.+ pushError(+ String(update.message ?? 'The agent stopped before completing this request.'),+ 'error',+ entry.source_run_id+ )+ continue+ }const content = update.content as { text?: string } | undefinedswitch (sessionUpdate) {case 'agent_message_chunk':@@ -1576,6 +1633,7 @@ export interface runStreamLogicValues {currentProgress: string | nullcurrentRunStatus: RunStatus | nullcurrentStage: string | null+ errorTraceIds: Map<string, string>foldedThread: FoldedThreadhasGitArtifacts: booleanhasThreadItems: boolean@@ -1853,6 +1911,7 @@ export interface runStreamLogicMeta {isBootstrapResumeRun: boolean,pendingRunMessage: PendingRunMessage | null) => FoldedThread+ errorTraceIds: (threadItems: ThreadItem[]) => Map<string, string>latestTurnTraceId: (threadItems: ThreadItem[]) => string | nullthreadItems: (foldedThread: FoldedThread, showDebugLogs: boolean) => ThreadItem[]hasThreadItems: (threadItems: ThreadItem[]) => boolean@@ -2459,6 +2518,32 @@ export const runStreamLogic = kea<runStreamLogicType>([(log: RunLog, isResumeRun: boolean, pendingMessage: PendingRunMessage | null): FoldedThread =>foldLogToThread(log.entries, { isResumeRun, pendingMessage }),],+ errorTraceIds: [+ (s) => [s.threadItems],+ (threadItems: ThreadItem[]): Map<string, string> => {+ // An error belongs to the turn that completes after it. A turn that never completes+ // (a failed follow-up, a run that stopped) has no trace id, so the error gets none.+ const result = new Map<string, string>()+ threadItems.forEach((item, index) => {+ if (item.type !== 'error') {+ return+ }+ for (let j = index + 1; j < threadItems.length; j++) {+ const later = threadItems[j]+ if (later.type === 'human_message') {+ break+ }+ if (later.type === 'turn_separator') {+ if (later.traceId) {+ result.set(item.id, later.traceId)+ }+ break+ }+ }+ })+ return result+ },+ ],latestTurnTraceId: [(s) => [s.threadItems],(threadItems: ThreadItem[]): string | null => {diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsxindex 58d24ef6a221..6845edb7fbd8 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx@@ -19,6 +19,7 @@ import { ComposerModelEffortPickers } from '../../../components/composer/Composeimport { ComposerModePicker } from '../../../components/composer/ComposerModePicker'import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'+import { ContextUsageChip } from '../../../components/ContextUsageChip'export function TaskRunComposer({logicProps,@@ -165,6 +166,9 @@ export function TaskRunComposer({}/></fieldset>+ <div className="ml-auto">+ <ContextUsageChip />+ </div></Composer.Footer></Composer.Frame><AIConsentPopoverWrapperdiff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.tsindex dab7b9872f29..eee3ce2c3eb4 100644--- a/products/posthog_ai/frontend/types/streamTypes.ts+++ b/products/posthog_ai/frontend/types/streamTypes.ts@@ -24,7 +24,13 @@ export interface ProgressStep {* banner (attempt counter + backoff); `connection_failed` is its terminal state (retries exhausted or a* non-retryable open); `agent_error` / `agent_crash` are genuine agent-emitted failures rendered inline.*/-export type RunAlertKind = 'reconnecting' | 'connection_failed' | 'agent_error' | 'agent_crash'+export type RunAlertKind =+ | 'reconnecting'+ | 'connection_failed'+ | 'agent_error'+ | 'agent_error_continued'+ | 'agent_crash'+ | 'message_undelivered'/*** View-model for the live connection banner, derived by `runStreamLogic.runConnectionState` and consumed@@ -150,7 +156,11 @@ export interface ThreadItem {* For `error` items — distinguishes a friendlier agent-crash affordance (`crash`) from a* raw error line (`error`, the default). Drives the copy/styling branch in the renderer.*/- variant?: 'error' | 'crash'+ variant?: 'error' | 'crash' | 'undelivered'+ /** For `error` items — a follow-up message failed to reach the agent because of this error. */+ undeliveredMessage?: boolean+ /** For `error` items — the run in the resume chain whose frame produced this error. */+ sourceRunId?: string/** For `status` and `task_notification` items — the wire `status` string. */status?: string/** For `status` items — whether the status phase has completed. */diff --git a/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts b/products/posthog_ai/frontend/utils/groupThreadActivity.test.tsindex 0620af34085c..72325a43ff56 100644--- a/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts+++ b/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts@@ -85,17 +85,13 @@ describe('thread activity grouping', () => {expect(groups.flat()).toEqual(items)})- it.each([0, 1, 10, 11, 300])('makes every item reachable in bounded pages for %i activities', (count) => {+ it.each([0, 1, 10, 11, 300])('shows every one of %i activities with at most one click', (count) => {const items = Array.from({ length: count }, (_, i) => i)- const collapsed = activityWindow(items, null)+ const collapsed = activityWindow(items, false)expect(collapsed.first.length + collapsed.last.length).toBeLessThanOrEqual(10)- const seen = [...collapsed.first]- for (let page = 0; page < collapsed.pageCount; page++) {- const window = activityWindow(items, page)- expect(window.first.length + window.middle.length + window.last.length).toBeLessThanOrEqual(15)- seen.push(...window.middle)- }- seen.push(...collapsed.last)- expect(seen).toEqual(items)+ expect(collapsed.middle).toEqual([])+ expect(collapsed.hiddenCount).toBe(count > 10 ? count - 5 : 0)+ const open = activityWindow(items, true)+ expect([...open.first, ...open.middle, ...open.last]).toEqual(items)})})diff --git a/products/posthog_ai/frontend/utils/groupThreadActivity.ts b/products/posthog_ai/frontend/utils/groupThreadActivity.tsindex 50cca9671813..684f86c19cc2 100644--- a/products/posthog_ai/frontend/utils/groupThreadActivity.ts+++ b/products/posthog_ai/frontend/utils/groupThreadActivity.ts@@ -68,29 +68,22 @@ export function groupThreadActivity(items: ThreadItem[], standaloneToolIds: Readreturn 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. */+export const ACTIVITY_CHAIN_MIN = 3+export function activityWindow<T>(items: T[],- middlePage: number | null-): {- first: T[]- middle: T[]- last: T[]- hiddenCount: number- pageCount: number- page: number-} {- const hiddenCount = items.length > 10 ? items.length - 5 : 0- const pageCount = Math.ceil(hiddenCount / 10)- const page = Math.max(0, Math.min(middlePage ?? 0, pageCount - 1))+ showMiddle: boolean+): { first: T[]; middle: T[]; last: T[]; hiddenCount: number } {+ if (items.length <= ACTIVITY_WINDOW_LIMIT) {+ return { first: items, middle: [], last: [], hiddenCount: 0 }+ }return {- first: hiddenCount ? items.slice(0, 2) : items,- middle:- hiddenCount && middlePage !== null- ? items.slice(2 + page * 10, Math.min(2 + (page + 1) * 10, items.length - 3))- : [],- last: hiddenCount ? items.slice(-3) : [],- hiddenCount,- pageCount,- page,+ first: items.slice(0, 2),+ middle: showMiddle ? items.slice(2, -3) : [],+ last: items.slice(-3),+ hiddenCount: items.length - 5,}}