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(replay-vision): make observation progress a single bar that only moves forward (#115126)

Tue Haulund13f6f77e9ae9
diff --git a/products/replay_vision/backend/api/observation_progress.py b/products/replay_vision/backend/api/observation_progress.py
index 086a05e5b1e0..8eb0f26b1c65 100644
--- a/products/replay_vision/backend/api/observation_progress.py
+++ b/products/replay_vision/backend/api/observation_progress.py
@@ -1,6 +1,7 @@
import json
import time
import asyncio
+import datetime as dt
from collections.abc import AsyncGenerator
from dataclasses import dataclass
from typing import Any
@@ -31,6 +32,11 @@ PROGRESS_POLL_INTERVAL_S = 1.5
# client never disconnects. Observations finish in minutes; well past that we close and free the worker.
MAX_STREAM_DURATION_S = 10 * 60
+# A query or describe waits on a busy worker; without a bound one slow call stalls every tick behind it.
+TEMPORAL_RPC_TIMEOUT = dt.timedelta(seconds=5)
+
+RASTERIZE_ACTIVITY_TYPE = "rasterize-recording"
+
def _sse_event(label: str, data: str) -> str:
return f"event: {label}\ndata: {data}\n\n"
@@ -62,6 +68,7 @@ def _fallback_progress(status: str) -> ObservationProgress:
"step": OBSERVATION_PHASE_INDEX[phase],
"total_steps": len(OBSERVATION_PHASE_ORDER),
"rasterizer_workflow_id": None,
+ "phase_started_at": None,
}
@@ -69,11 +76,15 @@ async def _read_rasterizer_frame_progress(client: Any, rasterizer_workflow_id: s
"""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()
+ desc = await child_handle.describe(rpc_timeout=TEMPORAL_RPC_TIMEOUT)
pending = getattr(desc.raw_description, "pending_activities", None) or []
- if not pending:
+ render = next((p for p in pending if p.activity_type.name == RASTERIZE_ACTIVITY_TYPE), None)
+ if render is None:
+ return None
+ # Heartbeat details carry over to a retry, so details older than the current attempt are a dead attempt's.
+ if render.last_heartbeat_time.ToDatetime() < render.last_started_time.ToDatetime():
return None
- raw_payloads = list(pending[0].heartbeat_details.payloads)
+ raw_payloads = list(render.heartbeat_details.payloads)
if not raw_payloads:
return None
codec = getattr(client.data_converter, "payload_codec", None)
@@ -86,9 +97,14 @@ async def _read_rasterizer_frame_progress(client: Any, rasterizer_workflow_id: s
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")
+ payload: dict[str, Any] = await client.get_workflow_handle(workflow_id).query(
+ "get_progress", rpc_timeout=TEMPORAL_RPC_TIMEOUT
+ )
except Exception:
- return None # Workflow not queryable yet/anymore — caller falls back to a status-derived payload.
+ return None # Workflow not queryable yet/anymore — caller repeats its last tick or a status-derived one.
+ phase_started_at = payload.get("phase_started_at")
+ # Elapsed rather than a timestamp, so the client needs no clock agreement with the server.
+ payload["phase_elapsed_s"] = max(0.0, time.time() - phase_started_at) if phase_started_at else None
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)
@@ -102,6 +118,7 @@ async def stream_observation_progress(observation: ReplayObservation) -> AsyncGe
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.
+ At the duration cap the stream closes without a terminal event, and the client reconnects.
"""
observation_id = observation.id
team_id = observation.team_id
@@ -117,12 +134,12 @@ async def stream_observation_progress(observation: ReplayObservation) -> AsyncGe
client = None # Without Temporal we still tick a status-derived payload so the bar moves.
deadline = time.monotonic() + MAX_STREAM_DURATION_S
+ last_payload: dict[str, Any] | None = None
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:
@@ -134,7 +151,10 @@ async def stream_observation_progress(observation: ReplayObservation) -> AsyncGe
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)))
+ if payload is not None:
+ last_payload = payload
+ # A failed query repeats the last real tick; the status fallback would report an earlier phase.
+ yield _sse_event("observation-progress", json.dumps(last_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.
diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.py
index 2f2820a4c566..47ac4dfe3e3b 100644
--- a/products/replay_vision/backend/temporal/types.py
+++ b/products/replay_vision/backend/temporal/types.py
@@ -104,6 +104,8 @@ class ObservationProgress(TypedDict):
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
+ # Workflow-clock epoch seconds, so a client that joins mid-phase still sees the true elapsed time.
+ phase_started_at: float | None
class MarkObservationFailedInputs(BaseModel, frozen=True):
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index 3a8eccc596ac..48aea9a0c1cf 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -270,6 +270,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
"step": 0,
"total_steps": len(OBSERVATION_PHASE_ORDER),
"rasterizer_workflow_id": None,
+ "phase_started_at": None,
}
@wf.query
@@ -280,12 +281,14 @@ class ApplyScannerWorkflow(PostHogWorkflow):
def _advance_phase(self, phase: str, rasterizer_workflow_id: str | None = None) -> None:
self._progress["phase"] = phase
self._progress["step"] = OBSERVATION_PHASE_INDEX[phase]
+ self._progress["phase_started_at"] = wf.now().timestamp()
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
+ self._progress["phase_started_at"] = wf.now().timestamp()
create_result: CreateObservationOutput = await wf.execute_activity(
create_observation_activity,
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index ecefda45e111..7963a99fee2d 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -42,7 +42,7 @@ from posthog.session_recordings.queries.session_replay_events import SessionEven
from posthog.session_recordings.session_recording_v2_service import RecordingBlock
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.api.observation_progress import _ObservationState, stream_observation_progress
from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.enqueue_claims import (
_RELEASE_GRACE_SECONDS,
@@ -2758,6 +2758,7 @@ async def _run_workflow(
patch("temporalio.workflow.execute_child_workflow", side_effect=mocks.execute_child_workflow),
# `wf.logger` requires a real workflow event loop, which this direct-call harness skips.
patch("temporalio.workflow.logger"),
+ patch("temporalio.workflow.now", return_value=dt.datetime(2026, 1, 1, tzinfo=dt.UTC)),
):
await ApplyScannerWorkflow().run(inputs)
@@ -3140,6 +3141,9 @@ async def test_apply_scanner_workflow_exits_when_create_returns_was_created_fals
assert mocks.child_calls == []
+_PROGRESS_MODULE = "products.replay_vision.backend.api.observation_progress"
+
+
def test_workflow_get_progress_advances_through_phases() -> None:
workflow = ApplyScannerWorkflow()
assert workflow.get_progress() == {
@@ -3147,16 +3151,21 @@ def test_workflow_get_progress_advances_through_phases() -> None:
"step": 0,
"total_steps": 6,
"rasterizer_workflow_id": None,
+ "phase_started_at": None,
}
- workflow._advance_phase("rendering", rasterizer_workflow_id="rast-1")
+ rendering_started = dt.datetime(2026, 1, 1, 12, 0, tzinfo=dt.UTC)
+ with patch("temporalio.workflow.now", return_value=rendering_started):
+ 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"
+ assert progress["phase_started_at"] == rendering_started.timestamp()
# A later phase without an id keeps the previously recorded rasterizer id.
- workflow._advance_phase("analyzing")
+ with patch("temporalio.workflow.now", return_value=rendering_started):
+ workflow._advance_phase("analyzing")
assert workflow.get_progress()["phase"] == "analyzing"
assert workflow.get_progress()["rasterizer_workflow_id"] == "rast-1"
@@ -3170,6 +3179,29 @@ async def test_progress_stream_completes_immediately_for_terminal_observation()
assert '"status": "succeeded"' in events[0]
+async def test_progress_stream_repeats_last_tick_when_query_fails() -> None:
+ observation = ReplayObservation(id=uuid.uuid4(), team_id=1, status=ObservationStatus.RUNNING)
+ analyzing = {"phase": "analyzing", "step": 4, "total_steps": 6, "rasterizer_workflow_id": None}
+ states = iter(
+ [
+ _ObservationState(status=ObservationStatus.RUNNING, workflow_id="wf-1"),
+ _ObservationState(status=ObservationStatus.RUNNING, workflow_id="wf-1"),
+ _ObservationState(status=ObservationStatus.SUCCEEDED, workflow_id="wf-1"),
+ ]
+ )
+ with (
+ patch(f"{_PROGRESS_MODULE}.async_connect", AsyncMock(return_value=MagicMock())),
+ patch(f"{_PROGRESS_MODULE}._read_observation_state", AsyncMock(side_effect=lambda *_: next(states))),
+ patch(f"{_PROGRESS_MODULE}._query_progress", AsyncMock(side_effect=[analyzing, None])),
+ patch(f"{_PROGRESS_MODULE}.asyncio.sleep", AsyncMock()),
+ ):
+ events = [event async for event in stream_observation_progress(observation)]
+
+ phases = [json.loads(e.split("data: ", 1)[1])["phase"] for e in events if "observation-progress" in e]
+ assert phases == ["analyzing", "analyzing"]
+ assert "observation-complete" in events[-1]
+
+
@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 50caf903767b..be67c03e6564 100644
--- a/products/replay_vision/frontend/components/ObservationCard.tsx
+++ b/products/replay_vision/frontend/components/ObservationCard.tsx
@@ -505,7 +505,7 @@ export function ObservationDockCard({
)}
{(observation.status === 'pending' || observation.status === 'running') && (
- <ObservationProgressBar observationId={observation.id} sessionId={observation.session_id} compact />
+ <ObservationProgressBar observationId={observation.id} sessionId={observation.session_id} />
)}
</div>
)
diff --git a/products/replay_vision/frontend/components/ObservationProgressBar.tsx b/products/replay_vision/frontend/components/ObservationProgressBar.tsx
index 1c1837e79dbd..42aa952ad4ef 100644
--- a/products/replay_vision/frontend/components/ObservationProgressBar.tsx
+++ b/products/replay_vision/frontend/components/ObservationProgressBar.tsx
@@ -1,156 +1,57 @@
import { useActions, useValues } from 'kea'
-import { useEffect, useRef } from 'react'
+import { useEffect } from 'react'
-import { IconCheckCircle, IconCircleDashed, IconWarning } from '@posthog/icons'
+import { IconWarning } from '@posthog/icons'
import { Spinner } from '@posthog/lemon-ui'
-import { usePeriodicRerender } from 'lib/hooks/usePeriodicRerender'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { DISPLAY_PHASES } from '../observations/observationProgress'
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',
-}
-
-// Per-phase time constants (seconds) for an asymptotic fill (~63% at tau, ~86% at 2*tau) so the bar keeps moving.
-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, phaseStartedAt, streamError } = useValues(observationProgressLogic({ observationId, sessionId }))
- const { startStream } = useActions(observationProgressLogic({ observationId, sessionId }))
- usePeriodicRerender(1000)
+ const logic = observationProgressLogic({ observationId, sessionId })
+ const { percent, displayPhase, stepNumber, frames, streamError } = useValues(logic)
+ const { startStream } = useActions(logic)
- const mountedAtRef = useRef(Date.now())
useEffect(() => {
- mountedAtRef.current = Date.now()
startStream()
}, [observationId, startStream])
- const currentStep = Math.min(progress?.step ?? 0, PHASE_ORDER.length - 1)
- const activePhase = PHASE_ORDER[currentStep]
- const activeStartedAt = phaseStartedAt[currentStep] ?? mountedAtRef.current
- const activeElapsed = Math.max(0, (Date.now() - activeStartedAt) / 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 (streamError) {
// The stream died but the observation may still be running — status polling keeps the page truthful.
return (
<div className="flex items-center gap-2 text-muted text-sm">
<IconWarning className="text-warning text-base shrink-0" />
- <span>Live progress unavailable: {streamError}</span>
+ <span>Live progress isn't available. This updates when the observation finishes.</span>
</div>
)
}
- 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 />
- {/* `detail` ticks every second and comes and goes. Left bare it is a text node
- React tracks, so a page-translation extension replacing it with a <font>
- element freezes it and makes its removal throw removeChild NotFoundError
- (react#11538). The phase label is static and stays translatable. */}
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center gap-2 text-muted text-sm">
+ <Spinner textColored />
+ <span className="min-w-0 truncate">{displayPhase.label}…</span>
+ </div>
+ <LemonProgress percent={percent} />
+ {/* Ticking numbers skip page translation, which would otherwise freeze them and crash React on removal (react#11538). */}
+ <div className="flex items-center justify-between gap-2 text-muted text-xs" translate="no">
+ <span>
+ Step {stepNumber} of {DISPLAY_PHASES.length}
+ </span>
+ {frames && (
<span>
- {PHASE_LABELS[activePhase]}
- <span translate="no">{detail}</span>…
+ {frames.frame.toLocaleString()} / {frames.estimatedTotalFrames.toLocaleString()} frames
</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" translate="no">
- &nbsp;({detail})
- </span>
- ) : null}
- </span>
- </div>
- <div className="pl-6">
- <LemonProgress percent={barPercent} />
- </div>
- </div>
- )
- })}
</div>
)
}
diff --git a/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx b/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx
index 5e0ef58634b1..b0dccb937dcd 100644
--- a/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx
+++ b/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx
@@ -279,11 +279,7 @@ function FocusPane({
</div>
)}
{isInFlight(observation) && (
- <ObservationProgressBar
- observationId={observation.id}
- sessionId={observation.session_id}
- compact
- />
+ <ObservationProgressBar observationId={observation.id} sessionId={observation.session_id} />
)}
</div>
)}
diff --git a/products/replay_vision/frontend/observations/observationProgress.ts b/products/replay_vision/frontend/observations/observationProgress.ts
new file mode 100644
index 000000000000..74351f51ef24
--- /dev/null
+++ b/products/replay_vision/frontend/observations/observationProgress.ts
@@ -0,0 +1,76 @@
+export interface ObservationFrameProgress {
+ phase?: 'setup' | 'capture' | 'upload'
+ 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
+ // Optional: the backend's fallback tick omits these keys entirely.
+ phase_elapsed_s?: number | null
+ rasterizer?: ObservationRasterizerProgress | null
+}
+
+export interface DisplayPhase {
+ label: string
+ weight: number
+ /** Time constant (seconds) for the time-based fill. */
+ tauS: number
+}
+
+// Weights and time constants follow measured production phase durations; only rendering has real progress (frames).
+export const DISPLAY_PHASES: DisplayPhase[] = [
+ { label: 'Preparing recording', weight: 20, tauS: 20 },
+ { label: 'Rendering video', weight: 25, tauS: 15 },
+ { label: 'Analyzing recording', weight: 53, tauS: 45 },
+ { label: 'Finishing up', weight: 2, tauS: 2 },
+]
+
+const RENDERING_STEP = 1
+
+// A time-based fill stops short of its phase's end, so the next phase's real start is never a step back.
+const TIME_FILL_CAP = 0.9
+
+export function framesOf(progress: ObservationProgress | null): ObservationFrameProgress | null {
+ const frames = progress?.rasterizer?.frame_progress
+ if (!frames || frames.estimatedTotalFrames <= 0 || frames.phase === 'setup') {
+ return null
+ }
+ return frames
+}
+
+/** Rendering counts only once frames exist, so the rasterizer queue and browser setup read as preparing. */
+export function displayStepFor(progress: ObservationProgress): number {
+ switch (progress.phase) {
+ case 'rendering':
+ return framesOf(progress) ? RENDERING_STEP : 0
+ case 'uploading':
+ case 'analyzing':
+ return 2
+ case 'finalizing':
+ return 3
+ default:
+ return 0
+ }
+}
+
+export function isRenderingStep(step: number): boolean {
+ return step === RENDERING_STEP
+}
+
+export function overallPercent(step: number, stepElapsedS: number, frames: ObservationFrameProgress | null): number {
+ const phase = DISPLAY_PHASES[step]
+ const before = DISPLAY_PHASES.slice(0, step).reduce((sum, p) => sum + p.weight, 0)
+ const fill =
+ isRenderingStep(step) && frames
+ ? Math.min(frames.frame / frames.estimatedTotalFrames, 1)
+ : (1 - Math.exp(-Math.max(0, stepElapsedS) / phase.tauS)) * TIME_FILL_CAP
+ return before + phase.weight * fill
+}
diff --git a/products/replay_vision/frontend/observations/observationProgressLogic.test.ts b/products/replay_vision/frontend/observations/observationProgressLogic.test.ts
index 5e53affb73b1..6c913396960f 100644
--- a/products/replay_vision/frontend/observations/observationProgressLogic.test.ts
+++ b/products/replay_vision/frontend/observations/observationProgressLogic.test.ts
@@ -1,44 +1,79 @@
import { initKeaTests } from '~/test/init'
-import { type ObservationProgress, observationProgressLogic } from './observationProgressLogic'
+import { type ObservationProgress } from './observationProgress'
+import { observationProgressLogic } from './observationProgressLogic'
-const tick = (step: number): ObservationProgress => ({ phase: 'any', step, total_steps: 6 })
+const tick = (phase: string, extra: Partial<ObservationProgress> = {}): ObservationProgress => ({
+ phase,
+ step: 0,
+ total_steps: 6,
+ ...extra,
+})
+
+const rendering = (
+ frame: number,
+ estimatedTotalFrames: number,
+ stage: 'setup' | 'capture' = 'capture'
+): ObservationProgress =>
+ tick('rendering', { rasterizer: { frame_progress: { phase: stage, frame, estimatedTotalFrames } } })
describe('observationProgressLogic', () => {
beforeEach(() => {
initKeaTests()
})
- it.each([
- ['progress', (logic: ReturnType<typeof observationProgressLogic.build>) => logic.values.progress, tick(2)],
- [
- 'phase start times',
- (logic: ReturnType<typeof observationProgressLogic.build>) => logic.values.phaseStartedAt,
- { 1: 1000, 2: 2000 },
- ],
- ])('keeps %s across a remount', (_, read, expected) => {
+ it('keeps the phase and percent across a remount', () => {
const first = observationProgressLogic({ observationId: 'obs-1' })
const unmount = first.mount()
- first.actions.setProgress(tick(1), 1000)
- first.actions.setProgress(tick(1), 1500)
- first.actions.setProgress(tick(2), 2000)
+ first.actions.setProgress(tick('fetching'), 1000)
+ first.actions.setProgress(tick('analyzing'), 20000)
+ first.actions.tick(50000)
+ const percent = first.values.percent
unmount()
const second = observationProgressLogic({ observationId: 'obs-1' })
second.mount()
- expect(read(second)).toEqual(expected)
+ expect(second.values.displayPhase.label).toEqual('Analyzing recording')
+ expect(second.values.percent).toEqual(percent)
})
it('forgets a settled observation', () => {
const first = observationProgressLogic({ observationId: 'obs-2' })
const unmount = first.mount()
- first.actions.setProgress(tick(3), 1000)
+ first.actions.setProgress(tick('analyzing'), 1000)
first.actions.streamCompleted()
unmount()
const second = observationProgressLogic({ observationId: 'obs-2' })
second.mount()
expect(second.values.progress).toBeNull()
- expect(second.values.phaseStartedAt).toEqual({})
+ expect(second.values.percent).toEqual(0)
+ })
+
+ it.each([
+ ['a failed query falls back to an earlier phase', [tick('analyzing'), tick('fetching')], 'Analyzing recording'],
+ [
+ 'frame counts start after a long renderer setup',
+ [tick('fetching'), rendering(0, 0, 'setup'), rendering(0, 900)],
+ 'Rendering video',
+ ],
+ ['a render retry restarts the frame count', [rendering(800, 900), rendering(5, 900)], 'Rendering video'],
+ ])('never moves the bar back when %s', (_, ticks, expectedLabel) => {
+ const logic = observationProgressLogic({ observationId: `obs-${expectedLabel}-${ticks.length}` })
+ logic.mount()
+ const percents: number[] = []
+ ticks.forEach((progress, i) => {
+ logic.actions.setProgress(progress, (i + 1) * 60_000)
+ percents.push(logic.values.percent)
+ })
+ expect(percents).toEqual([...percents].sort((a, b) => a - b))
+ expect(logic.values.displayPhase.label).toEqual(expectedLabel)
+ })
+
+ it('starts a phase at its server elapsed time, so a late joiner sees the bar already filled', () => {
+ const logic = observationProgressLogic({ observationId: 'obs-late' })
+ logic.mount()
+ logic.actions.setProgress(tick('analyzing', { phase_elapsed_s: 120 }), 1000)
+ expect(logic.values.percent).toBeGreaterThan(70)
})
})
diff --git a/products/replay_vision/frontend/observations/observationProgressLogic.ts b/products/replay_vision/frontend/observations/observationProgressLogic.ts
index 920a1d05bded..f4a005fc58b5 100644
--- a/products/replay_vision/frontend/observations/observationProgressLogic.ts
+++ b/products/replay_vision/frontend/observations/observationProgressLogic.ts
@@ -1,41 +1,42 @@
-import { MakeLogicType, actions, kea, key, listeners, path, props, reducers } from 'kea'
+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { teamLogic } from 'scenes/teamLogic'
import { observationsDockLogic } from '../logics/observationsDockLogic'
+import {
+ DISPLAY_PHASES,
+ type DisplayPhase,
+ type ObservationFrameProgress,
+ type ObservationProgress,
+ displayStepFor,
+ framesOf,
+ isRenderingStep,
+ overallPercent,
+} from './observationProgress'
-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
+interface DisplayState {
step: number
- total_steps: number
- // Optional: the backend's fallback tick omits the key entirely.
- rasterizer?: ObservationRasterizerProgress | null
+ /** Client-clock ms when the current display step started. */
+ startedAt: number
}
-export type PhaseStartedAt = Record<number, number>
-
interface RememberedProgress {
progress: ObservationProgress | null
- phaseStartedAt: PhaseStartedAt
+ display: DisplayState | null
+ percent: number
}
// Survives unmount so a reopened tab or dock resumes the bar instead of restarting it.
const progressMemory = new Map<string, RememberedProgress>()
function rememberedProgress(observationId: string): RememberedProgress {
- return progressMemory.get(observationId) ?? { progress: null, phaseStartedAt: {} }
+ return progressMemory.get(observationId) ?? { progress: null, display: null, percent: 0 }
}
+const PROGRESS_TICK_MS = 1000
+const RECONNECT_INITIAL_DELAY_MS = 2000
+const RECONNECT_MAX_DELAY_MS = 30000
+
export interface ObservationProgressLogicProps {
observationId: string
/** Lets the dock list refresh on completion; optional since the details page has no dock. */
@@ -78,7 +79,7 @@ async function consumeProgressStream(
observationId: string,
signal: AbortSignal,
handlers: StreamHandlers
-): Promise<void> {
+): Promise<boolean> {
// 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',
@@ -87,19 +88,21 @@ async function consumeProgressStream(
signal,
})
if (!response.ok || !response.body) {
- return
+ return false
}
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
+ let received = false
while (true) {
const { done, value } = await reader.read()
if (done) {
- break
+ return received
}
buffer += decoder.decode(value, { stream: true })
let boundary = buffer.indexOf('\n\n')
while (boundary !== -1) {
+ received = true
dispatchSseBlock(buffer.slice(0, boundary), handlers)
buffer = buffer.slice(boundary + 2)
boundary = buffer.indexOf('\n\n')
@@ -107,15 +110,56 @@ async function consumeProgressStream(
}
}
+function waitFor(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ const onAbort = (): void => {
+ clearTimeout(timer)
+ resolve()
+ }
+ const timer = setTimeout(() => {
+ signal.removeEventListener('abort', onAbort)
+ resolve()
+ }, ms)
+ signal.addEventListener('abort', onAbort, { once: true })
+ })
+}
+
+/** The server caps stream length and proxies drop idle streams, so any close short of a terminal event reconnects. */
+async function followProgressStream(
+ teamId: number,
+ observationId: string,
+ signal: AbortSignal,
+ handlers: StreamHandlers
+): Promise<void> {
+ let delayMs = RECONNECT_INITIAL_DELAY_MS
+ while (!signal.aborted) {
+ let received = false
+ try {
+ received = await consumeProgressStream(teamId, observationId, signal, handlers)
+ } catch {
+ // An abort ends the loop; other errors reconnect.
+ }
+ delayMs = received ? RECONNECT_INITIAL_DELAY_MS : Math.min(delayMs * 2, RECONNECT_MAX_DELAY_MS)
+ await waitFor(delayMs, signal)
+ }
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationProgressLogicValues {
- phaseStartedAt: PhaseStartedAt
+ display: DisplayState | null
+ displayPhase: DisplayPhase
+ frames: ObservationFrameProgress | null
+ percent: number
progress: ObservationProgress | null
+ stepNumber: number
streamError: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationProgressLogicActions {
+ setPercent: (percent: number) => {
+ percent: number
+ }
setProgress: (
progress: ObservationProgress,
receivedAt?: number
@@ -132,11 +176,19 @@ export interface observationProgressLogicActions {
streamCompleted: () => {
value: true
}
+ tick: (now?: number) => {
+ now: number
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationProgressLogicMeta {
key: string
+ __keaTypeGenInternalSelectorTypes: {
+ frames: (progress: ObservationProgress | null) => ObservationFrameProgress | null
+ displayPhase: (display: DisplayState | null) => DisplayPhase
+ stepNumber: (display: DisplayState | null) => number
+ }
}
export type observationProgressLogicType = MakeLogicType<
@@ -159,6 +211,8 @@ export const observationProgressLogic = kea<observationProgressLogicType>([
// Idempotent — callers that know the observation is in flight open the stream; settled rows never do.
startStream: true,
setProgress: (progress: ObservationProgress, receivedAt: number = Date.now()) => ({ progress, receivedAt }),
+ tick: (now: number = Date.now()) => ({ now }),
+ setPercent: (percent: number) => ({ percent }),
streamCompleted: true,
setStreamError: (error: string) => ({ error }),
}),
@@ -170,11 +224,25 @@ export const observationProgressLogic = kea<observationProgressLogicType>([
setProgress: (_, { progress }) => progress,
},
],
- phaseStartedAt: [
- rememberedProgress(props.observationId).phaseStartedAt,
+ display: [
+ rememberedProgress(props.observationId).display,
{
- setProgress: (state, { progress, receivedAt }) =>
- progress.step in state ? state : { ...state, [progress.step]: receivedAt },
+ setProgress: (state, { progress, receivedAt }) => {
+ const step = displayStepFor(progress)
+ // A stale tick (failed query, render retry) must not pull the bar back.
+ if (state && step <= state.step) {
+ return state
+ }
+ // Rendering is measured in frames, so only time-filled steps need the server's elapsed time.
+ const elapsedMs = isRenderingStep(step) ? 0 : (progress.phase_elapsed_s ?? 0) * 1000
+ return { step, startedAt: receivedAt - elapsedMs }
+ },
+ },
+ ],
+ percent: [
+ rememberedProgress(props.observationId).percent,
+ {
+ setPercent: (state, { percent }) => Math.max(state, percent),
},
],
streamError: [
@@ -185,11 +253,32 @@ export const observationProgressLogic = kea<observationProgressLogicType>([
],
})),
+ selectors({
+ frames: [
+ (s) => [s.progress],
+ (progress: ObservationProgress | null): ObservationFrameProgress | null => framesOf(progress),
+ ],
+ displayPhase: [
+ (s) => [s.display],
+ (display: DisplayState | null): DisplayPhase => DISPLAY_PHASES[display?.step ?? 0],
+ ],
+ stepNumber: [(s) => [s.display], (display: DisplayState | null): number => (display?.step ?? 0) + 1],
+ }),
+
listeners(({ props, actions, cache, values }) => ({
- setProgress: () => {
+ setProgress: ({ receivedAt }) => {
+ actions.tick(receivedAt)
+ },
+ tick: ({ now }) => {
+ const { display, frames } = values
+ if (display) {
+ const elapsedS = (now - display.startedAt) / 1000
+ actions.setPercent(overallPercent(display.step, elapsedS, frames))
+ }
progressMemory.set(props.observationId, {
progress: values.progress,
- phaseStartedAt: values.phaseStartedAt,
+ display: values.display,
+ percent: values.percent,
})
},
startStream: () => {
@@ -201,15 +290,18 @@ export const observationProgressLogic = kea<observationProgressLogicType>([
// 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.
- })
+ void followProgressStream(teamId, props.observationId, controller.signal, actions)
return () => controller.abort()
}, 'progressStream')
+ cache.disposables.add(() => {
+ const interval = setInterval(() => actions.tick(), PROGRESS_TICK_MS)
+ return () => clearInterval(interval)
+ }, 'progressTicker')
},
streamCompleted: () => {
// The observation settled — dispose the stream so tab hide/show cycles don't resurrect it.
cache.disposables.dispose('progressStream')
+ cache.disposables.dispose('progressTicker')
progressMemory.delete(props.observationId)
// Refresh the dock list so the finished card swaps to the result immediately; no-op if the dock isn't mounted.
if (props.sessionId) {
@@ -218,6 +310,7 @@ export const observationProgressLogic = kea<observationProgressLogicType>([
},
setStreamError: () => {
cache.disposables.dispose('progressStream')
+ cache.disposables.dispose('progressTicker')
},
})),
])