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(max): toggle between new posthog_ai surface and legacy chat (#67148)

Georgiy Tarasov959c881d6618
diff --git a/frontend/src/scenes/max/Context.tsx b/frontend/src/scenes/max/Context.tsx
index 91e03838f5a5..5e0bd6008a92 100644
--- a/frontend/src/scenes/max/Context.tsx
+++ b/frontend/src/scenes/max/Context.tsx
@@ -10,7 +10,6 @@ import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopov
import { IconAction, IconEvent } from 'lib/lemon-ui/icons'
import { ModeSelector } from './components/ModeSelector'
-import { SandboxModeToggle } from './components/SandboxModeToggle'
import { maxContextLogic } from './maxContextLogic'
import { maxThreadLogic } from './maxThreadLogic'
import {
@@ -385,7 +384,6 @@ export function ContextDisplay({ size = 'default' }: ContextDisplayProps): JSX.E
<div className="px-2 w-full">
<div className="flex flex-wrap items-start gap-1 w-full">
<ModeSelector />
- <SandboxModeToggle />
<Tooltip title={contextDisabledReason ?? 'Add context to help PostHog AI answer your question'}>
{/* Wrapper span prevents Base UI's Tooltip.Trigger from merging
props into TaxonomicPopover. Without it, mergeProps treats
diff --git a/frontend/src/scenes/max/Max.tsx b/frontend/src/scenes/max/Max.tsx
index fdf8de99472a..e5ab672a53da 100644
--- a/frontend/src/scenes/max/Max.tsx
+++ b/frontend/src/scenes/max/Max.tsx
@@ -27,9 +27,13 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { SidePanelTab } from '~/types'
+import { runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'
+
import { AiFirstMaxInstance } from './components/AiFirstMaxInstance'
import { AnimatedBackButton } from './components/AnimatedBackButton'
import { MaxNotConfigured } from './components/MaxNotConfigured'
+import { MAX_SIDE_PANEL_ID, PhaiSidePanelChat } from './components/PhaiSidePanelChat'
+import { PhaiViewToggle } from './components/PhaiViewToggle'
import { SidebarQuestionInput } from './components/SidebarQuestionInput'
import { SidebarQuestionInputWithSuggestions } from './components/SidebarQuestionInputWithSuggestions'
import { ThreadAutoScroller } from './components/ThreadAutoScroller'
@@ -96,7 +100,12 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:
} = useValues(maxLogic(logicProps))
const { startNewConversation, goBack } = useActions(maxLogic(logicProps))
const { openSidePanelMax } = useActions(maxGlobalLogic)
- const { isMaxAvailable } = useValues(maxGlobalLogic)
+ const { isMaxAvailable, effectivePhaiView } = useValues(maxGlobalLogic)
+ // The new posthog_ai view's back button walks its own panel view state (run -> history -> composer)
+ // rather than legacy Max's conversation stack — mounting this tiny headless logic in legacy view is
+ // harmless (unconditional hooks).
+ const { canGoBack: panelCanGoBack } = useValues(runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }))
+ const { goBack: panelGoBack } = useActions(runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }))
const threadProps: MaxThreadLogicProps = {
...logicProps,
@@ -106,12 +115,18 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:
const { closeSidePanel } = useActions(sidePanelLogic)
+ const isNewView = effectivePhaiView === 'new'
+ const headerBackDisabled = isNewView ? !panelCanGoBack : backButtonDisabled
+
const content = !isMaxAvailable ? (
<MaxNotConfigured />
) : (
<BindLogic logic={maxLogic} props={logicProps}>
<BindLogic logic={maxThreadLogic} props={threadProps}>
- {conversationHistoryVisible ? (
+ {effectivePhaiView === 'new' ? (
+ // Side panel only shows the new composer + thread viewer — the tasks list lives on /ai.
+ <PhaiSidePanelChat />
+ ) : conversationHistoryVisible ? (
<ConversationHistory sidePanel={sidePanel} />
) : !threadVisible ? (
// pb-7 below is intentionally specific - it's chosen so that the bottom-most chat's title
@@ -160,13 +175,13 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:
<SidePanelPaneHeader className="transition-all duration-200" showCloseButton={false}>
<div className="flex flex-1 min-w-0 overflow-hidden">
<div className="flex items-center flex-1 min-w-0">
- <AnimatedBackButton in={!backButtonDisabled}>
+ <AnimatedBackButton in={isNewView ? panelCanGoBack : !backButtonDisabled}>
<ButtonPrimitive
iconOnly
- onClick={() => goBack()}
+ onClick={() => (isNewView ? panelGoBack() : goBack())}
tooltip="Go back"
tooltipPlacement="bottom-end"
- disabledReasons={backButtonDisabled ? { 'You are already at home': true } : undefined}
+ disabledReasons={headerBackDisabled ? { 'You are already at home': true } : undefined}
>
<IconChevronLeft className="text-tertiary size-3 group-hover:text-primary z-10" />
</ButtonPrimitive>
@@ -201,6 +216,7 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:
<IconShare className="text-tertiary size-3 group-hover:text-primary z-10" />
</ButtonPrimitive>
)}
+ <PhaiViewToggle variant="primitive" />
<Link
buttonProps={{
iconOnly: true,
diff --git a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
index f5731ba126d6..41d67cc21167 100644
--- a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
+++ b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
@@ -10,12 +10,15 @@ import { urls } from 'scenes/urls'
import { SceneName } from '~/layout/scenes/components/SceneTitleSection'
+import { EmbeddedRunner } from 'products/posthog_ai/frontend/api/runner'
+
import { Intro } from '../Intro'
import { maxGlobalLogic } from '../maxGlobalLogic'
import { maxLogic } from '../maxLogic'
import { MaxThreadLogicProps, maxThreadLogic } from '../maxThreadLogic'
import { Thread } from '../Thread'
import { MaxNotConfigured } from './MaxNotConfigured'
+import { PhaiViewToggle } from './PhaiViewToggle'
import { SidebarQuestionInputWithSuggestions } from './SidebarQuestionInputWithSuggestions'
import { ThreadAutoScroller } from './ThreadAutoScroller'
@@ -53,6 +56,7 @@ export function ChatHeader({
)}
</div>
<div className="flex items-center gap-2">
+ <PhaiViewToggle variant="lemon" />
{conversationId ? (
<LemonButton
size="small"
@@ -92,7 +96,22 @@ interface AiFirstMaxInstanceProps {
export function AiFirstMaxInstance({ tabId }: AiFirstMaxInstanceProps): JSX.Element {
const { threadVisible, threadLogicKey, conversation, conversationId } = useValues(maxLogic({ panelId: tabId }))
const { startNewConversation } = useActions(maxLogic({ panelId: tabId }))
- const { isMaxAvailable } = useValues(maxGlobalLogic)
+ const { isMaxAvailable, effectivePhaiView } = useValues(maxGlobalLogic)
+
+ // On `/ai` the new view is the full TaskTracker product (tasks list + composer + run detail); a thin
+ // bar keeps the toggle reachable so the user can drop back to the legacy chat.
+ if (effectivePhaiView === 'new') {
+ return (
+ <div className="flex flex-col grow overflow-hidden h-full">
+ <div className="flex w-full items-center justify-end gap-2 py-2 px-2 border-b border-primary">
+ <PhaiViewToggle variant="lemon" />
+ </div>
+ <div className="flex flex-col flex-1 min-h-0">
+ <EmbeddedRunner />
+ </div>
+ </div>
+ )
+ }
const threadProps: MaxThreadLogicProps = {
panelId: tabId,
diff --git a/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx b/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx
new file mode 100644
index 000000000000..2c6537e3b685
--- /dev/null
+++ b/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx
@@ -0,0 +1,20 @@
+import { SidePanelRunner } from 'products/posthog_ai/frontend/api/runner'
+
+// The client-side key for the embedded `taskTrackerSceneLogic` (and paired `runnerPanelLogic`) instance
+// this panel binds — stable so the panel keeps the same in-flight run across re-renders of its host.
+export const MAX_SIDE_PANEL_ID = 'max-side-panel'
+
+/**
+ * The new posthog_ai side-panel experience: task-based, built on the `products/posthog_ai/frontend` runner
+ * surface (composer -> pending thread -> live run) rather than Max's conversation logics
+ * (`maxThreadLogic`/`askMax`/the conversations API). The legacy conversation chat remains behind the
+ * `effectivePhaiView` toggle (see `maxGlobalLogic`). `scenes/max` hosts this only until the Max scene is
+ * replaced outright by the posthog_ai product surface.
+ */
+export function PhaiSidePanelChat(): JSX.Element {
+ return (
+ <div className="flex flex-col h-full min-h-0">
+ <SidePanelRunner panelId={MAX_SIDE_PANEL_ID} />
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/max/components/PhaiViewToggle.tsx b/frontend/src/scenes/max/components/PhaiViewToggle.tsx
new file mode 100644
index 000000000000..28ae079a42fc
--- /dev/null
+++ b/frontend/src/scenes/max/components/PhaiViewToggle.tsx
@@ -0,0 +1,43 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRevert, IconSparkles } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
+
+import { maxGlobalLogic } from '../maxGlobalLogic'
+
+/**
+ * Switches the Max scene between the new posthog_ai/frontend surface and the legacy Max chat. Only
+ * rendered for users on the sandbox flag; the new surface is their default (see `effectivePhaiView`).
+ *
+ * `lemon` matches the small secondary buttons in the main `/ai` header; `primitive` matches the
+ * icon-only chrome around "Open as main focus" in the side-panel header.
+ */
+export function PhaiViewToggle({ variant = 'lemon' }: { variant?: 'lemon' | 'primitive' }): JSX.Element | null {
+ const { isPhaiSandboxFlagOn, effectivePhaiView } = useValues(maxGlobalLogic)
+ const { setPhaiViewMode } = useActions(maxGlobalLogic)
+
+ if (!isPhaiSandboxFlagOn) {
+ return null
+ }
+
+ const switchingToLegacy = effectivePhaiView === 'new'
+ const tooltip = switchingToLegacy ? 'Switch to legacy PostHog AI' : 'Switch to new PostHog AI'
+ const Icon = switchingToLegacy ? IconRevert : IconSparkles
+ const onClick = (): void => setPhaiViewMode(switchingToLegacy ? 'legacy' : 'new')
+
+ if (variant === 'primitive') {
+ return (
+ <ButtonPrimitive iconOnly onClick={onClick} tooltip={tooltip} tooltipPlacement="bottom-end">
+ <Icon className="text-tertiary size-3 group-hover:text-primary z-10" />
+ </ButtonPrimitive>
+ )
+ }
+
+ return (
+ <LemonButton size="small" type="secondary" sideIcon={<Icon />} onClick={onClick} tooltip={tooltip}>
+ {switchingToLegacy ? 'Legacy view' : 'New view'}
+ </LemonButton>
+ )
+}
diff --git a/frontend/src/scenes/max/max-storage-keys.ts b/frontend/src/scenes/max/max-storage-keys.ts
index 2042acc70bd1..ea4c664299ea 100644
--- a/frontend/src/scenes/max/max-storage-keys.ts
+++ b/frontend/src/scenes/max/max-storage-keys.ts
@@ -5,3 +5,6 @@
/** Key for persisting pending AI prompts across page reloads (e.g., OAuth redirects) */
export const PENDING_AI_PROMPT_KEY = 'posthog_ai_pending_prompt'
+
+/** Which PostHog AI implementation the Max scene renders when the sandbox flag is on (see maxGlobalLogic). */
+export const PHAI_VIEW_MODE_KEY = 'posthog_ai_view_mode'
diff --git a/frontend/src/scenes/max/maxGlobalLogic.test.ts b/frontend/src/scenes/max/maxGlobalLogic.test.ts
index e5fe7d7ccc3e..52a7ff27e068 100644
--- a/frontend/src/scenes/max/maxGlobalLogic.test.ts
+++ b/frontend/src/scenes/max/maxGlobalLogic.test.ts
@@ -1,6 +1,8 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { useMocks } from '~/mocks/jest'
@@ -109,4 +111,27 @@ describe('maxGlobalLogic', () => {
})
})
})
+
+ // The flag is the only thing that may expose the new posthog_ai surface — without the gate a stored
+ // preference (or a missing default) would leak it to every user. Lock in: flag off collapses to legacy
+ // regardless of the stored mode; flag on passes the stored mode through.
+ describe('effectivePhaiView selector', () => {
+ it.each([
+ { flagOn: false, mode: 'new', expected: 'legacy' },
+ { flagOn: false, mode: 'legacy', expected: 'legacy' },
+ { flagOn: true, mode: 'new', expected: 'new' },
+ { flagOn: true, mode: 'legacy', expected: 'legacy' },
+ ] as const)(
+ 'is $expected when sandbox flag is $flagOn and stored mode is $mode',
+ async ({ flagOn, mode, expected }) => {
+ featureFlagLogic.actions.setFeatureFlags(
+ flagOn ? [FEATURE_FLAGS.PHAI_SANDBOX_MODE] : [],
+ flagOn ? { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true } : {}
+ )
+ logic.actions.setPhaiViewMode(mode)
+
+ await expectLogic(logic).toMatchValues({ effectivePhaiView: expected })
+ }
+ )
+ })
})
diff --git a/frontend/src/scenes/max/maxGlobalLogic.tsx b/frontend/src/scenes/max/maxGlobalLogic.tsx
index a4ad2f590d68..32b291aef2b6 100644
--- a/frontend/src/scenes/max/maxGlobalLogic.tsx
+++ b/frontend/src/scenes/max/maxGlobalLogic.tsx
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import api from 'lib/api'
-import { OrganizationMembershipLevel } from 'lib/constants'
+import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -21,9 +21,17 @@ import { conversationsDestroy } from 'products/conversations/frontend/generated/
import { requestAiAccessCreate } from 'products/platform_features/frontend/generated/api'
import { TOOL_DEFINITIONS, ToolRegistration } from './max-constants'
+import { PHAI_VIEW_MODE_KEY } from './max-storage-keys'
import type { maxGlobalLogicType } from './maxGlobalLogicType'
import { SIDE_PANEL_PANEL_ID, maxLogic, mergeConversationHistory, mergeConversations } from './maxLogic'
+/**
+ * Which PostHog AI implementation the Max scene renders. `'new'` is the posthog_ai/frontend surface
+ * (the tasks product on `/ai`, the new composer + thread viewer in the side panel); `'legacy'` is the
+ * existing Max chat. Only meaningful while the `PHAI_SANDBOX_MODE` flag is on — see `effectivePhaiView`.
+ */
+export type PhaiViewMode = 'new' | 'legacy'
+
// Keep this stored across all projects, only display this once per device
const AI_LIABILITY_NOTICE_STORAGE_KEY = 'posthog_ai_liability_notice_dismissed'
@@ -113,6 +121,7 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
deleteConversation: (id: string) => ({ id }),
dismissLiabilityNotice: true,
dismissDataProcessing: true,
+ setPhaiViewMode: (mode: PhaiViewMode) => ({ mode }),
requestAiAccess: true,
markAiAccessRequested: (organizationId: string) => ({ organizationId }),
requestAiAccessError: true,
@@ -204,6 +213,15 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
markAiAccessRequested: (state, { organizationId }) => ({ ...state, [organizationId]: true }),
},
],
+ // The user's chosen implementation, persisted per device. Defaults to the new surface so a
+ // flagged user lands there; `effectivePhaiView` collapses this to legacy when the flag is off.
+ phaiViewMode: [
+ 'new' as PhaiViewMode,
+ { persist: true, storageKey: PHAI_VIEW_MODE_KEY },
+ {
+ setPhaiViewMode: (_, { mode }) => mode,
+ },
+ ],
}),
listeners(({ actions, values }) => ({
acceptDataProcessing: async ({ testOnlyOverride }) => {
@@ -326,6 +344,18 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
(isOrganizationCreatedRecently, liabilityNoticeDismissed): boolean =>
isOrganizationCreatedRecently && !liabilityNoticeDismissed,
],
+ // Gates the new-vs-legacy toggle: only flagged users can switch, and the new surface only
+ // exists for them.
+ isPhaiSandboxFlagOn: [
+ (s) => [s.featureFlags],
+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE],
+ ],
+ // The implementation the Max scene actually renders: the user's choice while the flag is on,
+ // always legacy otherwise (so non-flagged users are unaffected regardless of any stored value).
+ effectivePhaiView: [
+ (s) => [s.isPhaiSandboxFlagOn, s.phaiViewMode],
+ (isPhaiSandboxFlagOn, phaiViewMode): PhaiViewMode => (isPhaiSandboxFlagOn ? phaiViewMode : 'legacy'),
+ ],
availableStaticTools: [
(s) => [s.featureFlags],
(featureFlags): ToolRegistration[] => {
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
index b8b5da5173f6..5d30b0c247c1 100644
--- a/products/posthog_ai/frontend/AGENTS.md
+++ b/products/posthog_ai/frontend/AGENTS.md
@@ -18,12 +18,12 @@ them. There are four tiers, split along dependency/side-effect boundaries (not c
preserves code-splitting). Consumers pick the **lowest tier** that does the job. The full decision table,
import rule, and copy-paste recipes live in the consumer-facing [`README.md`](./README.md); the summary:
-| Tier | Module | What's in it |
-| ------------------------------ | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts |
-| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms, `ThreadView`, `Composer.*`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces |
-| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status + thinking helpers; folded-thread + tool types |
-| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers |
+| Tier | Module | What's in it |
+| ------------------------------ | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` + `api/runner` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts; `EmbeddedRunner` (lazy TaskTracker product for inline hosts) |
+| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms, `ThreadView`, `Composer.*`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces |
+| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status + thinking helpers; folded-thread + tool types |
+| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers |
**Why the split, not one flat barrel:** the tool registry registers built-ins at module load — a top-level
side effect that is _not_ tree-shaken. A single barrel statically re-exports it alongside the
@@ -56,6 +56,12 @@ The headline exports per module:
(`scenes/TaskTracker/TaskRunChat`) composes its own live-composer layout. Because the compound is eager, import
it only from an already route-split scene (the `/tasks` runner) or another lazily-loaded layout module — a
light bundle that should stay split uses `api/readableRun` instead.
+- **`api/runner`** — **`EmbeddedRunner`** (`<EmbeddedRunner taskId? />`), the lazy, code-split TaskTracker
+ product (tasks list + composer + agent-run detail) for hosts that render the whole `/tasks` experience
+ inline (the Max scene surfaces it behind the sandbox view toggle). The heavy scene chunk loads only via
+ `EmbeddedRunner`'s dynamic `import()`, so importing this module never statically pulls the scene. Task
+ selection/creation still routes through the scene's own `/tasks/:id` URLs — it's the standalone product
+ embedded, not a route-decoupled widget.
- **`api/primitives`** — **`Thread`** (Radix-style compound: `Thread.Root` is the virtualized presenter, the
atoms `Thread.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall` are the building blocks for
bespoke threads), **`Composer`** (logic-free compound input — the caller owns
@@ -148,6 +154,7 @@ loosely typed — guard at the parse boundary with runtime checks; never assume
api/ # public API facade — the contract (import api/<module>, never deep paths)
readableRun.ts # Tier 1: ReadonlyRunSurface (lazy read-only embed)
runSurface.ts # Tier 1: RunSurface compound (Root + slots, eager) for custom layouts
+ runner.ts # Tier 1: EmbeddedRunner (lazy TaskTracker product) for inline hosts
primitives.ts # Tier 2: Composer, Thread + atoms, ThreadView, QueuedMessageList, presenters, perm/question/resource
logics.ts # Tier 3: runStreamLogic, runInteractionLogic, status + thinking helpers (headless)
types.ts # Tier 3: folded-thread + tool domain types (pure types)
diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.md
index 14ccdaf92155..d8a056847ab8 100644
--- a/products/posthog_ai/frontend/README.md
+++ b/products/posthog_ai/frontend/README.md
@@ -30,12 +30,12 @@ re-introduce the exact bundling problem the split solves. Always import an `api/
Pick the **lowest tier** that does the job.
-| Tier | Module | What's in it | Use when |
-| ------------------------------ | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
-| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts | "Just show a run" → `ReadonlyRunSurface` (inbox embeds). "Drive a run / custom layout" → `RunSurface` (tasks). |
-| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces | Custom layout, or a bespoke/compact thread. |
-| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers; folded-thread + tool types | Status badge or automation — no React, no registry. |
-| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Register them from your own scene. |
+| Tier | Module | What's in it | Use when |
+| ------------------------------ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` + `api/runner` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts; `EmbeddedRunner` (lazy TaskTracker product for inline hosts) | "Just show a run" → `ReadonlyRunSurface` (inbox embeds). "Drive a run / custom layout" → `RunSurface` (tasks). "Embed the whole `/tasks` product" → `EmbeddedRunner` (Max). |
+| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces | Custom layout, or a bespoke/compact thread. |
+| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers; folded-thread + tool types | Status badge or automation — no React, no registry. |
+| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Register them from your own scene. |
The Tier 1 surfaces are built on `api/primitives` (Tier 2), which consumes the headless
`api/logics`/`api/types` (Tier 3). Going down a tier trades convenience for control and a smaller chunk.
diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.ts
index ef907a419bf1..65d5420dc20b 100644
--- a/products/posthog_ai/frontend/api/logics.ts
+++ b/products/posthog_ai/frontend/api/logics.ts
@@ -18,3 +18,12 @@ export type { RunInteractionLogicProps, QueuedMessage } from '../logics/runInter
// --- Thinking-message helpers ---
export { getThinkingMessageFromResponse, getRandomThinkingMessage, THINKING_MESSAGES } from '../utils/thinkingMessages'
+
+// --- Composer model/effort helpers (pure — no component imports) ---
+export { resolveEffortForModel, DEFAULT_COMPOSER_MODEL, DEFAULT_COMPOSER_EFFORT } from '../utils/composerModels'
+
+// --- Panel view state (headless) ---
+// Panel-level view state (active run vs. history vs. composer) for hosts that render chrome — e.g. a
+// header back button — outside the lazy panel chunk (Tier 1 `api/runner`).
+export { runnerPanelLogic } from '../logics/runnerPanelLogic'
+export type { RunnerPanelLogicProps, ActiveCreation } from '../logics/runnerPanelLogic'
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index bf709c0625d5..60813dff43fd 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -19,6 +19,10 @@ export type {
ComposerSubmitProps,
} from '../components/composer/Composer'
+// Controlled model + reasoning-effort pickers for a composer footer.
+export { ComposerModelEffortPickers } from '../components/composer/ComposerModelEffortPickers'
+export type { ComposerModelEffortPickersProps } from '../components/composer/ComposerModelEffortPickers'
+
// Welcome header (logomark + headline + subheadline) and its overridable default headlines.
export { Welcome } from '../components/welcome/Welcome'
export type { WelcomeProps } from '../components/welcome/Welcome'
diff --git a/products/posthog_ai/frontend/api/runner.ts b/products/posthog_ai/frontend/api/runner.ts
new file mode 100644
index 000000000000..c61225f3ae2a
--- /dev/null
+++ b/products/posthog_ai/frontend/api/runner.ts
@@ -0,0 +1,20 @@
+// Tier 1 — the embeddable runner scene. `EmbeddedRunner` (`<EmbeddedRunner taskId? />`) is the lazy,
+// code-split TaskTracker product (tasks list + composer + agent-run detail) for hosts that want to render
+// the whole `/tasks` experience inline — e.g. the Max scene surfacing it behind the sandbox view toggle.
+//
+// LIGHT boundary: the heavy TaskTracker scene chunk is reached only through `EmbeddedRunner`'s dynamic
+// `import()`, so importing this module never statically pulls the scene/list/run-surface into the host
+// bundle. Task selection/creation still routes through the scene's own `/tasks/:id` URLs.
+//
+// Part of the `products/posthog_ai/frontend/api/<module>` public surface — import from here, not from
+// deep `../scenes/*` paths. See ../README.md for the tier model and ../AGENTS.md for the coupling rule.
+
+export { EmbeddedRunner, type TaskTrackerProps } from '../components/EmbeddedRunner'
+
+// `SidePanelRunner` (`<SidePanelRunner panelId />`) is the lazy, code-split compact task-run surface
+// (composer -> pending thread -> live run, no list/detail chrome) for narrow hosts that render a single
+// in-place run rather than the whole `/tasks` list/detail experience — e.g. Max's side panel behind the
+// posthog_ai view toggle. Same LIGHT boundary as `EmbeddedRunner`: the heavy chunk is reached only through
+// its dynamic `import()`. `panelId` keys an embedded `taskTrackerSceneLogic` instance independent of the
+// `/tasks` scene's own singleton — submitting a task here never navigates the host.
+export { SidePanelRunner, type SidePanelRunnerProps } from '../components/SidePanelRunner'
diff --git a/products/posthog_ai/frontend/components/EmbeddedRunner.tsx b/products/posthog_ai/frontend/components/EmbeddedRunner.tsx
new file mode 100644
index 000000000000..66129a367e68
--- /dev/null
+++ b/products/posthog_ai/frontend/components/EmbeddedRunner.tsx
@@ -0,0 +1,31 @@
+import { lazy, Suspense } from 'react'
+
+import { Spinner } from 'lib/lemon-ui/Spinner'
+
+import type { TaskTrackerProps } from '../scenes/TaskTracker/TaskTracker'
+
+export type { TaskTrackerProps } from '../scenes/TaskTracker/TaskTracker'
+
+// The TaskTracker scene (master/detail list + composer + run detail) is the heavy runner UI. It's loaded on
+// demand so a consumer that only links to it — e.g. the Max scene rendering it behind the sandbox view
+// toggle — doesn't statically pull it into its own chunk. Only `react` + a lightweight spinner load eagerly.
+const Lazy = lazy(() => import('../scenes/TaskTracker/TaskTracker').then((m) => ({ default: m.TaskTracker })))
+
+/**
+ * Embeddable, code-split TaskTracker runner. Renders the standalone `/tasks` product (tasks list + composer
+ * + agent-run detail) inside any host. Pass `taskId` to preselect a task; omit it for the list + composer.
+ * Note the scene routes task selection/creation through its own `/tasks/:id` URLs.
+ */
+export function EmbeddedRunner(props: TaskTrackerProps): JSX.Element {
+ return (
+ <Suspense
+ fallback={
+ <div className="flex flex-1 items-center justify-center">
+ <Spinner className="text-2xl" />
+ </div>
+ }
+ >
+ <Lazy {...props} />
+ </Suspense>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/SidePanelRunner.tsx b/products/posthog_ai/frontend/components/SidePanelRunner.tsx
new file mode 100644
index 000000000000..22ca2db3fdf2
--- /dev/null
+++ b/products/posthog_ai/frontend/components/SidePanelRunner.tsx
@@ -0,0 +1,33 @@
+import { lazy, Suspense } from 'react'
+
+import { Spinner } from 'lib/lemon-ui/Spinner'
+
+import type { SidePanelRunnerImplProps } from '../scenes/TaskTracker/components/SidePanelRunnerImpl'
+
+export type SidePanelRunnerProps = SidePanelRunnerImplProps
+
+// The compact side-panel task-run surface (composer -> pending thread -> live run, no list/detail chrome) is
+// loaded on demand so a consumer that only links to it — e.g. Max's side panel — doesn't statically pull the
+// TaskTracker scene's components into its own chunk. Only `react` + a lightweight spinner load eagerly.
+const Lazy = lazy(() =>
+ import('../scenes/TaskTracker/components/SidePanelRunnerImpl').then((m) => ({ default: m.SidePanelRunnerImpl }))
+)
+
+/**
+ * Embeddable, code-split compact task-run surface for narrow hosts. Renders the composer, the optimistic
+ * pending thread, and the live run — keyed by `panelId` so a host's embedded `taskTrackerSceneLogic` instance
+ * stays independent of the `/tasks` scene's own singleton.
+ */
+export function SidePanelRunner(props: SidePanelRunnerProps): JSX.Element {
+ return (
+ <Suspense
+ fallback={
+ <div className="flex flex-1 items-center justify-center">
+ <Spinner className="text-2xl" />
+ </div>
+ }
+ >
+ <Lazy {...props} />
+ </Suspense>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ComposerModelEffortPickers.tsx b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx
similarity index 100%
rename from products/posthog_ai/frontend/scenes/TaskTracker/components/ComposerModelEffortPickers.tsx
rename to products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx
diff --git a/products/posthog_ai/frontend/logics/runnerPanelLogic.test.ts b/products/posthog_ai/frontend/logics/runnerPanelLogic.test.ts
new file mode 100644
index 000000000000..8538017b7bc0
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/runnerPanelLogic.test.ts
@@ -0,0 +1,43 @@
+import { initKeaTests } from '~/test/init'
+
+import { runnerPanelLogic } from './runnerPanelLogic'
+
+describe('runnerPanelLogic', () => {
+ let logic: ReturnType<typeof runnerPanelLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = runnerPanelLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ // goBack must route to where the open task was launched from — history if the panel was showing the
+ // history list, the composer otherwise — mirroring legacy Max's `backToScreen` memory. Guards against
+ // either the "opened a task" listener losing that memory or `goBack` landing on the wrong screen.
+ it('goBack from a task opened out of history returns to history, then to the composer', () => {
+ logic.actions.setHistoryExpanded(true)
+ logic.actions.setActiveCreation({ streamKey: 'run-1' })
+ expect(logic.values.activeCreation).toEqual({ streamKey: 'run-1' })
+ expect(logic.values.historyExpanded).toBe(false)
+
+ logic.actions.goBack()
+ expect(logic.values.activeCreation).toBe(null)
+ expect(logic.values.historyExpanded).toBe(true)
+
+ logic.actions.goBack()
+ expect(logic.values.historyExpanded).toBe(false)
+ })
+
+ it('goBack from a task opened out of the composer lands directly on the composer', () => {
+ logic.actions.setActiveCreation({ streamKey: 'run-1' })
+ expect(logic.values.historyExpanded).toBe(false)
+
+ logic.actions.goBack()
+ expect(logic.values.activeCreation).toBe(null)
+ expect(logic.values.historyExpanded).toBe(false)
+ })
+})
diff --git a/products/posthog_ai/frontend/logics/runnerPanelLogic.ts b/products/posthog_ai/frontend/logics/runnerPanelLogic.ts
new file mode 100644
index 000000000000..2e916604fa91
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/runnerPanelLogic.ts
@@ -0,0 +1,97 @@
+import { actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+
+import type { runnerPanelLogicType } from './runnerPanelLogicType'
+
+// The optimistic run opened on send, before the task/run exist. `streamKey` is the client key the pending
+// `RunSurface` (and its seeded `runStreamLogic`) bind to; `taskId`/`runId` are filled once known (reserved
+// for a future zero-flash in-place handoff — today the scene navigates to the detail page once the run exists).
+export interface ActiveCreation {
+ streamKey: string
+ taskId?: string
+ runId?: string
+}
+
+// `panelId` is set only by an embedded instance (e.g. Max's side panel runner), which mounts this logic
+// under its own key rather than a scene's default singleton. Pass the same `panelId` a paired
+// `taskTrackerSceneLogic` instance uses so the two stay keyed together.
+export interface RunnerPanelLogicProps {
+ panelId?: string
+}
+
+export const runnerPanelLogic = kea<runnerPanelLogicType>([
+ path(['products', 'posthog_ai', 'frontend', 'logics', 'runnerPanelLogic']),
+ props({} as RunnerPanelLogicProps),
+ // No `panelId` resolves to the same 'scene' key `taskTrackerSceneLogic` falls back to, so an unkeyed
+ // caller pairs with the scene's own singleton.
+ key((props) => props.panelId ?? 'scene'),
+
+ actions({
+ setActiveCreation: (creation: ActiveCreation) => ({ creation }),
+ clearActiveCreation: true,
+ toggleHistory: true,
+ setHistoryExpanded: (expanded: boolean) => ({ expanded }),
+ goBack: true,
+ setCameFromHistory: (cameFromHistory: boolean) => ({ cameFromHistory }),
+ }),
+
+ reducers({
+ // The in-flight optimistic create. While set (and no task is selected) the panel shows the pending
+ // run thread instead of the composer.
+ activeCreation: [
+ null as ActiveCreation | null,
+ {
+ setActiveCreation: (_, { creation }) => creation,
+ clearActiveCreation: () => null,
+ },
+ ],
+ // Whether the panel is showing the full task history list instead of the composer/run.
+ historyExpanded: [
+ false,
+ {
+ toggleHistory: (state) => !state,
+ setHistoryExpanded: (_, { expanded }) => expanded,
+ },
+ ],
+ // Whether the currently active creation was opened from the expanded history view, so `goBack`
+ // knows to return there instead of falling through to the composer — mirrors legacy Max's
+ // `backToScreen: 'history'`.
+ cameFromHistory: [
+ false,
+ {
+ setCameFromHistory: (_, { cameFromHistory }) => cameFromHistory,
+ },
+ ],
+ }),
+
+ selectors({
+ canGoBack: [
+ (s) => [s.activeCreation, s.historyExpanded],
+ (activeCreation, historyExpanded): boolean => !!activeCreation || historyExpanded,
+ ],
+ }),
+
+ listeners(({ actions, values }) => ({
+ // Opening a task (from the composer or from history) collapses the history list so the run takes
+ // over the panel, and remembers whether it came from there — read-then-clear works because
+ // reducers for this same dispatch run before listeners.
+ setActiveCreation: () => {
+ if (values.historyExpanded) {
+ actions.setCameFromHistory(true)
+ actions.setHistoryExpanded(false)
+ } else {
+ actions.setCameFromHistory(false)
+ }
+ },
+ // Back walks run -> history-or-composer -> composer.
+ goBack: () => {
+ if (values.activeCreation) {
+ actions.clearActiveCreation()
+ if (values.cameFromHistory) {
+ actions.setHistoryExpanded(true)
+ }
+ } else if (values.historyExpanded) {
+ actions.setHistoryExpanded(false)
+ }
+ },
+ })),
+])
diff --git a/products/posthog_ai/frontend/logics/taskHistoryLogic.ts b/products/posthog_ai/frontend/logics/taskHistoryLogic.ts
new file mode 100644
index 000000000000..3a1fda8c720b
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/taskHistoryLogic.ts
@@ -0,0 +1,61 @@
+import { actions, connect, events, kea, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { userLogic } from 'scenes/userLogic'
+
+import { loadErrorMessage } from '../lib/load-error'
+import { OriginProduct, Task } from '../types/taskTypes'
+import type { taskHistoryLogicType } from './taskHistoryLogicType'
+
+// Deliberately independent of `tasksLogic` — the panel history must show the user's own recent
+// posthog_ai tasks regardless of whatever search/assignee filter is active on the /tasks scene.
+export const taskHistoryLogic = kea<taskHistoryLogicType>([
+ path(['products', 'posthog_ai', 'frontend', 'logics', 'taskHistoryLogic']),
+
+ connect(() => ({
+ values: [userLogic, ['user']],
+ })),
+
+ actions({
+ taskArchived: (taskId: string) => ({ taskId }),
+ }),
+
+ loaders(({ values }) => ({
+ history: [
+ [] as Task[],
+ {
+ loadHistory: async (_: void, breakpoint) => {
+ const response = await api.tasks.list({
+ origin_product: OriginProduct.POSTHOG_AI,
+ created_by: values.user?.id,
+ limit: 20,
+ })
+ breakpoint()
+ return response.results
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ history: {
+ // The full-list surface archives via `tasksLogic.deleteTask` and dispatches this to keep
+ // this independent list in sync without re-fetching.
+ taskArchived: (state, { taskId }) => state.filter((task) => task.id !== taskId),
+ },
+ historyError: [
+ null as string | null,
+ {
+ loadHistory: () => null,
+ loadHistoryFailure: (_, { error, errorObject }) => loadErrorMessage(error, errorObject),
+ },
+ ],
+ }),
+
+ events(({ actions }) => ({
+ afterMount: () => {
+ actions.loadHistory()
+ },
+ })),
+])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
new file mode 100644
index 000000000000..bba41c2bc40a
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
@@ -0,0 +1,91 @@
+import { BindLogic, useActions, useValues } from 'kea'
+
+import { IconArrowLeft } from '@posthog/icons'
+import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
+
+import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
+
+import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
+import { TaskComposer } from './TaskComposer'
+import { TaskHistoryList, TaskHistoryPreview } from './TaskHistory'
+import { TaskRunChat } from './TaskRunChat'
+
+export interface SidePanelRunnerImplProps {
+ /** Embedded `taskTrackerSceneLogic` key — keeps this instance independent of the `/tasks` scene singleton. */
+ panelId: string
+}
+
+/**
+ * Compact task-run surface for narrow hosts (Max's side panel): the same optimistic
+ * create -> pending thread -> live run flow as the `/tasks` scene, without its list/detail chrome or
+ * `/tasks/:id` navigation. Binds an embedded `taskTrackerSceneLogic` instance (keyed by `panelId`, see
+ * `TaskTrackerSceneLogicProps`) so `TaskComposer` — which reads the unbound `taskTrackerSceneLogic` — resolves
+ * this instance instead of the scene's own singleton.
+ */
+export function SidePanelRunnerImpl({ panelId }: SidePanelRunnerImplProps): JSX.Element {
+ return (
+ <BindLogic logic={taskTrackerSceneLogic} props={{ panelId }}>
+ <SidePanelRunnerContent />
+ </BindLogic>
+ )
+}
+
+function SidePanelRunnerContent(): JSX.Element {
+ const { activeCreation, historyExpanded } = useValues(taskTrackerSceneLogic)
+ const { toggleHistory, updateActiveCreationRun } = useActions(taskTrackerSceneLogic)
+
+ if (!activeCreation && historyExpanded) {
+ return (
+ <div className="flex flex-col h-full min-h-0">
+ <div className="flex items-center shrink-0 border-b border-primary px-2 py-1">
+ <LemonButton size="small" icon={<IconArrowLeft />} onClick={() => toggleHistory()}>
+ Back
+ </LemonButton>
+ </div>
+ <div className="flex-1 min-h-0 overflow-y-auto px-4 py-2">
+ <TaskHistoryList />
+ </div>
+ </div>
+ )
+ }
+
+ if (!activeCreation) {
+ // Mirrors the legacy Max welcome layout: a centered composer with the recent-tasks
+ // history pinned as a sibling at the bottom of the panel, not inside the composer column.
+ return (
+ <div className="relative flex flex-col gap-4 pb-7 h-full min-h-0 overflow-y-auto">
+ {/* No `items-center` (unlike the legacy welcome block): `TaskComposer` must stretch to full
+ width — it centers its own content, same as under the `/tasks` scene's wrapper. */}
+ <div className="grow min-h-0 flex flex-col">
+ <TaskComposer />
+ </div>
+ <TaskHistoryPreview />
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex flex-col h-full min-h-0">
+ <LemonDivider className="my-0" />
+ {activeCreation.taskId && activeCreation.runId ? (
+ // `TaskRunChat`'s inner container compensates for the `/tasks` scene's own horizontal margin
+ // with `-mx-4`; a `px-4` wrapper here neutralizes that bleed instead of editing the shared
+ // component, so it renders flush with the panel edge like the composer and pending states.
+ <div className="flex-1 min-h-0 px-4">
+ <TaskRunChat
+ taskId={activeCreation.taskId}
+ runId={activeCreation.runId}
+ streamKey={activeCreation.streamKey}
+ onRunStarted={updateActiveCreationRun}
+ />
+ </div>
+ ) : (
+ <div className="@container/thread flex flex-col flex-1 min-h-0">
+ <RunSurface.Root taskId="" runId={null} streamKey={activeCreation.streamKey} interaction="live">
+ <RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />
+ </RunSurface.Root>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index de379ffb9b15..8211baf5fbee 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -11,8 +11,8 @@ import {
} from 'products/posthog_ai/frontend/api/primitives'
import { resolveEffortForModel } from 'products/posthog_ai/frontend/utils/composerModels'
+import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
-import { ComposerModelEffortPickers } from './ComposerModelEffortPickers'
import { RepositorySelector } from './RepositorySelector'
export function TaskComposer(): JSX.Element {
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskHistory.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskHistory.tsx
new file mode 100644
index 000000000000..4d727b228a61
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskHistory.tsx
@@ -0,0 +1,168 @@
+import { useActions, useValues } from 'kea'
+
+import { IconArchive } from '@posthog/icons'
+import { LemonButton, LemonSkeleton, Link, Spinner } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { urls } from 'scenes/urls'
+
+import { taskHistoryLogic } from '../../../logics/taskHistoryLogic'
+import { tasksLogic } from '../../../logics/tasksLogic'
+import { Task, TaskRunStatus } from '../../../types/taskTypes'
+import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
+
+const IN_PROGRESS_STATUSES = new Set<TaskRunStatus>([TaskRunStatus.QUEUED, TaskRunStatus.IN_PROGRESS])
+
+// Compact "time ago" using a single largest unit, e.g. 18m, 1h, 7d.
+function compactTimeAgo(iso: string): string {
+ const seconds = dayjs().diff(dayjs(iso), 'second')
+ if (seconds < 60) {
+ return 'now'
+ }
+ return humanFriendlyDuration(seconds, { maxUnits: 1 })
+}
+
+function isTaskInProgress(task: Task): boolean {
+ return task.latest_run ? IN_PROGRESS_STATUSES.has(task.latest_run.status) : false
+}
+
+export function TaskHistoryPreview(): JSX.Element | null {
+ const { history, historyLoading } = useValues(taskHistoryLogic)
+ const { toggleHistory, openExistingTask } = useActions(taskTrackerSceneLogic)
+
+ if (!history.length && !historyLoading) {
+ return null
+ }
+
+ return (
+ <div className="max-w-120 w-full self-center flex flex-col gap-2 px-3">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-sm font-medium text-secondary mb-0">Recent tasks</h3>
+ <LemonButton
+ size="small"
+ onClick={() => toggleHistory()}
+ data-attr="task-view-all-history"
+ tooltip="Open task history"
+ tooltipPlacement="bottom"
+ >
+ View all
+ </LemonButton>
+ </div>
+ {historyLoading && !history.length ? (
+ <>
+ <LemonSkeleton className="h-5 w-full" />
+ <LemonSkeleton className="h-5 w-full" />
+ <LemonSkeleton className="h-5 w-full" />
+ </>
+ ) : (
+ history
+ .slice(0, 3)
+ .map((task) => <TaskHistoryPreviewRow key={task.id} task={task} onOpen={openExistingTask} />)
+ )}
+ </div>
+ )
+}
+
+interface TaskHistoryRowProps {
+ task: Task
+ onOpen: (task: Task) => void
+}
+
+function TaskHistoryPreviewRow({ task, onOpen }: TaskHistoryRowProps): JSX.Element {
+ return (
+ <span className="flex items-center gap-2">
+ <Link
+ className="grow text-sm text-primary hover:text-accent-hover active:text-accent-active"
+ data-attr="task-open-history-preview"
+ to={urls.taskDetail(task.id)}
+ onClick={(e) => {
+ e.preventDefault()
+ onOpen(task)
+ }}
+ >
+ <div className="flex items-center gap-2">
+ <span className="flex-1 line-clamp-1">{task.title || task.slug}</span>
+ </div>
+ </Link>
+ {isTaskInProgress(task) ? (
+ <Spinner className="h-4 w-4" />
+ ) : (
+ <span className="text-right text-secondary whitespace-nowrap cursor-default">
+ {compactTimeAgo(task.updated_at)}
+ </span>
+ )}
+ </span>
+ )
+}
+
+export function TaskHistoryList(): JSX.Element {
+ const { history, historyLoading } = useValues(taskHistoryLogic)
+ const { openExistingTask } = useActions(taskTrackerSceneLogic)
+
+ if (historyLoading && !history.length) {
+ return (
+ <div className="flex flex-col gap-2 w-full">
+ <LemonSkeleton className="h-14" />
+ <LemonSkeleton className="h-14 opacity-80" />
+ <LemonSkeleton className="h-14 opacity-60" />
+ </div>
+ )
+ }
+
+ if (!history.length) {
+ return (
+ <div className="flex flex-col items-center justify-center text-center py-8 text-muted">
+ <p className="text-sm mb-0">No tasks yet</p>
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-2 w-full">
+ {history.map((task) => (
+ <TaskHistoryCard key={task.id} task={task} onOpen={openExistingTask} />
+ ))}
+ </div>
+ )
+}
+
+function TaskHistoryCard({ task, onOpen }: TaskHistoryRowProps): JSX.Element {
+ const { deleteTask } = useActions(tasksLogic)
+ const { taskArchived } = useActions(taskHistoryLogic)
+
+ return (
+ <div
+ className="p-3 flex flex-row bg-surface-primary rounded-lg gap-2 w-full items-center justify-between cursor-pointer"
+ role="button"
+ tabIndex={0}
+ data-attr="task-open-history-card"
+ onClick={() => onOpen(task)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ onOpen(task)
+ }
+ }}
+ >
+ <span className="flex-1 line-clamp-1 text-sm">{task.title || task.slug}</span>
+ <div className="flex items-center gap-2 shrink-0">
+ {isTaskInProgress(task) ? (
+ <Spinner className="h-4 w-4" />
+ ) : (
+ <span className="text-secondary text-xs">{compactTimeAgo(task.updated_at)}</span>
+ )}
+ <LemonButton
+ size="small"
+ icon={<IconArchive />}
+ status="danger"
+ aria-label="Archive task"
+ onClick={(e) => {
+ e.stopPropagation()
+ deleteTask({ taskId: task.id })
+ taskArchived(task.id)
+ }}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
index 79a45f6cd45a..ca3809779291 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
@@ -7,8 +7,8 @@ import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/pr
// flash. The inbox embeds keep the lazy `ReadonlyRunSurface`.
import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
+import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
import { taskDetailSceneLogic } from '../taskDetailSceneLogic'
-import { ComposerModelEffortPickers } from './ComposerModelEffortPickers'
export interface TaskRunChatProps {
taskId: string
@@ -19,6 +19,8 @@ export interface TaskRunChatProps {
* fresh one. Passed to both `RunSurface.Root` and `runInteractionLogic` so they never diverge.
*/
streamKey?: string
+ /** Called after a fresh run starts, in addition to the `taskDetailSceneLogic` re-pointing below. */
+ onRunStarted?: (runId: string) => void
}
/**
@@ -29,7 +31,7 @@ export interface TaskRunChatProps {
* re-points scene selection to it. `RunSurface.Root` owns bootstrap: it reads the run status from the tasks
* API and never opens SSE for an already-terminal run.
*/
-export function TaskRunChat({ taskId, runId, streamKey }: TaskRunChatProps): JSX.Element {
+export function TaskRunChat({ taskId, runId, streamKey, onRunStarted }: TaskRunChatProps): JSX.Element {
const { setSelectedRunId, loadTaskRuns } = useActions(taskDetailSceneLogic({ taskId }))
const { selectedRun } = useValues(taskDetailSceneLogic({ taskId }))
const logicProps: RunInteractionLogicProps = {
@@ -41,6 +43,9 @@ export function TaskRunChat({ taskId, runId, streamKey }: TaskRunChatProps): JSX
onRunStarted: (newRunId) => {
setSelectedRunId(newRunId, taskId)
loadTaskRuns()
+ // The embedded panel renders from its own creation state, so it must be re-pointed
+ // when a fresh run starts.
+ onRunStarted?.(newRunId)
},
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index 850fecc0e069..bbdcec7c3759 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -4,9 +4,28 @@ import { expectLogic } from 'kea-test-utils'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { OriginProduct } from '../../types/taskTypes'
+import { OriginProduct, Task, TaskRunEnvironment, TaskRunStatus } from '../../types/taskTypes'
import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'
+const buildTask = (overrides: Partial<Task> = {}): Task => ({
+ id: 'task-1',
+ task_number: 1,
+ slug: 'task-1',
+ title: 'Some task',
+ description: 'do the thing',
+ origin_product: OriginProduct.POSTHOG_AI,
+ repository: null,
+ github_integration: null,
+ signal_report: null,
+ json_schema: null,
+ internal: false,
+ latest_run: null,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ ...overrides,
+})
+
describe('taskTrackerSceneLogic', () => {
let logic: ReturnType<typeof taskTrackerSceneLogic.build>
let createBody: Record<string, any> | null
@@ -87,4 +106,73 @@ describe('taskTrackerSceneLogic', () => {
expect(logic.values.newTaskData.repositoryConfig.integrationId).toBe(7)
})
+
+ // An embedded instance (e.g. Max's side panel runner) keeps the run in place instead of navigating the
+ // host to `/tasks/:id`, and must never have its `activeCreation` cleared by unrelated main-app
+ // navigation. Guards against either guard (`props.panelId` in `submitNewTask` / `urlToAction`) being
+ // dropped, which would yank the host to the tasks scene or silently drop the panel's in-flight run.
+ it('does not navigate on create and ignores url cleanup for an embedded instance', async () => {
+ const panelLogic = taskTrackerSceneLogic({ panelId: 'test-panel' })
+ panelLogic.mount()
+ const initialPath = router.values.location.pathname
+
+ panelLogic.actions.setNewTaskData({ description: 'do the thing' })
+ panelLogic.actions.submitNewTask()
+ await expectLogic(panelLogic).toFinishAllListeners()
+
+ expect(router.values.location.pathname).toBe(initialPath)
+ expect(panelLogic.values.activeCreation).toMatchObject({ taskId: 'new-task' })
+
+ router.actions.push('/tasks/some-other-task')
+ expect(panelLogic.values.activeCreation).toMatchObject({ taskId: 'new-task' })
+
+ panelLogic.unmount()
+ })
+
+ // Opening a task from the panel's history must render its run in place (a task with a run) or fall
+ // back to the full detail page (a task that never ran) — never the other way round.
+ it.each([
+ {
+ description: 'a task with a latest run',
+ task: buildTask({
+ id: 'task-with-run',
+ latest_run: {
+ id: 'run-1',
+ task: 'task-with-run',
+ stage: null,
+ branch: null,
+ status: TaskRunStatus.COMPLETED,
+ environment: TaskRunEnvironment.CLOUD,
+ log_url: null,
+ error_message: null,
+ output: null,
+ state: {},
+ artifacts: [],
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ completed_at: '2026-01-01T00:00:00Z',
+ },
+ }),
+ expectedActiveCreation: { streamKey: 'run-1', taskId: 'task-with-run', runId: 'run-1' },
+ expectedPath: undefined,
+ },
+ {
+ description: 'a task that never ran',
+ task: buildTask({ id: 'task-without-run', latest_run: null }),
+ expectedActiveCreation: null,
+ expectedPath: '/tasks/task-without-run',
+ },
+ ])('openExistingTask opens $description', ({ task, expectedActiveCreation, expectedPath }) => {
+ logic.mount()
+ const initialPath = router.values.location.pathname
+ // Set beforehand to prove opening a task resets it, even for the never-ran/navigate case.
+ logic.actions.toggleHistory()
+ expect(logic.values.historyExpanded).toBe(true)
+
+ logic.actions.openExistingTask(task)
+
+ expect(logic.values.activeCreation).toEqual(expectedActiveCreation)
+ expect(logic.values.historyExpanded).toBe(false)
+ expect(router.values.location.pathname).toContain(expectedPath ?? initialPath)
+ })
})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 86054b19bcae..c8a4944c74f5 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -1,4 +1,4 @@
-import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
+import { actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
@@ -16,12 +16,15 @@ import {
import { runStreamLogic } from '../../api/logics'
import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'
import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'
+import { runnerPanelLogic } from '../../logics/runnerPanelLogic'
import { tasksLogic } from '../../logics/tasksLogic'
-import type { RepositoryConfig } from '../../types/taskTypes'
+import type { RepositoryConfig, Task } from '../../types/taskTypes'
import { OriginProduct, TaskUpsertProps } from '../../types/taskTypes'
import { DEFAULT_COMPOSER_EFFORT, DEFAULT_COMPOSER_MODEL, resolveEffortForModel } from '../../utils/composerModels'
import type { taskTrackerSceneLogicType } from './taskTrackerSceneLogicType'
+export type { ActiveCreation } from '../../logics/runnerPanelLogic'
+
export interface TaskCreateForm {
description: string
repositoryConfig: RepositoryConfig
@@ -33,13 +36,12 @@ export interface TaskCreateForm {
// want the branch picker to re-derive the repo's actual default branch (from the GitHub API), not pin a stale one.
export type PersistedRepositoryConfig = Pick<RepositoryConfig, 'integrationId' | 'repository'>
-// The optimistic run opened on send, before the task/run exist. `streamKey` is the client key the pending
-// `RunSurface` (and its seeded `runStreamLogic`) bind to; `taskId`/`runId` are filled once known (reserved
-// for a future zero-flash in-place handoff — today the scene navigates to the detail page once the run exists).
-export interface ActiveCreation {
- streamKey: string
- taskId?: string
- runId?: string
+// `panelId` is set only by an embedded instance (e.g. Max's side panel runner), which mounts this logic
+// under its own key rather than the scene's default singleton. Embedded instances stay in place on submit
+// (no `/tasks/:id` navigation — the host renders the run from `activeCreation` itself) and ignore the scene's
+// `urlToAction` cleanup (main-app navigation must never release a side panel's in-flight creation).
+export interface TaskTrackerSceneLogicProps {
+ panelId?: string
}
const LAST_REPOSITORY_CONFIG_STORAGE_KEY = 'posthog_ai.tasks.lastRepositoryConfig'
@@ -56,10 +58,24 @@ const EMPTY_TASK_FORM: TaskCreateForm = {
export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
path(['products', 'posthog_ai', 'frontend', 'scenes', 'TaskTracker', 'taskTrackerSceneLogic']),
+ props({} as TaskTrackerSceneLogicProps),
+ // No `panelId` (the scene's own mount) resolves to the same 'scene' key every existing unbound
+ // `useValues(taskTrackerSceneLogic)` / `taskTrackerSceneLogic.actions...` call site already relies on —
+ // only an embedded caller that passes `panelId` gets its own instance.
+ key((props) => props.panelId ?? 'scene'),
- connect(() => ({
- values: [tasksLogic, ['tasks', 'repositories', 'taskListParams'], integrationsLogic, ['integrations']],
+ connect((props: TaskTrackerSceneLogicProps) => ({
+ values: [
+ runnerPanelLogic(props),
+ ['activeCreation', 'historyExpanded'],
+ tasksLogic,
+ ['tasks', 'repositories', 'taskListParams'],
+ integrationsLogic,
+ ['integrations'],
+ ],
actions: [
+ runnerPanelLogic(props),
+ ['setActiveCreation', 'clearActiveCreation', 'toggleHistory', 'setHistoryExpanded'],
tasksLogic,
['loadTasks', 'loadRepositories', 'deleteTask'],
integrationsLogic,
@@ -78,8 +94,10 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
applySuggestion: (item: SuggestionItem) => ({ item }),
setHeadline: (headline: string) => ({ headline }),
setPersistedRepositoryConfig: (config: PersistedRepositoryConfig) => ({ config }),
- setActiveCreation: (creation: ActiveCreation) => ({ creation }),
- clearActiveCreation: true,
+ openExistingTask: (task: Task) => ({ task }),
+ // Re-points the panel at a fresh run started from the composer on a reopened terminal task
+ // (the run surface's own re-pointing targets the detail scene, which the panel doesn't render).
+ updateActiveCreationRun: (runId: string) => ({ runId }),
}),
reducers({
@@ -122,15 +140,6 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
setHeadline: (_, { headline }) => headline,
},
],
- // The in-flight optimistic create. While set (and no task is selected) the scene shows the pending
- // run thread instead of the composer.
- activeCreation: [
- null as ActiveCreation | null,
- {
- setActiveCreation: (_, { creation }) => creation,
- clearActiveCreation: () => null,
- },
- ],
}),
selectors({
@@ -141,7 +150,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
],
}),
- listeners(({ actions, values, cache }) => ({
+ listeners(({ actions, values, cache, props }) => ({
// Release the manually-mounted optimistic stream once the create resolves (navigated to the real run)
// or fails (returned to the composer), so the throwaway draft instance never leaks.
clearActiveCreation: () => {
@@ -252,7 +261,11 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// (same `streamKey` + real `runId`) instead of cold-bootstrapping a fresh, skeleton-flashing one.
// Kept set across navigation; cleared by the `urlToAction` below once the user leaves this run.
actions.setActiveCreation({ streamKey, taskId: newTask.id, runId: runResponse.latest_run?.id })
- router.actions.push(`/tasks/${newTask.id}`)
+ // An embedded instance (`panelId` set) keeps the run in place — the host renders it from
+ // `activeCreation` — rather than navigating the main app to the `/tasks/:id` detail page.
+ if (!props.panelId) {
+ router.actions.push(`/tasks/${newTask.id}`)
+ }
actions.submitNewTaskSuccess()
actions.resetNewTaskData()
@@ -265,6 +278,24 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
actions.submitNewTaskFailure(error instanceof Error ? error.message : 'Unknown error')
}
},
+ openExistingTask: ({ task }) => {
+ if (task.latest_run) {
+ // No optimistic stream seeding — the run surface bootstraps the thread from the API.
+ actions.setActiveCreation({ streamKey: task.latest_run.id, taskId: task.id, runId: task.latest_run.id })
+ return
+ }
+ // Never-ran task (rare for this panel's posthog_ai origin) — fall back to the full detail page.
+ // No `setActiveCreation` on this branch, so collapse history explicitly (the runnerPanelLogic
+ // listener that normally does this only fires off that action).
+ actions.setHistoryExpanded(false)
+ router.actions.push(`/tasks/${task.id}`)
+ },
+ updateActiveCreationRun: ({ runId }) => {
+ if (!values.activeCreation?.taskId) {
+ return
+ }
+ actions.setActiveCreation({ streamKey: runId, taskId: values.activeCreation.taskId, runId })
+ },
})),
events(({ actions, values, cache }) => ({
@@ -287,7 +318,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
},
})),
- urlToAction(({ actions, values }) => {
+ urlToAction(({ actions, values, props }) => {
// The optimistic creation is kept alive across the success navigation so the detail page can adopt
// its seeded stream. Release it once the user lands anywhere other than the created task — another
// task, the list, or back to `/tasks/new`. Guarded on `taskId` being set so the pre-id provisioning
@@ -299,8 +330,10 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
}
}
return {
- '/tasks': () => clearIfLeftCreatedTask(),
- '/tasks/:taskId': ({ taskId }) => clearIfLeftCreatedTask(taskId),
+ // An embedded instance never navigates the main app on its own creation (see `submitNewTask`), so
+ // main-app URL changes are unrelated to its run — never release the side panel's active creation.
+ '/tasks': () => (props.panelId ? undefined : clearIfLeftCreatedTask()),
+ '/tasks/:taskId': ({ taskId }) => (props.panelId ? undefined : clearIfLeftCreatedTask(taskId)),
}
}),
])