:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(wizard): stream session updates via SSE (#59109)
Fernando Gomes5750ed06336d
diff --git a/products/wizard/backend/facade/api.py b/products/wizard/backend/facade/api.pyindex 43709acacd5f..0247059938a8 100644--- a/products/wizard/backend/facade/api.py+++ b/products/wizard/backend/facade/api.py@@ -8,17 +8,16 @@ dataclasses. Never return ORM instances or import DRF.from __future__ import annotations+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from typing import Any+from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardSessionDTO-from products.wizard.backend.logic import sessions+from products.wizard.backend.logic import pubsub, sessionsdef upsert(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO, bool]:- """Upsert a session and report whether the row was newly created.-- Returns `(dto, created)` so consumers can distinguish 201 from 200 in- their response semantics, and so retry-aware clients can short-circuit- after the first successful write.- """+ """Returns `(dto, created)` so callers can pick 201 vs 200."""return sessions.upsert_session(params)@@ -26,7 +25,7 @@ def get(team_id: int, session_id: str) -> WizardSessionDTO | None:return sessions.get_session(team_id, session_id)-def get_latest(team_id: int, workflow_id: str, skill_id: str) -> WizardSessionDTO | None:+def get_latest(team_id: int, workflow_id: str, skill_id: str | None = None) -> WizardSessionDTO | None:return sessions.get_latest_session(team_id, workflow_id, skill_id)@@ -38,12 +37,6 @@ def list_for_team(offset: int = 0,limit: int | None = None,) -> list[WizardSessionDTO]:- """List sessions for a team, ordered by started_at desc.-- `offset`/`limit` are applied at the SQL layer; callers should pass a- bounded `limit` for any user-facing list endpoint so the read cost stays- bounded regardless of per-team row count.- """return sessions.list_sessions(team_id,workflow_id=workflow_id,@@ -51,3 +44,17 @@ def list_for_team(offset=offset,limit=limit,)+++@asynccontextmanager+async def subscribe_to_updates(+ team_id: int,+ workflow_id: str,+ skill_id: str | None = None,+) -> AsyncIterator[Any]:+ async with pubsub.subscribe(team_id, workflow_id, skill_id) as ps:+ yield ps+++def serialize_dto(dto: WizardSessionDTO) -> bytes:+ return pubsub.serialize_dto(dto)diff --git a/products/wizard/backend/logic/pubsub.py b/products/wizard/backend/logic/pubsub.pynew file mode 100644index 000000000000..f645bfedb7f5--- /dev/null+++ b/products/wizard/backend/logic/pubsub.py@@ -0,0 +1,144 @@+"""+Redis pub/sub fanout for wizard session updates.++Publish happens inside `transaction.on_commit` so subscribers never see+uncommitted state. Subscribers (SSE endpoint) use the async client so each+idle connection is a coroutine on the event loop, not a thread pinning the+asgiref pool.+"""++from __future__ import annotations++import re+import dataclasses+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from datetime import datetime+from enum import Enum+from typing import Any++from django.db import transaction++import orjson+import structlog++from posthog.redis import get_async_client, get_client++from products.wizard.backend.facade.contracts import WizardSessionDTO++logger = structlog.get_logger(__name__)++CHANNEL_PREFIX = "wizard_sessions"++# workflow_id / skill_id appear unescaped in Redis channel names / patterns;+# reject anything that could be a glob metacharacter (`*?[]\`) or the `:` delimiter.+_SAFE_ID_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,255}$")+++def _validate_id(value: str, name: str) -> None:+ if not _SAFE_ID_RE.match(value):+ raise ValueError(f"{name} must match {_SAFE_ID_RE.pattern}; got {value!r}")+++def channel_name(team_id: int, workflow_id: str, skill_id: str) -> str:+ _validate_id(workflow_id, "workflow_id")+ _validate_id(skill_id, "skill_id")+ return f"{CHANNEL_PREFIX}:team:{team_id}:workflow:{workflow_id}:skill:{skill_id}"+++def channel_pattern(team_id: int, workflow_id: str) -> str:+ """Pattern for subscribing to all skills under a (team, workflow_id)."""+ _validate_id(workflow_id, "workflow_id")+ return f"{CHANNEL_PREFIX}:team:{team_id}:workflow:{workflow_id}:skill:*"+++def serialize_dto(dto: WizardSessionDTO) -> bytes:+ return orjson.dumps(dto, default=_json_default)+++def publish_session_update(dto: WizardSessionDTO) -> None:+ """Schedule a Redis publish after the current transaction commits.++ Publish failures are logged and swallowed — fanout is best-effort and+ must not fail the already-committed upsert.+ """+ payload = serialize_dto(dto)+ channel = channel_name(dto.team_id, dto.workflow_id, dto.skill_id)++ def _publish() -> None:+ try:+ receivers = get_client().publish(channel, payload)+ except Exception:+ logger.exception(+ "wizard_sessions publish failed",+ channel=channel,+ session_id=dto.session_id,+ payload_bytes=len(payload),+ )+ return+ logger.debug(+ "wizard_sessions publish",+ channel=channel,+ session_id=dto.session_id,+ run_phase=dto.run_phase.value,+ payload_bytes=len(payload),+ receivers=receivers,+ )++ transaction.on_commit(_publish)+++@asynccontextmanager+async def subscribe(team_id: int, workflow_id: str, skill_id: str | None = None) -> AsyncIterator[Any]:+ """Subscribe to wizard-session events.++ With `skill_id`, subscribes to the exact `(team, workflow, skill)` channel.+ Without it, pattern-subscribes to every skill under `(team, workflow)`;+ messages arrive as `{type: 'pmessage', ...}` instead of `{type: 'message'}`.+ """+ if skill_id is not None:+ target = channel_name(team_id, workflow_id, skill_id)+ is_pattern = False+ else:+ target = channel_pattern(team_id, workflow_id)+ is_pattern = True++ redis = get_async_client()+ pubsub = redis.pubsub(ignore_subscribe_messages=True)+ try:+ if is_pattern:+ await pubsub.psubscribe(target)+ else:+ await pubsub.subscribe(target)+ except Exception:+ try:+ await pubsub.close()+ except Exception:+ pass+ raise++ try:+ yield pubsub+ finally:+ try:+ if is_pattern:+ await pubsub.punsubscribe(target)+ else:+ await pubsub.unsubscribe(target)+ except Exception:+ logger.warning("wizard_sessions unsubscribe failed", target=target)+ finally:+ try:+ await pubsub.close()+ except Exception:+ logger.warning("wizard_sessions pubsub close failed", target=target)+++def _json_default(value: Any) -> Any:+ if dataclasses.is_dataclass(value) and not isinstance(value, type):+ return dataclasses.asdict(value)+ if isinstance(value, Enum):+ return value.value+ if isinstance(value, datetime):+ return value.isoformat()+ raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")diff --git a/products/wizard/backend/logic/sessions.py b/products/wizard/backend/logic/sessions.pyindex 89851b91617d..beb9cf90caff 100644--- a/products/wizard/backend/logic/sessions.py+++ b/products/wizard/backend/logic/sessions.py@@ -4,6 +4,7 @@ Business logic for Wizard sessions.from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardSessionDTO, WizardTaskDTOfrom products.wizard.backend.facade.enums import RunPhase, TaskStatus+from products.wizard.backend.logic.pubsub import publish_session_updatefrom products.wizard.backend.logic.utils import is_stalefrom products.wizard.backend.models import WizardSession@@ -37,7 +38,9 @@ def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO,"error": params.error,},)- return _to_dto(instance), created+ dto = _to_dto(instance)+ publish_session_update(dto)+ return dto, createddef get_session(team_id: int, session_id: str) -> WizardSessionDTO | None:@@ -45,12 +48,11 @@ def get_session(team_id: int, session_id: str) -> WizardSessionDTO | None:return _to_dto(instance) if instance else None-def get_latest_session(team_id: int, workflow_id: str, skill_id: str) -> WizardSessionDTO | None:- instance = (- WizardSession.objects.filter(team_id=team_id, workflow_id=workflow_id, skill_id=skill_id)- .order_by("-started_at")- .first()- )+def get_latest_session(team_id: int, workflow_id: str, skill_id: str | None = None) -> WizardSessionDTO | None:+ qs = WizardSession.objects.filter(team_id=team_id, workflow_id=workflow_id)+ if skill_id:+ qs = qs.filter(skill_id=skill_id)+ instance = qs.order_by("-started_at").first()return _to_dto(instance) if instance else Nonediff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.pyindex 876825805573..4b2b31933229 100644--- a/products/wizard/backend/presentation/views.py+++ b/products/wizard/backend/presentation/views.py@@ -5,19 +5,32 @@ Validates JSON via serializers, routes everything through the facade,returns DTO-shaped responses. No model imports."""+import time+from collections.abc import AsyncIteratorfrom typing import Any+from django.conf import settings+from django.http import StreamingHttpResponse+import structlog+from asgiref.sync import sync_to_asyncfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import status, viewsets+from rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound, ValidationError+from rest_framework.renderers import BaseRendererfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.models.scoping import team_scopefrom products.wizard.backend.facade import api as wizard_facade-from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, UpsertWizardSessionRequest+from products.wizard.backend.facade.contracts import (+ UpsertWizardSessionInput,+ UpsertWizardSessionRequest,+ WizardSessionDTO,+)from products.wizard.backend.presentation.serializers import (UpsertWizardSessionRequestSerializer,WizardSessionSerializer,@@ -27,13 +40,18 @@ from products.wizard.backend.presentation.utils import pagination_windowlogger = structlog.get_logger(__name__)-def _log_request_auth(request: Request, *, action: str, team_id: int | None) -> None:- """Debug-only dump of how the incoming wizard_sessions request authenticated.+class EventStreamRenderer(BaseRenderer):+ """Satisfies DRF content negotiation for `Accept: text/event-stream`; never actually invoked."""- Fires only at DEBUG level — kept around for diagnosing 401/403 chains during- rollout. Once the wizard CLI auth flow is stable, this can be removed- entirely.- """+ media_type = "text/event-stream"+ format = "event-stream"+ charset = "utf-8"++ def render(self, data: Any, accepted_media_type: str | None = None, renderer_context: Any = None) -> bytes:+ return data if isinstance(data, bytes) else b""+++def _log_request_auth(request: Request, *, action: str, team_id: int | None) -> None:if not logger.isEnabledFor(10): # logging.DEBUGreturn@@ -73,18 +91,22 @@ def _log_request_auth(request: Request, *, action: str, team_id: int | None) ->)+SSE_HEARTBEAT_INTERVAL_SECONDS = 15.0+SSE_POLL_TIMEOUT_SECONDS = 1.0+SSE_MAX_DURATION_SECONDS = 30 * 60++class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "wizard_session"- scope_object_read_actions = ["list", "retrieve"]+ scope_object_read_actions = ["list", "retrieve", "stream"]scope_object_write_actions = ["create"]http_method_names = ["get", "post", "head", "options"]lookup_field = "session_id"- lookup_value_regex = r"[^/]+"+ # Negative lookahead so a session_id of `stream` can't collide with the+ # `@action(url_path="stream")` detail-vs-action route.+ lookup_value_regex = r"(?!stream$)[^/]+"def check_permissions(self, request: Request) -> None:- """Log the auth state before DRF decides allow/deny. Fires for both 200 and 403."""- # team_id is a cached_property that can raise on malformed URLs — don't- # let the diagnostic logger mask a clean 4xx with a 500.try:team_id = self.team_idexcept (KeyError, ValidationError, NotFound, AttributeError):@@ -125,8 +147,6 @@ class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):offset=page_offset,limit=page_limit,)- # `sessions` is already a bounded slice; DRF's paginator can still wrap- # it so the response shape (count/next/previous) stays consistent.page = self.paginate_queryset(sessions)if page is not None:return self.get_paginated_response(WizardSessionSerializer(page, many=True).data)@@ -180,3 +200,116 @@ class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OKreturn Response(WizardSessionSerializer(dto).data, status=response_status)++ @extend_schema(+ description=(+ "Server-Sent Events stream of wizard session updates for a "+ "(workflow_id, skill_id) pair. On connect, the current latest "+ "session (if any) is emitted as the first event; subsequent "+ "upserts are streamed in real time. The server closes the "+ f"connection after {SSE_MAX_DURATION_SECONDS} seconds with an "+ "`event: end` line so the client (EventSource) can reconnect.\n\n"+ "**SDK consumers**: do not call the generated fetch wrapper for "+ "this path — it will buffer the entire infinite stream. Use the "+ "URL builder (`getWizardSessionsStreamRetrieveUrl`) with the "+ "browser's `EventSource` API instead."+ ),+ parameters=[+ OpenApiParameter(+ name="workflow_id",+ required=True,+ type=str,+ location=OpenApiParameter.QUERY,+ ),+ OpenApiParameter(+ name="skill_id",+ required=False,+ type=str,+ location=OpenApiParameter.QUERY,+ ),+ ],+ responses={+ (200, "text/event-stream"): {+ "type": "string",+ "description": "SSE stream of WizardSession events.",+ }+ },+ )+ @action(detail=False, methods=["get"], url_path="stream", renderer_classes=[EventStreamRenderer])+ def stream(self, request: Request, *args: Any, **kwargs: Any) -> StreamingHttpResponse:+ workflow_id = request.query_params.get("workflow_id")+ skill_id = request.query_params.get("skill_id") or None+ if not workflow_id:+ raise ValidationError({"detail": "workflow_id is required."})++ # The generator is `async def` — WSGI can't consume an async iterator.+ if getattr(settings, "SERVER_GATEWAY_INTERFACE", "ASGI") != "ASGI":+ raise RuntimeError("wizard_sessions.stream requires ASGI.")++ generator = _wizard_session_event_stream(+ team_id=self.team_id,+ workflow_id=workflow_id,+ skill_id=skill_id,+ request=request,+ )+ return StreamingHttpResponse(+ generator,+ status=status.HTTP_200_OK,+ content_type="text/event-stream",+ headers={+ "Cache-Control": "no-cache, no-transform",+ "X-Accel-Buffering": "no",+ },+ )+++async def _wizard_session_event_stream(+ team_id: int,+ workflow_id: str,+ skill_id: str | None,+ request: Request | None = None,+) -> AsyncIterator[bytes]:+ """Stream SSE bytes for a wizard session subscription.++ Subscribes first, then fetches initial state, so publishes that race the+ snapshot are buffered on the pubsub socket and drained on the next tick.+ """+ started_at = time.monotonic()++ async with wizard_facade.subscribe_to_updates(team_id, workflow_id, skill_id) as pubsub:++ def _get_initial() -> WizardSessionDTO | None:+ with team_scope(team_id):+ return wizard_facade.get_latest(team_id, workflow_id, skill_id)++ latest = await sync_to_async(_get_initial, thread_sensitive=False)()+ if latest is not None:+ yield b"data: " + wizard_facade.serialize_dto(latest) + b"\n\n"++ last_heartbeat = time.monotonic()+ while True:+ if time.monotonic() - started_at >= SSE_MAX_DURATION_SECONDS:+ yield b"event: end\ndata: reconnect\n\n"+ return++ if request is not None:+ is_disconnected = getattr(request, "is_disconnected", None)+ if is_disconnected is not None:+ try:+ if await is_disconnected():+ return+ except Exception:+ pass++ message = await pubsub.get_message(timeout=SSE_POLL_TIMEOUT_SECONDS)+ now = time.monotonic()++ # `pmessage` arrives via pattern subscribe; `message` via exact.+ if message and message.get("type") in ("message", "pmessage"):+ yield b"data: " + message["data"] + b"\n\n"+ last_heartbeat = now+ continue++ if now - last_heartbeat >= SSE_HEARTBEAT_INTERVAL_SECONDS:+ yield b": ping\n\n"+ last_heartbeat = nowdiff --git a/products/wizard/backend/tests/test_presentation.py b/products/wizard/backend/tests/test_presentation.pyindex a94d87a6268f..a9b1d5881895 100644--- a/products/wizard/backend/tests/test_presentation.py+++ b/products/wizard/backend/tests/test_presentation.py@@ -192,3 +192,9 @@ class TestWizardSessionViewSet(APIBaseTest):data = response.json()self.assertEqual(data["event_plan"], {"events": [{"name": "$pageview"}]})self.assertEqual(data["error"], {"type": "TimeoutError", "message": "Anthropic API timed out"})++ def test_stream_requires_workflow_id(self):+ # No params → 400 from the view-level validation (workflow_id is the+ # only required query param; skill_id is optional for pattern subscribe).+ response = self.client.get(f"{self._url()}stream/")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)diff --git a/products/wizard/backend/tests/test_pubsub.py b/products/wizard/backend/tests/test_pubsub.pynew file mode 100644index 000000000000..64d7d6b58dc6--- /dev/null+++ b/products/wizard/backend/tests/test_pubsub.py@@ -0,0 +1,93 @@+from datetime import UTC, datetime++import pytest+from unittest.mock import MagicMock, patch++from django.db import transaction++from products.wizard.backend.facade.contracts import WizardSessionDTO, WizardTaskDTO+from products.wizard.backend.facade.enums import RunPhase, TaskStatus+from products.wizard.backend.logic.pubsub import channel_name, publish_session_update+++def _dto(team_id: int = 1) -> WizardSessionDTO:+ now = datetime(2026, 5, 19, 10, 0, 0, tzinfo=UTC)+ return WizardSessionDTO(+ # session_id has no colons because channel_name validates the safe-id+ # alphabet on workflow_id/skill_id. session_id itself isn't part of+ # the channel name, but we still keep the format safe for downstream+ # consumers.+ session_id="onboarding-nextjs-2026-05-19T10-00-00Z",+ team_id=team_id,+ workflow_id="onboarding",+ skill_id="nextjs",+ started_at=now,+ run_phase=RunPhase.RUNNING,+ is_stale=False,+ tasks=(WizardTaskDTO(id="1", title="Install SDK", status=TaskStatus.IN_PROGRESS),),+ event_plan=None,+ error=None,+ created_at=now,+ updated_at=now,+ )+++def test_channel_name_is_deterministic():+ assert channel_name(1, "onboarding", "nextjs") == "wizard_sessions:team:1:workflow:onboarding:skill:nextjs"+++def test_channel_name_rejects_unsafe_ids():+ """workflow_id / skill_id can't smuggle Redis glob metacharacters or `:`."""+ with pytest.raises(ValueError):+ channel_name(1, "onboarding", "next*")+ with pytest.raises(ValueError):+ channel_name(1, "*", "nextjs")+ with pytest.raises(ValueError):+ channel_name(1, "onboarding:malicious", "nextjs")+ with pytest.raises(ValueError):+ channel_name(1, "onboarding", "next[js]")++[email protected]_db(transaction=True)+def test_publish_session_update_publishes_after_commit():+ """In transaction.atomic, the publish should defer to on_commit."""+ redis_mock = MagicMock()+ with patch("products.wizard.backend.logic.pubsub.get_client", return_value=redis_mock):+ with transaction.atomic():+ publish_session_update(_dto())+ assert redis_mock.publish.call_count == 0 # not yet committed++ # After atomic block exits, on_commit hooks fire.+ assert redis_mock.publish.call_count == 1+ channel, payload = redis_mock.publish.call_args.args+ assert channel == "wizard_sessions:team:1:workflow:onboarding:skill:nextjs"+ assert b'"session_id":"onboarding-nextjs-2026-05-19T10-00-00Z"' in payload+ assert b'"run_phase":"running"' in payload+ assert b'"status":"in_progress"' in payload+++def test_publish_session_update_does_not_publish_on_rollback():+ redis_mock = MagicMock()+ with patch("products.wizard.backend.logic.pubsub.get_client", return_value=redis_mock):+ try:+ with transaction.atomic():+ publish_session_update(_dto())+ raise RuntimeError("force rollback")+ except RuntimeError:+ pass++ assert redis_mock.publish.call_count == 0++[email protected]_db(transaction=True)+def test_publish_session_update_swallows_redis_errors():+ """Redis publish failure must not fail the upsert request."""+ redis_mock = MagicMock()+ redis_mock.publish.side_effect = ConnectionError("redis is down")++ with patch("products.wizard.backend.logic.pubsub.get_client", return_value=redis_mock):+ with transaction.atomic():+ publish_session_update(_dto())+ # If the exception escaped on_commit, this assertion wouldn't run.+ assert redis_mock.publish.call_count == 1diff --git a/products/wizard/backend/tests/test_stream.py b/products/wizard/backend/tests/test_stream.pynew file mode 100644index 000000000000..cc71e1f24604--- /dev/null+++ b/products/wizard/backend/tests/test_stream.py@@ -0,0 +1,187 @@+from contextlib import asynccontextmanager+from datetime import UTC, datetime++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from asgiref.sync import sync_to_async++from products.wizard.backend.facade import api as wizard_facade+from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardTaskDTO+from products.wizard.backend.facade.enums import RunPhase, TaskStatus+from products.wizard.backend.presentation.views import _wizard_session_event_stream+++class _StopStream(Exception):+ """Helper to break the infinite generator after we've collected what we want."""+++def _input(team_id: int, **overrides) -> UpsertWizardSessionInput:+ params: dict = {+ "team_id": team_id,+ "session_id": "onboarding-nextjs-2026-05-19T10-00-00Z",+ "workflow_id": "onboarding",+ "skill_id": "nextjs",+ "started_at": datetime(2026, 5, 19, 10, 0, 0, tzinfo=UTC),+ "run_phase": RunPhase.RUNNING,+ "tasks": (WizardTaskDTO(id="1", title="Install SDK", status=TaskStatus.IN_PROGRESS),),+ "event_plan": None,+ "error": None,+ }+ params.update(overrides)+ return UpsertWizardSessionInput(**params)+++async def _drain(generator, max_events: int):+ """Pull up to max_events from the async generator, stopping early on _StopStream."""+ events = []+ try:+ for _ in range(max_events):+ events.append(await anext(generator))+ except (_StopStream, StopAsyncIteration):+ pass+ finally:+ # Close the generator so its `async with` runs cleanup (closes the+ # Redis subscription). Without this, leaked subscriptions would pass+ # the tests silently.+ await generator.aclose()+ return events+++def _async_subscribe_cm(pubsub_mock):+ """Build an async context manager that yields the given pubsub mock.++ Tracks enter/exit calls on the returned tuple `(cm_factory, exit_marker)`+ so tests can assert cleanup ran.+ """+ exit_marker = MagicMock(name="exit_marker")++ @asynccontextmanager+ async def _cm(team_id, workflow_id, skill_id):+ try:+ yield pubsub_mock+ finally:+ exit_marker(team_id, workflow_id, skill_id)++ return _cm, exit_marker+++def _patch_subscribe(pubsub_mock):+ """Patch the facade's `subscribe_to_updates` async context manager.++ Returns the patch object plus a sentinel that records cleanup so tests+ can confirm the Redis subscription's `__aexit__` ran.+ """+ cm_factory, exit_marker = _async_subscribe_cm(pubsub_mock)+ return (+ patch(+ "products.wizard.backend.presentation.views.wizard_facade.subscribe_to_updates",+ cm_factory,+ ),+ exit_marker,+ )+++def _async_get_message(side_effects):+ return AsyncMock(side_effect=side_effects)++[email protected]_db(transaction=True)+async def test_stream_emits_initial_state_when_session_exists(team):+ await sync_to_async(wizard_facade.upsert)(_input(team.id))++ pubsub_mock = MagicMock()+ pubsub_mock.get_message = _async_get_message([_StopStream()])++ patcher, exit_marker = _patch_subscribe(pubsub_mock)+ with patcher:+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="onboarding", skill_id="nextjs")+ events = await _drain(gen, max_events=2)++ assert len(events) == 1+ assert events[0].startswith(b"data: ")+ assert b'"session_id":"onboarding-nextjs-2026-05-19T10-00-00Z"' in events[0]+ assert events[0].endswith(b"\n\n")+ # Cleanup must run — otherwise we'd leak Redis subscriptions on every+ # client disconnect.+ exit_marker.assert_called_once_with(team.id, "onboarding", "nextjs")++[email protected]_db(transaction=True)+async def test_stream_skips_initial_event_when_no_session(team):+ pubsub_mock = MagicMock()+ pubsub_mock.get_message = _async_get_message([_StopStream()])++ patcher, exit_marker = _patch_subscribe(pubsub_mock)+ with patcher:+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")+ events = await _drain(gen, max_events=2)++ assert events == []+ exit_marker.assert_called_once()++[email protected]_db(transaction=True)+async def test_stream_forwards_pubsub_messages(team):+ pubsub_mock = MagicMock()+ pubsub_mock.get_message = _async_get_message(+ [+ {"type": "message", "data": b'{"session_id":"a"}'},+ {"type": "message", "data": b'{"session_id":"b"}'},+ _StopStream(),+ ]+ )++ patcher, exit_marker = _patch_subscribe(pubsub_mock)+ with patcher:+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")+ events = await _drain(gen, max_events=5)++ assert events == [+ b'data: {"session_id":"a"}\n\n',+ b'data: {"session_id":"b"}\n\n',+ ]+ exit_marker.assert_called_once()++[email protected]_db(transaction=True)+async def test_stream_emits_heartbeat_when_idle(team):+ pubsub_mock = MagicMock()+ pubsub_mock.get_message = _async_get_message([None, None, _StopStream()])++ patcher, exit_marker = _patch_subscribe(pubsub_mock)+ # Force heartbeat threshold to zero so any idle tick emits one.+ with (+ patcher,+ patch("products.wizard.backend.presentation.views.SSE_HEARTBEAT_INTERVAL_SECONDS", 0.0),+ ):+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")+ events = await _drain(gen, max_events=4)++ assert events == [b": ping\n\n", b": ping\n\n"]+ exit_marker.assert_called_once()++[email protected]_db(transaction=True)+async def test_stream_terminates_on_max_duration(team):+ """SSE_MAX_DURATION_SECONDS=0 -> first loop tick emits `event: end` and exits."""+ pubsub_mock = MagicMock()+ pubsub_mock.get_message = _async_get_message([None] * 10)++ patcher, exit_marker = _patch_subscribe(pubsub_mock)+ with (+ patcher,+ patch("products.wizard.backend.presentation.views.SSE_MAX_DURATION_SECONDS", 0),+ ):+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")+ events = await _drain(gen, max_events=5)++ # Generator emits `event: end` then returns — clean close, no leaked+ # subscription.+ assert events == [b"event: end\ndata: reconnect\n\n"]+ exit_marker.assert_called_once()diff --git a/products/wizard/frontend/generated/api.schemas.ts b/products/wizard/frontend/generated/api.schemas.tsindex c941b284abf1..912be569cd99 100644--- a/products/wizard/frontend/generated/api.schemas.ts+++ b/products/wizard/frontend/generated/api.schemas.ts@@ -155,3 +155,8 @@ export type WizardSessionsListParams = {*/workflow_id?: string}++export type WizardSessionsStreamRetrieveParams = {+ skill_id?: string+ workflow_id: string+}diff --git a/products/wizard/frontend/generated/api.ts b/products/wizard/frontend/generated/api.tsindex 5a56f28ae06b..4964fad179e5 100644--- a/products/wizard/frontend/generated/api.ts+++ b/products/wizard/frontend/generated/api.ts@@ -13,6 +13,7 @@ import type {UpsertWizardSessionRequestApi,WizardSessionDTOApi,WizardSessionsListParams,+ WizardSessionsStreamRetrieveParams,} from './api.schemas'export const getWizardSessionsListUrl = (projectId: string, params?: WizardSessionsListParams) => {@@ -82,3 +83,35 @@ export const wizardSessionsRetrieve = async (method: 'GET',})}++export const getWizardSessionsStreamRetrieveUrl = (projectId: string, params: WizardSessionsStreamRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/wizard/sessions/stream/?${stringifiedParams}`+ : `/api/projects/${projectId}/wizard/sessions/stream/`+}++/**+ * Server-Sent Events stream of wizard session updates for a (workflow_id, skill_id) pair. On connect, the current latest session (if any) is emitted as the first event; subsequent upserts are streamed in real time. The server closes the connection after 1800 seconds with an `event: end` line so the client (EventSource) can reconnect.++**SDK consumers**: do not call the generated fetch wrapper for this path — it will buffer the entire infinite stream. Use the URL builder (`getWizardSessionsStreamRetrieveUrl`) with the browser's `EventSource` API instead.+ */+export const wizardSessionsStreamRetrieve = async (+ projectId: string,+ params: WizardSessionsStreamRetrieveParams,+ options?: RequestInit+): Promise<string> => {+ return apiMutator<string>(getWizardSessionsStreamRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fd3ccf8c63e3..f91d6bca1a60 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46947,6 +46947,11 @@ export namespace Schemas {workflow_id?: string;};+ export type WizardSessionsStreamRetrieveParams = {+ skill_id?: string;+ workflow_id: string;+ };+export type PublicHogFunctionTemplatesListParams = {/*** Number of results to return per page.