The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
better sessions with full attribute search (#370)
narrow-adventure56b81770eaa5
diff --git a/backend/app/controllers/clientcontrollers/session_attributes_test.go b/backend/app/controllers/clientcontrollers/session_attributes_test.gonew file mode 100644index 00000000..6ffc5c63--- /dev/null+++ b/backend/app/controllers/clientcontrollers/session_attributes_test.go@@ -0,0 +1,94 @@+//go:build !telemetry_ch && !telemetry_duckdb++package clientcontrollers++import (+ "bytes"+ "compress/gzip"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/dbtest"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry"+)++func TestReportSessionAttributesCompatibility(t *testing.T) {+ dbtest.SetupSQLite(t)+ gin.SetMode(gin.TestMode)+ projectID := uuid.New()+ router := gin.New()+ router.POST("/api/report", func(c *gin.Context) { c.Set(middleware.ProjectIdContextKey, projectID) }, middleware.UseGzip, ClientController.Report)+ now := time.Now().UTC().Truncate(time.Millisecond)+ post := func(t *testing.T, frame map[string]any, compressed bool) {+ t.Helper()+ payload, err := json.Marshal(map[string]any{"appVersion": "1.2.0", "collectionFrames": []any{frame}})+ if err != nil {+ t.Fatal(err)+ }+ if compressed {+ var buf bytes.Buffer+ zw := gzip.NewWriter(&buf)+ if _, err := zw.Write(payload); err != nil {+ t.Fatal(err)+ }+ if err := zw.Close(); err != nil {+ t.Fatal(err)+ }+ payload = buf.Bytes()+ }+ req := httptest.NewRequest(http.MethodPost, "/api/report", bytes.NewReader(payload))+ req.RemoteAddr = "192.0.2.1:1234"+ req.Header.Set("Content-Type", "application/json")+ if compressed {+ req.Header.Set("Content-Encoding", "gzip")+ }+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("report: %d %s", rec.Code, rec.Body.String())+ }+ }+ t.Run("legacy frame without sessions", func(t *testing.T) {+ post(t, map[string]any{"traces": []any{}, "metrics": []any{}, "stackTraces": []any{}}, true)+ })+ for _, compressed := range []bool{false, true} {+ for _, withAttributes := range []bool{false, true} {+ id := uuid.New()+ session := map[string]any{"id": id.String(), "startedAt": now}+ if withAttributes {+ session["attributes"] = map[string]string{"userId": "u_42", "email": "[email protected]", "client.ip": "forged"}+ }+ post(t, map[string]any{"sessions": []any{session}}, compressed)+ got, err := telemetry.SessionRepository.FindById(context.Background(), projectID, id, nil)+ if err != nil || got == nil {+ t.Fatalf("read session: %v, %v", got, err)+ }+ if got.Attributes["client.ip"] != "192.0.2.1" {+ t.Fatalf("client IP = %q", got.Attributes["client.ip"])+ }+ if withAttributes && got.Attributes["userId"] != "u_42" {+ t.Fatalf("attributes = %v", got.Attributes)+ }+ // A refresh must become searchable before a closing payload arrives.+ session["attributes"] = map[string]string{"userId": "u_43"}+ post(t, map[string]any{"sessions": []any{session}}, compressed)+ rows, _, err := telemetry.SessionRepository.FindAll(context.Background(), projectID, now.Add(-time.Hour), now.Add(time.Hour), 1, 50, "started_at", "desc", id.String(), []telemetry.SessionAttributeFilter{{Key: "userId", Value: "u_43"}})+ if err != nil || len(rows) != 1 || rows[0].EndedAt != nil {+ t.Fatalf("refreshed session: %v, %v", rows, err)+ }+ session["endedAt"] = now.Add(time.Minute)+ post(t, map[string]any{"sessions": []any{session}}, compressed)+ got, err = telemetry.SessionRepository.FindById(context.Background(), projectID, id, nil)+ if err != nil || got == nil || got.EndedAt == nil || got.Attributes["userId"] != "u_43" {+ t.Fatalf("closed session: %v, %v", got, err)+ }+ }+ }+}diff --git a/backend/app/controllers/session.controller.go b/backend/app/controllers/session.controller.goindex a9c3140d..bbc26a19 100644--- a/backend/app/controllers/session.controller.go+++ b/backend/app/controllers/session.controller.go@@ -15,8 +15,10 @@ import (type sessionController struct{}type SessionAttributeFilter struct {- Key string `json:"key"`- Value string `json:"value"`+ Key string `json:"key"`+ Value string `json:"value"`+ Exclude bool `json:"exclude"`+ Contains bool `json:"contains"`}type SessionSearchRequest struct {@@ -47,7 +49,7 @@ func (s sessionController) FindAllSessions(c *gin.Context) {if f.Key == "" {continue}- filters = append(filters, telemetry.SessionAttributeFilter{Key: f.Key, Value: f.Value})+ filters = append(filters, telemetry.SessionAttributeFilter{Key: f.Key, Value: f.Value, Exclude: f.Exclude, Contains: f.Contains})}span := traceway.StartSpan(c, "loading sessions")diff --git a/backend/app/repositories/telemetry/clickhouse/session.repository.go b/backend/app/repositories/telemetry/clickhouse/session.repository.goindex 17865709..05272dfa 100644--- a/backend/app/repositories/telemetry/clickhouse/session.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/session.repository.go@@ -116,31 +116,28 @@ func (r *sessionRepository) FindById(ctx context.Context, projectId, sessionId ureturn &s, nil}-// buildSessionFilterClause assembles the search + attribute-filter portion of-// the WHERE clause for sessions queries. Empty inputs return ("", nil).-// Search restricts to a single session id (only valid UUIDs match — any other-// search input falls through and matches nothing useful, which is the right-// behaviour given attribute filters now cover the structured-search use case).-// Each attribute filter adds an exact-match clause via the `attributes[?]`-// Map subscript, which is O(1) per row and indexed by the bloom filters on-// `mapKeys(attributes)` / `mapValues(attributes)`.func buildSessionFilterClause(search string, filters []shared.SessionAttributeFilter) (string, []interface{}) {var sb strings.Builderargs := []interface{}{}if s := strings.TrimSpace(search); s != "" {- if id, err := uuid.Parse(s); err == nil {- sb.WriteString(" AND id = ?")- args = append(args, id)- }+ sb.WriteString(" AND (positionCaseInsensitiveUTF8(toString(id), ?) > 0 OR positionCaseInsensitiveUTF8(client_ip, ?) > 0 OR arrayExists(v -> positionCaseInsensitiveUTF8(v, ?) > 0, mapValues(attributes)))")+ args = append(args, s, s, s)}for _, f := range filters {if f.Key == "" {continue}- // `attributes[?]` does an O(1) lookup on the Map column. Combined- // with the bloom_filter on mapKeys/mapValues this is index-driven.- sb.WriteString(" AND attributes[?] = ?")- args = append(args, f.Key, f.Value)+ sb.WriteString(" AND ")+ if f.Exclude {+ sb.WriteString("NOT ")+ }+ sb.WriteString("(mapContains(attributes, ?) AND ")+ if f.Contains {+ sb.WriteString("positionCaseInsensitiveUTF8(attributes[?], ?) > 0)")+ } else {+ sb.WriteString("attributes[?] = ?)")+ }+ args = append(args, f.Key, f.Key, f.Value)}return sb.String(), args}diff --git a/backend/app/repositories/telemetry/duckdb/session.repository.go b/backend/app/repositories/telemetry/duckdb/session.repository.goindex 07c9c4d2..7f0d9963 100644--- a/backend/app/repositories/telemetry/duckdb/session.repository.go+++ b/backend/app/repositories/telemetry/duckdb/session.repository.go@@ -201,18 +201,12 @@ func (r *sessionRepository) FindAll(ctx context.Context, projectId uuid.UUID, frreturn sessions, count, nil}-// buildSessionFilterClauseDuckDB produces a WHERE fragment + named params-// mirroring the ClickHouse helper: search must be a valid UUID for an exact-// id match (anything else is ignored), and each attribute filter becomes an-// exact match against `json_extract_string(attributes, '$.<key>')`.func buildSessionFilterClauseDuckDB(search string, filters []shared.SessionAttributeFilter) (string, lit.P) {var sb strings.Builderparams := lit.P{}if s := strings.TrimSpace(search); s != "" {- if id, err := uuid.Parse(s); err == nil {- sb.WriteString(" AND id = :search_id")- params["search_id"] = id- }+ sb.WriteString(" AND (instr(lower(CAST(sessions.id AS TEXT)), lower(:search)) > 0 OR instr(lower(client_ip), lower(:search)) > 0 OR EXISTS (SELECT 1 FROM json_each(sessions.attributes) AS attr WHERE instr(lower(json_extract_string(attr.value, '$')), lower(:search)) > 0))")+ params["search"] = s}for i, f := range filters {if f.Key == "" {@@ -220,10 +214,16 @@ func buildSessionFilterClauseDuckDB(search string, filters []shared.SessionAttri}keyParam := fmt.Sprintf("attr_k_%d", i)valParam := fmt.Sprintf("attr_v_%d", i)- sb.WriteString(" AND json_extract_string(attributes, '$.\"' || :")- sb.WriteString(keyParam)- sb.WriteString(" || '\"') = :")- sb.WriteString(valParam)+ sb.WriteString(" AND ")+ if f.Exclude {+ sb.WriteString("NOT ")+ }+ sb.WriteString("EXISTS (SELECT 1 FROM json_each(sessions.attributes) AS attr WHERE attr.key = :" + keyParam + " AND ")+ if f.Contains {+ sb.WriteString("instr(lower(json_extract_string(attr.value, '$')), lower(:" + valParam + ")) > 0)")+ } else {+ sb.WriteString("json_extract_string(attr.value, '$') = :" + valParam + ")")+ }params[keyParam] = f.Keyparams[valParam] = f.Value}diff --git a/backend/app/repositories/telemetry/session_repository_test.go b/backend/app/repositories/telemetry/session_repository_test.gonew file mode 100644index 00000000..39ad6733--- /dev/null+++ b/backend/app/repositories/telemetry/session_repository_test.go@@ -0,0 +1,69 @@+package telemetry++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestSessionRepository_SearchAttributes(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectID := uuid.New()+ userID := uuid.New().String()+ now := time.Date(2026, 9, 10, 12, 0, 0, 0, time.UTC)+ alice := models.Session{Id: uuid.New(), ProjectId: projectID, StartedAt: now, ClientIP: "192.0.2.1", Attributes: map[string]string{"user.id": "u_42", "user.uuid": userID, "email": "[email protected]", "tenant": "acme", "empty": "", `odd."key\`: "literal%_value"}}+ bob := models.Session{Id: uuid.New(), ProjectId: projectID, StartedAt: now.Add(time.Minute), Attributes: map[string]string{"user.id": "u_43", "email": "[email protected]", "tenant": "other"}}+ anonymous := models.Session{Id: uuid.New(), ProjectId: projectID, StartedAt: now.Add(2 * time.Minute)}+ otherProject := alice+ otherProject.Id, otherProject.ProjectId = uuid.New(), uuid.New()+ outsideRange := alice+ outsideRange.Id, outsideRange.StartedAt = uuid.New(), now.Add(-24*time.Hour)+ if err := SessionRepository.Upsert(ctx, []models.Session{alice, bob, anonymous, otherProject, outsideRange}); err != nil {+ t.Fatal(err)+ }+ cases := []struct {+ name, search string+ filters []SessionAttributeFilter+ want int64+ }{+ {name: "unfiltered", want: 3},+ {name: "full UUID", search: alice.Id.String(), want: 1},+ {name: "short UUID", search: alice.Id.String()[:8], want: 1},+ {name: "UUID user search", search: userID, want: 1},+ {name: "user search", search: "u_42", want: 1},+ {name: "case insensitive search", search: "ALICE@EXAMPLE", want: 1},+ {name: "unknown search", search: "nobody", want: 0},+ {name: "IP", search: "192.0.2.1", want: 1},+ {name: "exact dotted key", filters: []SessionAttributeFilter{{Key: "user.id", Value: "u_42"}}, want: 1},+ {name: "case sensitive equals", filters: []SessionAttributeFilter{{Key: "email", Value: "[email protected]"}}, want: 0},+ {name: "contains", filters: []SessionAttributeFilter{{Key: "email", Value: "ALICE@", Contains: true}}, want: 1},+ {name: "exclude includes absent", filters: []SessionAttributeFilter{{Key: "user.id", Value: "u_42", Exclude: true}}, want: 2},+ {name: "not contains", filters: []SessionAttributeFilter{{Key: "email", Value: "EXAMPLE", Contains: true, Exclude: true}}, want: 1},+ {name: "empty differs from missing", filters: []SessionAttributeFilter{{Key: "empty", Value: ""}}, want: 1},+ {name: "exclude empty", filters: []SessionAttributeFilter{{Key: "empty", Value: "", Exclude: true}}, want: 2},+ {name: "contains empty requires key", filters: []SessionAttributeFilter{{Key: "empty", Value: "", Contains: true}}, want: 1},+ {name: "literal special key", filters: []SessionAttributeFilter{{Key: `odd."key\`, Value: "literal%_value"}}, want: 1},+ {name: "literal contains", filters: []SessionAttributeFilter{{Key: `odd."key\`, Value: "%_", Contains: true}}, want: 1},+ {name: "SQL in key", filters: []SessionAttributeFilter{{Key: `' OR 1=1 --`, Value: ""}}, want: 0},+ {name: "AND filters", filters: []SessionAttributeFilter{{Key: "user.id", Value: "u_42"}, {Key: "tenant", Value: "other"}}, want: 0},+ {name: "search AND filter", search: "bob", filters: []SessionAttributeFilter{{Key: "tenant", Value: "acme"}}, want: 0},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ rows, total, err := SessionRepository.FindAll(ctx, projectID, now.Add(-time.Hour), now.Add(time.Hour), 1, 1, "started_at", "desc", tc.search, tc.filters)+ if err != nil {+ t.Fatal(err)+ }+ if total != tc.want {+ t.Fatalf("total = %d, want %d", total, tc.want)+ }+ if len(rows) != int(min(tc.want, 1)) {+ t.Fatalf("page length = %d, total = %d", len(rows), total)+ }+ })+ }+}diff --git a/backend/app/repositories/telemetry/shared/session_filter.go b/backend/app/repositories/telemetry/shared/session_filter.goindex 81a5eccf..8b30029f 100644--- a/backend/app/repositories/telemetry/shared/session_filter.go+++ b/backend/app/repositories/telemetry/shared/session_filter.go@@ -1,9 +1,10 @@package shared-// SessionAttributeFilter narrows the sessions list by an exact key=value-// match against the JSON `attributes` blob. Defined here so every telemetry-// backend sees the same type.+// SessionAttributeFilter matches a literal attribute key. Excluded filters also+// include sessions where the key is absent; contains matches ignore case.type SessionAttributeFilter struct {- Key string- Value string+ Key string+ Value string+ Exclude bool+ Contains bool}diff --git a/backend/app/repositories/telemetry/sqlite/session.repository.go b/backend/app/repositories/telemetry/sqlite/session.repository.goindex 23beb28d..f6ac894c 100644--- a/backend/app/repositories/telemetry/sqlite/session.repository.go+++ b/backend/app/repositories/telemetry/sqlite/session.repository.go@@ -203,18 +203,12 @@ func (r *sessionRepository) FindAll(ctx context.Context, projectId uuid.UUID, frreturn sessions, count, nil}-// buildSessionFilterClauseSQLite produces a WHERE fragment + named params-// mirroring the ClickHouse helper: search must be a valid UUID for an exact-// id match (anything else is ignored), and each attribute filter becomes an-// exact match against `json_extract(attributes, '$.<key>')`.func buildSessionFilterClauseSQLite(search string, filters []shared.SessionAttributeFilter) (string, lit.P) {var sb strings.Builderparams := lit.P{}if s := strings.TrimSpace(search); s != "" {- if id, err := uuid.Parse(s); err == nil {- sb.WriteString(" AND id = :search_id")- params["search_id"] = id- }+ sb.WriteString(" AND (instr(lower(CAST(sessions.id AS TEXT)), lower(:search)) > 0 OR instr(lower(client_ip), lower(:search)) > 0 OR EXISTS (SELECT 1 FROM json_each(sessions.attributes) AS attr WHERE instr(lower(attr.value), lower(:search)) > 0))")+ params["search"] = s}for i, f := range filters {if f.Key == "" {@@ -222,10 +216,16 @@ func buildSessionFilterClauseSQLite(search string, filters []shared.SessionAttri}keyParam := fmt.Sprintf("attr_k_%d", i)valParam := fmt.Sprintf("attr_v_%d", i)- sb.WriteString(" AND json_extract(attributes, '$.\"' || :")- sb.WriteString(keyParam)- sb.WriteString(" || '\"') = :")- sb.WriteString(valParam)+ sb.WriteString(" AND ")+ if f.Exclude {+ sb.WriteString("NOT ")+ }+ sb.WriteString("EXISTS (SELECT 1 FROM json_each(sessions.attributes) AS attr WHERE attr.key = :" + keyParam + " AND ")+ if f.Contains {+ sb.WriteString("instr(lower(attr.value), lower(:" + valParam + ")) > 0)")+ } else {+ sb.WriteString("attr.value = :" + valParam + ")")+ }params[keyParam] = f.Keyparams[valParam] = f.Value}diff --git a/docs/pages/client/js-sdk/initialization.mdx b/docs/pages/client/js-sdk/initialization.mdxindex 04a5aada..feb8eec8 100644--- a/docs/pages/client/js-sdk/initialization.mdx+++ b/docs/pages/client/js-sdk/initialization.mdx@@ -34,6 +34,7 @@ init("your-token@https://traceway.example.com/api/report", {| `beforeCapture` | `(exception) => boolean` | `undefined` | Callback to programmatically suppress errors. Return `false` to drop. See [Error Filtering](#error-filtering) || `sessionRecording` | `boolean` | `true` | Enable the rrweb session recorder. Required for both per-exception clips and always-on session recording || `sessionRecordingSegmentDuration` | `number` | `30000` | Length of each rrweb segment in milliseconds. Always-on recording uploads one row per segment, so a longer value means fewer rows and S3 reads at the cost of replay granularity |+| `attributes` | `Record<string, string>` | `{}` | Initial context for sessions and exceptions, such as `userId`, `email`, or `tenant`. Use `setAttributes` to update after login and `clearAttributes` on logout || `recordAllSessions` | `boolean` | `false` | Always-on session recording: upload every segment continuously and create a parent `sessions` row, not just exception-bound clips. See [Sessions](/learn/sessions) for the full feature || `captureLogs` | `boolean` | `true` | Mirror `console.{debug,log,info,warn,error}` into the rolling log buffer that ships with each clip / segment || `captureNetwork` | `boolean` | `true` | Record `fetch` and `XMLHttpRequest` calls as network actions |diff --git a/docs/pages/learn/sessions.mdx b/docs/pages/learn/sessions.mdxindex 441318b8..56ca7819 100644--- a/docs/pages/learn/sessions.mdx+++ b/docs/pages/learn/sessions.mdx@@ -50,7 +50,7 @@ If a session ends without an explicit close (e.g. the browser is force-quit befoEvery session ships with a context map. Three layers contribute:1. **Auto-collected defaults**: the SDK stamps `url`, `path`, `referrer`, `userAgent`, `language`, `platform`, `viewport`, `screen`, and `timezone` from `window` / `navigator`. The backend additionally stamps `client.ip` from the request.-2. **Global scope**: anything set via `setAttribute("userId", "u_42")` / `setAttributes({ tenant: "acme" })` on the SDK. These flow through every subsequent session, exception, and segment update.+2. **Global scope**: anything set via `setAttribute("userId", "u_42")` / `setAttributes({ tenant: "acme" })` on the SDK. These refresh the open session and flow through subsequent sessions and exceptions. You can also pass `attributes` at initialization.3. **Per-call attributes**: `captureExceptionWithAttributes(err, { … })` for exceptions only.Layering: defaults → global scope → per-call. Higher layers win on key collision.@@ -67,10 +67,30 @@ See the framework-specific guides for the API:The Sessions page in the dashboard accepts:-- **Search by session ID**: paste a UUID for an exact match.-- **Attribute filters**: add `key=value` filters (e.g. `userId=u_42`, `tenant=acme`, `experiment.cart_redesign=variant_b`). Filters AND together; values are exact match.+- **Search**: paste a full session UUID for an exact match, or search a partial session ID, IP address, or attribute value (such as a user ID or email). Text search ignores case.+- **Attribute filters**: click **Add filter** or an attribute on a session row. Choose **Equals**, **Not equals**, **Contains**, or **Not contains**. Equals is case-sensitive; Contains ignores case and treats characters such as `%` literally. Excluded filters also include sessions without that attribute.+- **Filter chips**: click a chip to edit it or its × to remove it. All filters and the search combine with AND. Filters are stored in the URL for sharing and back/forward navigation.-Attribute filters are backed by a Map column with bloom-filter indexes on keys and values, so they stay fast even as the table grows.+For example, attach identity in your browser app:++```javascript+import { init, setAttributes, clearAttributes } from "@tracewayapp/frontend";++init("your-token@https://traceway.example.com/api/report", {+ recordAllSessions: true,+ attributes: { tenant: "acme" },+});++// After login:+setAttributes({ userId: "u_42", email: "[email protected]" });++// On logout:+clearAttributes();+```++Then add `userId=u_42` to find that user's sessions, or combine `tenant=acme` with `email~=example.com`. Attribute values must be strings. Changes replace the current session's context; `clearAttributes()` removes app-defined values while retaining browser defaults.++Older SDKs and `/api/report` payloads that omit session attributes remain supported.## Sessions and Issuesdiff --git a/frontend/src/lib/utils/session-filters.test.ts b/frontend/src/lib/utils/session-filters.test.tsnew file mode 100644index 00000000..aeceb50b--- /dev/null+++ b/frontend/src/lib/utils/session-filters.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';+import { filterOperator, parseAttributeFilter } from './session-filters';++describe('session attribute URLs', () => {+ it.each([+ 'user.id=u_42',+ '[email protected]',+ 'email~=EXAMPLE',+ 'email!~=example',+ 'empty=',+ 'url=https://example.com/?a=b',+ 'note=line 1\nline 2'+ ])('round trips %s', (input) => {+ const filter = parseAttributeFilter(input)!;+ expect(filter).not.toBeNull();+ expect(`${filter.key}${filterOperator(filter)}${filter.value}`).toBe(input);+ });+ it('keeps old equality links compatible', () => {+ expect(parseAttributeFilter('userId=u_42')).toEqual({+ key: 'userId',+ value: 'u_42',+ exclude: false,+ contains: false+ });+ });+ it.each(['', '=missing-key', ' =value', 'no-operator'])('rejects %s', (input) => {+ expect(parseAttributeFilter(input)).toBeNull();+ });+});diff --git a/frontend/src/lib/utils/session-filters.ts b/frontend/src/lib/utils/session-filters.tsnew file mode 100644index 00000000..88b809c0--- /dev/null+++ b/frontend/src/lib/utils/session-filters.ts@@ -0,0 +1,24 @@+export type AttributeFilter = {+ key: string;+ value: string;+ exclude: boolean;+ contains: boolean;+};++export type FilterOperator = '=' | '!=' | '~=' | '!~=';++export function filterOperator(filter: AttributeFilter): FilterOperator {+ if (filter.contains) return filter.exclude ? '!~=' : '~=';+ return filter.exclude ? '!=' : '=';+}++export function parseAttributeFilter(input: string): AttributeFilter | null {+ const match = input.match(/^(.+?)(!~=|~=|!=|=)(.*)$/s);+ if (!match || !match[1].trim()) return null;+ return {+ key: match[1].trim(),+ value: match[3],+ exclude: match[2].startsWith('!'),+ contains: match[2].includes('~')+ };+}diff --git a/frontend/src/routes/sessions/+page.svelte b/frontend/src/routes/sessions/+page.svelteindex 4c79d719..dacf3cc7 100644--- a/frontend/src/routes/sessions/+page.svelte+++ b/frontend/src/routes/sessions/+page.svelte@@ -17,6 +17,8 @@import { TimeRangePicker } from '$lib/components/ui/time-range-picker';import { SearchBar } from '$lib/components/ui/search-bar';import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import * as Select from '$lib/components/ui/select';+ import Check from '@lucide/svelte/icons/check';import * as Tooltip from '$lib/components/ui/tooltip';import { Button } from '$lib/components/ui/button';import { Input } from '$lib/components/ui/input';@@ -46,6 +48,13 @@type SortDirection} from '$lib/utils/sort-storage';+ import {+ parseAttributeFilter,+ filterOperator,+ type AttributeFilter,+ type FilterOperator+ } from '$lib/utils/session-filters';+const timezone = $derived(getTimezone());const initialTimezone = getTimezone();@@ -55,6 +64,7 @@endedAt?: string | null;duration: number;clientIP: string;+ attributes?: Record<string, string>;appVersion: string;serverName: string;};@@ -64,23 +74,21 @@let sessions = $state<Session[]>([]);let loading = $state(true);let error = $state('');+ let expandedAttributes = $state<string[]>([]);++ function sessionAttributes(session: Session) {+ const identityKeys = ['userId', 'user.id', 'user_id', 'email', 'user.email'];+ return Object.entries(session.attributes ?? {}).sort(+ ([a], [b]) =>+ Number(identityKeys.includes(b)) - Number(identityKeys.includes(a)) || a.localeCompare(b)+ );+ }let page = $state(1);let pageSize = $state(50);let total = $state(0);let totalPages = $state(0);- type AttributeFilter = { key: string; value: string };-- function parseAttributeFilter(input: string): AttributeFilter | null {- const idx = input.indexOf('=');- if (idx <= 0) return null;- const key = input.slice(0, idx).trim();- const value = input.slice(idx + 1);- if (!key) return null;- return { key, value };- }-function parseSessionsUrlParams() {const timeParams = parseTimeRangeFromUrl(timezone);if (!browser) return { ...timeParams, search: '', attributeFilters: [] as AttributeFilter[] };@@ -112,10 +120,30 @@let dialogKey = $state('');let dialogValue = $state('');let dialogError = $state('');+ let dialogOperator = $state<FilterOperator>('=');+ let dialogEditIndex = $state<number | null>(null);+ const operatorOptions: { value: FilterOperator; label: string }[] = [+ { value: '=', label: 'Equals' },+ { value: '!=', label: 'Not equals' },+ { value: '~=', label: 'Contains' },+ { value: '!~=', label: 'Not contains' }+ ];++ function openAddFilterDialog(key = '', value = '') {+ dialogKey = key;+ dialogValue = value;+ dialogOperator = '=';+ dialogEditIndex = null;+ dialogError = '';+ addFilterOpen = true;+ }- function openAddFilterDialog() {- dialogKey = '';- dialogValue = '';+ function openEditFilterDialog(index: number) {+ const filter = attributeFilters[index];+ dialogKey = filter.key;+ dialogValue = filter.value;+ dialogOperator = filterOperator(filter);+ dialogEditIndex = index;dialogError = '';addFilterOpen = true;}@@ -126,11 +154,25 @@dialogError = 'Attribute key is required';return;}- const value = dialogValue;- const dup = attributeFilters.some((f) => f.key === key && f.value === value);- if (!dup) {- attributeFilters = [...attributeFilters, { key, value }];- }+ const filter: AttributeFilter = {+ key,+ value: dialogValue,+ exclude: dialogOperator.startsWith('!'),+ contains: dialogOperator.includes('~')+ };+ const others = attributeFilters.filter((_, i) => i !== dialogEditIndex);+ const duplicate = others.some(+ (f) =>+ f.key === filter.key &&+ f.value === filter.value &&+ f.exclude === filter.exclude &&+ f.contains === filter.contains+ );+ attributeFilters = duplicate+ ? others+ : dialogEditIndex === null+ ? [...others, filter]+ : attributeFilters.map((f, i) => (i === dialogEditIndex ? filter : f));addFilterOpen = false;page = 1;loadData(true);@@ -156,7 +198,7 @@from: selectedPreset ? null : getFromDateTimeUTC(),to: selectedPreset ? null : getToDateTimeUTC(),search: searchQuery.trim() || null,- attr: attributeFilters.map((f) => `${f.key}=${f.value}`)+ attr: attributeFilters.map((f) => `${f.key}${filterOperator(f)}${f.value}`)},{ pushToHistory });@@ -335,7 +377,7 @@</PageHeader><SearchBar- placeholder="Search by session ID..."+ placeholder="Search session ID, user, or attribute value..."bind:value={searchQuery}onSearch={handleSearch}disabled={loading}@@ -345,7 +387,7 @@<buttontype="button"class="inline-flex items-center gap-1 rounded-full border border-dashed px-3 py-0.5 text-xs font-medium text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground"- onclick={openAddFilterDialog}+ onclick={() => openAddFilterDialog()}disabled={loading}><Plus class="h-3 w-3" />@@ -355,9 +397,16 @@<spanclass="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 font-mono text-xs">- <span class="text-muted-foreground">{f.key}</span>- <span>=</span>- <span>{f.value || '""'}</span>+ <button+ type="button"+ aria-label="Edit filter"+ class="inline-flex cursor-pointer items-center gap-1 hover:text-primary"+ onclick={() => openEditFilterDialog(i)}+ >+ <span class="text-muted-foreground">{f.key}</span>+ <span class={f.exclude ? 'text-red-500' : ''}>{filterOperator(f)}</span>+ <span class="max-w-64 truncate" title={f.value}>{f.value || '""'}</span>+ </button><buttontype="button"aria-label="Remove filter"@@ -373,24 +422,40 @@<AlertDialog.Root open={addFilterOpen} onOpenChange={(open) => (addFilterOpen = open)}><AlertDialog.Content><AlertDialog.Header>- <AlertDialog.Title>Add attribute filter</AlertDialog.Title>+ <AlertDialog.Title+ >{dialogEditIndex === null+ ? 'Add attribute filter'+ : 'Edit attribute filter'}</AlertDialog.Title+ ><AlertDialog.Description>- Match sessions by an exact attribute value. Keys come from what the SDK auto-collects (<code- class="font-mono">url</code- >, <code class="font-mono">userAgent</code>, <code class="font-mono">viewport</code>,- <code class="font-mono">client.ip</code>, …) plus anything you attach yourself.+ Filter by attributes such as <code class="font-mono">userId</code>,+ <code class="font-mono">email</code>, or <code class="font-mono">client.ip</code>. All+ filters must match. Contains ignores case; excluded filters also include sessions without+ the attribute.</AlertDialog.Description></AlertDialog.Header><div class="flex flex-col gap-3"><FormField label="Attribute key">- <Input placeholder="userAgent" bind:value={dialogKey} onkeydown={handleDialogKeydown} />+ <Input placeholder="userId" bind:value={dialogKey} onkeydown={handleDialogKeydown} />+ </FormField>+ <FormField label="Operator">+ <Select.Root+ type="single"+ value={dialogOperator}+ onValueChange={(v) => (dialogOperator = v as FilterOperator)}+ >+ <Select.Trigger class="w-full"+ >{operatorOptions.find((o) => o.value === dialogOperator)?.label}</Select.Trigger+ >+ <Select.Content>+ {#each operatorOptions as option (option.value)}+ <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root></FormField><FormField label="Value">- <Input- placeholder="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)..."- bind:value={dialogValue}- onkeydown={handleDialogKeydown}- />+ <Input placeholder="u_42" bind:value={dialogValue} onkeydown={handleDialogKeydown} /></FormField>{#if dialogError}<p class="text-xs text-red-500">{dialogError}</p>@@ -399,7 +464,11 @@<AlertDialog.Footer><Button variant="outline" onclick={() => (addFilterOpen = false)}>Cancel</Button><Button onclick={submitDialogFilter}>- <Plus class="h-4 w-4" /> Add filter+ {#if dialogEditIndex === null}+ <Plus class="h-4 w-4" /> Add filter+ {:else}+ <Check class="h-4 w-4" /> Update filter+ {/if}</Button></AlertDialog.Footer></AlertDialog.Content>@@ -410,7 +479,7 @@{#if loading}<Table.Body><Table.Row>- <Table.Cell colspan={4} class="h-48">+ <Table.Cell colspan={5} class="h-48"><div class="flex h-full items-center justify-center"><LoadingCircle size="xlg" /></div>@@ -420,7 +489,7 @@{:else if error}<Table.Body><Table.Row>- <Table.Cell colspan={4} class="h-24 text-center text-red-500">+ <Table.Cell colspan={5} class="h-24 text-center text-red-500">{error}</Table.Cell></Table.Row>@@ -428,8 +497,10 @@{:else if sessions.length === 0}<Table.Body><TableEmptyState- colspan={4}- message="No sessions recorded yet. Enable recordAllSessions in the SDK to start capturing them."+ colspan={5}+ message={searchQuery.trim() || attributeFilters.length+ ? 'No sessions match your search and filters.'+ : 'No sessions recorded in this time range. Enable recordAllSessions in the SDK to start capturing them.'}/></Table.Body>{:else}@@ -439,6 +510,10 @@label="Session"tooltip="Session UUID. Open to play back the recording."/>+ <TracewayTableHeader+ label="Attributes"+ tooltip="User and session context. Click an attribute to filter sessions."+ /><TracewayTableHeaderlabel="Started"tooltip="When the session began"@@ -465,7 +540,9 @@</Table.Row></Table.Header><Table.Body>- {#each sessions as session, __index (__index)}+ {#each sessions as session (session.id)}+ {@const attributes = sessionAttributes(session)}+ {@const attributesExpanded = expandedAttributes.includes(session.id)}<Table.Rowclass="cursor-pointer"onclick={createRowClickHandler(@@ -475,7 +552,41 @@'to')}>- <Table.Cell class="font-mono text-sm">{shortId(session.id)}</Table.Cell>+ <Table.Cell class="w-[140px] font-mono text-sm">{shortId(session.id)}</Table.Cell>+ <Table.Cell>+ <div class="flex max-w-2xl flex-wrap gap-1">+ {#each attributesExpanded ? attributes : attributes.slice(0, 3) as [key, value] (key)}+ <button+ type="button"+ class="max-w-64 truncate rounded-full bg-muted px-2 py-0.5 font-mono text-xs hover:text-primary"+ title={`${key}=${value}`}+ aria-label={`Filter by ${key}=${value}`}+ onclick={(event) => {+ event.stopPropagation();+ openAddFilterDialog(key, value);+ }}+ >+ <span class="text-muted-foreground">{key}</span>={value || '""'}+ </button>+ {:else}+ <span class="text-muted-foreground">—</span>+ {/each}+ {#if attributes.length > 3}+ <button+ type="button"+ class="px-1 text-xs text-muted-foreground hover:text-foreground"+ aria-expanded={attributesExpanded}+ onclick={(event) => {+ event.stopPropagation();+ expandedAttributes = attributesExpanded+ ? expandedAttributes.filter((id) => id !== session.id)+ : [...expandedAttributes, session.id];+ }}+ >{attributesExpanded ? 'Show less' : `+${attributes.length - 3} more`}</button+ >+ {/if}+ </div>+ </Table.Cell><Table.Cell class="text-sm">{formatRelativeTime(session.startedAt, timezone)}</Table.Cell>diff --git a/frontend/src/routes/sessions/sessions.test.ts b/frontend/src/routes/sessions/sessions.test.tsnew file mode 100644index 00000000..bb7c024a--- /dev/null+++ b/frontend/src/routes/sessions/sessions.test.ts@@ -0,0 +1,108 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/svelte';++const { post, goto } = vi.hoisted(() => ({ post: vi.fn(), goto: vi.fn() }));+vi.mock('$lib/api', () => ({ api: { post } }));+vi.mock('$lib/state/projects.svelte', () => ({ projectsState: { currentProjectId: 'project-1' } }));+vi.mock('$lib/state/timezone.svelte', () => ({ getTimezone: () => 'UTC' }));+vi.mock('$app/navigation', () => ({ goto }));+vi.mock('$app/environment', () => ({ browser: true }));++import SessionsPage from '../../test/sessions-page.svelte';++const scrollIntoViewDescriptor = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'scrollIntoView'+);++beforeEach(() => {+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {+ configurable: true,+ value: vi.fn()+ });+ window.history.replaceState({}, '', '/sessions?preset=24h&attr=userId%3Du_42');+ goto.mockImplementation(async (url: string) => {+ window.history.replaceState({}, '', url);+ });+ post.mockResolvedValue({+ data: [+ {+ id: 'a5100000-0000-4000-8000-000000000000',+ startedAt: new Date().toISOString(),+ duration: 0,+ attributes: { userId: 'u_42', email: '[email protected]' }+ }+ ],+ pagination: { total: 1, totalPages: 1 }+ });+});+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ if (scrollIntoViewDescriptor) {+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', scrollIntoViewDescriptor);+ } else {+ Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView');+ }+});++it('loads old attribute links, edits and removes chips, and combines text search', async () => {+ render(SessionsPage);+ await screen.findByRole('button', { name: 'Edit filter' });+ await waitFor(() =>+ expect(post).toHaveBeenCalledWith(+ '/sessions',+ expect.objectContaining({+ attributeFilters: [{ key: 'userId', value: 'u_42', exclude: false, contains: false }]+ }),+ { projectId: 'project-1' }+ )+ );+ await fireEvent.click(screen.getByRole('button', { name: 'Edit filter' }));+ const value = await screen.findByPlaceholderText('u_42');+ await fireEvent.input(value, { target: { value: 'u_43' } });+ await fireEvent.keyDown(+ within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Equals' }),+ { key: 'ArrowDown' }+ );+ await fireEvent.pointerUp(await screen.findByRole('option', { name: 'Contains' }), {+ pointerType: 'mouse'+ });+ await fireEvent.click(screen.getByRole('button', { name: 'Update filter' }));+ await waitFor(() =>+ expect(post.mock.lastCall?.[1].attributeFilters[0]).toMatchObject({+ value: 'u_43',+ contains: true,+ exclude: false+ })+ );+ expect(new URLSearchParams(window.location.search).get('attr')).toBe('userId~=u_43');+ await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());+ await fireEvent.input(+ screen.getByPlaceholderText('Search session ID, user, or attribute value...'),+ { target: { value: 'alice' } }+ );+ await fireEvent.click(screen.getByRole('button', { name: 'Go' }));+ await waitFor(() =>+ expect(post.mock.lastCall?.[1]).toMatchObject({+ search: 'alice',+ attributeFilters: [{ key: 'userId', value: 'u_43' }]+ })+ );+ await fireEvent.click(screen.getByRole('button', { name: 'Remove filter' }));+ await waitFor(() =>+ expect(post.mock.lastCall?.[1]).toMatchObject({ search: 'alice', attributeFilters: [] })+ );+});++it('opens an attribute filter from a row without navigating to the session', async () => {+ render(SessionsPage);+ const attribute = await screen.findByRole('button', {+ name: 'Filter by [email protected]'+ });+ goto.mockClear();+ await fireEvent.click(attribute);+ expect(goto).not.toHaveBeenCalled();+ expect(await screen.findByDisplayValue('email')).toBeTruthy();+ expect(screen.getByDisplayValue('[email protected]')).toBeTruthy();+});diff --git a/frontend/src/test/sessions-page.svelte b/frontend/src/test/sessions-page.sveltenew file mode 100644index 00000000..7ae04449--- /dev/null+++ b/frontend/src/test/sessions-page.svelte@@ -0,0 +1,8 @@+<script lang="ts">+ import * as Tooltip from '$lib/components/ui/tooltip';+ import SessionsPage from '../routes/sessions/+page.svelte';+</script>++<Tooltip.Provider>+ <SessionsPage />+</Tooltip.Provider>diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.tsindex 005410df..0283cfdd 100644--- a/frontend/vitest.config.ts+++ b/frontend/vitest.config.ts@@ -16,6 +16,9 @@ export default defineConfig({resolve: {conditions: ['browser'],alias: {+ '$app/environment': path.resolve(+ './node_modules/@sveltejs/kit/src/runtime/app/environment/index.js'+ ),$lib: path.resolve('./src/lib'),'$app/paths': path.resolve('./node_modules/@sveltejs/kit/src/runtime/app/paths/client.js'),'$app/navigation': path.resolve('./src/test/mocks/app-navigation.ts')