Skip to content

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

feat(replay-vision): live SSE progress for in-progress observations (#61510)

Kim Svatos Duganc98bf45005bf
diff --git a/products/replay_vision/backend/api/observation_progress.py b/products/replay_vision/backend/api/observation_progress.py
new file mode 100644
index 000000000000..f7442ff6d044
--- /dev/null
+++ b/products/replay_vision/backend/api/observation_progress.py
@@ -0,0 +1,133 @@
+import json
+import time
+import asyncio
+from collections.abc import AsyncGenerator
+from typing import Any
+from uuid import UUID
+
+import structlog
+
+from posthog.sync import database_sync_to_async
+from posthog.temporal.common.client import async_connect
+
+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.temporal.types import (
+ OBSERVATION_PHASE_INDEX,
+ OBSERVATION_PHASE_ORDER,
+ ObservationProgress,
+)
+
+logger = structlog.get_logger(__name__)
+
+# How often the stream re-reads observation status and re-queries the workflow for progress.
+PROGRESS_POLL_INTERVAL_S = 1.5
+
+# Hard cap on how long we hold an ASGI worker for one stream, in case the workflow is stuck or the
+# client never disconnects. Observations finish in minutes; well past that we close and free the worker.
+MAX_STREAM_DURATION_S = 10 * 60
+
+_TERMINAL_STATUSES = frozenset({ObservationStatus.SUCCEEDED, ObservationStatus.FAILED, ObservationStatus.INELIGIBLE})
+
+
+def _sse_event(label: str, data: str) -> str:
+ return f"event: {label}\ndata: {data}\n\n"
+
+
+@database_sync_to_async
+def _read_observation_state(observation_id: UUID, team_id: int) -> tuple[str, str] | None:
+ """Returns (status, workflow_id), or None if the row vanished. Team-scoped: the caller already
+ authorized this observation via get_object(), but the query stays tenant-scoped per the IDOR rule."""
+ row = (
+ ReplayObservation.objects.filter(pk=observation_id, team_id=team_id)
+ .values_list("status", "workflow_id")
+ .first()
+ )
+ return None if row is None else (row[0], row[1])
+
+
+def _fallback_progress(status: str) -> ObservationProgress:
+ """Used when the workflow can't be queried yet (brief startup window or post-completion eviction)."""
+ phase = "queued" if status == ObservationStatus.PENDING else "fetching"
+ return {
+ "phase": phase,
+ "step": OBSERVATION_PHASE_INDEX[phase],
+ "total_steps": len(OBSERVATION_PHASE_ORDER),
+ "rasterizer_workflow_id": None,
+ }
+
+
+async def _read_rasterizer_frame_progress(client: Any, rasterizer_workflow_id: str) -> dict[str, Any] | None:
+ """Frame counts come from the rasterizer activity's heartbeats. Errors swallowed — progress is best-effort."""
+ try:
+ child_handle = client.get_workflow_handle(rasterizer_workflow_id)
+ desc = await child_handle.describe()
+ pending = getattr(desc.raw_description, "pending_activities", None) or []
+ if not pending:
+ return None
+ raw_payloads = list(pending[0].heartbeat_details.payloads)
+ if not raw_payloads:
+ return None
+ codec = getattr(client.data_converter, "payload_codec", None)
+ decoded = await codec.decode(raw_payloads) if codec is not None else raw_payloads
+ return {"frame_progress": json.loads(decoded[0].data)} if decoded else None
+ except Exception:
+ return None
+
+
+async def _query_progress(client: Any, workflow_id: str) -> dict[str, Any] | None:
+ """Query the running workflow's `get_progress`; attach rasterizer frame progress while rendering."""
+ try:
+ payload: dict[str, Any] = await client.get_workflow_handle(workflow_id).query("get_progress")
+ except Exception:
+ return None # Workflow not queryable yet/anymore — caller falls back to a status-derived payload.
+ rasterizer_workflow_id = payload.get("rasterizer_workflow_id")
+ if payload.get("phase") == "rendering" and rasterizer_workflow_id:
+ payload["rasterizer"] = await _read_rasterizer_frame_progress(client, rasterizer_workflow_id)
+ else:
+ payload["rasterizer"] = None
+ return payload
+
+
+async def stream_observation_progress(observation: ReplayObservation) -> AsyncGenerator[str, None]:
+ """SSE generator: live phase + rendering frame progress for one observation until it reaches a terminal state.
+
+ Emits `observation-progress` ticks, then a single `observation-complete` (carrying the terminal status) once the
+ row settles; `observation-error` on an unexpected failure. The client refetches the row to render the final result.
+ """
+ observation_id = observation.id
+ team_id = observation.team_id
+
+ # Fast path: already settled (e.g. details page opened after completion) — close immediately.
+ if observation.status in _TERMINAL_STATUSES:
+ yield _sse_event("observation-complete", json.dumps({"status": observation.status}))
+ return
+
+ try:
+ client = await async_connect()
+ except Exception:
+ client = None # Without Temporal we still tick a status-derived payload so the bar moves.
+
+ deadline = time.monotonic() + MAX_STREAM_DURATION_S
+ try:
+ while True:
+ if time.monotonic() > deadline:
+ # Free the ASGI worker rather than hold it open indefinitely on a stuck workflow.
+ logger.info("replay_vision.observation_progress_stream_timeout", observation_id=str(observation_id))
+ yield _sse_event("observation-error", "Progress stream timed out.")
+ return
+ state = await _read_observation_state(observation_id, team_id)
+ if state is None:
+ yield _sse_event("observation-error", "Observation not found")
+ return
+ status, workflow_id = state
+ if status in _TERMINAL_STATUSES:
+ yield _sse_event("observation-complete", json.dumps({"status": status}))
+ return
+
+ payload = await _query_progress(client, workflow_id) if client and workflow_id else None
+ yield _sse_event("observation-progress", json.dumps(payload or _fallback_progress(status)))
+ await asyncio.sleep(PROGRESS_POLL_INTERVAL_S)
+ except Exception:
+ # Don't leak the raw exception (DB hosts, internal details) to the client; it's logged server-side.
+ logger.exception("replay_vision.observation_progress_stream_failed", observation_id=str(observation_id))
+ yield _sse_event("observation-error", "An unexpected error occurred.")
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index e3e4e7914043..cba18975156c 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -1,9 +1,11 @@
import uuid
from typing import Any
+from django.conf import settings
from django.db.models import Case, CharField, FloatField, Func, IntegerField, Q, QuerySet, Value, When
from django.db.models.fields.json import KeyTextTransform, KeyTransform
from django.db.models.functions import Cast
+from django.http import StreamingHttpResponse
import structlog
import django_filters
@@ -18,8 +20,10 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
+from posthog.renderers import ServerSentEventRenderer
from products.replay_vision.backend.api.filters import MultiChoiceFilter, OrderByFilter, ordering_enum
+from products.replay_vision.backend.api.observation_progress import stream_observation_progress
from products.replay_vision.backend.api.observation_stats import compute_observation_stats
from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission
from products.replay_vision.backend.models.replay_observation import (
@@ -500,3 +504,23 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
# Hide `stats/` on the session-scoped viewset — it has no `parent_lookup_scanner_id` to dispatch on.
def stats(self, request: Request, **kwargs: Any) -> Response: # type: ignore[override]
raise NotFound()
+
+ @extend_schema(exclude=True)
+ @action(detail=True, methods=["GET"], url_path="progress")
+ def progress(self, request: Request, **kwargs: Any) -> StreamingHttpResponse:
+ """Stream live progress (phase + rendering frame counts) for one in-flight observation as SSE.
+
+ `get_object()` applies the same RBAC scoping as retrieve, so this can't leak observations the caller
+ can't read. The stream self-terminates once the observation reaches a terminal state.
+ """
+ # The generator is `async def` — WSGI can't consume an async iterator, so fail loudly there.
+ if getattr(settings, "SERVER_GATEWAY_INTERFACE", "ASGI") != "ASGI":
+ raise RuntimeError("observation progress stream requires ASGI.")
+ observation = self.get_object()
+ response = StreamingHttpResponse(
+ stream_observation_progress(observation),
+ content_type=ServerSentEventRenderer.media_type,
+ )
+ response["Cache-Control"] = "no-cache"
+ response["X-Accel-Buffering"] = "no"
+ return response
diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.py
index 08aac44d01f5..217f23d1b3fc 100644
--- a/products/replay_vision/backend/temporal/types.py
+++ b/products/replay_vision/backend/temporal/types.py
@@ -1,5 +1,5 @@
import datetime as dt
-from typing import Annotated, Any
+from typing import Annotated, Any, TypedDict
from uuid import UUID
from pydantic import BaseModel, Field, ValidationError, model_validator
@@ -78,6 +78,20 @@ class MarkObservationRunningInputs(BaseModel, frozen=True):
observation_id: UUID
+# Coarse progress phases, surfaced live via ApplyScannerWorkflow's `get_progress` query and streamed over SSE.
+OBSERVATION_PHASE_ORDER = ("queued", "fetching", "rendering", "uploading", "analyzing", "finalizing")
+OBSERVATION_PHASE_INDEX = {phase: index for index, phase in enumerate(OBSERVATION_PHASE_ORDER)}
+
+
+class ObservationProgress(TypedDict):
+ """Live progress snapshot returned by ApplyScannerWorkflow's `get_progress` query, streamed to the client over SSE."""
+
+ phase: str # one of OBSERVATION_PHASE_ORDER
+ step: int # index of `phase` in OBSERVATION_PHASE_ORDER
+ total_steps: int # len(OBSERVATION_PHASE_ORDER)
+ rasterizer_workflow_id: str | None # set while rendering, so the stream can read the child's frame heartbeats
+
+
class MarkObservationFailedInputs(BaseModel, frozen=True):
observation_id: UUID
# `kind:message` — kind is one of FailureKind values.
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index ed7dc61ee1b0..39fdab8e047f 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -1,5 +1,6 @@
import asyncio
import datetime as dt
+from typing import cast
from uuid import UUID
import temporalio.workflow as wf
@@ -40,6 +41,8 @@ from products.replay_vision.backend.temporal.errors import (
from products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput
from products.replay_vision.backend.temporal.scanners.summarizer import SummarizerOutput
from products.replay_vision.backend.temporal.types import (
+ OBSERVATION_PHASE_INDEX,
+ OBSERVATION_PHASE_ORDER,
ApplyScannerInputs,
CallScannerProviderInputs,
CleanupGeminiFileInputs,
@@ -55,6 +58,7 @@ from products.replay_vision.backend.temporal.types import (
MarkObservationIneligibleInputs,
MarkObservationRunningInputs,
MarkObservationSucceededInputs,
+ ObservationProgress,
ScannerCallOutput,
ScannerResult,
UploadedVideo,
@@ -130,12 +134,36 @@ def _encode_reason(kind: str, message: str) -> str:
return f"{kind}:{message}"
+def _rasterizer_workflow_id(inputs: ApplyScannerInputs) -> str:
+ # Per-scanner child id so concurrent observations of the same session don't collide on WorkflowAlreadyStartedError.
+ return f"replay-vision-rasterize-{inputs.team_id}-{inputs.session_id}-{inputs.scanner_id}"
+
+
@wf.defn(name=APPLY_SCANNER_WORKFLOW_NAME)
class ApplyScannerWorkflow(PostHogWorkflow):
"""Apply one scanner to one session: create row → fetch+rasterize → upload → call provider → emit event → mark succeeded."""
inputs_cls = ApplyScannerInputs
+ def __init__(self) -> None:
+ self._progress: ObservationProgress = {
+ "phase": OBSERVATION_PHASE_ORDER[0],
+ "step": 0,
+ "total_steps": len(OBSERVATION_PHASE_ORDER),
+ "rasterizer_workflow_id": None,
+ }
+
+ @wf.query
+ def get_progress(self) -> ObservationProgress:
+ # Copy so Temporal serializes a stable snapshot without racing the run() coroutine.
+ return cast(ObservationProgress, dict(self._progress))
+
+ def _advance_phase(self, phase: str, rasterizer_workflow_id: str | None = None) -> None:
+ self._progress["phase"] = phase
+ self._progress["step"] = OBSERVATION_PHASE_INDEX[phase]
+ if rasterizer_workflow_id is not None:
+ self._progress["rasterizer_workflow_id"] = rasterizer_workflow_id
+
@wf.run
async def run(self, inputs: ApplyScannerInputs) -> None:
workflow_id = wf.info().workflow_id
@@ -164,17 +192,21 @@ class ApplyScannerWorkflow(PostHogWorkflow):
start_to_close_timeout=dt.timedelta(seconds=30),
retry_policy=_STATE_ACTIVITY_RETRY,
)
+ self._advance_phase("fetching")
uploaded: UploadedVideo | None = None
try:
asset_result = await self._fetch_and_ensure_asset(inputs, observation_id)
+ self._advance_phase("rendering", rasterizer_workflow_id=_rasterizer_workflow_id(inputs))
await self._run_rasterize_child(inputs, asset_result.asset_id)
+ self._advance_phase("uploading")
uploaded = await wf.execute_activity(
upload_video_to_gemini_activity,
UploadVideoToGeminiInputs(asset_id=asset_result.asset_id),
start_to_close_timeout=dt.timedelta(minutes=10),
retry_policy=_UPLOAD_RETRY,
)
+ self._advance_phase("analyzing")
call_output: ScannerCallOutput = await wf.execute_activity(
call_scanner_provider_activity,
CallScannerProviderInputs(
@@ -186,6 +218,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
start_to_close_timeout=dt.timedelta(minutes=5),
retry_policy=_PROVIDER_CALL_RETRY,
)
+ self._advance_phase("finalizing")
await self._apply_scanner_side_effects(inputs, observation_id, call_output.model_output)
await wf.execute_activity(
emit_observation_event_activity,
@@ -247,12 +280,11 @@ class ApplyScannerWorkflow(PostHogWorkflow):
return asset_result
async def _run_rasterize_child(self, inputs: ApplyScannerInputs, asset_id: int) -> None:
- # Per-scanner child id so concurrent observations of the same session don't collide on WorkflowAlreadyStartedError.
try:
await wf.execute_child_workflow(
"rasterize-recording",
RasterizeRecordingInputs(exported_asset_id=asset_id),
- id=f"replay-vision-rasterize-{inputs.team_id}-{inputs.session_id}-{inputs.scanner_id}",
+ id=_rasterizer_workflow_id(inputs),
task_queue=settings.SESSION_REPLAY_TASK_QUEUE,
retry_policy=common.RetryPolicy(maximum_attempts=int(settings.TEMPORAL_WORKFLOW_MAX_ATTEMPTS)),
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 0b0a71985280..4c3a97187478 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -21,6 +21,7 @@ from posthog.redis import get_async_client
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from products.exports.backend.models.exported_asset import ExportedAsset
+from products.replay_vision.backend.api.observation_progress import stream_observation_progress
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
@@ -1386,6 +1387,36 @@ async def test_apply_scanner_workflow_exits_when_create_returns_was_created_fals
assert mocks.child_calls == []
+def test_workflow_get_progress_advances_through_phases() -> None:
+ workflow = ApplyScannerWorkflow()
+ assert workflow.get_progress() == {
+ "phase": "queued",
+ "step": 0,
+ "total_steps": 6,
+ "rasterizer_workflow_id": None,
+ }
+
+ workflow._advance_phase("rendering", rasterizer_workflow_id="rast-1")
+ progress = workflow.get_progress()
+ assert progress["phase"] == "rendering"
+ assert progress["step"] == 2
+ assert progress["rasterizer_workflow_id"] == "rast-1"
+
+ # A later phase without an id keeps the previously recorded rasterizer id.
+ workflow._advance_phase("analyzing")
+ assert workflow.get_progress()["phase"] == "analyzing"
+ assert workflow.get_progress()["rasterizer_workflow_id"] == "rast-1"
+
+
+async def test_progress_stream_completes_immediately_for_terminal_observation() -> None:
+ # Fast path: opening the stream for a settled observation emits a single complete event and closes.
+ observation = ReplayObservation(id=uuid.uuid4(), status=ObservationStatus.SUCCEEDED)
+ events = [event async for event in stream_observation_progress(observation)]
+ assert len(events) == 1
+ assert "event: observation-complete" in events[0]
+ assert '"status": "succeeded"' in events[0]
+
+
@pytest.mark.asyncio
async def test_apply_scanner_workflow_propagates_workflow_id_to_create() -> None:
mocks = _WorkflowMocks(
diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsx
index d9c0593f19b7..2059ffb70a88 100644
--- a/products/replay_vision/frontend/components/ObservationCard.tsx
+++ b/products/replay_vision/frontend/components/ObservationCard.tsx
@@ -11,6 +11,7 @@ import {
parseIneligibleReason,
scannerTypeLabel,
} from '../replay_scanners/types'
+import { ObservationProgressBar } from './ObservationProgressBar'
export function ObservationStatusTag({
status,
@@ -365,12 +366,7 @@ export function IneligibleDetail({ errorReason }: { errorReason: string }): JSX.
}
function ObservationProgress({ observation }: { observation: ReplayObservationApi }): JSX.Element {
- return (
- <div className="flex items-center gap-2 text-muted text-sm">
- <Spinner textColored />
- <span>{observation.status === 'pending' ? 'Queued…' : 'Analyzing recording…'}</span>
- </div>
- )
+ return <ObservationProgressBar observationId={observation.id} sessionId={observation.session_id} compact />
}
export function ObservationDockCard({
diff --git a/products/replay_vision/frontend/components/ObservationProgressBar.tsx b/products/replay_vision/frontend/components/ObservationProgressBar.tsx
new file mode 100644
index 000000000000..c7f0c9431d55
--- /dev/null
+++ b/products/replay_vision/frontend/components/ObservationProgressBar.tsx
@@ -0,0 +1,137 @@
+import { useValues } from 'kea'
+import { useRef } from 'react'
+
+import { IconCheckCircle, IconCircleDashed } from '@posthog/icons'
+import { Spinner } from '@posthog/lemon-ui'
+
+import { usePeriodicRerender } from 'lib/hooks/usePeriodicRerender'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+
+import { observationProgressLogic } from '../observations/observationProgressLogic'
+
+// Mirrors the backend OBSERVATION_PHASE_ORDER; the live phase arrives over SSE via observationProgressLogic.
+const PHASE_ORDER = ['queued', 'fetching', 'rendering', 'uploading', 'analyzing', 'finalizing'] as const
+type Phase = (typeof PHASE_ORDER)[number]
+
+const PHASE_LABELS: Record<Phase, string> = {
+ queued: 'Queued',
+ fetching: 'Fetching events',
+ rendering: 'Rendering video',
+ uploading: 'Uploading video for analysis',
+ analyzing: 'Analyzing recording',
+ finalizing: 'Finalizing',
+}
+
+// Rough per-phase time constants (seconds) driving an asymptotic fill for phases without real sub-progress, so the
+// bar keeps moving. At elapsed = tau the fill is ~63%; at 2*tau ~86%; never reaches 100% until the phase advances.
+const PHASE_TAU_S: Record<Phase, number> = {
+ queued: 4,
+ fetching: 4,
+ rendering: 30,
+ uploading: 6,
+ analyzing: 30,
+ finalizing: 5,
+}
+
+type PhaseStatus = 'done' | 'active' | 'pending'
+
+function asymptoticFillPercent(elapsedSeconds: number, tauSeconds: number): number {
+ return (1 - Math.exp(-elapsedSeconds / tauSeconds)) * 100
+}
+
+function phaseStatusAt(phaseIndex: number, currentStep: number): PhaseStatus {
+ if (phaseIndex < currentStep) {
+ return 'done'
+ }
+ return phaseIndex === currentStep ? 'active' : 'pending'
+}
+
+function PhaseStatusIcon({ status }: { status: PhaseStatus }): JSX.Element {
+ if (status === 'done') {
+ return <IconCheckCircle className="text-success text-base shrink-0" />
+ }
+ if (status === 'active') {
+ return <Spinner className="text-base shrink-0" />
+ }
+ return <IconCircleDashed className="text-muted-alt text-base shrink-0" />
+}
+
+/**
+ * Live progress for an in-progress observation, driven by the SSE stream in observationProgressLogic. Phase
+ * boundaries are server-truthful; the rendering phase shows real frame counts, other phases an asymptotic
+ * time-based fill. `compact` (dock) renders a single bar + label; otherwise a per-phase breakdown (details page).
+ */
+export function ObservationProgressBar({
+ observationId,
+ sessionId,
+ compact = false,
+}: {
+ observationId: string
+ sessionId: string
+ compact?: boolean
+}): JSX.Element {
+ const { progress } = useValues(observationProgressLogic({ observationId, sessionId }))
+ usePeriodicRerender(1000)
+
+ const currentStep = Math.min(progress?.step ?? 0, PHASE_ORDER.length - 1)
+ const activePhase = PHASE_ORDER[currentStep]
+
+ // Record when the active phase was first observed so its asymptotic fill animates from then.
+ const startTimesRef = useRef<Record<number, number>>({})
+ if (!(currentStep in startTimesRef.current)) {
+ startTimesRef.current[currentStep] = Date.now()
+ }
+ const activeElapsed = Math.max(0, (Date.now() - startTimesRef.current[currentStep]) / 1000)
+
+ // Real sub-progress only exists while rendering (frame counts from the rasterizer heartbeats); else asymptote.
+ const frame = activePhase === 'rendering' ? progress?.rasterizer?.frame_progress : undefined
+ const activeFill =
+ frame && frame.estimatedTotalFrames > 0
+ ? Math.min((frame.frame / frame.estimatedTotalFrames) * 100, 100)
+ : asymptoticFillPercent(activeElapsed, PHASE_TAU_S[activePhase])
+
+ if (compact) {
+ const detail =
+ frame && frame.estimatedTotalFrames > 0 ? ` (${frame.frame} / ${frame.estimatedTotalFrames} frames)` : ''
+ const overallPercent = ((currentStep + activeFill / 100) / PHASE_ORDER.length) * 100
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center gap-2 text-muted text-sm">
+ <Spinner textColored />
+ <span>
+ {PHASE_LABELS[activePhase]}
+ {detail}…
+ </span>
+ </div>
+ <LemonProgress percent={overallPercent} />
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ {PHASE_ORDER.map((phase, i) => {
+ const status = phaseStatusAt(i, currentStep)
+ const barPercent = status === 'done' ? 100 : status === 'active' ? activeFill : 0
+ const detail =
+ phase === 'rendering' && status === 'active' && frame && frame.estimatedTotalFrames > 0
+ ? `${frame.frame} / ${frame.estimatedTotalFrames} frames`
+ : null
+ return (
+ <div key={phase} className={`flex flex-col gap-1${status === 'pending' ? ' opacity-50' : ''}`}>
+ <div className="flex items-center gap-2 text-xs">
+ <PhaseStatusIcon status={status} />
+ <span className="truncate">
+ {PHASE_LABELS[phase]}
+ {detail ? <span className="text-muted-alt">&nbsp;({detail})</span> : null}
+ </span>
+ </div>
+ <div className="pl-6">
+ <LemonProgress percent={barPercent} />
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsx
index af883768f323..350bc3cccf69 100644
--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx
+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx
@@ -28,6 +28,7 @@ import {
readConfig,
readResult,
} from '../components/ObservationCard'
+import { ObservationProgressBar } from '../components/ObservationProgressBar'
import {
failureKindDescription,
modelLabel,
@@ -278,9 +279,7 @@ export function ReplayObservationSceneComponent({ tabId }: { tabId: string }): J
)}
{(observation.status === 'pending' || observation.status === 'running') && (
- <div className="text-muted text-sm">
- {observation.status === 'pending' ? 'Queued…' : 'Analyzing recording…'}
- </div>
+ <ObservationProgressBar observationId={observation.id} sessionId={observation.session_id} />
)}
</section>
diff --git a/products/replay_vision/frontend/observations/observationProgressLogic.ts b/products/replay_vision/frontend/observations/observationProgressLogic.ts
new file mode 100644
index 000000000000..c12e2e770b5d
--- /dev/null
+++ b/products/replay_vision/frontend/observations/observationProgressLogic.ts
@@ -0,0 +1,150 @@
+import { actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { observationsDockLogic } from '../logics/observationsDockLogic'
+import type { observationProgressLogicType } from './observationProgressLogicType'
+
+export interface ObservationFrameProgress {
+ frame: number
+ estimatedTotalFrames: number
+}
+
+export interface ObservationRasterizerProgress {
+ frame_progress: ObservationFrameProgress | null
+}
+
+/** Live progress payload from the `observation-progress` SSE event (mirrors backend ObservationProgress). */
+export interface ObservationProgress {
+ phase: string
+ step: number
+ total_steps: number
+ rasterizer: ObservationRasterizerProgress | null
+}
+
+export interface ObservationProgressLogicProps {
+ observationId: string
+ /** Lets the dock list refresh on completion; optional since the details page has no dock. */
+ sessionId?: string
+}
+
+interface StreamHandlers {
+ setProgress: (progress: ObservationProgress) => void
+ streamCompleted: () => void
+ setStreamError: (error: string) => void
+}
+
+/** Parse one SSE block (`event: <label>\ndata: <json>`) from our progress endpoint and dispatch it. */
+function dispatchSseBlock(block: string, handlers: StreamHandlers): void {
+ let event = ''
+ const dataLines: string[] = []
+ for (const line of block.split('\n')) {
+ if (line.startsWith('event:')) {
+ event = line.slice('event:'.length).trim()
+ } else if (line.startsWith('data:')) {
+ dataLines.push(line.slice('data:'.length).replace(/^ /, ''))
+ }
+ }
+ const data = dataLines.join('\n')
+ if (event === 'observation-progress') {
+ try {
+ handlers.setProgress(JSON.parse(data))
+ } catch {
+ // Drop an unparseable tick; the next one refreshes the bar.
+ }
+ } else if (event === 'observation-complete') {
+ handlers.streamCompleted()
+ } else if (event === 'observation-error') {
+ handlers.setStreamError(data)
+ }
+}
+
+async function consumeProgressStream(
+ teamId: number,
+ observationId: string,
+ signal: AbortSignal,
+ handlers: StreamHandlers
+): Promise<void> {
+ // Plain GET so read-only users can stream too (api.createResponse POSTs, which is blocked for them).
+ const response = await fetch(`/api/projects/${teamId}/vision/observations/${observationId}/progress/`, {
+ method: 'GET',
+ headers: { Accept: 'text/event-stream' },
+ credentials: 'same-origin',
+ signal,
+ })
+ if (!response.ok || !response.body) {
+ return
+ }
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let buffer = ''
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) {
+ break
+ }
+ buffer += decoder.decode(value, { stream: true })
+ let boundary = buffer.indexOf('\n\n')
+ while (boundary !== -1) {
+ dispatchSseBlock(buffer.slice(0, boundary), handlers)
+ buffer = buffer.slice(boundary + 2)
+ boundary = buffer.indexOf('\n\n')
+ }
+ }
+}
+
+/**
+ * Streams live progress for one in-flight observation over SSE. Keyed by observation id, so the dock card and the
+ * details page share a single stream. The stream self-terminates once the observation settles.
+ */
+export const observationProgressLogic = kea<observationProgressLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'observations', 'observationProgressLogic']),
+ props({} as ObservationProgressLogicProps),
+ key((props) => props.observationId),
+
+ actions({
+ setProgress: (progress: ObservationProgress) => ({ progress }),
+ streamCompleted: true,
+ setStreamError: (error: string) => ({ error }),
+ }),
+
+ reducers({
+ progress: [
+ null as ObservationProgress | null,
+ {
+ setProgress: (_, { progress }) => progress,
+ },
+ ],
+ streamError: [
+ null as string | null,
+ {
+ setStreamError: (_, { error }) => error,
+ },
+ ],
+ }),
+
+ listeners(({ props }) => ({
+ streamCompleted: () => {
+ // Refresh the dock list so the finished card swaps its progress bar for the result immediately,
+ // instead of lingering until the next poll. No-op where the dock isn't mounted (e.g. details page).
+ if (props.sessionId) {
+ observationsDockLogic.findMounted({ sessionId: props.sessionId })?.actions.loadObservations()
+ }
+ },
+ })),
+
+ afterMount(({ props, actions, cache }) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ // Disposable so the fetch is aborted on unmount and paused while the tab is hidden.
+ cache.disposables.add(() => {
+ const controller = new AbortController()
+ void consumeProgressStream(teamId, props.observationId, controller.signal, actions).catch(() => {
+ // Network/abort errors are non-fatal — the bar falls back to its time-based animation.
+ })
+ return () => controller.abort()
+ }, 'progressStream')
+ }),
+])
diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.ts b/products/replay_vision/frontend/observations/replayObservationLogic.ts
index f4e64994efd3..16d1ad33df66 100644
--- a/products/replay_vision/frontend/observations/replayObservationLogic.ts
+++ b/products/replay_vision/frontend/observations/replayObservationLogic.ts
@@ -1,10 +1,11 @@
-import { actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { visionObservationsRetrieve } from '../generated/api'
import type { ReplayObservationApi } from '../generated/api.schemas'
+import { observationProgressLogic } from './observationProgressLogic'
import type { replayObservationLogicType } from './replayObservationLogicType'
import { replayObservationSceneLogic } from './replayObservationSceneLogic'
@@ -18,6 +19,11 @@ export const replayObservationLogic = kea<replayObservationLogicType>([
props({} as ReplayObservationLogicProps),
key((props) => `${props.tabId}:${props.id}`),
+ // Mount the SSE progress stream alongside the page and listen for its completion to reload the row.
+ connect((props: ReplayObservationLogicProps) => ({
+ actions: [observationProgressLogic({ observationId: props.id }), ['streamCompleted']],
+ })),
+
actions({
loadObservation: true,
loadObservationSuccess: (observation: ReplayObservationApi) => ({ observation }),
@@ -60,6 +66,11 @@ export const replayObservationLogic = kea<replayObservationLogicType>([
actions.loadObservationFailure()
}
},
+
+ // When the stream reports the observation has settled, reload once to render the final result.
+ streamCompleted: () => {
+ actions.loadObservation()
+ },
})),
afterMount(({ actions }) => {