: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
fix(ai): preserve chat startup, history, and native tool results (#96773)
Georgiy Tarasov74e623e53eb9
diff --git a/posthog/api/test/test_mixins.py b/posthog/api/test/test_mixins.pyindex 3ad529381fa9..876cbcfe7342 100644--- a/posthog/api/test/test_mixins.py+++ b/posthog/api/test/test_mixins.py@@ -2,10 +2,9 @@ import uuidfrom typing import NoReturnimport pytest-from posthog.test.base import APIBaseTestfrom unittest.mock import Mock, patch-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializerfrom parameterized import parameterized@@ -42,7 +41,7 @@ class RaisingResponseSerializer(serializers.Serializer):raise RuntimeError("boom")-class TestValidatedRequestDecorator(APIBaseTest):+class TestValidatedRequestDecorator(SimpleTestCase):def test_request_validation_with_valid_event_data(self):"""All valid data, should return 200 OK"""@@ -289,7 +288,9 @@ class TestValidatedRequestDecorator(APIBaseTest):])@override_settings(DEBUG=True)- def test_polymorphic_proxy_response_bypasses_validation(self, _name, many, payload):+ def test_polymorphic_proxy_response_bypasses_validation(+ self, _name: str, many: bool, payload: dict[str, bool] | list[dict[str, bool]]+ ) -> None:@validated_request(request_serializer=EventCaptureRequestSerializer,responses={@@ -303,7 +304,7 @@ class TestValidatedRequestDecorator(APIBaseTest):),},)- def mock_endpoint(view_self, request):+ def mock_endpoint(view_self: object, request: object) -> Response:return Response(payload, status=status.HTTP_200_OK)mock_request = Mock()diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex 83ef13e62cbc..e98c0a3c3dc4 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -82,7 +82,6 @@ posthog/api/test/test_csp.py::TestCSPModuleposthog/api/test/test_event_definition_base.py::TestEventDefinitionGeneratorBaseposthog/api/test/test_event_definition_typescript.py::TestTypeScriptGeneratorOptionalInTypesposthog/api/test/test_github.py::TestRelayToEu-posthog/api/test/test_mixins.py::TestValidatedRequestDecoratorposthog/api/test/test_organization_domain.py::TestOrganizationDomainsposthog/api/test/test_proxy_record_diagnostics.py::TestCheckCaaposthog/api/test/test_proxy_record_diagnostics.py::TestCheckCloudflare@@ -382,7 +381,6 @@ products/tasks/backend/temporal/process_task/tests/test_utils.py::TestBuildSandbproducts/tasks/backend/temporal/process_task/tests/test_utils.py::TestGetImportedMcpServerConfigsproducts/tasks/backend/temporal/process_task/tests/test_utils.py::TestGetRelayedMcpServerNamesproducts/tasks/backend/temporal/process_task/tests/test_utils.py::TestGetSandboxGitHubToken-products/tasks/backend/temporal/process_task/tests/test_utils.py::TestGetSandboxMcpConfigsproducts/tasks/backend/temporal/process_task/tests/test_utils.py::TestMcpServerConfigToDictproducts/tasks/backend/temporal/slack_relay/tests/test_activities.py::TestSplitTextForSlackproducts/tasks/backend/tests/test_agentsh.py::TestBuildAuditQueryCommanddiff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.pyindex e42a539ba52b..d2b52da8c9e5 100644--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py@@ -27,6 +27,7 @@ from products.tasks.backend.constants import (WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG,)from products.tasks.backend.facade.agents import TurnPollResult+from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextfrom products.tasks.backend.temporal.process_task.utils import mcp_exec_skills_env_vars@@ -173,7 +174,17 @@ async def test_eval_run_preserves_bundled_skills_unless_exec_is_selected(environments: list[dict[str, str]] = []async def suite(ctx: EvalContext) -> None:- task_context = SimpleNamespace(interaction_origin=origin, organization_id="org-1", distinct_id="user-1")+ task_context = TaskProcessingContext(+ task_id="task-id",+ run_id="run-id",+ team_id=1,+ team_uuid="team-1",+ organization_id="org-1",+ github_integration_id=None,+ repository=None,+ distinct_id="user-1",+ state={"interaction_origin": origin},+ )environments.append(await asyncio.to_thread(mcp_exec_skills_env_vars, task_context))results = await harness._run_suites(diff --git a/products/posthog_ai/frontend/components/RunEscapeBoundary.tsx b/products/posthog_ai/frontend/components/RunEscapeBoundary.tsxindex 2a1387c4e898..115de8c81b30 100644--- a/products/posthog_ai/frontend/components/RunEscapeBoundary.tsx+++ b/products/posthog_ai/frontend/components/RunEscapeBoundary.tsx@@ -106,7 +106,12 @@ export function RunEscapeBoundary({})return (- <div ref={containerRef} data-run-escape-scope={scope} className={className}>+ <div+ ref={containerRef}+ data-run-escape-scope={scope}+ tabIndex={scope === 'chat' ? -1 : undefined}+ className={className}+ >{children}</div>)diff --git a/products/posthog_ai/frontend/components/composer/useDebouncedDraft.test.ts b/products/posthog_ai/frontend/components/composer/useDebouncedDraft.test.tsnew file mode 100644index 000000000000..2f247f42dd9a--- /dev/null+++ b/products/posthog_ai/frontend/components/composer/useDebouncedDraft.test.ts@@ -0,0 +1,48 @@+import { act, renderHook } from '@testing-library/react'+import { useRef, useState } from 'react'++import { useDebouncedDraft } from './useDebouncedDraft'++describe('useDebouncedDraft', () => {+ beforeEach(() => jest.useFakeTimers())+ afterEach(() => jest.useRealTimers())++ it.each([+ { settled: false, accepted: true },+ { settled: false, accepted: false },+ { settled: true, accepted: true },+ ])('submits the latest draft with settled=$settled and accepted=$accepted', ({ settled, accepted }) => {+ const send = jest.fn()+ const { result, unmount } = renderHook(() => {+ const [saved, setSaved] = useState('')+ const current = useRef(saved)+ const sync = (next: string): void => {+ current.current = next+ setSaved(next)+ }+ const draft = useDebouncedDraft(saved, sync)+ return {+ draft,+ submit: () =>+ draft.submit(() => {+ send(current.current)+ if (accepted) {+ sync('')+ }+ }),+ }+ })++ act(() => result.current.draft.onChange('follow-up message'))+ if (settled) {+ act(() => jest.advanceTimersByTime(150))+ }+ act(() => result.current.submit())++ expect(send).toHaveBeenCalledWith('follow-up message')+ expect(result.current.draft.value).toBe(accepted ? '' : 'follow-up message')+ act(() => jest.advanceTimersByTime(150))+ expect(result.current.draft.value).toBe(accepted ? '' : 'follow-up message')+ unmount()+ })+})diff --git a/products/posthog_ai/frontend/components/composer/useDebouncedDraft.ts b/products/posthog_ai/frontend/components/composer/useDebouncedDraft.tsindex 07e21a392083..b669d9c831a5 100644--- a/products/posthog_ai/frontend/components/composer/useDebouncedDraft.ts+++ b/products/posthog_ai/frontend/components/composer/useDebouncedDraft.ts@@ -1,4 +1,5 @@import { useEffect, useState } from 'react'+import { flushSync } from 'react-dom'import { useDebouncedCallback } from 'use-debounce'export interface DebouncedDraft {@@ -46,11 +47,10 @@ export function useDebouncedDraft(externalValue: string, sync: (value: string) =debouncedSync(next)},submit: (send: () => string | void): void => {- // Flush the pending keystroke synchronously so the send reads the latest draft, not the stale- // debounced value; a no-op when nothing is pending (kea already has it).- debouncedSync.flush()+ // Commit the draft before send can clear it. Batching both writes can hide the external+ // value change from the mirroring effect, leaving submitted text in the local echo.+ flushSync(() => debouncedSync.flush())const nextValue = send()- // A flush and reset can batch back to the original external value, skipping its effect.if (typeof nextValue === 'string') {setValue(nextValue)}diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex 3d5685dc6137..3e8d41ace861 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -2643,35 +2643,164 @@ describe('runStreamLogic', () => {).toEqual(['overlap'])})- it('keeps a genuinely repeated payload when the buffer holds more copies than history (multiset)', async () => {- // The agent legitimately emitted the same message twice live; the snapshot captured only- // one (the second landed after the snapshot read). One historical copy absorbs one buffered- // copy; the surplus survives — counts, not a set.- let resolveLogs: (value: unknown) => void = () => {}- jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(- new Promise((resolve) => (resolveLogs = resolve)) as any- )- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ test.each([+ { name: 'one chunk', ids: ['boot-9'], chunks: ['reply'], legacyEnvelope: false },+ {+ name: 'a chunk range',+ ids: ['boot-9', 'boot-10', 'boot-11'],+ chunks: ['re', 'pl', 'y'],+ legacyEnvelope: false,+ },+ { name: 'an opaque event ID', ids: ['opaque-event'], chunks: ['reply'], legacyEnvelope: false },+ { name: 'a legacy envelope', ids: ['boot-9'], chunks: ['reply'], legacyEnvelope: true },+ ])(+ 'reconciles $name compacted in history without dropping the next identical reply',+ async ({ ids, chunks, legacyEnvelope }) => {+ let resolveLogs: (value: unknown) => void = () => {}+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(+ new Promise((resolve) => (resolveLogs = resolve)) as any+ )+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)- logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })- await flushPromises()- await MockStream.latest().emitOpen()+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()- const repeated = sessionUpdate({- sessionUpdate: 'agent_message',- messageId: 'm1',- content: { text: 'ping' },- })- await MockStream.latest().emitMessage(repeated, '1-0')- await MockStream.latest().emitMessage(repeated, '2-0')+ for (const [index, eventId] of ids.entries()) {+ await MockStream.latest().emitMessage({+ ...notification('session/update', {+ sessionId: 'session-1',+ update: {+ sessionUpdate: 'agent_message_chunk',+ content: { type: 'text', text: chunks[index] },+ },+ }),+ event_id: eventId,+ })+ }+ const savedReply = sessionUpdate({+ sessionUpdate: 'agent_message',+ content: { type: 'text', text: 'reply' },+ })- resolveLogs([repeated])- await flushPromises()+ resolveLogs([+ {+ ...(legacyEnvelope ? { notification: savedReply.notification } : savedReply),+ event_id: ids.at(-1),+ first_event_id: ids[0],+ },+ ])+ await flushPromises()- expect(- logic.values.threadItems.filter((item) => item.type === 'assistant_message').map((item) => item.text)- ).toEqual(['ping', 'ping'])- })+ expect(+ logic.values.threadItems+ .filter((item) => item.type === 'assistant_message')+ .map((item) => item.text)+ ).toEqual(['reply'])++ await MockStream.latest().emitMessage({ ...savedReply, event_id: 'boot-12' })+ expect(+ logic.values.threadItems+ .filter((item) => item.type === 'assistant_message')+ .map((item) => item.text)+ ).toEqual(['reply', 'reply'])+ }+ )++ test.each([+ {+ name: 'legacy payloads',+ historyId: undefined,+ firstId: undefined,+ liveIds: [undefined, undefined],+ ancestor: false,+ count: 2,+ },+ {+ name: 'legacy history with live event IDs',+ historyId: undefined,+ firstId: undefined,+ liveIds: ['boot-1', 'boot-2'],+ ancestor: false,+ count: 2,+ },+ {+ name: 'distinct event IDs',+ historyId: 'boot-1',+ firstId: undefined,+ liveIds: ['boot-2', 'boot-3'],+ ancestor: false,+ count: 3,+ },+ {+ name: 'different agent boots',+ historyId: 'boot-1',+ firstId: undefined,+ liveIds: ['other-boot-1'],+ ancestor: false,+ count: 2,+ },+ {+ name: 'a different run',+ historyId: 'boot-1',+ firstId: undefined,+ liveIds: ['boot-1'],+ ancestor: true,+ count: 2,+ },+ {+ name: 'a malformed event range',+ historyId: 'boot-11',+ firstId: 'other-boot-9',+ liveIds: ['boot-10'],+ ancestor: false,+ count: 2,+ },+ {+ name: 'an opaque event range',+ historyId: 'opaque-z',+ firstId: 'opaque-a',+ liveIds: ['opaque-m'],+ ancestor: false,+ count: 2,+ },+ ])(+ 'keeps genuine repeated $name at the history seam',+ async ({ historyId, firstId, liveIds, ancestor, count }) => {+ let resolveLogs: (value: unknown) => void = () => {}+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(+ new Promise((resolve) => (resolveLogs = resolve)) as any+ )+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({+ status: 'in_progress',+ state: ancestor ? { resume_from_run_id: 'ancestor-run' } : {},+ } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ await MockStream.latest().emitOpen()++ const repeated = sessionUpdate({+ sessionUpdate: 'agent_message',+ messageId: 'm1',+ content: { text: 'ping' },+ })+ for (const [index, eventId] of liveIds.entries()) {+ await MockStream.latest().emitMessage({ ...repeated, event_id: eventId }, `${index + 1}-0`)+ }++ resolveLogs([+ ...(ancestor ? [notification('_posthog/run_started', { runId: 'ancestor-run' })] : []),+ { ...repeated, event_id: historyId, first_event_id: firstId },+ ])+ await flushPromises()++ expect(+ logic.values.threadItems+ .filter((item) => item.type === 'assistant_message')+ .map((item) => item.text)+ ).toEqual(Array(count).fill('ping'))+ }+ )})describe('replayOnly viewer (read-only)', () => {diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex f6855f42cdd4..f20c9d4154ee 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -378,6 +378,8 @@ function normalizeNotificationEntry(entry: unknown): StoredLogEntry | null {type: 'notification',...(typeof entry.timestamp === 'string' ? { timestamp: entry.timestamp } : {}),...(typeof entry.source_run_id === 'string' ? { source_run_id: entry.source_run_id } : {}),+ ...(typeof entry.event_id === 'string' ? { event_id: entry.event_id } : {}),+ ...(typeof entry.first_event_id === 'string' ? { first_event_id: entry.first_event_id } : {}),notification: entry.notification,} as StoredLogEntry}@@ -915,18 +917,17 @@ function isResumeContextPrompt(text: string): boolean {return text.startsWith(RESUME_CONTEXT_PREFIX)}-/**- * One-shot multiset reconciliation of the bootstrap seam (port of the reference client's- * `drainBufferedLogBatches`). While the S3 history loads we connect the live SSE first and buffer- * its frames; some buffered frames are the same logical entries the history already contains (the- * live stream and the S3 log overlap around the connect cutoff). This drops each buffered frame a- * historical frame accounts for, keyed on the ACP `notification` payload — the only field identical- * across both copies. The SSE `id` is the Redis stream id (absent from S3), and the envelope- * `timestamp` is stamped independently on the persist and the live-publish paths, so neither can be- * part of the key. A *multiset* (counts, not a set) so N genuine repeats of an identical payload- * survive: each historical copy absorbs exactly one buffered copy, and any buffered surplus passes- * through. Steady-state live frames after the drain are appended directly and never deduped.- */+function parseAgentEventId(eventId: string): { boot: string; sequence: number } | null {+ const match = /^(.+)-(\d+)$/.exec(eventId)+ if (!match) {+ return null+ }+ const sequence = Number(match[2])+ return Number.isSafeInteger(sequence) ? { boot: match[1], sequence } : null+}++// The persisted log coalesces chunks and strips adapter fields, so payload equality cannot identify+// modern overlap. Agent event IDs survive both paths; SSE IDs and timestamps do not.function dedupeBufferedAgainstHistory(buffered: StoredLogEntry[], history: StoredLogEntry[]): StoredLogEntry[] {const seamKey = (entry: StoredLogEntry): string =>JSON.stringify([@@ -936,17 +937,67 @@ function dedupeBufferedAgainstHistory(buffered: StoredLogEntry[], history: Store: undefined,entry.notification,])- const historicalCounts = new Map<string, number>()- for (const entry of history) {+ const historicalEntries = new Map<string, number[]>()+ const eventIds = new Map<string, number>()+ const eventRanges = new Map<string, { first: number; last: number; index: number }[]>()+ const hasEventId = (entry: StoredLogEntry): entry is StoredLogEntry & { event_id: string } =>+ typeof entry.event_id === 'string' && entry.event_id !== ''+ for (const [index, entry] of history.entries()) {const key = seamKey(entry)- historicalCounts.set(key, (historicalCounts.get(key) ?? 0) + 1)+ const entries = historicalEntries.get(key) ?? []+ entries.push(index)+ historicalEntries.set(key, entries)+ if (!hasEventId(entry) || !entry.source_run_id) {+ continue+ }+ eventIds.set(JSON.stringify([entry.source_run_id, entry.event_id]), index)+ if (typeof entry.first_event_id !== 'string' || !entry.first_event_id) {+ continue+ }+ eventIds.set(JSON.stringify([entry.source_run_id, entry.first_event_id]), index)+ const first = parseAgentEventId(entry.first_event_id)+ const last = parseAgentEventId(entry.event_id)+ if (first && last && first.boot === last.boot && first.sequence <= last.sequence) {+ const rangeKey = JSON.stringify([entry.source_run_id, first.boot])+ const ranges = eventRanges.get(rangeKey) ?? []+ ranges.push({ first: first.sequence, last: last.sequence, index })+ eventRanges.set(rangeKey, ranges)+ }}+ const consumedHistory = new Set<number>()const survivors: StoredLogEntry[] = []for (const entry of buffered) {+ let coveredIndex = hasEventId(entry)+ ? eventIds.get(JSON.stringify([entry.source_run_id, entry.event_id]))+ : undefined+ if (coveredIndex === undefined && hasEventId(entry)) {+ const parsed = parseAgentEventId(entry.event_id)+ if (parsed) {+ coveredIndex = eventRanges+ .get(JSON.stringify([entry.source_run_id, parsed.boot]))+ ?.find(({ first, last }) => first <= parsed.sequence && parsed.sequence <= last)?.index+ }+ }+ if (coveredIndex !== undefined) {+ consumedHistory.add(coveredIndex)+ continue+ }++ // Legacy overlap remains a multiset: each historical copy absorbs only one live copy.+ // Different stable IDs establish distinct events even when their payloads are identical.const key = seamKey(entry)- const remaining = historicalCounts.get(key) ?? 0- if (remaining > 0) {- historicalCounts.set(key, remaining - 1)+ const matchingIndex = historicalEntries+ .get(key)+ ?.find(+ (index) =>+ !consumedHistory.has(index) &&+ (!hasEventId(entry) || !hasEventId(history[index])) &&+ (!entry.source_run_id ||+ !history[index].source_run_id ||+ entry.source_run_id === history[index].source_run_id)+ )+ if (matchingIndex !== undefined) {+ consumedHistory.add(matchingIndex)continue}survivors.push(entry)diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 88fd1b63e5df..4ad515c73770 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -3,7 +3,9 @@ import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { phaiAiComposerSeedLogic } from 'scenes/max/phaiAiComposerSeedLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'+import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -95,74 +97,80 @@ describe('taskTrackerSceneLogic', () => {})it.each([- [false, ''],- [true, ''],- [true, 'A different task'],- ] as const)('handles a startup stop and draft when leaving=%s with a new draft=%s', async (leave, newDraft) => {- let finishCreation!: (response: [number, Record<string, unknown>]) => void- const creation = new Promise<[number, Record<string, unknown>]>((resolve) => {- finishCreation = resolve- })- let createdTasks: Task[] = []- useMocks({- get: { '/api/projects/:team/tasks/': () => [200, { results: createdTasks, count: createdTasks.length }] },- post: { '/api/projects/:team/tasks/': () => creation },- })- logic.mount()- await expectLogic(logic).toFinishAllListeners()- router.actions.push('/tasks/new')- logic.actions.setNewTaskData({ description: 'A synthetic task' })- logic.actions.submitNewTask()- const streamKey = logic.values.activeCreation!.streamKey- expect(runStreamLogic({ streamKey }).values.threadItems).toEqual([- expect.objectContaining({ type: 'human_message', text: 'A synthetic task' }),- ])- expect(runStreamLogic({ streamKey }).values.streamPhase).toBe('provisioning')- const cancellation = runCancellationLogic({ streamKey })- const unmount = cancellation.mount()- try {- cancellation.actions.requestCancellation()- logic.actions.setStartupDraft('A follow-up draft')- if (leave) {- router.actions.push('/tasks/another-task')- }- if (newDraft) {- router.actions.push('/tasks/new')- logic.actions.setNewTaskData({ description: newDraft })- }- createdTasks = [buildTask({ id: 'new-task', description: 'A synthetic task' })]- await expectLogic(logic, () =>- finishCreation([- 200,- {- id: 'new-task',- latest_run: { id: 'run-1' },- },- ])- ).toFinishAllListeners()- if (leave) {- expect(logic.values.activeCreation).toBeNull()- expect(cancellation.values.cancellationState).toBeNull()- expect(router.values.location.pathname).toContain(newDraft ? '/tasks/new' : '/tasks/another-task')- expect(toolEvents.values.applyBackTargetClaims[streamKey]).toBeUndefined()- } else {- expect(logic.values.activeCreation).toEqual({- streamKey,- interactionKey: streamKey,- composerWasFocused: false,- taskId: 'new-task',- runId: 'run-1',- draft: 'A follow-up draft',- })- expect(cancellation.values.cancellationState).toBe('waiting')+ [null, ''],+ ['/tasks/another-task', ''],+ ['/tasks/another-task', 'A different task'],+ ['/activity/explore', ''],+ ] as const)(+ 'handles a startup stop and draft when navigating to %s with a new draft=%s',+ async (destination, newDraft) => {+ let finishCreation!: (response: [number, Record<string, unknown>]) => void+ const creation = new Promise<[number, Record<string, unknown>]>((resolve) => {+ finishCreation = resolve+ })+ let createdTasks: Task[] = []+ useMocks({+ get: {+ '/api/projects/:team/tasks/': () => [200, { results: createdTasks, count: createdTasks.length }],+ },+ post: { '/api/projects/:team/tasks/': () => creation },+ })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ router.actions.push('/tasks/new')+ logic.actions.setNewTaskData({ description: 'A synthetic task' })+ logic.actions.submitNewTask()+ const streamKey = logic.values.activeCreation!.streamKey+ expect(runStreamLogic({ streamKey }).values.threadItems).toEqual([+ expect.objectContaining({ type: 'human_message', text: 'A synthetic task' }),+ ])+ expect(runStreamLogic({ streamKey }).values.streamPhase).toBe('provisioning')+ const cancellation = runCancellationLogic({ streamKey })+ const unmount = cancellation.mount()+ try {+ cancellation.actions.requestCancellation()+ logic.actions.setStartupDraft('A follow-up draft')+ if (destination) {+ router.actions.push(destination)+ }+ if (newDraft) {+ router.actions.push('/tasks/new')+ logic.actions.setNewTaskData({ description: newDraft })+ }+ createdTasks = [buildTask({ id: 'new-task', description: 'A synthetic task' })]+ await expectLogic(logic, () =>+ finishCreation([+ 200,+ {+ id: 'new-task',+ latest_run: { id: 'run-1' },+ },+ ])+ ).toFinishAllListeners()+ if (destination) {+ expect(logic.values.activeCreation).toBeNull()+ expect(cancellation.values.cancellationState).toBeNull()+ expect(router.values.location.pathname).toContain(newDraft ? '/tasks/new' : destination)+ expect(toolEvents.values.applyBackTargetClaims[streamKey]).toBeUndefined()+ } else {+ expect(logic.values.activeCreation).toEqual({+ streamKey,+ interactionKey: streamKey,+ composerWasFocused: false,+ taskId: 'new-task',+ runId: 'run-1',+ draft: 'A follow-up draft',+ })+ expect(cancellation.values.cancellationState).toBe('waiting')+ }+ expect(logic.values.newTaskData.description).toBe(newDraft)+ expect(logic.values.isSubmittingTask).toBe(false)+ await waitFor(() => expect(logic.values.tasks).toEqual(createdTasks))+ } finally {+ unmount()}- expect(logic.values.newTaskData.description).toBe(newDraft)- expect(logic.values.isSubmittingTask).toBe(false)- await waitFor(() => expect(logic.values.tasks).toEqual(createdTasks))- } finally {- unmount()}- })+ )it('loads PostHog Desktop access and exposes it to the task UI', async () => {logic.mount()@@ -532,23 +540,26 @@ describe('taskTrackerSceneLogic', () => {// 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+ it.each(['/tasks/some-other-task', '/activity/explore'])(+ 'keeps an embedded creation in place after navigation to %s',+ async (destination) => {+ 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()+ 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' })+ 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' })+ router.actions.push(destination)+ expect(panelLogic.values.activeCreation).toMatchObject({ taskId: 'new-task' })- panelLogic.unmount()- })+ 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.@@ -600,6 +611,52 @@ describe('taskTrackerSceneLogic', () => {expect(router.values.location.pathname).toContain(expectedPath ?? initialPath)})+ it.each([null, '/activity/explore'])('keeps a URL prompt attached until navigation to %s', async (destination) => {+ let finishCreation!: (response: [number, Record<string, unknown>]) => void+ const creation = new Promise<[number, Record<string, unknown>]>((resolve) => {+ finishCreation = resolve+ })+ let createCount = 0+ useMocks({+ post: {+ '/api/projects/:team/tasks/': async ({ request }) => {+ createCount+++ createBody = (await request.json()) as Record<string, unknown>+ return creation+ },+ },+ })+ router.actions.push(urls.ai(undefined, 'analyze churn'))+ const unmountBridge = phaiAiComposerSeedLogic().mount()+ try {+ logic.mount()+ const streamKey = logic.values.activeCreation!.streamKey+ expect(runStreamLogic({ streamKey }).values.threadItems).toEqual([+ expect.objectContaining({ type: 'human_message', text: 'analyze churn' }),+ ])+ if (destination) {+ router.actions.push(destination)+ expect(logic.values.activeCreation).toBeNull()+ }+ await expectLogic(logic, () =>+ finishCreation([200, { id: 'new-task', latest_run: { id: 'run-1' } }])+ ).toFinishAllListeners()++ expect(createBody).toMatchObject({ description: 'analyze churn' })+ expect(createCount).toBe(1)+ if (destination) {+ expect(logic.values.activeCreation).toBeNull()+ expect(router.values.location.pathname).toContain(destination)+ } else {+ expect(logic.values.activeCreation).toMatchObject({ taskId: 'new-task', runId: 'run-1' })+ expect(router.values.location.pathname).toContain('/tasks/new-task')+ }+ } finally {+ finishCreation([200, { id: 'new-task', latest_run: { id: 'run-1' } }])+ unmountBridge()+ }+ })+// A CTA opens the panel and stamps its prompt onto composerSeedLogic BEFORE the composer mounts, so the// seed must be picked up on mount — this is the live breakage the seam fixes (the prompt was dropped).// autoSubmit=false must only prefill, never send. Guards the afterMount pickup, the consume-once clear,diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex cb141181893a..20026fe2aa55 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -654,6 +654,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>(['active-creation',{ pauseOnPageHidden: false })+ cache.creationPath = router.values.location.pathnameactions.setActiveCreation({ streamKey, interactionKey: streamKey })stream.actions.startOptimisticRun(description)@@ -907,21 +908,27 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([},})),- urlToAction(({ actions, values, props }) => {+ urlToAction(({ actions, values, props, cache }) => {// 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`. Before attachment, only `/tasks/new` owns the creation.+ // task, the list, or back to `/tasks/new`. Before attachment, the starting page owns the creation,+ // including `/ai` when its URL prompt submits before this logic finishes mounting.const clearIfLeftCreatedTask = (taskId?: string): void => {const activeCreation = values.activeCreation- if (activeCreation && (activeCreation.taskId ? activeCreation.taskId !== taskId : taskId !== 'new')) {+ if (+ activeCreation &&+ (activeCreation.taskId+ ? activeCreation.taskId !== taskId+ : router.values.location.pathname !== cache.creationPath)+ ) {actions.clearActiveCreation()}}return {// 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)),+ '*': () => (props.panelId ? undefined : clearIfLeftCreatedTask()),}}),])diff --git a/products/posthog_ai/frontend/types/wireTypes.ts b/products/posthog_ai/frontend/types/wireTypes.tsindex 0a3d2ad60e26..0adc39ee8bae 100644--- a/products/posthog_ai/frontend/types/wireTypes.ts+++ b/products/posthog_ai/frontend/types/wireTypes.ts@@ -28,6 +28,8 @@ export interface AcpNotification {*/export interface StoredLogEntry {type: 'notification'+ event_id?: string+ first_event_id?: string/** Client-side ownership; the shared backend log payload stays unchanged. */source_run_id?: stringtimestamp?: stringdiff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex d451aab06655..19f267da9369 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -1,5 +1,3 @@-from types import SimpleNamespace-from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase, TestCase, override_settings@@ -175,7 +173,7 @@ class TestRunStateSnapshotPaths(TestCase):assert RunState.model_validate(state).resume_snapshot_carry_state() == expected-class TestGetSandboxMcpConfigs(TestCase):+class TestGetSandboxMcpConfigs(SimpleTestCase):TOKEN = "phx_test_token"PROJECT_ID = 42@@ -352,18 +350,30 @@ class TestGetSandboxMcpConfigs(TestCase):@parameterized.expand([- (None, False, "posthog-code"),- ("", False, "posthog-code"),- ("posthog-code", False, "posthog-code"),- ("some-other-origin", False, "posthog-code"),- ("slack", False, "slack"),- ("workflow", True, "slack"),- ("posthog_ai", False, "posthog_ai"),- ("eval", False, "eval"),+ (None, False, None, "posthog-code"),+ ("", False, None, "posthog-code"),+ ("posthog-code", False, None, "posthog-code"),+ ("some-other-origin", False, None, "posthog-code"),+ ("slack", False, None, "slack"),+ ("workflow", True, None, "slack"),+ ("posthog_ai", False, None, "posthog_ai"),+ ("eval", False, None, "eval"),+ (None, False, "posthog_ai", "posthog_ai"),+ ("", False, "posthog_ai", "posthog_ai"),+ (None, True, "posthog_ai", "slack"),+ ("slack", False, "posthog_ai", "slack"),+ ("eval", False, "posthog_ai", "eval"),+ ("posthog-code", False, "posthog_ai", "posthog-code"),+ ("some-other-origin", False, "posthog_ai", "posthog-code"),+ (None, False, "signals_scout", "posthog-code"),])def test_consumer_header_reflects_reply_context(- self, interaction_origin: str | None, slack_reply_context: bool, expected_consumer: str+ self,+ interaction_origin: str | None,+ slack_reply_context: bool,+ origin_product: str | None,+ expected_consumer: str,) -> None:with patch("products.tasks.backend.temporal.process_task.utils.settings") as mock_settings:mock_settings.SANDBOX_MCP_URL = None@@ -373,13 +383,17 @@ class TestGetSandboxMcpConfigs(TestCase):self.PROJECT_ID,interaction_origin=interaction_origin,slack_reply_context=slack_reply_context,+ origin_product=origin_product,)assert configs == [McpServerConfig(type="http",name="posthog",url="https://mcp.posthog.com/mcp",- headers=self._expected_headers(consumer=expected_consumer),+ headers=[+ *self._expected_headers(consumer=expected_consumer),+ *([{"name": "X-PostHog-Task-Origin", "value": origin_product}] if origin_product else []),+ ],description=POSTHOG_MCP_DESCRIPTION,)]@@ -421,7 +435,7 @@ class TestMcpServerConfigToDict(TestCase):}-class TestFetchUserMcpServerConfigs(TestCase):+class TestFetchUserMcpServerConfigs(SimpleTestCase):TOKEN = "phx_test_token"TEAM_ID = 42USER_ID = 7@@ -520,12 +534,13 @@ class TestFetchUserMcpServerConfigs(TestCase):@parameterized.expand([- ("slack", False, "slack"),- ("workflow", True, "slack"),- ("posthog_ai", False, "posthog_ai"),- ("eval", False, "eval"),- ("posthog_code", False, "posthog-code"),- (None, False, "posthog-code"),+ ("slack", False, None, "slack"),+ ("workflow", True, None, "slack"),+ ("posthog_ai", False, None, "posthog_ai"),+ ("eval", False, None, "eval"),+ ("posthog_code", False, None, "posthog-code"),+ (None, False, None, "posthog-code"),+ (None, False, "posthog_ai", "posthog_ai"),])@patch(MOCK_API_URL)@@ -534,6 +549,7 @@ class TestFetchUserMcpServerConfigs(TestCase):self,interaction_origin: str | None,slack_reply_context: bool,+ origin_product: str | None,expected_consumer: str,mock_facade,mock_api_url,@@ -547,6 +563,7 @@ class TestFetchUserMcpServerConfigs(TestCase):self.USER_ID,interaction_origin=interaction_origin,slack_reply_context=slack_reply_context,+ origin_product=origin_product,)assert configs[0].headers == self._expected_user_headers(consumer=expected_consumer)@@ -1516,24 +1533,36 @@ class TestIsBotAuthorshipFallback(_AuthorshipFixture):class TestMcpExecSkillsEnvVars(SimpleTestCase):@parameterized.expand([- ("web_phai_flag_on", "posthog_ai", True, True),- ("slack_flag_on", "slack", True, True),- ("eval_flag_on", "eval", True, True),- ("desktop_keeps_bundled_skills_even_with_flag_on", None, True, False),- ("web_phai_flag_off", "posthog_ai", False, False),+ ("web_phai_flag_on", "posthog_ai", None, True, True),+ ("slack_flag_on", "slack", None, True, True),+ ("eval_flag_on", "eval", None, True, True),+ ("desktop_keeps_bundled_skills_even_with_flag_on", None, None, True, False),+ ("web_phai_flag_off", "posthog_ai", None, False, False),+ ("web_phai_task_without_interaction_origin_flag_on", None, "posthog_ai", True, True),+ ("web_phai_task_without_interaction_origin_flag_off", None, "posthog_ai", False, False),])def test_strips_bundled_skills_only_for_learn_capable_runs_with_the_flag_on(- self, _name: str, interaction_origin: str | None, flag_enabled: bool, expect_stripped: bool+ self,+ _name: str,+ interaction_origin: str | None,+ origin_product: str | None,+ flag_enabled: bool,+ expect_stripped: bool,) -> None:- ctx = SimpleNamespace(interaction_origin=interaction_origin, organization_id="org-1", distinct_id="user-1")+ ctx = MagicMock(+ interaction_origin=interaction_origin,+ origin_product=origin_product,+ organization_id="org-1",+ distinct_id="user-1",+ )with patch("products.tasks.backend.temporal.process_task.utils.is_mcp_exec_skills_enabled", return_value=flag_enabled) as flag_check:env = mcp_exec_skills_env_vars(ctx)assert env == ({"POSTHOG_CODE_DISABLE_BUNDLED_SKILLS": "1"} if expect_stripped else {})- if interaction_origin is None:+ if interaction_origin is None and origin_product is None:flag_check.assert_not_called()else:flag_check.assert_called_once_with("org-1", "user-1")diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 80f06a1f9816..e2e05fd0dbdc 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -59,6 +59,9 @@ if TYPE_CHECKING:from posthog.models.user import Userfrom products.tasks.backend.models import SandboxSnapshot, Task, TaskRun+ from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (+ TaskProcessingContext,+ )logger = logging.getLogger(__name__)@@ -598,7 +601,9 @@ def get_user_mcp_server_configs(allowed_gateway_server_ids=allowed_gateway_server_ids,)api_base = get_sandbox_api_url().rstrip("/")- consumer = _resolve_mcp_consumer(interaction_origin, slack_reply_context=slack_reply_context)+ consumer = _resolve_mcp_consumer(+ interaction_origin, slack_reply_context=slack_reply_context, origin_product=origin_product+ )configs: list[McpServerConfig] = []for installation in installations:@@ -714,12 +719,16 @@ def get_imported_mcp_server_configs(task_run: TaskRun, existing_names: Iterable[return build_imported_mcp_server_configs(task_run.imported_mcp_servers, existing_names)-def _resolve_mcp_consumer(interaction_origin: str | None, *, slack_reply_context: bool = False) -> str:+def _resolve_mcp_consumer(+ interaction_origin: str | None, *, slack_reply_context: bool = False, origin_product: str | None = None+) -> str:"""Map the task's reply context to the `x-posthog-mcp-consumer` value.Slack reply contexts send `"slack"`, posthog_ai (Max) runs send `"posthog_ai"`,and eval harness runs send `"eval"`; everything else (the PostHog Desktop UI,- API callers, missing origin) is treated as PostHog Desktop. Only `"posthog-code"` is a UI-apps host+ API callers, missing origin) is treated as PostHog Desktop. Browser-created+ PostHog AI runs can lack an interaction origin, so their task origin selects+ the consumer that retains native widget data. Only `"posthog-code"` is a UI-apps hoston the MCP server — it gates UI-apps payload emission, so `"posthog_ai"` and`"slack"` deliberately don't get UI apps. Keep the `"posthog-code"` literalin sync with `POSTHOG_CODE_CONSUMER` in@@ -727,21 +736,21 @@ def _resolve_mcp_consumer(interaction_origin: str | None, *, slack_reply_context"""if slack_reply_context or interaction_origin == "slack":return "slack"- if interaction_origin == "posthog_ai":+ if interaction_origin == "posthog_ai" or (not interaction_origin and origin_product == "posthog_ai"):return "posthog_ai"if interaction_origin == EVAL_INTERACTION_ORIGIN:return EVAL_INTERACTION_ORIGINreturn "posthog-code"-def mcp_exec_skills_env_vars(ctx) -> dict[str, str]:+def mcp_exec_skills_env_vars(ctx: TaskProcessingContext) -> dict[str, str]:"""Env that launches the sandbox without bundled product skills when this run gets themthrough the MCP `learn` command instead.Desktop runs keep their bundled skills: the MCP server excludes the `posthog-code`consumer from `learn`, so stripping them there would leave the agent with no skills."""- if _resolve_mcp_consumer(ctx.interaction_origin) == "posthog-code":+ if _resolve_mcp_consumer(ctx.interaction_origin, origin_product=ctx.origin_product) == "posthog-code":return {}if not is_mcp_exec_skills_enabled(ctx.organization_id, ctx.distinct_id):return {}@@ -794,7 +803,9 @@ def get_sandbox_ph_mcp_configs({"name": "x-posthog-read-only", "value": str(read_only).lower()},{"name": "x-posthog-mcp-consumer",- "value": _resolve_mcp_consumer(interaction_origin, slack_reply_context=slack_reply_context),+ "value": _resolve_mcp_consumer(+ interaction_origin, slack_reply_context=slack_reply_context, origin_product=origin_product+ ),},]if task_id: