Skip to content

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

fix(posthog-ai): show approval cards live and expire stale approvals (#114416)

Shy Alter1deada935c80
diff --git a/ee/hogai/api/serializers.py b/ee/hogai/api/serializers.py
index 64a94c0fad05..d6cdb78a5410 100644
--- a/ee/hogai/api/serializers.py
+++ b/ee/hogai/api/serializers.py
@@ -7,6 +7,8 @@ from langgraph.graph.state import CompiledStateGraph
from rest_framework import serializers
from rest_framework_dataclasses.serializers import DataclassSerializer
+from posthog.schema import ApprovalDecisionStatus
+
from posthog.api.shared import UserBasicSerializer
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
@@ -19,7 +21,7 @@ from products.tasks.backend.facade.run_config import REASONING_EFFORTS, LLMProvi
from ee.hogai.artifacts.manager import ArtifactManager
from ee.hogai.chat_agent import AssistantGraph
from ee.hogai.research_agent.graph import ResearchAgentGraph
-from ee.hogai.tool import PENDING_APPROVAL_STATUS
+from ee.hogai.tool import ApprovalRequest, pending_approval_proposal_id
from ee.hogai.utils.helpers import should_output_assistant_message
from ee.hogai.utils.types import AssistantState
from ee.hogai.utils.types.composed import AssistantMaxGraphState
@@ -94,11 +96,15 @@ async def aget_conversation_state(
# Extract interrupt payloads from pending tasks — the single source of truth for payload data.
interrupt_payloads: dict[str, dict[str, Any]] = {}
for task in snapshot.tasks:
+ if task.result is not None:
+ continue
for interrupt in task.interrupts:
- if isinstance(interrupt.value, dict) and interrupt.value.get("status") == PENDING_APPROVAL_STATUS:
- proposal_id = interrupt.value.get("proposal_id")
- if proposal_id:
- interrupt_payloads[proposal_id] = interrupt.value
+ proposal_id = pending_approval_proposal_id(interrupt.value)
+ if proposal_id:
+ value = interrupt.value
+ interrupt_payloads[proposal_id] = (
+ value.model_dump() if isinstance(value, ApprovalRequest) else value
+ )
return ConversationStateResult(
state=state, has_unsupported_content=False, interrupt_payloads=interrupt_payloads
@@ -379,6 +385,12 @@ class ConversationSerializer(ConversationMinimalSerializer):
decision_status = decision_data.get("decision_status")
if not tool_name or not preview or not decision_status:
continue
+ if (
+ decision_status == ApprovalDecisionStatus.PENDING
+ and cached_state.state is not None
+ and proposal_id not in cached_state.interrupt_payloads
+ ):
+ decision_status = ApprovalDecisionStatus.AUTO_REJECTED
# Get payload from checkpoint interrupts (single source of truth)
payload = cached_state.interrupt_payloads.get(proposal_id, {}).get("payload", {})
diff --git a/ee/hogai/api/tests/test_serializers.py b/ee/hogai/api/tests/test_serializers.py
index c355982c9f97..edd85984f96a 100644
--- a/ee/hogai/api/tests/test_serializers.py
+++ b/ee/hogai/api/tests/test_serializers.py
@@ -2,7 +2,9 @@ from dataclasses import replace
from uuid import uuid4
from posthog.test.base import APIBaseTest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from parameterized import parameterized
from posthog.schema import (
AgentMode,
@@ -24,6 +26,7 @@ from ee.hogai.api.serializers import (
TaskSerializer,
)
from ee.hogai.chat_agent import AssistantGraph
+from ee.hogai.tool import ApprovalRequest
from ee.hogai.utils.types import AssistantState
from ee.hogai.utils.types.base import ArtifactRefMessage
@@ -157,6 +160,41 @@ class TestConversationSerializers(APIBaseTest):
self.assertEqual(len(data["messages"]), 1)
self.assertFalse(data["has_unsupported_content"])
+ @parameterized.expand([("checkpoint_loaded", True), ("checkpoint_read_failed", False)])
+ def test_pending_approval_without_live_interrupt_is_auto_rejected(self, _name: str, checkpoint_loads: bool):
+ conversation = Conversation.objects.create(
+ user=self.user,
+ team=self.team,
+ title="Approvals",
+ type=Conversation.Type.ASSISTANT,
+ approval_decisions={
+ "live": {"decision_status": "pending", "tool_name": "create_insight", "preview": "Update"},
+ "stale": {"decision_status": "pending", "tool_name": "create_insight", "preview": "Older update"},
+ },
+ )
+ live_request = ApprovalRequest(
+ proposal_id="live", tool_name="create_insight", preview="Update", payload={"insight_id": "abc"}
+ )
+
+ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock) as mock_get_state:
+ if checkpoint_loads:
+
+ class MockSnapshot:
+ values = AssistantState(messages=[]).model_dump()
+ tasks = [MagicMock(result=None, interrupts=[MagicMock(value=live_request)])]
+
+ mock_get_state.return_value = MockSnapshot()
+ else:
+ mock_get_state.side_effect = RuntimeError("checkpoint unavailable")
+
+ data = ConversationSerializer(conversation, context={"team": self.team, "user": self.user}).data
+
+ approvals = {a["proposal_id"]: (a["decision_status"], a["payload"]) for a in data["pending_approvals"]}
+ if checkpoint_loads:
+ self.assertEqual(approvals, {"live": ("pending", {"insight_id": "abc"}), "stale": ("auto_rejected", {})})
+ else:
+ self.assertEqual(approvals, {"live": ("pending", {}), "stale": ("pending", {})})
+
def test_agent_mode_defaults_when_missing(self):
conversation = Conversation.objects.create(
user=self.user, team=self.team, title="Conversation without agent mode", type=Conversation.Type.ASSISTANT
diff --git a/ee/hogai/core/executor.py b/ee/hogai/core/executor.py
index b09c5fdd76c2..976ae797a649 100644
--- a/ee/hogai/core/executor.py
+++ b/ee/hogai/core/executor.py
@@ -26,6 +26,7 @@ from ee.hogai.queue import ConversationQueueStore
from ee.hogai.stream.redis_stream import (
CONVERSATION_STREAM_MAX_LENGTH,
CONVERSATION_STREAM_TIMEOUT,
+ ApprovalEvent,
ConversationEvent,
ConversationRedisStream,
GenerationStatusEvent,
@@ -300,6 +301,8 @@ class AgentExecutor:
return (AssistantEventType.UPDATE, message.event.payload)
elif isinstance(message.event, GenerationStatusEvent):
return (AssistantEventType.STATUS, message.event.payload)
+ elif isinstance(message.event, ApprovalEvent):
+ return (AssistantEventType.APPROVAL, message.event.payload)
else:
return None
diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.py
index 0122ad22d986..5824ce57bf42 100644
--- a/ee/hogai/core/runner.py
+++ b/ee/hogai/core/runner.py
@@ -21,6 +21,7 @@ from opentelemetry import trace
from posthoganalytics.ai.langchain.callbacks import CallbackHandler, GenerationMetadata
from posthog.schema import (
+ ApprovalDecisionStatus,
AssistantEventType,
AssistantGenerationStatusEvent,
AssistantMessage,
@@ -47,7 +48,7 @@ from ee.hogai.core.ai_event_truncation import ai_event_truncator
from ee.hogai.core.base import BaseAssistantGraph
from ee.hogai.core.stream_processor import AssistantStreamProcessorProtocol
from ee.hogai.llm import POSTHOG_AI_PRODUCT, is_ai_gateway_served
-from ee.hogai.tool import ApprovalRequest, ClientToolCallRequest
+from ee.hogai.tool import ApprovalRequest, ClientToolCallRequest, pending_approval_proposal_id
from ee.hogai.utils.exceptions import (
AGENT_RUN_UNHANDLED_ERROR_COUNTER,
HTTPX_TRANSPORT_EXCEPTIONS,
@@ -528,9 +529,9 @@ class BaseAgentRunner(ABC):
original_tool_call_id=interrupt.value.original_tool_call_id,
message_id=message_id,
)
- yield AssistantEventType.APPROVAL, approval_payload
# Store approval card metadata for persistence (page reload)
await self._store_approval_card_data(approval_payload)
+ yield AssistantEventType.APPROVAL, approval_payload
else:
interrupt_message = interrupt.value
interrupt_messages.append(interrupt_message)
@@ -589,6 +590,17 @@ class BaseAgentRunner(ABC):
if message.id is not None:
self._stream_processor.mark_id_as_streamed(message.id)
+ await self._conversation.arefresh_from_db(fields=["approval_decisions"])
+ await self._expire_pending_approvals(
+ keep={
+ proposal_id
+ for task in snapshot.tasks
+ if task.result is None
+ for pending in task.interrupts
+ if (proposal_id := pending_approval_proposal_id(pending.value))
+ }
+ )
+
resume_value = self._resume_payload
if self._resume_payload and self._resume_payload.get("action") in ("approve", "reject"):
proposal_id = self._resume_payload.get("proposal_id")
@@ -598,14 +610,18 @@ class BaseAgentRunner(ABC):
for task in snapshot.tasks
if task.result is None
for pending in task.interrupts
- if isinstance(pending.value, ApprovalRequest) and pending.value.proposal_id == proposal_id
+ if isinstance(proposal_id, str) and pending_approval_proposal_id(pending.value) == proposal_id
),
None,
)
if approval_interrupt is None:
- raise ValueError("Approval does not match a pending operation")
- # A scalar resume targets the next interrupt, which may belong to a different approval card.
- resume_value = {approval_interrupt.interrupt_id: self._resume_payload}
+ if not self._latest_message:
+ raise ValueError("Approval does not match a pending operation")
+ self._resume_payload = None
+ resume_value = None
+ else:
+ # A scalar resume targets the next interrupt, which may belong to a different approval card.
+ resume_value = {approval_interrupt.interrupt_id: self._resume_payload}
# If there are pending nodes (snapshot.next is non-empty), we need to resume.
# This happens when:
@@ -644,6 +660,8 @@ class BaseAgentRunner(ABC):
# Return None to resume from checkpoint
return None
+ await self._expire_pending_approvals(keep=set())
+
# Add the latest message id to streamed messages, so we don't send it multiple times.
if self._latest_message and self._latest_message.id is not None:
self._stream_processor.mark_id_as_streamed(self._latest_message.id)
@@ -764,6 +782,7 @@ class BaseAgentRunner(ABC):
checkpoint's interrupt value (single source of truth). The serializer fetches it from there.
"""
# Only store if not already in approval_decisions (don't overwrite resolved status)
+ await self._conversation.arefresh_from_db(fields=["approval_decisions"])
if approval.proposal_id in self._conversation.approval_decisions:
return
@@ -797,3 +816,19 @@ class BaseAgentRunner(ABC):
self._conversation.approval_decisions[proposal_id]["decision_status"] = status
await self._conversation.asave(update_fields=["approval_decisions"])
+
+ def _pending_proposal_ids(self, keep: set[str]) -> list[str]:
+ return [
+ proposal_id
+ for proposal_id, decision in self._conversation.approval_decisions.items()
+ if proposal_id not in keep
+ and isinstance(decision, dict)
+ and decision.get("decision_status") == ApprovalDecisionStatus.PENDING
+ ]
+
+ async def _expire_pending_approvals(self, keep: set[str]) -> None:
+ expired_ids = self._pending_proposal_ids(keep)
+ for proposal_id in expired_ids:
+ self._conversation.approval_decisions[proposal_id]["decision_status"] = ApprovalDecisionStatus.AUTO_REJECTED
+ if expired_ids:
+ await self._conversation.asave(update_fields=["approval_decisions"])
diff --git a/ee/hogai/core/test/test_agent_executor.py b/ee/hogai/core/test/test_agent_executor.py
index 3b9429280e47..0c1d69d4fec3 100644
--- a/ee/hogai/core/test/test_agent_executor.py
+++ b/ee/hogai/core/test/test_agent_executor.py
@@ -17,6 +17,7 @@ from products.posthog_ai.backend.models.assistant import Conversation
from ee.hogai.core.executor import AgentExecutor
from ee.hogai.stream.redis_stream import (
+ ApprovalEvent,
ConversationEvent,
MessageEvent,
StatusPayload,
@@ -25,7 +26,8 @@ from ee.hogai.stream.redis_stream import (
StreamStatusEvent,
get_conversation_stream_key,
)
-from ee.hogai.utils.types.base import AssistantOutput
+from ee.hogai.utils.sse import AssistantSSESerializer
+from ee.hogai.utils.types.base import ApprovalPayload, AssistantOutput
class TestAgentExecutor(BaseTest):
@@ -257,6 +259,26 @@ class TestAgentExecutor(BaseTest):
await self.manager._redis_stream_to_assistant_output(event)
+ async def test_redis_stream_approval_event_reaches_client_as_sse(self):
+ approval = ApprovalPayload(
+ proposal_id="proposal-1",
+ decision_status="pending",
+ tool_name="upsert_dashboard",
+ preview="Remove 2 tiles",
+ payload={"dashboard_id": 1},
+ original_tool_call_id="call-1",
+ message_id="message-1",
+ )
+ event = StreamEvent(event=ApprovalEvent(type=AssistantEventType.APPROVAL, payload=approval))
+
+ result = await self.manager._redis_stream_to_assistant_output(event)
+ assert result is not None
+ sse = await AssistantSSESerializer().dumps(result)
+
+ event_line, data_line, *_ = sse.split("\n")
+ self.assertEqual(event_line, f"event: {AssistantEventType.APPROVAL}")
+ self.assertEqual(ApprovalPayload.model_validate_json(data_line.removeprefix("data: ")), approval)
+
async def test_redis_stream_to_assistant_output_unknown_event(self):
"""Test conversion with unknown event type."""
status_data = StreamStatusEvent(payload=StatusPayload(status="complete"))
diff --git a/ee/hogai/core/test/test_runner.py b/ee/hogai/core/test/test_runner.py
index 551f44b9f5f2..16bb497a5008 100644
--- a/ee/hogai/core/test/test_runner.py
+++ b/ee/hogai/core/test/test_runner.py
@@ -14,7 +14,7 @@ from langgraph.graph import END, START, StateGraph
from langgraph.types import interrupt
from parameterized import parameterized
-from posthog.schema import AssistantEventType, FailureMessage
+from posthog.schema import AssistantEventType, FailureMessage, HumanMessage
from products.posthog_ai.backend.models.assistant import Conversation
@@ -862,6 +862,7 @@ class TestRunnerClientToolCallInterrupt(BaseTest):
approvals = {pending.value.tool_name: pending.value for task in snapshot.tasks for pending in task.interrupts}
for approval in approvals.values():
self.conversation.approval_decisions[approval.proposal_id] = {"decision_status": "pending"}
+ await self.conversation.asave(update_fields=["approval_decisions"])
runner._resume_payload = {"action": action, "proposal_id": approvals["second"].proposal_id}
command = await runner._init_or_update_state()
await graph.ainvoke(command, config)
@@ -883,3 +884,58 @@ class TestRunnerClientToolCallInterrupt(BaseTest):
await graph.ainvoke(await runner._init_or_update_state(), config)
self.assertFalse((await graph.aget_state(config)).next)
self.assertEqual(executed, ["second"] if action == "approve" else [])
+
+ @parameterized.expand(
+ [
+ ("new_message", {"live": "auto_rejected", "stale": "auto_rejected"}),
+ ("stale_response", {"live": "pending", "stale": "auto_rejected"}),
+ ("stale_response_with_message", {"live": "auto_rejected", "stale": "auto_rejected"}),
+ ("live_response", {"live": "approved", "stale": "auto_rejected"}),
+ ]
+ )
+ async def test_unresumable_pending_approval_is_auto_rejected(self, trigger: str, expected: dict[str, str]) -> None:
+ live_id, stale_id = str(uuid4()), str(uuid4())
+
+ def operation(state: AssistantState) -> dict[str, object]:
+ interrupt(ApprovalRequest(proposal_id=live_id, tool_name="create_insight", preview="Update", payload={}))
+ return {}
+
+ builder = StateGraph(AssistantState)
+ builder.add_node("operation", operation)
+ builder.add_edge(START, "operation")
+ builder.add_edge("operation", END)
+ graph = builder.compile(checkpointer=MemorySaver())
+ runner, _ = self._create_runner_with_interrupt(None)
+ runner._graph = graph
+ config = runner._get_config()
+ config["callbacks"] = []
+ await graph.ainvoke(AssistantState(messages=[]), config)
+ self.conversation.approval_decisions = {
+ live_id: {"decision_status": "pending"},
+ stale_id: {"decision_status": "pending"},
+ }
+ await self.conversation.asave(update_fields=["approval_decisions"])
+
+ if trigger == "new_message":
+ runner._latest_message = HumanMessage(content="are you stuck?", id=str(uuid4()))
+ await runner._init_or_update_state()
+ elif trigger == "stale_response_with_message":
+ runner._latest_message = HumanMessage(content="are you stuck?", id=str(uuid4()))
+ runner._resume_payload = {"action": "reject", "proposal_id": stale_id}
+ self.assertIsInstance(await runner._init_or_update_state(), AssistantState)
+ elif trigger == "live_response":
+ runner._resume_payload = {"action": "approve", "proposal_id": live_id}
+ await runner._init_or_update_state()
+ else:
+ runner._resume_payload = {"action": "approve", "proposal_id": stale_id}
+ with self.assertRaisesMessage(ValueError, "Approval does not match a pending operation"):
+ await runner._init_or_update_state()
+
+ await self.conversation.arefresh_from_db()
+ self.assertEqual(
+ {
+ "live": self.conversation.approval_decisions[live_id]["decision_status"],
+ "stale": self.conversation.approval_decisions[stale_id]["decision_status"],
+ },
+ expected,
+ )
diff --git a/ee/hogai/tool.py b/ee/hogai/tool.py
index a5795192d980..1526299b0ea3 100644
--- a/ee/hogai/tool.py
+++ b/ee/hogai/tool.py
@@ -56,6 +56,15 @@ class ApprovalRequest(BaseModel):
original_tool_call_id: str | None = None
+def pending_approval_proposal_id(value: object) -> str | None:
+ if isinstance(value, ApprovalRequest):
+ return value.proposal_id
+ if isinstance(value, dict) and value.get("status") == PENDING_APPROVAL_STATUS:
+ proposal_id = value.get("proposal_id")
+ return proposal_id if isinstance(proposal_id, str) else None
+ return None
+
+
class ClientToolCallRequest(BaseModel):
"""Interrupt payload when a tool hands execution to its client-side handler.
diff --git a/ee/hogai/utils/sse.py b/ee/hogai/utils/sse.py
index dfb35e041c9f..3ad3cef3babb 100644
--- a/ee/hogai/utils/sse.py
+++ b/ee/hogai/utils/sse.py
@@ -9,6 +9,7 @@ from products.posthog_ai.backend.models.assistant import Conversation
from ee.hogai.api.serializers import ConversationMinimalSerializer
from ee.hogai.utils.types import AssistantMessageUnion, AssistantOutput
+from ee.hogai.utils.types.base import ApprovalPayload
class AssistantSSESerializer:
@@ -22,6 +23,8 @@ class AssistantSSESerializer:
return self._serialize_status(cast(AssistantGenerationStatusEvent, event_data))
elif event_type == AssistantEventType.UPDATE:
return self._serialize_update(cast(AssistantUpdateEvent | SubagentUpdateEvent, event_data))
+ elif event_type == AssistantEventType.APPROVAL:
+ return self._serialize_approval(cast(ApprovalPayload, event_data))
else:
raise ValueError(f"Unknown event type: {event_type}")
@@ -40,6 +43,11 @@ class AssistantSSESerializer:
output += f"data: {update.model_dump_json(exclude_none=True)}\n\n"
return output
+ def _serialize_approval(self, approval: ApprovalPayload) -> str:
+ output = f"event: {AssistantEventType.APPROVAL}\n"
+ output += f"data: {approval.model_dump_json(exclude_none=True)}\n\n"
+ return output
+
# `_serialize_conversation` needs to be async, as some serialization CAN involve sneaky sync ORM queries. We can't guarantee it won't.
# In particular, serialization Conversation can involve fetching conversation.user from DB sync. This shouldn't
# be needed, because we SHOULD be doing Conversation.objects.select_related("user"), but async here is a cheap way to safe.
diff --git a/frontend/src/scenes/max/components/InputFormArea.tsx b/frontend/src/scenes/max/components/InputFormArea.tsx
index 75ba6ad21141..14fcffda67f2 100644
--- a/frontend/src/scenes/max/components/InputFormArea.tsx
+++ b/frontend/src/scenes/max/components/InputFormArea.tsx
@@ -353,6 +353,7 @@ interface DangerousOperationInputProps {
function DangerousOperationInput({ operation }: DangerousOperationInputProps): JSX.Element {
const { continueAfterApproval, continueAfterRejection } = useActions(maxThreadLogic)
+ const { streamingActive } = useValues(maxThreadLogic)
const [status, setStatus] = useState<'pending' | 'approving' | 'rejecting' | 'custom'>('pending')
const options: Option[] = [
@@ -397,6 +398,7 @@ function DangerousOperationInput({ operation }: DangerousOperationInputProps): J
allowCustom
customPlaceholder="Explain what you'd like instead..."
onCustomSubmit={handleCustomSubmit}
+ disabled={streamingActive}
loading={isLoading}
loadingMessage={
status === 'approving'
diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.ts
index 452d56d12d2d..13591b2dd996 100644
--- a/frontend/src/scenes/max/maxThreadLogic.test.ts
+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts
@@ -32,12 +32,14 @@ import {
} from '~/queries/schema/schema-assistant-messages'
import { initKeaTests } from '~/test/init'
import {
+ ApprovalDecisionStatus,
Conversation,
ConversationDetail,
ConversationStatus,
ConversationType,
OrganizationType,
InsightShortId,
+ PendingApproval,
} from '~/types'
import { attachedContextLogic, runStreamLogic } from 'products/posthog_ai/frontend/api/logics'
@@ -3142,6 +3144,54 @@ describe('maxThreadLogic', () => {
})
})
+ describe('pending approval selection', () => {
+ const approval = (proposal_id: string, decision_status: ApprovalDecisionStatus): PendingApproval => ({
+ proposal_id,
+ decision_status,
+ tool_name: 'create_insight',
+ preview: `Update insight ${proposal_id}`,
+ payload: {},
+ })
+ const visibleProposal = (): string | undefined => logic.values.activeDangerousOperationApproval?.proposalId
+
+ it('keeps a streamed approval visible after the turn ends and moves past resolved ones', () => {
+ logic.actions.setConversation({
+ ...MOCK_IN_PROGRESS_CONVERSATION,
+ pending_approvals: [approval('stale', 'pending')],
+ })
+ logic.actions.addPendingApprovalData(approval('stale', 'pending'))
+ logic.actions.setResolvedApprovalStatus('stale', 'approved')
+
+ logic.actions.addPendingApprovalData(approval('new', 'pending'))
+ logic.actions.setPendingApproval('new')
+ expect(visibleProposal()).toBe('new')
+
+ logic.actions.completeThreadGeneration()
+ expect(visibleProposal()).toBe('new')
+
+ logic.actions.setPendingApproval('stale')
+ logic.actions.setConversation({
+ ...MOCK_CONVERSATION,
+ pending_approvals: [approval('new', 'pending'), approval('stale', 'auto_rejected')],
+ })
+ expect(visibleProposal()).toBe('new')
+ })
+
+ it('follows the server for approvals it returns and selects none at turn end without a selection', () => {
+ logic.actions.addPendingApprovalData(approval('other', 'pending'))
+ logic.actions.completeThreadGeneration()
+ expect(visibleProposal()).toBeUndefined()
+
+ logic.actions.setConversation({
+ ...MOCK_CONVERSATION,
+ pending_approvals: [approval('other', 'auto_rejected')],
+ })
+ logic.actions.setConversation({ ...MOCK_CONVERSATION, pending_approvals: [approval('other', 'pending')] })
+ expect(logic.values.pendingApprovalsData['other'].decision_status).toBe('pending')
+ expect(visibleProposal()).toBe('other')
+ })
+ })
+
describe('retryCount', () => {
it('starts at 0', () => {
expect(logic.values.retryCount).toBe(0)
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index 3f0661feee29..759eec353777 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -1201,17 +1201,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
(conversation?.pending_approvals ?? []).map((a) => [a.proposal_id, a])
) as Record<string, PendingApproval>
- // Merge: existing data takes precedence (streaming approvals are more up-to-date)
- // This prevents losing approval cards when setConversation is called during askMax
- const hasExistingData = Object.keys(state).length > 0
- if (hasExistingData) {
- return {
- ...incomingApprovals,
- ...state,
- }
- }
-
- return incomingApprovals
+ return { ...state, ...incomingApprovals }
},
},
],
@@ -2274,6 +2264,12 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
const newConversation = {
...values.conversation,
+ pending_approvals: Object.values(values.pendingApprovalsData)
+ .filter((approval) => approval.proposal_id === values.pendingApprovalProposalId)
+ .map((approval) => {
+ const resolved = values.resolvedApprovalStatuses[approval.proposal_id]
+ return resolved ? { ...approval, decision_status: resolved.status } : approval
+ }),
status: ConversationStatus.Idle,
}
diff --git a/products/posthog_ai/frontend/components/OptionSelector.tsx b/products/posthog_ai/frontend/components/OptionSelector.tsx
index e4bd05e7e04e..fdbeaa67677b 100644
--- a/products/posthog_ai/frontend/components/OptionSelector.tsx
+++ b/products/posthog_ai/frontend/components/OptionSelector.tsx
@@ -137,6 +137,9 @@ export function OptionSelector({
className="grid items-center gap-x-2 grid-cols-[min-content_auto] text-sm cursor-pointer"
onClick={(e) => {
e.preventDefault()
+ if (disabled) {
+ return
+ }
if (selectedValue === o.value) {
onSelect(null)
} else {
@@ -149,6 +152,7 @@ export function OptionSelector({
type="radio"
className="cursor-pointer"
checked={selectedValue === o.value && !showCustomInput}
+ disabled={disabled}
onChange={() => {}}
/>
<span>{o.label}</span>
@@ -167,6 +171,7 @@ export function OptionSelector({
type="radio"
className="cursor-pointer"
checked={showCustomInput}
+ disabled={disabled}
onChange={() => {
setUserWantsCustomMode(true)
}}
@@ -181,6 +186,7 @@ export function OptionSelector({
value={customInput}
onChange={setCustomInput}
onPressEnter={handleCustomSubmit}
+ disabled={disabled}
autoFocus={true}
/>
) : (
@@ -197,7 +203,7 @@ export function OptionSelector({
})}
>
{onSkip && (
- <LemonButton type="secondary" size="small" onClick={onSkip}>
+ <LemonButton type="secondary" size="small" onClick={onSkip} disabled={disabled}>
Skip question
</LemonButton>
)}
@@ -206,6 +212,7 @@ export function OptionSelector({
<LemonButton
type="primary"
size="small"
+ disabled={disabled}
disabledReason={!customInput.trim() ? 'Please type a response' : undefined}
onClick={handleCustomSubmit}
>
diff --git a/products/posthog_ai/frontend/components/QuestionField.test.tsx b/products/posthog_ai/frontend/components/QuestionField.test.tsx
index a0413499687b..a68b75d1d013 100644
--- a/products/posthog_ai/frontend/components/QuestionField.test.tsx
+++ b/products/posthog_ai/frontend/components/QuestionField.test.tsx
@@ -41,6 +41,25 @@ describe('QuestionField', () => {
expect(screen.getByText('Option B')).toBeInTheDocument()
})
+ it.each([
+ [false, 1],
+ [true, 0],
+ ])('select option click with disabled=%s answers %s times', (disabled, answers) => {
+ const onAnswer = jest.fn()
+ render(
+ <QuestionField
+ question={selectQuestion}
+ value={undefined}
+ onAnswer={onAnswer}
+ onChange={jest.fn()}
+ onSubmit={jest.fn()}
+ disabled={disabled}
+ />
+ )
+ fireEvent.click(screen.getByText('Option A'))
+ expect(onAnswer).toHaveBeenCalledTimes(answers)
+ })
+
it('renders multi_select with checkboxes', () => {
const onAnswer = jest.fn()
const question: MultiQuestionFormQuestion = {