The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
fix: cap sessions at the SDK's max duration so zombie segments stop inflating replays (#380)
Jovan Stojiljkovic1d6a8e6a4371
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8248f534..13f19ddb 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1116,7 +1116,7 @@ Observability (emitted every 10s via `traceway.CaptureMetric`):Sustained drops also fire a rate-limited (1/min) `traceway.CaptureException` so overload is visible in the issues feed without flooding it.-**Session end is derived on read.** The browser SDK's closing payload is unreliable (a keepalive body over 64 KB is rejected on unload, and frozen mobile tabs never fire `pagehide`), so the stored `sessions.ended_at` is only a hint. Each segment row carries its client-side `ended_at` (`ch/0100`, `sqlite_telemetry/0027`, `duckdb_telemetry/0008`), and every session read joins the latest segment activity and applies `shared.ResolveSessionEnd`: an explicit end is kept only when it lands within `SessionIdleTimeout` (15 min, the SDK's inactivity timeout) after the last activity, otherwise the session ends at its last activity; it is still live while a segment arrived (server time) within the timeout. `HasRecording` is set when any segment exists, and the frontend labels an old session with neither as "No recording" (`utils/session-duration.ts`). Sorting the list by duration uses a SQL copy of the same rule in each backend (`sessionDurationSortKey`); `TestSessionRepository_EndFromRecordingActivity` holds the SQL order to the Go rule. `GET /api/sessions/:id/recording?startedAt=` bounds the segment lookup to the session's window, and segments are read from storage 16 at a time.+**Session end is derived on read.** The browser SDK's closing payload is unreliable (a keepalive body over 64 KB is rejected on unload, and frozen mobile tabs never fire `pagehide`), so the stored `sessions.ended_at` is only a hint. Each segment row carries its client-side `ended_at` (`ch/0100`, `sqlite_telemetry/0027`, `duckdb_telemetry/0008`), and every session read joins the latest segment activity and applies `shared.ResolveSessionEnd`: an explicit end is kept only when it lands within `SessionIdleTimeout` (15 min, the SDK's inactivity timeout) after the last activity, otherwise the session ends at its last activity; it is still live while a segment arrived (server time) within the timeout. Every session is capped at `shared.SessionMaxSpan` (65 min: the SDK's 60 min cap plus slack) because `@tracewayapp/frontend` <= 1.2.0 kept uploading segments under an ended session id for the tab's whole lifetime (18h "sessions"); the end and duration are clamped to it (sessions without segments too), except that when segments run past it a stored close inside it wins (the SDK's own 60 min close; `Session.CutoffAt` carries the resulting cut-off), a session whose segments run past it is never live (compared on the client clock, so skew between browser and server cannot end a live session), and the session detail and `GET /api/sessions/:id/recording` drop exceptions and segments past `CutoffAt`, anchored on the stored session start rather than the `startedAt` query param (`shared.SegmentsWithinSession`). `HasRecording` is set when any segment exists, and the frontend labels an old session with neither as "No recording" (`utils/session-duration.ts`). Sorting the list by duration uses a SQL copy of the same rule in each backend (`sessionDurationSortKey`); `TestSessionRepository_EndFromRecordingActivity` holds the SQL order to the Go rule. `GET /api/sessions/:id/recording?startedAt=` bounds the segment lookup to the session's window, and segments are read from storage 16 at a time.#### Users, Organizations & Projectsdiff --git a/backend/app/controllers/session_detail.controller.go b/backend/app/controllers/session_detail.controller.goindex de5e067b..7cfb2575 100644--- a/backend/app/controllers/session_detail.controller.go+++ b/backend/app/controllers/session_detail.controller.go@@ -9,6 +9,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/repositories/telemetry"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""github.com/tracewayapp/traceway/backend/app/storage""golang.org/x/sync/errgroup"@@ -65,10 +66,7 @@ func (s sessionDetailController) GetSessionDetail(c *gin.Context) {_ = c.ShouldBindJSON(&request)span := traceway.StartSpan(c, "loading session")- session, err := telemetry.SessionRepository.FindById(c, projectId, sessionId, request.StartedAt)- if session == nil && err == nil && request.StartedAt != nil {- session, err = telemetry.SessionRepository.FindById(c, projectId, sessionId, nil)- }+ session, err := findSession(c, projectId, sessionId, request.StartedAt)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading session: %w", err))@@ -89,6 +87,9 @@ func (s sessionDetailController) GetSessionDetail(c *gin.Context) {out := make([]SessionExceptionInfo, 0, len(exceptions))for _, e := range exceptions {+ if e.RecordedAt.After(session.CutoffAt) {+ continue+ }out = append(out, SessionExceptionInfo{Id: e.Id,ExceptionHash: e.ExceptionHash,@@ -122,13 +123,26 @@ func (s sessionDetailController) GetSessionRecording(c *gin.Context) {startedAt = &t}- span := traceway.StartSpan(c, "loading session segments")- segments, err := telemetry.SessionRecordingRepository.FindBySessionId(c, projectId, sessionId, startedAt)+ span := traceway.StartSpan(c, "loading session")+ session, err := findSession(c, projectId, sessionId, startedAt)+ span.End()+ if err != nil {+ c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading session: %w", err))+ return+ }+ if session == nil {+ c.JSON(http.StatusNotFound, gin.H{"error": "Session not found"})+ return+ }++ span = traceway.StartSpan(c, "loading session segments")+ segments, err := telemetry.SessionRecordingRepository.FindBySessionId(c, projectId, sessionId, &session.StartedAt)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading session segments: %w", err))return}+ segments = shared.SegmentsWithinSession(segments, session.CutoffAt)span = traceway.StartSpan(c, "reading session segments")bodies := readSegments(c.Request.Context(), segments)@@ -157,6 +171,14 @@ func (s sessionDetailController) GetSessionRecording(c *gin.Context) {c.JSON(http.StatusOK, payload)}+func findSession(c *gin.Context, projectId, sessionId uuid.UUID, startedAt *time.Time) (*models.Session, error) {+ session, err := telemetry.SessionRepository.FindById(c, projectId, sessionId, startedAt)+ if session == nil && err == nil && startedAt != nil {+ return telemetry.SessionRepository.FindById(c, projectId, sessionId, nil)+ }+ return session, err+}+const segmentReadConcurrency = 16type segmentBody struct {diff --git a/backend/app/models/session.model.go b/backend/app/models/session.model.goindex b48349b0..9e076c96 100644--- a/backend/app/models/session.model.go+++ b/backend/app/models/session.model.go@@ -18,4 +18,5 @@ type Session struct {ServerName string `json:"serverName" ch:"server_name"`TraceId string `json:"traceId,omitempty" ch:"trace_id"`HasRecording bool `json:"hasRecording" ch:"-"`+ CutoffAt time.Time `json:"-" ch:"-"`}diff --git a/backend/app/repositories/telemetry/clickhouse/session.repository.go b/backend/app/repositories/telemetry/clickhouse/session.repository.goindex f858bbf8..9dc44dfc 100644--- a/backend/app/repositories/telemetry/clickhouse/session.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/session.repository.go@@ -107,13 +107,16 @@ const sessionActivityQuery = `SELECT assumeNotNull(session_id) AS sid,WHERE project_id = ? AND session_id IS NOT NULL AND recorded_at >= ? AND recorded_at <= ?GROUP BY sid`-var sessionDurationSortKey = fmt.Sprintf(`if(a.last_activity IS NULL, intDiv(s.duration, 1000000),- toInt64(dateDiff('millisecond', toDateTime64(s.started_at, 3), if(+var sessionDurationSortKey = fmt.Sprintf(`multiIf(a.last_activity IS NULL, least(intDiv(s.duration, 1000000), %[2]d),+ assumeNotNull(a.last_activity) > toDateTime64(s.started_at, 3) + INTERVAL %[3]d MINUTE+ AND s.ended_at > s.started_at AND s.ended_at <= s.started_at + INTERVAL %[3]d MINUTE,+ toInt64(dateDiff('millisecond', toDateTime64(s.started_at, 3), toDateTime64(assumeNotNull(s.ended_at), 3))),+ least(toInt64(dateDiff('millisecond', toDateTime64(s.started_at, 3), if(s.ended_at > greatest(assumeNotNull(a.last_activity), toDateTime64(s.started_at, 3))- AND s.ended_at < greatest(assumeNotNull(a.last_activity), toDateTime64(s.started_at, 3)) + INTERVAL %d MINUTE,+ AND s.ended_at < greatest(assumeNotNull(a.last_activity), toDateTime64(s.started_at, 3)) + INTERVAL %[1]d MINUTE,toDateTime64(assumeNotNull(s.ended_at), 3),- greatest(assumeNotNull(a.last_activity), toDateTime64(s.started_at, 3))))))`,- int(shared.SessionIdleTimeout/time.Minute))+ greatest(assumeNotNull(a.last_activity), toDateTime64(s.started_at, 3))))), %[2]d))`,+ int(shared.SessionIdleTimeout/time.Minute), shared.SessionMaxSpan.Milliseconds(), int(shared.SessionMaxSpan/time.Minute))func (r *sessionRepository) FindById(ctx context.Context, projectId, sessionId uuid.UUID, startedAt *time.Time) (*models.Session, error) {var s models.Sessiondiff --git a/backend/app/repositories/telemetry/duckdb/session.repository.go b/backend/app/repositories/telemetry/duckdb/session.repository.goindex 482b3c72..ee348130 100644--- a/backend/app/repositories/telemetry/duckdb/session.repository.go+++ b/backend/app/repositories/telemetry/duckdb/session.repository.go@@ -77,12 +77,15 @@ const sessionActivityJoin = ` LEFT JOIN (GROUP BY session_id) AS activity ON activity.session_id = sessions.id`-var sessionDurationSortKey = fmt.Sprintf(`CASE WHEN activity.last_activity IS NULL THEN CAST(sessions.duration // 1000000 AS BIGINT)- ELSE epoch_ms(CASE+var sessionDurationSortKey = fmt.Sprintf(`CASE WHEN activity.last_activity IS NULL THEN least(CAST(sessions.duration // 1000000 AS BIGINT), %[2]d)+ WHEN activity.last_activity > sessions.started_at + INTERVAL %[3]d MINUTE+ AND sessions.ended_at > sessions.started_at AND sessions.ended_at <= sessions.started_at + INTERVAL %[3]d MINUTE+ THEN epoch_ms(sessions.ended_at) - epoch_ms(sessions.started_at)+ ELSE least(epoch_ms(CASEWHEN sessions.ended_at > greatest(activity.last_activity, sessions.started_at)- AND sessions.ended_at < greatest(activity.last_activity, sessions.started_at) + INTERVAL %d MINUTE- THEN sessions.ended_at ELSE greatest(activity.last_activity, sessions.started_at) END) - epoch_ms(sessions.started_at) END`,- int(shared.SessionIdleTimeout/time.Minute))+ AND sessions.ended_at < greatest(activity.last_activity, sessions.started_at) + INTERVAL %[1]d MINUTE+ THEN sessions.ended_at ELSE greatest(activity.last_activity, sessions.started_at) END) - epoch_ms(sessions.started_at), %[2]d) END`,+ int(shared.SessionIdleTimeout/time.Minute), shared.SessionMaxSpan.Milliseconds(), int(shared.SessionMaxSpan/time.Minute))type sessionRepository struct{}diff --git a/backend/app/repositories/telemetry/session_repository_test.go b/backend/app/repositories/telemetry/session_repository_test.goindex f042ac59..61617e8a 100644--- a/backend/app/repositories/telemetry/session_repository_test.go+++ b/backend/app/repositories/telemetry/session_repository_test.go@@ -107,7 +107,9 @@ func TestSessionRepository_EndFromRecordingActivity(t *testing.T) {live := models.Session{Id: uuid.New(), ProjectId: projectID, StartedAt: ago(10 * time.Minute)}unrecorded := models.Session{Id: uuid.New(), ProjectId: projectID, StartedAt: ago(70 * time.Minute)}skewedClock := models.Session{Id: uuid.New(), ProjectId: projectID, StartedAt: ago(30 * time.Minute), EndedAt: ptr(ago(16 * time.Minute)), Duration: int64(14 * time.Minute)}- if err := SessionRepository.Upsert(ctx, []models.Session{idle, closedByPagehide, closedByLateTimer, live, unrecorded, skewedClock}); err != nil {+ recordedPastCap := models.Session{Id: uuid.New(), ProjectId: projectID, StartedAt: ago(100 * time.Minute), EndedAt: ptr(ago(40 * time.Minute)), Duration: int64(60 * time.Minute)}+ longIdle := models.Session{Id: uuid.New(), ProjectId: projectID, StartedAt: ago(110 * time.Minute)}+ if err := SessionRepository.Upsert(ctx, []models.Session{idle, closedByPagehide, closedByLateTimer, live, unrecorded, skewedClock, recordedPastCap, longIdle}); err != nil {t.Fatal(err)}@@ -121,6 +123,9 @@ func TestSessionRepository_EndFromRecordingActivity(t *testing.T) {segment(closedByLateTimer, 0, ago(85*time.Minute)),segment(live, 0, ago(time.Minute)),segment(skewedClock, 0, ago(32*time.Minute)),+ segment(recordedPastCap, 0, ago(90*time.Minute)),+ segment(recordedPastCap, 1, ago(time.Minute)),+ segment(longIdle, 0, ago(48*time.Minute)),}); err != nil {t.Fatal(err)}@@ -131,6 +136,8 @@ func TestSessionRepository_EndFromRecordingActivity(t *testing.T) {ended boolrecorded bool}{+ {longIdle, 62 * time.Minute, true, true},+ {recordedPastCap, 60 * time.Minute, true, true},{skewedClock, 14 * time.Minute, true, true},{idle, 10 * time.Minute, true, true},{live, 9 * time.Minute, false, true},diff --git a/backend/app/repositories/telemetry/shared/session_activity.go b/backend/app/repositories/telemetry/shared/session_activity.goindex 7726f9f2..760fe3a1 100644--- a/backend/app/repositories/telemetry/shared/session_activity.go+++ b/backend/app/repositories/telemetry/shared/session_activity.go@@ -8,6 +8,8 @@ import (const SessionIdleTimeout = 15 * time.Minute+const SessionMaxSpan = 65 * time.Minute+const sessionEndTolerance = time.Secondtype SessionActivity struct {@@ -23,7 +25,13 @@ func SessionRecordingWindow(from, to time.Time) (time.Time, time.Time) {func ResolveSessionEnd(s *models.Session, activity SessionActivity, now time.Time) {s.HasRecording = activity.LastActivity != nil+ limit := s.StartedAt.Add(SessionMaxSpan)+ s.CutoffAt = limitif activity.LastActivity == nil {+ if s.EndedAt != nil && s.EndedAt.After(limit) {+ s.EndedAt = &limit+ }+ s.Duration = min(s.Duration, SessionMaxSpan.Nanoseconds())return}@@ -31,18 +39,29 @@ func ResolveSessionEnd(s *models.Session, activity SessionActivity, now time.Timif last.Before(s.StartedAt) {last = s.StartedAt}+ pastLimit := last.After(limit)+ if pastLimit {+ last = limit+ if s.EndedAt != nil && s.EndedAt.After(s.StartedAt) && !s.EndedAt.After(limit) {+ last = *s.EndedAt+ s.CutoffAt = last+ }+ }end := lastif s.EndedAt != nil && s.EndedAt.After(last) && s.EndedAt.Before(last.Add(SessionIdleTimeout)) {end = *s.EndedAt}+ if end.After(limit) {+ end = limit+ }endedByRecord := s.EndedAt != nil && !s.EndedAt.Before(last.Add(-sessionEndTolerance))lastReceived := lastif activity.LastReceived != nil {lastReceived = *activity.LastReceived}- idle := now.Sub(lastReceived) >= SessionIdleTimeout+ idle := now.Sub(lastReceived) >= SessionIdleTimeout || pastLimits.Duration = end.Sub(s.StartedAt).Nanoseconds()if endedByRecord || idle {@@ -51,3 +70,17 @@ func ResolveSessionEnd(s *models.Session, activity SessionActivity, now time.Tims.EndedAt = nil}}++func SegmentsWithinSession(segments []models.SessionRecording, cutoff time.Time) []models.SessionRecording {+ kept := segments[:0]+ for _, seg := range segments {+ end := seg.RecordedAt+ if seg.EndedAt != nil {+ end = *seg.EndedAt+ }+ if !end.After(cutoff) {+ kept = append(kept, seg)+ }+ }+ return kept+}diff --git a/backend/app/repositories/telemetry/shared/session_activity_test.go b/backend/app/repositories/telemetry/shared/session_activity_test.goindex 3ad98e8d..c02128d7 100644--- a/backend/app/repositories/telemetry/shared/session_activity_test.go+++ b/backend/app/repositories/telemetry/shared/session_activity_test.go@@ -16,6 +16,7 @@ func TestResolveSessionEnd(t *testing.T) {cases := []struct {name stringendedAt *time.Time+ duration time.DurationlastActivity *time.TimelastReceived *time.Timenow time.Time@@ -34,10 +35,16 @@ func TestResolveSessionEnd(t *testing.T) {{name: "activity before start on a skewed clock clamps to zero", lastActivity: at(-2), now: *at(30), wantEnd: at(0), wantDuration: 0, wantRecorded: true},{name: "second-precision end just before the last segment still closes", endedAt: at(5), lastActivity: at(5.01), now: *at(6), wantEnd: at(5.01), wantDuration: time.Duration(5.01 * float64(time.Minute)), wantRecorded: true},{name: "explicit end is measured from the clamped activity", endedAt: at(14), lastActivity: at(-2), now: *at(30), wantEnd: at(14), wantDuration: 14 * time.Minute, wantRecorded: true},+ {name: "segments uploaded after the SDK closed the session keep its close", endedAt: at(60), lastActivity: at(18 * 60), now: *at(18*60 + 1), wantEnd: at(60), wantDuration: 60 * time.Minute, wantRecorded: true},+ {name: "a close past the max span falls back to the cap when segments run on", endedAt: at(70), lastActivity: at(18 * 60), now: *at(18*60 + 1), wantEnd: at(65), wantDuration: 65 * time.Minute, wantRecorded: true},+ {name: "a session past the max span is over while segments still arrive", lastActivity: at(300), now: *at(301), wantEnd: at(65), wantDuration: 65 * time.Minute, wantRecorded: true},+ {name: "explicit end past the max span is capped", endedAt: at(70), lastActivity: at(64), now: *at(71), wantEnd: at(65), wantDuration: 65 * time.Minute, wantRecorded: true},+ {name: "no segments and an end past the max span is capped", endedAt: at(18 * 60), duration: 18 * time.Hour, now: *at(18*60 + 1), wantEnd: at(65), wantDuration: 65 * time.Minute},+ {name: "a client clock behind the server keeps a live session open", lastActivity: at(29), lastReceived: at(129), now: *at(130), wantDuration: 29 * time.Minute, wantRecorded: true},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {- s := models.Session{StartedAt: start, EndedAt: tc.endedAt}+ s := models.Session{StartedAt: start, EndedAt: tc.endedAt, Duration: tc.duration.Nanoseconds()}ResolveSessionEnd(&s, SessionActivity{LastActivity: tc.lastActivity, LastReceived: tc.lastReceived}, tc.now)if s.HasRecording != tc.wantRecorded {t.Fatalf("HasRecording = %v, want %v", s.HasRecording, tc.wantRecorded)@@ -51,3 +58,48 @@ func TestResolveSessionEnd(t *testing.T) {})}}++func TestSegmentsWithinSession(t *testing.T) {+ start := time.Date(2026, 9, 26, 12, 0, 0, 0, time.UTC)+ at := func(minutes int) time.Time { return start.Add(time.Duration(minutes) * time.Minute) }+ ptr := func(v time.Time) *time.Time { return &v }+ segments := []models.SessionRecording{+ {SegmentIndex: 0, RecordedAt: at(1), EndedAt: ptr(at(1))},+ {SegmentIndex: 1, RecordedAt: at(66), EndedAt: ptr(at(65))},+ {SegmentIndex: 2, RecordedAt: at(64)},+ {SegmentIndex: 3, RecordedAt: at(70), EndedAt: ptr(at(70))},+ {SegmentIndex: 4, RecordedAt: at(900)},+ }+ kept := SegmentsWithinSession(segments, start.Add(SessionMaxSpan))+ if len(kept) != 3 || kept[0].SegmentIndex != 0 || kept[1].SegmentIndex != 1 || kept[2].SegmentIndex != 2 {+ t.Fatalf("kept %+v, want segments 0, 1, 2", kept)+ }+}++func TestResolveSessionEndCutoff(t *testing.T) {+ start := time.Date(2026, 9, 26, 12, 0, 0, 0, time.UTC)+ at := func(minutes int) *time.Time {+ v := start.Add(time.Duration(minutes) * time.Minute)+ return &v+ }+ cases := []struct {+ name string+ endedAt *time.Time+ lastActivity *time.Time+ want time.Time+ }{+ {name: "no segments", endedAt: at(20), want: *at(65)},+ {name: "activity within the cap", endedAt: at(20), lastActivity: at(30), want: *at(65)},+ {name: "activity past the cap with the SDK close inside it", endedAt: at(60), lastActivity: at(600), want: *at(60)},+ {name: "activity past the cap without a close", lastActivity: at(600), want: *at(65)},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ s := models.Session{StartedAt: start, EndedAt: tc.endedAt}+ ResolveSessionEnd(&s, SessionActivity{LastActivity: tc.lastActivity}, *at(601))+ if !s.CutoffAt.Equal(tc.want) {+ t.Fatalf("CutoffAt = %v, want %v", s.CutoffAt, tc.want)+ }+ })+ }+}diff --git a/backend/app/repositories/telemetry/sqlite/session.repository.go b/backend/app/repositories/telemetry/sqlite/session.repository.goindex 96b12c03..1b96559c 100644--- a/backend/app/repositories/telemetry/sqlite/session.repository.go+++ b/backend/app/repositories/telemetry/sqlite/session.repository.go@@ -95,12 +95,16 @@ const sessionActivityJoin = ` LEFT JOIN (GROUP BY session_id) AS activity ON activity.session_id = sessions.id`-var sessionDurationSortKey = fmt.Sprintf(`CASE WHEN activity.last_activity IS NULL THEN sessions.duration / 1000000- ELSE CAST(ROUND((julianday(CASE+var sessionDurationSortKey = fmt.Sprintf(`CASE WHEN activity.last_activity IS NULL THEN MIN(sessions.duration / 1000000, %[2]d)+ WHEN julianday(activity.last_activity) > julianday(sessions.started_at) + %[3]d / 1440.0+ AND julianday(sessions.ended_at) > julianday(sessions.started_at)+ AND julianday(sessions.ended_at) <= julianday(sessions.started_at) + %[3]d / 1440.0+ THEN CAST(ROUND((julianday(sessions.ended_at) - julianday(sessions.started_at)) * 86400000) AS INTEGER)+ ELSE MIN(CAST(ROUND((julianday(CASEWHEN sessions.ended_at > MAX(activity.last_activity, sessions.started_at)- AND julianday(sessions.ended_at) < julianday(MAX(activity.last_activity, sessions.started_at)) + %d / 1440.0- THEN sessions.ended_at ELSE MAX(activity.last_activity, sessions.started_at) END) - julianday(sessions.started_at)) * 86400000) AS INTEGER) END`,- int(shared.SessionIdleTimeout/time.Minute))+ AND julianday(sessions.ended_at) < julianday(MAX(activity.last_activity, sessions.started_at)) + %[1]d / 1440.0+ THEN sessions.ended_at ELSE MAX(activity.last_activity, sessions.started_at) END) - julianday(sessions.started_at)) * 86400000) AS INTEGER), %[2]d) END`,+ int(shared.SessionIdleTimeout/time.Minute), shared.SessionMaxSpan.Milliseconds(), int(shared.SessionMaxSpan/time.Minute))type sessionRepository struct{}diff --git a/docs/pages/learn/sessions.mdx b/docs/pages/learn/sessions.mdxindex cf5005f9..e234f8c7 100644--- a/docs/pages/learn/sessions.mdx+++ b/docs/pages/learn/sessions.mdx@@ -43,7 +43,7 @@ It ends on the first of:| **Maximum duration** | 60 minutes from session start | Hard cap regardless of activity || **Page unload** | `pagehide` fires (close tab, hard refresh, navigate away) | Final segment is drained, closing payload sent via `fetch keepalive` |-The closing payload is not guaranteed to arrive: the browser can be force-quit before `pagehide` runs, mobile browsers freeze background tabs without firing it, and the flush itself can be dropped. The backend therefore does not depend on it. Once no replay segment has arrived for 15 minutes, the session ends at the time of its last recorded segment. A close reported more than 15 minutes after the last segment, which is what the inactivity timer sends from a tab that sat frozen in the background, is replaced the same way, so the duration reflects activity rather than time the tab spent unattended. A session with no recorded segments and no close is shown as **No recording**.+The closing payload is not guaranteed to arrive: the browser can be force-quit before `pagehide` runs, mobile browsers freeze background tabs without firing it, and the flush itself can be dropped. The backend therefore does not depend on it. Once no replay segment has arrived for 15 minutes, the session ends at the time of its last recorded segment. A close reported more than 15 minutes after the last segment, which is what the inactivity timer sends from a tab that sat frozen in the background, is replaced the same way, so the duration reflects activity rather than time the tab spent unattended. Replay segments recorded more than 65 minutes after a session started (the 60 minute cap plus slack for a late timer) are not part of it: browser SDK versions up to 1.2.0 kept uploading segments under an ended session for as long as the tab stayed open, and those sessions end at the close the SDK reported, or at the cap when there is none. A session with no recorded segments and no close is shown as **No recording**.## Attributesdiff --git a/frontend/src/routes/sessions/[sessionId]/+page.svelte b/frontend/src/routes/sessions/[sessionId]/+page.svelteindex 46df3af8..7dbd15eb 100644--- a/frontend/src/routes/sessions/[sessionId]/+page.svelte+++ b/frontend/src/routes/sessions/[sessionId]/+page.svelte@@ -59,6 +59,8 @@let recordingEvents = $state<SessionReplayEvent[] | null>(null);let recordingLogs = $state<SessionLogEvent[]>([]);let recordingActions = $state<SessionActionEvent[]>([]);+ let recordingLoading = $state(false);+ let recordingError = $state('');let loading = $state(true);let error = $state('');let notFound = $state(false);@@ -74,46 +76,71 @@const hasActions = $derived(recordingActions.length > 0);const defaultTab = $derived(hasLogs ? 'logs' : 'actions');+ let loadGeneration = 0;++ function requestRecording(startedAt: string) {+ return api.get(`/sessions/${sessionId}/recording?startedAt=${encodeURIComponent(startedAt)}`, {+ projectId: projectsState.currentProjectId ?? undefined+ });+ }++ async function loadRecording(generation: number, request: ReturnType<typeof requestRecording>) {+ recordingLoading = true;+ recordingError = '';+ try {+ const recording = await request;+ if (generation !== loadGeneration) return;+ recordingEvents = recording?.events ?? [];+ recordingLogs = recording?.logs ?? [];+ recordingActions = recording?.actions ?? [];+ } catch (e) {+ if (generation !== loadGeneration) return;+ recordingError = getErrorMessage(e) || 'Failed to load the replay';+ } finally {+ if (generation === loadGeneration) recordingLoading = false;+ }+ }++ function retryRecording() {+ if (!session) return;+ loadRecording(++loadGeneration, requestRecording(session.startedAt));+ }+async function loadAll() {+ const generation = ++loadGeneration;loading = true;error = '';notFound = false;+ recordingEvents = null;+ recordingLogs = [];+ recordingActions = [];- try {- const projectId = projectsState.currentProjectId ?? undefined;- const loadRecording = (startedAt: string) =>- api.get(`/sessions/${sessionId}/recording?startedAt=${encodeURIComponent(startedAt)}`, {- projectId- });+ const startedAt = pageState.url.searchParams.get('t');+ const recordingRequest = startedAt ? requestRecording(startedAt) : null;+ recordingRequest?.catch(() => {});- const startedAt = pageState.url.searchParams.get('t');- const detailRequest = api.post(`/sessions/${sessionId}`, startedAt ? { startedAt } : {}, {- projectId+ let loaded: Session;+ try {+ const detail = await api.post(`/sessions/${sessionId}`, startedAt ? { startedAt } : {}, {+ projectId: projectsState.currentProjectId ?? undefined});- const recordingRequest = startedAt ? loadRecording(startedAt) : null;- recordingRequest?.catch(() => {});-- const detail = await detailRequest;- session = detail.session;+ if (generation !== loadGeneration) return;+ loaded = detail.session;+ session = loaded;exceptions = detail.exceptions || [];-- const sessionStartedAt: string = detail.session.startedAt;- const recording =- startedAt && recordingRequest && Date.parse(startedAt) === Date.parse(sessionStartedAt)- ? await recordingRequest- : await loadRecording(sessionStartedAt);- recordingEvents = recording?.events ?? [];- recordingLogs = recording?.logs ?? [];- recordingActions = recording?.actions ?? [];} catch (e) {+ if (generation !== loadGeneration) return;if (getErrorStatus(e) === 404) {notFound = true;} else {error = getErrorMessage(e) || 'Failed to load session';}+ return;} finally {- loading = false;+ if (generation === loadGeneration) loading = false;}++ loadRecording(generation, recordingRequest ?? requestRecording(loaded.startedAt));}onMount(() => {@@ -163,7 +190,26 @@</Card.Root>{/if}- {#if recordingEvents && recordingEvents.length > 0}+ {#if recordingLoading}+ <Card.Root>+ <Card.Header>+ <Card.Title>Session Replay</Card.Title>+ </Card.Header>+ <Card.Content class="flex h-64 items-center justify-center">+ <LoadingCircle size="lg" />+ </Card.Content>+ </Card.Root>+ {:else if recordingError}+ <Card.Root>+ <Card.Header>+ <Card.Title>Session Replay</Card.Title>+ </Card.Header>+ <Card.Content class="flex items-center justify-between gap-4 text-sm text-muted-foreground">+ <span>{recordingError}</span>+ <Button variant="outline" size="sm" onclick={retryRecording}>Retry</Button>+ </Card.Content>+ </Card.Root>+ {:else if recordingEvents && recordingEvents.length > 0}<Card.Root class="pb-0"><Card.Header class="gap-0"><Card.Title>Session Replay</Card.Title>