The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
postmortems and frontend cleanup/formatting progress (#288)
narrow-adventure88d669a000d1
diff --git a/CLAUDE.md b/CLAUDE.mdindex e6c3ac9c..36a9542c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -503,8 +503,10 @@ const handleClick = createRowClickHandler('/issues/abc123', 'preset', 'from', 't/tasks Background tasks list/tasks/[task] Single task details/dashboards Dashboards page (tabs of org dashboards; /metrics redirects here)-/monitors Monitors (synthetic checks): single sidebar item, TabsRow tabs Monitors | Status Pages (?tab=, Status Pages admin-only); status pages tab has branding (description, logo upload, custom domain); old /monitors/status-pages redirects to the tab, /monitors/runners to /monitors (runners have no UI — operator infra)-/monitors/[checkId] Monitor detail (latency chart, uptime bars, runs w/ result filter, incidents)+/monitors Monitors (synthetic checks): single sidebar item, TabsRow tabs Monitors | Status Pages | Post-Mortems (?tab=, Status Pages admin-only, Post-Mortems for all members); status pages tab has branding (description, logo upload, custom domain) plus a link to the per-page incidents page (which owns the Record Incident dialog); old /monitors/status-pages redirects to the tab, /monitors/runners to /monitors (runners have no UI — operator infra), bare /monitors/post-mortems to the tab+/monitors/status-pages/[pageId]/incidents Paginated incident management for one status page (timeline updates, titles, manual resolve/delete, post-mortem links); reads for members, mutations admin-gated in the UI+/monitors/[checkId] Monitor detail (latency chart, uptime bars, runs w/ result filter, incidents w/ titles + post-mortem links)+/monitors/post-mortems/[id] Post-mortem editor/viewer (@milkdown/crepe WYSIWYG with a Rich text/Markdown raw toggle, tag pills + Add-tags dialog, incident link pill + searchable picker, Activity sheet; write gating follows the effective project role). Project-scoped: opening a doc under a different project 404s. Creation is a title-only dialog (new-post-mortem-dialog.svelte, openable from the tab, monitor detail incidents, and the status page incidents page with an optional incident pre-link) that POSTs immediately and navigates here; /monitors/post-mortems/new redirects to the tab/status/[slug] Public status page (light standalone design, no auth, raw fetch, listed in isPublicPath)/connection SDK integration guide```@@ -773,6 +775,8 @@ Org-scoped entities in the main DB. Teams (`teams`/`team_members`) own projectsChecks (`synthetic_checks`, main DB) are http/tcp/browser probes with per-check interval, timeout, and a consecutive-failure threshold (flap damping). Runs flow through the `check_runs` queue (outbox-style guarded claims, terminal rows deleted, expired queued runs recorded as `missed`); results are telemetry (`check_results`, all three backends, pruned by the SQLite retention worker / 90d CH TTL). State transitions open/resolve `check_incidents` and feed the event-driven notification rule type `check_down` (recovery auto-resolves the page a rule-scoped dedup key opened via `oncall.AutoResolveByDedupKey`; recovery never dispatches to escalation channels). The notify hook runs post-commit with no ambient tx (SQLite single-connection). Remember: `notification_rule.repository.go` (both copies) lists event rule types explicitly, and `check_down` is one of them.+**Incidents, incident updates & post-mortems.** `check_incidents` covers both auto and manual incidents: auto rows carry `check_id`+`project_id` (nullable now), hand-recorded ones carry only `status_page_id` (org admins record them from a status page for outages monitors missed; they never affect uptime numbers). All incidents can be given a public `title` and statuspage.io-style timeline updates (`incident_updates`: status investigating/identified/monitoring/update/resolved + message; auto open/resolve seeds empty-message investigating/resolved updates in the same tx in `synthetics/result.go`, and the probe `error_message` stays internal, never in the public payload). A `resolved` update closes a manual incident; auto lifecycle stays owned by `ProcessOutcome` (manual resolve/time-edit/delete of auto incidents answer 422). The public `/api/status/:slug` payload gained `pastIncidents` (90d union of the page's checks' auto incidents + its manual ones, titles defaulting to "<check name> is down", nested updates, cap 30, no ids/error messages); incident mutations invalidate every status-page cache slug of the org. Post-mortems (`post_mortems`, **project-scoped**: `project_id` NOT-NULL-in-practice with ON DELETE CASCADE, backfilled by migration from the linked incident's project else the org's oldest project) are internal markdown documents, never public: optional 1:1 incident link (`incident_id` unique where set, `ON DELETE SET NULL` so documents survive monitor/incident deletion; linkable incidents are the project's own autos plus the org's manual status-page incidents — cross-project autos answer 422), JSON-array `tags` (models.StringSlice), LIKE search over title/content/tags, and an append-only edit log (`post_mortem_events`: action created/updated + JSON `changes` field list, recorded only when something actually changed; served as the Activity panel). Routes are project-scoped (`/api/post-mortems*`, standard RequireProjectAccess/RequireWriteAccess chains, org resolved from the project for incident validation); incident mutations are org-admin since they are public content. Frontend: Post-Mortems tab on `/monitors` (all members; creation is a title-only dialog that creates the document immediately and opens the editor page), full-page WYSIWYG editor at `/monitors/post-mortems/[id]` (`@milkdown/crepe`, dynamically imported, app font stack overrides the theme's serif), paginated incident management page at `/monitors/status-pages/[pageId]/incidents` (which owns the Record Incident dialog).+| Method | Endpoint | Auth | Purpose ||--------|----------|------|---------|| GET/POST | `/api/synthetics/checks` | App / App+Write | List / create checks (422 validation incl. browser-mode + cloud gates) |@@ -790,7 +794,16 @@ Checks (`synthetic_checks`, main DB) are http/tcp/browser probes with per-check| POST | `/api/organizations/:organizationId/status-pages/:id/logo` | Admin | Upload a PNG/JPEG logo (raw body, 1MB cap, sniffed content type; SVG rejected as scriptable) stored via storage.Store under `statuspages/<id>/logo` || GET | `/api/status/:slug/logo` | None (rate-limited) | Streams a public page's logo || GET | `/api/status-domains/resolve` | None (rate-limited) | Maps the request Host header to a public status page slug — backs CNAMEd vanity domains (TLS terminates at the operator's proxy); the SPA calls it for anonymous visits to `/` |-| GET | `/api/status/:slug` | None (rate-limited) | Public status payload: per-check status + 90 daily uptime buckets + incidents; cached ~30s per slug; private/unknown slugs are both 404; latency values stripped. Frontend page: `/status/[slug]` (in `isPublicPath`) |+| GET | `/api/status/:slug` | None (rate-limited) | Public status payload: per-check status + 90 daily uptime buckets + incidents + `pastIncidents` (date-grouped titles with timeline updates); cached ~30s per slug; private/unknown slugs are both 404; latency values and internal error messages stripped. Frontend page: `/status/[slug]` (in `isPublicPath`) |+| GET | `/api/organizations/:organizationId/incidents` | Member | Org incidents (90d, joined check/status-page names, updatesCount, postMortemId) |+| GET | `/api/organizations/:organizationId/incidents/:incidentId/updates` | Member | One incident + its timeline updates |+| GET | `/api/organizations/:organizationId/status-pages/:id/incidents` | Member | Paginated incident history of one status page (auto incidents of its checks + its manual ones, no time window; standard pagination envelope + `statusPage` meta). Frontend page: `/monitors/status-pages/[pageId]/incidents` |+| POST | `/api/organizations/:organizationId/status-pages/:id/incidents` | Admin | Record a manual incident on a status page (title required, optional first update message, backdatable, optional resolvedAt) |+| PUT/DELETE | `/api/organizations/:organizationId/incidents/:incidentId` | Admin | Edit title (any incident) / times (manual only, empty resolvedAt reopens; 422 for auto) / delete (manual only, 422 for auto) |+| POST/DELETE | `/api/organizations/:organizationId/incidents/:incidentId/updates(/:updateId)` | Admin | Post / delete a public timeline update (a `resolved` update also closes an unresolved manual incident) |+| GET/POST | `/api/post-mortems` | App / App+Write | Paginated list for the project (query params search/page/pageSize + repeatable `tag` params ANDed together) / create in the project (422 on duplicate or cross-project incident link) |+| GET/PUT/DELETE | `/api/post-mortems/:id` | App / +Write / +Write | Full document with author names (contentMd) / update (records a `post_mortem_events` diff row; no-op saves change nothing) / delete |+| GET | `/api/post-mortems/:id/activity` | App | Edit log for the Activity panel (who created/edited what, joined user names) |**Logs**| Method | Endpoint | Auth | Purpose |@@ -853,7 +866,10 @@ func (c *ReportController) Report(ctx *gin.Context) {| `starred_dashboard_widgets` | Homepage layout per project (dashboard id + widget id, position, col_span, size) || `synthetic_checks` | Synthetic check config + current state (status, consecutive_failures, next_run_at) || `check_runs` | Synthetic run queue (queued/claimed only; terminal rows deleted, telemetry is the record) |-| `check_incidents` | Down/up incident spans per check (feeds status pages) |+| `check_incidents` | Incident spans: auto (nullable check_id+project_id) and manual (nullable status_page_id), plus public title (feeds status pages) |+| `incident_updates` | Public timeline updates on incidents (status + message, seeded on auto open/resolve) |+| `post_mortems` | Internal markdown post-mortems (project-scoped via `project_id` ON DELETE CASCADE, tags JSON array, optional unique incident link with ON DELETE SET NULL) |+| `post_mortem_events` | Append-only post-mortem edit log (action, JSON changes list, user, ON DELETE CASCADE) || `synthetic_runners` | Liveness registry for self-registered runner fleet (unique name, version, first/last_seen_at; no credentials, no org scoping) || `status_pages` | Public uptime pages (org-scoped slug + selected check ids + branding: description, logo_key, unique custom_domain) || `widget_groups` / `widget_group_widgets` / `starred_widgets` | Legacy pre-dashboards tables, retained read-only for rollback until a follow-up drop |@@ -876,7 +892,7 @@ In SQLite mode (`DB_TYPE=sqlite`), the backend uses **two separate SQLite databa- `users`, `organizations`, `organization_users`, `projects`, `invitations`- `source_maps`, `metric_registry`, `dashboards`, `project_dashboards`, `dashboard_templates`, `starred_dashboard_widgets` (plus the legacy `widget_groups`/`widget_group_widgets`/`starred_widgets`)- `notification_channels`, `notification_rules`-- `synthetic_checks`, `check_runs`, `check_incidents`, `synthetic_runners`, `status_pages`+- `synthetic_checks`, `check_runs`, `check_incidents`, `incident_updates`, `post_mortems`, `post_mortem_events`, `synthetic_runners`, `status_pages`**Telemetry DB tables** (`db.TelemetryDB` — non-transactional, uses lit with `db.TelemetryDB` directly):- `endpoints`, `tasks`, `exception_stack_traces`, `spans`, `metric_points`diff --git a/backend/app/controllers/incident.controller.go b/backend/app/controllers/incident.controller.gonew file mode 100644index 00000000..ba4f2630--- /dev/null+++ b/backend/app/controllers/incident.controller.go@@ -0,0 +1,542 @@+package controllers++import (+ "database/sql"+ "encoding/json"+ "net/http"+ "strconv"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/gin-gonic/gin"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"++ traceway "go.tracewayapp.com"+)++type incidentController struct{}++const (+ incidentWindowDays = 90+ incidentListLimit = 200+ incidentTitleMax = 200+ incidentMessageMax = 2000+)++func incidentIdFromPath(ctx *gin.Context) (int, bool) {+ id, err := strconv.Atoi(ctx.Param("incidentId"))+ if err != nil || id < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid incident id"})+ return 0, false+ }+ return id, true+}++func invalidateOrgStatusPageCaches(tx *sql.Tx, organizationId int) error {+ pages, err := transactional.StatusPageRepository.ListByOrganization(tx, organizationId)+ if err != nil {+ return err+ }+ for _, page := range pages {+ invalidateStatusPageCache(page.Slug)+ }+ return nil+}++func loadOrgIncident(ctx *gin.Context, tx *sql.Tx, organizationId int) (*models.CheckIncident, bool) {+ incidentId, ok := incidentIdFromPath(ctx)+ if !ok {+ return nil, false+ }+ incident, err := transactional.CheckIncidentRepository.FindByIdInOrganization(tx, incidentId, organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load incident: %w", err))+ return nil, false+ }+ if incident == nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Incident not found"})+ return nil, false+ }+ return incident, true+}++type incidentView struct {+ *models.OrgIncident+ UpdatesCount int `json:"updatesCount"`+ PostMortemId *int `json:"postMortemId"`+}++func incidentDecorations(ctx *gin.Context, tx *sql.Tx, incidentIds []int) (map[int]int, map[int]int, bool) {+ counts, err := transactional.IncidentUpdateRepository.CountByIncidentIds(tx, incidentIds)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count incident updates: %w", err))+ return nil, nil, false+ }+ refs, err := transactional.PostMortemRepository.FindRefsByIncidentIds(tx, incidentIds)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load post-mortem refs: %w", err))+ return nil, nil, false+ }+ postMortemIds := map[int]int{}+ for _, ref := range refs {+ if ref.IncidentId != nil {+ postMortemIds[*ref.IncidentId] = ref.Id+ }+ }+ return counts, postMortemIds, true+}++func buildIncidentViews(ctx *gin.Context, tx *sql.Tx, incidents []*models.OrgIncident) ([]incidentView, bool) {+ incidentIds := make([]int, len(incidents))+ for i, incident := range incidents {+ incidentIds[i] = incident.Id+ }+ counts, postMortemIds, ok := incidentDecorations(ctx, tx, incidentIds)+ if !ok {+ return nil, false+ }+ views := make([]incidentView, len(incidents))+ for i, incident := range incidents {+ view := incidentView{OrgIncident: incident, UpdatesCount: counts[incident.Id]}+ if id, ok := postMortemIds[incident.Id]; ok {+ postMortemId := id+ view.PostMortemId = &postMortemId+ }+ views[i] = view+ }+ return views, true+}++func (ctrl *incidentController) List(ctx *gin.Context) {+ organizationId, ok := organizationIdFromPath(ctx)+ if !ok {+ return+ }+ tx := db.GetTx(ctx)+ since := time.Now().UTC().AddDate(0, 0, -incidentWindowDays)+ incidents, err := transactional.CheckIncidentRepository.FindRecentByOrganization(tx, organizationId, since, incidentListLimit)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list incidents: %w", err))+ return+ }+ if incidents == nil {+ incidents = []*models.OrgIncident{}+ }+ views, ok := buildIncidentViews(ctx, tx, incidents)+ if !ok {+ return+ }+ ctx.JSON(http.StatusOK, gin.H{"incidents": views})+}++func (ctrl *incidentController) ListForStatusPage(ctx *gin.Context) {+ organizationId, ok := organizationIdFromPath(ctx)+ if !ok {+ return+ }+ pageId, err := strconv.Atoi(ctx.Param("id"))+ if err != nil || pageId < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid status page id"})+ return+ }+ page, pageSize := paginationFromQuery(ctx)++ tx := db.GetTx(ctx)+ statusPage, err := transactional.StatusPageRepository.FindByIdForOrganization(tx, pageId, organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load status page: %w", err))+ return+ }+ if statusPage == nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Status page not found"})+ return+ }+ var checkIds []int+ if err := json.Unmarshal(statusPage.CheckIds, &checkIds); err != nil {+ checkIds = nil+ }++ incidents, err := transactional.CheckIncidentRepository.FindByStatusPagePaged(tx, statusPage.Id, checkIds, pageSize, (page-1)*pageSize)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list status page incidents: %w", err))+ return+ }+ if incidents == nil {+ incidents = []*models.OrgIncident{}+ }+ total, err := transactional.CheckIncidentRepository.CountByStatusPage(tx, statusPage.Id, checkIds)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count status page incidents: %w", err))+ return+ }+ views, ok := buildIncidentViews(ctx, tx, incidents)+ if !ok {+ return+ }+ ctx.JSON(http.StatusOK, gin.H{+ "statusPage": gin.H{"id": statusPage.Id, "name": statusPage.Name},+ "data": views,+ "pagination": buildPagination(page, pageSize, total),+ })+}++func (ctrl *incidentController) ListUpdates(ctx *gin.Context) {+ organizationId, ok := organizationIdFromPath(ctx)+ if !ok {+ return+ }+ tx := db.GetTx(ctx)+ incident, ok := loadOrgIncident(ctx, tx, organizationId)+ if !ok {+ return+ }+ updates, err := transactional.IncidentUpdateRepository.FindByIncident(tx, incident.Id)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list incident updates: %w", err))+ return+ }+ if updates == nil {+ updates = []*models.IncidentUpdate{}+ }+ ctx.JSON(http.StatusOK, gin.H{"incident": incident, "updates": updates})+}++type manualIncidentRequest struct {+ Title string `json:"title"`+ StartedAt string `json:"startedAt"`+ ResolvedAt string `json:"resolvedAt"`+ Message string `json:"message"`+}++func (ctrl *incidentController) Create(ctx *gin.Context) {+ organizationId, ok := organizationIdFromPath(ctx)+ if !ok {+ return+ }+ pageId, err := strconv.Atoi(ctx.Param("id"))+ if err != nil || pageId < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid status page id"})+ return+ }+ var req manualIncidentRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})+ return+ }+ tx := db.GetTx(ctx)+ page, err := transactional.StatusPageRepository.FindByIdForOrganization(tx, pageId, organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load status page: %w", err))+ return+ }+ if page == nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Status page not found"})+ return+ }++ req.Title = strings.TrimSpace(req.Title)+ if req.Title == "" {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Title is required."})+ return+ }+ if utf8.RuneCountInString(req.Title) > incidentTitleMax {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Title must be 200 characters or fewer."})+ return+ }+ req.Message = strings.TrimSpace(req.Message)+ if utf8.RuneCountInString(req.Message) > incidentMessageMax {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Message must be 2000 characters or fewer."})+ return+ }+ now := time.Now().UTC()+ startedAt := now+ if req.StartedAt != "" {+ parsed, err := time.Parse(time.RFC3339, req.StartedAt)+ if err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Started at must be an RFC 3339 timestamp."})+ return+ }+ startedAt = parsed.UTC()+ }+ var resolvedAt *time.Time+ if req.ResolvedAt != "" {+ parsed, err := time.Parse(time.RFC3339, req.ResolvedAt)+ if err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Resolved at must be an RFC 3339 timestamp."})+ return+ }+ utc := parsed.UTC()+ if utc.Before(startedAt) {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Resolved at must not be before started at."})+ return+ }+ resolvedAt = &utc+ }++ incident := &models.CheckIncident{+ StatusPageId: &page.Id,+ Title: req.Title,+ StartedAt: startedAt,+ ResolvedAt: resolvedAt,+ }+ incidentId, err := transactional.CheckIncidentRepository.Open(tx, incident)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create incident: %w", err))+ return+ }+ incident.Id = incidentId++ userId := middleware.GetUserId(ctx)+ status := models.IncidentUpdateInvestigating+ updateAt := startedAt+ if resolvedAt != nil {+ status = models.IncidentUpdateResolved+ updateAt = *resolvedAt+ }+ update := &models.IncidentUpdate{+ IncidentId: incidentId,+ Status: status,+ Message: req.Message,+ CreatedBy: &userId,+ CreatedAt: updateAt,+ }+ if _, err := transactional.IncidentUpdateRepository.Create(tx, update); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create incident update: %w", err))+ return+ }+ if err := invalidateOrgStatusPageCaches(tx, organizationId); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to invalidate status page caches: %w", err))+ return+ }+ ctx.JSON(http.StatusCreated, incident)+}++type editIncidentRequest struct {+ Title string `json:"title"`+ StartedAt *string `json:"startedAt"`+ ResolvedAt *string `json:"resolvedAt"`+}++func (ctrl *incidentController) Update(ctx *gin.Context) {+ organizationId, ok := organizationIdFromPath(ctx)+ if !ok {+ return+ }+ var req editIncidentRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})+ return+ }+ tx := db.GetTx(ctx)+ incident, ok := loadOrgIncident(ctx, tx, organizationId)+ if !ok {+ return+ }++ req.Title = strings.TrimSpace(req.Title)+ if utf8.RuneCountInString(req.Title) > incidentTitleMax {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Title must be 200 characters or fewer."})+ return+ }+ isManual := incident.StatusPageId != nil+ if isManual && req.Title == "" {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Title is required."})+ return+ }+ if !isManual && (req.StartedAt != nil || req.ResolvedAt != nil) {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Start and resolve times of auto-detected incidents are managed by the monitor."})+ return+ }++ if err := transactional.CheckIncidentRepository.UpdateTitle(tx, incident.Id, req.Title); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update incident title: %w", err))+ return+ }+ incident.Title = req.Title++ if isManual && (req.StartedAt != nil || req.ResolvedAt != nil) {+ startedAt := incident.StartedAt+ if req.StartedAt != nil && *req.StartedAt != "" {+ parsed, err := time.Parse(time.RFC3339, *req.StartedAt)+ if err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Started at must be an RFC 3339 timestamp."})+ return+ }+ startedAt = parsed.UTC()+ }+ resolvedAt := incident.ResolvedAt+ if req.ResolvedAt != nil {+ if *req.ResolvedAt == "" {+ resolvedAt = nil+ } else {+ parsed, err := time.Parse(time.RFC3339, *req.ResolvedAt)+ if err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Resolved at must be an RFC 3339 timestamp."})+ return+ }+ utc := parsed.UTC()+ resolvedAt = &utc+ }+ }+ if resolvedAt != nil && resolvedAt.Before(startedAt) {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Resolved at must not be before started at."})+ return+ }+ if err := transactional.CheckIncidentRepository.UpdateManualTimes(tx, incident.Id, startedAt, resolvedAt); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update incident times: %w", err))+ return+ }+ if incident.ResolvedAt != nil && resolvedAt == nil {+ userId := middleware.GetUserId(ctx)+ reopened := &models.IncidentUpdate{+ IncidentId: incident.Id,+ Status: models.IncidentUpdateInvestigating,+ Message: "",+ CreatedBy: &userId,+ CreatedAt: time.Now().UTC(),+ }+ if _, err := transactional.IncidentUpdateRepository.Create(tx, reopened); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create incident update: %w", err))+ return+ }+ }+ incident.StartedAt = startedAt+ incident.ResolvedAt = resolvedAt+ }++ if err := invalidateOrgStatusPageCaches(tx, organizationId); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to invalidate status page caches: %w", err))+ return+ }+ ctx.JSON(http.StatusOK, incident)+}++func (ctrl *incidentController) Delete(ctx *gin.Context) {+ organizationId, ok := organizationIdFromPath(ctx)+ if !ok {+ return+ }+ tx := db.GetTx(ctx)+ incident, ok := loadOrgIncident(ctx, tx, organizationId)+ if !ok {+ return+ }+ if incident.StatusPageId == nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Only manually recorded incidents can be deleted."})+ return+ }+ if err := transactional.CheckIncidentRepository.DeleteManual(tx, incident.Id); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete incident: %w", err))+ return+ }+ if err := invalidateOrgStatusPageCaches(tx, organizationId); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to invalidate status page caches: %w", err))+ return+ }+ ctx.JSON(http.StatusOK, gin.H{"deleted": true})+}++type postIncidentUpdateRequest struct {+ Status string `json:"status"`+ Message string `json:"message"`+}++func (ctrl *incidentController) CreateUpdate(ctx *gin.Context) {+ organizationId, ok := organizationIdFromPath(ctx)+ if !ok {+ return+ }+ var req postIncidentUpdateRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})+ return+ }+ tx := db.GetTx(ctx)+ incident, ok := loadOrgIncident(ctx, tx, organizationId)+ if !ok {+ return+ }+ if !models.IsValidIncidentUpdateStatus(req.Status) {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Status must be one of investigating, identified, monitoring, update, resolved."})+ return+ }+ if req.Status == models.IncidentUpdateResolved && incident.StatusPageId == nil && incident.ResolvedAt == nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Auto-detected incidents resolve when the monitor recovers."})+ return+ }+ req.Message = strings.TrimSpace(req.Message)+ if utf8.RuneCountInString(req.Message) > incidentMessageMax {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Message must be 2000 characters or fewer."})+ return+ }++ now := time.Now().UTC()+ userId := middleware.GetUserId(ctx)+ update := &models.IncidentUpdate{+ IncidentId: incident.Id,+ Status: req.Status,+ Message: req.Message,+ CreatedBy: &userId,+ CreatedAt: now,+ }+ updateId, err := transactional.IncidentUpdateRepository.Create(tx, update)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create incident update: %w", err))+ return+ }+ update.Id = updateId++ if req.Status == models.IncidentUpdateResolved && incident.StatusPageId != nil && incident.ResolvedAt == nil {+ if err := transactional.CheckIncidentRepository.ResolveManual(tx, incident.Id, now); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to resolve incident: %w", err))+ return+ }+ }++ if err := invalidateOrgStatusPageCaches(tx, organizationId); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to invalidate status page caches: %w", err))+ return+ }+ ctx.JSON(http.StatusCreated, update)+}++func (ctrl *incidentController) DeleteUpdate(ctx *gin.Context) {+ organizationId, ok := organizationIdFromPath(ctx)+ if !ok {+ return+ }+ updateId, err := strconv.Atoi(ctx.Param("updateId"))+ if err != nil || updateId < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid update id"})+ return+ }+ tx := db.GetTx(ctx)+ incident, ok := loadOrgIncident(ctx, tx, organizationId)+ if !ok {+ return+ }+ update, err := transactional.IncidentUpdateRepository.FindById(tx, updateId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load incident update: %w", err))+ return+ }+ if update == nil || update.IncidentId != incident.Id {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Incident update not found"})+ return+ }+ if err := transactional.IncidentUpdateRepository.Delete(tx, updateId); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete incident update: %w", err))+ return+ }+ if err := invalidateOrgStatusPageCaches(tx, organizationId); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to invalidate status page caches: %w", err))+ return+ }+ ctx.JSON(http.StatusOK, gin.H{"deleted": true})+}++var IncidentController = incidentController{}diff --git a/backend/app/controllers/post_mortem.controller.go b/backend/app/controllers/post_mortem.controller.gonew file mode 100644index 00000000..2a4507f8--- /dev/null+++ b/backend/app/controllers/post_mortem.controller.go@@ -0,0 +1,390 @@+package controllers++import (+ "net/http"+ "slices"+ "strconv"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"++ traceway "go.tracewayapp.com"+)++type postMortemController struct{}++const (+ postMortemTitleMax = 200+ postMortemContentMax = 200_000+ postMortemTagMax = 50+ postMortemMaxTags = 20+)++const postMortemDuplicateMessage = "This incident already has a post-mortem."++type postMortemRequest struct {+ Title string `json:"title"`+ ContentMd string `json:"contentMd"`+ Tags []string `json:"tags"`+ IncidentId *int `json:"incidentId"`+}++func normalizePostMortemTags(tags []string) (models.StringSlice, string) {+ normalized := models.StringSlice{}+ seen := map[string]bool{}+ for _, tag := range tags {+ tag = strings.ToLower(strings.TrimSpace(tag))+ tag = strings.NewReplacer("\"", "", "\\", "", ",", "").Replace(tag)+ if tag == "" || seen[tag] {+ continue+ }+ if utf8.RuneCountInString(tag) > postMortemTagMax {+ return nil, "Tags must be 50 characters or fewer."+ }+ seen[tag] = true+ normalized = append(normalized, tag)+ }+ if len(normalized) > postMortemMaxTags {+ return nil, "A post-mortem can have at most 20 tags."+ }+ return normalized, ""+}++func validatePostMortemRequest(req *postMortemRequest) (models.StringSlice, string) {+ req.Title = strings.TrimSpace(req.Title)+ if req.Title == "" {+ return nil, "Title is required."+ }+ if utf8.RuneCountInString(req.Title) > postMortemTitleMax {+ return nil, "Title must be 200 characters or fewer."+ }+ if len(req.ContentMd) > postMortemContentMax {+ return nil, "Content must be 200KB or smaller."+ }+ return normalizePostMortemTags(req.Tags)+}++func intPtrEqual(a, b *int) bool {+ if a == nil || b == nil {+ return a == b+ }+ return *a == *b+}++// postMortemProjectContext resolves the project from RequireProjectAccess and+// its owning organization; post-mortems belong to a project, but incident+// links are still validated against the organization.+func postMortemProjectContext(ctx *gin.Context) (uuid.UUID, int, bool) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return uuid.Nil, 0, false+ }+ tx := db.GetTx(ctx)+ project, err := transactional.ProjectRepository.FindById(tx, projectId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load project: %w", err))+ return uuid.Nil, 0, false+ }+ if project == nil || project.OrganizationId == nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Project not found"})+ return uuid.Nil, 0, false+ }+ return projectId, *project.OrganizationId, true+}++func checkIncidentLink(ctx *gin.Context, organizationId int, projectId uuid.UUID, incidentId int) bool {+ tx := db.GetTx(ctx)+ incident, err := transactional.CheckIncidentRepository.FindByIdInOrganization(tx, incidentId, organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load incident: %w", err))+ return false+ }+ if incident == nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "The linked incident does not belong to this organization."})+ return false+ }+ if incident.ProjectId != nil && *incident.ProjectId != projectId {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "The linked incident belongs to a different project."})+ return false+ }+ return true+}++func (ctrl *postMortemController) List(ctx *gin.Context) {+ projectId, _, ok := postMortemProjectContext(ctx)+ if !ok {+ return+ }+ search := strings.TrimSpace(ctx.Query("search"))+ tags := []string{}+ for _, tag := range ctx.QueryArray("tag") {+ if tag = strings.ToLower(strings.TrimSpace(tag)); tag != "" {+ tags = append(tags, tag)+ }+ }+ page, pageSize := paginationFromQuery(ctx)++ tx := db.GetTx(ctx)+ items, err := transactional.PostMortemRepository.ListByProject(tx, projectId, search, tags, pageSize, (page-1)*pageSize)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list post-mortems: %w", err))+ return+ }+ if items == nil {+ items = []*models.PostMortemListItem{}+ }+ for _, item := range items {+ if item.Tags == nil {+ item.Tags = models.StringSlice{}+ }+ }+ total, err := transactional.PostMortemRepository.CountByProject(tx, projectId, search, tags)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count post-mortems: %w", err))+ return+ }+ ctx.JSON(http.StatusOK, gin.H{+ "data": items,+ "pagination": buildPagination(page, pageSize, total),+ })+}++func (ctrl *postMortemController) Get(ctx *gin.Context) {+ projectId, _, ok := postMortemProjectContext(ctx)+ if !ok {+ return+ }+ id, err := strconv.Atoi(ctx.Param("id"))+ if err != nil || id < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post-mortem id"})+ return+ }+ tx := db.GetTx(ctx)+ postMortem, err := transactional.PostMortemRepository.FindDetailByIdForProject(tx, id, projectId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load post-mortem: %w", err))+ return+ }+ if postMortem == nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Post-mortem not found"})+ return+ }+ if postMortem.Tags == nil {+ postMortem.Tags = models.StringSlice{}+ }+ ctx.JSON(http.StatusOK, postMortem)+}++func (ctrl *postMortemController) Activity(ctx *gin.Context) {+ projectId, _, ok := postMortemProjectContext(ctx)+ if !ok {+ return+ }+ id, err := strconv.Atoi(ctx.Param("id"))+ if err != nil || id < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post-mortem id"})+ return+ }+ tx := db.GetTx(ctx)+ events, err := transactional.PostMortemRepository.ListEvents(tx, id, projectId, 200)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list post-mortem activity: %w", err))+ return+ }+ if events == nil {+ events = []*models.PostMortemEventItem{}+ }+ for _, event := range events {+ if event.Changes == nil {+ event.Changes = models.StringSlice{}+ }+ }+ ctx.JSON(http.StatusOK, gin.H{"events": events})+}++func (ctrl *postMortemController) Create(ctx *gin.Context) {+ projectId, organizationId, ok := postMortemProjectContext(ctx)+ if !ok {+ return+ }+ var req postMortemRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})+ return+ }+ tx := db.GetTx(ctx)+ tags, message := validatePostMortemRequest(&req)+ if message != "" {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": message})+ return+ }+ if req.IncidentId != nil && !checkIncidentLink(ctx, organizationId, projectId, *req.IncidentId) {+ return+ }++ userId := middleware.GetUserId(ctx)+ now := time.Now().UTC()+ postMortem := &models.PostMortem{+ OrganizationId: organizationId,+ ProjectId: projectId,+ IncidentId: req.IncidentId,+ Title: req.Title,+ ContentMd: req.ContentMd,+ Tags: tags,+ CreatedBy: &userId,+ UpdatedBy: &userId,+ CreatedAt: now,+ UpdatedAt: now,+ }+ id, err := transactional.PostMortemRepository.Create(tx, postMortem)+ if err != nil {+ if db.IsUniqueViolation(err) {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": postMortemDuplicateMessage})+ return+ }+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create post-mortem: %w", err))+ return+ }+ postMortem.Id = id+ if err := transactional.PostMortemRepository.RecordEvent(tx, &models.PostMortemEvent{+ PostMortemId: id,+ UserId: &userId,+ Action: models.PostMortemEventCreated,+ Changes: models.StringSlice{},+ CreatedAt: now,+ }); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to record post-mortem event: %w", err))+ return+ }+ ctx.JSON(http.StatusCreated, postMortem)+}++func (ctrl *postMortemController) Update(ctx *gin.Context) {+ projectId, organizationId, ok := postMortemProjectContext(ctx)+ if !ok {+ return+ }+ id, err := strconv.Atoi(ctx.Param("id"))+ if err != nil || id < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post-mortem id"})+ return+ }+ var req postMortemRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})+ return+ }+ tx := db.GetTx(ctx)+ postMortem, err := transactional.PostMortemRepository.FindByIdForProject(tx, id, projectId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load post-mortem: %w", err))+ return+ }+ if postMortem == nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Post-mortem not found"})+ return+ }+ tags, message := validatePostMortemRequest(&req)+ if message != "" {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": message})+ return+ }+ if req.IncidentId != nil && !checkIncidentLink(ctx, organizationId, projectId, *req.IncidentId) {+ return+ }++ changes := models.StringSlice{}+ if postMortem.Title != req.Title {+ changes = append(changes, "title")+ }+ if postMortem.ContentMd != req.ContentMd {+ changes = append(changes, "content")+ }+ if !slices.Equal(postMortem.Tags, tags) {+ changes = append(changes, "tags")+ }+ if !intPtrEqual(postMortem.IncidentId, req.IncidentId) {+ changes = append(changes, "incident link")+ }+ if len(changes) == 0 {+ ctrl.Get(ctx)+ return+ }++ userId := middleware.GetUserId(ctx)+ now := time.Now().UTC()+ postMortem.IncidentId = req.IncidentId+ postMortem.Title = req.Title+ postMortem.ContentMd = req.ContentMd+ postMortem.Tags = tags+ postMortem.UpdatedBy = &userId+ postMortem.UpdatedAt = now+ if err := transactional.PostMortemRepository.Update(tx, postMortem); err != nil {+ if db.IsUniqueViolation(err) {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": postMortemDuplicateMessage})+ return+ }+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update post-mortem: %w", err))+ return+ }+ if err := transactional.PostMortemRepository.RecordEvent(tx, &models.PostMortemEvent{+ PostMortemId: id,+ UserId: &userId,+ Action: models.PostMortemEventUpdated,+ Changes: changes,+ CreatedAt: now,+ }); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to record post-mortem event: %w", err))+ return+ }+ detail, err := transactional.PostMortemRepository.FindDetailByIdForProject(tx, id, projectId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reload post-mortem after update: %w", err))+ return+ }+ if detail == nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("post-mortem %d vanished during update", id))+ return+ }+ if detail.Tags == nil {+ detail.Tags = models.StringSlice{}+ }+ ctx.JSON(http.StatusOK, detail)+}++func (ctrl *postMortemController) Delete(ctx *gin.Context) {+ projectId, _, ok := postMortemProjectContext(ctx)+ if !ok {+ return+ }+ id, err := strconv.Atoi(ctx.Param("id"))+ if err != nil || id < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post-mortem id"})+ return+ }+ tx := db.GetTx(ctx)+ postMortem, err := transactional.PostMortemRepository.FindByIdForProject(tx, id, projectId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load post-mortem: %w", err))+ return+ }+ if postMortem == nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Post-mortem not found"})+ return+ }+ if err := transactional.PostMortemRepository.Delete(tx, id, projectId); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete post-mortem: %w", err))+ return+ }+ ctx.JSON(http.StatusOK, gin.H{"deleted": true})+}++var PostMortemController = postMortemController{}diff --git a/backend/app/controllers/post_mortem_sqlite_test.go b/backend/app/controllers/post_mortem_sqlite_test.gonew file mode 100644index 00000000..9692b46a--- /dev/null+++ b/backend/app/controllers/post_mortem_sqlite_test.go@@ -0,0 +1,394 @@+//go:build !transactional_pg && !telemetry_ch && !telemetry_duckdb++package controllers++import (+ "database/sql"+ "slices"+ "testing"+ "time"++ "github.com/google/uuid"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/dbtest"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+)++func createTestOrg(t *testing.T, name string) int {+ t.Helper()+ org, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Organization, error) {+ return transactional.OrganizationRepository.Create(tx, name, "UTC")+ })+ if err != nil {+ t.Fatalf("create organization: %v", err)+ }+ return org.Id+}++func createTestPostMortem(t *testing.T, organizationId int, projectId uuid.UUID, title string, content string, tags []string, incidentId *int) *models.PostMortem {+ t.Helper()+ now := time.Now().UTC()+ postMortem := &models.PostMortem{+ OrganizationId: organizationId,+ ProjectId: projectId,+ IncidentId: incidentId,+ Title: title,+ ContentMd: content,+ Tags: models.StringSlice(tags),+ CreatedAt: now,+ UpdatedAt: now,+ }+ id, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.PostMortemRepository.Create(tx, postMortem)+ })+ if err != nil {+ t.Fatalf("create post-mortem %q: %v", title, err)+ }+ postMortem.Id = id+ return postMortem+}++func TestPostMortemCrudAndSearch(t *testing.T) {+ dbtest.SetupSQLite(t)+ orgId := createTestOrg(t, "org-a")+ otherOrgId := createTestOrg(t, "org-b")+ project, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {+ return transactional.ProjectRepository.CreateWithOrganization(tx, "proj-a", "gin", orgId)+ })+ if err != nil {+ t.Fatalf("create project: %v", err)+ }+ otherProject, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {+ return transactional.ProjectRepository.CreateWithOrganization(tx, "proj-b", "gin", otherOrgId)+ })+ if err != nil {+ t.Fatalf("create other project: %v", err)+ }++ redis := createTestPostMortem(t, orgId, project.Id, "Redis outage", "A cache stampede after failover.", []string{"redis", "cache"}, nil)+ createTestPostMortem(t, orgId, project.Id, "DB failover", "Postgres replication lag caused stale reads.", []string{"postgres"}, nil)++ type listResult struct {+ items []*models.PostMortemListItem+ total int+ }+ list := func(search string, tags ...string) listResult {+ t.Helper()+ result, err := db.ExecuteTransaction(func(tx *sql.Tx) (listResult, error) {+ items, err := transactional.PostMortemRepository.ListByProject(tx, project.Id, search, tags, 50, 0)+ if err != nil {+ return listResult{}, err+ }+ total, err := transactional.PostMortemRepository.CountByProject(tx, project.Id, search, tags)+ return listResult{items: items, total: total}, err+ })+ if err != nil {+ t.Fatalf("list post-mortems (search=%q tags=%v): %v", search, tags, err)+ }+ return result+ }++ if got := list(""); len(got.items) != 2 || got.total != 2 {+ t.Fatalf("unfiltered list: %d items total %d, want 2/2", len(got.items), got.total)+ }+ if got := list("stampede"); len(got.items) != 1 || got.items[0].Title != "Redis outage" {+ t.Fatalf("content search returned %+v", got.items)+ }+ if got := list("REDIS"); len(got.items) != 1 || got.items[0].Title != "Redis outage" {+ t.Fatalf("case-insensitive search returned %+v", got.items)+ }+ if got := list("", "postgres"); len(got.items) != 1 || got.items[0].Title != "DB failover" {+ t.Fatalf("tag filter returned %+v", got.items)+ }+ if got := list("nothing-matches"); len(got.items) != 0 || got.total != 0 {+ t.Fatalf("no-match search returned %+v", got.items)+ }++ if got := list("%"); len(got.items) != 0 || got.total != 0 {+ t.Fatalf("wildcard search matched %+v, want none", got.items)+ }+ if got := list("", "post%"); len(got.items) != 0 || got.total != 0 {+ t.Fatalf("wildcard tag filter matched %+v, want none", got.items)+ }++ foreign, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.PostMortem, error) {+ return transactional.PostMortemRepository.FindByIdForProject(tx, redis.Id, otherProject.Id)+ })+ if err != nil || foreign != nil {+ t.Fatalf("post-mortem leaked across projects: %+v (%v)", foreign, err)+ }++ redis.Title = "Redis outage (updated)"+ redis.Tags = models.StringSlice{"redis"}+ redis.UpdatedAt = time.Now().UTC()+ if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (bool, error) {+ return true, transactional.PostMortemRepository.Update(tx, redis)+ }); err != nil {+ t.Fatalf("update post-mortem: %v", err)+ }+ reloaded, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.PostMortem, error) {+ return transactional.PostMortemRepository.FindByIdForProject(tx, redis.Id, project.Id)+ })+ if err != nil || reloaded == nil || reloaded.Title != "Redis outage (updated)" || !slices.Equal(reloaded.Tags, models.StringSlice{"redis"}) {+ t.Fatalf("reloaded post-mortem = %+v (%v)", reloaded, err)+ }++ if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (bool, error) {+ return true, transactional.PostMortemRepository.Delete(tx, redis.Id, project.Id)+ }); err != nil {+ t.Fatalf("delete post-mortem: %v", err)+ }+ if got := list(""); got.total != 1 {+ t.Fatalf("after delete total = %d, want 1", got.total)+ }+}++func TestIncidentOwnershipAndPostMortemLink(t *testing.T) {+ dbtest.SetupSQLite(t)+ orgId := createTestOrg(t, "org-a")+ otherOrgId := createTestOrg(t, "org-b")++ project, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {+ return transactional.ProjectRepository.CreateWithOrganization(tx, "proj", "gin", orgId)+ })+ if err != nil {+ t.Fatalf("create project: %v", err)+ }+ now := time.Now().UTC()+ check := &models.SyntheticCheck{+ ProjectId: project.Id,+ Name: "api",+ CheckType: models.CheckTypeHttp,+ Enabled: true,+ IntervalSeconds: 60,+ TimeoutSeconds: 5,+ Config: models.JSONText(`{}`),+ FailureThreshold: 1,+ CurrentStatus: models.CheckStatusUnknown,+ NextRunAt: now,+ CreatedAt: now,+ UpdatedAt: now,+ }+ checkId, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.SyntheticCheckRepository.Create(tx, check)+ })+ if err != nil {+ t.Fatalf("create check: %v", err)+ }+ check.Id = checkId++ page := &models.StatusPage{+ OrganizationId: orgId,+ Slug: "acme-status",+ Name: "Acme Status",+ IsPublic: true,+ CheckIds: models.JSONText(`[]`),+ CreatedAt: now,+ UpdatedAt: now,+ }+ pageId, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.StatusPageRepository.Create(tx, page)+ })+ if err != nil {+ t.Fatalf("create status page: %v", err)+ }+ page.Id = pageId++ autoIncidentId, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.CheckIncidentRepository.Open(tx, &models.CheckIncident{+ CheckId: &check.Id,+ ProjectId: &project.Id,+ StartedAt: now,+ ErrorMessage: "status 500",+ })+ })+ if err != nil {+ t.Fatalf("open auto incident: %v", err)+ }+ manualIncidentId, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.CheckIncidentRepository.Open(tx, &models.CheckIncident{+ StatusPageId: &page.Id,+ Title: "Payment provider outage",+ StartedAt: now,+ })+ })+ if err != nil {+ t.Fatalf("open manual incident: %v", err)+ }++ for _, incidentId := range []int{autoIncidentId, manualIncidentId} {+ found, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.CheckIncident, error) {+ return transactional.CheckIncidentRepository.FindByIdInOrganization(tx, incidentId, orgId)+ })+ if err != nil || found == nil {+ t.Fatalf("incident %d not found in owning org: %v", incidentId, err)+ }+ foreign, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.CheckIncident, error) {+ return transactional.CheckIncidentRepository.FindByIdInOrganization(tx, incidentId, otherOrgId)+ })+ if err != nil || foreign != nil {+ t.Fatalf("incident %d leaked to another org: %+v (%v)", incidentId, foreign, err)+ }+ }++ orgIncidents, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.OrgIncident, error) {+ return transactional.CheckIncidentRepository.FindRecentByOrganization(tx, orgId, now.AddDate(0, 0, -90), 100)+ })+ if err != nil || len(orgIncidents) != 2 {+ t.Fatalf("org incidents = %d (%v), want 2", len(orgIncidents), err)+ }++ if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (bool, error) {+ return true, transactional.CheckIncidentRepository.ResolveManual(tx, autoIncidentId, now)+ }); err != nil {+ t.Fatalf("resolve manual on auto incident: %v", err)+ }+ autoIncident, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.CheckIncident, error) {+ return transactional.CheckIncidentRepository.FindByIdInOrganization(tx, autoIncidentId, orgId)+ })+ if err != nil || autoIncident == nil || autoIncident.ResolvedAt != nil {+ t.Fatalf("auto incident was hand-resolved: %+v (%v)", autoIncident, err)+ }++ linked := createTestPostMortem(t, orgId, project.Id, "Payment outage write-up", "What happened.", []string{"payments"}, &manualIncidentId)+ _, err = db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.PostMortemRepository.Create(tx, &models.PostMortem{+ OrganizationId: orgId,+ ProjectId: project.Id,+ IncidentId: &manualIncidentId,+ Title: "Duplicate",+ Tags: models.StringSlice{},+ CreatedAt: now,+ UpdatedAt: now,+ })+ })+ if err == nil || !db.IsUniqueViolation(err) {+ t.Fatalf("duplicate incident link error = %v, want unique violation", err)+ }++ if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (bool, error) {+ return true, transactional.CheckIncidentRepository.DeleteManual(tx, manualIncidentId)+ }); err != nil {+ t.Fatalf("delete manual incident: %v", err)+ }+ survivor, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.PostMortem, error) {+ return transactional.PostMortemRepository.FindByIdForProject(tx, linked.Id, project.Id)+ })+ if err != nil || survivor == nil {+ t.Fatalf("post-mortem did not survive incident deletion: %v", err)+ }+ if survivor.IncidentId != nil {+ t.Fatalf("incident link not severed: %+v", survivor)+ }++ if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.IncidentUpdateRepository.Create(tx, &models.IncidentUpdate{+ IncidentId: autoIncidentId,+ Status: models.IncidentUpdateInvestigating,+ CreatedAt: now,+ })+ }); err != nil {+ t.Fatalf("create incident update: %v", err)+ }+ if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (bool, error) {+ return true, transactional.SyntheticCheckRepository.Delete(tx, check.Id, project.Id)+ }); err != nil {+ t.Fatalf("delete check: %v", err)+ }+ gone, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.CheckIncident, error) {+ return transactional.CheckIncidentRepository.FindByIdInOrganization(tx, autoIncidentId, orgId)+ })+ if err != nil || gone != nil {+ t.Fatalf("auto incident survived check deletion: %+v (%v)", gone, err)+ }+ updates, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.IncidentUpdate, error) {+ return transactional.IncidentUpdateRepository.FindByIncident(tx, autoIncidentId)+ })+ if err != nil || len(updates) != 0 {+ t.Fatalf("incident updates survived check deletion: %+v (%v)", updates, err)+ }+}++func TestIncidentUpdateBatchHelpers(t *testing.T) {+ dbtest.SetupSQLite(t)+ orgId := createTestOrg(t, "org-a")+ now := time.Now().UTC()+ page := &models.StatusPage{+ OrganizationId: orgId,+ Slug: "acme-status",+ Name: "Acme Status",+ IsPublic: true,+ CheckIds: models.JSONText(`[]`),+ CreatedAt: now,+ UpdatedAt: now,+ }+ pageId, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.StatusPageRepository.Create(tx, page)+ })+ if err != nil {+ t.Fatalf("create status page: %v", err)+ }++ incidentId, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.CheckIncidentRepository.Open(tx, &models.CheckIncident{+ StatusPageId: &pageId,+ Title: "Outage",+ StartedAt: now,+ })+ })+ if err != nil {+ t.Fatalf("open incident: %v", err)+ }+ for i, status := range []string{models.IncidentUpdateInvestigating, models.IncidentUpdateMonitoring} {+ if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return transactional.IncidentUpdateRepository.Create(tx, &models.IncidentUpdate{+ IncidentId: incidentId,+ Status: status,+ CreatedAt: now.Add(time.Duration(i) * time.Minute),+ })+ }); err != nil {+ t.Fatalf("create update: %v", err)+ }+ }++ empty, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.IncidentUpdate, error) {+ return transactional.IncidentUpdateRepository.FindByIncidentIds(tx, nil)+ })+ if err != nil || len(empty) != 0 {+ t.Fatalf("empty id fast path returned %+v (%v)", empty, err)+ }+ batched, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.IncidentUpdate, error) {+ return transactional.IncidentUpdateRepository.FindByIncidentIds(tx, []int{incidentId, incidentId + 100})+ })+ if err != nil || len(batched) != 2 {+ t.Fatalf("batched updates = %d (%v), want 2", len(batched), err)+ }+ counts, err := db.ExecuteTransaction(func(tx *sql.Tx) (map[int]int, error) {+ return transactional.IncidentUpdateRepository.CountByIncidentIds(tx, []int{incidentId})+ })+ if err != nil || counts[incidentId] != 2 {+ t.Fatalf("counts = %v (%v), want map[%d:2]", counts, err, incidentId)+ }+}++func TestNormalizePostMortemTags(t *testing.T) {+ tags, message := normalizePostMortemTags([]string{" Redis ", "redis", `ca"che`, "", `a\b,c`})+ if message != "" {+ t.Fatalf("unexpected validation message: %s", message)+ }+ if !slices.Equal(tags, models.StringSlice{"redis", "cache", "abc"}) {+ t.Fatalf("normalized tags = %v", tags)+ }+ if _, message := normalizePostMortemTags([]string{string(make([]byte, 60))}); message == "" {+ t.Fatal("expected over-long tag to be rejected")+ }+ many := make([]string, 21)+ for i := range many {+ many[i] = "tag" + string(rune('a'+i))+ }+ if _, message := normalizePostMortemTags(many); message == "" {+ t.Fatal("expected too many tags to be rejected")+ }+}diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex 065ac934..77d594c5 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -2,6 +2,7 @@ package controllersimport ("net/http"+ "strconv""time""github.com/tracewayapp/traceway/backend/app/config"@@ -33,6 +34,29 @@ type Pagination struct {TotalPages int64 `json:"totalPages"`}+func paginationFromQuery(ctx *gin.Context) (int, int) {+ page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))+ if page < 1 {+ page = 1+ }+ pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "25"))+ if pageSize < 1 {+ pageSize = 25+ }+ if pageSize > 100 {+ pageSize = 100+ }+ return page, pageSize+}++func buildPagination(page, pageSize, total int) Pagination {+ totalPages := int64(0)+ if total > 0 {+ totalPages = int64((total + pageSize - 1) / pageSize)+ }+ return Pagination{Page: page, PageSize: pageSize, Total: int64(total), TotalPages: totalPages}+}+func RegisterControllers(router *gin.RouterGroup) {router.OPTIONS("/report", middleware.CORSReport)router.POST("/report", middleware.CORSReport, middleware.UseClientAuth, middleware.IngestAdmission, middleware.UseGzip, clientcontrollers.ClientController.Report)@@ -244,6 +268,22 @@ func RegisterControllers(router *gin.RouterGroup) {router.PUT("/organizations/:organizationId/status-pages/:id", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, StatusPageController.Update)router.DELETE("/organizations/:organizationId/status-pages/:id", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, StatusPageController.Delete)router.POST("/organizations/:organizationId/status-pages/:id/logo", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, StatusPageController.UploadLogo)++ router.GET("/organizations/:organizationId/incidents", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, IncidentController.List)+ router.GET("/organizations/:organizationId/incidents/:incidentId/updates", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, IncidentController.ListUpdates)+ router.GET("/organizations/:organizationId/status-pages/:id/incidents", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, IncidentController.ListForStatusPage)+ router.POST("/organizations/:organizationId/status-pages/:id/incidents", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, IncidentController.Create)+ router.PUT("/organizations/:organizationId/incidents/:incidentId", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, IncidentController.Update)+ router.DELETE("/organizations/:organizationId/incidents/:incidentId", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, IncidentController.Delete)+ router.POST("/organizations/:organizationId/incidents/:incidentId/updates", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, IncidentController.CreateUpdate)+ router.DELETE("/organizations/:organizationId/incidents/:incidentId/updates/:updateId", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, IncidentController.DeleteUpdate)++ router.GET("/post-mortems", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.Transactional, PostMortemController.List)+ router.GET("/post-mortems/:id", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.Transactional, PostMortemController.Get)+ router.GET("/post-mortems/:id/activity", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.Transactional, PostMortemController.Activity)+ router.POST("/post-mortems", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, PostMortemController.Create)+ router.PUT("/post-mortems/:id", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, PostMortemController.Update)+ router.DELETE("/post-mortems/:id", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, PostMortemController.Delete)// Anonymous, rate-limited, cached ~30s per slug; no Transactional (it// reads main DB + telemetry through its own short transactions).router.GET("/status/:slug", middleware.RateLimitPerIP(30, time.Minute), StatusPageController.Public)diff --git a/backend/app/controllers/status_page.controller.go b/backend/app/controllers/status_page.controller.goindex 0ab083f9..6d0b7218 100644--- a/backend/app/controllers/status_page.controller.go+++ b/backend/app/controllers/status_page.controller.go@@ -8,6 +8,7 @@ import ("net""net/http""regexp"+ "sort""strconv""strings""sync"@@ -37,10 +38,11 @@ func organizationIdFromPath(ctx *gin.Context) (int, bool) {var statusPageSlugPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$`)const (- statusPageUptimeDays = 90- statusPageCacheTTL = 30 * time.Second- statusPageMaxChecks = 50- statusPageIncidentCap = 20+ statusPageUptimeDays = 90+ statusPageCacheTTL = 30 * time.Second+ statusPageMaxChecks = 50+ statusPageIncidentCap = 20+ statusPagePastIncidentCap = 30)type statusPageRequest struct {@@ -281,12 +283,26 @@ type statusPageIncidentView struct {ResolvedAt *time.Time `json:"resolvedAt"`}+type statusPagePastIncidentView struct {+ Title string `json:"title"`+ StartedAt time.Time `json:"startedAt"`+ ResolvedAt *time.Time `json:"resolvedAt"`+ Updates []statusPagePastIncidentUpdateView `json:"updates"`+}++type statusPagePastIncidentUpdateView struct {+ Status string `json:"status"`+ Message string `json:"message"`+ CreatedAt time.Time `json:"createdAt"`+}+type statusPageView struct {- Name string `json:"name"`- Description string `json:"description"`- HasLogo bool `json:"hasLogo"`- Checks []statusPageCheckView `json:"checks"`- GeneratedAt time.Time `json:"generatedAt"`+ Name string `json:"name"`+ Description string `json:"description"`+ HasLogo bool `json:"hasLogo"`+ Checks []statusPageCheckView `json:"checks"`+ PastIncidents []statusPagePastIncidentView `json:"pastIncidents"`+ GeneratedAt time.Time `json:"generatedAt"`}// The public endpoint is anonymous and its 90-day aggregation is far heavier@@ -381,12 +397,18 @@ func buildStatusPageView(ctx *gin.Context, slug string, now time.Time) (*statusPfrom := now.AddDate(0, 0, -statusPageUptimeDays)view := &statusPageView{- Name: loaded.page.Name,- Description: loaded.page.Description,- HasLogo: loaded.page.LogoKey != "",- Checks: []statusPageCheckView{},- GeneratedAt: now,- }+ Name: loaded.page.Name,+ Description: loaded.page.Description,+ HasLogo: loaded.page.LogoKey != "",+ Checks: []statusPageCheckView{},+ PastIncidents: []statusPagePastIncidentView{},+ GeneratedAt: now,+ }+ type pastIncidentSource struct {+ incident *models.CheckIncident+ checkName string+ }+ var pastIncidents []pastIncidentSourcefor _, check := range loaded.checks {days, err := telemetry.CheckResultRepository.SeriesByCheck(ctx, check.ProjectId, check.Id, from, now, 1440)if err != nil {@@ -425,6 +447,9 @@ func buildStatusPageView(ctx *gin.Context, slug string, now time.Time) (*statusP}incidentViews = append(incidentViews, statusPageIncidentView{StartedAt: incident.StartedAt, ResolvedAt: incident.ResolvedAt})}+ for _, incident := range incidents {+ pastIncidents = append(pastIncidents, pastIncidentSource{incident: incident, checkName: check.Name})+ }status := check.CurrentStatusif !check.Enabled {@@ -439,6 +464,59 @@ func buildStatusPageView(ctx *gin.Context, slug string, now time.Time) (*statusPIncidents: incidentViews,})}++ manualIncidents, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.CheckIncident, error) {+ return transactional.CheckIncidentRepository.FindByStatusPageSince(tx, loaded.page.Id, from)+ })+ if err != nil {+ return nil, err+ }+ for _, incident := range manualIncidents {+ pastIncidents = append(pastIncidents, pastIncidentSource{incident: incident})+ }+ sort.SliceStable(pastIncidents, func(a, b int) bool {+ if pastIncidents[a].incident.StartedAt.Equal(pastIncidents[b].incident.StartedAt) {+ return pastIncidents[a].incident.Id > pastIncidents[b].incident.Id+ }+ return pastIncidents[a].incident.StartedAt.After(pastIncidents[b].incident.StartedAt)+ })+ if len(pastIncidents) > statusPagePastIncidentCap {+ pastIncidents = pastIncidents[:statusPagePastIncidentCap]+ }+ incidentIds := make([]int, len(pastIncidents))+ for i, source := range pastIncidents {+ incidentIds[i] = source.incident.Id+ }+ updates, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.IncidentUpdate, error) {+ return transactional.IncidentUpdateRepository.FindByIncidentIds(tx, incidentIds)+ })+ if err != nil {+ return nil, err+ }+ updatesByIncident := map[int][]statusPagePastIncidentUpdateView{}+ for _, update := range updates {+ updatesByIncident[update.IncidentId] = append(updatesByIncident[update.IncidentId], statusPagePastIncidentUpdateView{+ Status: update.Status,+ Message: update.Message,+ CreatedAt: update.CreatedAt,+ })+ }+ for _, source := range pastIncidents {+ title := source.incident.Title+ if title == "" {+ title = source.checkName + " is down"+ }+ incidentUpdates := updatesByIncident[source.incident.Id]+ if incidentUpdates == nil {+ incidentUpdates = []statusPagePastIncidentUpdateView{}+ }+ view.PastIncidents = append(view.PastIncidents, statusPagePastIncidentView{+ Title: title,+ StartedAt: source.incident.StartedAt,+ ResolvedAt: source.incident.ResolvedAt,+ Updates: incidentUpdates,+ })+ }return view, nil}diff --git a/backend/app/controllers/synthetic_check.controller.go b/backend/app/controllers/synthetic_check.controller.goindex 2f379686..a8693bb8 100644--- a/backend/app/controllers/synthetic_check.controller.go+++ b/backend/app/controllers/synthetic_check.controller.go@@ -296,7 +296,29 @@ func (ctrl *syntheticCheckController) Get(ctx *gin.Context) {if incidents == nil {incidents = []*models.CheckIncident{}}- ctx.JSON(http.StatusOK, gin.H{"check": check, "incidents": incidents})+ incidentIds := make([]int, len(incidents))+ for i, incident := range incidents {+ incidentIds[i] = incident.Id+ }+ updateCounts, postMortemIds, ok := incidentDecorations(ctx, tx, incidentIds)+ if !ok {+ return+ }+ type checkIncidentView struct {+ *models.CheckIncident+ UpdatesCount int `json:"updatesCount"`+ PostMortemId *int `json:"postMortemId"`+ }+ incidentViews := make([]checkIncidentView, len(incidents))+ for i, incident := range incidents {+ view := checkIncidentView{CheckIncident: incident, UpdatesCount: updateCounts[incident.Id]}+ if id, ok := postMortemIds[incident.Id]; ok {+ postMortemId := id+ view.PostMortemId = &postMortemId+ }+ incidentViews[i] = view+ }+ ctx.JSON(http.StatusOK, gin.H{"check": check, "incidents": incidentViews})}func (ctrl *syntheticCheckController) Update(ctx *gin.Context) {diff --git a/backend/app/migrations/pg/0119_alter_check_incidents_check_id_nullable.up.sql b/backend/app/migrations/pg/0119_alter_check_incidents_check_id_nullable.up.sqlnew file mode 100644index 00000000..1dfb5eb1--- /dev/null+++ b/backend/app/migrations/pg/0119_alter_check_incidents_check_id_nullable.up.sql@@ -0,0 +1 @@+ALTER TABLE check_incidents ALTER COLUMN check_id DROP NOT NULLdiff --git a/backend/app/migrations/pg/0120_alter_check_incidents_project_id_nullable.up.sql b/backend/app/migrations/pg/0120_alter_check_incidents_project_id_nullable.up.sqlnew file mode 100644index 00000000..f350d001--- /dev/null+++ b/backend/app/migrations/pg/0120_alter_check_incidents_project_id_nullable.up.sql@@ -0,0 +1 @@+ALTER TABLE check_incidents ALTER COLUMN project_id DROP NOT NULLdiff --git a/backend/app/migrations/pg/0121_add_title_to_check_incidents.up.sql b/backend/app/migrations/pg/0121_add_title_to_check_incidents.up.sqlnew file mode 100644index 00000000..90c3e374--- /dev/null+++ b/backend/app/migrations/pg/0121_add_title_to_check_incidents.up.sql@@ -0,0 +1 @@+ALTER TABLE check_incidents ADD COLUMN title TEXT NOT NULL DEFAULT ''diff --git a/backend/app/migrations/pg/0122_add_status_page_id_to_check_incidents.up.sql b/backend/app/migrations/pg/0122_add_status_page_id_to_check_incidents.up.sqlnew file mode 100644index 00000000..588832c4--- /dev/null+++ b/backend/app/migrations/pg/0122_add_status_page_id_to_check_incidents.up.sql@@ -0,0 +1 @@+ALTER TABLE check_incidents ADD COLUMN status_page_id INT REFERENCES status_pages(id) ON DELETE CASCADEdiff --git a/backend/app/migrations/pg/0123_create_check_incidents_status_page_idx.up.sql b/backend/app/migrations/pg/0123_create_check_incidents_status_page_idx.up.sqlnew file mode 100644index 00000000..d6c5c0e6--- /dev/null+++ b/backend/app/migrations/pg/0123_create_check_incidents_status_page_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS check_incidents_status_page_idx ON check_incidents (status_page_id, started_at)diff --git a/backend/app/migrations/pg/0124_create_incident_updates.up.sql b/backend/app/migrations/pg/0124_create_incident_updates.up.sqlnew file mode 100644index 00000000..c18994c9--- /dev/null+++ b/backend/app/migrations/pg/0124_create_incident_updates.up.sql@@ -0,0 +1,8 @@+CREATE TABLE IF NOT EXISTS incident_updates (+ id SERIAL PRIMARY KEY,+ incident_id INT NOT NULL REFERENCES check_incidents(id) ON DELETE CASCADE,+ status TEXT NOT NULL,+ message TEXT NOT NULL DEFAULT '',+ created_by INT REFERENCES users(id),+ created_at TIMESTAMPTZ NOT NULL+)diff --git a/backend/app/migrations/pg/0125_create_incident_updates_incident_idx.up.sql b/backend/app/migrations/pg/0125_create_incident_updates_incident_idx.up.sqlnew file mode 100644index 00000000..c68a4bce--- /dev/null+++ b/backend/app/migrations/pg/0125_create_incident_updates_incident_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS incident_updates_incident_idx ON incident_updates (incident_id, created_at)diff --git a/backend/app/migrations/pg/0126_create_post_mortems.up.sql b/backend/app/migrations/pg/0126_create_post_mortems.up.sqlnew file mode 100644index 00000000..41b22344--- /dev/null+++ b/backend/app/migrations/pg/0126_create_post_mortems.up.sql@@ -0,0 +1,11 @@+CREATE TABLE IF NOT EXISTS post_mortems (+ id SERIAL PRIMARY KEY,+ organization_id INT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,+ incident_id INT REFERENCES check_incidents(id) ON DELETE SET NULL,+ title TEXT NOT NULL,+ tags TEXT NOT NULL DEFAULT '[]',+ created_by INT REFERENCES users(id),+ created_at TIMESTAMPTZ NOT NULL,+ updated_at TIMESTAMPTZ NOT NULL,+ content_md TEXT NOT NULL DEFAULT ''+)diff --git a/backend/app/migrations/pg/0127_create_post_mortems_org_idx.up.sql b/backend/app/migrations/pg/0127_create_post_mortems_org_idx.up.sqlnew file mode 100644index 00000000..0851d867--- /dev/null+++ b/backend/app/migrations/pg/0127_create_post_mortems_org_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS post_mortems_org_idx ON post_mortems (organization_id, updated_at)diff --git a/backend/app/migrations/pg/0128_create_post_mortems_incident_unique.up.sql b/backend/app/migrations/pg/0128_create_post_mortems_incident_unique.up.sqlnew file mode 100644index 00000000..d6e6146a--- /dev/null+++ b/backend/app/migrations/pg/0128_create_post_mortems_incident_unique.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX IF NOT EXISTS post_mortems_incident_unique ON post_mortems (incident_id) WHERE incident_id IS NOT NULLdiff --git a/backend/app/migrations/pg/0129_add_updated_by_to_post_mortems.up.sql b/backend/app/migrations/pg/0129_add_updated_by_to_post_mortems.up.sqlnew file mode 100644index 00000000..4df222b5--- /dev/null+++ b/backend/app/migrations/pg/0129_add_updated_by_to_post_mortems.up.sql@@ -0,0 +1 @@+ALTER TABLE post_mortems ADD COLUMN updated_by INT REFERENCES users(id)diff --git a/backend/app/migrations/pg/0130_create_post_mortem_events.up.sql b/backend/app/migrations/pg/0130_create_post_mortem_events.up.sqlnew file mode 100644index 00000000..325aa2e1--- /dev/null+++ b/backend/app/migrations/pg/0130_create_post_mortem_events.up.sql@@ -0,0 +1,8 @@+CREATE TABLE IF NOT EXISTS post_mortem_events (+ id SERIAL PRIMARY KEY,+ post_mortem_id INT NOT NULL REFERENCES post_mortems(id) ON DELETE CASCADE,+ user_id INT REFERENCES users(id),+ action TEXT NOT NULL,+ changes TEXT NOT NULL DEFAULT '[]',+ created_at TIMESTAMPTZ NOT NULL+)diff --git a/backend/app/migrations/pg/0131_create_post_mortem_events_idx.up.sql b/backend/app/migrations/pg/0131_create_post_mortem_events_idx.up.sqlnew file mode 100644index 00000000..f76e2f13--- /dev/null+++ b/backend/app/migrations/pg/0131_create_post_mortem_events_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS post_mortem_events_pm_idx ON post_mortem_events (post_mortem_id, created_at)diff --git a/backend/app/migrations/pg/0132_add_project_id_to_post_mortems.up.sql b/backend/app/migrations/pg/0132_add_project_id_to_post_mortems.up.sqlnew file mode 100644index 00000000..982918a3--- /dev/null+++ b/backend/app/migrations/pg/0132_add_project_id_to_post_mortems.up.sql@@ -0,0 +1 @@+ALTER TABLE post_mortems ADD COLUMN project_id UUID REFERENCES projects(id) ON DELETE CASCADEdiff --git a/backend/app/migrations/pg/0133_backfill_post_mortem_project_from_incident.up.sql b/backend/app/migrations/pg/0133_backfill_post_mortem_project_from_incident.up.sqlnew file mode 100644index 00000000..3a106fe6--- /dev/null+++ b/backend/app/migrations/pg/0133_backfill_post_mortem_project_from_incident.up.sql@@ -0,0 +1 @@+UPDATE post_mortems SET project_id = (SELECT sc.project_id FROM check_incidents ci JOIN synthetic_checks sc ON sc.id = ci.check_id WHERE ci.id = post_mortems.incident_id) WHERE incident_id IS NOT NULLdiff --git a/backend/app/migrations/pg/0134_backfill_post_mortem_project_fallback.up.sql b/backend/app/migrations/pg/0134_backfill_post_mortem_project_fallback.up.sqlnew file mode 100644index 00000000..23407828--- /dev/null+++ b/backend/app/migrations/pg/0134_backfill_post_mortem_project_fallback.up.sql@@ -0,0 +1 @@+UPDATE post_mortems SET project_id = (SELECT p.id FROM projects p WHERE p.organization_id = post_mortems.organization_id ORDER BY p.created_at LIMIT 1) WHERE project_id IS NULLdiff --git a/backend/app/migrations/pg/0135_create_post_mortems_project_idx.up.sql b/backend/app/migrations/pg/0135_create_post_mortems_project_idx.up.sqlnew file mode 100644index 00000000..cc1c032c--- /dev/null+++ b/backend/app/migrations/pg/0135_create_post_mortems_project_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS post_mortems_project_idx ON post_mortems (project_id, updated_at)diff --git a/backend/app/migrations/sqlite/0067_reshape_check_incidents.up.sql b/backend/app/migrations/sqlite/0067_reshape_check_incidents.up.sqlnew file mode 100644index 00000000..816fa516--- /dev/null+++ b/backend/app/migrations/sqlite/0067_reshape_check_incidents.up.sql@@ -0,0 +1,21 @@+ALTER TABLE check_incidents RENAME TO check_incidents_old;++CREATE TABLE check_incidents (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ check_id INTEGER REFERENCES synthetic_checks(id) ON DELETE CASCADE,+ project_id TEXT,+ status_page_id INTEGER REFERENCES status_pages(id) ON DELETE CASCADE,+ title TEXT NOT NULL DEFAULT '',+ started_at DATETIME NOT NULL,+ resolved_at DATETIME,+ error_message TEXT NOT NULL DEFAULT ''+);++INSERT INTO check_incidents (id, check_id, project_id, started_at, resolved_at, error_message)+SELECT id, check_id, project_id, started_at, resolved_at, error_message FROM check_incidents_old;++DROP TABLE check_incidents_old;++CREATE INDEX IF NOT EXISTS check_incidents_check_idx ON check_incidents (check_id, started_at);++CREATE INDEX IF NOT EXISTS check_incidents_status_page_idx ON check_incidents (status_page_id, started_at);diff --git a/backend/app/migrations/sqlite/0068_create_incident_updates.up.sql b/backend/app/migrations/sqlite/0068_create_incident_updates.up.sqlnew file mode 100644index 00000000..dad020ba--- /dev/null+++ b/backend/app/migrations/sqlite/0068_create_incident_updates.up.sql@@ -0,0 +1,10 @@+CREATE TABLE IF NOT EXISTS incident_updates (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ incident_id INTEGER NOT NULL REFERENCES check_incidents(id) ON DELETE CASCADE,+ status TEXT NOT NULL,+ message TEXT NOT NULL DEFAULT '',+ created_by INTEGER REFERENCES users(id),+ created_at DATETIME NOT NULL+);++CREATE INDEX IF NOT EXISTS incident_updates_incident_idx ON incident_updates (incident_id, created_at);diff --git a/backend/app/migrations/sqlite/0069_create_post_mortems.up.sql b/backend/app/migrations/sqlite/0069_create_post_mortems.up.sqlnew file mode 100644index 00000000..094a0930--- /dev/null+++ b/backend/app/migrations/sqlite/0069_create_post_mortems.up.sql@@ -0,0 +1,15 @@+CREATE TABLE IF NOT EXISTS post_mortems (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ organization_id INTEGER NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,+ incident_id INTEGER REFERENCES check_incidents(id) ON DELETE SET NULL,+ title TEXT NOT NULL,+ tags TEXT NOT NULL DEFAULT '[]',+ created_by INTEGER REFERENCES users(id),+ created_at DATETIME NOT NULL,+ updated_at DATETIME NOT NULL,+ content_md TEXT NOT NULL DEFAULT ''+);++CREATE INDEX IF NOT EXISTS post_mortems_org_idx ON post_mortems (organization_id, updated_at);++CREATE UNIQUE INDEX IF NOT EXISTS post_mortems_incident_unique ON post_mortems (incident_id) WHERE incident_id IS NOT NULL;diff --git a/backend/app/migrations/sqlite/0070_add_updated_by_to_post_mortems.up.sql b/backend/app/migrations/sqlite/0070_add_updated_by_to_post_mortems.up.sqlnew file mode 100644index 00000000..acd563b7--- /dev/null+++ b/backend/app/migrations/sqlite/0070_add_updated_by_to_post_mortems.up.sql@@ -0,0 +1 @@+ALTER TABLE post_mortems ADD COLUMN updated_by INTEGER REFERENCES users(id);diff --git a/backend/app/migrations/sqlite/0071_create_post_mortem_events.up.sql b/backend/app/migrations/sqlite/0071_create_post_mortem_events.up.sqlnew file mode 100644index 00000000..d5d469f0--- /dev/null+++ b/backend/app/migrations/sqlite/0071_create_post_mortem_events.up.sql@@ -0,0 +1,10 @@+CREATE TABLE IF NOT EXISTS post_mortem_events (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ post_mortem_id INTEGER NOT NULL REFERENCES post_mortems(id) ON DELETE CASCADE,+ user_id INTEGER REFERENCES users(id),+ action TEXT NOT NULL,+ changes TEXT NOT NULL DEFAULT '[]',+ created_at DATETIME NOT NULL+);++CREATE INDEX IF NOT EXISTS post_mortem_events_pm_idx ON post_mortem_events (post_mortem_id, created_at);diff --git a/backend/app/migrations/sqlite/0072_add_project_id_to_post_mortems.up.sql b/backend/app/migrations/sqlite/0072_add_project_id_to_post_mortems.up.sqlnew file mode 100644index 00000000..1d2797f6--- /dev/null+++ b/backend/app/migrations/sqlite/0072_add_project_id_to_post_mortems.up.sql@@ -0,0 +1,7 @@+ALTER TABLE post_mortems ADD COLUMN project_id TEXT REFERENCES projects(id) ON DELETE CASCADE;++UPDATE post_mortems SET project_id = (SELECT sc.project_id FROM check_incidents ci JOIN synthetic_checks sc ON sc.id = ci.check_id WHERE ci.id = post_mortems.incident_id) WHERE incident_id IS NOT NULL;++UPDATE post_mortems SET project_id = (SELECT p.id FROM projects p WHERE p.organization_id = post_mortems.organization_id ORDER BY p.created_at LIMIT 1) WHERE project_id IS NULL;++CREATE INDEX IF NOT EXISTS post_mortems_project_idx ON post_mortems (project_id, updated_at);diff --git a/backend/app/models/incident.model.go b/backend/app/models/incident.model.gonew file mode 100644index 00000000..5ef73c73--- /dev/null+++ b/backend/app/models/incident.model.go@@ -0,0 +1,50 @@+package models++import (+ "time"++ "github.com/google/uuid"+)++const (+ IncidentUpdateInvestigating = "investigating"+ IncidentUpdateIdentified = "identified"+ IncidentUpdateMonitoring = "monitoring"+ IncidentUpdateResolved = "resolved"+ IncidentUpdateNote = "update"+)++type IncidentUpdate struct {+ Id int `json:"id" lit:"id"`+ IncidentId int `json:"incidentId" lit:"incident_id"`+ Status string `json:"status" lit:"status"`+ Message string `json:"message" lit:"message"`+ CreatedBy *int `json:"createdBy" lit:"created_by"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+}++type IncidentUpdateCount struct {+ IncidentId int `lit:"incident_id"`+ Count int `lit:"count"`+}++type OrgIncident struct {+ Id int `json:"id" lit:"id"`+ CheckId *int `json:"checkId" lit:"check_id"`+ ProjectId *uuid.UUID `json:"projectId" lit:"project_id"`+ StatusPageId *int `json:"statusPageId" lit:"status_page_id"`+ Title string `json:"title" lit:"title"`+ StartedAt time.Time `json:"startedAt" lit:"started_at"`+ ResolvedAt *time.Time `json:"resolvedAt" lit:"resolved_at"`+ ErrorMessage string `json:"errorMessage" lit:"error_message"`+ CheckName *string `json:"checkName" lit:"check_name"`+ StatusPageName *string `json:"statusPageName" lit:"status_page_name"`+}++func IsValidIncidentUpdateStatus(status string) bool {+ switch status {+ case IncidentUpdateInvestigating, IncidentUpdateIdentified, IncidentUpdateMonitoring, IncidentUpdateResolved, IncidentUpdateNote:+ return true+ }+ return false+}diff --git a/backend/app/models/models.go b/backend/app/models/models.goindex 950eda69..2182b026 100644--- a/backend/app/models/models.go+++ b/backend/app/models/models.go@@ -74,6 +74,15 @@ func Init(driver lit.Driver) {lit.RegisterModel[CheckRun](driver)lit.RegisterModel[CheckRunHealthCounts](driver)lit.RegisterModel[CheckIncident](driver)+ lit.RegisterModel[IncidentUpdate](driver)+ lit.RegisterModel[IncidentUpdateCount](driver)+ lit.RegisterModel[OrgIncident](driver)+ lit.RegisterModel[PostMortem](driver)+ lit.RegisterModel[PostMortemDetail](driver)+ lit.RegisterModel[PostMortemListItem](driver)+ lit.RegisterModel[PostMortemRef](driver)+ lit.RegisterModel[PostMortemEvent](driver)+ lit.RegisterModel[PostMortemEventItem](driver)lit.RegisterModel[SyntheticRunner](driver)lit.RegisterModel[StatusPage](driver)diff --git a/backend/app/models/post_mortem.model.go b/backend/app/models/post_mortem.model.gonew file mode 100644index 00000000..7f0c28ae--- /dev/null+++ b/backend/app/models/post_mortem.model.go@@ -0,0 +1,81 @@+package models++import (+ "time"++ "github.com/google/uuid"+)++type PostMortem struct {+ Id int `json:"id" lit:"id"`+ OrganizationId int `json:"organizationId" lit:"organization_id"`+ ProjectId uuid.UUID `json:"projectId" lit:"project_id"`+ IncidentId *int `json:"incidentId" lit:"incident_id"`+ Title string `json:"title" lit:"title"`+ ContentMd string `json:"contentMd" lit:"content_md"`+ Tags StringSlice `json:"tags" lit:"tags"`+ CreatedBy *int `json:"createdBy" lit:"created_by"`+ UpdatedBy *int `json:"updatedBy" lit:"updated_by"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+ UpdatedAt time.Time `json:"updatedAt" lit:"updated_at"`+}++type PostMortemDetail struct {+ Id int `json:"id" lit:"id"`+ OrganizationId int `json:"organizationId" lit:"organization_id"`+ ProjectId uuid.UUID `json:"projectId" lit:"project_id"`+ IncidentId *int `json:"incidentId" lit:"incident_id"`+ Title string `json:"title" lit:"title"`+ ContentMd string `json:"contentMd" lit:"content_md"`+ Tags StringSlice `json:"tags" lit:"tags"`+ CreatedBy *int `json:"createdBy" lit:"created_by"`+ UpdatedBy *int `json:"updatedBy" lit:"updated_by"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+ UpdatedAt time.Time `json:"updatedAt" lit:"updated_at"`+ CreatedByName *string `json:"createdByName" lit:"created_by_name"`+ UpdatedByName *string `json:"updatedByName" lit:"updated_by_name"`+}++type PostMortemListItem struct {+ Id int `json:"id" lit:"id"`+ OrganizationId int `json:"organizationId" lit:"organization_id"`+ ProjectId uuid.UUID `json:"projectId" lit:"project_id"`+ IncidentId *int `json:"incidentId" lit:"incident_id"`+ Title string `json:"title" lit:"title"`+ Tags StringSlice `json:"tags" lit:"tags"`+ CreatedBy *int `json:"createdBy" lit:"created_by"`+ UpdatedBy *int `json:"updatedBy" lit:"updated_by"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+ UpdatedAt time.Time `json:"updatedAt" lit:"updated_at"`+ CreatedByName *string `json:"createdByName" lit:"created_by_name"`+ UpdatedByName *string `json:"updatedByName" lit:"updated_by_name"`+}++type PostMortemRef struct {+ Id int `json:"id" lit:"id"`+ IncidentId *int `json:"incidentId" lit:"incident_id"`+}++const (+ PostMortemEventCreated = "created"+ PostMortemEventUpdated = "updated"+)++type PostMortemEvent struct {+ Id int `json:"id" lit:"id"`+ PostMortemId int `json:"postMortemId" lit:"post_mortem_id"`+ UserId *int `json:"userId" lit:"user_id"`+ Action string `json:"action" lit:"action"`+ Changes StringSlice `json:"changes" lit:"changes"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+}++type PostMortemEventItem struct {+ Id int `json:"id" lit:"id"`+ PostMortemId int `json:"postMortemId" lit:"post_mortem_id"`+ UserId *int `json:"userId" lit:"user_id"`+ Action string `json:"action" lit:"action"`+ Changes StringSlice `json:"changes" lit:"changes"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+ UserName *string `json:"userName" lit:"user_name"`+}diff --git a/backend/app/models/synthetics.model.go b/backend/app/models/synthetics.model.goindex 853f9c6b..147dbc52 100644--- a/backend/app/models/synthetics.model.go+++ b/backend/app/models/synthetics.model.go@@ -57,8 +57,10 @@ type CheckRun struct {type CheckIncident struct {Id int `json:"id" lit:"id"`- CheckId int `json:"checkId" lit:"check_id"`- ProjectId uuid.UUID `json:"projectId" lit:"project_id"`+ CheckId *int `json:"checkId" lit:"check_id"`+ ProjectId *uuid.UUID `json:"projectId" lit:"project_id"`+ StatusPageId *int `json:"statusPageId" lit:"status_page_id"`+ Title string `json:"title" lit:"title"`StartedAt time.Time `json:"startedAt" lit:"started_at"`ResolvedAt *time.Time `json:"resolvedAt" lit:"resolved_at"`ErrorMessage string `json:"errorMessage" lit:"error_message"`diff --git a/backend/app/repositories/transactional/pg/check_incident.repository.go b/backend/app/repositories/transactional/pg/check_incident.repository.goindex 4a7008d1..da5d055c 100644--- a/backend/app/repositories/transactional/pg/check_incident.repository.go+++ b/backend/app/repositories/transactional/pg/check_incident.repository.go@@ -14,7 +14,11 @@ import (type checkIncidentRepository struct{}-const checkIncidentColumns = "id, check_id, project_id, started_at, resolved_at, error_message"+const checkIncidentColumns = "id, check_id, project_id, status_page_id, title, started_at, resolved_at, error_message"++const checkIncidentJoinedColumns = "i.id, i.check_id, i.project_id, i.status_page_id, i.title, i.started_at, i.resolved_at, i.error_message"++const checkIncidentOrgJoin = "FROM check_incidents i LEFT JOIN synthetic_checks c ON c.id = i.check_id LEFT JOIN projects p ON p.id = c.project_id LEFT JOIN status_pages sp ON sp.id = i.status_page_id"func (r *checkIncidentRepository) Open(tx *sql.Tx, incident *models.CheckIncident) (int, error) {return lit.Insert[models.CheckIncident](tx, incident)@@ -56,4 +60,112 @@ func (r *checkIncidentRepository) FindByCheckSince(tx *sql.Tx, checkId int, sinc)}+func (r *checkIncidentRepository) FindByIdInOrganization(tx *sql.Tx, id int, organizationId int) (*models.CheckIncident, error) {+ return lit.SelectSingleNamed[models.CheckIncident](+ tx,+ "SELECT "+checkIncidentJoinedColumns+" "+checkIncidentOrgJoin+" WHERE i.id = :id AND (p.organization_id = :organization_id OR sp.organization_id = :organization_id)",+ lit.P{"id": id, "organization_id": organizationId},+ )+}++func (r *checkIncidentRepository) FindByStatusPageSince(tx *sql.Tx, statusPageId int, since time.Time) ([]*models.CheckIncident, error) {+ return lit.SelectNamed[models.CheckIncident](+ tx,+ "SELECT "+checkIncidentColumns+" FROM check_incidents WHERE status_page_id = :status_page_id AND (resolved_at IS NULL OR resolved_at >= :since) ORDER BY started_at DESC, id DESC",+ lit.P{"status_page_id": statusPageId, "since": since.UTC()},+ )+}++func (r *checkIncidentRepository) FindRecentByOrganization(tx *sql.Tx, organizationId int, since time.Time, limit int) ([]*models.OrgIncident, error) {+ return lit.SelectNamed[models.OrgIncident](+ tx,+ "SELECT "+checkIncidentJoinedColumns+", c.name AS check_name, sp.name AS status_page_name "+checkIncidentOrgJoin+" WHERE (p.organization_id = :organization_id OR sp.organization_id = :organization_id) AND (i.resolved_at IS NULL OR i.resolved_at >= :since) ORDER BY i.started_at DESC, i.id DESC LIMIT :limit",+ lit.P{"organization_id": organizationId, "since": since.UTC(), "limit": limit},+ )+}++func statusPageIncidentCondition(statusPageId int, checkIds []int) (string, lit.P) {+ condition := "i.status_page_id = :status_page_id"+ params := lit.P{"status_page_id": statusPageId}+ if len(checkIds) > 0 {+ inList, inParams := incidentIdParams(checkIds)+ for name, value := range inParams {+ params[name] = value+ }+ condition = "(" + condition + " OR i.check_id IN (" + inList + "))"+ }+ return condition, params+}++func (r *checkIncidentRepository) FindByStatusPagePaged(tx *sql.Tx, statusPageId int, checkIds []int, limit int, offset int) ([]*models.OrgIncident, error) {+ condition, params := statusPageIncidentCondition(statusPageId, checkIds)+ params["limit"] = limit+ params["offset"] = offset+ return lit.SelectNamed[models.OrgIncident](+ tx,+ "SELECT "+checkIncidentJoinedColumns+", c.name AS check_name, sp.name AS status_page_name "+checkIncidentOrgJoin+" WHERE "+condition+" ORDER BY i.started_at DESC, i.id DESC LIMIT :limit OFFSET :offset",+ params,+ )+}++func (r *checkIncidentRepository) CountByStatusPage(tx *sql.Tx, statusPageId int, checkIds []int) (int, error) {+ condition, params := statusPageIncidentCondition(statusPageId, checkIds)+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ "SELECT COUNT(*) as count FROM check_incidents i WHERE "+condition,+ params,+ )+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Count, nil+}++func (r *checkIncidentRepository) UpdateTitle(tx *sql.Tx, id int, title string) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE check_incidents SET title = :title WHERE id = :id",+ lit.P{"title": title, "id": id},+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, query, args...)+}++func (r *checkIncidentRepository) UpdateManualTimes(tx *sql.Tx, id int, startedAt time.Time, resolvedAt *time.Time) error {+ var resolved any+ if resolvedAt != nil {+ resolved = resolvedAt.UTC()+ }+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE check_incidents SET started_at = :started_at, resolved_at = :resolved_at WHERE id = :id AND status_page_id IS NOT NULL",+ lit.P{"started_at": startedAt.UTC(), "resolved_at": resolved, "id": id},+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, query, args...)+}++func (r *checkIncidentRepository) ResolveManual(tx *sql.Tx, id int, resolvedAt time.Time) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE check_incidents SET resolved_at = :resolved_at WHERE id = :id AND status_page_id IS NOT NULL AND resolved_at IS NULL",+ lit.P{"resolved_at": resolvedAt.UTC(), "id": id},+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, query, args...)+}++func (r *checkIncidentRepository) DeleteManual(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM check_incidents WHERE id = :id AND status_page_id IS NOT NULL", lit.P{"id": id})+}+var CheckIncidentRepository = checkIncidentRepository{}diff --git a/backend/app/repositories/transactional/pg/incident_update.repository.go b/backend/app/repositories/transactional/pg/incident_update.repository.gonew file mode 100644index 00000000..1f8cbc40--- /dev/null+++ b/backend/app/repositories/transactional/pg/incident_update.repository.go@@ -0,0 +1,87 @@+//go:build transactional_pg++package pg++import (+ "database/sql"+ "fmt"+ "strings"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/tracewayapp/lit/v2"+)++type incidentUpdateRepository struct{}++const incidentUpdateColumns = "id, incident_id, status, message, created_by, created_at"++func incidentIdParams(incidentIds []int) (string, lit.P) {+ params := lit.P{}+ names := make([]string, len(incidentIds))+ for i, id := range incidentIds {+ name := fmt.Sprintf("id_%d", i)+ names[i] = ":" + name+ params[name] = id+ }+ return strings.Join(names, ", "), params+}++func (r *incidentUpdateRepository) Create(tx *sql.Tx, update *models.IncidentUpdate) (int, error) {+ return lit.Insert[models.IncidentUpdate](tx, update)+}++func (r *incidentUpdateRepository) FindByIncident(tx *sql.Tx, incidentId int) ([]*models.IncidentUpdate, error) {+ return lit.SelectNamed[models.IncidentUpdate](+ tx,+ "SELECT "+incidentUpdateColumns+" FROM incident_updates WHERE incident_id = :incident_id ORDER BY created_at DESC, id DESC",+ lit.P{"incident_id": incidentId},+ )+}++func (r *incidentUpdateRepository) FindById(tx *sql.Tx, id int) (*models.IncidentUpdate, error) {+ return lit.SelectSingleNamed[models.IncidentUpdate](+ tx,+ "SELECT "+incidentUpdateColumns+" FROM incident_updates WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *incidentUpdateRepository) Delete(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM incident_updates WHERE id = :id", lit.P{"id": id})+}++func (r *incidentUpdateRepository) FindByIncidentIds(tx *sql.Tx, incidentIds []int) ([]*models.IncidentUpdate, error) {+ if len(incidentIds) == 0 {+ return []*models.IncidentUpdate{}, nil+ }+ inList, params := incidentIdParams(incidentIds)+ return lit.SelectNamed[models.IncidentUpdate](+ tx,+ "SELECT "+incidentUpdateColumns+" FROM incident_updates WHERE incident_id IN ("+inList+") ORDER BY incident_id ASC, created_at DESC, id DESC",+ params,+ )+}++func (r *incidentUpdateRepository) CountByIncidentIds(tx *sql.Tx, incidentIds []int) (map[int]int, error) {+ if len(incidentIds) == 0 {+ return map[int]int{}, nil+ }+ inList, params := incidentIdParams(incidentIds)+ rows, err := lit.SelectNamed[models.IncidentUpdateCount](+ tx,+ "SELECT incident_id, COUNT(*) AS count FROM incident_updates WHERE incident_id IN ("+inList+") GROUP BY incident_id",+ params,+ )+ if err != nil {+ return nil, err+ }+ counts := make(map[int]int, len(rows))+ for _, row := range rows {+ counts[row.IncidentId] = row.Count+ }+ return counts, nil+}++var IncidentUpdateRepository = incidentUpdateRepository{}diff --git a/backend/app/repositories/transactional/pg/post_mortem.repository.go b/backend/app/repositories/transactional/pg/post_mortem.repository.gonew file mode 100644index 00000000..a7161fe9--- /dev/null+++ b/backend/app/repositories/transactional/pg/post_mortem.repository.go@@ -0,0 +1,129 @@+//go:build transactional_pg++package pg++import (+ "database/sql"+ "fmt"+ "strings"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/tracewayapp/lit/v2"+)++type postMortemRepository struct{}++const postMortemColumns = "id, organization_id, project_id, incident_id, title, content_md, tags, created_by, updated_by, created_at, updated_at"++const postMortemUserJoins = " LEFT JOIN users cu ON cu.id = pm.created_by LEFT JOIN users uu ON uu.id = pm.updated_by"++const postMortemDetailColumns = "pm.id, pm.organization_id, pm.project_id, pm.incident_id, pm.title, pm.content_md, pm.tags, pm.created_by, pm.updated_by, pm.created_at, pm.updated_at, cu.name AS created_by_name, uu.name AS updated_by_name"++const postMortemListColumns = "pm.id, pm.organization_id, pm.project_id, pm.incident_id, pm.title, pm.tags, pm.created_by, pm.updated_by, pm.created_at, pm.updated_at, cu.name AS created_by_name, uu.name AS updated_by_name"++var likeEscaper = strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`)++func postMortemFilter(projectId uuid.UUID, search string, tags []string) (string, lit.P) {+ conditions := "pm.project_id = :project_id"+ params := lit.P{"project_id": projectId}+ if search != "" {+ conditions += ` AND (LOWER(pm.title) LIKE :search ESCAPE '\' OR LOWER(pm.content_md) LIKE :search ESCAPE '\' OR LOWER(pm.tags) LIKE :search ESCAPE '\')`+ params["search"] = "%" + likeEscaper.Replace(strings.ToLower(search)) + "%"+ }+ for i, tag := range tags {+ name := fmt.Sprintf("tag_%d", i)+ conditions += " AND pm.tags LIKE :" + name + ` ESCAPE '\'`+ params[name] = "%\"" + likeEscaper.Replace(tag) + "\"%"+ }+ return conditions, params+}++func (r *postMortemRepository) Create(tx *sql.Tx, postMortem *models.PostMortem) (int, error) {+ return lit.Insert[models.PostMortem](tx, postMortem)+}++func (r *postMortemRepository) Update(tx *sql.Tx, postMortem *models.PostMortem) error {+ return lit.UpdateNamed(tx, postMortem, "id = :id AND project_id = :project_id", lit.P{"id": postMortem.Id, "project_id": postMortem.ProjectId})+}++func (r *postMortemRepository) Delete(tx *sql.Tx, id int, projectId uuid.UUID) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM post_mortems WHERE id = :id AND project_id = :project_id", lit.P{"id": id, "project_id": projectId})+}++func (r *postMortemRepository) FindByIdForProject(tx *sql.Tx, id int, projectId uuid.UUID) (*models.PostMortem, error) {+ return lit.SelectSingleNamed[models.PostMortem](+ tx,+ "SELECT "+postMortemColumns+" FROM post_mortems WHERE id = :id AND project_id = :project_id",+ lit.P{"id": id, "project_id": projectId},+ )+}++func (r *postMortemRepository) FindDetailByIdForProject(tx *sql.Tx, id int, projectId uuid.UUID) (*models.PostMortemDetail, error) {+ return lit.SelectSingleNamed[models.PostMortemDetail](+ tx,+ "SELECT "+postMortemDetailColumns+" FROM post_mortems pm"+postMortemUserJoins+" WHERE pm.id = :id AND pm.project_id = :project_id",+ lit.P{"id": id, "project_id": projectId},+ )+}++func (r *postMortemRepository) FindRefsByIncidentIds(tx *sql.Tx, incidentIds []int) ([]*models.PostMortemRef, error) {+ if len(incidentIds) == 0 {+ return []*models.PostMortemRef{}, nil+ }+ inList, params := incidentIdParams(incidentIds)+ return lit.SelectNamed[models.PostMortemRef](+ tx,+ "SELECT id, incident_id FROM post_mortems WHERE incident_id IN ("+inList+")",+ params,+ )+}++func (r *postMortemRepository) ListByProject(tx *sql.Tx, projectId uuid.UUID, search string, tags []string, limit int, offset int) ([]*models.PostMortemListItem, error) {+ conditions, params := postMortemFilter(projectId, search, tags)+ params["limit"] = limit+ params["offset"] = offset+ return lit.SelectNamed[models.PostMortemListItem](+ tx,+ "SELECT "+postMortemListColumns+" FROM post_mortems pm"+postMortemUserJoins+" WHERE "+conditions+" ORDER BY pm.updated_at DESC, pm.id DESC LIMIT :limit OFFSET :offset",+ params,+ )+}++func (r *postMortemRepository) CountByProject(tx *sql.Tx, projectId uuid.UUID, search string, tags []string) (int, error) {+ conditions, params := postMortemFilter(projectId, search, tags)+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ "SELECT COUNT(*) as count FROM post_mortems pm WHERE "+conditions,+ params,+ )+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Count, nil+}++func (r *postMortemRepository) RecordEvent(tx *sql.Tx, event *models.PostMortemEvent) error {+ _, err := lit.Insert[models.PostMortemEvent](tx, event)+ return err+}++func (r *postMortemRepository) ListEvents(tx *sql.Tx, postMortemId int, projectId uuid.UUID, limit int) ([]*models.PostMortemEventItem, error) {+ return lit.SelectNamed[models.PostMortemEventItem](+ tx,+ "SELECT e.id, e.post_mortem_id, e.user_id, e.action, e.changes, e.created_at, u.name AS user_name"++ " FROM post_mortem_events e"++ " JOIN post_mortems pm ON pm.id = e.post_mortem_id"++ " LEFT JOIN users u ON u.id = e.user_id"++ " WHERE e.post_mortem_id = :post_mortem_id AND pm.project_id = :project_id"++ " ORDER BY e.created_at DESC, e.id DESC LIMIT :limit",+ lit.P{"post_mortem_id": postMortemId, "project_id": projectId, "limit": limit},+ )+}++var PostMortemRepository = postMortemRepository{}diff --git a/backend/app/repositories/transactional/sqlite/check_incident.repository.go b/backend/app/repositories/transactional/sqlite/check_incident.repository.goindex f81ae757..c8406b9f 100644--- a/backend/app/repositories/transactional/sqlite/check_incident.repository.go+++ b/backend/app/repositories/transactional/sqlite/check_incident.repository.go@@ -14,7 +14,11 @@ import (type checkIncidentRepository struct{}-const checkIncidentColumns = "id, check_id, project_id, started_at, resolved_at, error_message"+const checkIncidentColumns = "id, check_id, project_id, status_page_id, title, started_at, resolved_at, error_message"++const checkIncidentJoinedColumns = "i.id, i.check_id, i.project_id, i.status_page_id, i.title, i.started_at, i.resolved_at, i.error_message"++const checkIncidentOrgJoin = "FROM check_incidents i LEFT JOIN synthetic_checks c ON c.id = i.check_id LEFT JOIN projects p ON p.id = c.project_id LEFT JOIN status_pages sp ON sp.id = i.status_page_id"func (r *checkIncidentRepository) Open(tx *sql.Tx, incident *models.CheckIncident) (int, error) {return lit.Insert[models.CheckIncident](tx, incident)@@ -56,4 +60,112 @@ func (r *checkIncidentRepository) FindByCheckSince(tx *sql.Tx, checkId int, sinc)}+func (r *checkIncidentRepository) FindByIdInOrganization(tx *sql.Tx, id int, organizationId int) (*models.CheckIncident, error) {+ return lit.SelectSingleNamed[models.CheckIncident](+ tx,+ "SELECT "+checkIncidentJoinedColumns+" "+checkIncidentOrgJoin+" WHERE i.id = :id AND (p.organization_id = :organization_id OR sp.organization_id = :organization_id)",+ lit.P{"id": id, "organization_id": organizationId},+ )+}++func (r *checkIncidentRepository) FindByStatusPageSince(tx *sql.Tx, statusPageId int, since time.Time) ([]*models.CheckIncident, error) {+ return lit.SelectNamed[models.CheckIncident](+ tx,+ "SELECT "+checkIncidentColumns+" FROM check_incidents WHERE status_page_id = :status_page_id AND (resolved_at IS NULL OR resolved_at >= :since) ORDER BY started_at DESC, id DESC",+ lit.P{"status_page_id": statusPageId, "since": since.UTC()},+ )+}++func (r *checkIncidentRepository) FindRecentByOrganization(tx *sql.Tx, organizationId int, since time.Time, limit int) ([]*models.OrgIncident, error) {+ return lit.SelectNamed[models.OrgIncident](+ tx,+ "SELECT "+checkIncidentJoinedColumns+", c.name AS check_name, sp.name AS status_page_name "+checkIncidentOrgJoin+" WHERE (p.organization_id = :organization_id OR sp.organization_id = :organization_id) AND (i.resolved_at IS NULL OR i.resolved_at >= :since) ORDER BY i.started_at DESC, i.id DESC LIMIT :limit",+ lit.P{"organization_id": organizationId, "since": since.UTC(), "limit": limit},+ )+}++func statusPageIncidentCondition(statusPageId int, checkIds []int) (string, lit.P) {+ condition := "i.status_page_id = :status_page_id"+ params := lit.P{"status_page_id": statusPageId}+ if len(checkIds) > 0 {+ inList, inParams := incidentIdParams(checkIds)+ for name, value := range inParams {+ params[name] = value+ }+ condition = "(" + condition + " OR i.check_id IN (" + inList + "))"+ }+ return condition, params+}++func (r *checkIncidentRepository) FindByStatusPagePaged(tx *sql.Tx, statusPageId int, checkIds []int, limit int, offset int) ([]*models.OrgIncident, error) {+ condition, params := statusPageIncidentCondition(statusPageId, checkIds)+ params["limit"] = limit+ params["offset"] = offset+ return lit.SelectNamed[models.OrgIncident](+ tx,+ "SELECT "+checkIncidentJoinedColumns+", c.name AS check_name, sp.name AS status_page_name "+checkIncidentOrgJoin+" WHERE "+condition+" ORDER BY i.started_at DESC, i.id DESC LIMIT :limit OFFSET :offset",+ params,+ )+}++func (r *checkIncidentRepository) CountByStatusPage(tx *sql.Tx, statusPageId int, checkIds []int) (int, error) {+ condition, params := statusPageIncidentCondition(statusPageId, checkIds)+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ "SELECT COUNT(*) as count FROM check_incidents i WHERE "+condition,+ params,+ )+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Count, nil+}++func (r *checkIncidentRepository) UpdateTitle(tx *sql.Tx, id int, title string) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE check_incidents SET title = :title WHERE id = :id",+ lit.P{"title": title, "id": id},+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, query, args...)+}++func (r *checkIncidentRepository) UpdateManualTimes(tx *sql.Tx, id int, startedAt time.Time, resolvedAt *time.Time) error {+ var resolved any+ if resolvedAt != nil {+ resolved = resolvedAt.UTC()+ }+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE check_incidents SET started_at = :started_at, resolved_at = :resolved_at WHERE id = :id AND status_page_id IS NOT NULL",+ lit.P{"started_at": startedAt.UTC(), "resolved_at": resolved, "id": id},+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, query, args...)+}++func (r *checkIncidentRepository) ResolveManual(tx *sql.Tx, id int, resolvedAt time.Time) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE check_incidents SET resolved_at = :resolved_at WHERE id = :id AND status_page_id IS NOT NULL AND resolved_at IS NULL",+ lit.P{"resolved_at": resolvedAt.UTC(), "id": id},+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, query, args...)+}++func (r *checkIncidentRepository) DeleteManual(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM check_incidents WHERE id = :id AND status_page_id IS NOT NULL", lit.P{"id": id})+}+var CheckIncidentRepository = checkIncidentRepository{}diff --git a/backend/app/repositories/transactional/sqlite/incident_update.repository.go b/backend/app/repositories/transactional/sqlite/incident_update.repository.gonew file mode 100644index 00000000..6dbc7a25--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/incident_update.repository.go@@ -0,0 +1,87 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "fmt"+ "strings"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/tracewayapp/lit/v2"+)++type incidentUpdateRepository struct{}++const incidentUpdateColumns = "id, incident_id, status, message, created_by, created_at"++func incidentIdParams(incidentIds []int) (string, lit.P) {+ params := lit.P{}+ names := make([]string, len(incidentIds))+ for i, id := range incidentIds {+ name := fmt.Sprintf("id_%d", i)+ names[i] = ":" + name+ params[name] = id+ }+ return strings.Join(names, ", "), params+}++func (r *incidentUpdateRepository) Create(tx *sql.Tx, update *models.IncidentUpdate) (int, error) {+ return lit.Insert[models.IncidentUpdate](tx, update)+}++func (r *incidentUpdateRepository) FindByIncident(tx *sql.Tx, incidentId int) ([]*models.IncidentUpdate, error) {+ return lit.SelectNamed[models.IncidentUpdate](+ tx,+ "SELECT "+incidentUpdateColumns+" FROM incident_updates WHERE incident_id = :incident_id ORDER BY created_at DESC, id DESC",+ lit.P{"incident_id": incidentId},+ )+}++func (r *incidentUpdateRepository) FindById(tx *sql.Tx, id int) (*models.IncidentUpdate, error) {+ return lit.SelectSingleNamed[models.IncidentUpdate](+ tx,+ "SELECT "+incidentUpdateColumns+" FROM incident_updates WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *incidentUpdateRepository) Delete(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM incident_updates WHERE id = :id", lit.P{"id": id})+}++func (r *incidentUpdateRepository) FindByIncidentIds(tx *sql.Tx, incidentIds []int) ([]*models.IncidentUpdate, error) {+ if len(incidentIds) == 0 {+ return []*models.IncidentUpdate{}, nil+ }+ inList, params := incidentIdParams(incidentIds)+ return lit.SelectNamed[models.IncidentUpdate](+ tx,+ "SELECT "+incidentUpdateColumns+" FROM incident_updates WHERE incident_id IN ("+inList+") ORDER BY incident_id ASC, created_at DESC, id DESC",+ params,+ )+}++func (r *incidentUpdateRepository) CountByIncidentIds(tx *sql.Tx, incidentIds []int) (map[int]int, error) {+ if len(incidentIds) == 0 {+ return map[int]int{}, nil+ }+ inList, params := incidentIdParams(incidentIds)+ rows, err := lit.SelectNamed[models.IncidentUpdateCount](+ tx,+ "SELECT incident_id, COUNT(*) AS count FROM incident_updates WHERE incident_id IN ("+inList+") GROUP BY incident_id",+ params,+ )+ if err != nil {+ return nil, err+ }+ counts := make(map[int]int, len(rows))+ for _, row := range rows {+ counts[row.IncidentId] = row.Count+ }+ return counts, nil+}++var IncidentUpdateRepository = incidentUpdateRepository{}diff --git a/backend/app/repositories/transactional/sqlite/post_mortem.repository.go b/backend/app/repositories/transactional/sqlite/post_mortem.repository.gonew file mode 100644index 00000000..f617db55--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/post_mortem.repository.go@@ -0,0 +1,129 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "fmt"+ "strings"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/tracewayapp/lit/v2"+)++type postMortemRepository struct{}++const postMortemColumns = "id, organization_id, project_id, incident_id, title, content_md, tags, created_by, updated_by, created_at, updated_at"++const postMortemUserJoins = " LEFT JOIN users cu ON cu.id = pm.created_by LEFT JOIN users uu ON uu.id = pm.updated_by"++const postMortemDetailColumns = "pm.id, pm.organization_id, pm.project_id, pm.incident_id, pm.title, pm.content_md, pm.tags, pm.created_by, pm.updated_by, pm.created_at, pm.updated_at, cu.name AS created_by_name, uu.name AS updated_by_name"++const postMortemListColumns = "pm.id, pm.organization_id, pm.project_id, pm.incident_id, pm.title, pm.tags, pm.created_by, pm.updated_by, pm.created_at, pm.updated_at, cu.name AS created_by_name, uu.name AS updated_by_name"++var likeEscaper = strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`)++func postMortemFilter(projectId uuid.UUID, search string, tags []string) (string, lit.P) {+ conditions := "pm.project_id = :project_id"+ params := lit.P{"project_id": projectId}+ if search != "" {+ conditions += ` AND (LOWER(pm.title) LIKE :search ESCAPE '\' OR LOWER(pm.content_md) LIKE :search ESCAPE '\' OR LOWER(pm.tags) LIKE :search ESCAPE '\')`+ params["search"] = "%" + likeEscaper.Replace(strings.ToLower(search)) + "%"+ }+ for i, tag := range tags {+ name := fmt.Sprintf("tag_%d", i)+ conditions += " AND pm.tags LIKE :" + name + ` ESCAPE '\'`+ params[name] = "%\"" + likeEscaper.Replace(tag) + "\"%"+ }+ return conditions, params+}++func (r *postMortemRepository) Create(tx *sql.Tx, postMortem *models.PostMortem) (int, error) {+ return lit.Insert[models.PostMortem](tx, postMortem)+}++func (r *postMortemRepository) Update(tx *sql.Tx, postMortem *models.PostMortem) error {+ return lit.UpdateNamed(tx, postMortem, "id = :id AND project_id = :project_id", lit.P{"id": postMortem.Id, "project_id": postMortem.ProjectId})+}++func (r *postMortemRepository) Delete(tx *sql.Tx, id int, projectId uuid.UUID) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM post_mortems WHERE id = :id AND project_id = :project_id", lit.P{"id": id, "project_id": projectId})+}++func (r *postMortemRepository) FindByIdForProject(tx *sql.Tx, id int, projectId uuid.UUID) (*models.PostMortem, error) {+ return lit.SelectSingleNamed[models.PostMortem](+ tx,+ "SELECT "+postMortemColumns+" FROM post_mortems WHERE id = :id AND project_id = :project_id",+ lit.P{"id": id, "project_id": projectId},+ )+}++func (r *postMortemRepository) FindDetailByIdForProject(tx *sql.Tx, id int, projectId uuid.UUID) (*models.PostMortemDetail, error) {+ return lit.SelectSingleNamed[models.PostMortemDetail](+ tx,+ "SELECT "+postMortemDetailColumns+" FROM post_mortems pm"+postMortemUserJoins+" WHERE pm.id = :id AND pm.project_id = :project_id",+ lit.P{"id": id, "project_id": projectId},+ )+}++func (r *postMortemRepository) FindRefsByIncidentIds(tx *sql.Tx, incidentIds []int) ([]*models.PostMortemRef, error) {+ if len(incidentIds) == 0 {+ return []*models.PostMortemRef{}, nil+ }+ inList, params := incidentIdParams(incidentIds)+ return lit.SelectNamed[models.PostMortemRef](+ tx,+ "SELECT id, incident_id FROM post_mortems WHERE incident_id IN ("+inList+")",+ params,+ )+}++func (r *postMortemRepository) ListByProject(tx *sql.Tx, projectId uuid.UUID, search string, tags []string, limit int, offset int) ([]*models.PostMortemListItem, error) {+ conditions, params := postMortemFilter(projectId, search, tags)+ params["limit"] = limit+ params["offset"] = offset+ return lit.SelectNamed[models.PostMortemListItem](+ tx,+ "SELECT "+postMortemListColumns+" FROM post_mortems pm"+postMortemUserJoins+" WHERE "+conditions+" ORDER BY pm.updated_at DESC, pm.id DESC LIMIT :limit OFFSET :offset",+ params,+ )+}++func (r *postMortemRepository) CountByProject(tx *sql.Tx, projectId uuid.UUID, search string, tags []string) (int, error) {+ conditions, params := postMortemFilter(projectId, search, tags)+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ "SELECT COUNT(*) as count FROM post_mortems pm WHERE "+conditions,+ params,+ )+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Count, nil+}++func (r *postMortemRepository) RecordEvent(tx *sql.Tx, event *models.PostMortemEvent) error {+ _, err := lit.Insert[models.PostMortemEvent](tx, event)+ return err+}++func (r *postMortemRepository) ListEvents(tx *sql.Tx, postMortemId int, projectId uuid.UUID, limit int) ([]*models.PostMortemEventItem, error) {+ return lit.SelectNamed[models.PostMortemEventItem](+ tx,+ "SELECT e.id, e.post_mortem_id, e.user_id, e.action, e.changes, e.created_at, u.name AS user_name"++ " FROM post_mortem_events e"++ " JOIN post_mortems pm ON pm.id = e.post_mortem_id"++ " LEFT JOIN users u ON u.id = e.user_id"++ " WHERE e.post_mortem_id = :post_mortem_id AND pm.project_id = :project_id"++ " ORDER BY e.created_at DESC, e.id DESC LIMIT :limit",+ lit.P{"post_mortem_id": postMortemId, "project_id": projectId, "limit": limit},+ )+}++var PostMortemRepository = postMortemRepository{}diff --git a/backend/app/repositories/transactional/transactional_pg.go b/backend/app/repositories/transactional/transactional_pg.goindex 89484981..a60c90ea 100644--- a/backend/app/repositories/transactional/transactional_pg.go+++ b/backend/app/repositories/transactional/transactional_pg.go@@ -12,6 +12,7 @@ var (DashboardTemplateRepository = pgrepo.DashboardTemplateRepositoryDeviceAuthorizationRepository = pgrepo.DeviceAuthorizationRepositoryEscalationPolicyRepository = pgrepo.EscalationPolicyRepository+ IncidentUpdateRepository = pgrepo.IncidentUpdateRepositoryInvitationRepository = pgrepo.InvitationRepositoryMetricRegistryRepository = pgrepo.MetricRegistryRepositoryNotificationChannelRepository = pgrepo.NotificationChannelRepository@@ -25,6 +26,7 @@ var (PageNotificationRepository = pgrepo.PageNotificationRepositoryPageRepository = pgrepo.PageRepositoryPersonalAccessTokenRepository = pgrepo.PersonalAccessTokenRepository+ PostMortemRepository = pgrepo.PostMortemRepositoryProjectRepository = pgrepo.ProjectRepositoryProjectUserRoleRepository = pgrepo.ProjectUserRoleRepositoryRefreshTokenRepository = pgrepo.RefreshTokenRepositorydiff --git a/backend/app/repositories/transactional/transactional_sqlite.go b/backend/app/repositories/transactional/transactional_sqlite.goindex 3b7754c9..2effc2c5 100644--- a/backend/app/repositories/transactional/transactional_sqlite.go+++ b/backend/app/repositories/transactional/transactional_sqlite.go@@ -12,6 +12,7 @@ var (DashboardTemplateRepository = sqliterepo.DashboardTemplateRepositoryDeviceAuthorizationRepository = sqliterepo.DeviceAuthorizationRepositoryEscalationPolicyRepository = sqliterepo.EscalationPolicyRepository+ IncidentUpdateRepository = sqliterepo.IncidentUpdateRepositoryInvitationRepository = sqliterepo.InvitationRepositoryMetricRegistryRepository = sqliterepo.MetricRegistryRepositoryNotificationChannelRepository = sqliterepo.NotificationChannelRepository@@ -25,6 +26,7 @@ var (PageNotificationRepository = sqliterepo.PageNotificationRepositoryPageRepository = sqliterepo.PageRepositoryPersonalAccessTokenRepository = sqliterepo.PersonalAccessTokenRepository+ PostMortemRepository = sqliterepo.PostMortemRepositoryProjectRepository = sqliterepo.ProjectRepositoryProjectUserRoleRepository = sqliterepo.ProjectUserRoleRepositoryRefreshTokenRepository = sqliterepo.RefreshTokenRepositorydiff --git a/backend/app/synthetics/result.go b/backend/app/synthetics/result.goindex 99a47073..59e5c3df 100644--- a/backend/app/synthetics/result.go+++ b/backend/app/synthetics/result.go@@ -102,12 +102,21 @@ func ProcessOutcome(ctx context.Context, run *models.CheckRun, claimedBy string,}if open == nil {incident := &models.CheckIncident{- CheckId: check.Id,- ProjectId: check.ProjectId,+ CheckId: &check.Id,+ ProjectId: &check.ProjectId,StartedAt: outcome.ExecutedAt,ErrorMessage: outcome.ErrorMsg,}- if _, err := transactional.CheckIncidentRepository.Open(tx, incident); err != nil {+ incidentId, err := transactional.CheckIncidentRepository.Open(tx, incident)+ if err != nil {+ return res, err+ }+ update := &models.IncidentUpdate{+ IncidentId: incidentId,+ Status: models.IncidentUpdateInvestigating,+ CreatedAt: outcome.ExecutedAt,+ }+ if _, err := transactional.IncidentUpdateRepository.Create(tx, update); err != nil {return res, err}}@@ -121,6 +130,14 @@ func ProcessOutcome(ctx context.Context, run *models.CheckRun, claimedBy string,if err := transactional.CheckIncidentRepository.Resolve(tx, open.Id, outcome.ExecutedAt); err != nil {return res, err}+ update := &models.IncidentUpdate{+ IncidentId: open.Id,+ Status: models.IncidentUpdateResolved,+ CreatedAt: outcome.ExecutedAt,+ }+ if _, err := transactional.IncidentUpdateRepository.Create(tx, update); err != nil {+ return res, err+ }}}diff --git a/backend/app/synthetics/synthetics_sqlite_test.go b/backend/app/synthetics/synthetics_sqlite_test.goindex b1c0e4c8..10af37b1 100644--- a/backend/app/synthetics/synthetics_sqlite_test.go+++ b/backend/app/synthetics/synthetics_sqlite_test.go@@ -299,6 +299,24 @@ func TestFailureThresholdIncidentAndRecovery(t *testing.T) {if err != nil || openIncident == nil {t.Fatalf("expected an open incident, got %+v (%v)", openIncident, err)}+ if openIncident.CheckId == nil || *openIncident.CheckId != check.Id {+ t.Fatalf("open incident check id = %v, want %d", openIncident.CheckId, check.Id)+ }+ if openIncident.StatusPageId != nil {+ t.Fatalf("auto incident carries a status page id: %+v", openIncident)+ }+ openUpdates, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.IncidentUpdate, error) {+ return transactional.IncidentUpdateRepository.FindByIncident(tx, openIncident.Id)+ })+ if err != nil {+ t.Fatalf("find incident updates: %v", err)+ }+ if len(openUpdates) != 1 || openUpdates[0].Status != models.IncidentUpdateInvestigating {+ t.Fatalf("expected one seeded investigating update, got %+v", openUpdates)+ }+ if openUpdates[0].Message != "" {+ t.Fatalf("seeded update must not leak the probe error, got %q", openUpdates[0].Message)+ }// A third failure must not re-notify or duplicate the incident.runOnce(now.Add(122 * time.Second))@@ -332,6 +350,15 @@ func TestFailureThresholdIncidentAndRecovery(t *testing.T) {if stillOpen != nil {t.Fatalf("incident not resolved: %+v", stillOpen)}+ resolvedUpdates, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.IncidentUpdate, error) {+ return transactional.IncidentUpdateRepository.FindByIncident(tx, openIncident.Id)+ })+ if err != nil {+ t.Fatalf("find incident updates after recovery: %v", err)+ }+ if len(resolvedUpdates) != 2 || resolvedUpdates[0].Status != models.IncidentUpdateResolved {+ t.Fatalf("expected a seeded resolved update on top, got %+v", resolvedUpdates)+ }results := checkResults(t, projectId, check.Id)if len(results) != 4 {diff --git a/docs/pages/learn/_meta.json b/docs/pages/learn/_meta.jsonindex 2b2b51c0..1e0a8538 100644--- a/docs/pages/learn/_meta.json+++ b/docs/pages/learn/_meta.json@@ -18,6 +18,7 @@"alerts": "Alerts","on-call": "On-Call","monitors": "Monitors",+ "incidents": "Incidents & Post-Mortems","sso": "SSO","cli": "CLI","cli-auth": "CLI Authentication",diff --git a/docs/pages/learn/incidents.mdx b/docs/pages/learn/incidents.mdxnew file mode 100644index 00000000..5cf5b65a--- /dev/null+++ b/docs/pages/learn/incidents.mdx@@ -0,0 +1,83 @@+# Incidents & Post-Mortems++Monitors detect outages. Incidents are the record of them, and post-mortems are the write-up that makes the next one shorter. Together they give you the full incident lifecycle in one place: detection, public communication while it burns, and the internal document afterwards. Everything lives under **Monitors** in the sidebar.++## Incidents++An incident is a span of time when something was down, with an optional public story attached: a title and a timeline of updates. Incidents come from two sources.++### Automatic incidents++When a monitor crosses its failure threshold, an incident opens. When the monitor recovers, it resolves. You configure nothing; every state transition is recorded.++- The timeline is seeded automatically: an **Investigating** entry when the incident opens and a **Resolved** entry when it closes.+- The probe's error message stays internal. It shows on the monitor's run history, never in the public payload.+- The incident appears on the monitor's detail page, in the organization's incident history, and on any public status page that includes the monitor.+- The lifecycle belongs to the monitor. An automatic incident cannot be hand-resolved, re-timed, or deleted; it closes when the probes say the service is back.++### Manual incidents++Not every outage is caught by a probe. Organization admins can record an incident by hand with the **Record Incident** button on a status page's incident history, for outages the monitors missed or for events like maintenance windows.++- A manual incident needs a title. It can carry an optional first update message.+- It can be backdated, and it can be created already resolved by setting an end time.+- Resolve it later by posting a **Resolved** update or setting the resolved time. Clearing the resolved time reopens it. Manual incidents can also be deleted.+- Manual incidents only feed the incident history and the public Past Incidents section. They never change a monitor's uptime bars.++### Titles and timeline updates++Every incident, automatic or manual, can carry a public title and a statuspage-style timeline:++- **Title.** Automatic incidents default to "<monitor name> is down". Rename them to something users understand, like "Checkout is failing for some card payments".+- **Updates.** Post entries with a status of **Investigating**, **Identified**, **Monitoring**, **Update**, or **Resolved**, each with a message. Posting a Resolved update also closes a manual incident.++Updates are public content, so posting, renaming, and deleting them needs an organization admin. Every member can read the incident history.++### Where you manage them++- **Status Pages tab → incidents action**: the full, paginated incident history of one status page. This is where new manual incidents are recorded. Expand an incident to rename it, post timeline updates, attach a post-mortem, or delete a manual one.+- **Monitor detail page**: the incidents of that one monitor, with the same title and post-mortem links.+- **Public status page**: the last 90 days appear in the **Past Incidents** section, grouped by day, with the title and the update timeline. No login required, no internal details.++## Post-mortems++Post-mortems are internal write-ups of incidents: what happened, why, and what changes. Each post-mortem belongs to one project, the same way monitors do: the **Post-Mortems** tab shows the current project's documents, and a document opened under a different project is not found. They are visible to every organization member with access to the project and never appear on public status pages.++### Creating one++Creation is deliberately lightweight: a dialog asks for a title and nothing else. The document is created immediately and the editor opens. You can start one from three places:++- the **Post-Mortems** tab,+- the incidents list on a monitor's detail page,+- an incident on a status page's incident history, which pre-links the incident.++### Writing++The editor is a WYSIWYG markdown editor. Select text to get the formatting toolbar, or type `/` to insert blocks: headings, lists, tables, code blocks, quotes. A **Rich text / Markdown** toggle at the top switches to a plain-text view of the raw markdown, for pasting an existing document or editing the source directly. Both views edit the same content.++Press **Update Post-Mortem** to save. Documents are capped at 200KB of markdown.++### Tags and the incident link++Under the title, the document carries a row of pills:++- **Tags** like `redis` or `dns`. The **+ Add tags** pill opens a dialog where you add several at once. Up to 20 tags per document.+- **Linked incident**. The **Link incident** pill opens a searchable picker of recent incidents: the project's own monitor incidents, plus manually recorded status page incidents, which belong to the organization rather than a project. Each incident can have at most one post-mortem, so incidents that already have one are not offered. Unlink with the ✕ on the pill.++The link is what connects the public and internal sides: an incident with a post-mortem shows a link to it in the incident history and on the monitor detail page. Post-mortems survive the deletion of their incident or monitor; the link is simply severed.++### Finding them again++The Post-Mortems tab has a search box that matches titles, content, and tags, so "redis" finds the stampede write-up from last year even if the title never mentions redis. Clicking a tag pill in the list filters by it, and multiple tag filters combine, narrowing to documents that carry all of them. That is the point of the tab: the next time a similar incident hits, the fix from last time is one search away.++### Activity++Every post-mortem records its own history. The **Activity** button on the document opens a panel listing every edit: who created it, who edited it, when, and which parts changed (title, content, tags, or the incident link). Saving without changing anything records nothing.++### Permissions++| Action | Who |+|--------|-----|+| Read post-mortems and incident history | Every organization member, including read-only |+| Create, edit, delete post-mortems | Members with write access to the project (per-project read-only overrides apply) |+| Record incidents, rename them, post public updates | Organization admins, since this is public content |diff --git a/docs/pages/learn/monitors.mdx b/docs/pages/learn/monitors.mdxindex c188193e..944036a0 100644--- a/docs/pages/learn/monitors.mdx+++ b/docs/pages/learn/monitors.mdx@@ -2,7 +2,7 @@Monitors answer the question your telemetry cannot: is the service actually reachable from the outside? Traces and logs only exist while requests arrive. A monitor keeps probing on a schedule, so you find out your site is down before a user tells you.-They live under **Monitors** in the sidebar, with tabs for the monitors themselves and **Status Pages**. The badge counts the monitors currently down on the current project.+They live under **Monitors** in the sidebar, with tabs for the monitors themselves, **Status Pages**, and **Post-Mortems**. The badge counts the monitors currently down on the current project.## Check types@@ -41,6 +41,14 @@ Each status page can carry a custom domain (for example `status.acme.com`):Anonymous visitors hitting the instance under that Host are routed to the status page automatically (the backend maps the Host header to the page via `/api/status-domains/resolve`).+## Incidents and post-mortems++Monitors feed a full incident-management workflow, covered in depth in [Incidents & Post-Mortems](/learn/incidents):++- **Incidents open and resolve themselves** from monitor state transitions, with an automatic Investigating and Resolved timeline. Outages your monitors missed can be recorded by hand on a status page, backdated if needed; manual incidents never change uptime numbers.+- **The public story is yours to tell.** Give incidents public titles and post statuspage-style timeline updates (Investigating, Identified, Monitoring, Update, Resolved). The last 90 days appear in the **Past Incidents** section of the public page; probe error messages stay internal.+- **Post-mortems** are internal write-ups in the **Post-Mortems** tab, owned by the project like the monitors themselves: a WYSIWYG markdown editor with a raw-markdown toggle, tags, an optional link to the incident (one per incident), a full edit activity log, and search across titles, content, and tags. They never appear on public status pages.+## Browser execution modesBrowser checks execute real user-authored JavaScript, so where that code runs is an explicit deployment decision, controlled by `SYNTHETICS_BROWSER_MODE`:diff --git a/examples/devtesting-embedded/go.mod b/examples/devtesting-embedded/go.modindex 6f49f26a..b9edb172 100644--- a/examples/devtesting-embedded/go.mod+++ b/examples/devtesting-embedded/go.mod@@ -110,7 +110,7 @@ require (github.com/tklauser/go-sysconf v0.4.0 // indirectgithub.com/tklauser/numcpus v0.12.0 // indirectgithub.com/tracewayapp/lit/v2 v2.0.2 // indirect- github.com/tracewayapp/traceway/cli v0.0.0-00010101000000-000000000000 // indirect+ github.com/tracewayapp/traceway/cli v1.9.15 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.3.1 // indirectgithub.com/yosida95/uritemplate/v3 v3.0.2 // indirect@@ -126,7 +126,7 @@ require (go.opentelemetry.io/proto/otlp/collector/profiles/v1development v0.3.0 // indirectgo.opentelemetry.io/proto/otlp/profiles/v1development v0.3.0 // indirectgo.tracewayapp.com v1.0.4 // indirect- go.tracewayapp.com/tracewaygin v1.0.2 // indirect+ go.tracewayapp.com/tracewaygin v1.0.4 // indirectgo.yaml.in/yaml/v3 v3.0.4 // indirectgolang.org/x/arch v0.25.0 // indirectgolang.org/x/crypto v0.51.0 // indirectdiff --git a/examples/devtesting-embedded/go.sum b/examples/devtesting-embedded/go.sumindex ad918dd0..bc79250b 100644--- a/examples/devtesting-embedded/go.sum+++ b/examples/devtesting-embedded/go.sum@@ -357,8 +357,8 @@ go.opentelemetry.io/proto/otlp/profiles/v1development v0.3.0 h1:ZQs05qo3Yh4KUHeVgo.opentelemetry.io/proto/otlp/profiles/v1development v0.3.0/go.mod h1:3iiRVKaCfVo0UI1ZaSMm5WbCBbINRqVlD9SUmvyBNrY=go.tracewayapp.com v1.0.4 h1:n9O1OQDRDNPwCBnb7kNd+DutcVoPj9uLn+c9n4M7qzM=go.tracewayapp.com v1.0.4/go.mod h1:sFMbWkA2TbT1OW6Hx+6jMDum2yt96irUXpC5lymblyc=-go.tracewayapp.com/tracewaygin v1.0.2 h1:MRAvtOKz0zceoe1Ee7pl5eciSerc+gIogC7oWJaKQf8=-go.tracewayapp.com/tracewaygin v1.0.2/go.mod h1:p/26TIhpfte86Gp3QJpA8Q72pJShFXX1jogIiKG2LXQ=+go.tracewayapp.com/tracewaygin v1.0.4 h1:/3DqDuTy//vaIHVMm7UtxOIF1yhWG6Zu0OXoqBbrsJA=+go.tracewayapp.com/tracewaygin v1.0.4/go.mod h1:4VCaqh0LKJJP57Ko8xeiliVO7HQIFXWpqFoJpAxkvak=go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 6fc31361..a63a4ff4 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -13,12 +13,12 @@"@fontsource-variable/inter": "^5.2.8","@fontsource/ibm-plex-mono": "^5.2.7","@fontsource/jetbrains-mono": "^5.2.8",+ "@milkdown/crepe": "^7.22.1","@sveltejs/svelte-json-tree": "^2.2.1","@tracewayapp/svelte": "^1.0.2","codemirror": "^6.0.2","d3-flame-graph": "^5.0.0","d3-selection": "^3.0.0",- "lucide-svelte": "^0.562.0","luxon": "^3.7.2","rrweb-player": "^2.0.0-alpha.18","svelte-highlight": "^7.9.0",@@ -133,16 +133,39 @@"node": ">=6.9.0"}},+ "node_modules/@babel/helper-string-parser": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },"node_modules/@babel/helper-validator-identifier": {"version": "7.29.7","resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz","integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",- "dev": true,"license": "MIT","engines": {"node": ">=6.9.0"}},+ "node_modules/@babel/parser": {+ "version": "7.29.8",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz",+ "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==",+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.29.8"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },"node_modules/@babel/runtime": {"version": "7.29.7","resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",@@ -153,6 +176,19 @@"node": ">=6.9.0"}},+ "node_modules/@babel/types": {+ "version": "7.29.8",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",+ "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.29.7",+ "@babel/helper-validator-identifier": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },"node_modules/@bramus/specificity": {"version": "2.4.2","resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",@@ -190,6 +226,83 @@"@lezer/common": "^1.1.0"}},+ "node_modules/@codemirror/lang-angular": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-angular/-/lang-angular-0.1.4.tgz",+ "integrity": "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/lang-html": "^6.0.0",+ "@codemirror/lang-javascript": "^6.1.2",+ "@codemirror/language": "^6.0.0",+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.3.3"+ }+ },+ "node_modules/@codemirror/lang-cpp": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz",+ "integrity": "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0",+ "@lezer/cpp": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-css": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",+ "integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@lezer/common": "^1.0.2",+ "@lezer/css": "^1.1.7"+ }+ },+ "node_modules/@codemirror/lang-go": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-go/-/lang-go-6.0.1.tgz",+ "integrity": "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/language": "^6.6.0",+ "@codemirror/state": "^6.0.0",+ "@lezer/common": "^1.0.0",+ "@lezer/go": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-html": {+ "version": "6.4.12",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.12.tgz",+ "integrity": "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/lang-css": "^6.0.0",+ "@codemirror/lang-javascript": "^6.0.0",+ "@codemirror/language": "^6.4.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.17.0",+ "@lezer/common": "^1.0.0",+ "@lezer/css": "^1.1.0",+ "@lezer/html": "^1.3.12"+ }+ },+ "node_modules/@codemirror/lang-java": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-java/-/lang-java-6.0.2.tgz",+ "integrity": "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0",+ "@lezer/java": "^1.0.0"+ }+ },"node_modules/@codemirror/lang-javascript": {"version": "6.2.5","resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",@@ -205,6 +318,194 @@"@lezer/javascript": "^1.0.0"}},+ "node_modules/@codemirror/lang-jinja": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-jinja/-/lang-jinja-6.0.1.tgz",+ "integrity": "sha512-P5kyHLObzjtbGj16h+hyvZTxJhSjBEeSx4wMjbnAf3b0uwTy2+F0zGjMZL4PQOm/mh2eGZ5xUDVZXgwP783Nsw==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/lang-html": "^6.0.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.0.0",+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.2.0",+ "@lezer/lr": "^1.4.0"+ }+ },+ "node_modules/@codemirror/lang-json": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz",+ "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0",+ "@lezer/json": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-less": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-less/-/lang-less-6.0.2.tgz",+ "integrity": "sha512-EYdQTG22V+KUUk8Qq582g7FMnCZeEHsyuOJisHRft/mQ+ZSZ2w51NupvDUHiqtsOy7It5cHLPGfHQLpMh9bqpQ==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/lang-css": "^6.2.0",+ "@codemirror/language": "^6.0.0",+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-liquid": {+ "version": "6.3.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-liquid/-/lang-liquid-6.3.2.tgz",+ "integrity": "sha512-6PDVU3ZnfeYyz1at1E/ttorErZvZFXXt1OPhtfe1EZJ2V2iDFa0CwPqPgG5F7NXN0yONGoBogKmFAafKTqlwIw==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/lang-html": "^6.0.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.0.0",+ "@lezer/common": "^1.0.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.3.1"+ }+ },+ "node_modules/@codemirror/lang-markdown": {+ "version": "6.5.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz",+ "integrity": "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.7.1",+ "@codemirror/lang-html": "^6.0.0",+ "@codemirror/language": "^6.3.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.0.0",+ "@lezer/common": "^1.2.1",+ "@lezer/markdown": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-php": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-php/-/lang-php-6.0.2.tgz",+ "integrity": "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/lang-html": "^6.0.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@lezer/common": "^1.0.0",+ "@lezer/php": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-python": {+ "version": "6.2.1",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz",+ "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.3.2",+ "@codemirror/language": "^6.8.0",+ "@codemirror/state": "^6.0.0",+ "@lezer/common": "^1.2.1",+ "@lezer/python": "^1.1.4"+ }+ },+ "node_modules/@codemirror/lang-rust": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-rust/-/lang-rust-6.0.2.tgz",+ "integrity": "sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0",+ "@lezer/rust": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-sass": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-sass/-/lang-sass-6.0.2.tgz",+ "integrity": "sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/lang-css": "^6.2.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@lezer/common": "^1.0.2",+ "@lezer/sass": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-sql": {+ "version": "6.10.0",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz",+ "integrity": "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-vue": {+ "version": "0.1.3",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-vue/-/lang-vue-0.1.3.tgz",+ "integrity": "sha512-QSKdtYTDRhEHCfo5zOShzxCmqKJvgGrZwDQSdbvCRJ5pRLWBS7pD/8e/tH44aVQT6FKm0t6RVNoSUWHOI5vNug==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/lang-html": "^6.0.0",+ "@codemirror/lang-javascript": "^6.1.2",+ "@codemirror/language": "^6.0.0",+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.3.1"+ }+ },+ "node_modules/@codemirror/lang-wast": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-wast/-/lang-wast-6.0.2.tgz",+ "integrity": "sha512-Imi2KTpVGm7TKuUkqyJ5NRmeFWF7aMpNiwHnLQe0x9kmrxElndyH0K6H/gXtWwY6UshMRAhpENsgfpSwsgmC6Q==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0",+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-xml": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz",+ "integrity": "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/language": "^6.4.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.0.0",+ "@lezer/common": "^1.0.0",+ "@lezer/xml": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-yaml": {+ "version": "6.1.3",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-yaml/-/lang-yaml-6.1.3.tgz",+ "integrity": "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.2.0",+ "@lezer/lr": "^1.0.0",+ "@lezer/yaml": "^1.0.0"+ }+ },"node_modules/@codemirror/language": {"version": "6.12.4","resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz",@@ -219,6 +520,46 @@"style-mod": "^4.0.0"}},+ "node_modules/@codemirror/language-data": {+ "version": "6.5.2",+ "resolved": "https://registry.npmjs.org/@codemirror/language-data/-/language-data-6.5.2.tgz",+ "integrity": "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/lang-angular": "^0.1.0",+ "@codemirror/lang-cpp": "^6.0.0",+ "@codemirror/lang-css": "^6.0.0",+ "@codemirror/lang-go": "^6.0.0",+ "@codemirror/lang-html": "^6.0.0",+ "@codemirror/lang-java": "^6.0.0",+ "@codemirror/lang-javascript": "^6.0.0",+ "@codemirror/lang-jinja": "^6.0.0",+ "@codemirror/lang-json": "^6.0.0",+ "@codemirror/lang-less": "^6.0.0",+ "@codemirror/lang-liquid": "^6.0.0",+ "@codemirror/lang-markdown": "^6.0.0",+ "@codemirror/lang-php": "^6.0.0",+ "@codemirror/lang-python": "^6.0.0",+ "@codemirror/lang-rust": "^6.0.0",+ "@codemirror/lang-sass": "^6.0.0",+ "@codemirror/lang-sql": "^6.0.0",+ "@codemirror/lang-vue": "^0.1.1",+ "@codemirror/lang-wast": "^6.0.0",+ "@codemirror/lang-xml": "^6.0.0",+ "@codemirror/lang-yaml": "^6.0.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/legacy-modes": "^6.4.0"+ }+ },+ "node_modules/@codemirror/legacy-modes": {+ "version": "6.5.3",+ "resolved": "https://registry.npmjs.org/@codemirror/legacy-modes/-/legacy-modes-6.5.3.tgz",+ "integrity": "sha512-xCsmIzH78MyWkib9jlPaaun57XNkfbMIhagfaZVd0iLTqlpw3jXaIcbZm72MTmmn64eTZpBVNjbyYh+QXnxRsg==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0"+ }+ },"node_modules/@codemirror/lint": {"version": "6.9.7","resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",@@ -1056,7 +1397,6 @@"version": "1.7.3","resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz","integrity": "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w==",- "dev": true,"license": "MIT","dependencies": {"@floating-ui/utils": "^0.2.10"@@ -1066,7 +1406,6 @@"version": "1.7.4","resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.4.tgz","integrity": "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA==",- "dev": true,"license": "MIT","dependencies": {"@floating-ui/core": "^1.7.3",@@ -1077,7 +1416,6 @@"version": "0.2.10","resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.10.tgz","integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==",- "dev": true,"license": "MIT"},"node_modules/@fontsource-variable/inter": {@@ -1220,6 +1558,39 @@"integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==","license": "MIT"},+ "node_modules/@lezer/cpp": {+ "version": "1.1.6",+ "resolved": "https://registry.npmjs.org/@lezer/cpp/-/cpp-1.1.6.tgz",+ "integrity": "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@lezer/css": {+ "version": "1.3.6",+ "resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.6.tgz",+ "integrity": "sha512-YJE78Wcg+zX8f10hiHWQ4Az48Qr/c13eId0VtRQYLBpxHDmDeSrXIlkbl+fJGW42rWC/uoUco9mhBZeVWP/A1g==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.3.0"+ }+ },+ "node_modules/@lezer/go": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@lezer/go/-/go-1.0.1.tgz",+ "integrity": "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.3.0"+ }+ },"node_modules/@lezer/highlight": {"version": "1.2.3","resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",@@ -1229,6 +1600,28 @@"@lezer/common": "^1.3.0"}},+ "node_modules/@lezer/html": {+ "version": "1.3.13",+ "resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",+ "integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@lezer/java": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@lezer/java/-/java-1.1.3.tgz",+ "integrity": "sha512-yHquUfujwg6Yu4Fd1GNHCvidIvJwi/1Xu2DaKl/pfWIA2c1oXkVvawH3NyXhCaFx4OdlYBVX5wvz2f7Aoa/4Xw==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },"node_modules/@lezer/javascript": {"version": "1.5.4","resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz",@@ -1240,6 +1633,17 @@"@lezer/lr": "^1.3.0"}},+ "node_modules/@lezer/json": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz",+ "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },"node_modules/@lezer/lr": {"version": "1.4.10","resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz",@@ -1249,30 +1653,501 @@"@lezer/common": "^1.0.0"}},- "node_modules/@lucide/svelte": {- "version": "0.561.0",- "resolved": "https://registry.npmjs.org/@lucide/svelte/-/svelte-0.561.0.tgz",- "integrity": "sha512-vofKV2UFVrKE6I4ewKJ3dfCXSV6iP6nWVmiM83MLjsU91EeJcEg7LoWUABLp/aOTxj1HQNbJD1f3g3L0JQgH9A==",- "dev": true,- "license": "ISC",- "peerDependencies": {- "svelte": "^5"+ "node_modules/@lezer/markdown": {+ "version": "1.7.2",+ "resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.7.2.tgz",+ "integrity": "sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.5.0",+ "@lezer/highlight": "^1.0.0"}},- "node_modules/@marijn/find-cluster-break": {- "version": "1.0.3",- "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz",- "integrity": "sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==",- "license": "MIT"- },- "node_modules/@polka/url": {- "version": "1.0.0-next.29",- "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",- "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==",- "dev": true,- "license": "MIT"+ "node_modules/@lezer/php": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/@lezer/php/-/php-1.0.5.tgz",+ "integrity": "sha512-W7asp9DhM6q0W6DYNwIkLSKOvxlXRrif+UXBMxzsJUuqmhE7oVU+gS3THO4S/Puh7Xzgm858UNaFi6dxTP8dJA==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.1.0"+ }},- "node_modules/@rollup/rollup-android-arm-eabi": {+ "node_modules/@lezer/python": {+ "version": "1.1.19",+ "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.19.tgz",+ "integrity": "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@lezer/rust": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@lezer/rust/-/rust-1.0.2.tgz",+ "integrity": "sha512-Lz5sIPBdF2FUXcWeCu1//ojFAZqzTQNRga0aYv6dYXqJqPfMdCAI0NzajWUd4Xijj1IKJLtjoXRPMvTKWBcqKg==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@lezer/sass": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@lezer/sass/-/sass-1.1.0.tgz",+ "integrity": "sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@lezer/xml": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@lezer/xml/-/xml-1.0.6.tgz",+ "integrity": "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@lezer/yaml": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/@lezer/yaml/-/yaml-1.0.4.tgz",+ "integrity": "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.4.0"+ }+ },+ "node_modules/@lucide/svelte": {+ "version": "0.561.0",+ "resolved": "https://registry.npmjs.org/@lucide/svelte/-/svelte-0.561.0.tgz",+ "integrity": "sha512-vofKV2UFVrKE6I4ewKJ3dfCXSV6iP6nWVmiM83MLjsU91EeJcEg7LoWUABLp/aOTxj1HQNbJD1f3g3L0JQgH9A==",+ "dev": true,+ "license": "ISC",+ "peerDependencies": {+ "svelte": "^5"+ }+ },+ "node_modules/@marijn/find-cluster-break": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz",+ "integrity": "sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==",+ "license": "MIT"+ },+ "node_modules/@milkdown/components": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/components/-/components-7.22.1.tgz",+ "integrity": "sha512-6IA8fcFcBTm/x1X1typz73yUoT1JuN4srmifGAIeWEtCnayEwRjFxpQOoQrfvMgBYx4DSHcPVLhJUlR/xbBtxg==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/dom": "^1.5.1",+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/exception": "7.22.1",+ "@milkdown/plugin-diff": "7.22.1",+ "@milkdown/plugin-tooltip": "7.22.1",+ "@milkdown/preset-commonmark": "7.22.1",+ "@milkdown/preset-gfm": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/transformer": "7.22.1",+ "@milkdown/utils": "7.22.1",+ "@types/lodash-es": "^4.17.12",+ "clsx": "^2.0.0",+ "dompurify": "^3.2.5",+ "lodash-es": "^4.17.21",+ "nanoid": "^6.0.0",+ "unist-util-visit": "^5.0.0",+ "vue": "^3.5.20"+ },+ "peerDependencies": {+ "@codemirror/language": "^6",+ "@codemirror/state": "^6",+ "@codemirror/view": "^6"+ }+ },+ "node_modules/@milkdown/components/node_modules/nanoid": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.1.tgz",+ "integrity": "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.js"+ },+ "engines": {+ "node": "^22 || ^24 || >=26"+ }+ },+ "node_modules/@milkdown/core": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/core/-/core-7.22.1.tgz",+ "integrity": "sha512-X4O3al2aYugpFP/Do7VoPgvVEftjJVi+6UhZmz9fSdqMtpU70AitJ8R/erUA18hay2hWvNO9m3pxIJoR6no6KQ==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/ctx": "7.22.1",+ "@milkdown/exception": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/transformer": "7.22.1",+ "remark-parse": "^11.0.0",+ "remark-stringify": "^11.0.0",+ "unified": "^11.0.3"+ }+ },+ "node_modules/@milkdown/crepe": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/crepe/-/crepe-7.22.1.tgz",+ "integrity": "sha512-0BZTGBRV8lnlKsA3vmPK5Qyomjqd952493AIzfnbhiYwzHpluX03iMtOgHC6E2UcpMXP86P5CXhPUWjzDu+JZQ==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/commands": "^6.2.4",+ "@codemirror/language": "^6.10.1",+ "@codemirror/language-data": "^6.3.1",+ "@codemirror/state": "^6.4.1",+ "@codemirror/theme-one-dark": "^6.1.2",+ "@codemirror/view": "^6.16.0",+ "@milkdown/kit": "7.22.1",+ "@types/lodash-es": "^4.17.12",+ "clsx": "^2.0.0",+ "codemirror": "^6.0.1",+ "dompurify": "^3.2.5",+ "katex": "^0.18.0",+ "lodash-es": "^4.17.21",+ "prosemirror-virtual-cursor": "^0.4.2",+ "remark-math": "^6.0.0",+ "unist-util-visit": "^5.0.0",+ "vue": "^3.5.20"+ }+ },+ "node_modules/@milkdown/ctx": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/ctx/-/ctx-7.22.1.tgz",+ "integrity": "sha512-6+LJdo3DcrkO1lzGcje0yWqaG6ZKgTR8kDxyDrrm7iocBjq3M+bkw04f99ZG/BLp1Rbc4yRyin2mUy6m4SEVaA==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/exception": "7.22.1"+ }+ },+ "node_modules/@milkdown/exception": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/exception/-/exception-7.22.1.tgz",+ "integrity": "sha512-wXUfn+fpWy0jeJ6AVEjKPieouLfJIDLQ4IRqyEL3d5yZDiZTtKu1Va0+RprrvqANpGJ1YBRQ1uCgDE6sJgTEjQ==",+ "license": "MIT"+ },+ "node_modules/@milkdown/kit": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/kit/-/kit-7.22.1.tgz",+ "integrity": "sha512-gXLMhjqe0j8XRSUe97LBXbpZ0sDi5EM6nnt1zXewUaGDS3mleMjNntSCWrp9ln40kz8tGs0ol50kSAr1n/JBnQ==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/components": "7.22.1",+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/exception": "7.22.1",+ "@milkdown/plugin-block": "7.22.1",+ "@milkdown/plugin-clipboard": "7.22.1",+ "@milkdown/plugin-cursor": "7.22.1",+ "@milkdown/plugin-diff": "7.22.1",+ "@milkdown/plugin-history": "7.22.1",+ "@milkdown/plugin-indent": "7.22.1",+ "@milkdown/plugin-listener": "7.22.1",+ "@milkdown/plugin-slash": "7.22.1",+ "@milkdown/plugin-streaming": "7.22.1",+ "@milkdown/plugin-tooltip": "7.22.1",+ "@milkdown/plugin-trailing": "7.22.1",+ "@milkdown/plugin-upload": "7.22.1",+ "@milkdown/preset-commonmark": "7.22.1",+ "@milkdown/preset-gfm": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/transformer": "7.22.1",+ "@milkdown/utils": "7.22.1"+ }+ },+ "node_modules/@milkdown/plugin-block": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-block/-/plugin-block-7.22.1.tgz",+ "integrity": "sha512-R0gOuKRqR1DyFULD75Oic0+57DXTthagUZbbB9lsHM59aQmxKJ1nRmujptPeMfDlDfEod2ao5rsow7LO8p+ZWQ==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/dom": "^1.5.1",+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1",+ "@types/lodash-es": "^4.17.12",+ "lodash-es": "^4.17.21"+ }+ },+ "node_modules/@milkdown/plugin-clipboard": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-clipboard/-/plugin-clipboard-7.22.1.tgz",+ "integrity": "sha512-H1meyLEj2fOnFWSopeQ2H7hl6VXM+OQZoU9H7GrlHFM5GKtBFBErFFV4Cl5tUSVFY+xYy/4rEPOA23Ba1u6OfA==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1"+ }+ },+ "node_modules/@milkdown/plugin-cursor": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-cursor/-/plugin-cursor-7.22.1.tgz",+ "integrity": "sha512-3tJzpQl5cyn+8vzsHkPBYsW6QacEN7yP2O5GkyUjrNLvMIQ5vVi7GUuztLeoouJKlOc1vjIq3h7ARXCgHAKe8g==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1",+ "prosemirror-drop-indicator": "^0.1.0"+ }+ },+ "node_modules/@milkdown/plugin-diff": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-diff/-/plugin-diff-7.22.1.tgz",+ "integrity": "sha512-qjuCMx11HwhMlTJuybqbFZT8PQkasSi0qICxq2HdYqH0WQuLO99I2mb17UAJz1aF+JM9rp1StHWr4bxC0ofamA==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/transformer": "7.22.1",+ "@milkdown/utils": "7.22.1"+ }+ },+ "node_modules/@milkdown/plugin-history": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-history/-/plugin-history-7.22.1.tgz",+ "integrity": "sha512-SRD6emVhfVmA6mrcCsCiWrONN/2Kp+VT5LLojIQxNc/spzjWw15PtkA3r4nUe9cZmNN5rE7XvrPaA0WnjJIyeQ==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1"+ }+ },+ "node_modules/@milkdown/plugin-indent": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-indent/-/plugin-indent-7.22.1.tgz",+ "integrity": "sha512-s/wmqxaJpIKT01gEXsC9gCkzA3Clm+MNioZLzNCYD8xI/4Hf3AhmIEoEqf3LIQ9w10Zs2yhIxIrknNWfCOgsEw==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1"+ }+ },+ "node_modules/@milkdown/plugin-listener": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-listener/-/plugin-listener-7.22.1.tgz",+ "integrity": "sha512-6k8JMDrdAL0E0WygpDX1YOR0Q9Wc4pia8pIMN5nN5liEeAyNaM6LwAxXJY+awQJ0OstDKHTfjkh7WzJo4QiXOA==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@types/lodash-es": "^4.17.12",+ "lodash-es": "^4.17.21"+ }+ },+ "node_modules/@milkdown/plugin-slash": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-slash/-/plugin-slash-7.22.1.tgz",+ "integrity": "sha512-eFKCjfgXfAQusTSOyzhz4nASquOApdiBy9hnGkPB/SJ6oltTC8SonB3nIxF/X0wPZHfn09vuz/JBqh9cyDtXJA==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/dom": "^1.5.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1",+ "@types/lodash-es": "^4.17.12",+ "lodash-es": "^4.17.21"+ }+ },+ "node_modules/@milkdown/plugin-streaming": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-streaming/-/plugin-streaming-7.22.1.tgz",+ "integrity": "sha512-CR0lujyc7ae0sbjNfscvS+b+cUP7b6XJ90ioTor605UV+F8EKh5t4PMJM79IVzSUCeob51a+rtXA2LAA1b/GyA==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/plugin-diff": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1"+ }+ },+ "node_modules/@milkdown/plugin-tooltip": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-tooltip/-/plugin-tooltip-7.22.1.tgz",+ "integrity": "sha512-drdWA/7WlrDr2B+ABYf4tY9xTiwg/CJMUCydfD05dR2d8wOkaF6oOHZwJbWnkWLMtAJWdieOYgfXGPhQRwXxCg==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/dom": "^1.5.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1",+ "@types/lodash-es": "^4.17.12",+ "lodash-es": "^4.17.21"+ }+ },+ "node_modules/@milkdown/plugin-trailing": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-trailing/-/plugin-trailing-7.22.1.tgz",+ "integrity": "sha512-Buy8IX3I7wwq0QPfJRep77QnvlkBeg6BvDHkbh5eTMrgnwSiWhN+tV9RVCYpdWXM7QhQZpSjU2SejluLuTyVCg==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/ctx": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1"+ }+ },+ "node_modules/@milkdown/plugin-upload": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/plugin-upload/-/plugin-upload-7.22.1.tgz",+ "integrity": "sha512-vV0bZzdh/PhM+Jk9Nk5cKHDXHY5jt+ePcaitTfvESDYfg83YZ9AglOhw/YclPWklMvswrnCGZZFTZD4daqc4hg==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/exception": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/utils": "7.22.1"+ }+ },+ "node_modules/@milkdown/preset-commonmark": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/preset-commonmark/-/preset-commonmark-7.22.1.tgz",+ "integrity": "sha512-it+G0YUG5MDXt0qLB6W083ss5i6tnWAXWCW8SgnmsehGxntkN5//gNM/8vh3rqwl8RvnBvjLWpJ6TgHSlBPhlw==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/exception": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/transformer": "7.22.1",+ "@milkdown/utils": "7.22.1",+ "remark-inline-links": "^7.0.0",+ "unist-util-visit": "^5.0.0",+ "unist-util-visit-parents": "^6.0.1"+ }+ },+ "node_modules/@milkdown/preset-gfm": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/preset-gfm/-/preset-gfm-7.22.1.tgz",+ "integrity": "sha512-UPMdHRdMHlVourOOTiwsp3qHu614pDFWlWtVzxe8fyl8uKZUk6IOuewH5ubhqD/opos8OEB+zgEomUGfee1oTw==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/exception": "7.22.1",+ "@milkdown/preset-commonmark": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/transformer": "7.22.1",+ "@milkdown/utils": "7.22.1",+ "prosemirror-safari-ime-span": "^1.0.1",+ "remark-gfm": "^4.0.1"+ }+ },+ "node_modules/@milkdown/prose": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/prose/-/prose-7.22.1.tgz",+ "integrity": "sha512-fqgTHl94G7oDPY94cPYBm6ARxEoLQ10ubkTNLD1nzAlTUfJLULZkIEMSMy4CECncw2go3ExW32CZPpXLJVSxnQ==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/exception": "7.22.1",+ "prosemirror-changeset": "^2.3.1",+ "prosemirror-commands": "^1.7.1",+ "prosemirror-dropcursor": "^1.8.2",+ "prosemirror-gapcursor": "^1.4.0",+ "prosemirror-history": "^1.5.0",+ "prosemirror-inputrules": "^1.5.1",+ "prosemirror-keymap": "^1.2.3",+ "prosemirror-model": "^1.25.4",+ "prosemirror-schema-list": "^1.5.1",+ "prosemirror-state": "^1.4.4",+ "prosemirror-tables": "^1.8.1",+ "prosemirror-transform": "^1.10.5",+ "prosemirror-view": "^1.41.3"+ }+ },+ "node_modules/@milkdown/transformer": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/transformer/-/transformer-7.22.1.tgz",+ "integrity": "sha512-rU1IBtxezNg7TSWaq+RP59/t6tfD3jIPGrwAtMKPIGuYEax+8d1fyGisp98TeI3l0VQEIgMpF+KlNDV+Y1HJVA==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/exception": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "remark": "^15.0.1",+ "unified": "^11.0.3"+ }+ },+ "node_modules/@milkdown/utils": {+ "version": "7.22.1",+ "resolved": "https://registry.npmjs.org/@milkdown/utils/-/utils-7.22.1.tgz",+ "integrity": "sha512-ye0LGy/Ez8fjtcYyYj93wp4XfH00JYpCiy1IDHYB+9HVIpnbr3ed7PvY4s2000xmDWe0Vlx07TOyv96yvFrnjQ==",+ "license": "MIT",+ "dependencies": {+ "@milkdown/core": "7.22.1",+ "@milkdown/ctx": "7.22.1",+ "@milkdown/exception": "7.22.1",+ "@milkdown/prose": "7.22.1",+ "@milkdown/transformer": "7.22.1",+ "nanoid": "^6.0.0"+ }+ },+ "node_modules/@milkdown/utils/node_modules/nanoid": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.1.tgz",+ "integrity": "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.js"+ },+ "engines": {+ "node": "^22 || ^24 || >=26"+ }+ },+ "node_modules/@ocavue/utils": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/@ocavue/utils/-/utils-1.7.0.tgz",+ "integrity": "sha512-yEk9ATNBjTZTtuVFMB/MAIF6zJBvJ2+lVNQvK2+O+ggEBGTgx2tp27d4FPgmD5bRsNHHP3D0SleQia/bvIeV8w==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ocavue"+ }+ },+ "node_modules/@polka/url": {+ "version": "1.0.0-next.29",+ "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",+ "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@rollup/rollup-android-arm-eabi": {"version": "4.54.0","resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.54.0.tgz","integrity": "sha512-OywsdRHrFvCdvsewAInDKCNyR3laPA2mc9bRYJ6LBp5IyvF3fvXbbNR0bSzHlZVFtn6E0xw2oZlyjg4rKCVcng==",@@ -2267,6 +3142,15 @@"dev": true,"license": "MIT"},+ "node_modules/@types/debug": {+ "version": "4.1.13",+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",+ "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",+ "license": "MIT",+ "dependencies": {+ "@types/ms": "*"+ }+ },"node_modules/@types/deep-eql": {"version": "4.0.2","resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",@@ -2280,6 +3164,15 @@"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==","license": "MIT"},+ "node_modules/@types/hast": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz",+ "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },"node_modules/@types/json-schema": {"version": "7.0.15","resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",@@ -2287,6 +3180,27 @@"dev": true,"license": "MIT"},+ "node_modules/@types/katex": {+ "version": "0.16.8",+ "resolved": "https://registry.npmjs.org/@types/katex/-/katex-0.16.8.tgz",+ "integrity": "sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==",+ "license": "MIT"+ },+ "node_modules/@types/lodash": {+ "version": "4.17.25",+ "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.25.tgz",+ "integrity": "sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ==",+ "license": "MIT"+ },+ "node_modules/@types/lodash-es": {+ "version": "4.17.12",+ "resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz",+ "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==",+ "license": "MIT",+ "dependencies": {+ "@types/lodash": "*"+ }+ },"node_modules/@types/luxon": {"version": "3.7.1","resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.7.1.tgz",@@ -2294,6 +3208,21 @@"dev": true,"license": "MIT"},+ "node_modules/@types/mdast": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },+ "node_modules/@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",+ "license": "MIT"+ },"node_modules/@types/node": {"version": "22.19.3","resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.3.tgz",@@ -2304,6 +3233,19 @@"undici-types": "~6.21.0"}},+ "node_modules/@types/trusted-types": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/@types/unist": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",+ "license": "MIT"+ },"node_modules/@typescript-eslint/eslint-plugin": {"version": "8.51.0","resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.51.0.tgz",@@ -2673,42 +3615,164 @@"url": "https://opencollective.com/vitest"}},- "node_modules/@xstate/fsm": {- "version": "1.6.5",- "resolved": "https://registry.npmjs.org/@xstate/fsm/-/fsm-1.6.5.tgz",- "integrity": "sha512-b5o1I6aLNeYlU/3CPlj/Z91ybk1gUsKT+5NAJI+2W4UjvS5KLG28K9v5UvNoFVjHV8PajVZ00RH3vnjyQO7ZAw==",+ "node_modules/@vue/compiler-core": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.41.tgz",+ "integrity": "sha512-q0Xtv/F9w2YO/7htQhtiL+Ev2WCJbe5N2hc+XfgyKkEKqWpSxknmT8QOuGdEKNdjPq0c3F7rNpFkTo3Kfrm7pg==",+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.29.8",+ "@vue/shared": "3.5.41",+ "entities": "^7.0.1",+ "estree-walker": "^2.0.2",+ "source-map-js": "^1.2.1"+ }+ },+ "node_modules/@vue/compiler-core/node_modules/entities": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },+ "node_modules/@vue/compiler-core/node_modules/estree-walker": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==","license": "MIT"},- "node_modules/acorn": {- "version": "8.15.0",- "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",- "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",+ "node_modules/@vue/compiler-dom": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.41.tgz",+ "integrity": "sha512-oKacVfNglLvGjnS6BXOlGL7EyG2h8X03pqXCjzotRZUaXGjbrTJUnVAQjrCqUnS+lyu31nwQjZY/d817GmCnfw==","license": "MIT",- "bin": {- "acorn": "bin/acorn"- },- "engines": {- "node": ">=0.4.0"+ "dependencies": {+ "@vue/compiler-core": "3.5.41",+ "@vue/shared": "3.5.41"}},- "node_modules/acorn-jsx": {- "version": "5.3.2",- "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",- "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",- "dev": true,+ "node_modules/@vue/compiler-sfc": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.41.tgz",+ "integrity": "sha512-XJhip7R2wy6vX3knCxdZN4KracFaZUef58s1KYewqluedHIJaPIVfXoYT7MF1F8nCvv6k8bWWxDC8opMkg1VTQ==","license": "MIT",- "peerDependencies": {- "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"+ "dependencies": {+ "@babel/parser": "^7.29.8",+ "@vue/compiler-core": "3.5.41",+ "@vue/compiler-dom": "3.5.41",+ "@vue/compiler-ssr": "3.5.41",+ "@vue/shared": "3.5.41",+ "estree-walker": "^2.0.2",+ "magic-string": "^0.30.21",+ "postcss": "^8.5.19",+ "source-map-js": "^1.2.1"}},- "node_modules/ajv": {- "version": "6.12.6",- "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",- "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",- "dev": true,+ "node_modules/@vue/compiler-sfc/node_modules/estree-walker": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",+ "license": "MIT"+ },+ "node_modules/@vue/compiler-ssr": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.41.tgz",+ "integrity": "sha512-U3v5OejKEGqOI0Wy0+Sz7hGuIFZHA4LSXzrNM3IMIeDyJEBBfTpX26n3SDgToRpP2bLc9FfI2j/kSgcJ8Emq5A==","license": "MIT","dependencies": {- "fast-deep-equal": "^3.1.1",+ "@vue/compiler-dom": "3.5.41",+ "@vue/shared": "3.5.41"+ }+ },+ "node_modules/@vue/reactivity": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.41.tgz",+ "integrity": "sha512-rznsqKM0np0x18EjzF8x88MpEhdNsffbvFbckLL5+oUKz1BxAImEmO7J1ArRYSyo6aQaVoBDp7jEkT91OOxydA==",+ "license": "MIT",+ "dependencies": {+ "@vue/shared": "3.5.41"+ }+ },+ "node_modules/@vue/runtime-core": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.41.tgz",+ "integrity": "sha512-Vcry58hiAKwGen9Z1jUZE0feFsNArPCMOImYI8el48A9Idf6DuQYD0U05zZIF2Iad1hGhPSvcbBbAOhNr55fhg==",+ "license": "MIT",+ "dependencies": {+ "@vue/reactivity": "3.5.41",+ "@vue/shared": "3.5.41"+ }+ },+ "node_modules/@vue/runtime-dom": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.41.tgz",+ "integrity": "sha512-3vVBahVBS9+U6cmXBLyb8nE6/yYo4J/CGI9eVFs3KiMc0YHuudwKyShTD65jtJy/L9PUUxNAFu4cj4LiJ0UFbw==",+ "license": "MIT",+ "dependencies": {+ "@vue/reactivity": "3.5.41",+ "@vue/runtime-core": "3.5.41",+ "@vue/shared": "3.5.41",+ "csstype": "^3.2.3"+ }+ },+ "node_modules/@vue/server-renderer": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.41.tgz",+ "integrity": "sha512-n6hx/pNFfbD6SuyeuMVkvqox8bwf/ET9JlA/kAz/imw8sw++wkqKe2mHX5KutjPpbKE4Z56yTHszoOjGMI9igQ==",+ "license": "MIT",+ "dependencies": {+ "@vue/compiler-ssr": "3.5.41",+ "@vue/runtime-dom": "3.5.41",+ "@vue/shared": "3.5.41"+ }+ },+ "node_modules/@vue/shared": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.41.tgz",+ "integrity": "sha512-IOnwSCma8j+9xJT6b8H0dEYidC80NsYmNMlZxRsukYcSoGaDBohog5hDxzeUXdFeGWFA++vWvxqOmrr96VlqMA==",+ "license": "MIT"+ },+ "node_modules/@xstate/fsm": {+ "version": "1.6.5",+ "resolved": "https://registry.npmjs.org/@xstate/fsm/-/fsm-1.6.5.tgz",+ "integrity": "sha512-b5o1I6aLNeYlU/3CPlj/Z91ybk1gUsKT+5NAJI+2W4UjvS5KLG28K9v5UvNoFVjHV8PajVZ00RH3vnjyQO7ZAw==",+ "license": "MIT"+ },+ "node_modules/acorn": {+ "version": "8.15.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",+ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",+ "license": "MIT",+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-jsx": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",+ "dev": true,+ "license": "MIT",+ "peerDependencies": {+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },+ "node_modules/ajv": {+ "version": "6.12.6",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.1","fast-json-stable-stringify": "^2.0.0","json-schema-traverse": "^0.4.1","uri-js": "^4.2.2"@@ -2779,6 +3843,16 @@"node": ">= 0.4"}},+ "node_modules/bail": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/balanced-match": {"version": "1.0.2","resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",@@ -2851,6 +3925,16 @@"node": ">=6"}},+ "node_modules/ccount": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/chai": {"version": "6.2.2","resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",@@ -2878,6 +3962,16 @@"url": "https://github.com/chalk/chalk?sponsor=1"}},+ "node_modules/character-entities": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/chokidar": {"version": "4.0.3","resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",@@ -2961,6 +4055,15 @@"dev": true,"license": "MIT"},+ "node_modules/commander": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",+ "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },"node_modules/concat-map": {"version": "0.0.1","resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",@@ -3033,6 +4136,12 @@"node": ">=4"}},+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",+ "license": "MIT"+ },"node_modules/d3-array": {"version": "3.2.4","resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",@@ -3236,7 +4345,6 @@"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz","integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",- "dev": true,"license": "MIT","dependencies": {"ms": "^2.1.3"@@ -3257,6 +4365,19 @@"dev": true,"license": "MIT"},+ "node_modules/decode-named-character-reference": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",+ "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",+ "license": "MIT",+ "dependencies": {+ "character-entities": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/deep-is": {"version": "0.1.4","resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",@@ -3278,7 +4399,6 @@"version": "2.0.3","resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz","integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",- "dev": true,"license": "MIT","engines": {"node": ">=6"@@ -3300,6 +4420,28 @@"integrity": "sha512-jDwizj+IlEZBunHcOuuFVBnIMPAEHvTsJj0BcIp94xYguLRVBcXO853px/MyIJvbVzWdsGvrRweIUWJw8hBP7A==","license": "MIT"},+ "node_modules/devlop": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",+ "license": "MIT",+ "dependencies": {+ "dequal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/dompurify": {+ "version": "3.4.13",+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.13.tgz",+ "integrity": "sha512-2vmYIoqjze2d+kakP8S/nS5shfsl587kzwEjcGlTdiksUVgFHnFCsLYDVj/JNqJVOQZGSYBTmuycv0PodwmnMQ==",+ "license": "(MPL-2.0 OR Apache-2.0)",+ "optionalDependencies": {+ "@types/trusted-types": "^2.0.7"+ }+ },"node_modules/enhanced-resolve": {"version": "5.18.4","resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.18.4.tgz",@@ -3628,6 +4770,12 @@"node": ">=12.0.0"}},+ "node_modules/extend": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",+ "license": "MIT"+ },"node_modules/fast-deep-equal": {"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",@@ -3880,6 +5028,18 @@"node": ">=0.10.0"}},+ "node_modules/is-plain-obj": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/is-potential-custom-element-name": {"version": "1.0.1","resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",@@ -3995,6 +5155,22 @@"dev": true,"license": "MIT"},+ "node_modules/katex": {+ "version": "0.18.4",+ "resolved": "https://registry.npmjs.org/katex/-/katex-0.18.4.tgz",+ "integrity": "sha512-IMPntbRLOU+eu88XDiFKqQ8Akhr9Tv7jDMXqPhjG9SI1JMA4DIgXk4x9k4skJz2NZJXBRbC+2pYBLj9olqcZow==",+ "funding": [+ "https://opencollective.com/katex",+ "https://github.com/sponsors/katex"+ ],+ "license": "MIT",+ "dependencies": {+ "commander": "^8.3.0"+ },+ "bin": {+ "katex": "cli.js"+ }+ },"node_modules/keyv": {"version": "4.5.4","resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",@@ -4329,6 +5505,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/lodash-es": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz",+ "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==",+ "license": "MIT"+ },"node_modules/lodash.merge": {"version": "4.6.2","resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",@@ -4336,6 +5518,16 @@"dev": true,"license": "MIT"},+ "node_modules/longest-streak": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/lru-cache": {"version": "11.5.1","resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz",@@ -4346,15 +5538,6 @@"node": "20 || >=22"}},- "node_modules/lucide-svelte": {- "version": "0.562.0",- "resolved": "https://registry.npmjs.org/lucide-svelte/-/lucide-svelte-0.562.0.tgz",- "integrity": "sha512-kSJDH/55lf0mun/o4nqWBXOcq0fWYzPeIjbTD97ywoeumAB9kWxtM06gC7oynqjtK3XhAljWSz5RafIzPEYIQA==",- "license": "ISC",- "peerDependencies": {- "svelte": "^3 || ^4 || ^5.0.0-next.42"- }- },"node_modules/luxon": {"version": "3.7.2","resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz",@@ -4370,25 +5553,868 @@"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==","dev": true,"license": "MIT",- "bin": {- "lz-string": "bin/bin.js"+ "bin": {+ "lz-string": "bin/bin.js"+ }+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/markdown-table": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/mdast-util-definitions": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-definitions/-/mdast-util-definitions-6.0.0.tgz",+ "integrity": "sha512-scTllyX6pnYNZH/AIp/0ePz6s4cZtARxImwoPJ7kS42n+MnVsI4XbnG6d4ibehRIldYMWM2LD7ImQblVhUejVQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "unist-util-visit": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-find-and-replace": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",+ "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "escape-string-regexp": "^5.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mdast-util-from-markdown": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz",+ "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark": "^4.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",+ "license": "MIT",+ "dependencies": {+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-gfm-autolink-literal": "^2.0.0",+ "mdast-util-gfm-footnote": "^2.0.0",+ "mdast-util-gfm-strikethrough": "^2.0.0",+ "mdast-util-gfm-table": "^2.0.0",+ "mdast-util-gfm-task-list-item": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-autolink-literal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "ccount": "^2.0.0",+ "devlop": "^1.0.0",+ "mdast-util-find-and-replace": "^3.0.0",+ "micromark-util-character": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.1.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-strikethrough": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz",+ "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-table": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "markdown-table": "^3.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-task-list-item": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-math": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-math/-/mdast-util-math-3.0.0.tgz",+ "integrity": "sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "longest-streak": "^3.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.1.0",+ "unist-util-remove-position": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-phrasing": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-markdown": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz",+ "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "longest-streak": "^3.0.0",+ "mdast-util-phrasing": "^4.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "unist-util-visit": "^5.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-string": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdn-data": {+ "version": "2.27.1",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",+ "dev": true,+ "license": "CC0-1.0"+ },+ "node_modules/micromark": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",+ "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/debug": "^4.0.0",+ "debug": "^4.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-core-commonmark": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz",+ "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-factory-destination": "^2.0.0",+ "micromark-factory-label": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-factory-title": "^2.0.0",+ "micromark-factory-whitespace": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-html-tag-name": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-extension-gfm": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",+ "license": "MIT",+ "dependencies": {+ "micromark-extension-gfm-autolink-literal": "^2.0.0",+ "micromark-extension-gfm-footnote": "^2.0.0",+ "micromark-extension-gfm-strikethrough": "^2.0.0",+ "micromark-extension-gfm-table": "^2.0.0",+ "micromark-extension-gfm-tagfilter": "^2.0.0",+ "micromark-extension-gfm-task-list-item": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-autolink-literal": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-strikethrough": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-table": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz",+ "integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-tagfilter": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-task-list-item": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-math": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-math/-/micromark-extension-math-3.1.0.tgz",+ "integrity": "sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg==",+ "license": "MIT",+ "dependencies": {+ "@types/katex": "^0.16.0",+ "devlop": "^1.0.0",+ "katex": "^0.16.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-math/node_modules/katex": {+ "version": "0.16.47",+ "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.47.tgz",+ "integrity": "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==",+ "funding": [+ "https://opencollective.com/katex",+ "https://github.com/sponsors/katex"+ ],+ "license": "MIT",+ "dependencies": {+ "commander": "^8.3.0"+ },+ "bin": {+ "katex": "cli.js"+ }+ },+ "node_modules/micromark-factory-destination": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-label": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-space": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz",+ "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-title": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-whitespace": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-character": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-chunked": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-classify-character": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-combine-extensions": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-numeric-character-reference": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-string": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-encode": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-html-tag-name": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-normalize-identifier": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-resolve-all": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-sanitize-uri": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"}},- "node_modules/magic-string": {- "version": "0.30.21",- "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",- "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "node_modules/micromark-util-subtokenize": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],"license": "MIT","dependencies": {- "@jridgewell/sourcemap-codec": "^1.5.5"+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"}},- "node_modules/mdn-data": {- "version": "2.27.1",- "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",- "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",- "dev": true,- "license": "CC0-1.0"+ "node_modules/micromark-util-symbol": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-types": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",+ "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"},"node_modules/minimatch": {"version": "3.1.2",@@ -4433,13 +6459,12 @@"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz","integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",- "dev": true,"license": "MIT"},"node_modules/nanoid": {- "version": "3.3.11",- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",- "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",+ "version": "3.3.18",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",+ "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==","funding": [{"type": "github",@@ -4493,6 +6518,12 @@"node": ">= 0.8.0"}},+ "node_modules/orderedmap": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz",+ "integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==",+ "license": "MIT"+ },"node_modules/p-limit": {"version": "3.1.0","resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",@@ -4598,9 +6629,9 @@}},"node_modules/postcss": {- "version": "8.5.6",- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",- "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",+ "version": "8.5.26",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",+ "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==","funding": [{"type": "opencollective",@@ -4617,7 +6648,7 @@],"license": "MIT","dependencies": {- "nanoid": "^3.3.11",+ "nanoid": "^3.3.17","picocolors": "^1.1.1","source-map-js": "^1.2.1"},@@ -4877,6 +6908,198 @@"url": "https://github.com/chalk/ansi-styles?sponsor=1"}},+ "node_modules/prosemirror-changeset": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/prosemirror-changeset/-/prosemirror-changeset-2.4.1.tgz",+ "integrity": "sha512-96WBLhOaYhJ+kPhLg3uW359Tz6I/MfcrQfL4EGv4SrcqKEMC1gmoGrXHecPE8eOwTVCJ4IwgfzM8fFad25wNfw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-transform": "^1.0.0"+ }+ },+ "node_modules/prosemirror-commands": {+ "version": "1.7.2",+ "resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.2.tgz",+ "integrity": "sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.0.0",+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.10.2"+ }+ },+ "node_modules/prosemirror-drop-indicator": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/prosemirror-drop-indicator/-/prosemirror-drop-indicator-0.1.4.tgz",+ "integrity": "sha512-YaRB1pZmU5GCorPVWbc9dbhbwqr4iMBO/AjPu4BTKHCUzxEDUXje2dUyoxOHib/z4uyPUZTJz64h7mHDJZeSzA==",+ "license": "MIT",+ "dependencies": {+ "@ocavue/utils": "^1.6.0",+ "prosemirror-model": "^1.25.7",+ "prosemirror-state": "^1.4.4",+ "prosemirror-view": "^1.41.8"+ },+ "funding": {+ "url": "https://github.com/sponsors/ocavue"+ }+ },+ "node_modules/prosemirror-dropcursor": {+ "version": "1.8.3",+ "resolved": "https://registry.npmjs.org/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.3.tgz",+ "integrity": "sha512-FoYbsJR8gK+DGlqhNoE29Loa38eIZPzQRIb1VMaDNBoo4OLP6vVof/jR8qFY/6XvUd6Dhug8MDCHl2a/h8RTfQ==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.1.0",+ "prosemirror-view": "^1.1.0"+ }+ },+ "node_modules/prosemirror-gapcursor": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/prosemirror-gapcursor/-/prosemirror-gapcursor-1.4.1.tgz",+ "integrity": "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-keymap": "^1.0.0",+ "prosemirror-model": "^1.0.0",+ "prosemirror-state": "^1.0.0",+ "prosemirror-view": "^1.0.0"+ }+ },+ "node_modules/prosemirror-history": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/prosemirror-history/-/prosemirror-history-1.5.0.tgz",+ "integrity": "sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.2.2",+ "prosemirror-transform": "^1.0.0",+ "prosemirror-view": "^1.31.0",+ "rope-sequence": "^1.3.0"+ }+ },+ "node_modules/prosemirror-inputrules": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.5.1.tgz",+ "integrity": "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.0.0"+ }+ },+ "node_modules/prosemirror-keymap": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz",+ "integrity": "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.0.0",+ "w3c-keyname": "^2.2.0"+ }+ },+ "node_modules/prosemirror-model": {+ "version": "1.25.11",+ "resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.11.tgz",+ "integrity": "sha512-QWg9RhnpLlogAmp3p96uEFrE5txQpFynd4vhBAELkwgOCWQs/X0yCzB3/hrHqiPwf91RG5KyWq6553zs9JqIOQ==",+ "license": "MIT",+ "dependencies": {+ "orderedmap": "^2.0.0"+ }+ },+ "node_modules/prosemirror-safari-ime-span": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/prosemirror-safari-ime-span/-/prosemirror-safari-ime-span-1.0.2.tgz",+ "integrity": "sha512-QJqD8s1zE/CuK56kDsUhndh5hiHh/gFnAuPOA9ytva2s85/ZEt2tNWeALTJN48DtWghSKOmiBsvVn2OlnJ5H2w==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.4.3",+ "prosemirror-view": "^1.33.8"+ },+ "funding": {+ "url": "https://github.com/sponsors/ocavue"+ }+ },+ "node_modules/prosemirror-schema-list": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz",+ "integrity": "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.0.0",+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.7.3"+ }+ },+ "node_modules/prosemirror-state": {+ "version": "1.4.4",+ "resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz",+ "integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.0.0",+ "prosemirror-transform": "^1.0.0",+ "prosemirror-view": "^1.27.0"+ }+ },+ "node_modules/prosemirror-tables": {+ "version": "1.8.5",+ "resolved": "https://registry.npmjs.org/prosemirror-tables/-/prosemirror-tables-1.8.5.tgz",+ "integrity": "sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-keymap": "^1.2.3",+ "prosemirror-model": "^1.25.4",+ "prosemirror-state": "^1.4.4",+ "prosemirror-transform": "^1.10.5",+ "prosemirror-view": "^1.41.4"+ }+ },+ "node_modules/prosemirror-transform": {+ "version": "1.12.0",+ "resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.0.tgz",+ "integrity": "sha512-GxboyN4AMIsoHNtz5uf2r2Ru551i5hWeCMD6E2Ib4Eogqoub0NflniaBPVQ4MrGE5yZ8JV9tUHg9qcZTTrcN4w==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.21.0"+ }+ },+ "node_modules/prosemirror-view": {+ "version": "1.42.2",+ "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.2.tgz",+ "integrity": "sha512-Pdg0l5kXm8aLDquFAnQFTCITg0q44sLqBlHlpsVLD9segdOao8TOfQdAhCrCXyVgPSRr6UDDROOIWA3bIrN9YQ==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.25.8",+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.1.0"+ }+ },+ "node_modules/prosemirror-virtual-cursor": {+ "version": "0.4.2",+ "resolved": "https://registry.npmjs.org/prosemirror-virtual-cursor/-/prosemirror-virtual-cursor-0.4.2.tgz",+ "integrity": "sha512-pUMKnIuOhhnMcgIJUjhIQTVJruBEGxfMBVQSrK0g2qhGPDm1i12KdsVaFw15dYk+29tZcxjMeR7P5VDKwmbwJg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ocavue"+ },+ "peerDependencies": {+ "prosemirror-model": "^1.0.0",+ "prosemirror-state": "^1.0.0",+ "prosemirror-view": "^1.0.0"+ },+ "peerDependenciesMeta": {+ "prosemirror-model": {+ "optional": true+ },+ "prosemirror-state": {+ "optional": true+ },+ "prosemirror-view": {+ "optional": true+ }+ }+ },"node_modules/punycode": {"version": "2.3.1","resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",@@ -4908,6 +7131,102 @@"url": "https://paulmillr.com/funding/"}},+ "node_modules/remark": {+ "version": "15.0.1",+ "resolved": "https://registry.npmjs.org/remark/-/remark-15.0.1.tgz",+ "integrity": "sha512-Eht5w30ruCXgFmxVUSlNWQ9iiimq07URKeFS3hNc8cUWy1llX4KDWfyEDZRycMc+znsN9Ux5/tJ/BFdgdOwA3A==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "remark-parse": "^11.0.0",+ "remark-stringify": "^11.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-gfm": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-gfm": "^3.0.0",+ "micromark-extension-gfm": "^3.0.0",+ "remark-parse": "^11.0.0",+ "remark-stringify": "^11.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-inline-links": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/remark-inline-links/-/remark-inline-links-7.0.0.tgz",+ "integrity": "sha512-4uj1pPM+F495ySZhTIB6ay2oSkTsKgmYaKk/q5HIdhX2fuyLEegpjWa0VdJRJ01sgOqAFo7MBKdDUejIYBMVMQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-definitions": "^6.0.0",+ "unist-util-visit": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-math": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/remark-math/-/remark-math-6.0.0.tgz",+ "integrity": "sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-math": "^3.0.0",+ "micromark-extension-math": "^3.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-parse": {+ "version": "11.0.0",+ "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-stringify": {+ "version": "11.0.0",+ "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz",+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/require-from-string": {"version": "2.0.2","resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",@@ -4970,6 +7289,12 @@"fsevents": "~2.3.2"}},+ "node_modules/rope-sequence": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz",+ "integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==",+ "license": "MIT"+ },"node_modules/rrdom": {"version": "2.0.0-alpha.20","resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.0.0-alpha.20.tgz",@@ -5500,6 +7825,16 @@"node": ">=20"}},+ "node_modules/trough": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz",+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/ts-api-utils": {"version": "2.3.0","resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.3.0.tgz",@@ -5547,7 +7882,7 @@"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz","integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",- "dev": true,+ "devOptional": true,"license": "Apache-2.0","bin": {"tsc": "bin/tsc",@@ -5598,6 +7933,94 @@"dev": true,"license": "MIT"},+ "node_modules/unified": {+ "version": "11.0.5",+ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "bail": "^2.0.0",+ "devlop": "^1.0.0",+ "extend": "^3.0.0",+ "is-plain-obj": "^4.0.0",+ "trough": "^2.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-is": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-remove-position": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-remove-position/-/unist-util-remove-position-5.0.0.tgz",+ "integrity": "sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-visit": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-stringify-position": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz",+ "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit-parents": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/uri-js": {"version": "4.4.1","resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",@@ -5615,6 +8038,34 @@"dev": true,"license": "MIT"},+ "node_modules/vfile": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vfile-message": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/vite": {"version": "7.3.0","resolved": "https://registry.npmjs.org/vite/-/vite-7.3.0.tgz",@@ -5800,6 +8251,27 @@}}},+ "node_modules/vue": {+ "version": "3.5.41",+ "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.41.tgz",+ "integrity": "sha512-2laE0p+aK+/AOPG/XL/WepOs/GlK755LJ1XECi9kDUrz1FKNw8rb2Xzlw9JS1rqEV55nb0ttsKxVlTCcd+R5cg==",+ "license": "MIT",+ "dependencies": {+ "@vue/compiler-dom": "3.5.41",+ "@vue/compiler-sfc": "3.5.41",+ "@vue/runtime-dom": "3.5.41",+ "@vue/server-renderer": "3.5.41",+ "@vue/shared": "3.5.41"+ },+ "peerDependencies": {+ "typescript": "*"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },"node_modules/w3c-keyname": {"version": "2.2.8","resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",@@ -5932,6 +8404,16 @@"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz","integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==","license": "MIT"+ },+ "node_modules/zwitch": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }}}}diff --git a/frontend/package.json b/frontend/package.jsonindex fe74a1cc..82e56aeb 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -63,12 +63,12 @@"@fontsource-variable/inter": "^5.2.8","@fontsource/ibm-plex-mono": "^5.2.7","@fontsource/jetbrains-mono": "^5.2.8",+ "@milkdown/crepe": "^7.22.1","@sveltejs/svelte-json-tree": "^2.2.1","@tracewayapp/svelte": "^1.0.2","codemirror": "^6.0.2","d3-flame-graph": "^5.0.0","d3-selection": "^3.0.0",- "lucide-svelte": "^0.562.0","luxon": "^3.7.2","rrweb-player": "^2.0.0-alpha.18","svelte-highlight": "^7.9.0",diff --git a/frontend/src/app.d.ts b/frontend/src/app.d.tsindex 75b2d66f..7be578df 100644--- a/frontend/src/app.d.ts+++ b/frontend/src/app.d.ts@@ -15,14 +15,18 @@ declare global {const __TRACEWAY_URL__: string;interface Window {+ captureException: typeof import('@tracewayapp/frontend').captureException;turnstile: {- render: (element: HTMLElement, options: {- sitekey: string;- callback: (token: string) => void;- 'error-callback'?: () => void;- 'expired-callback'?: () => void;- theme?: 'light' | 'dark' | 'auto';- }) => string;+ render: (+ element: HTMLElement,+ options: {+ sitekey: string;+ callback: (token: string) => void;+ 'error-callback'?: () => void;+ 'expired-callback'?: () => void;+ theme?: 'light' | 'dark' | 'auto';+ }+ ) => string;remove: (widgetId: string) => void;};onTurnstileLoad?: () => void;diff --git a/frontend/src/app.html b/frontend/src/app.htmlindex 1e7fb2d3..15af15af 100644--- a/frontend/src/app.html+++ b/frontend/src/app.html@@ -1,5 +1,5 @@<!doctype html>-<html lang="en" class="dark" style="color-scheme: dark; background: #0b0d16;">+<html lang="en" class="dark" style="color-scheme: dark; background: #0b0d16"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 45b90776..05a76276 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4,85 +4,91 @@ import { toast } from 'svelte-sonner';const BASE_URL = '/api';interface RequestOptions {- projectId?: string;- skipProjectId?: boolean;+ projectId?: string;+ skipProjectId?: boolean;}async function request(method: string, endpoint: string, data?: unknown, options?: RequestOptions) {- const currentToken = authState.token;- const headers: Record<string, string> = {- 'Content-Type': 'application/json'- };+ const currentToken = authState.token;+ const headers: Record<string, string> = {+ 'Content-Type': 'application/json'+ };- if (currentToken) {- headers['Authorization'] = `Bearer ${currentToken}`;- }+ if (currentToken) {+ headers['Authorization'] = `Bearer ${currentToken}`;+ }- const config: RequestInit = {- method,- headers,- };+ const config: RequestInit = {+ method,+ headers+ };- if (data) {- config.body = JSON.stringify(data);- }+ if (data) {+ config.body = JSON.stringify(data);+ }- // Add projectId as query parameter if provided- let url = `${BASE_URL}${endpoint}`;- if (options?.projectId && !options?.skipProjectId) {- const separator = endpoint.includes('?') ? '&' : '?';- url = `${url}${separator}projectId=${options.projectId}`;- }+ // Add projectId as query parameter if provided+ let url = `${BASE_URL}${endpoint}`;+ if (options?.projectId && !options?.skipProjectId) {+ const separator = endpoint.includes('?') ? '&' : '?';+ url = `${url}${separator}projectId=${options.projectId}`;+ }- const response = await fetch(url, config);+ const response = await fetch(url, config);- if (response.status === 401) {- authState.logout();- window.location.href = '/login';- throw new Error('Unauthorized');- }+ if (response.status === 401) {+ authState.logout();+ window.location.href = '/login';+ throw new Error('Unauthorized');+ }- if (response.status === 403) {- if (method !== 'GET') {- const body = await response.json().catch(() => ({}));- const message = body.error || "You don't have permission to perform this action";- toast.error(message, { position: 'top-center' });- const error = new Error(message) as Error & { status: number; body?: unknown };- error.status = 403;- error.body = body;- throw error;- }- const currentPath = window.location.pathname;- if (currentPath === '/' || currentPath === '') {- authState.logout();- window.location.href = '/login';- } else {- toast.warning("You don't have permission to access that feature", { position: 'top-center' });- window.location.href = '/';- }- throw new Error('Forbidden');- }+ if (response.status === 403) {+ if (method !== 'GET') {+ const body = await response.json().catch(() => ({}));+ const message = body.error || "You don't have permission to perform this action";+ toast.error(message);+ const error = new Error(message) as Error & { status: number; body?: unknown };+ error.status = 403;+ error.body = body;+ throw error;+ }+ const currentPath = window.location.pathname;+ if (currentPath === '/' || currentPath === '') {+ authState.logout();+ window.location.href = '/login';+ } else {+ toast.warning("You don't have permission to access that feature");+ window.location.href = '/';+ }+ throw new Error('Forbidden');+ }- if (response.status === 422) {- const body = await response.json().catch(() => ({}));- const error = new Error(body.error || 'Validation failed') as Error & { status: number; body?: unknown };- error.status = 422;- error.body = body;- throw error;- }+ if (response.status === 422) {+ const body = await response.json().catch(() => ({}));+ const error = new Error(body.error || 'Validation failed') as Error & {+ status: number;+ body?: unknown;+ };+ error.status = 422;+ error.body = body;+ throw error;+ }- if (!response.ok) {- const error = new Error(`API Error: ${response.statusText}`) as Error & { status: number };- error.status = response.status;- throw error;- }+ if (!response.ok) {+ const error = new Error(`API Error: ${response.statusText}`) as Error & { status: number };+ error.status = response.status;+ throw error;+ }- return response.json();+ return response.json();}export const api = {- get: (endpoint: string, options?: RequestOptions) => request('GET', endpoint, undefined, options),- post: (endpoint: string, data: unknown, options?: RequestOptions) => request('POST', endpoint, data, options),- put: (endpoint: string, data: unknown, options?: RequestOptions) => request('PUT', endpoint, data, options),- delete: (endpoint: string, options?: RequestOptions, data?: unknown) => request('DELETE', endpoint, data, options)+ get: (endpoint: string, options?: RequestOptions) => request('GET', endpoint, undefined, options),+ post: (endpoint: string, data: unknown, options?: RequestOptions) =>+ request('POST', endpoint, data, options),+ put: (endpoint: string, data: unknown, options?: RequestOptions) =>+ request('PUT', endpoint, data, options),+ delete: (endpoint: string, options?: RequestOptions, data?: unknown) =>+ request('DELETE', endpoint, data, options)};diff --git a/frontend/src/lib/components/add-project-modal.svelte b/frontend/src/lib/components/add-project-modal.svelteindex d6b2e625..6333d579 100644--- a/frontend/src/lib/components/add-project-modal.svelte+++ b/frontend/src/lib/components/add-project-modal.svelte@@ -1,222 +1,213 @@<script lang="ts">- import { untrack } from 'svelte';- import * as Sheet from "$lib/components/ui/sheet";- import { Button } from "$lib/components/ui/button";- import { Input } from "$lib/components/ui/input";- import { Label } from "$lib/components/ui/label";- import * as Select from "$lib/components/ui/select";- import { ErrorAlert } from "$lib/components/ui/error-alert";- import { projectsState, getFrameworkLabel, type ProjectWithToken, type Framework } from '$lib/state/projects.svelte';- import { authState } from '$lib/state/auth.svelte';- import { Copy, Check, ExternalLink, Plus } from 'lucide-svelte';- import FrameworkIcon from './framework-icon.svelte';- import FrameworkCombobox from './framework-combobox.svelte';-- interface Props {- open: boolean;- onOpenChange: (open: boolean) => void;- onProjectCreated: () => void;- }-- let { open, onOpenChange, onProjectCreated }: Props = $props();-- let projectName = $state('');- let selectedFramework = $state<Framework>('opentelemetry');- let loading = $state(false);- let error = $state('');- let createdProject = $state<ProjectWithToken | null>(null);- let copied = $state(false);- let selectedOrgId = $state<number | null>(null);-- const writableOrgs = $derived(authState.organizations.filter(o => o.role !== 'readonly'));- const selectedOrgName = $derived(writableOrgs.find(o => o.id === selectedOrgId)?.name ?? '');-- $effect(() => {- if (open) {- untrack(() => {- const currentOrgId = projectsState.currentProject?.organizationId;- selectedOrgId = writableOrgs.some(o => o.id === currentOrgId)- ? currentOrgId!- : (writableOrgs[0]?.id ?? null);- });- }- });-- async function handleSubmit(e: Event) {- e.preventDefault();-- loading = true;- error = '';-- try {- const project = await projectsState.createProject(projectName.trim(), selectedFramework, selectedOrgId ?? undefined);- createdProject = project;- } catch (err) {- error = err instanceof Error ? err.message : 'Failed to create project';- } finally {- loading = false;- }- }-- async function copyToken() {- if (createdProject?.token) {- await navigator.clipboard.writeText(createdProject.token);- copied = true;- setTimeout(() => copied = false, 2000);- }- }-- function handleClose() {- projectName = '';- selectedFramework = 'opentelemetry';- error = '';- createdProject = null;- selectedOrgId = null;- onOpenChange(false);- }-- function handleGoToConnection() {- if (createdProject) {- projectsState.selectProject(createdProject.id);- }- handleClose();- onProjectCreated();- }+ import { untrack } from 'svelte';+ import * as Sheet from '$lib/components/ui/sheet';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import * as Select from '$lib/components/ui/select';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import {+ projectsState,+ getFrameworkLabel,+ type ProjectWithToken,+ type Framework+ } from '$lib/state/projects.svelte';+ import { authState } from '$lib/state/auth.svelte';+ import { ExternalLink, Plus } from '@lucide/svelte';+ import CopyButton from '$lib/components/traceway/copy-button.svelte';+ import FrameworkIcon from './framework-icon.svelte';+ import FrameworkCombobox from './framework-combobox.svelte';++ interface Props {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onProjectCreated: () => void;+ }++ let { open, onOpenChange, onProjectCreated }: Props = $props();++ let projectName = $state('');+ let selectedFramework = $state<Framework>('opentelemetry');+ let loading = $state(false);+ let error = $state('');+ let createdProject = $state<ProjectWithToken | null>(null);+ let selectedOrgId = $state<number | null>(null);++ const writableOrgs = $derived(authState.organizations.filter((o) => o.role !== 'readonly'));+ const selectedOrgName = $derived(writableOrgs.find((o) => o.id === selectedOrgId)?.name ?? '');++ $effect(() => {+ if (open) {+ untrack(() => {+ const currentOrgId = projectsState.currentProject?.organizationId;+ selectedOrgId = writableOrgs.some((o) => o.id === currentOrgId)+ ? currentOrgId!+ : (writableOrgs[0]?.id ?? null);+ });+ }+ });++ async function handleSubmit(e: Event) {+ e.preventDefault();++ loading = true;+ error = '';++ try {+ const project = await projectsState.createProject(+ projectName.trim(),+ selectedFramework,+ selectedOrgId ?? undefined+ );+ createdProject = project;+ } catch (err) {+ error = err instanceof Error ? err.message : 'Failed to create project';+ } finally {+ loading = false;+ }+ }++ function handleClose() {+ projectName = '';+ selectedFramework = 'opentelemetry';+ error = '';+ createdProject = null;+ selectedOrgId = null;+ onOpenChange(false);+ }++ function handleGoToConnection() {+ if (createdProject) {+ projectsState.selectProject(createdProject.id);+ }+ handleClose();+ onProjectCreated();+ }</script><Sheet.Root {open} onOpenChange={handleClose}>- <Sheet.Content side="right" class="w-[400px] sm:w-[540px]">- <Sheet.Header>- <Sheet.Title>- {#if createdProject}- Project Created!- {:else}- New Project- {/if}- </Sheet.Title>- <Sheet.Description>- {#if createdProject}- Your project has been created. Save the token below - you'll need it to connect your application.- {:else}- Add a new project to start tracking errors and metrics.- {/if}- </Sheet.Description>- </Sheet.Header>-- {#if createdProject}- <div class="px-6 py-6 space-y-6">- <div class="space-y-2">- <Label>Project Name</Label>- <div class="text-lg font-medium">{createdProject.name}</div>- </div>-- <div class="space-y-2">- <Label>Organization</Label>- <div class="text-sm text-muted-foreground">{selectedOrgName}</div>- </div>-- <div class="space-y-2">- <Label>Framework</Label>- <div class="flex items-center gap-2 text-sm text-muted-foreground">- <FrameworkIcon framework={selectedFramework} />- <span>{getFrameworkLabel(selectedFramework)}</span>- </div>- </div>-- <div class="space-y-2">- <Label>Project Token</Label>- <div class="flex gap-2">- <Input- type="text"- value={createdProject.token}- readonly- class="font-mono text-sm"- />- <Button variant="outline" size="icon" onclick={copyToken}>- {#if copied}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>- </div>- <p class="text-sm text-muted-foreground">- This token will only be shown once. Make sure to save it securely.- </p>- </div>- </div>-- <div class="flex justify-end gap-2 px-6 pb-6">- <Button variant="outline" onclick={handleClose}>- Close- </Button>- <Button onclick={handleGoToConnection}>- <ExternalLink class="mr-2 h-4 w-4" />- Go to Connection- </Button>- </div>- {:else}- <form onsubmit={handleSubmit} class="px-6 py-6 space-y-5">- <ErrorAlert {error} />-- <div class="space-y-2">- <Label>Organization</Label>- {#if writableOrgs.length > 1}- <Select.Root- type="single"- value={selectedOrgId !== null ? String(selectedOrgId) : undefined}- onValueChange={(val) => { if (val) selectedOrgId = Number(val); }}- >- <Select.Trigger class="w-full" disabled={loading}>- {selectedOrgName || 'Select organization'}- </Select.Trigger>- <Select.Content>- {#each writableOrgs as org (org.id)}- <Select.Item value={String(org.id)}>{org.name}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- {:else}- <div class="text-sm font-medium">{selectedOrgName}</div>- {/if}- </div>-- <div class="space-y-2">- <Label for="project-name">Project Name</Label>- <Input- id="project-name"- type="text"- placeholder="My Application"- bind:value={projectName}- disabled={loading}- />- <p class="text-xs text-muted-foreground">- A unique name for your project (letters, numbers, spaces, hyphens)- </p>- </div>-- <div class="space-y-2">- <Label for="framework">Framework</Label>- <FrameworkCombobox bind:value={selectedFramework} disabled={loading} />- <p class="text-xs text-muted-foreground">- Select your framework for tailored integration code- </p>- </div>-- <div class="flex justify-end gap-2 pt-2">- <Button type="button" variant="outline" onclick={handleClose} disabled={loading}>- Cancel- </Button>- <Button type="submit" variant="success" disabled={loading}>- {#if loading}- Creating...- {:else}- <Plus class="mr-2 h-4 w-4" />- New Project- {/if}- </Button>- </div>- </form>- {/if}- </Sheet.Content>+ <Sheet.Content side="right" class="w-[400px] sm:w-[540px]">+ <Sheet.Header>+ <Sheet.Title>+ {#if createdProject}+ Project Created!+ {:else}+ New Project+ {/if}+ </Sheet.Title>+ <Sheet.Description>+ {#if createdProject}+ Your project has been created. Save the token below - you'll need it to connect your+ application.+ {:else}+ Add a new project to start tracking errors and metrics.+ {/if}+ </Sheet.Description>+ </Sheet.Header>++ {#if createdProject}+ <div class="space-y-6 px-6 py-6">+ <div class="space-y-2">+ <Label>Project Name</Label>+ <div class="text-lg font-medium">{createdProject.name}</div>+ </div>++ <div class="space-y-2">+ <Label>Organization</Label>+ <div class="text-sm text-muted-foreground">{selectedOrgName}</div>+ </div>++ <div class="space-y-2">+ <Label>Framework</Label>+ <div class="flex items-center gap-2 text-sm text-muted-foreground">+ <FrameworkIcon framework={selectedFramework} />+ <span>{getFrameworkLabel(selectedFramework)}</span>+ </div>+ </div>++ <div class="space-y-2">+ <Label>Project Token</Label>+ <div class="flex gap-2">+ <Input type="text" value={createdProject.token} readonly class="font-mono text-sm" />+ <CopyButton text={() => createdProject?.token ?? ''} size="default" />+ </div>+ <p class="text-sm text-muted-foreground">+ This token will only be shown once. Make sure to save it securely.+ </p>+ </div>+ </div>++ <div class="flex justify-end gap-2 px-6 pb-6">+ <Button variant="outline" onclick={handleClose}>Close</Button>+ <Button onclick={handleGoToConnection}>+ <ExternalLink class="mr-2 h-4 w-4" />+ Go to Connection+ </Button>+ </div>+ {:else}+ <form onsubmit={handleSubmit} class="space-y-5 px-6 py-6">+ <ErrorAlert {error} />++ <div class="space-y-2">+ <Label>Organization</Label>+ {#if writableOrgs.length > 1}+ <Select.Root+ type="single"+ value={selectedOrgId !== null ? String(selectedOrgId) : undefined}+ onValueChange={(val) => {+ if (val) selectedOrgId = Number(val);+ }}+ >+ <Select.Trigger class="w-full" disabled={loading}>+ {selectedOrgName || 'Select organization'}+ </Select.Trigger>+ <Select.Content>+ {#each writableOrgs as org (org.id)}+ <Select.Item value={String(org.id)}>{org.name}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ {:else}+ <div class="text-sm font-medium">{selectedOrgName}</div>+ {/if}+ </div>++ <div class="space-y-2">+ <Label for="project-name">Project Name</Label>+ <Input+ id="project-name"+ type="text"+ placeholder="My Application"+ bind:value={projectName}+ disabled={loading}+ />+ <p class="text-xs text-muted-foreground">+ A unique name for your project (letters, numbers, spaces, hyphens)+ </p>+ </div>++ <div class="space-y-2">+ <Label for="framework">Framework</Label>+ <FrameworkCombobox bind:value={selectedFramework} disabled={loading} />+ <p class="text-xs text-muted-foreground">+ Select your framework for tailored integration code+ </p>+ </div>++ <div class="flex justify-end gap-2 pt-2">+ <Button type="button" variant="outline" onclick={handleClose} disabled={loading}>+ Cancel+ </Button>+ <Button type="submit" variant="success" disabled={loading}>+ {#if loading}+ Creating...+ {:else}+ <Plus class="mr-2 h-4 w-4" />+ New Project+ {/if}+ </Button>+ </div>+ </form>+ {/if}+ </Sheet.Content></Sheet.Root>diff --git a/frontend/src/lib/components/ai/ai-nav-tabs.svelte b/frontend/src/lib/components/ai/ai-nav-tabs.svelteindex 454dfd73..6205db09 100644--- a/frontend/src/lib/components/ai/ai-nav-tabs.svelte+++ b/frontend/src/lib/components/ai/ai-nav-tabs.svelte@@ -1,8 +1,7 @@<script lang="ts">- import * as Tabs from '$lib/components/ui/tabs';- import { goto } from '$app/navigation';+ import PageTabs from '$lib/components/traceway/page-tabs.svelte';import { resolve } from '$app/paths';- import { addStickyParamsToHref } from '$lib/utils/navigation';+ import { addStickyParamsToHref, gotoHref } from '$lib/utils/navigation';type Props = {active: 'traces' | 'conversations' | 'users';@@ -19,15 +18,8 @@function onTabChange(value: string) {const tab = tabs.find((t) => t.value === value);if (!tab || tab.value === active) return;- // eslint-disable-next-line svelte/no-navigation-without-resolve- goto(addStickyParamsToHref(tab.href, 'preset', 'from', 'to'));+ gotoHref(addStickyParamsToHref(tab.href, 'preset', 'from', 'to'));}</script>-<Tabs.Root value={active} onValueChange={(v) => v && onTabChange(v)}>- <Tabs.List>- {#each tabs as tab (tab.value)}- <Tabs.Trigger value={tab.value}>{tab.label}</Tabs.Trigger>- {/each}- </Tabs.List>-</Tabs.Root>+<PageTabs {tabs} activeTab={active} {onTabChange} />diff --git a/frontend/src/lib/components/ai/conversation-messages.svelte b/frontend/src/lib/components/ai/conversation-messages.svelteindex 6f4f3376..30fa400e 100644--- a/frontend/src/lib/components/ai/conversation-messages.svelte+++ b/frontend/src/lib/components/ai/conversation-messages.svelte@@ -32,7 +32,7 @@</script><div class="space-y-3">- {#each visibleMessages as msg}+ {#each visibleMessages as msg, __index (__index)}<div class="flex gap-3"><divclass="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-medium@@ -50,7 +50,7 @@<p class="mb-1 text-xs font-medium text-muted-foreground">{getRoleLabel(msg.role)}</p>- {#each getMessageImages(msg.content) as imageUrl}+ {#each getMessageImages(msg.content) as imageUrl, __index (__index)}{#if imageUrl && !imageUrl.includes('REDACTED')}<div class="mb-2 max-w-sm"><img@@ -73,7 +73,7 @@{getMessageText(msg.content)}</div>{/if}- {#each msg.toolCalls ?? [] as call}+ {#each msg.toolCalls ?? [] as call, __index (__index)}<ToolCallBlock {call} result={call.id ? toolResults.get(call.id) : undefined} />{/each}</div>diff --git a/frontend/src/lib/components/ai/flagged-badge.svelte b/frontend/src/lib/components/ai/flagged-badge.svelteindex b663f37e..f47664a9 100644--- a/frontend/src/lib/components/ai/flagged-badge.svelte+++ b/frontend/src/lib/components/ai/flagged-badge.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { TriangleAlert } from 'lucide-svelte';+ import { TriangleAlert } from '@lucide/svelte';import * as Tooltip from '$lib/components/ui/tooltip';type Props = {diff --git a/frontend/src/lib/components/ai/flagged-filter.svelte b/frontend/src/lib/components/ai/flagged-filter.svelteindex 307b1687..7df4af69 100644--- a/frontend/src/lib/components/ai/flagged-filter.svelte+++ b/frontend/src/lib/components/ai/flagged-filter.svelte@@ -1,5 +1,5 @@<script lang="ts">- import * as Select from '$lib/components/ui/select';+ import ToolbarSelect from '$lib/components/traceway/toolbar-select.svelte';type Props = {value?: string;@@ -12,19 +12,6 @@{ value: 'all', label: 'All' },{ value: 'flagged', label: 'Flagged only' }];-- const label = $derived(options.find((o) => o.value === value)?.label ?? 'All');</script>-<Select.Root type="single" bind:value onValueChange={(v) => onChange?.(v ?? 'all')}>- <Select.Trigger class="h-9 w-[130px] rounded-none border-r-0 shadow-none">- {label}- </Select.Trigger>- <Select.Content>- {#each options as option}- <Select.Item value={option.value} label={option.label}>- {option.label}- </Select.Item>- {/each}- </Select.Content>-</Select.Root>+<ToolbarSelect bind:value {options} class="w-[130px]" onChange={(v) => onChange?.(v || 'all')} />diff --git a/frontend/src/lib/components/ai/tool-call-block.svelte b/frontend/src/lib/components/ai/tool-call-block.svelteindex 64a72d33..290c130f 100644--- a/frontend/src/lib/components/ai/tool-call-block.svelte+++ b/frontend/src/lib/components/ai/tool-call-block.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Wrench, ChevronRight } from 'lucide-svelte';+ import { Wrench, ChevronRight } from '@lucide/svelte';import {tryParseJson,getMessageText,@@ -48,7 +48,8 @@<p class="mb-1 text-[0.65rem] font-medium tracking-wide text-muted-foreground uppercase">Arguments</p>- <pre class="max-h-64 overflow-auto font-mono text-xs break-words whitespace-pre-wrap">{formattedArguments}</pre>+ <pre+ class="max-h-64 overflow-auto font-mono text-xs break-words whitespace-pre-wrap">{formattedArguments}</pre></div>{/if}{#if resultText}@@ -66,7 +67,8 @@/></button>{#if showResult}- <pre class="mt-1 max-h-64 overflow-auto font-mono text-xs break-words whitespace-pre-wrap">{resultText}</pre>+ <pre+ class="mt-1 max-h-64 overflow-auto font-mono text-xs break-words whitespace-pre-wrap">{resultText}</pre>{/if}</div>{/if}diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelteindex 1a17cf6a..02b4e839 100644--- a/frontend/src/lib/components/app-sidebar.svelte+++ b/frontend/src/lib/components/app-sidebar.svelte@@ -10,7 +10,6 @@Bug,Link2,ChartNoAxesCombined,- ChartNoAxesGantt,FileText,Film,Flame,@@ -170,7 +169,7 @@><Sidebar.SidebarGroupContent><Sidebar.SidebarMenu>- {#each sidebarItems as sidebarItem}+ {#each sidebarItems as sidebarItem, __index (__index)}{@const active =page.url.pathname === sidebarItem.href ||page.url.pathname.startsWith(sidebarItem.href + '/')}@@ -215,7 +214,7 @@><Sidebar.SidebarGroupContent><Sidebar.SidebarMenu>- {#each sidebarItemsBottom as sidebarItem}+ {#each sidebarItemsBottom as sidebarItem, __index (__index)}<Sidebar.SidebarMenuItem>{#if sidebarItem.external}<Sidebar.SidebarMenuButtondiff --git a/frontend/src/lib/components/archive-confirmation-dialog.svelte b/frontend/src/lib/components/archive-confirmation-dialog.svelteindex 85da0bf5..88f2ac5e 100644--- a/frontend/src/lib/components/archive-confirmation-dialog.svelte+++ b/frontend/src/lib/components/archive-confirmation-dialog.svelte@@ -1,10 +1,10 @@<script lang="ts">- import * as AlertDialog from "$lib/components/ui/alert-dialog";- import { Button } from "$lib/components/ui/button";- import { Checkbox } from "$lib/components/ui/checkbox";- import { Archive } from "lucide-svelte";- import { api } from "$lib/api";- import { projectsState } from "$lib/state/projects.svelte";+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Button } from '$lib/components/ui/button';+ import { Checkbox } from '$lib/components/ui/checkbox';+ import { Archive } from '@lucide/svelte';+ import { api } from '$lib/api';+ import { projectsState } from '$lib/state/projects.svelte';interface Props {open: boolean;@@ -48,7 +48,7 @@try {await onConfirm(linkedPages > 0 && resolvePages);onOpenChange(false);- } catch (e) {+ } catch {// Error handling done in parent, just reset loading} finally {loading = false;@@ -67,8 +67,8 @@<AlertDialog.Header><AlertDialog.Title>Archive Issue{count > 1 ? 's' : ''}</AlertDialog.Title><AlertDialog.Description>- Are you sure you want to archive {count} issue{count > 1 ? 's' : ''}?- Archived issues will be hidden from the main issues list.+ Are you sure you want to archive {count} issue{count > 1 ? 's' : ''}? Archived issues will+ be hidden from the main issues list.</AlertDialog.Description></AlertDialog.Header>{#if linkedPages > 0}@@ -84,11 +84,10 @@</label>{/if}<AlertDialog.Footer>- <Button variant="outline" onclick={handleCancel} disabled={loading}>- Cancel- </Button>+ <Button variant="outline" onclick={handleCancel} disabled={loading}>Cancel</Button><Button variant="destructiveOutline" onclick={handleConfirm} disabled={loading}>- <Archive class="h-4 w-4" /> {loading ? 'Archiving...' : 'Archive'}+ <Archive class="h-4 w-4" />+ {loading ? 'Archiving...' : 'Archive'}</Button></AlertDialog.Footer></AlertDialog.Content>diff --git a/frontend/src/lib/components/attributes-display.svelte b/frontend/src/lib/components/attributes-display.svelteindex 3ab7cc8d..e6c0fddb 100644--- a/frontend/src/lib/components/attributes-display.svelte+++ b/frontend/src/lib/components/attributes-display.svelte@@ -18,7 +18,7 @@{#if entries.length > 0}<div class="flex flex-wrap items-center gap-1">- {#each visibleEntries as [key, value]}+ {#each visibleEntries as [key, value], __index (__index)}<spanclass="inline-flex items-center rounded bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground">@@ -39,7 +39,7 @@<div class="space-y-2"><h4 class="text-sm font-medium">All Attributes Tags</h4><div class="grid gap-2">- {#each entries as [key, value]}+ {#each entries as [key, value], __index (__index)}<div class="flex items-start gap-2 text-sm"><span class="shrink-0 font-medium text-muted-foreground">{key}:</span><span class="font-mono break-all">{value}</span>diff --git a/frontend/src/lib/components/dashboard/d3-gauge.svelte b/frontend/src/lib/components/dashboard/d3-gauge.svelteindex ce80b24c..e1b2634c 100644--- a/frontend/src/lib/components/dashboard/d3-gauge.svelte+++ b/frontend/src/lib/components/dashboard/d3-gauge.svelte@@ -105,7 +105,7 @@{#if radius > 20}<svg {width} {height}><g transform="translate({cx}, {cy})">- {#each bandPaths as seg}+ {#each bandPaths as seg, __index (__index)}<path d={seg.path} fill={seg.color} />{/each}<path d={trackPath} fill="var(--muted)" />@@ -119,22 +119,10 @@>{valueLabel}</text>- <text- x={-endX}- y={endY}- text-anchor="middle"- font-size="11"- fill="var(--muted-foreground)"- >+ <text x={-endX} y={endY} text-anchor="middle" font-size="11" fill="var(--muted-foreground)">{formatValue(min)}</text>- <text- x={endX}- y={endY}- text-anchor="middle"- font-size="11"- fill="var(--muted-foreground)"- >+ <text x={endX} y={endY} text-anchor="middle" font-size="11" fill="var(--muted-foreground)">{formatValue(max)}</text></g>diff --git a/frontend/src/lib/components/dashboard/d3-horizontal-bar-chart.svelte b/frontend/src/lib/components/dashboard/d3-horizontal-bar-chart.svelteindex 65dd05f0..3da73e24 100644--- a/frontend/src/lib/components/dashboard/d3-horizontal-bar-chart.svelte+++ b/frontend/src/lib/components/dashboard/d3-horizontal-bar-chart.svelte@@ -58,12 +58,10 @@const chartHeight = $derived(Math.max(0, height - padding.top - padding.bottom));// Sort data by value descending (worst at top)- const sortedData = $derived(- [...data].sort((a, b) => b.value - a.value)- );+ const sortedData = $derived([...data].sort((a, b) => b.value - a.value));// Calculate max value for scale- const maxValue = $derived(max(sortedData, d => d.value) ?? 0);+ const maxValue = $derived(max(sortedData, (d) => d.value) ?? 0);// X scale (value)const xScale = $derived(@@ -75,7 +73,7 @@// Y scale (endpoints)const yScale = $derived(scaleBand<string>()- .domain(sortedData.map(d => d.endpoint))+ .domain(sortedData.map((d) => d.endpoint)).range([0, chartHeight]).padding(0.25));@@ -107,16 +105,12 @@}</script>-<div- bind:this={containerRef}- class="relative w-full"- style="height: {height}px;"->+<div bind:this={containerRef} class="relative w-full" style="height: {height}px;">{#if hasData && chartWidth > 0}<svg {width} {height}><g transform="translate({padding.left}, {padding.top})"><!-- Bars -->- {#each sortedData as item, i}+ {#each sortedData as item, i (i)}{@const y = yScale(item.endpoint) ?? 0}{@const barWidth = xScale(item.value)}{@const color = chartColors[i % chartColors.length]}@@ -173,7 +167,7 @@{@const item = sortedData[hoveredIndex]}{@const y = (yScale(item.endpoint) ?? 0) + padding.top + barHeight / 2}<div- class="absolute z-10 pointer-events-none bg-background border border-border rounded px-2 py-1 text-xs text-muted-foreground whitespace-nowrap shadow-sm"+ class="pointer-events-none absolute z-10 rounded border border-border bg-background px-2 py-1 text-xs whitespace-nowrap text-muted-foreground shadow-sm"style="right: {width - padding.left + 8}px; top: {y}px; transform: translateY(-50%);">{item.endpoint}diff --git a/frontend/src/lib/components/dashboard/d3-line-chart.svelte b/frontend/src/lib/components/dashboard/d3-line-chart.svelteindex 203ce861..33373cae 100644--- a/frontend/src/lib/components/dashboard/d3-line-chart.svelte+++ b/frontend/src/lib/components/dashboard/d3-line-chart.svelte@@ -1,5 +1,6 @@<script lang="ts">- import { scaleUtc, scaleLinear, type NumberValue } from 'd3-scale';+ import { scaleUtc, scaleLinear } from 'd3-scale';+ import { SvelteSet } from 'svelte/reactivity';import { line, area } from 'd3-shape';import { min, max } from 'd3-array';import { formatDateTime } from '$lib/utils/formatters';@@ -110,17 +111,9 @@const yDomainMax = $derived(yMax() + yPadding);// Scales- const xScale = $derived(- scaleUtc()- .domain([xMin, xMax])- .range([0, chartWidth])- );+ const xScale = $derived(scaleUtc().domain([xMin, xMax]).range([0, chartWidth]));- const yScale = $derived(- scaleLinear()- .domain([yDomainMin, yDomainMax])- .range([chartHeight, 0])- );+ const yScale = $derived(scaleLinear().domain([yDomainMin, yDomainMax]).range([chartHeight, 0]));// Generate Y axis ticksconst yTicks = $derived(() => yScale.ticks(4));@@ -134,6 +127,16 @@const yAxisUnit = $derived(() => axisScale?.unit ?? '');+ const yTickItems = $derived(() => {+ const seen = new SvelteSet<string>();+ return yTicks().filter((tick) => {+ const label = formatYLabel(tick);+ if (seen.has(label)) return false;+ seen.add(label);+ return true;+ });+ });+function formatYLabel(value: number): string {if (axisScale) {return formatAxisTick(value, axisScale.divisor);@@ -149,8 +152,8 @@if (seriesData.length === 0) return '';const lineGen = line<DataPoint>()- .x(d => xScale(d.timestamp))- .y(d => yScale(d.value));+ .x((d) => xScale(d.timestamp))+ .y((d) => yScale(d.value));return lineGen(seriesData) || '';}@@ -159,9 +162,9 @@if (seriesData.length === 0) return '';const areaGen = area<DataPoint>()- .x(d => xScale(d.timestamp))+ .x((d) => xScale(d.timestamp)).y0(chartHeight)- .y1(d => yScale(d.value));+ .y1((d) => yScale(d.value));return areaGen(seriesData) || '';}@@ -191,7 +194,7 @@const timeDiff = xMax.getTime() - xMin.getTime();if (timeDiff <= 0) return padding.left;const percentage = (time.getTime() - xMin.getTime()) / timeDiff;- return padding.left + (percentage * chartWidth);+ return padding.left + percentage * chartWidth;}// Calculate gap threshold from data (2x median interval)@@ -236,10 +239,12 @@const isolated: DataPoint[] = [];for (let i = 0; i < pointData.length; i++) {- const hasGapBefore = i === 0 ||- (pointData[i].timestamp.getTime() - pointData[i - 1].timestamp.getTime() > threshold);- const hasGapAfter = i === pointData.length - 1 ||- (pointData[i + 1].timestamp.getTime() - pointData[i].timestamp.getTime() > threshold);+ const hasGapBefore =+ i === 0 ||+ pointData[i].timestamp.getTime() - pointData[i - 1].timestamp.getTime() > threshold;+ const hasGapAfter =+ i === pointData.length - 1 ||+ pointData[i + 1].timestamp.getTime() - pointData[i].timestamp.getTime() > threshold;if (hasGapBefore && hasGapAfter) {isolated.push(pointData[i]);@@ -250,7 +255,10 @@}// Find the value at a given time, interpolating for line sections- function getValueAtTime(time: Date, pointData: DataPoint[]): { value: number; isInterpolated: boolean } | null {+ function getValueAtTime(+ time: Date,+ pointData: DataPoint[]+ ): { value: number; isInterpolated: boolean } | null {if (pointData.length === 0) return null;const targetMs = time.getTime();@@ -354,7 +362,9 @@// Selection region computed valuesconst selectionLeft = $derived(Math.max(padding.left, Math.min(dragStartX, dragEndX)));- const selectionRight = $derived(() => Math.min(width - padding.right, Math.max(dragStartX, dragEndX)));+ const selectionRight = $derived(() =>+ Math.min(width - padding.right, Math.max(dragStartX, dragEndX))+ );const selectionWidth = $derived(selectionRight() - selectionLeft);const selectionStartTime = $derived(() => getTimeAtPosition(selectionLeft));const selectionEndTime = $derived(() => getTimeAtPosition(selectionLeft + selectionWidth));@@ -429,8 +439,12 @@<divbind:this={containerRef}- class="relative select-none w-full"- style="height: {height}px; cursor: {isDragging ? 'col-resize' : (isInChartArea() ? 'crosshair' : 'default')};"+ class="relative w-full select-none"+ style="height: {height}px; cursor: {isDragging+ ? 'col-resize'+ : isInChartArea()+ ? 'crosshair'+ : 'default'};"onmouseenter={handleMouseEnter}onmouseleave={handleMouseLeave}onmousemove={handleMouseMove}@@ -449,7 +463,7 @@</defs><g transform="translate({padding.left}, {padding.top})"><!-- Y axis grid lines -->- {#each yTicks() as tick}+ {#each yTickItems() as tick, __index (__index)}<linex1={0}y1={yScale(tick)}@@ -462,7 +476,7 @@{/each}<!-- Y axis labels -->- {#each yTicks() as tick}+ {#each yTickItems() as tick, __index (__index)}<textx={-8}y={yScale(tick)}@@ -477,13 +491,7 @@<!-- Y axis unit label -->{#if yAxisUnit()}- <text- x={-8}- y={-4}- text-anchor="end"- fill="#9ca3af"- font-size="10"- >+ <text x={-8} y={-4} text-anchor="end" fill="#9ca3af" font-size="10">{yAxisUnit()}</text>{/if}@@ -499,25 +507,18 @@/><!-- Y axis line -->- <line- x1={0}- y1={0}- x2={0}- y2={chartHeight}- stroke="#e5e7eb"- stroke-width="1"- />+ <line x1={0} y1={0} x2={0} y2={chartHeight} stroke="#e5e7eb" stroke-width="1" /><!-- Lines for each series (with gap detection) --><g clip-path="url(#{clipId})">- {#each series as s}+ {#each series as s, __index (__index)}{#if s.data.length > 0}{@const segments = getLineSegments(s.data)}{@const isolated = getIsolatedPoints(s.data)}<!-- Draw area fills (when areaFill is enabled) -->{#if areaFill}- {#each segments as segment}+ {#each segments as segment, __index (__index)}{#if segment.length > 1}<pathd={generateAreaPath(segment)}@@ -530,19 +531,14 @@{/if}<!-- Draw line segments (only segments with 2+ points) -->- {#each segments as segment}+ {#each segments as segment, __index (__index)}{#if segment.length > 1}- <path- d={generatePath(segment)}- fill="none"- stroke={s.color}- stroke-width="1.5"- />+ <path d={generatePath(segment)} fill="none" stroke={s.color} stroke-width="1.5" />{/if}{/each}<!-- Draw isolated points as dots -->- {#each isolated as point}+ {#each isolated as point, __index (__index)}<circlecx={xScale(point.timestamp)}cy={yScale(point.value)}@@ -564,13 +560,17 @@<!-- Drag selection overlay -->{#if isDragging && selectionWidth > 0}<div- class="absolute top-0 bottom-0 bg-primary/20 border-x border-primary/40 pointer-events-none"+ class="pointer-events-none absolute top-0 bottom-0 border-x border-primary/40 bg-primary/20"style="left: {selectionLeft}px; width: {selectionWidth}px;">- <div class="absolute -top-5 left-0 -translate-x-full text-[9px] font-medium text-primary whitespace-nowrap">+ <div+ class="absolute -top-5 left-0 -translate-x-full text-[9px] font-medium whitespace-nowrap text-primary"+ >{formatTime(selectionStartTime())}</div>- <div class="absolute -top-5 right-0 translate-x-full text-[9px] font-medium text-primary whitespace-nowrap">+ <div+ class="absolute -top-5 right-0 translate-x-full text-[9px] font-medium whitespace-nowrap text-primary"+ >{formatTime(selectionEndTime())}</div></div>@@ -583,22 +583,31 @@<!-- Vertical line --><div- class="absolute top-0 bottom-0 w-px bg-muted-foreground/50 pointer-events-none"+ class="pointer-events-none absolute top-0 bottom-0 w-px bg-muted-foreground/50"style="left: {clampedX}px;"></div><!-- Value tooltip -->{#if hasMultiServerData && calculatedServerValues().length > 0}<div- class="absolute top-0 -translate-x-1/2 -translate-y-full pointer-events-none"+ class="pointer-events-none absolute top-0 -translate-x-1/2 -translate-y-full"style="left: {clampedX}px;">- <div class="bg-foreground text-background rounded px-2 py-1 text-xs font-medium whitespace-nowrap shadow-lg mb-1 flex flex-col gap-0.5">- {#each calculatedServerValues() as serverValue}+ <div+ class="mb-1 flex flex-col gap-0.5 rounded bg-foreground px-2 py-1 text-xs font-medium whitespace-nowrap text-background shadow-lg"+ >+ {#each calculatedServerValues() as serverValue, __index (__index)}{@const formatted = formatDisplayValue(serverValue.value)}<div class="flex items-center gap-1.5">- <span class="h-2 w-2 rounded-full flex-shrink-0" style="background-color: {serverValue.color};"></span>- <span>{formatted.text}{#if unit && !formatted.includesUnit}<span class="text-background/70 ml-0.5">{unit}</span>{/if}</span>+ <span+ class="h-2 w-2 flex-shrink-0 rounded-full"+ style="background-color: {serverValue.color};"+ ></span>+ <span+ >{formatted.text}{#if unit && !formatted.includesUnit}<span+ class="ml-0.5 text-background/70">{unit}</span+ >{/if}</span+ ></div>{/each}</div>@@ -606,21 +615,27 @@{:else if valueData}{@const formatted = formatDisplayValue(valueData.value)}<div- class="absolute top-0 -translate-x-1/2 -translate-y-full pointer-events-none"+ class="pointer-events-none absolute top-0 -translate-x-1/2 -translate-y-full"style="left: {clampedX}px;">- <div class="bg-foreground text-background rounded px-2 py-1 text-xs font-medium whitespace-nowrap shadow-lg mb-1">- {formatted.text}{#if unit && !formatted.includesUnit}<span class="text-background/70 ml-0.5">{unit}</span>{/if}+ <div+ class="mb-1 rounded bg-foreground px-2 py-1 text-xs font-medium whitespace-nowrap text-background shadow-lg"+ >+ {formatted.text}{#if unit && !formatted.includesUnit}<span+ class="ml-0.5 text-background/70">{unit}</span+ >{/if}</div></div>{/if}<!-- Time label --><div- class="absolute bottom-0 -translate-x-1/2 translate-y-full pointer-events-none"+ class="pointer-events-none absolute bottom-0 -translate-x-1/2 translate-y-full"style="left: {clampedX}px;">- <div class="bg-background border border-border rounded px-1.5 py-0.5 text-[10px] text-muted-foreground whitespace-nowrap shadow-sm mt-1">+ <div+ class="mt-1 rounded border border-border bg-background px-1.5 py-0.5 text-[10px] whitespace-nowrap text-muted-foreground shadow-sm"+ >{formatTime(calculatedTime())}</div></div>@@ -631,7 +646,7 @@{@const shadowX = shadowLineX()}{#if shadowX >= padding.left && shadowX <= width - padding.right}<div- class="absolute top-0 bottom-0 w-px bg-muted-foreground/25 pointer-events-none"+ class="pointer-events-none absolute top-0 bottom-0 w-px bg-muted-foreground/25"style="left: {shadowX}px;"></div>{/if}diff --git a/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte b/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelteindex 59da3f36..16dd7fe8 100644--- a/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte+++ b/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte@@ -1,5 +1,6 @@<script lang="ts">import { scaleUtc, scaleLinear } from 'd3-scale';+ import { SvelteMap } from 'svelte/reactivity';import { stack, area, stackOrderReverse } from 'd3-shape';import { min, max } from 'd3-array';import { formatDateTime } from '$lib/utils/formatters';@@ -88,7 +89,7 @@if (series.length === 0 || endpoints.length === 0) return [];// Group by timestamp- const byTimestamp = new Map<number, StackedData>();+ const byTimestamp = new SvelteMap<number, StackedData>();for (const point of series) {const ts = point.timestamp.getTime();@@ -149,17 +150,9 @@const yDomainMax = $derived(yMax() * 1.1 || 1);// Scales- const xScale = $derived(- scaleUtc()- .domain([xMin(), xMax()])- .range([0, chartWidth])- );-- const yScale = $derived(- scaleLinear()- .domain([0, yDomainMax])- .range([chartHeight, 0])- );+ const xScale = $derived(scaleUtc().domain([xMin(), xMax()]).range([0, chartWidth]));++ const yScale = $derived(scaleLinear().domain([0, yDomainMax]).range([chartHeight, 0]));// Generate Y axis ticksconst yTicks = $derived(() => yScale.ticks(4));@@ -188,9 +181,7 @@const data = stackedData();if (data.length === 0 || endpoints.length === 0) return [];- const stackGen = stack<StackedData>()- .keys(endpoints)- .order(stackOrderReverse);+ const stackGen = stack<StackedData>().keys(endpoints).order(stackOrderReverse);const stackedSeries = stackGen(data);@@ -353,8 +344,12 @@<div class="flex flex-col gap-2"><divbind:this={containerRef}- class="relative select-none w-full"- style="height: {height}px; cursor: {isDragging ? 'col-resize' : (isInChartArea() ? 'crosshair' : 'default')};"+ class="relative w-full select-none"+ style="height: {height}px; cursor: {isDragging+ ? 'col-resize'+ : isInChartArea()+ ? 'crosshair'+ : 'default'};"onmouseenter={handleMouseEnter}onmouseleave={handleMouseLeave}onmousemove={handleMouseMove}@@ -367,7 +362,7 @@<svg {width} {height}><g transform="translate({padding.left}, {padding.top})"><!-- Y axis grid lines -->- {#each yTicks() as tick}+ {#each yTicks() as tick, __index (__index)}<linex1={0}y1={yScale(tick)}@@ -381,7 +376,7 @@{/each}<!-- Y axis labels -->- {#each yTicks() as tick}+ {#each yTicks() as tick, __index (__index)}<textx={-8}y={yScale(tick)}@@ -432,7 +427,7 @@/><!-- Stacked areas -->- {#each stackedAreas() as area}+ {#each stackedAreas() as area, __index (__index)}<pathd={area.path}fill={area.color}@@ -452,13 +447,17 @@<!-- Drag selection overlay -->{#if isDragging && selectionWidth > 0}<div- class="absolute top-0 bottom-0 bg-primary/20 border-x border-primary/40 pointer-events-none"+ class="pointer-events-none absolute top-0 bottom-0 border-x border-primary/40 bg-primary/20"style="left: {selectionLeft}px; width: {selectionWidth}px;">- <div class="absolute -top-5 left-0 -translate-x-full text-[9px] font-medium text-primary whitespace-nowrap">+ <div+ class="absolute -top-5 left-0 -translate-x-full text-[9px] font-medium whitespace-nowrap text-primary"+ >{formatTime(selectionStartTime)}</div>- <div class="absolute -top-5 right-0 translate-x-full text-[9px] font-medium text-primary whitespace-nowrap">+ <div+ class="absolute -top-5 right-0 translate-x-full text-[9px] font-medium whitespace-nowrap text-primary"+ >{formatTime(selectionEndTime)}</div></div>@@ -471,24 +470,33 @@<!-- Vertical line --><div- class="absolute top-0 bottom-0 w-px bg-muted-foreground/50 pointer-events-none"+ class="pointer-events-none absolute top-0 bottom-0 w-px bg-muted-foreground/50"style="left: {clampedX}px;"></div><!-- Value tooltip -->{#if data}<div- class="absolute -translate-x-1/2 -translate-y-full pointer-events-none z-10"+ class="pointer-events-none absolute z-10 -translate-x-1/2 -translate-y-full"style="left: {clampedX}px; top: 10px;">- <div class="bg-background text-foreground border border-border rounded px-2 py-1.5 text-xs font-medium whitespace-nowrap mb-1 flex flex-col gap-0.5">- {#each endpoints as endpoint}+ <div+ class="mb-1 flex flex-col gap-0.5 rounded border border-border bg-background px-2 py-1.5 text-xs font-medium whitespace-nowrap text-foreground"+ >+ {#each endpoints as endpoint, __index (__index)}{@const value = getNumericValue(data, endpoint)}{#if value > 0}<div class="flex items-center gap-1.5">- <span class="h-2 w-2 rounded-full flex-shrink-0" style="background-color: {getEndpointColor(endpoint)};"></span>- <span class="truncate max-w-[200px]" title={endpoint}>{truncateEndpoint(endpoint, 25)}</span>- <span class="ml-auto tabular-nums">{formatDisplayValue(value)}{!formatValue && unit ? ` ${unit}` : ''}</span>+ <span+ class="h-2 w-2 flex-shrink-0 rounded-full"+ style="background-color: {getEndpointColor(endpoint)};"+ ></span>+ <span class="max-w-[200px] truncate" title={endpoint}+ >{truncateEndpoint(endpoint, 25)}</span+ >+ <span class="ml-auto tabular-nums"+ >{formatDisplayValue(value)}{!formatValue && unit ? ` ${unit}` : ''}</span+ ></div>{/if}{/each}@@ -498,10 +506,12 @@<!-- Time label --><div- class="absolute bottom-0 -translate-x-1/2 translate-y-full pointer-events-none"+ class="pointer-events-none absolute bottom-0 -translate-x-1/2 translate-y-full"style="left: {clampedX}px;">- <div class="bg-background border border-border rounded px-1.5 py-0.5 text-[10px] text-muted-foreground whitespace-nowrap shadow-sm mt-1">+ <div+ class="mt-1 rounded border border-border bg-background px-1.5 py-0.5 text-[10px] whitespace-nowrap text-muted-foreground shadow-sm"+ >{formatTime(calculatedTime())}</div></div>@@ -511,10 +521,15 @@<!-- Legend -->{#if hasData && showBuiltinLegend}<div class="flex flex-wrap gap-x-4 gap-y-1 px-2 text-xs text-muted-foreground">- {#each endpoints as endpoint, i}+ {#each endpoints as endpoint, i (i)}<div class="flex items-center gap-1.5">- <span class="h-2 w-2 rounded-full flex-shrink-0" style="background-color: {palette[i % palette.length]};"></span>- <span class="truncate max-w-[180px]" title={endpoint}>{truncateEndpoint(endpoint, 25)}</span>+ <span+ class="h-2 w-2 flex-shrink-0 rounded-full"+ style="background-color: {palette[i % palette.length]};"+ ></span>+ <span class="max-w-[180px] truncate" title={endpoint}+ >{truncateEndpoint(endpoint, 25)}</span+ ></div>{/each}</div>diff --git a/frontend/src/lib/components/dashboard/dashboard-command.svelte b/frontend/src/lib/components/dashboard/dashboard-command.svelteindex 46e86f0c..ff0a7b75 100644--- a/frontend/src/lib/components/dashboard/dashboard-command.svelte+++ b/frontend/src/lib/components/dashboard/dashboard-command.svelte@@ -1,8 +1,8 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';import * as Command from '$lib/components/ui/command';import { api } from '$lib/api';- import { goto } from '$app/navigation';- import { addStickyParamsToHref } from '$lib/utils/navigation';+ import { addStickyParamsToHref, gotoHref } from '$lib/utils/navigation';import { page } from '$app/state';import { projectsState } from '$lib/state/projects.svelte';import { authState } from '$lib/state/auth.svelte';@@ -16,7 +16,7 @@ChartLine,Check,Building2- } from 'lucide-svelte';+ } from '@lucide/svelte';type LibraryDashboard = {id: number;@@ -91,9 +91,9 @@api.get('/dashboards/library', { projectId }).catch(() => ({ organizations: [] })),api.get('/dashboard-templates', { projectId }).catch(() => ({ templates: [] })),currentOrgId- ? api.get(`/metrics/discover/org?organizationId=${currentOrgId}`, { projectId }).catch(- () => ({ metrics: [], truncated: false })- )+ ? api+ .get(`/metrics/discover/org?organizationId=${currentOrgId}`, { projectId })+ .catch(() => ({ metrics: [], truncated: false })): Promise.resolve({ metrics: [], truncated: false })]);organizations = library.organizations ?? [];@@ -110,7 +110,7 @@const target = addStickyParamsToHref(`/dashboards${params}`, 'preset', 'from', 'to');const current = page.url.pathname + page.url.search;if (current === target) return;- goto(target);+ gotoHref(target);}function runAction(action: 'create' | 'import' | 'grafana') {@@ -132,7 +132,7 @@async function selectDashboard(org: LibraryOrganization, dashboard: LibraryDashboard) {if (!currentProjectId) {- toast.error('Select a project first', { position: 'top-center' });+ toast.error('Select a project first');return;}if (dashboard.appliedProjectIds.includes(currentProjectId)) {@@ -147,7 +147,7 @@{ organizationId: currentOrgId, applyToProjectIds: [currentProjectId] },{ projectId: currentProjectId });- toast.success('Successfully copied the Dashboard', { position: 'top-center' });+ toast.success('Successfully copied the Dashboard');finishWithDashboard(copy.id);} else {const current = await api.get(`/dashboards/${dashboard.id}`, {@@ -161,12 +161,12 @@{ projectId: currentProjectId });}- toast.success('Successfully applied the Dashboard', { position: 'top-center' });+ toast.success('Successfully applied the Dashboard');finishWithDashboard(dashboard.id);}- } catch (e: any) {- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to add the dashboard', { position: 'top-center' });+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to add the dashboard');}} finally {busy = false;@@ -175,7 +175,7 @@async function installTemplate(template: Template) {if (!currentProjectId) {- toast.error('Select a project first', { position: 'top-center' });+ toast.error('Select a project first');return;}busy = true;@@ -185,11 +185,11 @@{},{ projectId: currentProjectId });- toast.success('Successfully installed the Dashboard', { position: 'top-center' });+ toast.success('Successfully installed the Dashboard');finishWithDashboard(dashboard.id);- } catch (e: any) {- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to install the template', { position: 'top-center' });+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to install the template');}} finally {busy = false;@@ -215,15 +215,27 @@<Command.List><Command.Empty>No results found.</Command.Empty><Command.Group heading="Actions">- <Command.Item value="action-new-dashboard" keywords={['new', 'create', 'dashboard']} onSelect={() => runAction('create')}>+ <Command.Item+ value="action-new-dashboard"+ keywords={['new', 'create', 'dashboard']}+ onSelect={() => runAction('create')}+ ><Plus /><span>New Dashboard</span></Command.Item>- <Command.Item value="action-import-json" keywords={['import', 'json', 'file']} onSelect={() => runAction('import')}>+ <Command.Item+ value="action-import-json"+ keywords={['import', 'json', 'file']}+ onSelect={() => runAction('import')}+ ><Upload /><span>Import JSON</span></Command.Item>- <Command.Item value="action-import-grafana" keywords={['import', 'grafana', 'convert']} onSelect={() => runAction('grafana')}>+ <Command.Item+ value="action-import-grafana"+ keywords={['import', 'grafana', 'convert']}+ onSelect={() => runAction('grafana')}+ ><FolderInput /><span>Import from Grafana</span></Command.Item>@@ -276,7 +288,8 @@<div class="flex min-w-0 flex-1 flex-col"><span class="truncate">{template.name}</span><span class="truncate text-xs text-muted-foreground">- {template.category} · {template.widgetCount} widget{template.widgetCount === 1+ {template.category} · {template.widgetCount} widget{template.widgetCount ===+ 1? '': 's'}{#if template.description}· {template.description}{/if}diff --git a/frontend/src/lib/components/dashboard/metric-card.svelte b/frontend/src/lib/components/dashboard/metric-card.svelteindex 682ede90..57e8b9c7 100644--- a/frontend/src/lib/components/dashboard/metric-card.svelte+++ b/frontend/src/lib/components/dashboard/metric-card.svelte@@ -24,10 +24,7 @@}>();// Check if we have multi-server data- const hasMultiServerData = $derived(- metric.servers && metric.servers.length > 1- );-+ const hasMultiServerData = $derived(metric.servers && metric.servers.length > 1);// Calculate X domain from timeDomain or dataconst xDomainValue = $derived(() => {@@ -53,11 +50,13 @@color: serverColorMap[server.serverName] || '#3b82f6'}));}- return [{- key: 'value',- data: metric.trend,- color: '#3b82f6'- }];+ return [+ {+ key: 'value',+ data: metric.trend,+ color: '#3b82f6'+ }+ ];});const hasData = $derived(() => {@@ -86,7 +85,8 @@servers={metric.servers}{serverColorMap}unit={metric.unit}- formatValue={(v) => metric.formatValue ? metric.formatValue(v) : formatMetricLabel(v, metric.unit)}+ formatValue={(v) =>+ metric.formatValue ? metric.formatValue(v) : formatMetricLabel(v, metric.unit)}{sharedHoverTime}{isSourceChart}{onHoverTimeChange}diff --git a/frontend/src/lib/components/dashboard/server-filter.svelte b/frontend/src/lib/components/dashboard/server-filter.svelteindex 7cb0dc3e..bd242145 100644--- a/frontend/src/lib/components/dashboard/server-filter.svelte+++ b/frontend/src/lib/components/dashboard/server-filter.svelte@@ -4,7 +4,7 @@import { Input } from '$lib/components/ui/input';import { Separator } from '$lib/components/ui/separator';import { Badge } from '$lib/components/ui/badge';- import { CirclePlus, Check } from 'lucide-svelte';+ import { CirclePlus, Check } from '@lucide/svelte';interface Props {availableServers: string[];@@ -25,9 +25,7 @@// Filter servers based on searchconst filteredServers = $derived(- [...availableServers]- .sort()- .filter(s => s.toLowerCase().includes(searchQuery.toLowerCase()))+ [...availableServers].sort().filter((s) => s.toLowerCase().includes(searchQuery.toLowerCase())));// Marker for "none selected" state@@ -51,7 +49,8 @@// Has active filters (some but not all selected, or none selected)const hasActiveFilters = $derived(- isNoneSelected || (selectedServers.length > 0 && selectedServers.length < availableServers.length)+ isNoneSelected ||+ (selectedServers.length > 0 && selectedServers.length < availableServers.length));function isSelected(serverName: string): boolean {@@ -80,10 +79,10 @@newSelection = [serverName];} else if (selectedServers.length === 0) {// Currently "all selected" - clicking one deselects it (select all except this one)- newSelection = availableServers.filter(s => s !== serverName);+ newSelection = availableServers.filter((s) => s !== serverName);} else if (selectedServers.includes(serverName)) {// Remove from selection- newSelection = selectedServers.filter(s => s !== serverName);+ newSelection = selectedServers.filter((s) => s !== serverName);// If removing last one, go to none selected stateif (newSelection.length === 0) {newSelection = [NONE_SELECTED];@@ -123,20 +122,21 @@{#if displayServers().length > 0}<Separator orientation="vertical" class="mx-2 h-4" /><div class="flex flex-wrap gap-1">- {#each displayServers() as server}+ {#each displayServers() as server, __index (__index)}{@const color = serverColorMap[server] || '#888888'}- <Badge variant="secondary" class="rounded-sm px-1.5 py-0 font-normal flex items-center gap-1">- <span- class="h-2 w-2 rounded-full flex-shrink-0"- style="background-color: {color};"+ <Badge+ variant="secondary"+ class="flex items-center gap-1 rounded-sm px-1.5 py-0 font-normal"+ >+ <span class="h-2 w-2 flex-shrink-0 rounded-full" style="background-color: {color};"></span>- <span class="truncate max-w-[80px]">{server}</span>+ <span class="max-w-[80px] truncate">{server}</span></Badge>{/each}</div>{:else if isNoneSelected}<Separator orientation="vertical" class="mx-2 h-4" />- <span class="text-muted-foreground text-xs">None selected</span>+ <span class="text-xs text-muted-foreground">None selected</span>{/if}</Button></Popover.Trigger>@@ -144,26 +144,16 @@<Popover.Content class="w-[200px] p-0" align="start"><!-- Search Input --><div class="p-2">- <Input- placeholder="Servers"- bind:value={searchQuery}- class="h-8"- />+ <Input placeholder="Servers" bind:value={searchQuery} class="h-8" /></div><!-- Quick Actions -->{#if availableServers.length > 0}<div class="flex items-center justify-between border-t px-2 py-1.5">- <button- class="text-xs text-muted-foreground hover:text-foreground"- onclick={selectAll}- >+ <button class="text-xs text-muted-foreground hover:text-foreground" onclick={selectAll}>Select all</button>- <button- class="text-xs text-muted-foreground hover:text-foreground"- onclick={selectNone}- >+ <button class="text-xs text-muted-foreground hover:text-foreground" onclick={selectNone}>Deselect all</button></div>@@ -171,40 +161,37 @@<!-- Server List --><div class="max-h-[200px] overflow-y-auto">- {#each filteredServers as serverName}+ {#each filteredServers as serverName, __index (__index)}{@const color = serverColorMap[serverName] || '#888888'}{@const selected = isSelected(serverName)}<button- class="relative flex w-full cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground"+ class="relative flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none hover:bg-accent hover:text-accent-foreground"onclick={() => toggleServer(serverName)}>- <div class="flex h-4 w-4 items-center justify-center rounded-sm border border-primary {selected ? 'bg-primary text-primary-foreground' : 'opacity-50'}">+ <div+ class="flex h-4 w-4 items-center justify-center rounded-sm border border-primary {selected+ ? 'bg-primary text-primary-foreground'+ : 'opacity-50'}"+ >{#if selected}<Check class="h-3 w-3" />{/if}</div>- <span- class="h-2 w-2 rounded-full flex-shrink-0"- style="background-color: {color};"+ <span class="h-2 w-2 flex-shrink-0 rounded-full" style="background-color: {color};"></span><span class="flex-1 truncate text-left">{serverName}</span></button>{/each}{#if filteredServers.length === 0}- <div class="py-6 text-center text-sm text-muted-foreground">- No servers found.- </div>+ <div class="py-6 text-center text-sm text-muted-foreground">No servers found.</div>{/if}</div><!-- Clear Filters -->{#if hasActiveFilters}<Separator />- <button- class="w-full py-2 text-center text-sm hover:bg-accent"- onclick={clearFilters}- >+ <button class="w-full py-2 text-center text-sm hover:bg-accent" onclick={clearFilters}>Clear filters</button>{/if}diff --git a/frontend/src/lib/components/dashboard/tag-filter.svelte b/frontend/src/lib/components/dashboard/tag-filter.svelteindex 87979e30..7e14f6b3 100644--- a/frontend/src/lib/components/dashboard/tag-filter.svelte+++ b/frontend/src/lib/components/dashboard/tag-filter.svelte@@ -1,7 +1,7 @@<script lang="ts">import { Button } from '$lib/components/ui/button';import * as Select from '$lib/components/ui/select';- import { X } from 'lucide-svelte';+ import { X } from '@lucide/svelte';let {tagKeys = [],@@ -50,17 +50,12 @@</script><div class="flex flex-wrap items-center gap-2">- {#each Object.entries(activeFilters) as [key, value]}- <div- class="flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-1 text-xs"- >+ {#each Object.entries(activeFilters) as [key, value], __index (__index)}+ <div class="flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-1 text-xs"><span class="font-medium">{key}</span><span class="text-muted-foreground">=</span><span>{value}</span>- <button- class="ml-1 rounded hover:bg-muted"- onclick={() => removeFilter(key)}- >+ <button class="ml-1 rounded hover:bg-muted" onclick={() => removeFilter(key)}><X class="h-3 w-3" /></button></div>@@ -82,7 +77,7 @@{/if}</Select.Trigger><Select.Content>- {#each tagValueOptions[selectedKey] ?? [] as val}+ {#each tagValueOptions[selectedKey] ?? [] as val, __index (__index)}<Select.Item value={val}>{val}</Select.Item>{/each}</Select.Content>@@ -97,11 +92,9 @@if (v) handleKeySelect(v);}}>- <Select.Trigger class="h-7 w-[140px] text-xs">- + Filter by tag- </Select.Trigger>+ <Select.Trigger class="h-7 w-[140px] text-xs">+ Filter by tag</Select.Trigger><Select.Content>- {#each availableKeys as key}+ {#each availableKeys as key, __index (__index)}<Select.Item value={key}>{key}</Select.Item>{/each}</Select.Content>diff --git a/frontend/src/lib/components/dashboard/widget-config-panel.svelte b/frontend/src/lib/components/dashboard/widget-config-panel.svelteindex b8506884..38fc2fc9 100644--- a/frontend/src/lib/components/dashboard/widget-config-panel.svelte+++ b/frontend/src/lib/components/dashboard/widget-config-panel.svelte@@ -8,29 +8,25 @@import { THRESHOLD_COLOR_NAMES, resolveThresholdColor } from './gauge-thresholds';import { api } from '$lib/api';import { projectsState } from '$lib/state/projects.svelte';- import { Plus, Check, X } from 'lucide-svelte';+ import { Plus, Check, X } from '@lucide/svelte';import { ErrorAlert } from '$lib/components/ui/error-alert';- import type { DiscoveredMetric } from '$lib/types/dashboard';-- type WidgetSource = {- type: 'metric';- name: string;- aggregation: string;- tagFilters?: Record<string, string>;- groupBy?: string;- label?: string;- };+ import type {+ DashboardWidget,+ DashboardWidgetConfig,+ DashboardWidgetSource,+ DiscoveredMetric+ } from '$lib/types/dashboard';const CHART_TYPES = ['line_chart', 'area_chart', 'stacked_area'];- function legendFromConfig(config: any): 'auto' | 'on' | 'off' {+ function legendFromConfig(config?: DashboardWidgetConfig): 'auto' | 'on' | 'off' {if (config?.showLegend === true) return 'on';if (config?.showLegend === false) return 'off';return 'auto';}function thresholdsFromConfig(- config: any,+ config: DashboardWidgetConfig | undefined,savedType: string | undefined): Array<{ value: string; color: string }> {if (Array.isArray(config?.thresholds) && config.thresholds.length > 0) {@@ -52,10 +48,10 @@onCancel} = $props<{open: boolean;- widget: { id?: number | string; title: string; widgetType: string; config: any } | null;+ widget: (Omit<DashboardWidget, 'id'> & { id?: number | string }) | null;availableMetrics: DiscoveredMetric[];error?: string;- onSave: (data: { title: string; widgetType: string; config: any }) => void;+ onSave: (data: { title: string; widgetType: string; config: DashboardWidgetConfig }) => void;onCancel: () => void;}>();@@ -66,13 +62,17 @@let widgetType = $state(initialWidget?.widgetType ?? 'line_chart');let unit = $state(initialWidget?.config?.unit ?? '');let unitManuallySet = $state(!!initialWidget?.config?.unit);- let sources = $state<WidgetSource[]>(+ let sources = $state<DashboardWidgetSource[]>(initialWidget?.config?.sources ?? [{ type: 'metric', name: '', aggregation: 'avg' }]);let legend = $state<'auto' | 'on' | 'off'>(legendFromConfig(initialWidget?.config));let showSparkline = $state(!!initialWidget?.config?.showSparkline);- let gaugeMin = $state(initialWidget?.config?.min != null ? String(initialWidget.config.min) : '0');- let gaugeMax = $state(initialWidget?.config?.max != null ? String(initialWidget.config.max) : '100');+ let gaugeMin = $state(+ initialWidget?.config?.min != null ? String(initialWidget.config.min) : '0'+ );+ let gaugeMax = $state(+ initialWidget?.config?.max != null ? String(initialWidget.config.max) : '100'+ );let baseColor = $state(initialWidget?.config?.baseColor ?? 'green');let thresholds = $state<Array<{ value: string; color: string }>>(thresholdsFromConfig(initialWidget?.config, initialWidget?.widgetType)@@ -97,9 +97,7 @@});function addThreshold() {- const values = thresholds- .map((t) => parseFloat(t.value))- .filter((v) => Number.isFinite(v));+ const values = thresholds.map((t) => parseFloat(t.value)).filter((v) => Number.isFinite(v));const nextValue = values.length > 0 ? Math.max(...values) + 10 : 80;const usedColors = new Set(thresholds.map((t) => t.color));const nextColor =@@ -157,13 +155,13 @@function handleSave() {const validSources = sources- .filter((s: WidgetSource) => s.name)- .map((s: WidgetSource) => {+ .filter((s: DashboardWidgetSource) => s.name)+ .map((s: DashboardWidgetSource) => {const { label, ...rest } = s;return label?.trim() ? { ...rest, label: label.trim() } : rest;});const displayTitle = title.trim() || validSources[0]?.name || '';- const config: Record<string, any> = { sources: validSources };+ const config: DashboardWidgetConfig = { sources: validSources };if (unit) config.unit = unit;if (widget?.config?.colSpan != null) config.colSpan = widget.config.colSpan;if (widget?.config?.size != null) config.size = widget.config.size;@@ -223,7 +221,17 @@}}><Select.Trigger>- {({ line_chart: 'Line Chart', area_chart: 'Area Chart', stacked_area: 'Stacked Area', bar_chart: 'Bar Chart', single_value: 'Single Value', gauge: 'Gauge', table: 'Table' } as Record<string, string>)[widgetType] ?? widgetType}+ {(+ {+ line_chart: 'Line Chart',+ area_chart: 'Area Chart',+ stacked_area: 'Stacked Area',+ bar_chart: 'Bar Chart',+ single_value: 'Single Value',+ gauge: 'Gauge',+ table: 'Table'+ } as Record<string, string>+ )[widgetType] ?? widgetType}</Select.Trigger><Select.Content><Select.Item value="line_chart">Line Chart</Select.Item>@@ -248,7 +256,12 @@}}><Select.Trigger>- {({ auto: 'Auto (when multiple series)', on: 'Always', off: 'Never' } as Record<string, string>)[legend]}+ {(+ { auto: 'Auto (when multiple series)', on: 'Always', off: 'Never' } as Record<+ string,+ string+ >+ )[legend]}</Select.Trigger><Select.Content><Select.Item value="auto">Auto (when multiple series)</Select.Item>@@ -292,22 +305,21 @@{#if widgetType === 'gauge' || widgetType === 'single_value'}<div><span class="text-sm font-medium">Thresholds</span>- <p class="text-xs text-muted-foreground mb-2">+ <p class="mb-2 text-xs text-muted-foreground">The value takes the color of the highest threshold it crosses</p><div class="space-y-2">- {#each thresholds as threshold, i}+ {#each thresholds as threshold, i (i)}<div class="flex items-center gap-2">- <Input- type="number"- bind:value={thresholds[i].value}- class="h-8 w-28 text-xs"- />+ <Input type="number" bind:value={thresholds[i].value} class="h-8 w-28 text-xs" /><div class="flex items-center gap-1.5">- {#each THRESHOLD_COLOR_NAMES as colorName}+ {#each THRESHOLD_COLOR_NAMES as colorName, __index (__index)}<buttontype="button"- class="h-5 w-5 cursor-pointer rounded-full transition-transform {threshold.color === colorName ? 'ring-2 ring-ring ring-offset-2 ring-offset-background' : 'opacity-50 hover:opacity-100'}"+ class="h-5 w-5 cursor-pointer rounded-full transition-transform {threshold.color ===+ colorName+ ? 'ring-2 ring-ring ring-offset-2 ring-offset-background'+ : 'opacity-50 hover:opacity-100'}"style="background-color: {resolveThresholdColor(colorName)};"aria-label={colorName}title={colorName}@@ -329,10 +341,13 @@<div class="flex items-center gap-2"><span class="w-28 px-3 text-xs text-muted-foreground">Base</span><div class="flex items-center gap-1.5">- {#each THRESHOLD_COLOR_NAMES as colorName}+ {#each THRESHOLD_COLOR_NAMES as colorName, __index (__index)}<buttontype="button"- class="h-5 w-5 cursor-pointer rounded-full transition-transform {baseColor === colorName ? 'ring-2 ring-ring ring-offset-2 ring-offset-background' : 'opacity-50 hover:opacity-100'}"+ class="h-5 w-5 cursor-pointer rounded-full transition-transform {baseColor ===+ colorName+ ? 'ring-2 ring-ring ring-offset-2 ring-offset-background'+ : 'opacity-50 hover:opacity-100'}"style="background-color: {resolveThresholdColor(colorName)};"aria-label={colorName}title={colorName}@@ -354,12 +369,14 @@id="widget-unit"bind:value={unit}placeholder="Auto-detected from metric"- oninput={() => { unitManuallySet = unit.length > 0; }}+ oninput={() => {+ unitManuallySet = unit.length > 0;+ }}/>- <p class="text-xs text-muted-foreground mt-1">%, ms, s, MB, GB, bytes, count, ns</p>+ <p class="mt-1 text-xs text-muted-foreground">%, ms, s, MB, GB, bytes, count, ns</p></div>- {#each sources as source, i}+ {#each sources as source, i (i)}<div class="space-y-2 rounded-md border p-3"><div class="flex items-center gap-2"><Select.Root@@ -371,7 +388,7 @@><Select.Trigger class="flex-1">{source.name || 'Select metric'}</Select.Trigger><Select.Content>- {#each availableMetrics as m}+ {#each availableMetrics as m, __index (__index)}<Select.Item value={m.name}>{m.name}</Select.Item>{/each}</Select.Content>@@ -429,7 +446,7 @@><Select.Content><Select.Item value="">None</Select.Item>- {#each getMetricTagKeys(source.name) as key}+ {#each getMetricTagKeys(source.name) as key, __index (__index)}<Select.Item value={key}>{key}</Select.Item>{/each}</Select.Content>@@ -442,7 +459,9 @@<Sheet.Footer class="flex-row justify-end border-t px-6"><Button variant="outline" onclick={handleClose}>Cancel</Button><Button variant={widget?.id ? 'default' : 'success'} onclick={handleSave}>- {#if widget?.id}<Check class="mr-1 h-4 w-4" /> Update Widget{:else}<Plus class="mr-1 h-4 w-4" /> New Widget{/if}+ {#if widget?.id}<Check class="mr-2 h-4 w-4" /> Update Widget{:else}<Plus+ class="mr-2 h-4 w-4"+ /> New Widget{/if}</Button></Sheet.Footer></Sheet.Content>diff --git a/frontend/src/lib/components/dashboard/widget-grid.svelte b/frontend/src/lib/components/dashboard/widget-grid.svelteindex 8d522140..84d56e53 100644--- a/frontend/src/lib/components/dashboard/widget-grid.svelte+++ b/frontend/src/lib/components/dashboard/widget-grid.svelte@@ -14,14 +14,15 @@ArrowLeftRight,ArrowUpDown,Check- } from 'lucide-svelte';+ } from '@lucide/svelte';import WidgetRenderer from './widget-renderer.svelte';+ import type { DashboardWidgetConfig } from '$lib/types/dashboard';type Widget = {id: number | string;title: string;widgetType: string;- config: any;+ config: DashboardWidgetConfig;position: number;isStarred?: boolean;};@@ -63,9 +64,7 @@return null;}const aggregations = new Set<string>(- (widget.config?.sources ?? []).map(- (s: { aggregation?: string }) => s.aggregation || 'avg'- )+ (widget.config?.sources ?? []).map((s: { aggregation?: string }) => s.aggregation || 'avg'));return aggregations.size === 1 ? [...aggregations][0] : null;}@@ -188,7 +187,7 @@({widget.config.unit})</span>{/if}{#if widgetAggregation(widget)}<spanclass="text-xs font-normal text-muted-foreground"- > · {widgetAggregation(widget)}</span+ > · {widgetAggregation(widget)}</span>{/if}</Card.Title></div>diff --git a/frontend/src/lib/components/dashboard/widget-renderer.svelte b/frontend/src/lib/components/dashboard/widget-renderer.svelteindex c6ed9186..3572b864 100644--- a/frontend/src/lib/components/dashboard/widget-renderer.svelte+++ b/frontend/src/lib/components/dashboard/widget-renderer.svelte@@ -5,37 +5,19 @@import D3Gauge from './d3-gauge.svelte';import WidgetTable from './widget-table.svelte';import Sparkline from './sparkline.svelte';- import { activeThresholdColor, type ThresholdStep } from './gauge-thresholds';- import { SvelteSet } from 'svelte/reactivity';+ import { activeThresholdColor } from './gauge-thresholds';+ import { SvelteMap, SvelteSet } from 'svelte/reactivity';import { api } from '$lib/api';import { projectsState } from '$lib/state/projects.svelte';import { LoadingCircle } from '$lib/components/ui/loading-circle';- import type { MetricTrendPoint, MetricQueryResponse } from '$lib/types/dashboard';+ import type {+ DashboardWidgetConfig,+ DashboardWidgetSource,+ MetricTrendPoint,+ MetricQueryResponse+ } from '$lib/types/dashboard';import { formatMetricLabel, formatMetricValue } from '$lib/utils/metric-format';- type WidgetSource = {- type: 'metric';- name: string;- tagFilters?: Record<string, string>;- aggregation: string;- groupBy?: string;- label?: string;- };-- type WidgetConfig = {- sources?: WidgetSource[];- yAxisLabel?: string;- showLegend?: boolean;- unit?: string;- colSpan?: 1 | 2 | 3;- size?: 'sm' | 'md' | 'lg';- showSparkline?: boolean;- min?: number;- max?: number;- baseColor?: string;- thresholds?: ThresholdStep[];- };-let {widget,fromDateUTC,@@ -50,7 +32,7 @@id: number;title: string;widgetType: string;- config: WidgetConfig;+ config: DashboardWidgetConfig;};fromDateUTC: string;toDateUTC: string;@@ -66,7 +48,14 @@let singleValue = $state<number | null>(null);let resolvedUnit = $state('');- const colors = ['var(--chart-1)', 'var(--chart-2)', 'var(--chart-3)', 'var(--chart-4)', 'var(--chart-5)', 'var(--crit)'];+ const colors = [+ 'var(--chart-1)',+ 'var(--chart-2)',+ 'var(--chart-3)',+ 'var(--chart-4)',+ 'var(--chart-5)',+ 'var(--crit)'+ ];const effectiveUnit = $derived(widget.config.unit ?? resolvedUnit);@@ -133,7 +122,7 @@const newSeries: Array<{ key: string; data: MetricTrendPoint[]; color: string }> = [];let colorIdx = 0;- const queries = sources.map((s: WidgetSource) => ({+ const queries = sources.map((s: DashboardWidgetSource) => ({name: s.name,aggregation: s.aggregation || 'avg',tagFilters: s.tagFilters,@@ -146,8 +135,8 @@{ projectId: projectsState.currentProjectId ?? undefined });- const units = new Set<string>();- const usedKeys = new Set<string>();+ const units = new SvelteSet<string>();+ const usedKeys = new SvelteSet<string>();for (const [idx, result] of response.results.entries()) {if (result.unit) units.add(result.unit);const baseName = sources[idx]?.label?.trim() || result.name;@@ -207,7 +196,7 @@// which the charts' fixed default would clipconst axisMaxValue = $derived.by(() => {if (widget.widgetType === 'stacked_area') {- const sums = new Map<number, number>();+ const sums = new SvelteMap<number, number>();for (const s of visibleSeries) {for (const p of s.data) {const t = p.timestamp.getTime();@@ -233,56 +222,102 @@});</script>-<div class="flex h-full w-full min-h-[200px] flex-col">+<div class="flex h-full min-h-[200px] w-full flex-col"><div class="min-h-0 w-full flex-1" bind:clientHeight={chartAreaHeight}>- {#if loading}- <div class="flex h-full items-center justify-center">- <LoadingCircle size="md" />- </div>- {:else if widget.widgetType === 'single_value'}- <div class="flex h-full flex-col items-center justify-center gap-2">- <span class="text-3xl font-bold" style={singleValueColor ? `color: ${singleValueColor};` : ''}>- {singleValue !== null ? formatMetricLabel(singleValue, effectiveUnit) : '-'}- </span>- {#if widget.config.showSparkline && series[0]?.data && series[0].data.length > 1}- <div class="w-full px-6">- <Sparkline data={series[0].data} color={singleValueColor ?? series[0].color} />- </div>- {/if}- </div>- {:else if widget.widgetType === 'gauge'}- {#if singleValue !== null}- <D3Gauge- value={singleValue}- min={widget.config.min ?? 0}- max={widget.config.max ?? 100}- baseColor={widget.config.baseColor}- thresholds={widget.config.thresholds}- formatValue={(v) => formatMetricLabel(v, effectiveUnit)}- />- {:else}- <div class="flex h-full items-center justify-center text-sm text-muted-foreground">- No data+ {#if loading}+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="md" /></div>- {/if}- {:else if widget.widgetType === 'bar_chart'}- {#if barData.length > 0}- <D3HorizontalBarChart data={barData} height={chartHeight} unit={effectiveUnit} formatValue={(v) => formatMetricLabel(v, effectiveUnit)} />- {:else}- <div class="flex h-full items-center justify-center text-sm text-muted-foreground">- No data- </div>- {/if}- {:else if widget.widgetType === 'table'}- {#if series.length > 0}- <WidgetTable {series} unit={effectiveUnit} />- {:else}- <div class="flex h-full items-center justify-center text-sm text-muted-foreground">- No data+ {:else if widget.widgetType === 'single_value'}+ <div class="flex h-full flex-col items-center justify-center gap-2">+ <span+ class="text-3xl font-bold"+ style={singleValueColor ? `color: ${singleValueColor};` : ''}+ >+ {singleValue !== null ? formatMetricLabel(singleValue, effectiveUnit) : '-'}+ </span>+ {#if widget.config.showSparkline && series[0]?.data && series[0].data.length > 1}+ <div class="w-full px-6">+ <Sparkline data={series[0].data} color={singleValueColor ?? series[0].color} />+ </div>+ {/if}</div>- {/if}- {:else if widget.widgetType === 'area_chart'}- {#if series.length > 0}+ {:else if widget.widgetType === 'gauge'}+ {#if singleValue !== null}+ <D3Gauge+ value={singleValue}+ min={widget.config.min ?? 0}+ max={widget.config.max ?? 100}+ baseColor={widget.config.baseColor}+ thresholds={widget.config.thresholds}+ formatValue={(v) => formatMetricLabel(v, effectiveUnit)}+ />+ {:else}+ <div class="flex h-full items-center justify-center text-sm text-muted-foreground">+ No data+ </div>+ {/if}+ {:else if widget.widgetType === 'bar_chart'}+ {#if barData.length > 0}+ <D3HorizontalBarChart+ data={barData}+ height={chartHeight}+ unit={effectiveUnit}+ formatValue={(v) => formatMetricLabel(v, effectiveUnit)}+ />+ {:else}+ <div class="flex h-full items-center justify-center text-sm text-muted-foreground">+ No data+ </div>+ {/if}+ {:else if widget.widgetType === 'table'}+ {#if series.length > 0}+ <WidgetTable {series} unit={effectiveUnit} />+ {:else}+ <div class="flex h-full items-center justify-center text-sm text-muted-foreground">+ No data+ </div>+ {/if}+ {:else if widget.widgetType === 'area_chart'}+ {#if series.length > 0}+ <D3LineChart+ series={visibleSeries}+ xDomain={timeDomain ?? undefined}+ height={chartHeight}+ padding={chartPadding}+ {onRangeSelect}+ data={visibleSeries[0]?.data ?? []}+ areaFill={true}+ unit={effectiveUnit}+ formatValue={(v) => formatMetricLabel(v, effectiveUnit)}+ {sharedHoverTime}+ {isSourceChart}+ {onHoverTimeChange}+ />+ {:else}+ <div class="flex h-full items-center justify-center text-sm text-muted-foreground">+ No data+ </div>+ {/if}+ {:else if widget.widgetType === 'stacked_area'}+ {#if series.length > 0}+ <D3StackedAreaChart+ endpoints={visibleSeries.map((s) => s.key)}+ series={stackedPoints}+ height={chartHeight}+ padding={chartPadding}+ unit={effectiveUnit}+ formatValue={(v) => formatMetricLabel(v, effectiveUnit)}+ {onRangeSelect}+ colors={visibleSeries.map((s) => s.color)}+ showBuiltinLegend={false}+ />+ {:else}+ <div class="flex h-full items-center justify-center text-sm text-muted-foreground">+ No data+ </div>+ {/if}+ {:else if series.length > 0}<D3LineChartseries={visibleSeries}xDomain={timeDomain ?? undefined}@@ -290,7 +325,6 @@padding={chartPadding}{onRangeSelect}data={visibleSeries[0]?.data ?? []}- areaFill={true}unit={effectiveUnit}formatValue={(v) => formatMetricLabel(v, effectiveUnit)}{sharedHoverTime}@@ -302,43 +336,6 @@No data</div>{/if}- {:else if widget.widgetType === 'stacked_area'}- {#if series.length > 0}- <D3StackedAreaChart- endpoints={visibleSeries.map((s) => s.key)}- series={stackedPoints}- height={chartHeight}- padding={chartPadding}- unit={effectiveUnit}- formatValue={(v) => formatMetricLabel(v, effectiveUnit)}- {onRangeSelect}- colors={visibleSeries.map((s) => s.color)}- showBuiltinLegend={false}- />- {:else}- <div class="flex h-full items-center justify-center text-sm text-muted-foreground">- No data- </div>- {/if}- {:else if series.length > 0}- <D3LineChart- series={visibleSeries}- xDomain={timeDomain ?? undefined}- height={chartHeight}- padding={chartPadding}- {onRangeSelect}- data={visibleSeries[0]?.data ?? []}- unit={effectiveUnit}- formatValue={(v) => formatMetricLabel(v, effectiveUnit)}- {sharedHoverTime}- {isSourceChart}- {onHoverTimeChange}- />- {:else}- <div class="flex h-full items-center justify-center text-sm text-muted-foreground">- No data- </div>- {/if}</div>{#if legendVisible && !loading}@@ -346,12 +343,19 @@{#each series as s (s.key)}<buttontype="button"- class="flex items-center gap-1.5 text-xs transition-opacity {hiddenSeries.has(s.key) ? 'opacity-40' : ''}"+ class="flex items-center gap-1.5 text-xs transition-opacity {hiddenSeries.has(s.key)+ ? 'opacity-40'+ : ''}"onclick={() => toggleSeries(s.key)}title={s.key}>- <span class="h-2 w-2 flex-shrink-0 rounded-full" style="background-color: {s.color};"></span>- <span class="max-w-[180px] truncate text-muted-foreground {hiddenSeries.has(s.key) ? 'line-through' : ''}">{s.key}</span>+ <span class="h-2 w-2 flex-shrink-0 rounded-full" style="background-color: {s.color};"+ ></span>+ <span+ class="max-w-[180px] truncate text-muted-foreground {hiddenSeries.has(s.key)+ ? 'line-through'+ : ''}">{s.key}</span+ ></button>{/each}</div>diff --git a/frontend/src/lib/components/dashboard/widget-table.svelte b/frontend/src/lib/components/dashboard/widget-table.svelteindex 2e0e745f..912dad6a 100644--- a/frontend/src/lib/components/dashboard/widget-table.svelte+++ b/frontend/src/lib/components/dashboard/widget-table.svelte@@ -44,7 +44,7 @@<div class="overflow-auto"><Table.Root><Table.Body>- {#each stats() as stat}+ {#each stats() as stat, __index (__index)}<Table.Row><Table.Cell class="font-medium">{stat.label}</Table.Cell><Table.Cell class="text-right">{fmt(stat.value)}</Table.Cell>diff --git a/frontend/src/lib/components/distributed-trace/distributed-trace-card.svelte b/frontend/src/lib/components/distributed-trace/distributed-trace-card.svelteindex fd1bc2ca..5e31cce3 100644--- a/frontend/src/lib/components/distributed-trace/distributed-trace-card.svelte+++ b/frontend/src/lib/components/distributed-trace/distributed-trace-card.svelte@@ -1,15 +1,17 @@<script lang="ts">import { onMount } from 'svelte';- import { goto } from '$app/navigation';+ import { gotoHref } from '$lib/utils/navigation';import { api } from '$lib/api';import * as Card from '$lib/components/ui/card';import { Badge } from '$lib/components/ui/badge';import { Button } from '$lib/components/ui/button';import { LoadingCircle } from '$lib/components/ui/loading-circle';- import { formatDuration, getStatusColor, formatDateTime } from '$lib/utils/formatters';- import { getTimezone } from '$lib/state/timezone.svelte';- import { ArrowRight, GitBranch } from 'lucide-svelte';- import type { DistributedTraceResponse, DistributedTraceNode } from '$lib/types/distributed-trace';+ import { formatDuration, getStatusColor } from '$lib/utils/formatters';+ import { ArrowRight, GitBranch } from '@lucide/svelte';+ import type {+ DistributedTraceResponse,+ DistributedTraceNode+ } from '$lib/types/distributed-trace';interface Props {distributedTraceId: string;@@ -34,22 +36,18 @@return false;}- const timezone = $derived(getTimezone());-let response = $state<DistributedTraceResponse | null>(null);let loading = $state(true);- let error = $state('');async function loadTrace() {loading = true;- error = '';try {response = (await api.post(`/distributed-traces/${distributedTraceId}`,recordedAt ? { recordedAt } : {})) as DistributedTraceResponse;- } catch (e: any) {- error = e.message || 'Failed to load distributed trace';+ } catch {+ response = null;} finally {loading = false;}@@ -58,17 +56,17 @@function navigateToNode(node: DistributedTraceNode) {const project = `&projectId=${encodeURIComponent(node.projectId)}`;if (node.traceType === 'task' && node.task) {- goto(+ gotoHref(`/tasks/${encodeURIComponent(node.task.taskName)}/${node.task.id}?preset=24h&t=${encodeURIComponent(node.task.recordedAt)}${project}`);} else if (node.traceType === 'ai_trace' && node.aiTrace) {- goto(+ gotoHref(`/ai-traces/${encodeURIComponent(node.aiTrace.traceName)}/${node.aiTrace.id}?preset=24h&t=${encodeURIComponent(node.aiTrace.recordedAt)}${project}`);} else if (node.traceType === 'exception' && node.exception) {- goto(`/issues/${node.exception.exceptionHash}?preset=24h${project}`);+ gotoHref(`/issues/${node.exception.exceptionHash}?preset=24h${project}`);} else if (node.endpoint) {- goto(+ gotoHref(`/endpoints/${encodeURIComponent(node.endpoint.endpoint)}/${node.endpoint.id}?preset=24h&t=${encodeURIComponent(node.endpoint.recordedAt)}${project}`);}@@ -86,9 +84,7 @@<GitBranch class="h-5 w-5 text-muted-foreground" /><Card.Title>Distributed Trace</Card.Title></div>- <Card.Description>- This trace spans across multiple services- </Card.Description>+ <Card.Description>This trace spans across multiple services</Card.Description></Card.Header><Card.Content><div class="flex items-center justify-center py-6">@@ -103,13 +99,11 @@<GitBranch class="h-5 w-5 text-muted-foreground" /><Card.Title>Distributed Trace</Card.Title></div>- <Card.Description>- This trace spans across multiple services- </Card.Description>+ <Card.Description>This trace spans across multiple services</Card.Description></Card.Header><Card.Content><div class="space-y-3">- {#each response.nodes as node, i}+ {#each response.nodes as node, i (i)}<div class="flex items-center gap-3 rounded-md border p-3 {i > 0 ? 'ml-6' : ''}"><div class="flex min-w-0 flex-1 items-center gap-3"><Badge variant="outline" class="shrink-0">{node.projectName}</Badge>@@ -130,14 +124,18 @@</span>{/if}{#if node.traceType === 'ai_trace' && node.aiTrace}- <Badge variant="secondary" class="shrink-0">{node.aiTrace.provider || node.aiTrace.model || 'AI'}</Badge>+ <Badge variant="secondary" class="shrink-0"+ >{node.aiTrace.provider || node.aiTrace.model || 'AI'}</Badge+ >{/if}{#if node.traceType !== 'exception'}<span class="shrink-0 font-mono text-sm text-muted-foreground">{formatDuration(- node.traceType === 'task' ? node.task?.duration ?? 0- : node.traceType === 'ai_trace' ? node.aiTrace?.duration ?? 0- : node.endpoint?.duration ?? 0+ node.traceType === 'task'+ ? (node.task?.duration ?? 0)+ : node.traceType === 'ai_trace'+ ? (node.aiTrace?.duration ?? 0)+ : (node.endpoint?.duration ?? 0))}</span>{/if}@@ -146,15 +144,15 @@{/if}</div>{#if isCurrentNode(node)}- <Badge class="bg-blue-500 hover:bg-blue-500 text-white">You're here</Badge>- {:else}- <Button variant="ghost" size="sm" onclick={() => navigateToNode(node)}>- View- <ArrowRight class="ml-1 h-3 w-3" />- </Button>- {/if}+ <Badge class="bg-blue-500 text-white hover:bg-blue-500">You're here</Badge>+ {:else}+ <Button variant="ghost" size="sm" onclick={() => navigateToNode(node)}>+ View+ <ArrowRight class="ml-1 h-3 w-3" />+ </Button>+ {/if}</div>- {/each}+ {/each}</div></Card.Content></Card.Root>diff --git a/frontend/src/lib/components/edit-project-modal.svelte b/frontend/src/lib/components/edit-project-modal.svelteindex 1f07e4cc..b92ae35e 100644--- a/frontend/src/lib/components/edit-project-modal.svelte+++ b/frontend/src/lib/components/edit-project-modal.svelte@@ -1,463 +1,497 @@<script lang="ts">- import * as Sheet from "$lib/components/ui/sheet";- import * as AlertDialog from "$lib/components/ui/alert-dialog";- import * as Tabs from "$lib/components/ui/tabs";- import * as Select from "$lib/components/ui/select";- import { Button } from "$lib/components/ui/button";- import { Input } from "$lib/components/ui/input";- import { Label } from "$lib/components/ui/label";- import { ErrorAlert } from "$lib/components/ui/error-alert";- import { Checkbox } from "$lib/components/ui/checkbox";- import { DEFAULT_HEALTHCHECK_PATHS } from '$lib/utils/healthcheck';- import { projectsState, type Project, type Framework } from '$lib/state/projects.svelte';- import { Check, Trash2, Copy, CircleAlert } from 'lucide-svelte';- import FrameworkCombobox from './framework-combobox.svelte';- import { toast } from 'svelte-sonner';- import { goto } from '$app/navigation';-- interface Props {- open: boolean;- onOpenChange: (open: boolean) => void;- project: Project | null;- initialTab?: string;- }-- let { open, onOpenChange, project, initialTab = 'project' }: Props = $props();-- const tabTriggerClass = "-mb-px shrink-0 rounded-none border-b-2 border-transparent bg-transparent px-0 pb-2.5 pt-0 text-sm font-medium whitespace-nowrap text-muted-foreground shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none";-- const PROFILE_LABEL_KEY_REGEX = /^[a-zA-Z0-9._:-]+$/;-- let activeTab = $state('project');- let projectName = $state('');- let selectedFramework = $state<Framework>('gin');- let dropHealthyHealthchecks = $state(true);- let healthcheckPathsText = $state('');- let showDefaultHealthcheckPaths = $state(false);- let profileLabelsText = $state('');- let aiFlaggedTermsText = $state('');- let aiFlaggedLanguages = $state<string[]>(['en']);- let loading = $state(false);-- // Must match contentflag.AvailableLanguages() on the backend.- const FLAGGED_LANGUAGE_OPTIONS = [- { code: 'en', label: 'English' },- { code: 'de', label: 'German' },- { code: 'es', label: 'Spanish' },- { code: 'fr', label: 'French' },- { code: 'it', label: 'Italian' },- { code: 'pt', label: 'Portuguese' },- { code: 'sr', label: 'Serbian' }- ];-- const flaggedLanguagesLabel = $derived(- aiFlaggedLanguages.length === 0- ? 'None (custom terms only)'- : FLAGGED_LANGUAGE_OPTIONS.filter((o) => aiFlaggedLanguages.includes(o.code))- .map((o) => o.label)- .join(', ')- );- let error = $state('');- let showDeleteConfirm = $state(false);- let deleting = $state(false);- let deleteConfirmName = $state('');- let nameCopied = $state(false);-- $effect(() => {- if (open && project) {- activeTab = initialTab;- projectName = project.name;- selectedFramework = project.framework;- dropHealthyHealthchecks = project.dropHealthyHealthchecks ?? true;- healthcheckPathsText = (project.healthcheckPaths ?? []).join('\n');- profileLabelsText = (project.profileLabelAllowlist ?? []).join('\n');- aiFlaggedTermsText = (project.aiFlaggedTerms ?? []).join('\n');- aiFlaggedLanguages = project.aiFlaggedLanguages ?? ['en'];- error = '';- }- });-- $effect(() => {- if (!showDeleteConfirm) {- deleteConfirmName = '';- nameCopied = false;- }- });-- async function copyProjectName() {- if (!project) return;- await navigator.clipboard.writeText(project.name);- nameCopied = true;- setTimeout(() => nameCopied = false, 2000);- }-- let deleteConfirmMatches = $derived(- !!project && deleteConfirmName === project.name- );-- let subtitle = $derived(- activeTab === 'healthchecks' ? 'Control which healthcheck requests are stored.'- : activeTab === 'profiles' ? 'Choose which pprof sample labels are recorded and searchable.'- : activeTab === 'ai' ? 'Flag AI conversations that contain specific terms.'- : activeTab === 'danger' ? 'Irreversible and destructive actions.'- : ''- );-- let profileLabelKeys = $derived(- profileLabelsText- .split('\n')- .map((p) => p.trim())- .filter((p) => p.length > 0)- );-- let profileLabelError = $derived.by(() => {- const keys = profileLabelKeys;- if (keys.length > 20) {- return 'At most 20 profile label keys are allowed.';- }- for (const key of keys) {- if (key.toLowerCase() === 'endpoint') continue;- if (key.length > 100) {- return 'Profile label keys must be at most 100 characters.';- }- if (!PROFILE_LABEL_KEY_REGEX.test(key)) {- return `"${key}" may only contain letters, numbers, and . _ : -`;- }- }- return '';- });-- let aiFlaggedTerms = $derived(- aiFlaggedTermsText- .split('\n')- .map((t) => t.trim().toLowerCase())- .filter((t) => t.length > 0)- );-- let aiFlaggedTermsError = $derived.by(() => {- if (aiFlaggedTerms.length > 200) {- return 'At most 200 flagged terms are allowed.';- }- for (const term of aiFlaggedTerms) {- if (term.length > 100) {- return 'Flagged terms must be at most 100 characters.';- }- }- return '';- });-- async function handleSubmit(e: Event) {- e.preventDefault();- if (!projectName.trim()) {- error = 'Project name is required';- return;- }- if (!project) return;-- loading = true;- error = '';-- const healthcheckPaths = healthcheckPathsText- .split('\n')- .map(p => p.trim())- .filter(p => p.length > 0);-- const profileLabelAllowlist = profileLabelsText- .split('\n')- .map(p => p.trim())- .filter(p => p.length > 0);-- try {- await projectsState.updateProject(project.id, projectName.trim(), selectedFramework, dropHealthyHealthchecks, healthcheckPaths, profileLabelAllowlist, aiFlaggedTerms, aiFlaggedLanguages);- toast.success('Successfully updated the Project', { position: 'top-center' });- onOpenChange(false);- } catch (err: any) {- error = err instanceof Error ? err.message : 'Failed to update project';- } finally {- loading = false;- }- }-- async function handleDelete() {- if (!project || !deleteConfirmMatches) return;-- deleting = true;- try {- await projectsState.deleteProject(project.id, project.name);- toast.success('Successfully deleted the Project', { position: 'top-center' });- showDeleteConfirm = false;- onOpenChange(false);- goto('/');- } catch (err: any) {- toast.error(err instanceof Error ? err.message : 'Failed to delete project', { position: 'top-center' });- } finally {- deleting = false;- }- }-- function handleClose() {- error = '';- showDeleteConfirm = false;- onOpenChange(false);- }+ import { resolve } from '$app/paths';+ import * as Sheet from '$lib/components/ui/sheet';+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import * as Tabs from '$lib/components/ui/tabs';+ import * as Select from '$lib/components/ui/select';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { Checkbox } from '$lib/components/ui/checkbox';+ import { DEFAULT_HEALTHCHECK_PATHS } from '$lib/utils/healthcheck';+ import { projectsState, type Project, type Framework } from '$lib/state/projects.svelte';+ import { Check, Trash2, CircleAlert } from '@lucide/svelte';+ import CopyButton from '$lib/components/traceway/copy-button.svelte';+ import { underlineTabTriggerClass, underlineTabListClass } from '$lib/utils/tabs';+ import { cn } from '$lib/utils';+ import FrameworkCombobox from './framework-combobox.svelte';+ import { toast } from 'svelte-sonner';+ import { goto } from '$app/navigation';++ interface Props {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ project: Project | null;+ initialTab?: string;+ }++ let { open, onOpenChange, project, initialTab = 'project' }: Props = $props();++ const PROFILE_LABEL_KEY_REGEX = /^[a-zA-Z0-9._:-]+$/;++ let activeTab = $state('project');+ let projectName = $state('');+ let selectedFramework = $state<Framework>('gin');+ let dropHealthyHealthchecks = $state(true);+ let healthcheckPathsText = $state('');+ let showDefaultHealthcheckPaths = $state(false);+ let profileLabelsText = $state('');+ let aiFlaggedTermsText = $state('');+ let aiFlaggedLanguages = $state<string[]>(['en']);+ let loading = $state(false);++ // Must match contentflag.AvailableLanguages() on the backend.+ const FLAGGED_LANGUAGE_OPTIONS = [+ { code: 'en', label: 'English' },+ { code: 'de', label: 'German' },+ { code: 'es', label: 'Spanish' },+ { code: 'fr', label: 'French' },+ { code: 'it', label: 'Italian' },+ { code: 'pt', label: 'Portuguese' },+ { code: 'sr', label: 'Serbian' }+ ];++ const flaggedLanguagesLabel = $derived(+ aiFlaggedLanguages.length === 0+ ? 'None (custom terms only)'+ : FLAGGED_LANGUAGE_OPTIONS.filter((o) => aiFlaggedLanguages.includes(o.code))+ .map((o) => o.label)+ .join(', ')+ );+ let error = $state('');+ let showDeleteConfirm = $state(false);+ let deleting = $state(false);+ let deleteConfirmName = $state('');++ $effect(() => {+ if (open && project) {+ activeTab = initialTab;+ projectName = project.name;+ selectedFramework = project.framework;+ dropHealthyHealthchecks = project.dropHealthyHealthchecks ?? true;+ healthcheckPathsText = (project.healthcheckPaths ?? []).join('\n');+ profileLabelsText = (project.profileLabelAllowlist ?? []).join('\n');+ aiFlaggedTermsText = (project.aiFlaggedTerms ?? []).join('\n');+ aiFlaggedLanguages = project.aiFlaggedLanguages ?? ['en'];+ error = '';+ }+ });++ $effect(() => {+ if (!showDeleteConfirm) {+ deleteConfirmName = '';+ }+ });++ let deleteConfirmMatches = $derived(!!project && deleteConfirmName === project.name);++ let subtitle = $derived(+ activeTab === 'healthchecks'+ ? 'Control which healthcheck requests are stored.'+ : activeTab === 'profiles'+ ? 'Choose which pprof sample labels are recorded and searchable.'+ : activeTab === 'ai'+ ? 'Flag AI conversations that contain specific terms.'+ : activeTab === 'danger'+ ? 'Irreversible and destructive actions.'+ : ''+ );++ let profileLabelKeys = $derived(+ profileLabelsText+ .split('\n')+ .map((p) => p.trim())+ .filter((p) => p.length > 0)+ );++ let profileLabelError = $derived.by(() => {+ const keys = profileLabelKeys;+ if (keys.length > 20) {+ return 'At most 20 profile label keys are allowed.';+ }+ for (const key of keys) {+ if (key.toLowerCase() === 'endpoint') continue;+ if (key.length > 100) {+ return 'Profile label keys must be at most 100 characters.';+ }+ if (!PROFILE_LABEL_KEY_REGEX.test(key)) {+ return `"${key}" may only contain letters, numbers, and . _ : -`;+ }+ }+ return '';+ });++ let aiFlaggedTerms = $derived(+ aiFlaggedTermsText+ .split('\n')+ .map((t) => t.trim().toLowerCase())+ .filter((t) => t.length > 0)+ );++ let aiFlaggedTermsError = $derived.by(() => {+ if (aiFlaggedTerms.length > 200) {+ return 'At most 200 flagged terms are allowed.';+ }+ for (const term of aiFlaggedTerms) {+ if (term.length > 100) {+ return 'Flagged terms must be at most 100 characters.';+ }+ }+ return '';+ });++ async function handleSubmit(e: Event) {+ e.preventDefault();+ if (!projectName.trim()) {+ error = 'Project name is required';+ return;+ }+ if (!project) return;++ loading = true;+ error = '';++ const healthcheckPaths = healthcheckPathsText+ .split('\n')+ .map((p) => p.trim())+ .filter((p) => p.length > 0);++ const profileLabelAllowlist = profileLabelsText+ .split('\n')+ .map((p) => p.trim())+ .filter((p) => p.length > 0);++ try {+ await projectsState.updateProject(+ project.id,+ projectName.trim(),+ selectedFramework,+ dropHealthyHealthchecks,+ healthcheckPaths,+ profileLabelAllowlist,+ aiFlaggedTerms,+ aiFlaggedLanguages+ );+ toast.success('Successfully updated the Project', { position: 'top-center' });+ onOpenChange(false);+ } catch (err) {+ error = err instanceof Error ? err.message : 'Failed to update project';+ } finally {+ loading = false;+ }+ }++ async function handleDelete() {+ if (!project || !deleteConfirmMatches) return;++ deleting = true;+ try {+ await projectsState.deleteProject(project.id, project.name);+ toast.success('Successfully deleted the Project');+ showDeleteConfirm = false;+ onOpenChange(false);+ goto(resolve('/'));+ } catch (err) {+ toast.error(err instanceof Error ? err.message : 'Failed to delete project');+ } finally {+ deleting = false;+ }+ }++ function handleClose() {+ error = '';+ showDeleteConfirm = false;+ onOpenChange(false);+ }</script><Sheet.Root {open} onOpenChange={handleClose}>- <Sheet.Content side="right" class="w-full overflow-y-auto sm:w-[680px] sm:max-w-[680px]">- <Sheet.Header class="px-6 pb-0">- <Sheet.Title>Edit Project</Sheet.Title>- </Sheet.Header>-- <Tabs.Root value={activeTab} onValueChange={(v) => { if (v) activeTab = v; }}>- <Tabs.List class="h-auto w-full flex-nowrap justify-start gap-4 overflow-x-auto rounded-none border-b bg-transparent p-0 pr-6 pl-6 pt-0">- <Tabs.Trigger value="project" class={tabTriggerClass}>Project</Tabs.Trigger>- <Tabs.Trigger value="healthchecks" class={tabTriggerClass}>Healthchecks</Tabs.Trigger>- <Tabs.Trigger value="profiles" class={tabTriggerClass}>Profiles</Tabs.Trigger>- <Tabs.Trigger value="ai" class={tabTriggerClass}>AI</Tabs.Trigger>- <Tabs.Trigger value="danger" class={tabTriggerClass}>Danger Zone</Tabs.Trigger>- </Tabs.List>- </Tabs.Root>-- {#if subtitle}- <Sheet.Description class="px-6">{subtitle}</Sheet.Description>- {/if}-- {#if activeTab === 'danger'}- <div class="px-6 pb-6 space-y-3">- <p class="text-sm text-muted-foreground">- Permanently delete this project along with all of its data, including transactions, exceptions, logs, metrics, and dashboards.- </p>- <Button- type="button"- variant="destructiveOutline"- onclick={() => showDeleteConfirm = true}- >- <Trash2 class="mr-2 h-4 w-4" />- Delete Project- </Button>- </div>- {:else}- <form onsubmit={handleSubmit} class="px-6 pb-6 space-y-5">- <ErrorAlert {error} />-- {#if activeTab === 'project'}- <div class="space-y-2">- <Label for="edit-project-name">Project Name</Label>- <Input- id="edit-project-name"- type="text"- placeholder="My Application"- bind:value={projectName}- disabled={loading}- />- <p class="text-xs text-muted-foreground">- A unique name for your project (letters, numbers, spaces, hyphens)- </p>- </div>-- <div class="space-y-2">- <Label for="edit-framework">Framework</Label>- <FrameworkCombobox bind:value={selectedFramework} disabled={loading} />- <p class="text-xs text-muted-foreground">- Select your framework for tailored integration code- </p>- </div>- {:else if activeTab === 'healthchecks'}- <div class="flex items-start gap-2">- <Checkbox- checked={dropHealthyHealthchecks}- onCheckedChange={(checked) => dropHealthyHealthchecks = checked === true}- disabled={loading}- class="mt-0.5"- aria-label="Drop healthy healthcheck requests"- />- <div class="space-y-1">- <Label class="cursor-pointer" onclick={() => { if (!loading) dropHealthyHealthchecks = !dropHealthyHealthchecks; }}>Drop healthy healthcheck requests</Label>- <p class="text-xs text-muted-foreground">- Requests to common healthcheck endpoints (GET/HEAD) are only stored when they fail with status 400 or higher.- <button- type="button"- class="underline hover:text-foreground"- onclick={() => showDefaultHealthcheckPaths = !showDefaultHealthcheckPaths}- >- {showDefaultHealthcheckPaths ? 'Hide' : 'Show'} built-in paths- </button>- </p>- {#if showDefaultHealthcheckPaths}- <div class="flex flex-wrap gap-1 pt-1">- {#each DEFAULT_HEALTHCHECK_PATHS as path}- <code class="rounded bg-muted px-1.5 py-0.5 text-xs">{path}</code>- {/each}- </div>- {/if}- </div>- </div>-- {#if dropHealthyHealthchecks}- <div class="space-y-2">- <Label for="edit-healthcheck-paths">Additional healthcheck paths</Label>- <textarea- id="edit-healthcheck-paths"- bind:value={healthcheckPathsText}- disabled={loading}- rows="3"- placeholder={"/internal/probe\n/checks/*"}- class="border-input bg-background dark:bg-input/30 placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 flex w-full rounded-md border px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50"- ></textarea>- <p class="text-xs text-muted-foreground">- One path per line. Use a trailing * to match a prefix or a leading * to match a suffix.- </p>- </div>- {/if}- {:else if activeTab === 'profiles'}- <div class="space-y-2">- <Label>Built-in label</Label>- <div class="flex flex-wrap gap-1">- <code class="rounded bg-muted px-1.5 py-0.5 text-xs">endpoint</code>- </div>- <p class="text-xs text-muted-foreground">- The <code class="rounded bg-muted px-1 py-0.5 text-[0.7rem]">endpoint</code> label is always recorded and searchable.- </p>- </div>-- <div class="space-y-2">- <Label for="edit-profile-labels">Additional profile labels</Label>- <textarea- id="edit-profile-labels"- bind:value={profileLabelsText}- disabled={loading}- rows="3"- placeholder={"tenant\nregion"}- class="border-input bg-background dark:bg-input/30 placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 flex w-full rounded-md border px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50"- ></textarea>- {#if profileLabelError}- <p class="text-xs text-destructive flex items-center gap-1">- <CircleAlert class="h-3.5 w-3.5 shrink-0" />- {profileLabelError}- </p>- {/if}- <p class="text-xs text-muted-foreground">- One label key per line. These pprof sample labels are recorded at ingest and become searchable on the flame-graph page. Added keys only apply to profiles ingested afterward.- </p>- <p class="text-xs text-muted-foreground">- Avoid high-cardinality keys like <code class="rounded bg-muted px-1 py-0.5 text-[0.7rem]">user_id</code> or <code class="rounded bg-muted px-1 py-0.5 text-[0.7rem]">request_id</code>: every distinct value is stored as a separate sample, which bloats storage and slows queries.- </p>- </div>- {:else if activeTab === 'ai'}- <div class="space-y-2">- <Label>Flagged term languages</Label>- <Select.Root type="multiple" bind:value={aiFlaggedLanguages} disabled={loading}>- <Select.Trigger class="w-full">- <span class="truncate">{flaggedLanguagesLabel}</span>- </Select.Trigger>- <Select.Content>- {#each FLAGGED_LANGUAGE_OPTIONS as option (option.code)}- <Select.Item value={option.code} label={option.label}>- {option.label}- </Select.Item>- {/each}- </Select.Content>- </Select.Root>- <p class="text-xs text-muted-foreground">- Built-in profanity lists to scan conversations with. Deselect all to rely on custom terms only. Matching is per whole word, so these packs only cover languages with space-separated words.- </p>- </div>-- <div class="space-y-2">- <Label for="edit-ai-flagged-terms">Custom flagged terms</Label>- <textarea- id="edit-ai-flagged-terms"- bind:value={aiFlaggedTermsText}- disabled={loading}- rows="4"- placeholder={"competitor name\nrefund"}- class="border-input bg-background dark:bg-input/30 placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 flex w-full rounded-md border px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50"- ></textarea>- {#if aiFlaggedTermsError}- <p class="text-xs text-destructive flex items-center gap-1">- <CircleAlert class="h-3.5 w-3.5 shrink-0" />- {aiFlaggedTermsError}- </p>- {/if}- <p class="text-xs text-muted-foreground">- One term per line. AI conversations containing these terms, in addition to the selected language packs, are marked as flagged and filterable on the Conversations page. Terms match whole words, case-insensitively, and only apply to calls ingested afterward.- </p>- </div>- {/if}-- <div class="flex justify-end gap-2 pt-2">- <Button type="button" variant="outline" onclick={handleClose} disabled={loading}>- Cancel- </Button>- <Button type="submit" disabled={loading}>- {#if loading}- Updating...- {:else}- <Check class="mr-2 h-4 w-4" />- Update Project- {/if}- </Button>- </div>- </form>- {/if}- </Sheet.Content>+ <Sheet.Content side="right" class="w-full overflow-y-auto sm:w-[680px] sm:max-w-[680px]">+ <Sheet.Header class="px-6 pb-0">+ <Sheet.Title>Edit Project</Sheet.Title>+ </Sheet.Header>++ <Tabs.Root+ value={activeTab}+ onValueChange={(v) => {+ if (v) activeTab = v;+ }}+ >+ <Tabs.List class={cn(underlineTabListClass, 'flex-nowrap overflow-x-auto px-6')}>+ <Tabs.Trigger value="project" class={underlineTabTriggerClass}>Project</Tabs.Trigger>+ <Tabs.Trigger value="healthchecks" class={underlineTabTriggerClass}+ >Healthchecks</Tabs.Trigger+ >+ <Tabs.Trigger value="profiles" class={underlineTabTriggerClass}>Profiles</Tabs.Trigger>+ <Tabs.Trigger value="ai" class={underlineTabTriggerClass}>AI</Tabs.Trigger>+ <Tabs.Trigger value="danger" class={underlineTabTriggerClass}>Danger Zone</Tabs.Trigger>+ </Tabs.List>+ </Tabs.Root>++ {#if subtitle}+ <Sheet.Description class="px-6">{subtitle}</Sheet.Description>+ {/if}++ {#if activeTab === 'danger'}+ <div class="space-y-3 px-6 pb-6">+ <p class="text-sm text-muted-foreground">+ Permanently delete this project along with all of its data, including transactions,+ exceptions, logs, metrics, and dashboards.+ </p>+ <Button+ type="button"+ variant="destructiveOutline"+ onclick={() => (showDeleteConfirm = true)}+ >+ <Trash2 class="mr-2 h-4 w-4" />+ Delete Project+ </Button>+ </div>+ {:else}+ <form onsubmit={handleSubmit} class="space-y-5 px-6 pb-6">+ <ErrorAlert {error} />++ {#if activeTab === 'project'}+ <div class="space-y-2">+ <Label for="edit-project-name">Project Name</Label>+ <Input+ id="edit-project-name"+ type="text"+ placeholder="My Application"+ bind:value={projectName}+ disabled={loading}+ />+ <p class="text-xs text-muted-foreground">+ A unique name for your project (letters, numbers, spaces, hyphens)+ </p>+ </div>++ <div class="space-y-2">+ <Label for="edit-framework">Framework</Label>+ <FrameworkCombobox bind:value={selectedFramework} disabled={loading} />+ <p class="text-xs text-muted-foreground">+ Select your framework for tailored integration code+ </p>+ </div>+ {:else if activeTab === 'healthchecks'}+ <div class="flex items-start gap-2">+ <Checkbox+ checked={dropHealthyHealthchecks}+ onCheckedChange={(checked) => (dropHealthyHealthchecks = checked === true)}+ disabled={loading}+ class="mt-0.5"+ aria-label="Drop healthy healthcheck requests"+ />+ <div class="space-y-1">+ <Label+ class="cursor-pointer"+ onclick={() => {+ if (!loading) dropHealthyHealthchecks = !dropHealthyHealthchecks;+ }}>Drop healthy healthcheck requests</Label+ >+ <p class="text-xs text-muted-foreground">+ Requests to common healthcheck endpoints (GET/HEAD) are only stored when they fail+ with status 400 or higher.+ <button+ type="button"+ class="underline hover:text-foreground"+ onclick={() => (showDefaultHealthcheckPaths = !showDefaultHealthcheckPaths)}+ >+ {showDefaultHealthcheckPaths ? 'Hide' : 'Show'} built-in paths+ </button>+ </p>+ {#if showDefaultHealthcheckPaths}+ <div class="flex flex-wrap gap-1 pt-1">+ {#each DEFAULT_HEALTHCHECK_PATHS as path, __index (__index)}+ <code class="rounded bg-muted px-1.5 py-0.5 text-xs">{path}</code>+ {/each}+ </div>+ {/if}+ </div>+ </div>++ {#if dropHealthyHealthchecks}+ <div class="space-y-2">+ <Label for="edit-healthcheck-paths">Additional healthcheck paths</Label>+ <textarea+ id="edit-healthcheck-paths"+ bind:value={healthcheckPathsText}+ disabled={loading}+ rows="3"+ placeholder="/internal/probe /checks/*"+ class="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30"+ ></textarea>+ <p class="text-xs text-muted-foreground">+ One path per line. Use a trailing * to match a prefix or a leading * to match a+ suffix.+ </p>+ </div>+ {/if}+ {:else if activeTab === 'profiles'}+ <div class="space-y-2">+ <Label>Built-in label</Label>+ <div class="flex flex-wrap gap-1">+ <code class="rounded bg-muted px-1.5 py-0.5 text-xs">endpoint</code>+ </div>+ <p class="text-xs text-muted-foreground">+ The <code class="rounded bg-muted px-1 py-0.5 text-[0.7rem]">endpoint</code> label is always+ recorded and searchable.+ </p>+ </div>++ <div class="space-y-2">+ <Label for="edit-profile-labels">Additional profile labels</Label>+ <textarea+ id="edit-profile-labels"+ bind:value={profileLabelsText}+ disabled={loading}+ rows="3"+ placeholder="tenant region"+ class="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30"+ ></textarea>+ {#if profileLabelError}+ <p class="flex items-center gap-1 text-xs text-destructive">+ <CircleAlert class="h-3.5 w-3.5 shrink-0" />+ {profileLabelError}+ </p>+ {/if}+ <p class="text-xs text-muted-foreground">+ One label key per line. These pprof sample labels are recorded at ingest and become+ searchable on the flame-graph page. Added keys only apply to profiles ingested+ afterward.+ </p>+ <p class="text-xs text-muted-foreground">+ Avoid high-cardinality keys like <code+ class="rounded bg-muted px-1 py-0.5 text-[0.7rem]">user_id</code+ >+ or <code class="rounded bg-muted px-1 py-0.5 text-[0.7rem]">request_id</code>: every+ distinct value is stored as a separate sample, which bloats storage and slows queries.+ </p>+ </div>+ {:else if activeTab === 'ai'}+ <div class="space-y-2">+ <Label>Flagged term languages</Label>+ <Select.Root type="multiple" bind:value={aiFlaggedLanguages} disabled={loading}>+ <Select.Trigger class="w-full">+ <span class="truncate">{flaggedLanguagesLabel}</span>+ </Select.Trigger>+ <Select.Content>+ {#each FLAGGED_LANGUAGE_OPTIONS as option (option.code)}+ <Select.Item value={option.code} label={option.label}>+ {option.label}+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ <p class="text-xs text-muted-foreground">+ Built-in profanity lists to scan conversations with. Deselect all to rely on custom+ terms only. Matching is per whole word, so these packs only cover languages with+ space-separated words.+ </p>+ </div>++ <div class="space-y-2">+ <Label for="edit-ai-flagged-terms">Custom flagged terms</Label>+ <textarea+ id="edit-ai-flagged-terms"+ bind:value={aiFlaggedTermsText}+ disabled={loading}+ rows="4"+ placeholder="competitor name refund"+ class="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30"+ ></textarea>+ {#if aiFlaggedTermsError}+ <p class="flex items-center gap-1 text-xs text-destructive">+ <CircleAlert class="h-3.5 w-3.5 shrink-0" />+ {aiFlaggedTermsError}+ </p>+ {/if}+ <p class="text-xs text-muted-foreground">+ One term per line. AI conversations containing these terms, in addition to the+ selected language packs, are marked as flagged and filterable on the Conversations+ page. Terms match whole words, case-insensitively, and only apply to calls ingested+ afterward.+ </p>+ </div>+ {/if}++ <div class="flex justify-end gap-2 pt-2">+ <Button type="button" variant="outline" onclick={handleClose} disabled={loading}>+ Cancel+ </Button>+ <Button type="submit" disabled={loading}>+ {#if loading}+ Updating...+ {:else}+ <Check class="mr-2 h-4 w-4" />+ Update Project+ {/if}+ </Button>+ </div>+ </form>+ {/if}+ </Sheet.Content></Sheet.Root><AlertDialog.Root bind:open={showDeleteConfirm}>- <AlertDialog.Content interactOutsideBehavior="close">- <AlertDialog.Header>- <AlertDialog.Title>Delete Project</AlertDialog.Title>- <AlertDialog.Description>- This project will be permanently deleted along with all of its data, including transactions, exceptions, logs, metrics, and dashboards.- </AlertDialog.Description>- </AlertDialog.Header>-- <div class="rounded-md bg-destructive/10 border border-destructive/30 px-3 py-2">- <p class="text-sm">- <span class="font-semibold text-destructive">Warning:</span>- <span class="text-destructive/90">This action is not reversible. Please be certain.</span>- </p>- </div>-- <div class="space-y-2">- <Label for="delete-confirm-name" class="text-sm font-normal text-muted-foreground leading-relaxed">- Enter the project name <span class="font-semibold text-foreground">{project?.name}</span><button- type="button"- onclick={copyProjectName}- class="inline-flex items-center align-middle ml-1 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"- title="Copy project name"- aria-label="Copy project name"- >- {#if nameCopied}- <Check class="h-3.5 w-3.5" />- {:else}- <Copy class="h-3.5 w-3.5" />- {/if}- </button> to continue:- </Label>- <Input- id="delete-confirm-name"- type="text"- autocomplete="off"- bind:value={deleteConfirmName}- disabled={deleting}- />- {#if deleteConfirmName.length > 0 && !deleteConfirmMatches}- <p class="text-xs text-destructive flex items-center gap-1">- <CircleAlert class="h-3.5 w-3.5" />- The project name does not match- </p>- {/if}- </div>-- <AlertDialog.Footer class="sm:justify-between">- <Button variant="outline" onclick={() => showDeleteConfirm = false} disabled={deleting}>- Cancel- </Button>- <Button variant="destructive" onclick={handleDelete} disabled={deleting || !deleteConfirmMatches}>- <Trash2 class="mr-2 h-4 w-4" />- {deleting ? 'Deleting...' : 'Delete Project'}- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>+ <AlertDialog.Content interactOutsideBehavior="close">+ <AlertDialog.Header>+ <AlertDialog.Title>Delete Project</AlertDialog.Title>+ <AlertDialog.Description>+ This project will be permanently deleted along with all of its data, including transactions,+ exceptions, logs, metrics, and dashboards.+ </AlertDialog.Description>+ </AlertDialog.Header>++ <div class="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2">+ <p class="text-sm">+ <span class="font-semibold text-destructive">Warning:</span>+ <span class="text-destructive/90">This action is not reversible. Please be certain.</span>+ </p>+ </div>++ <div class="space-y-2">+ <Label+ for="delete-confirm-name"+ class="text-sm leading-relaxed font-normal text-muted-foreground"+ >+ Enter the project name <span class="font-semibold text-foreground">{project?.name}</span+ ><CopyButton+ bare+ text={() => project?.name ?? ''}+ title="Copy project name"+ iconClass="h-3.5 w-3.5"+ class="ml-1 inline-flex items-center p-0.5 align-middle hover:bg-accent"+ /> to continue:+ </Label>+ <Input+ id="delete-confirm-name"+ type="text"+ autocomplete="off"+ bind:value={deleteConfirmName}+ disabled={deleting}+ />+ {#if deleteConfirmName.length > 0 && !deleteConfirmMatches}+ <p class="flex items-center gap-1 text-xs text-destructive">+ <CircleAlert class="h-3.5 w-3.5" />+ The project name does not match+ </p>+ {/if}+ </div>++ <AlertDialog.Footer class="sm:justify-between">+ <Button variant="outline" onclick={() => (showDeleteConfirm = false)} disabled={deleting}>+ Cancel+ </Button>+ <Button+ variant="destructive"+ onclick={handleDelete}+ disabled={deleting || !deleteConfirmMatches}+ >+ <Trash2 class="mr-2 h-4 w-4" />+ {deleting ? 'Deleting...' : 'Delete Project'}+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content></AlertDialog.Root>diff --git a/frontend/src/lib/components/framework-combobox.svelte b/frontend/src/lib/components/framework-combobox.svelteindex a2c84d53..b2302c24 100644--- a/frontend/src/lib/components/framework-combobox.svelte+++ b/frontend/src/lib/components/framework-combobox.svelte@@ -1,153 +1,212 @@<script lang="ts">- import { Combobox } from "bits-ui";- import { cn } from "$lib/utils";- import { Check, ChevronDown, Search } from "@lucide/svelte";- import { getFrameworkLabel, type Framework } from '$lib/state/projects.svelte';- import FrameworkIcon from './framework-icon.svelte';- import SelectScrollUpButton from '$lib/components/ui/select/select-scroll-up-button.svelte';- import SelectScrollDownButton from '$lib/components/ui/select/select-scroll-down-button.svelte';+ import { Combobox } from 'bits-ui';+ import { cn } from '$lib/utils';+ import { Check, ChevronDown, Search } from '@lucide/svelte';+ import { getFrameworkLabel, type Framework } from '$lib/state/projects.svelte';+ import FrameworkIcon from './framework-icon.svelte';+ import SelectScrollUpButton from '$lib/components/ui/select/select-scroll-up-button.svelte';+ import SelectScrollDownButton from '$lib/components/ui/select/select-scroll-down-button.svelte';- interface Props {- value: Framework;- disabled?: boolean;- }+ interface Props {+ value: Framework;+ disabled?: boolean;+ }- let { value = $bindable(), disabled = false }: Props = $props();+ let { value = $bindable(), disabled = false }: Props = $props();- let open = $state(false);- let searchQuery = $state('');- let searchInputRef = $state<HTMLInputElement | null>(null);- let triggerWrapperRef = $state<HTMLDivElement | null>(null);- let contentRef = $state<HTMLElement | null>(null);+ let open = $state(false);+ let searchQuery = $state('');+ let searchInputRef = $state<HTMLInputElement | null>(null);+ let triggerWrapperRef = $state<HTMLDivElement | null>(null);+ let contentRef = $state<HTMLElement | null>(null);- const GROUP_ORDER = ['Backend', 'Browser', 'Mobile'] as const;+ const GROUP_ORDER = ['Backend', 'Browser', 'Mobile'] as const;- const frameworks = [- { value: 'opentelemetry', label: 'OpenTelemetry', description: 'Any backend: Go, Node.js, Python, PHP, Java, .NET, Ruby', group: 'Backend', keywords: 'otel opentelemetry go golang gin fiber chi fasthttp echo node nodejs express nestjs fastify koa hono cloudflare workers python django flask fastapi php symfony laravel slim java spring dotnet .net csharp ruby rails api server backend' },- { value: 'react', label: 'React', description: 'React apps, including Next.js and Remix', group: 'Browser', keywords: 'react nextjs next.js remix browser frontend spa' },- { value: 'svelte', label: 'Svelte', description: 'Svelte and SvelteKit apps', group: 'Browser', keywords: 'svelte sveltekit browser frontend' },- { value: 'vuejs', label: 'Vue.js', description: 'Vue and Nuxt apps', group: 'Browser', keywords: 'vue vuejs nuxt browser frontend' },- { value: 'jquery', label: 'jQuery', description: 'Legacy-friendly AJAX and DOM library', group: 'Browser', keywords: 'jquery browser frontend legacy' },- { value: 'flutter', label: 'Flutter', description: 'Flutter apps on Android and iOS', group: 'Mobile', keywords: 'flutter dart mobile android ios' },- { value: 'react-native', label: 'React Native', description: 'React Native and Expo apps', group: 'Mobile', keywords: 'react native expo mobile' },- { value: 'android', label: 'Android', description: 'Native Android (Kotlin/Java)', group: 'Mobile', keywords: 'android kotlin java mobile native' },- { value: 'ios', label: 'iOS', description: 'Native iOS (Swift/Objective-C)', group: 'Mobile', keywords: 'ios swift swiftui objective-c apple mobile native' },- ] as const;+ const frameworks = [+ {+ value: 'opentelemetry',+ label: 'OpenTelemetry',+ description: 'Any backend: Go, Node.js, Python, PHP, Java, .NET, Ruby',+ group: 'Backend',+ keywords:+ 'otel opentelemetry go golang gin fiber chi fasthttp echo node nodejs express nestjs fastify koa hono cloudflare workers python django flask fastapi php symfony laravel slim java spring dotnet .net csharp ruby rails api server backend'+ },+ {+ value: 'react',+ label: 'React',+ description: 'React apps, including Next.js and Remix',+ group: 'Browser',+ keywords: 'react nextjs next.js remix browser frontend spa'+ },+ {+ value: 'svelte',+ label: 'Svelte',+ description: 'Svelte and SvelteKit apps',+ group: 'Browser',+ keywords: 'svelte sveltekit browser frontend'+ },+ {+ value: 'vuejs',+ label: 'Vue.js',+ description: 'Vue and Nuxt apps',+ group: 'Browser',+ keywords: 'vue vuejs nuxt browser frontend'+ },+ {+ value: 'jquery',+ label: 'jQuery',+ description: 'Legacy-friendly AJAX and DOM library',+ group: 'Browser',+ keywords: 'jquery browser frontend legacy'+ },+ {+ value: 'flutter',+ label: 'Flutter',+ description: 'Flutter apps on Android and iOS',+ group: 'Mobile',+ keywords: 'flutter dart mobile android ios'+ },+ {+ value: 'react-native',+ label: 'React Native',+ description: 'React Native and Expo apps',+ group: 'Mobile',+ keywords: 'react native expo mobile'+ },+ {+ value: 'android',+ label: 'Android',+ description: 'Native Android (Kotlin/Java)',+ group: 'Mobile',+ keywords: 'android kotlin java mobile native'+ },+ {+ value: 'ios',+ label: 'iOS',+ description: 'Native iOS (Swift/Objective-C)',+ group: 'Mobile',+ keywords: 'ios swift swiftui objective-c apple mobile native'+ }+ ] as const;- const selectedFrameworkLabel = $derived(getFrameworkLabel(value));+ const selectedFrameworkLabel = $derived(getFrameworkLabel(value));- const query = $derived(searchQuery.toLowerCase().trim());+ const query = $derived(searchQuery.toLowerCase().trim());- const filteredFrameworks = $derived(- query === ''- ? frameworks- : frameworks.filter(f =>- f.label.toLowerCase().includes(query) ||- f.description.toLowerCase().includes(query) ||- f.group.toLowerCase().includes(query) ||- f.keywords.includes(query)- )- );+ const filteredFrameworks = $derived(+ query === ''+ ? frameworks+ : frameworks.filter(+ (f) =>+ f.label.toLowerCase().includes(query) ||+ f.description.toLowerCase().includes(query) ||+ f.group.toLowerCase().includes(query) ||+ f.keywords.includes(query)+ )+ );- const groups = $derived(- GROUP_ORDER- .map(name => ({ name, items: filteredFrameworks.filter(f => f.group === name) }))- .filter(g => g.items.length > 0)- );+ const groups = $derived(+ GROUP_ORDER.map((name) => ({+ name,+ items: filteredFrameworks.filter((f) => f.group === name)+ })).filter((g) => g.items.length > 0)+ );- function handleOpenChange(isOpen: boolean) {- open = isOpen;- if (!isOpen) {- searchQuery = '';- } else {- requestAnimationFrame(() => {- searchInputRef?.focus();- if (contentRef && triggerWrapperRef) {- contentRef.style.width = `${triggerWrapperRef.offsetWidth}px`;- }- });- }- }+ function handleOpenChange(isOpen: boolean) {+ open = isOpen;+ if (!isOpen) {+ searchQuery = '';+ } else {+ requestAnimationFrame(() => {+ searchInputRef?.focus();+ if (contentRef && triggerWrapperRef) {+ contentRef.style.width = `${triggerWrapperRef.offsetWidth}px`;+ }+ });+ }+ }</script><Combobox.Root type="single" bind:value bind:open onOpenChange={handleOpenChange}>- <div class="relative w-full" bind:this={triggerWrapperRef}>- <Combobox.Input- {disabled}- readonly- defaultValue={selectedFrameworkLabel}- class="absolute inset-0 w-full h-full opacity-0 pointer-events-none"- tabindex={-1}- />- <Combobox.Trigger- {disabled}- data-slot="select-trigger"- data-size="default"- class={cn(- "border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-full items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none select-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"- )}- >- <div class="flex items-center gap-2">- <FrameworkIcon framework={value} />- <span>{selectedFrameworkLabel}</span>- </div>- <ChevronDown class="size-4 opacity-50" />- </Combobox.Trigger>- </div>+ <div class="relative w-full" bind:this={triggerWrapperRef}>+ <Combobox.Input+ {disabled}+ readonly+ defaultValue={selectedFrameworkLabel}+ class="pointer-events-none absolute inset-0 h-full w-full opacity-0"+ tabindex={-1}+ />+ <Combobox.Trigger+ {disabled}+ data-slot="select-trigger"+ data-size="default"+ class={cn(+ "flex w-full items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none select-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground"+ )}+ >+ <div class="flex items-center gap-2">+ <FrameworkIcon framework={value} />+ <span>{selectedFrameworkLabel}</span>+ </div>+ <ChevronDown class="size-4 opacity-50" />+ </Combobox.Trigger>+ </div>- <Combobox.Portal>- <Combobox.Content- bind:ref={contentRef}- sideOffset={4}- preventScroll={true}- class={cn(- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 min-w-[8rem] rounded-md border shadow-md data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1"- )}- >- <div class="flex items-center border-b px-3 py-2">- <Search class="mr-2 size-4 shrink-0 opacity-50" />- <input- bind:this={searchInputRef}- bind:value={searchQuery}- placeholder="Search frameworks..."- class="flex h-7 w-full rounded-md bg-transparent text-sm outline-none placeholder:text-muted-foreground"- />- </div>+ <Combobox.Portal>+ <Combobox.Content+ bind:ref={contentRef}+ sideOffset={4}+ preventScroll={true}+ class={cn(+ 'relative z-50 min-w-[8rem] rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:translate-y-1 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:-translate-x-1 data-[side=left]:slide-in-from-end-2 data-[side=right]:translate-x-1 data-[side=right]:slide-in-from-start-2 data-[side=top]:-translate-y-1 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95'+ )}+ >+ <div class="flex items-center border-b px-3 py-2">+ <Search class="mr-2 size-4 shrink-0 opacity-50" />+ <input+ bind:this={searchInputRef}+ bind:value={searchQuery}+ placeholder="Search frameworks..."+ class="flex h-7 w-full rounded-md bg-transparent text-sm outline-none placeholder:text-muted-foreground"+ />+ </div>- <SelectScrollUpButton />- <Combobox.Viewport class="w-full max-h-72 overflow-y-auto scroll-my-1 p-1">- {#if filteredFrameworks.length === 0}- <div class="py-4 text-center text-sm text-muted-foreground">No frameworks found</div>- {:else}- {#each groups as group (group.name)}- <Combobox.Group>- <Combobox.GroupHeading class="px-2 py-1.5 text-xs font-semibold text-muted-foreground">{group.name}</Combobox.GroupHeading>- {#each group.items as fw (fw.value)}- <Combobox.Item- value={fw.value}- class={cn(- "data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 ps-2 pe-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"- )}- >- {#snippet children({ selected })}- <div class="flex items-center gap-2">- <FrameworkIcon framework={fw.value} />- <div class="flex flex-col">- <span class="font-medium">{fw.label}</span>- <span class="text-xs text-muted-foreground">{fw.description}</span>- </div>- </div>- {#if selected}- <Check class="absolute end-2 size-4" />- {/if}- {/snippet}- </Combobox.Item>- {/each}- </Combobox.Group>- {/each}- {/if}- </Combobox.Viewport>- <SelectScrollDownButton />- </Combobox.Content>- </Combobox.Portal>+ <SelectScrollUpButton />+ <Combobox.Viewport class="max-h-72 w-full scroll-my-1 overflow-y-auto p-1">+ {#if filteredFrameworks.length === 0}+ <div class="py-4 text-center text-sm text-muted-foreground">No frameworks found</div>+ {:else}+ {#each groups as group (group.name)}+ <Combobox.Group>+ <Combobox.GroupHeading class="px-2 py-1.5 text-xs font-semibold text-muted-foreground"+ >{group.name}</Combobox.GroupHeading+ >+ {#each group.items as fw (fw.value)}+ <Combobox.Item+ value={fw.value}+ class={cn(+ "relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 ps-2 pe-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground"+ )}+ >+ {#snippet children({ selected })}+ <div class="flex items-center gap-2">+ <FrameworkIcon framework={fw.value} />+ <div class="flex flex-col">+ <span class="font-medium">{fw.label}</span>+ <span class="text-xs text-muted-foreground">{fw.description}</span>+ </div>+ </div>+ {#if selected}+ <Check class="absolute end-2 size-4" />+ {/if}+ {/snippet}+ </Combobox.Item>+ {/each}+ </Combobox.Group>+ {/each}+ {/if}+ </Combobox.Viewport>+ <SelectScrollDownButton />+ </Combobox.Content>+ </Combobox.Portal></Combobox.Root>diff --git a/frontend/src/lib/components/framework-icon.svelte b/frontend/src/lib/components/framework-icon.svelteindex 0df68e2d..a5fa2d57 100644--- a/frontend/src/lib/components/framework-icon.svelte+++ b/frontend/src/lib/components/framework-icon.svelte@@ -1,73 +1,93 @@<script lang="ts">- import type { Framework } from '$lib/state/projects.svelte';+ import type { Framework } from '$lib/state/projects.svelte';- interface Props {- framework: Framework | string;- class?: string;- }+ interface Props {+ framework: Framework | string;+ class?: string;+ }- let { framework, class: className = 'size-4 shrink-0' }: Props = $props();+ let { framework, class: className = 'size-4 shrink-0' }: Props = $props();</script>{#if framework === 'gin'}- <img src="/gin.png" alt="Gin" class={className} />+ <img src="/gin.png" alt="Gin" class={className} />{:else if framework === 'fiber'}- <svg class={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">- <rect x="1" y="3" width="10" height="2.5" rx="0.5" fill="#00ACD7"/>- <rect x="1" y="6.75" width="14" height="2.5" rx="0.5" fill="#00ACD7"/>- <rect x="1" y="10.5" width="6" height="2.5" rx="0.5" fill="#00ACD7"/>- </svg>+ <svg class={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+ <rect x="1" y="3" width="10" height="2.5" rx="0.5" fill="#00ACD7" />+ <rect x="1" y="6.75" width="14" height="2.5" rx="0.5" fill="#00ACD7" />+ <rect x="1" y="10.5" width="6" height="2.5" rx="0.5" fill="#00ACD7" />+ </svg>{:else if framework === 'chi'}- <img src="/chi.png" alt="Chi" class={className} />+ <img src="/chi.png" alt="Chi" class={className} />{:else if framework === 'fasthttp'}- <img src="/fasthttp.png" alt="FastHTTP" class={className} />+ <img src="/fasthttp.png" alt="FastHTTP" class={className} />{:else if framework === 'stdlib'}- <img src="/stdlib.png" alt="Standard Library" class={className} />+ <img src="/stdlib.png" alt="Standard Library" class={className} />{:else if framework === 'react' || framework === 'react-native'}- <svg class={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">- <circle cx="8" cy="8" r="1.5" fill="#61DAFB"/>- <ellipse cx="8" cy="8" rx="6.5" ry="2.5" stroke="#61DAFB" stroke-width="0.8" fill="none"/>- <ellipse cx="8" cy="8" rx="6.5" ry="2.5" stroke="#61DAFB" stroke-width="0.8" fill="none" transform="rotate(60 8 8)"/>- <ellipse cx="8" cy="8" rx="6.5" ry="2.5" stroke="#61DAFB" stroke-width="0.8" fill="none" transform="rotate(120 8 8)"/>- </svg>+ <svg class={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+ <circle cx="8" cy="8" r="1.5" fill="#61DAFB" />+ <ellipse cx="8" cy="8" rx="6.5" ry="2.5" stroke="#61DAFB" stroke-width="0.8" fill="none" />+ <ellipse+ cx="8"+ cy="8"+ rx="6.5"+ ry="2.5"+ stroke="#61DAFB"+ stroke-width="0.8"+ fill="none"+ transform="rotate(60 8 8)"+ />+ <ellipse+ cx="8"+ cy="8"+ rx="6.5"+ ry="2.5"+ stroke="#61DAFB"+ stroke-width="0.8"+ fill="none"+ transform="rotate(120 8 8)"+ />+ </svg>{:else if framework === 'svelte'}- <img src="/svelte.png" alt="Svelte" class={className} />+ <img src="/svelte.png" alt="Svelte" class={className} />{:else if framework === 'vuejs'}- <svg class={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">- <path d="M12.8 1H10.4L8 5L5.6 1H3.2L8 9.5L12.8 1Z" fill="#41B883"/>- <path d="M15 1H12.8L8 9.5L3.2 1H1L8 13L15 1Z" fill="#41B883" opacity="0.6"/>- <path d="M12.8 1H10.4L8 5L5.6 1H3.2L8 9.5L12.8 1Z" fill="#35495E"/>- </svg>+ <svg class={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path d="M12.8 1H10.4L8 5L5.6 1H3.2L8 9.5L12.8 1Z" fill="#41B883" />+ <path d="M15 1H12.8L8 9.5L3.2 1H1L8 13L15 1Z" fill="#41B883" opacity="0.6" />+ <path d="M12.8 1H10.4L8 5L5.6 1H3.2L8 9.5L12.8 1Z" fill="#35495E" />+ </svg>{:else if framework === 'nextjs'}- <img src="/nextjs.png" alt="Next.js" class={className} />+ <img src="/nextjs.png" alt="Next.js" class={className} />{:else if framework === 'nestjs'}- <img src="/nestjs.png" alt="NestJS" class={className} />+ <img src="/nestjs.png" alt="NestJS" class={className} />{:else if framework === 'express'}- <img src="/express.png" alt="Express" class={className} />+ <img src="/express.png" alt="Express" class={className} />{:else if framework === 'remix'}- <img src="/remix.png" alt="Remix" class={className} />+ <img src="/remix.png" alt="Remix" class={className} />{:else if framework === 'jquery'}- <img src="/jquery.png" alt="jQuery" class={className} />+ <img src="/jquery.png" alt="jQuery" class={className} />{:else if framework === 'hono'}- <img src="/hono.png" alt="Hono" class={className} />+ <img src="/hono.png" alt="Hono" class={className} />{:else if framework === 'cloudflare'}- <img src="/cloudflare.png" alt="Cloudflare" class={className} />+ <img src="/cloudflare.png" alt="Cloudflare" class={className} />{:else if framework === 'opentelemetry'}- <img src="/opentelemetry.png" alt="OpenTelemetry" class={className} />+ <img src="/opentelemetry.png" alt="OpenTelemetry" class={className} />{:else if framework === 'symfony'}- <img src="/symfony.png" alt="Symfony" class={className} />+ <img src="/symfony.png" alt="Symfony" class={className} />{:else if framework === 'laravel'}- <img src="/laravel.png" alt="Laravel" class={className} />+ <img src="/laravel.png" alt="Laravel" class={className} />{:else if framework === 'django'}- <img src="/django.png" alt="Django" class={className} style="object-fit: contain;" />+ <img src="/django.png" alt="Django" class={className} style="object-fit: contain;" />{:else if framework === 'flutter'}- <img src="/flutter.png" alt="Flutter" class={className} style="object-fit: contain;" />+ <img src="/flutter.png" alt="Flutter" class={className} style="object-fit: contain;" />{:else if framework === 'android'}- <img src="/android.png" alt="Android" class={className} style="object-fit: contain;" />+ <img src="/android.png" alt="Android" class={className} style="object-fit: contain;" />{:else if framework === 'ios'}- <svg class={className} viewBox="0 1 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">- <path d="M11.05 8.5c-.02-1.5 1.23-2.22 1.28-2.26-.7-1.02-1.78-1.16-2.17-1.18-.92-.09-1.8.54-2.27.54-.47 0-1.19-.53-1.96-.51-1.01.01-1.94.59-2.46 1.49-1.05 1.82-.27 4.51.76 5.99.5.72 1.1 1.53 1.88 1.5.76-.03 1.04-.49 1.96-.49.91 0 1.17.49 1.97.47.81-.01 1.33-.73 1.83-1.46.58-.84.81-1.65.83-1.69-.02-.01-1.59-.61-1.61-2.43zM9.6 4.07c.42-.51.7-1.21.62-1.91-.6.02-1.33.4-1.76.91-.39.45-.73 1.17-.64 1.85.67.05 1.36-.34 1.78-.85z"/>- </svg>+ <svg class={className} viewBox="0 1 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">+ <path+ d="M11.05 8.5c-.02-1.5 1.23-2.22 1.28-2.26-.7-1.02-1.78-1.16-2.17-1.18-.92-.09-1.8.54-2.27.54-.47 0-1.19-.53-1.96-.51-1.01.01-1.94.59-2.46 1.49-1.05 1.82-.27 4.51.76 5.99.5.72 1.1 1.53 1.88 1.5.76-.03 1.04-.49 1.96-.49.91 0 1.17.49 1.97.47.81-.01 1.33-.73 1.83-1.46.58-.84.81-1.65.83-1.69-.02-.01-1.59-.61-1.61-2.43zM9.6 4.07c.42-.51.7-1.21.62-1.91-.6.02-1.33.4-1.76.91-.39.45-.73 1.17-.64 1.85.67.05 1.36-.34 1.78-.85z"+ />+ </svg>{:else}- <img src="/custom.png" alt="Custom" class={className} />+ <img src="/custom.png" alt="Custom" class={className} />{/if}diff --git a/frontend/src/lib/components/issue-trend-chart.svelte b/frontend/src/lib/components/issue-trend-chart.svelteindex 5ae8fb71..28119d1a 100644--- a/frontend/src/lib/components/issue-trend-chart.svelte+++ b/frontend/src/lib/components/issue-trend-chart.svelte@@ -1,11 +1,15 @@<script lang="ts">- import * as Tooltip from "$lib/components/ui/tooltip";+ import * as Tooltip from '$lib/components/ui/tooltip';+ import { SvelteMap } from 'svelte/reactivity';import { formatDateTime, getNow } from '$lib/utils/formatters';import { getTimezone } from '$lib/state/timezone.svelte';type TrendPoint = { timestamp: string; count: number };- let { trend = [], timezone }: {+ let {+ trend = [],+ timezone+ }: {trend: TrendPoint[];timezone?: string;} = $props();@@ -22,7 +26,7 @@const result: { hour: Date; count: number }[] = [];// Create a map of hour -> count from trend data- const trendMap = new Map<string, number>();+ const trendMap = new SvelteMap<string, number>();for (const point of trend) {const date = new Date(point.timestamp);const key = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}-${date.getHours()}`;@@ -45,7 +49,7 @@// Actual max from dataconst actualMax = $derived(() => {- return Math.max(...hourlyData().map(d => d.count), 0);+ return Math.max(...hourlyData().map((d) => d.count), 0);});// Scale max - at least SCALE_MAX, or higher if data exceeds it@@ -62,20 +66,20 @@<div class="relative h-8 w-44 flex-shrink-0"><!-- Solid bottom line -->- <div class="absolute left-0 right-7 bottom-0 border-t border-muted-foreground/30"></div>+ <div class="absolute right-7 bottom-0 left-0 border-t border-muted-foreground/30"></div><!-- Dashed line at actual max -->{#if actualMax() > 0}<div- class="absolute left-0 right-7 h-[1px]"+ class="absolute right-7 left-0 h-[1px]"style="bottom: {linePositionPct()}%; background: repeating-linear-gradient(to right, var(--muted-foreground) 0, var(--muted-foreground) 4px, transparent 4px, transparent 7px); opacity: 0.4;"></div><!-- Max count label --><span- class="absolute right-1 text-[10px] w-[20px] font-medium text-muted-foreground tabular-nums"+ class="absolute right-1 w-[20px] text-[10px] font-medium text-muted-foreground tabular-nums"style="bottom: calc({linePositionPct()}% - 6px);">- {actualMax() > 999 ? (actualMax()/1000).toFixed(1) + "k" : actualMax()}+ {actualMax() > 999 ? (actualMax() / 1000).toFixed(1) + 'k' : actualMax()}</span>{/if}@@ -86,7 +90,7 @@{@const hasEvents = point.count > 0}{@const isPeak = hasEvents && point.count === actualMax()}<Tooltip.Root>- <Tooltip.Trigger class="flex-1 h-full flex items-end justify-center">+ <Tooltip.Trigger class="flex h-full flex-1 items-end justify-center"><divclass="w-full max-w-[5px] rounded-[2px] {hasEvents? isPeak@@ -96,9 +100,12 @@style="height: {Math.max(hasEvents ? 8 : 3, heightPct)}%;"></div></Tooltip.Trigger>- <Tooltip.Content side="top" class="py-2 px-3 !animate-none !transition-none">- <div class="font-medium text-sm">{point.count} {point.count === 1 ? 'Event' : 'Events'}</div>- <div class="text-muted-foreground text-xs">+ <Tooltip.Content side="top" class="!animate-none px-3 py-2 !transition-none">+ <div class="text-sm font-medium">+ {point.count}+ {point.count === 1 ? 'Event' : 'Events'}+ </div>+ <div class="text-xs text-muted-foreground">{formatDateTime(point.hour, { timezone: tz, format: 'full' })}</div></Tooltip.Content>diff --git a/frontend/src/lib/components/issues/event-card.svelte b/frontend/src/lib/components/issues/event-card.svelteindex b75da000..74de4f3d 100644--- a/frontend/src/lib/components/issues/event-card.svelte+++ b/frontend/src/lib/components/issues/event-card.svelte@@ -1,14 +1,11 @@<script lang="ts">+ import { resolve } from '$app/paths';import { goto } from '$app/navigation';import { Button } from '$lib/components/ui/button';import * as Card from '$lib/components/ui/card';import * as Tabs from '$lib/components/ui/tabs';- import { ArrowRight } from 'lucide-svelte';- import type {- ExceptionOccurrence,- LinkedTrace,- SessionRecording- } from '$lib/types/exceptions';+ import { ArrowRight } from '@lucide/svelte';+ import type { ExceptionOccurrence, LinkedTrace, SessionRecording } from '$lib/types/exceptions';import { formatDuration, getStatusColor, formatDateTime } from '$lib/utils/formatters';import { getTimezone } from '$lib/state/timezone.svelte';import { AttributesGrid } from '$lib/components/ui/attributes-grid';@@ -71,11 +68,7 @@<Card.Header class="flex flex-row items-center justify-between gap-2"><Card.Title>Session Replay</Card.Title>{#if sessionId}- <Button- variant="outline"- size="sm"- onclick={() => goto(`/sessions/${sessionId}`)}- >+ <Button variant="outline" size="sm" onclick={() => goto(resolve(`/sessions/${sessionId}`))}>View full session<ArrowRight class="size-4" /></Button>@@ -85,7 +78,7 @@{#key recordingEvents}<SessionReplaybind:this={replayRef}- events={recordingEvents as any}+ events={recordingEvents}onTimeUpdate={(ms) => (currentTimeMs = ms)}/>{/key}@@ -95,11 +88,7 @@<Card.Root><Card.Header class="flex flex-row items-center justify-between gap-2"><Card.Title>Session</Card.Title>- <Button- variant="outline"- size="sm"- onclick={() => goto(`/sessions/${sessionId}`)}- >+ <Button variant="outline" size="sm" onclick={() => goto(resolve(`/sessions/${sessionId}`))}>View full session<ArrowRight class="size-4" /></Button>@@ -116,8 +105,8 @@<Card.Header><Card.Title>Session Context</Card.Title><Card.Description>- The last seconds of console output and recorded actions before this- exception. Times are offsets from the start of the recording.+ The last seconds of console output and recorded actions before this exception. Times are+ offsets from the start of the recording.</Card.Description></Card.Header><Card.Content>@@ -229,7 +218,9 @@size="sm"onclick={() =>goto(- `/tasks/${encodeURIComponent(linkedTrace.endpoint)}/${linkedTrace.id}?preset=24h`+ resolve(+ `/tasks/${encodeURIComponent(linkedTrace.endpoint)}/${linkedTrace.id}?preset=24h`+ ))}>View Task Details@@ -241,7 +232,9 @@size="sm"onclick={() =>goto(- `/endpoints/${encodeURIComponent(linkedTrace.endpoint)}/${linkedTrace.id}?preset=24h`+ resolve(+ `/endpoints/${encodeURIComponent(linkedTrace.endpoint)}/${linkedTrace.id}?preset=24h`+ ))}>View Endpoint Details@@ -254,5 +247,9 @@</Card.Root>{#if linkedTrace?.distributedTraceId || occurrence.distributedTraceId}- <DistributedTraceCard distributedTraceId={(linkedTrace?.distributedTraceId ?? occurrence.distributedTraceId)!} currentExceptionHash={occurrence.exceptionHash} recordedAt={linkedTrace?.recordedAt ?? occurrence.recordedAt} />+ <DistributedTraceCard+ distributedTraceId={(linkedTrace?.distributedTraceId ?? occurrence.distributedTraceId)!}+ currentExceptionHash={occurrence.exceptionHash}+ recordedAt={linkedTrace?.recordedAt ?? occurrence.recordedAt}+ />{/if}diff --git a/frontend/src/lib/components/issues/events-table.svelte b/frontend/src/lib/components/issues/events-table.svelteindex d9bde4b4..dfcad278 100644--- a/frontend/src/lib/components/issues/events-table.svelte+++ b/frontend/src/lib/components/issues/events-table.svelte@@ -1,119 +1,126 @@<script lang="ts">- import { createRowClickHandler } from '$lib/utils/navigation';- import * as Card from "$lib/components/ui/card";- import * as Table from "$lib/components/ui/table";- import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";- import { TableEmptyState } from "$lib/components/ui/table-empty-state";- import { ViewAllTableRow } from "$lib/components/ui/view-all-table-row";- import type { ExceptionOccurrence } from '$lib/types/exceptions';- import { formatDateTime, truncateStackTrace } from '$lib/utils/formatters';- import { getTimezone } from '$lib/state/timezone.svelte';- import { projectsState, isFrontendFramework } from '$lib/state/projects.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import * as Card from '$lib/components/ui/card';+ import * as Table from '$lib/components/ui/table';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { ViewAllTableRow } from '$lib/components/ui/view-all-table-row';+ import type { ExceptionOccurrence } from '$lib/types/exceptions';+ import { formatDateTime, truncateStackTrace } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import { projectsState, isFrontendFramework } from '$lib/state/projects.svelte';- interface Props {- occurrences: ExceptionOccurrence[];- exceptionHash: string;- total: number;- hasMore?: boolean;- showViewAll?: boolean;- currentExceptionId?: string;- timezone?: string;- }+ interface Props {+ occurrences: ExceptionOccurrence[];+ exceptionHash: string;+ total: number;+ hasMore?: boolean;+ showViewAll?: boolean;+ currentExceptionId?: string;+ timezone?: string;+ }- let {- occurrences,- exceptionHash,- total,- hasMore = false,- showViewAll = true,- currentExceptionId,- timezone- }: Props = $props();+ let {+ occurrences,+ exceptionHash,+ total,+ hasMore = false,+ showViewAll = true,+ currentExceptionId,+ timezone+ }: Props = $props();- const tz = $derived(timezone ?? getTimezone());- const isFrontend = $derived(- projectsState.currentProject?.framework- ? isFrontendFramework(projectsState.currentProject.framework)- : false- );+ const tz = $derived(timezone ?? getTimezone());+ const isFrontend = $derived(+ projectsState.currentProject?.framework+ ? isFrontendFramework(projectsState.currentProject.framework)+ : false+ );- function getRowUrl(occurrence: ExceptionOccurrence): string {- return `/issues/${exceptionHash}/${occurrence.id}?t=${encodeURIComponent(occurrence.recordedAt)}`;- }+ function getRowUrl(occurrence: ExceptionOccurrence): string {+ return `/issues/${exceptionHash}/${occurrence.id}?t=${encodeURIComponent(occurrence.recordedAt)}`;+ }- function isCurrentEvent(occurrence: ExceptionOccurrence): boolean {- return currentExceptionId !== undefined && occurrence.id === currentExceptionId;- }+ function isCurrentEvent(occurrence: ExceptionOccurrence): boolean {+ return currentExceptionId !== undefined && occurrence.id === currentExceptionId;+ }</script><Card.Root>- <Card.Header>- <Card.Title>Events</Card.Title>- <Card.Description>All occurrences of this exception ({total} total)</Card.Description>- </Card.Header>- <Card.Content>- <div class="rounded-md border overflow-hidden">- <Table.Root>- {#if occurrences.length > 0}- <Table.Header>- <Table.Row>- <TracewayTableHeader- label="Recorded At"- tooltip="When this occurrence was recorded"- />- {#if isFrontend}- <TracewayTableHeader- label="Title"- tooltip="Exception message from the first line of the stack trace"- />- {:else}- <TracewayTableHeader- label="Server"- tooltip="Server instance where error occurred"- />- <TracewayTableHeader- label="Trace"- tooltip="Trace ID if this occurred during a request"- />- {/if}- </Table.Row>- </Table.Header>- {/if}- <Table.Body>- {#if occurrences.length === 0}- <TableEmptyState colspan={isFrontend ? 2 : 3} message="No occurrences found." />- {:else}- {#each occurrences as occurrence}- <Table.Row- class="cursor-pointer hover:bg-muted/50 {isCurrentEvent(occurrence) ? 'bg-muted' : ''}"- onclick={createRowClickHandler(getRowUrl(occurrence))}- >- <Table.Cell>- {formatDateTime(occurrence.recordedAt, { timezone: tz })}- {#if isCurrentEvent(occurrence)}- <span class="ml-2 text-xs text-muted-foreground">(current)</span>- {/if}- </Table.Cell>- {#if isFrontend}- <Table.Cell class="font-mono text-sm text-muted-foreground truncate max-w-[400px]" title={occurrence.stackTrace.split('\n')[0]}>- {truncateStackTrace(occurrence.stackTrace, 60)}- </Table.Cell>- {:else}- <Table.Cell class="font-mono text-sm text-muted-foreground">- {occurrence.serverName || '-'}- </Table.Cell>- <Table.Cell class="font-mono text-sm">- {occurrence.traceId || '-'}- </Table.Cell>- {/if}- </Table.Row>- {/each}- {#if hasMore && showViewAll}- <ViewAllTableRow colspan={isFrontend ? 2 : 3} href={`/issues/${exceptionHash}/events`} label={`View all ${total} events`} />- {/if}- {/if}- </Table.Body>- </Table.Root>- </div>- </Card.Content>+ <Card.Header>+ <Card.Title>Events</Card.Title>+ <Card.Description>All occurrences of this exception ({total} total)</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="overflow-hidden rounded-md border">+ <Table.Root>+ {#if occurrences.length > 0}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader+ label="Recorded At"+ tooltip="When this occurrence was recorded"+ />+ {#if isFrontend}+ <TracewayTableHeader+ label="Title"+ tooltip="Exception message from the first line of the stack trace"+ />+ {:else}+ <TracewayTableHeader+ label="Server"+ tooltip="Server instance where error occurred"+ />+ <TracewayTableHeader+ label="Trace"+ tooltip="Trace ID if this occurred during a request"+ />+ {/if}+ </Table.Row>+ </Table.Header>+ {/if}+ <Table.Body>+ {#if occurrences.length === 0}+ <TableEmptyState colspan={isFrontend ? 2 : 3} message="No occurrences found." />+ {:else}+ {#each occurrences as occurrence, __index (__index)}+ <Table.Row+ class="cursor-pointer {isCurrentEvent(occurrence) ? 'bg-muted' : ''}"+ onclick={createRowClickHandler(getRowUrl(occurrence))}+ >+ <Table.Cell>+ {formatDateTime(occurrence.recordedAt, { timezone: tz })}+ {#if isCurrentEvent(occurrence)}+ <span class="ml-2 text-xs text-muted-foreground">(current)</span>+ {/if}+ </Table.Cell>+ {#if isFrontend}+ <Table.Cell+ class="max-w-[400px] truncate font-mono text-sm text-muted-foreground"+ title={occurrence.stackTrace.split('\n')[0]}+ >+ {truncateStackTrace(occurrence.stackTrace, 60)}+ </Table.Cell>+ {:else}+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {occurrence.serverName || '-'}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm">+ {occurrence.traceId || '-'}+ </Table.Cell>+ {/if}+ </Table.Row>+ {/each}+ {#if hasMore && showViewAll}+ <ViewAllTableRow+ colspan={isFrontend ? 2 : 3}+ href={`/issues/${exceptionHash}/events`}+ label={`View all ${total} events`}+ />+ {/if}+ {/if}+ </Table.Body>+ </Table.Root>+ </div>+ </Card.Content></Card.Root>diff --git a/frontend/src/lib/components/issues/index.ts b/frontend/src/lib/components/issues/index.tsindex b764a56d..5233a536 100644--- a/frontend/src/lib/components/issues/index.ts+++ b/frontend/src/lib/components/issues/index.ts@@ -1,4 +1,3 @@export { default as StackTraceCard } from './stack-trace-card.svelte';export { default as EventCard } from './event-card.svelte';export { default as EventsTable } from './events-table.svelte';-export { default as PageHeader } from './page-header.svelte';diff --git a/frontend/src/lib/components/issues/page-header.svelte b/frontend/src/lib/components/issues/page-header.sveltedeleted file mode 100644index 35c945c2..00000000--- a/frontend/src/lib/components/issues/page-header.svelte+++ /dev/null@@ -1,39 +0,0 @@-<script lang="ts">- import type { Snippet } from 'svelte';- import { cn } from '$lib/utils.js';- import { Button } from '$lib/components/ui/button';- import { ArrowLeft } from 'lucide-svelte';-- interface Props {- title: string;- subtitle?: string;- onBack?: (e: MouseEvent) => void;- trailing?: Snippet;- }-- let { title, subtitle, onBack, trailing }: Props = $props();-</script>--<div class="flex items-start gap-4">- {#if onBack}- <Button variant="ghost" size="sm" onclick={onBack} class="h-8 w-8 p-0">- <ArrowLeft class="h-4 w-4" />- </Button>- {/if}- <div>- <div class="flex flex-wrap items-center gap-2">- <h2- class={cn(- 'font-semibold tracking-tight text-balance break-words',- onBack ? 'text-[25px] leading-8' : 'text-3xl'- )}- >- {title}- </h2>- {#if trailing}{@render trailing()}{/if}- </div>- {#if subtitle}- <p class="mt-1 font-mono text-sm text-muted-foreground">{subtitle}</p>- {/if}- </div>-</div>diff --git a/frontend/src/lib/components/issues/session-actions-table.svelte b/frontend/src/lib/components/issues/session-actions-table.svelteindex d322b710..c1a90ff2 100644--- a/frontend/src/lib/components/issues/session-actions-table.svelte+++ b/frontend/src/lib/components/issues/session-actions-table.svelte@@ -101,10 +101,10 @@});</script>-<div bind:this={scrollEl} class="rounded-md border max-h-[440px] overflow-y-auto">+<div bind:this={scrollEl} class="max-h-[440px] overflow-y-auto rounded-md border"><Table.Root>{#if actions.length > 0}- <Table.Header class="sticky top-0 bg-background z-10">+ <Table.Header class="sticky top-0 z-10 bg-background"><Table.Row><TracewayTableHeaderlabel="Time"@@ -127,11 +127,11 @@{#if actions.length === 0}<TableEmptyState colspan={3} message="No actions captured for this session." />{:else}- {#each actions as entry, i}+ {#each actions as entry, i (i)}<Table.Rowonclick={() => onSeek?.(offsetMs(entry.timestamp))}- class="cursor-pointer hover:bg-muted/50 {i === activeIndex- ? 'bg-primary/10 border-l-2 border-l-primary'+ class="cursor-pointer {i === activeIndex+ ? 'border-l-2 border-l-primary bg-primary/10': ''}"><Table.Cell class="font-mono text-xs text-muted-foreground tabular-nums">@@ -140,10 +140,7 @@<Table.Cell class="font-mono text-xs uppercase {typeColor(entry.type)}">{entry.type}</Table.Cell>- <Table.Cell- class="font-mono text-xs truncate max-w-[600px]"- title={summary(entry)}- >+ <Table.Cell class="max-w-[600px] truncate font-mono text-xs" title={summary(entry)}>{summary(entry)}</Table.Cell></Table.Row>diff --git a/frontend/src/lib/components/issues/session-logs-table.svelte b/frontend/src/lib/components/issues/session-logs-table.svelteindex 5daa8bbc..6efe90fd 100644--- a/frontend/src/lib/components/issues/session-logs-table.svelte+++ b/frontend/src/lib/components/issues/session-logs-table.svelte@@ -98,10 +98,10 @@{#if logs.length === 0}<TableEmptyState colspan={3} message="No logs captured for this session." />{:else}- {#each logs as entry, i}+ {#each logs as entry, i (i)}<Table.Rowonclick={() => onSeek?.(offsetMs(entry.timestamp))}- class="cursor-pointer hover:bg-muted/50 {i === activeIndex+ class="cursor-pointer {i === activeIndex? 'border-l-2 border-l-primary bg-primary/10': ''}">diff --git a/frontend/src/lib/components/issues/session-replay.svelte b/frontend/src/lib/components/issues/session-replay.svelteindex 3d054e05..c0c2f8b2 100644--- a/frontend/src/lib/components/issues/session-replay.svelte+++ b/frontend/src/lib/components/issues/session-replay.svelte@@ -1,6 +1,7 @@<script lang="ts">import { onMount, onDestroy } from 'svelte';- import { Globe, Play, Pause, Maximize, Minimize } from 'lucide-svelte';+ import { Globe, Play, Pause, Maximize, Minimize } from '@lucide/svelte';+ import type { FlutterVideoEvent, SessionReplayEvent } from '$lib/types/exceptions';import type { eventWithTime } from '@rrweb/types';// Static side-effect import - keeps the rrweb-player stylesheet attached// to the page for the lifetime of the SPA, even across mount/unmount cycles.@@ -9,22 +10,14 @@// background fill on .replayer-wrapper until a hard refresh.import 'rrweb-player/dist/style.css';- interface FlutterVideoEvent {- type: 'flutter_video';- data: string;- format: string;- fps: number;- durationSeconds: number;- }-interface Props {- events: (eventWithTime & { data?: { href?: string } })[] | FlutterVideoEvent[] | null;+ events: SessionReplayEvent[] | null;onTimeUpdate?: (ms: number) => void;}let { events, onTimeUpdate }: Props = $props();let container: HTMLElement;- let player: any = null;+ let player: InstanceType<(typeof import('rrweb-player'))['default']> | null = null;let resizeObserver: ResizeObserver | null = null;let rafId: number | null = null;let lastReportedMs = -1;@@ -38,9 +31,7 @@}}- let isFlutterVideo = $derived(- events && events.length > 0 && (events[0] as any)?.type === 'flutter_video'- );+ let isFlutterVideo = $derived(events && events.length > 0 && events[0]?.type === 'flutter_video');let flutterVideoSrc = $derived.by(() => {if (!isFlutterVideo || !events) return '';@@ -236,12 +227,7 @@<span class="url-bar-text">Flutter Screen Recording</span></div><div class="flutter-video-container" bind:this={videoContainerEl}>- <video- bind:this={videoEl}- src={flutterVideoSrc}- playsinline- onclick={togglePlay}- >+ <video bind:this={videoEl} src={flutterVideoSrc} playsinline onclick={togglePlay}><track kind="captions" /></video><div class="fv-controller">@@ -258,7 +244,8 @@onclick={handleProgressClick}onkeydown={(e) => {if (!videoEl) return;- if (e.key === 'ArrowRight') videoEl.currentTime = Math.min(duration, currentTime + 5);+ if (e.key === 'ArrowRight')+ videoEl.currentTime = Math.min(duration, currentTime + 5);if (e.key === 'ArrowLeft') videoEl.currentTime = Math.max(0, currentTime - 5);}}>@@ -279,11 +266,8 @@<Play size={16} />{/if}</button>- {#each [1, 2, 4, 8] as s}- <button- class:active={playbackSpeed === s}- onclick={() => setSpeed(s)}- >+ {#each [1, 2, 4, 8] as s, __index (__index)}+ <button class:active={playbackSpeed === s} onclick={() => setSpeed(s)}>{s}x</button>{/each}diff --git a/frontend/src/lib/components/issues/stack-trace-card.svelte b/frontend/src/lib/components/issues/stack-trace-card.svelteindex 96346375..e1ece117 100644--- a/frontend/src/lib/components/issues/stack-trace-card.svelte+++ b/frontend/src/lib/components/issues/stack-trace-card.svelte@@ -1,10 +1,11 @@<script lang="ts">import * as Card from '$lib/components/ui/card';+ import { SvelteSet } from 'svelte/reactivity';import * as Tabs from '$lib/components/ui/tabs';import { formatDateTime } from '$lib/utils/formatters';import { getTimezone } from '$lib/state/timezone.svelte';import Button from '../ui/button/button.svelte';- import { Archive, ChevronRight, ChevronDown } from 'lucide-svelte';+ import { Archive, ChevronRight, ChevronDown } from '@lucide/svelte';import {parseStackTrace,looksLikeJava,@@ -54,7 +55,7 @@let expandedGroups = $state<Set<number>>(new Set());function toggleGroup(index: number) {- const next = new Set(expandedGroups);+ const next = new SvelteSet(expandedGroups);if (next.has(index)) {next.delete(index);} else {@@ -145,7 +146,7 @@</div>{#if viewMode === 'formatted'}<ol role="list" class="divide-y divide-border/60">- {#each parsed.groups as group, i}+ {#each parsed.groups as group, i (i)}{#if group.type === 'app'}{@const f = formatFrame(group.frame)}<li@@ -193,7 +194,7 @@role="list"class="divide-y divide-border/40 border-t border-border/40 bg-muted/30">- {#each group.frames as frame}+ {#each group.frames as frame, __index (__index)}{@const f = formatFrame(frame)}<liclass="flex flex-wrap items-baseline gap-x-1.5 py-2 pr-4 pl-9 font-mono text-sm text-muted-foreground tabular-nums"diff --git a/frontend/src/lib/components/oauth-buttons.svelte b/frontend/src/lib/components/oauth-buttons.svelteindex 6e1de813..3a8ee92f 100644--- a/frontend/src/lib/components/oauth-buttons.svelte+++ b/frontend/src/lib/components/oauth-buttons.svelte@@ -1,73 +1,82 @@<script lang="ts">- import { Button } from "$lib/components/ui/button";- import { onMount } from 'svelte';- import { stashSsoReturnTo } from '$lib/utils/navigation';+ import { Button } from '$lib/components/ui/button';+ import { onMount } from 'svelte';+ import { stashSsoReturnTo } from '$lib/utils/navigation';- let { passwordLoginEnabled = $bindable(true), loaded = $bindable(false) } = $props();+ let { passwordLoginEnabled = $bindable(true), loaded = $bindable(false) } = $props();- let providers = $state<string[]>([]);- let providerLabels = $state<Record<string, string>>({});+ let providers = $state<string[]>([]);+ let providerLabels = $state<Record<string, string>>({});- onMount(async () => {- try {- const response = await fetch('/api/auth/providers');- if (response.ok) {- const data = await response.json();- providers = data.providers || [];- providerLabels = data.providerLabels || {};- passwordLoginEnabled = data.passwordLoginEnabled ?? true;- }- } catch {- providers = [];- } finally {- loaded = true;- }- });+ onMount(async () => {+ try {+ const response = await fetch('/api/auth/providers');+ if (response.ok) {+ const data = await response.json();+ providers = data.providers || [];+ providerLabels = data.providerLabels || {};+ passwordLoginEnabled = data.passwordLoginEnabled ?? true;+ }+ } catch {+ providers = [];+ } finally {+ loaded = true;+ }+ });- function start(provider: string) {- stashSsoReturnTo(new URLSearchParams(window.location.search).get('returnTo'));- window.location.href = `/api/auth/start/${provider}`;- }+ function start(provider: string) {+ stashSsoReturnTo(new URLSearchParams(window.location.search).get('returnTo'));+ window.location.href = `/api/auth/start/${provider}`;+ }- function getLabel(provider: string): string {- if (provider === 'google') return 'Continue with Google';- if (provider === 'github') return 'Continue with GitHub';- const custom = providerLabels[provider];- if (provider === 'oidc') return `Continue with ${custom ?? 'SSO'}`;- return `Continue with ${custom ?? provider}`;- }+ function getLabel(provider: string): string {+ if (provider === 'google') return 'Continue with Google';+ if (provider === 'github') return 'Continue with GitHub';+ const custom = providerLabels[provider];+ if (provider === 'oidc') return `Continue with ${custom ?? 'SSO'}`;+ return `Continue with ${custom ?? provider}`;+ }</script>{#if loaded && providers.length > 0}- <div class="flex flex-col gap-2">- {#each providers as provider}- <Button- type="button"- variant="outline"- class="w-full"- onclick={() => start(provider)}- >- {#if provider === 'google'}- <svg class="size-4" viewBox="0 0 24 24" aria-hidden="true">- <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />- <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />- <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />- <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />- </svg>- {:else if provider === 'github'}- <svg class="size-4" viewBox="0 0 24 24" aria-hidden="true" fill="currentColor">- <path d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.1.79-.25.79-.56v-2.16c-3.2.7-3.87-1.37-3.87-1.37-.52-1.32-1.27-1.67-1.27-1.67-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.75 2.69 1.24 3.34.95.1-.74.4-1.24.72-1.53-2.55-.29-5.24-1.27-5.24-5.66 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.46.11-3.05 0 0 .96-.31 3.15 1.17.91-.25 1.89-.38 2.86-.39.97 0 1.95.13 2.86.39 2.18-1.48 3.14-1.17 3.14-1.17.62 1.59.23 2.76.11 3.05.74.8 1.18 1.82 1.18 3.07 0 4.4-2.69 5.36-5.25 5.65.41.36.78 1.07.78 2.15v3.18c0 .31.21.67.8.56C20.21 21.39 23.5 17.08 23.5 12 23.5 5.65 18.35.5 12 .5z" />- </svg>- {/if}- {getLabel(provider)}- </Button>- {/each}- {#if passwordLoginEnabled}- <div class="flex items-center gap-3 my-2">- <div class="flex-1 border-t"></div>- <p class="text-xs text-muted-foreground">or</p>- <div class="flex-1 border-t"></div>- </div>- {/if}- </div>+ <div class="flex flex-col gap-2">+ {#each providers as provider, __index (__index)}+ <Button type="button" variant="outline" class="w-full" onclick={() => start(provider)}>+ {#if provider === 'google'}+ <svg class="size-4" viewBox="0 0 24 24" aria-hidden="true">+ <path+ fill="#4285F4"+ d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"+ />+ <path+ fill="#34A853"+ d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"+ />+ <path+ fill="#FBBC05"+ d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"+ />+ <path+ fill="#EA4335"+ d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"+ />+ </svg>+ {:else if provider === 'github'}+ <svg class="size-4" viewBox="0 0 24 24" aria-hidden="true" fill="currentColor">+ <path+ d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.1.79-.25.79-.56v-2.16c-3.2.7-3.87-1.37-3.87-1.37-.52-1.32-1.27-1.67-1.27-1.67-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.75 2.69 1.24 3.34.95.1-.74.4-1.24.72-1.53-2.55-.29-5.24-1.27-5.24-5.66 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.46.11-3.05 0 0 .96-.31 3.15 1.17.91-.25 1.89-.38 2.86-.39.97 0 1.95.13 2.86.39 2.18-1.48 3.14-1.17 3.14-1.17.62 1.59.23 2.76.11 3.05.74.8 1.18 1.82 1.18 3.07 0 4.4-2.69 5.36-5.25 5.65.41.36.78 1.07.78 2.15v3.18c0 .31.21.67.8.56C20.21 21.39 23.5 17.08 23.5 12 23.5 5.65 18.35.5 12 .5z"+ />+ </svg>+ {/if}+ {getLabel(provider)}+ </Button>+ {/each}+ {#if passwordLoginEnabled}+ <div class="my-2 flex items-center gap-3">+ <div class="flex-1 border-t"></div>+ <p class="text-xs text-muted-foreground">or</p>+ <div class="flex-1 border-t"></div>+ </div>+ {/if}+ </div>{/if}diff --git a/frontend/src/lib/components/post-mortems/activity-sheet.svelte b/frontend/src/lib/components/post-mortems/activity-sheet.sveltenew file mode 100644index 00000000..6c5a0a7a--- /dev/null+++ b/frontend/src/lib/components/post-mortems/activity-sheet.svelte@@ -0,0 +1,108 @@+<script lang="ts">+ import { untrack } from 'svelte';+ import * as Sheet from '$lib/components/ui/sheet';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { FilePlus2, Pencil } from '@lucide/svelte';+ import { api } from '$lib/api';+ import { formatDateTime } from '$lib/utils/formatters';+ import { getErrorMessage } from '$lib/utils/errors';+ import { projectsState } from '$lib/state/projects.svelte';++ interface ActivityEvent {+ id: number;+ action: 'created' | 'updated';+ changes: string[];+ userName: string | null;+ createdAt: string;+ }++ interface Props {+ open: boolean;+ postMortemId: string;+ }++ let { open = $bindable(), postMortemId }: Props = $props();++ let events = $state<ActivityEvent[]>([]);+ let loading = $state(false);+ let error = $state('');+ let loadSeq = 0;++ $effect(() => {+ if (!open) return;+ void postMortemId;+ untrack(() => load());+ });++ async function load() {+ const projectId = projectsState.currentProjectId;+ if (projectId === null) return;+ const seq = ++loadSeq;+ loading = true;+ error = '';+ try {+ const res = (await api.get(`/post-mortems/${postMortemId}/activity`, {+ projectId+ })) as { events?: ActivityEvent[] };+ if (seq !== loadSeq) return;+ events = res.events || [];+ } catch (e) {+ if (seq !== loadSeq) return;+ error = e instanceof Error ? getErrorMessage(e) : 'Failed to load activity';+ } finally {+ if (seq === loadSeq) loading = false;+ }+ }++ function describe(event: ActivityEvent): string {+ if (event.action === 'created') return 'created this post-mortem';+ if (event.changes.length > 0) return `edited the ${event.changes.join(', ')}`;+ return 'edited this post-mortem';+ }+</script>++<Sheet.Root bind:open>+ <Sheet.Content side="right" class="flex w-full flex-col gap-0 overflow-y-auto sm:max-w-md">+ <Sheet.Header class="border-b px-6 pb-4">+ <Sheet.Title>Activity</Sheet.Title>+ <Sheet.Description>Every edit made to this post-mortem.</Sheet.Description>+ </Sheet.Header>++ <div class="flex-1 px-6 py-5">+ {#if loading}+ <div class="flex h-32 items-center justify-center">+ <LoadingCircle size="lg" />+ </div>+ {:else if error}+ <p class="text-sm text-red-500">{error}</p>+ {:else if events.length === 0}+ <p class="text-sm text-muted-foreground">No activity recorded yet.</p>+ {:else}+ <div class="space-y-5">+ {#each events as event (event.id)}+ <div class="flex gap-3">+ <div+ class="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground"+ >+ {#if event.action === 'created'}+ <FilePlus2 class="size-3.5" />+ {:else}+ <Pencil class="size-3.5" />+ {/if}+ </div>+ <div class="min-w-0">+ <p class="text-sm">+ <span class="font-medium">{event.userName || 'Someone'}</span>+ {describe(event)}+ </p>+ <p class="text-xs text-muted-foreground">+ {formatDateTime(event.createdAt, { format: 'short' })}+ </p>+ </div>+ </div>+ {/each}+ </div>+ {/if}+ </div>+ </Sheet.Content>+</Sheet.Root>diff --git a/frontend/src/lib/components/post-mortems/markdown-editor.svelte b/frontend/src/lib/components/post-mortems/markdown-editor.sveltenew file mode 100644index 00000000..dc7f3258--- /dev/null+++ b/frontend/src/lib/components/post-mortems/markdown-editor.svelte@@ -0,0 +1,277 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import * as Tabs from '$lib/components/ui/tabs';+ import { themeState } from '$lib/state/theme.svelte';++ interface Props {+ value: string;+ readonly?: boolean;+ }++ let { value = $bindable(), readonly = false }: Props = $props();++ let container = $state<HTMLDivElement | null>(null);+ let mode = $state<'rich' | 'markdown'>('rich');+ let ready = $state(false);+ let failed = $state(false);++ type CrepeInstance = {+ create: () => Promise<unknown>;+ destroy: () => void;+ getMarkdown: () => string;+ setReadonly: (value: boolean) => unknown;+ on: (fn: (api: { markdownUpdated: (fn: () => void) => void }) => void) => unknown;+ };+ type CrepeCtor = {+ new (config: {+ root: HTMLElement;+ defaultValue: string;+ featureConfigs: Record<string, unknown>;+ }): CrepeInstance;+ Feature: { Placeholder: string };+ };+ let CrepeClass: CrepeCtor | null = null;+ let crepe: CrepeInstance | null = null;+ let themeStyle: HTMLStyleElement | null = null;+ let lightCss = '';+ let darkCss = '';+ let destroyed = false;+ let createSeq = 0;++ async function ensureAssets(): Promise<boolean> {+ if (CrepeClass) return true;+ try {+ const [{ Crepe }, common, light, dark] = await Promise.all([+ import('@milkdown/crepe'),+ import('@milkdown/crepe/theme/common/style.css?inline'),+ import('@milkdown/crepe/theme/frame.css?inline'),+ import('@milkdown/crepe/theme/frame-dark.css?inline')+ ]);+ if (destroyed) return false;+ CrepeClass = Crepe as unknown as CrepeCtor;+ lightCss = light.default;+ darkCss = dark.default;++ const commonStyle = document.createElement('style');+ commonStyle.dataset.crepe = 'common';+ commonStyle.textContent = common.default;+ document.head.appendChild(commonStyle);+ themeStyle = document.createElement('style');+ themeStyle.dataset.crepe = 'theme';+ themeStyle.textContent = themeState.isDark ? darkCss : lightCss;+ document.head.appendChild(themeStyle);+ return true;+ } catch {+ return false;+ }+ }++ async function showRich() {+ const seq = ++createSeq;+ failed = false;+ const loaded = await ensureAssets();+ if (destroyed || seq !== createSeq) return;+ if (!loaded || !CrepeClass || !container) {+ failed = true;+ return;+ }+ try {+ const instance = new CrepeClass({+ root: container,+ defaultValue: value,+ featureConfigs: {+ [CrepeClass.Feature.Placeholder]: {+ text: 'Write the post-mortem: what happened, why, and what changes. Type / to add headings, lists, tables...'+ }+ }+ });+ instance.on((api) => {+ api.markdownUpdated(() => {+ value = instance.getMarkdown();+ });+ });+ instance.setReadonly(readonly);+ await instance.create();+ if (destroyed || seq !== createSeq) {+ instance.destroy();+ return;+ }+ crepe = instance;+ ready = true;+ } catch {+ if (!destroyed && seq === createSeq) failed = true;+ }+ }++ // The markdownUpdated listener is debounced; callers that are about to save+ // use this to pull the very latest content synchronously.+ export function flushPendingChanges() {+ if (crepe && ready && mode === 'rich') {+ try {+ value = crepe.getMarkdown();+ } catch {+ // keep the last synced value+ }+ }+ }++ function destroyEditor() {+ createSeq++;+ crepe?.destroy();+ crepe = null;+ ready = false;+ }++ function setMode(next: string) {+ if ((next !== 'rich' && next !== 'markdown') || next === mode) return;+ mode = next;+ if (next === 'markdown') {+ // The markdownUpdated listener is debounced, so pull the latest content+ // directly before tearing the instance down.+ if (crepe && ready) {+ try {+ value = crepe.getMarkdown();+ } catch {+ // keep the last synced value+ }+ }+ destroyEditor();+ failed = false;+ } else {+ showRich();+ }+ }++ onMount(() => {+ showRich();+ return () => {+ destroyed = true;+ crepe?.destroy();+ crepe = null;+ for (const style of document.head.querySelectorAll('style[data-crepe]')) {+ style.remove();+ }+ };+ });++ // Read the reactive values unconditionally: `crepe`/`themeStyle` are plain+ // variables, and short-circuiting past the reactive reads while they are+ // still null would leave these effects with no dependencies to re-run on.+ $effect(() => {+ const ro = readonly;+ crepe?.setReadonly(ro);+ });++ $effect(() => {+ const isDark = themeState.isDark;+ if (!ready || !themeStyle) return;+ themeStyle.textContent = isDark ? darkCss : lightCss;+ });+</script>++<div class="relative space-y-2">+ <div class="flex justify-end sm:absolute sm:top-4 sm:right-2 sm:z-20">+ <Tabs.Root value={mode} onValueChange={setMode}>+ <Tabs.List class="h-8">+ <Tabs.Trigger value="rich" class="px-2.5 py-0.5 text-xs">Rich text</Tabs.Trigger>+ <Tabs.Trigger value="markdown" class="px-2.5 py-0.5 text-xs">Markdown</Tabs.Trigger>+ </Tabs.List>+ </Tabs.Root>+ </div>++ <div class="relative min-h-[420px] rounded-md border">+ {#if mode === 'rich' && failed}+ <div class="flex min-h-[420px] items-center justify-center px-4 text-center text-sm text-red-500">+ Failed to load the editor. Switch to Markdown to keep editing.+ </div>+ {:else if mode === 'rich' && !ready}+ <div class="absolute inset-0 flex items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ {/if}+ {#if mode === 'markdown'}+ <textarea+ bind:value+ {readonly}+ spellcheck={false}+ placeholder="Write the post-mortem in Markdown..."+ class="post-mortem-raw block min-h-[420px] w-full resize-y rounded-md bg-transparent px-4 py-5 text-sm outline-none placeholder:text-muted-foreground sm:px-8 sm:py-6"+ ></textarea>+ {/if}+ <div+ bind:this={container}+ class="post-mortem-editor"+ class:hidden={mode !== 'rich' || failed}+ class:invisible={!ready}+ ></div>+ </div>+</div>++<style>+ .post-mortem-editor :global(.milkdown) {+ --crepe-font-title: var(--font-body);+ --crepe-font-default: var(--font-body);+ --crepe-font-code: var(--font-code);+ --crepe-color-background: transparent;+ min-height: 420px;+ }+ .post-mortem-editor :global(.milkdown .ProseMirror) {+ min-height: 380px;+ padding: 0.875rem 1rem 1.25rem;+ }+ /* Headings carry a large margin-top for spacing between sections; on the+ first block it just pushes the content away from the top border. Cursor+ widgets (absolute-positioned divs) come and go as the first child, so+ match the first real content block, not literally :first-child. */+ .post-mortem-editor+ :global(+ .milkdown+ .ProseMirror+ > :nth-child(1 of :not(.ProseMirror-widget, .prosemirror-virtual-cursor))+ ) {+ margin-top: 0;+ }+ .post-mortem-editor :global(.milkdown .ProseMirror h1),+ .post-mortem-editor :global(.milkdown .ProseMirror h2),+ .post-mortem-editor :global(.milkdown .ProseMirror h3) {+ font-weight: 650;+ letter-spacing: -0.02em;+ }+ @media (min-width: 640px) {+ .post-mortem-editor :global(.milkdown .ProseMirror) {+ padding: 1rem 2rem 1.5rem;+ }+ }+ .post-mortem-editor :global(.milkdown .milkdown-toolbar),+ .post-mortem-editor :global(.milkdown .milkdown-slash-menu),+ .post-mortem-editor :global(.milkdown .milkdown-link-preview),+ .post-mortem-editor :global(.milkdown .milkdown-link-edit) {+ box-shadow: none;+ border: 1px solid var(--border);+ }+ /* The theme's outline gray reads as disabled; use the foreground color. */+ .post-mortem-editor :global(.milkdown .milkdown-toolbar .toolbar-item svg) {+ color: color-mix(in srgb, var(--foreground) 85%, transparent);+ fill: color-mix(in srgb, var(--foreground) 85%, transparent);+ }+ /* Formatting goes through the selection toolbar and the / menu; the floating+ gutter handle (drag grip + plus) is hidden entirely. */+ .post-mortem-editor :global(.milkdown .milkdown-block-handle) {+ display: none;+ }+ /* Crepe renders the caret as a 2px virtual cursor in the gray outline color;+ match the native thin foreground caret instead. */+ .post-mortem-editor :global(.milkdown .ProseMirror-focused) {+ --prosemirror-virtual-cursor-color: var(--foreground);+ }+ .post-mortem-editor :global(.milkdown .ProseMirror .prosemirror-virtual-cursor) {+ border-left-width: 1px;+ }+ .post-mortem-editor :global(.milkdown .cm-editor .cm-content) {+ caret-color: var(--foreground);+ }+ .post-mortem-raw {+ font-family: var(--font-code);+ }+</style>diff --git a/frontend/src/lib/components/profiles/flame-graph.svelte b/frontend/src/lib/components/profiles/flame-graph.svelteindex 22e8fde3..40a93501 100644--- a/frontend/src/lib/components/profiles/flame-graph.svelte+++ b/frontend/src/lib/components/profiles/flame-graph.svelte@@ -27,7 +27,8 @@export function diffColor(delta: number): string {const mag = Math.min(1, Math.abs(delta));- if (delta > 0.001) return `hsl(8, ${Math.round(45 + mag * 45)}%, ${Math.round(68 - mag * 22)}%)`;+ if (delta > 0.001)+ return `hsl(8, ${Math.round(45 + mag * 45)}%, ${Math.round(68 - mag * 22)}%)`;if (delta < -0.001)return `hsl(140, ${Math.round(40 + mag * 45)}%, ${Math.round(66 - mag * 20)}%)`;return 'hsl(220, 6%, 78%)';diff --git a/frontend/src/lib/components/profiles/flame-graph.test.ts b/frontend/src/lib/components/profiles/flame-graph.test.tsindex 311e20e0..ab93d461 100644--- a/frontend/src/lib/components/profiles/flame-graph.test.ts+++ b/frontend/src/lib/components/profiles/flame-graph.test.ts@@ -51,9 +51,7 @@ describe('flameTooltipLabel', () => {});it('renders 0% and no parent/self when the total and parent are zero', () => {- expect(flameTooltipLabel('main.work', 10, 0, 0, 0, NS)).toBe(- 'main.work · 10 ns (0% of total)'- );+ expect(flameTooltipLabel('main.work', 10, 0, 0, 0, NS)).toBe('main.work · 10 ns (0% of total)');});});diff --git a/frontend/src/lib/components/profiles/profile-series-chart.svelte b/frontend/src/lib/components/profiles/profile-series-chart.svelteindex 80156c33..3b8008e9 100644--- a/frontend/src/lib/components/profiles/profile-series-chart.svelte+++ b/frontend/src/lib/components/profiles/profile-series-chart.svelte@@ -36,7 +36,14 @@onSelectRange?: (fromIso: string, toIso: string) => void;}- let { series = [], groups = [], unit, isRate = false, height = 140, onSelectRange }: Props = $props();+ let {+ series = [],+ groups = [],+ unit,+ isRate = false,+ height = 140,+ onSelectRange+ }: Props = $props();const timezone = $derived(getTimezone());@@ -60,7 +67,8 @@const padB = 20;const lines = $derived.by(() => {- if (groups.length) return groups.map((g, i) => ({ key: g.key, points: g.points, color: seriesColor(i) }));+ if (groups.length)+ return groups.map((g, i) => ({ key: g.key, points: g.points, color: seriesColor(i) }));if (series.length) return [{ key: '', points: series, color: 'var(--primary)' }];return [] as { key: string; points: SeriesPoint[]; color: string }[];});@@ -199,23 +207,51 @@{#if hoverIdx >= 0 && lines[0]?.points[hoverIdx]}{@const hx = xOf(new Date(lines[0].points[hoverIdx].timestamp).getTime())}- <line x1={hx} y1={padT} x2={hx} y2={padT + plotH} class="stroke-muted-foreground/40" stroke-width="1" />+ <line+ x1={hx}+ y1={padT}+ x2={hx}+ y2={padT + plotH}+ class="stroke-muted-foreground/40"+ stroke-width="1"+ />{/if}{#if dragStart !== null && dragEnd !== null}{@const a = Math.min(dragStart, dragEnd)}{@const b = Math.max(dragStart, dragEnd)}- <rect x={a} y={padT} width={Math.max(0, b - a)} height={plotH} class="fill-primary/15 stroke-primary/50" stroke-width="1" />+ <rect+ x={a}+ y={padT}+ width={Math.max(0, b - a)}+ height={plotH}+ class="fill-primary/15 stroke-primary/50"+ stroke-width="1"+ />{/if}- <text x={padL} y={padT - 2} class="fill-muted-foreground" style="font-size: 10px;">{fmt(vMax)}</text>- <text x={padL} y={height - 6} class="fill-muted-foreground" style="font-size: 10px;">{fmtTime(tMin)}</text>- <text x={padL + plotW} y={height - 6} text-anchor="end" class="fill-muted-foreground" style="font-size: 10px;">{fmtTime(tMax)}</text>+ <text x={padL} y={padT - 2} class="fill-muted-foreground" style="font-size: 10px;"+ >{fmt(vMax)}</text+ >+ <text x={padL} y={height - 6} class="fill-muted-foreground" style="font-size: 10px;"+ >{fmtTime(tMin)}</text+ >+ <text+ x={padL + plotW}+ y={height - 6}+ text-anchor="end"+ class="fill-muted-foreground"+ style="font-size: 10px;">{fmtTime(tMax)}</text+ ></svg>{#if hoverIdx >= 0 && lines[0]?.points[hoverIdx]}- <div class="pointer-events-none absolute right-1 top-1 rounded border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-sm">- <div class="text-muted-foreground">{fmtTime(new Date(lines[0].points[hoverIdx].timestamp).getTime())}</div>+ <div+ class="pointer-events-none absolute top-1 right-1 rounded border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-sm"+ >+ <div class="text-muted-foreground">+ {fmtTime(new Date(lines[0].points[hoverIdx].timestamp).getTime())}+ </div>{#each lines as line (line.key)}<div class="flex items-center gap-1.5 tabular-nums"><span class="inline-block h-2 w-2 rounded-sm" style="background: {line.color}"></span>@@ -240,6 +276,8 @@{/if}{#if onSelectRange && allPoints.length >= 2}- <div class="mt-1 text-center text-[11px] text-muted-foreground">Drag to zoom into a time range</div>+ <div class="mt-1 text-center text-[11px] text-muted-foreground">+ Drag to zoom into a time range+ </div>{/if}</div>diff --git a/frontend/src/lib/components/profiles/top-functions-table.svelte b/frontend/src/lib/components/profiles/top-functions-table.svelteindex 65f68ca9..25615b8a 100644--- a/frontend/src/lib/components/profiles/top-functions-table.svelte+++ b/frontend/src/lib/components/profiles/top-functions-table.svelte@@ -10,9 +10,16 @@<script lang="ts">import * as Table from '$lib/components/ui/table';+ import { SvelteMap } from 'svelte/reactivity';import TracewayTableHeader from '$lib/components/ui/traceway-table-header/traceway-table-header.svelte';import { Button } from '$lib/components/ui/button';import { formatValue } from '$lib/utils/profile-format';+ import {+ getSortState,+ setSortState,+ handleSortClick,+ type SortDirection+ } from '$lib/utils/sort-storage';interface Props {rows: FunctionStat[];@@ -23,26 +30,25 @@let { rows, unit, onSelect, baselineRows }: Props = $props();- let sortField = $state<'flat' | 'cum'>('flat');- let sortDirection = $state<'asc' | 'desc'>('desc');+ const SORT_STORAGE_KEY = 'profile_functions';+ const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'flat', direction: 'desc' });+ let sortField = $state<'flat' | 'cum'>(initialSort.field === 'cum' ? 'cum' : 'flat');+ let sortDirection = $state<SortDirection>(initialSort.direction);let expanded = $state(false);const COLLAPSED = 15;const baseFlat = $derived.by(() => {- const m = new Map<string, number>();+ const m = new SvelteMap<string, number>();for (const r of baselineRows ?? []) m.set(r.name, r.flat);return m;});function onSort(field: string) {- const next = field as 'flat' | 'cum';- if (sortField === next) {- sortDirection = sortDirection === 'desc' ? 'asc' : 'desc';- } else {- sortField = next;- sortDirection = 'desc';- }+ const newSort = handleSortClick(field, sortField, sortDirection);+ sortField = newSort.field === 'cum' ? 'cum' : 'flat';+ sortDirection = newSort.direction;+ setSortState(SORT_STORAGE_KEY, newSort);}const sorted = $derived.by(() => {@@ -108,7 +114,7 @@<Table.Body>{#each visible as row (row.name)}<Table.Row- class={onSelect ? 'cursor-pointer hover:bg-muted/50' : ''}+ class={onSelect ? 'cursor-pointer' : ''}onclick={onSelect ? () => onSelect(row.name) : undefined}><Table.Cell class="max-w-[28rem] truncate font-mono text-xs" title={row.name}>diff --git a/frontend/src/lib/components/setup/ai-setup-steps.svelte b/frontend/src/lib/components/setup/ai-setup-steps.svelteindex a5bb1596..edb76c64 100644--- a/frontend/src/lib/components/setup/ai-setup-steps.svelte+++ b/frontend/src/lib/components/setup/ai-setup-steps.svelte@@ -42,8 +42,9 @@<h3 class="font-semibold">Run the Setup Prompt</h3></div><p class="mt-1 ml-9 text-sm text-muted-foreground">- Paste this prompt into your agent. Your instance URL and project token are already filled- in{sourceMapToken ? ', along with your source map upload token' : ''}.+ Paste this prompt into your agent. Your instance URL and project token are already filled in{sourceMapToken+ ? ', along with your source map upload token'+ : ''}.</p></div><div class="p-4">diff --git a/frontend/src/lib/components/setup/copyable-code-block.svelte b/frontend/src/lib/components/setup/copyable-code-block.svelteindex 94afa415..efe46a9d 100644--- a/frontend/src/lib/components/setup/copyable-code-block.svelte+++ b/frontend/src/lib/components/setup/copyable-code-block.svelte@@ -1,6 +1,5 @@<script lang="ts">- import { Button } from '$lib/components/ui/button';- import { Copy, Check } from 'lucide-svelte';+ import CopyButton from '$lib/components/traceway/copy-button.svelte';import Highlight from 'svelte-highlight';import type { LanguageFn } from 'highlight.js';import { themeState } from '$lib/state/theme.svelte';@@ -11,35 +10,17 @@language,wrap = false}: { code: string; language: { name: string; register: LanguageFn }; wrap?: boolean } = $props();-- let copied = $state(false);-- async function copy() {- await navigator.clipboard.writeText(code);- copied = true;- setTimeout(() => (copied = false), 2000);- }</script>-<div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copy}>- {#if copied}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>+<div class="flex items-start gap-2"><div- class="overflow-x-auto rounded-md text-sm {wrap ? 'wrap-code' : ''} {themeState.isDark- ? 'dark-code'- : 'light-code'}"+ class="min-w-0 flex-1 overflow-x-auto rounded-md text-sm {wrap+ ? 'wrap-code'+ : ''} {themeState.isDark ? 'dark-code' : 'light-code'}"><Highlight {language} {code} /></div>+ <CopyButton text={code} /></div><style>diff --git a/frontend/src/lib/components/setup/copyable-inline.svelte b/frontend/src/lib/components/setup/copyable-inline.svelteindex 1ce79592..f8e8aa15 100644--- a/frontend/src/lib/components/setup/copyable-inline.svelte+++ b/frontend/src/lib/components/setup/copyable-inline.svelte@@ -1,25 +1,10 @@<script lang="ts">- import { Button } from '$lib/components/ui/button';- import { Copy, Check } from 'lucide-svelte';+ import CopyButton from '$lib/components/traceway/copy-button.svelte';let { value }: { value: string } = $props();-- let copied = $state(false);-- async function copy() {- await navigator.clipboard.writeText(value);- copied = true;- setTimeout(() => (copied = false), 2000);- }</script><div class="flex items-center gap-2"><code class="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-sm break-all">{value}</code>- <Button variant="outline" size="sm" onclick={copy}>- {#if copied}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>+ <CopyButton text={value} /></div>diff --git a/frontend/src/lib/components/setup/copyable-prompt.svelte b/frontend/src/lib/components/setup/copyable-prompt.svelteindex cf9af5e8..146823f5 100644--- a/frontend/src/lib/components/setup/copyable-prompt.svelte+++ b/frontend/src/lib/components/setup/copyable-prompt.svelte@@ -1,35 +1,15 @@<script lang="ts">- import { Button } from '$lib/components/ui/button';- import { Copy, Check } from 'lucide-svelte';+ import CopyButton from '$lib/components/traceway/copy-button.svelte';import type { PromptPart } from '$lib/utils/ai-setup';let { parts }: { parts: PromptPart[] } = $props();const text = $derived(parts.map((p) => p.text).join(''));-- let copied = $state(false);-- async function copy() {- await navigator.clipboard.writeText(text);- copied = true;- setTimeout(() => (copied = false), 2000);- }</script>-<div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copy}>- {#if copied}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>+<div class="flex items-start gap-2"><code- class="block rounded-md bg-muted py-3 pr-24 pl-4 font-mono text-sm break-words whitespace-pre-wrap text-foreground"+ class="block min-w-0 flex-1 rounded-md bg-muted px-4 py-3 font-mono text-sm break-words whitespace-pre-wrap text-foreground">{#each parts as part, i (i)}{#if part.bold}@@ -39,4 +19,5 @@{/if}{/each}</code>+ <CopyButton {text} label="Copy" /></div>diff --git a/frontend/src/lib/components/setup/otel-exporter-config.svelte b/frontend/src/lib/components/setup/otel-exporter-config.svelteindex 1c1d8906..7ac4024a 100644--- a/frontend/src/lib/components/setup/otel-exporter-config.svelte+++ b/frontend/src/lib/components/setup/otel-exporter-config.svelte@@ -14,8 +14,8 @@<div><p class="mb-1 text-sm font-medium">OTLP Endpoint</p><p class="mb-2 text-xs text-muted-foreground">- Your SDK or Collector will append <code- class="rounded bg-muted px-1 py-0.5 font-mono text-xs">/v1/traces</code+ Your SDK or Collector will append <code class="rounded bg-muted px-1 py-0.5 font-mono text-xs"+ >/v1/traces</code>and<code class="rounded bg-muted px-1 py-0.5 font-mono text-xs">/v1/metrics</code> automatically.diff --git a/frontend/src/lib/components/setup/otel-setup-steps.svelte b/frontend/src/lib/components/setup/otel-setup-steps.svelteindex b6cab16b..1045a08c 100644--- a/frontend/src/lib/components/setup/otel-setup-steps.svelte+++ b/frontend/src/lib/components/setup/otel-setup-steps.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import { resolveHref } from '$lib/utils/links';import * as Tabs from '$lib/components/ui/tabs';import bash from 'svelte-highlight/languages/bash';import go from 'svelte-highlight/languages/go';@@ -9,12 +10,7 @@import csharp from 'svelte-highlight/languages/csharp';import ruby from 'svelte-highlight/languages/ruby';import yaml from 'svelte-highlight/languages/yaml';- import {- OTEL_TARGETS,- getOtelSteps,- type OtelStepLanguage,- type OtelTargetId- } from '$lib/utils/otel-setup';+ import { OTEL_TARGETS, getOtelSteps, type OtelStepLanguage } from '$lib/utils/otel-setup';import {getOtelTarget,setOtelTarget,@@ -109,7 +105,7 @@{#if step.link}<p class="pt-2 text-xs text-muted-foreground"><a- href={step.link.href}+ {...{ href: resolveHref(step.link.href) }}target="_blank"rel="noopener noreferrer"class="underline hover:text-foreground">{step.link.label}</adiff --git a/frontend/src/lib/components/setup/setup-mode-tabs.svelte b/frontend/src/lib/components/setup/setup-mode-tabs.svelteindex 363919c2..51ead655 100644--- a/frontend/src/lib/components/setup/setup-mode-tabs.svelte+++ b/frontend/src/lib/components/setup/setup-mode-tabs.svelte@@ -1,13 +1,11 @@<script lang="ts">import * as Tabs from '$lib/components/ui/tabs';import { setSetupMode, type SetupMode } from '$lib/utils/setup-storage';+ import { underlineTabTriggerClass, underlineTabListClass } from '$lib/utils/tabs';let { mode, onModeChange }: { mode: SetupMode; onModeChange: (mode: SetupMode) => void } =$props();- const tabTriggerClass =- '-mb-px rounded-none border-b-2 border-transparent bg-transparent px-0 pb-2.5 pt-0 text-sm font-medium text-muted-foreground shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none';-function handleChange(value: string) {if (value === 'ai' || value === 'manual') {setSetupMode(value);@@ -17,8 +15,8 @@</script><Tabs.Root value={mode} onValueChange={handleChange}>- <Tabs.List class="h-auto w-full justify-start gap-4 rounded-none border-b bg-transparent p-0">- <Tabs.Trigger value="ai" class={tabTriggerClass}>AI</Tabs.Trigger>- <Tabs.Trigger value="manual" class={tabTriggerClass}>Manual</Tabs.Trigger>+ <Tabs.List class={underlineTabListClass}>+ <Tabs.Trigger value="ai" class={underlineTabTriggerClass}>AI</Tabs.Trigger>+ <Tabs.Trigger value="manual" class={underlineTabTriggerClass}>Manual</Tabs.Trigger></Tabs.List></Tabs.Root>diff --git a/frontend/src/lib/components/setup/source-map-upload-card.svelte b/frontend/src/lib/components/setup/source-map-upload-card.svelteindex 974b902c..f78f3b62 100644--- a/frontend/src/lib/components/setup/source-map-upload-card.svelte+++ b/frontend/src/lib/components/setup/source-map-upload-card.svelte@@ -6,7 +6,7 @@CardHeader,CardTitle} from '$lib/components/ui/card';- import { KeyRound } from 'lucide-svelte';+ import { KeyRound } from '@lucide/svelte';import { projectsState, isProjectReadonly } from '$lib/state/projects.svelte';import SourceMapSetup from '$lib/components/source-map-setup.svelte';diff --git a/frontend/src/lib/components/source-map-setup.svelte b/frontend/src/lib/components/source-map-setup.svelteindex 6171a44b..ea499ce4 100644--- a/frontend/src/lib/components/source-map-setup.svelte+++ b/frontend/src/lib/components/source-map-setup.svelte@@ -1,15 +1,15 @@<script lang="ts">import { Button } from '$lib/components/ui/button';- import { Copy, Check, KeyRound, RefreshCw } from 'lucide-svelte';+ import { KeyRound, RefreshCw } from '@lucide/svelte';import { LoadingCircle } from '$lib/components/ui/loading-circle';import * as AlertDialog from '$lib/components/ui/alert-dialog';import * as Tabs from '$lib/components/ui/tabs';import { toast } from 'svelte-sonner';- import Highlight from 'svelte-highlight';import javascript from 'svelte-highlight/languages/javascript';import typescript from 'svelte-highlight/languages/typescript';import bash from 'svelte-highlight/languages/bash';- import { themeState } from '$lib/state/theme.svelte';+ import CopyButton from '$lib/components/traceway/copy-button.svelte';+ import CopyableCodeBlock from '$lib/components/setup/copyable-code-block.svelte';import { projectsState, isProjectReadonly } from '$lib/state/projects.svelte';type Bundler = 'vite' | 'rollup' | 'webpack';@@ -71,16 +71,6 @@ module.exports = {let bundler = $state<Bundler>('vite');let generatingToken = $state(false);- let copiedToken = $state(false);- let copiedPluginInstall = $state(false);- let copiedBundlerConfig = $state(false);- let copiedCommand = $state(false);- let copiedFlutterBuild = $state(false);- let copiedFlutterUpload = $state(false);- let copiedIosBuild = $state(false);- let copiedIosUpload = $state(false);- let copiedAndroidSetup = $state(false);- let copiedAndroidUpload = $state(false);const pluginInstallCommand = 'npm install -D @tracewayapp/bundler-plugin';@@ -163,72 +153,11 @@ traceway {try {await projectsState.generateSourceMapToken();regenerateDialogOpen = false;- toast.success('Successfully regenerated the Upload Token', { position: 'top-center' });+ toast.success('Successfully regenerated the Upload Token');} finally {generatingToken = false;}}-- async function copyToken() {- if (!sourceMapToken) return;- await navigator.clipboard.writeText(sourceMapToken);- copiedToken = true;- setTimeout(() => (copiedToken = false), 2000);- }-- async function copyPluginInstall() {- await navigator.clipboard.writeText(pluginInstallCommand);- copiedPluginInstall = true;- setTimeout(() => (copiedPluginInstall = false), 2000);- }-- async function copyBundlerConfig() {- await navigator.clipboard.writeText(bundlerConfigs[bundler].code);- copiedBundlerConfig = true;- setTimeout(() => (copiedBundlerConfig = false), 2000);- }-- async function copyUploadCommand() {- await navigator.clipboard.writeText(uploadCommand);- copiedCommand = true;- setTimeout(() => (copiedCommand = false), 2000);- }-- async function copyFlutterBuild() {- await navigator.clipboard.writeText(flutterBuildCommand);- copiedFlutterBuild = true;- setTimeout(() => (copiedFlutterBuild = false), 2000);- }-- async function copyFlutterUpload() {- await navigator.clipboard.writeText(flutterUploadCommand);- copiedFlutterUpload = true;- setTimeout(() => (copiedFlutterUpload = false), 2000);- }-- async function copyIosBuild() {- await navigator.clipboard.writeText(iosBuildCommand);- copiedIosBuild = true;- setTimeout(() => (copiedIosBuild = false), 2000);- }-- async function copyIosUpload() {- await navigator.clipboard.writeText(iosUploadCommand);- copiedIosUpload = true;- setTimeout(() => (copiedIosUpload = false), 2000);- }-- async function copyAndroidSetup() {- await navigator.clipboard.writeText(androidSetupSnippet);- copiedAndroidSetup = true;- setTimeout(() => (copiedAndroidSetup = false), 2000);- }-- async function copyAndroidUpload() {- await navigator.clipboard.writeText(androidUploadCommand);- copiedAndroidUpload = true;- setTimeout(() => (copiedAndroidUpload = false), 2000);- }</script>{#if sourceMapToken}@@ -239,13 +168,7 @@ traceway {<code class="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-sm break-all">{sourceMapToken}</code>- <Button variant="outline" size="sm" onclick={copyToken}>- {#if copiedToken}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>+ <CopyButton text={sourceMapToken ?? ''} /><Buttonvariant="destructiveOutline"size="sm"@@ -259,26 +182,7 @@ traceway {{#if isFlutter}<div><p class="mb-2 text-sm font-medium">Step 1: Build with obfuscation enabled</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyFlutterBuild}>- {#if copiedFlutterBuild}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={bash} code={flutterBuildCommand} />- </div>- </div>+ <CopyableCodeBlock code={flutterBuildCommand} language={bash} /><p class="mt-2 text-xs text-muted-foreground">This writes a per-architecture .symbols file into build/symbols. The example builds anAndroid APK; other targets emit their own symbol files in the same directory.@@ -286,26 +190,7 @@ traceway {</div><div><p class="mb-2 text-sm font-medium">Step 2: Upload the symbols after each release build</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyFlutterUpload}>- {#if copiedFlutterUpload}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={bash} code={flutterUploadCommand} />- </div>- </div>+ <CopyableCodeBlock code={flutterUploadCommand} language={bash} /><p class="mt-2 text-xs text-muted-foreground">Run from your project root after each release. The uploader auto-discovers build/symbolsand pushes every architecture in one go; symbols are unique per build, so re-upload on@@ -317,26 +202,7 @@ traceway {{:else if isIOS}<div><p class="mb-2 text-sm font-medium">Step 1: Build an archive with dSYMs</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyIosBuild}>- {#if copiedIosBuild}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={bash} code={iosBuildCommand} />- </div>- </div>+ <CopyableCodeBlock code={iosBuildCommand} language={bash} /><p class="mt-2 text-xs text-muted-foreground">Release builds emit a .dSYM bundle per architecture under the archive's dSYMs directory.Replace MyApp with your scheme name.@@ -344,26 +210,7 @@ traceway {</div><div><p class="mb-2 text-sm font-medium">Step 2: Upload the dSYM after each release build</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyIosUpload}>- {#if copiedIosUpload}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={bash} code={iosUploadCommand} />- </div>- </div>+ <CopyableCodeBlock code={iosUploadCommand} language={bash} /><p class="mt-2 text-xs text-muted-foreground">Upload the Mach-O DWARF inside the .dSYM bundle. Symbols are keyed by build UUID, sore-upload on each release.@@ -372,26 +219,7 @@ traceway {{:else if isAndroid}<div><p class="mb-2 text-sm font-medium">Step 1: Apply the Traceway symbols Gradle plugin</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyAndroidSetup}>- {#if copiedAndroidSetup}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={javascript} code={androidSetupSnippet} />- </div>- </div>+ <CopyableCodeBlock code={androidSetupSnippet} language={javascript} /><p class="mt-2 text-xs text-muted-foreground">Add to your app module's <code class="font-mono">build.gradle.kts</code>. The pluginembeds a ProGuard UUID into BuildConfig (matching Honeycomb's@@ -401,26 +229,7 @@ traceway {</div><div><p class="mb-2 text-sm font-medium">Step 2: Build and upload after each release</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyAndroidUpload}>- {#if copiedAndroidUpload}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={bash} code={androidUploadCommand} />- </div>- </div>+ <CopyableCodeBlock code={androidUploadCommand} language={bash} /><p class="mt-2 text-xs text-muted-foreground">Uploads the R8 <code class="font-mono">mapping.txt</code> and the unstripped native<code class="font-mono">.so</code> libraries. Native symbols are keyed by GNU build-id, so re-upload@@ -431,26 +240,7 @@ traceway {{#if showBundlerSetup}<div><p class="mb-2 text-sm font-medium">Step 1: Install the bundler plugin</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyPluginInstall}>- {#if copiedPluginInstall}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={bash} code={pluginInstallCommand} />- </div>- </div>+ <CopyableCodeBlock code={pluginInstallCommand} language={bash} /></div><div><p class="mb-2 text-sm font-medium">Step 2: Add the plugin to your bundler</p>@@ -469,55 +259,17 @@ traceway {<p class="mb-2 font-mono text-xs text-muted-foreground">{bundlerConfigs[bundler].file}</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyBundlerConfig}>- {#if copiedBundlerConfig}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight- language={bundlerConfigs[bundler].language}- code={bundlerConfigs[bundler].code}- />- </div>- </div>+ <CopyableCodeBlock+ code={bundlerConfigs[bundler].code}+ language={bundlerConfigs[bundler].language}+ /></div>{/if}<div><p class="mb-2 text-sm font-medium">{showBundlerSetup ? 'Step 3: Upload after your production build' : 'Usage'}</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyUploadCommand}>- {#if copiedCommand}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={bash} code={uploadCommand} />- </div>- </div>+ <CopyableCodeBlock code={uploadCommand} language={bash} /></div>{/if}</div>diff --git a/frontend/src/lib/components/spans/span-empty-state.svelte b/frontend/src/lib/components/spans/span-empty-state.svelteindex 935f040f..1251c84e 100644--- a/frontend/src/lib/components/spans/span-empty-state.svelte+++ b/frontend/src/lib/components/spans/span-empty-state.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { ExternalLink, Code } from 'lucide-svelte';+ import { Code } from '@lucide/svelte';import type { Framework } from '$lib/state/projects.svelte';import Highlight from 'svelte-highlight';import go from 'svelte-highlight/languages/go';@@ -13,23 +13,6 @@let { framework }: Props = $props();// TODO: Replace with actual documentation URLs when docs are built- function getDocsUrl(fw: Framework): string {- switch (fw) {- case 'gin':- return 'https://docs.traceway.io/go/gin/spans';- case 'fiber':- return 'https://docs.traceway.io/go/fiber/spans';- case 'chi':- return 'https://docs.traceway.io/go/chi/spans';- case 'fasthttp':- return 'https://docs.traceway.io/go/fasthttp/spans';- case 'stdlib':- return 'https://docs.traceway.io/go/stdlib/spans';- default:- return 'https://docs.traceway.io/go/spans';- }- }-function getCodeExample(fw: Framework): string {switch (fw) {case 'gin':@@ -73,7 +56,6 @@ span.End()`;const GO_FRAMEWORKS: Framework[] = ['gin', 'fiber', 'chi', 'fasthttp', 'stdlib', 'custom'];const isGoFramework = $derived(GO_FRAMEWORKS.includes(framework));- const docsUrl = $derived(getDocsUrl(framework));const codeExample = $derived(getCodeExample(framework));</script>diff --git a/frontend/src/lib/components/spans/span-row.svelte b/frontend/src/lib/components/spans/span-row.svelteindex 414ccbbb..f4991fdd 100644--- a/frontend/src/lib/components/spans/span-row.svelte+++ b/frontend/src/lib/components/spans/span-row.svelte@@ -3,10 +3,9 @@import { cn } from '$lib/utils';import { formatDuration, preciseTimeMs } from '$lib/utils/formatters';import * as Popover from '$lib/components/ui/popover';- import Copy from 'lucide-svelte/icons/copy';- import Check from 'lucide-svelte/icons/check';- import ChevronRight from 'lucide-svelte/icons/chevron-right';- import ChevronDown from 'lucide-svelte/icons/chevron-down';+ import CopyButton from '$lib/components/traceway/copy-button.svelte';+ import ChevronRight from '@lucide/svelte/icons/chevron-right';+ import ChevronDown from '@lucide/svelte/icons/chevron-down';type Props = {row: number;@@ -76,7 +75,7 @@let isHovered = $state(false);let barElement: HTMLDivElement;- function handleMouseEnter(e: MouseEvent) {+ function handleMouseEnter() {isHovered = true;}@@ -97,25 +96,11 @@}let nameElement: HTMLSpanElement;- let copied = $state(false);- let copiedKey = $state<string | null>(null);const attributeEntries = $derived(Object.entries(span.attributes ?? {}).sort((a, b) => a[0].localeCompare(b[0])));- async function copySpanName() {- await navigator.clipboard.writeText(span.name);- copied = true;- setTimeout(() => (copied = false), 2000);- }-- async function copyAttribute(key: string, value: string) {- await navigator.clipboard.writeText(value);- copiedKey = key;- setTimeout(() => (copiedKey = null), 2000);- }-$effect(() => {if (nameElement) {// Measure the natural width needed, including indentation and chevron@@ -159,32 +144,17 @@<div class="flex max-h-[60vh] flex-col gap-2 overflow-y-auto"><div class="flex items-start gap-2"><span class="font-mono text-xs break-all select-text">{span.name}</span>- <button onclick={copySpanName} class="shrink-0 p-1 rounded hover:bg-muted">- {#if copied}- <Check class="h-3.5 w-3.5 text-green-500" />- {:else}- <Copy class="h-3.5 w-3.5 text-muted-foreground" />- {/if}- </button>+ <CopyButton bare text={span.name} iconClass="h-3.5 w-3.5" class="shrink-0" /></div>{#if attributeEntries.length > 0}<div class="flex flex-col gap-1.5 border-t border-border pt-2">- {#each attributeEntries as [key, value]}+ {#each attributeEntries as [key, value], __index (__index)}<div class="flex items-start gap-2"><div class="min-w-0 flex-1"><div class="font-mono text-xs break-all text-muted-foreground">{key}</div><div class="font-mono text-xs break-all select-text">{value}</div></div>- <button- onclick={() => copyAttribute(key, value)}- class="shrink-0 p-1 rounded hover:bg-muted"- >- {#if copiedKey === key}- <Check class="h-3.5 w-3.5 text-green-500" />- {:else}- <Copy class="h-3.5 w-3.5 text-muted-foreground" />- {/if}- </button>+ <CopyButton bare text={value} iconClass="h-3.5 w-3.5" class="shrink-0" /></div>{/each}</div>diff --git a/frontend/src/lib/components/spans/span-waterfall.svelte b/frontend/src/lib/components/spans/span-waterfall.svelteindex fd24858e..e02cbd6a 100644--- a/frontend/src/lib/components/spans/span-waterfall.svelte+++ b/frontend/src/lib/components/spans/span-waterfall.svelte@@ -1,5 +1,6 @@<script lang="ts">import type { Span } from '$lib/types/spans';+ import { SvelteSet } from 'svelte/reactivity';import ScrollArea from '../ui/scroll-area/scroll-area.svelte';import SpanRow from './span-row.svelte';import { preciseTimeMs } from '$lib/utils/formatters';@@ -17,7 +18,7 @@let collapsed = $state(new Set<string>());function toggleCollapse(id: string) {- const next = new Set(collapsed);+ const next = new SvelteSet(collapsed);if (next.has(id)) {next.delete(id);} else {diff --git a/frontend/src/lib/components/synthetics/key-value-rows.svelte b/frontend/src/lib/components/synthetics/key-value-rows.svelteindex a3741e91..140a2df4 100644--- a/frontend/src/lib/components/synthetics/key-value-rows.svelte+++ b/frontend/src/lib/components/synthetics/key-value-rows.svelte@@ -29,15 +29,10 @@</script><div class="space-y-2">- {#each rows as _, index}+ {#each rows as row, index (index)}<div class="flex gap-2">- <Input bind:value={rows[index].key} placeholder={keyPlaceholder} class="flex-1" {disabled} />- <Input- bind:value={rows[index].value}- placeholder={valuePlaceholder}- class="flex-1"- {disabled}- />+ <Input bind:value={row.key} placeholder={keyPlaceholder} class="flex-1" {disabled} />+ <Input bind:value={row.value} placeholder={valuePlaceholder} class="flex-1" {disabled} /><Button variant="ghost" size="icon" type="button" onclick={() => removeRow(index)} {disabled}><Trash2 class="h-4 w-4" /></Button>diff --git a/frontend/src/lib/components/trace-logs/log-message.svelte b/frontend/src/lib/components/trace-logs/log-message.svelteindex f311d987..00d50fe5 100644--- a/frontend/src/lib/components/trace-logs/log-message.svelte+++ b/frontend/src/lib/components/trace-logs/log-message.svelte@@ -60,7 +60,7 @@</script>{#each segments as seg, i (i)}{#if seg.type === 'text'}{seg.text}{:else}<Tooltip.Root- ><Tooltip.Trigger class="cursor-default align-baseline text-blue-500 dark:text-blue-400"- >{seg.value}</Tooltip.Trigger- ><Tooltip.Content class="font-mono">{seg.name}</Tooltip.Content></Tooltip.Root- >{/if}{/each}+ ><Tooltip.Trigger class="cursor-default align-baseline text-blue-500 dark:text-blue-400"+ >{seg.value}</Tooltip.Trigger+ ><Tooltip.Content class="font-mono">{seg.name}</Tooltip.Content></Tooltip.Root+ >{/if}{/each}diff --git a/frontend/src/lib/components/trace-logs/trace-logs-panel.svelte b/frontend/src/lib/components/trace-logs/trace-logs-panel.svelteindex ebaeccd2..dd8df991 100644--- a/frontend/src/lib/components/trace-logs/trace-logs-panel.svelte+++ b/frontend/src/lib/components/trace-logs/trace-logs-panel.svelte@@ -1,5 +1,6 @@<script lang="ts">import { onMount } from 'svelte';+ import { SvelteMap } from 'svelte/reactivity';import { api } from '$lib/api';import * as Card from '$lib/components/ui/card';import * as Table from '$lib/components/ui/table';@@ -10,6 +11,8 @@import LogMessage from './log-message.svelte';import { formatDateTime } from '$lib/utils/formatters';import { getTimezone } from '$lib/state/timezone.svelte';+ import { underlineTabTriggerClass, underlineTabListClass } from '$lib/utils/tabs';+ import { cn } from '$lib/utils';import { spanIdUuidToHex } from '$lib/utils/span-id';import type { Span } from '$lib/types/spans';@@ -41,7 +44,6 @@traceId: string;distributedTraceId?: string | null;spans: Span[];- rootSpan: { id: string; name: string };traceRecordedAt: string;} = $props();@@ -49,8 +51,7 @@let activeTab = $state<'this-trace' | 'all-distributed'>('this-trace');- const tabTriggerClass =- 'rounded-none border-b-2 border-transparent bg-transparent px-0 pb-2 pt-0 text-sm font-medium text-muted-foreground shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none';+ const tabTriggerClass = cn(underlineTabTriggerClass, 'mb-0 pb-2');// This-trace datalet logs = $state<LogRecord[]>([]);@@ -65,7 +66,7 @@let distributedError = $state('');const childSpanNameByHex = $derived.by(() => {- const m = new Map<string, string>();+ const m = new SvelteMap<string, string>();for (const s of spans) {const hex = spanIdUuidToHex(s.id);if (hex) m.set(hex, s.name);@@ -158,16 +159,14 @@});</script>-<Card.Root class="gap-0 pb-0 overflow-hidden">+<Card.Root class="gap-0 overflow-hidden pb-0"><Card.Header class={distributedTraceId ? '' : 'pb-4'}><Card.Title>Logs</Card.Title></Card.Header><Card.Content class="p-0"><Tabs.Root value={activeTab} onValueChange={onTabChange}>{#if distributedTraceId}- <Tabs.List- class="h-auto w-full justify-start gap-4 rounded-none border-b bg-transparent p-0 pl-6 pt-0 pb-2"- >+ <Tabs.List class={cn(underlineTabListClass, 'pb-2 pl-6')}><Tabs.Trigger value="this-trace" class={tabTriggerClass}>This Trace</Tabs.Trigger><Tabs.Trigger value="all-distributed" class={tabTriggerClass}>All Distributed Traces@@ -199,10 +198,7 @@<Table.Body>{#each logs as log (log.id)}{@const spanName = resolveSpanName(log)}- <Table.Row- class="h-8 cursor-pointer hover:bg-muted/50"- onclick={() => toggleExpanded(log.id)}- >+ <Table.Row class="h-8 cursor-pointer" onclick={() => toggleExpanded(log.id)}><Table.Cell class="py-1.5 pl-6 text-xs text-muted-foreground tabular-nums">{formatDateTime(log.timestamp, { timezone })}</Table.Cell>@@ -266,10 +262,7 @@</Table.Header><Table.Body>{#each distributedLogs as log (log.id)}- <Table.Row- class="h-8 cursor-pointer hover:bg-muted/50"- onclick={() => toggleExpanded(log.id)}- >+ <Table.Row class="h-8 cursor-pointer" onclick={() => toggleExpanded(log.id)}><Table.Cell class="py-1.5 pl-6 text-xs text-muted-foreground tabular-nums">{formatDateTime(log.timestamp, { timezone })}</Table.Cell>diff --git a/frontend/src/lib/components/traceway/bulk-actions-bar.svelte b/frontend/src/lib/components/traceway/bulk-actions-bar.sveltenew file mode 100644index 00000000..7af483cb--- /dev/null+++ b/frontend/src/lib/components/traceway/bulk-actions-bar.svelte@@ -0,0 +1,21 @@+<script lang="ts">+ import type { Snippet } from 'svelte';+ import { Button } from '$lib/components/ui/button';++ interface Props {+ count: number;+ itemLabel?: string;+ onClear: () => void;+ children: Snippet;+ }++ let { count, itemLabel = 'item', onClear, children }: Props = $props();+</script>++<div+ class="flex animate-in flex-wrap items-center gap-3 rounded-md border bg-muted/50 p-3 duration-200 fade-in slide-in-from-top-1"+>+ <span class="text-sm font-medium">{count} {itemLabel}{count === 1 ? '' : 's'} selected</span>+ {@render children()}+ <Button variant="ghost" size="sm" onclick={onClear}>Clear selection</Button>+</div>diff --git a/frontend/src/lib/components/traceway/chart-card.svelte b/frontend/src/lib/components/traceway/chart-card.sveltenew file mode 100644index 00000000..aa01b67b--- /dev/null+++ b/frontend/src/lib/components/traceway/chart-card.svelte@@ -0,0 +1,58 @@+<script lang="ts">+ import type { Snippet } from 'svelte';+ import * as Card from '$lib/components/ui/card';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { cn } from '$lib/utils.js';++ interface Props {+ title: string;+ icon?: Snippet;+ controls?: Snippet;+ loading?: boolean;+ empty?: boolean;+ emptyMessage?: string;+ height?: number;+ class?: string;+ children: Snippet;+ }++ let {+ title,+ icon,+ controls,+ loading = false,+ empty = false,+ emptyMessage = 'No data in this period',+ height = 220,+ class: className,+ children+ }: Props = $props();+</script>++<Card.Root class={cn('gap-3 pt-2', className)}>+ <Card.Header+ class="flex flex-row items-center justify-between space-y-0 border-b pl-3 [.border-b]:pb-2"+ >+ <Card.Title class="flex items-center gap-2 text-base font-medium">+ {#if icon}{@render icon()}{/if}+ <span class="text-sm font-normal text-muted-foreground">{title}</span>+ </Card.Title>+ {#if controls}{@render controls()}{/if}+ </Card.Header>+ <Card.Content>+ {#if loading}+ <div class="flex items-center justify-center" style:height="{height}px">+ <LoadingCircle size="lg" />+ </div>+ {:else if empty}+ <div+ class="flex items-center justify-center text-sm text-muted-foreground"+ style:height="{height}px"+ >+ {emptyMessage}+ </div>+ {:else}+ {@render children()}+ {/if}+ </Card.Content>+</Card.Root>diff --git a/frontend/src/lib/components/traceway/confirm-delete-dialog.svelte b/frontend/src/lib/components/traceway/confirm-delete-dialog.sveltenew file mode 100644index 00000000..5f395c64--- /dev/null+++ b/frontend/src/lib/components/traceway/confirm-delete-dialog.svelte@@ -0,0 +1,52 @@+<script lang="ts">+ import type { Snippet } from 'svelte';+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Button } from '$lib/components/ui/button';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { Trash2 } from '@lucide/svelte';++ interface Props {+ open?: boolean;+ entity: string;+ verb?: 'Delete' | 'Revoke' | 'Remove';+ title?: string;+ description?: string;+ error?: string | null;+ loading?: boolean;+ onConfirm: () => void;+ children?: Snippet;+ }++ let {+ open = $bindable(false),+ entity,+ verb = 'Delete',+ title,+ description,+ error = null,+ loading = false,+ onConfirm,+ children+ }: Props = $props();+</script>++<AlertDialog.Root bind:open>+ <AlertDialog.Content>+ <AlertDialog.Header>+ <AlertDialog.Title>{title ?? `${verb} ${entity}`}</AlertDialog.Title>+ {#if description}+ <AlertDialog.Description>{description}</AlertDialog.Description>+ {/if}+ </AlertDialog.Header>+ {#if children}{@render children()}{/if}+ <ErrorAlert {error} />+ <AlertDialog.Footer>+ <AlertDialog.Cancel disabled={loading}>Cancel</AlertDialog.Cancel>+ <Button variant="destructive" onclick={onConfirm} disabled={loading}>+ <Trash2 class="mr-2 h-4 w-4" />+ {verb}+ {entity}+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+</AlertDialog.Root>diff --git a/frontend/src/lib/components/traceway/copy-button.svelte b/frontend/src/lib/components/traceway/copy-button.sveltenew file mode 100644index 00000000..7a1d1b56--- /dev/null+++ b/frontend/src/lib/components/traceway/copy-button.svelte@@ -0,0 +1,67 @@+<script lang="ts">+ import { Button } from '$lib/components/ui/button';+ import { Check, Copy } from '@lucide/svelte';+ import { cn } from '$lib/utils.js';++ interface Props {+ text: string | (() => string);+ label?: string;+ copiedLabel?: string;+ size?: 'sm' | 'default';+ bare?: boolean;+ class?: string;+ iconClass?: string;+ title?: string;+ }++ let {+ text,+ label,+ copiedLabel = 'Copied!',+ size = 'sm',+ bare = false,+ class: className,+ iconClass = 'h-4 w-4',+ title = 'Copy to clipboard'+ }: Props = $props();++ let copied = $state(false);+ let timer: ReturnType<typeof setTimeout> | undefined;++ async function copy() {+ const value = typeof text === 'function' ? text() : text;+ await navigator.clipboard.writeText(value);+ copied = true;+ clearTimeout(timer);+ timer = setTimeout(() => (copied = false), 2000);+ }+</script>++{#if bare}+ <button+ type="button"+ class={cn(+ 'cursor-pointer rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground',+ className+ )}+ onclick={copy}+ {title}+ >+ {#if copied}+ <Check class={cn(iconClass, 'text-green-500')} />+ {:else}+ <Copy class={iconClass} />+ {/if}+ <span class="sr-only">{title}</span>+ </button>+{:else}+ <Button variant="outline" {size} class={className} onclick={copy} {title}>+ {#if copied}+ <Check class={cn(iconClass, 'text-green-500', label ? 'mr-2' : '')} />+ {#if label}{copiedLabel}{/if}+ {:else}+ <Copy class={cn(iconClass, label ? 'mr-2' : '')} />+ {#if label}{label}{/if}+ {/if}+ </Button>+{/if}diff --git a/frontend/src/lib/components/traceway/empty-state.svelte b/frontend/src/lib/components/traceway/empty-state.svelteindex d957f82e..e32a648b 100644--- a/frontend/src/lib/components/traceway/empty-state.svelte+++ b/frontend/src/lib/components/traceway/empty-state.svelte@@ -1,23 +1,33 @@<script lang="ts">- import { Button } from '$lib/components/ui/button';+ import type { Snippet } from 'svelte';+ import { Button, type ButtonVariant } from '$lib/components/ui/button';import { Plus } from '@lucide/svelte';interface Props {message: string;actionLabel?: string;+ actionVariant?: ButtonVariant;onAction?: () => void;+ icon?: Snippet;}- let { message, actionLabel, onAction }: Props = $props();+ let { message, actionLabel, actionVariant = 'success', onAction, icon }: Props = $props();</script><divclass="flex flex-col items-center justify-center rounded-md bg-muted py-20 text-center text-muted-foreground">+ {#if icon}+ <div class="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-background">+ {@render icon()}+ </div>+ {/if}<p class={actionLabel && onAction ? 'mb-4' : ''}>{message}</p>{#if actionLabel && onAction}- <Button variant="success" onclick={onAction}>- <Plus class="mr-1 h-4 w-4" />+ <Button variant={actionVariant} onclick={onAction}>+ {#if actionVariant === 'success'}+ <Plus class="mr-2 h-4 w-4" />+ {/if}{actionLabel}</Button>{/if}diff --git a/frontend/src/lib/components/traceway/error-retry-box.svelte b/frontend/src/lib/components/traceway/error-retry-box.sveltenew file mode 100644index 00000000..177707f9--- /dev/null+++ b/frontend/src/lib/components/traceway/error-retry-box.svelte@@ -0,0 +1,18 @@+<script lang="ts">+ import { Button } from '$lib/components/ui/button';++ interface Props {+ message: string;+ onRetry?: () => void;+ retryLabel?: string;+ }++ let { message, onRetry, retryLabel = 'Retry' }: Props = $props();+</script>++<div class="flex flex-col items-center justify-center gap-3 rounded-md bg-muted py-20 text-center">+ <p class="text-sm text-destructive">{message}</p>+ {#if onRetry}+ <Button variant="outline" size="sm" onclick={onRetry}>{retryLabel}</Button>+ {/if}+</div>diff --git a/frontend/src/lib/components/traceway/escalation-chain.svelte b/frontend/src/lib/components/traceway/escalation-chain.svelteindex c40da633..ad430904 100644--- a/frontend/src/lib/components/traceway/escalation-chain.svelte+++ b/frontend/src/lib/components/traceway/escalation-chain.svelte@@ -61,7 +61,8 @@</span>{/each}{#if step.targets.length === 0}- <span class="text-muted-foreground {compact ? 'text-[10px]' : 'text-xs'}">No targets</span>+ <span class="text-muted-foreground {compact ? 'text-[10px]' : 'text-xs'}">No targets</span+ >{/if}</div></div>diff --git a/frontend/src/lib/components/traceway/form-field.svelte b/frontend/src/lib/components/traceway/form-field.sveltenew file mode 100644index 00000000..e0d65294--- /dev/null+++ b/frontend/src/lib/components/traceway/form-field.svelte@@ -0,0 +1,21 @@+<script lang="ts">+ import type { Snippet } from 'svelte';+ import { Label } from '$lib/components/ui/label';++ interface Props {+ label: string;+ for?: string;+ hint?: string;+ children: Snippet;+ }++ let { label, for: htmlFor, hint, children }: Props = $props();+</script>++<div class="space-y-2">+ <Label for={htmlFor}>{label}</Label>+ {@render children()}+ {#if hint}+ <p class="text-xs text-muted-foreground">{hint}</p>+ {/if}+</div>diff --git a/frontend/src/lib/components/traceway/oncall-owner.svelte b/frontend/src/lib/components/traceway/oncall-owner.svelteindex e1bc0b0c..e9ed8120 100644--- a/frontend/src/lib/components/traceway/oncall-owner.svelte+++ b/frontend/src/lib/components/traceway/oncall-owner.svelte@@ -1,5 +1,6 @@<script lang="ts" module>import { api } from '$lib/api';+ import { SvelteMap } from 'svelte/reactivity';import type { ProjectOncall } from '$lib/state/oncall.svelte';interface CacheEntry {@@ -7,7 +8,7 @@fetchedAt: number;}- const cache = new Map<string, CacheEntry>();+ const cache = new SvelteMap<string, CacheEntry>();const CACHE_TTL_MS = 60_000;function fetchOncall(projectId: string): Promise<ProjectOncall | null> {@@ -45,9 +46,7 @@});});- const names = $derived(- (oncall?.oncall ?? []).map((u) => u.name || u.email).join(', ')- );+ const names = $derived((oncall?.oncall ?? []).map((u) => u.name || u.email).join(', '));</script>{#if oncall?.team}diff --git a/frontend/src/lib/components/traceway/org-switcher.svelte b/frontend/src/lib/components/traceway/org-switcher.sveltenew file mode 100644index 00000000..226e8b16--- /dev/null+++ b/frontend/src/lib/components/traceway/org-switcher.svelte@@ -0,0 +1,32 @@+<script lang="ts">+ import * as Select from '$lib/components/ui/select';++ interface Props {+ organizations: { id: number; name: string }[];+ currentOrganizationId: number | null;+ currentOrganizationName?: string;+ onChange: (id: number) => void;+ }++ let { organizations, currentOrganizationId, currentOrganizationName, onChange }: Props = $props();+</script>++<div class="flex w-full items-center gap-2 sm:w-auto">+ <span class="text-sm text-muted-foreground">Organization</span>+ <Select.Root+ type="single"+ value={currentOrganizationId !== null ? String(currentOrganizationId) : undefined}+ onValueChange={(val) => {+ if (val) onChange(Number(val));+ }}+ >+ <Select.Trigger class="min-w-0 flex-1 sm:w-[220px] sm:flex-none">+ {currentOrganizationName || 'Select organization'}+ </Select.Trigger>+ <Select.Content>+ {#each organizations as org (org.id)}+ <Select.Item value={String(org.id)}>{org.name}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+</div>diff --git a/frontend/src/routes/on-call/page-badges.svelte b/frontend/src/lib/components/traceway/page-badges.sveltesimilarity index 100%rename from frontend/src/routes/on-call/page-badges.svelterename to frontend/src/lib/components/traceway/page-badges.sveltediff --git a/frontend/src/lib/components/traceway/page-header.svelte b/frontend/src/lib/components/traceway/page-header.sveltenew file mode 100644index 00000000..f2c3b1b5--- /dev/null+++ b/frontend/src/lib/components/traceway/page-header.svelte@@ -0,0 +1,59 @@+<script lang="ts">+ import type { Snippet } from 'svelte';+ import { Button } from '$lib/components/ui/button';+ import { ArrowLeft } from '@lucide/svelte';++ interface Props {+ title: string;+ subtitle?: string;+ description?: string;+ onBack?: (e: MouseEvent) => void;+ trailing?: Snippet;+ meta?: Snippet;+ actions?: Snippet;+ }++ let { title, subtitle, description, onBack, trailing, meta, actions }: Props = $props();+</script>++<!-- Container query rather than viewport breakpoints so the actions row accounts+ for the sidebar (and works inside sheets): below @2xl the actions become their+ own full-width stacked rows. -->+<div class="@container">+ <div class="flex flex-wrap items-start justify-between gap-x-4 gap-y-3">+ <div class="flex min-w-0 items-start gap-4">+ {#if onBack}+ <Button variant="ghost" size="sm" onclick={onBack} class="mt-1 h-8 w-8 shrink-0 p-0">+ <ArrowLeft class="h-4 w-4" />+ <span class="sr-only">Back</span>+ </Button>+ {/if}+ <div class="min-w-0">+ <div class="flex flex-wrap items-center gap-2">+ <h1+ class="min-w-0 text-3xl font-semibold tracking-tight text-balance [overflow-wrap:anywhere]"+ >+ {title}+ </h1>+ {#if trailing}{@render trailing()}{/if}+ </div>+ {#if subtitle}+ <p class="mt-1 font-mono text-sm break-all text-muted-foreground">{subtitle}</p>+ {/if}+ {#if description}+ <p class="mt-1 max-w-prose text-sm text-muted-foreground">{description}</p>+ {/if}+ </div>+ </div>+ {#if actions}+ <div class="flex w-full flex-col gap-2 @2xl:w-auto @2xl:flex-row @2xl:items-center">+ {@render actions()}+ </div>+ {/if}+ </div>+ {#if meta}+ <div class="mt-3 flex flex-wrap items-center gap-3">+ {@render meta()}+ </div>+ {/if}+</div>diff --git a/frontend/src/lib/components/traceway/tabs-row.svelte b/frontend/src/lib/components/traceway/page-tabs.sveltesimilarity index 73%rename from frontend/src/lib/components/traceway/tabs-row.svelterename to frontend/src/lib/components/traceway/page-tabs.svelteindex 9be1f05a..7e9c4af7 100644--- a/frontend/src/lib/components/traceway/tabs-row.svelte+++ b/frontend/src/lib/components/traceway/page-tabs.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import type { Snippet } from 'svelte';import * as Tabs from '$lib/components/ui/tabs';import * as Select from '$lib/components/ui/select';import { Button } from '$lib/components/ui/button';@@ -15,20 +16,21 @@onTabChange: (tab: string) => void;actionLabel?: string;onAction?: () => void;+ actions?: Snippet;}- let { tabs, activeTab, onTabChange, actionLabel, onAction }: Props = $props();+ let { tabs, activeTab, onTabChange, actionLabel, onAction, actions }: Props = $props();const activeLabel = $derived(tabs.find((t) => t.value === activeTab)?.label ?? tabs[0]?.label ?? '');</script>-<!-- Container query: the tab list collapses into a full-row dropdown (and the action- button wraps to its own full row) based on the content width, not the viewport,- so it accounts for the sidebar. -->+<!-- Container query: the tab list collapses into a full-row dropdown (and the+ actions wrap to their own full-width rows) based on the content width, not+ the viewport, so it accounts for the sidebar. --><div class="@container">- <div class="flex flex-wrap items-center justify-between gap-x-2 gap-y-4">+ <div class="flex flex-wrap items-center justify-between gap-x-2 gap-y-2"><Tabs.Rootvalue={activeTab}onValueChange={(v) => {@@ -56,9 +58,13 @@{/each}</Select.Content></Select.Root>- {#if actionLabel && onAction}+ {#if actions}+ <div class="flex w-full flex-col gap-2 @2xl:w-auto @2xl:flex-row @2xl:items-center">+ {@render actions()}+ </div>+ {:else if actionLabel && onAction}<Button size="sm" variant="success" class="w-full @2xl:w-auto" onclick={onAction}>- <Plus class="mr-1 h-4 w-4" />+ <Plus class="mr-2 h-4 w-4" />{actionLabel}</Button>{/if}diff --git a/frontend/src/lib/components/traceway/stat-row.svelte b/frontend/src/lib/components/traceway/stat-row.sveltenew file mode 100644index 00000000..1de364ec--- /dev/null+++ b/frontend/src/lib/components/traceway/stat-row.svelte@@ -0,0 +1,22 @@+<script lang="ts">+ import type { Snippet } from 'svelte';+ import * as Card from '$lib/components/ui/card';+ import { cn } from '$lib/utils.js';++ interface Props {+ columns?: number;+ class?: string;+ children: Snippet;+ }++ let { columns = 4, class: className, children }: Props = $props();+</script>++<Card.Root class={cn('py-0', className)}>+ <div+ class="grid grid-cols-2 divide-y divide-border sm:grid-cols-[repeat(var(--stat-cols),minmax(0,1fr))] sm:divide-x sm:divide-y-0"+ style="--stat-cols: {columns}"+ >+ {@render children()}+ </div>+</Card.Root>diff --git a/frontend/src/lib/components/traceway/stat-tile.svelte b/frontend/src/lib/components/traceway/stat-tile.sveltenew file mode 100644index 00000000..48321478--- /dev/null+++ b/frontend/src/lib/components/traceway/stat-tile.svelte@@ -0,0 +1,22 @@+<script lang="ts">+ import { cn } from '$lib/utils.js';++ interface Props {+ label: string;+ value: string | number;+ sub?: string;+ valueClass?: string;+ }++ let { label, value, sub, valueClass }: Props = $props();+</script>++<div class="px-6 py-4">+ <div class="text-xs font-medium text-muted-foreground">{label}</div>+ <div class={cn('mt-1 text-2xl font-semibold tracking-tight tabular-nums', valueClass)}>+ {value}+ </div>+ {#if sub}+ <div class="mt-0.5 text-xs text-muted-foreground">{sub}</div>+ {/if}+</div>diff --git a/frontend/src/lib/components/traceway/status-pill.svelte b/frontend/src/lib/components/traceway/status-pill.sveltenew file mode 100644index 00000000..265b1767--- /dev/null+++ b/frontend/src/lib/components/traceway/status-pill.svelte@@ -0,0 +1,45 @@+<script lang="ts">+ import type { Snippet } from 'svelte';+ import { cn } from '$lib/utils.js';++ export type PillTone = 'success' | 'danger' | 'warning' | 'info' | 'neutral' | 'violet';++ interface Props {+ tone: PillTone;+ label?: string;+ dot?: boolean;+ class?: string;+ children?: Snippet;+ }++ let { tone, label, dot = false, class: className, children }: Props = $props();++ const tones: Record<PillTone, string> = {+ success: 'bg-green-500/15 text-green-600 dark:text-green-400',+ danger: 'bg-red-500/15 text-red-600 dark:text-red-400',+ warning: 'bg-amber-500/15 text-amber-700 dark:text-amber-400',+ info: 'bg-blue-500/15 text-blue-600 dark:text-blue-400',+ neutral: 'bg-muted text-muted-foreground',+ violet: 'bg-violet-500/15 text-violet-600 dark:text-violet-400'+ };++ const dots: Record<PillTone, string> = {+ success: 'bg-green-500',+ danger: 'bg-red-500',+ warning: 'bg-amber-500',+ info: 'bg-blue-500',+ neutral: 'bg-muted-foreground/60',+ violet: 'bg-violet-500'+ };+</script>++<span+ class={cn(+ 'inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium whitespace-nowrap',+ tones[tone],+ className+ )}+>+ {#if dot}<span class={cn('h-1.5 w-1.5 rounded-full', dots[tone])}></span>{/if}+ {#if children}{@render children()}{:else}{label}{/if}+</span>diff --git a/frontend/src/lib/components/traceway/table-container.svelte b/frontend/src/lib/components/traceway/table-container.sveltenew file mode 100644index 00000000..03009a10--- /dev/null+++ b/frontend/src/lib/components/traceway/table-container.svelte@@ -0,0 +1,20 @@+<script lang="ts">+ import type { Snippet } from 'svelte';+ import { cn } from '$lib/utils.js';++ interface Props {+ class?: string;+ minWidth?: string;+ children: Snippet;+ }++ let { class: className, minWidth, children }: Props = $props();+</script>++<!-- Wide tables scroll inside this container instead of squishing their columns+ or silently clipping them at the viewport edge. -->+<div class={cn('overflow-x-auto rounded-md border', className)}>+ <div style:min-width={minWidth}>+ {@render children()}+ </div>+</div>diff --git a/frontend/src/lib/components/traceway/tags-input.svelte b/frontend/src/lib/components/traceway/tags-input.sveltenew file mode 100644index 00000000..58b868f0--- /dev/null+++ b/frontend/src/lib/components/traceway/tags-input.svelte@@ -0,0 +1,75 @@+<script lang="ts">+ import { Badge } from '$lib/components/ui/badge';+ import { X } from '@lucide/svelte';++ interface Props {+ tags: string[];+ disabled?: boolean;+ placeholder?: string;+ }++ let {+ tags = $bindable(),+ disabled = false,+ placeholder = 'Add a tag and press Enter'+ }: Props = $props();++ let draft = $state('');++ function addDraft() {+ const tag = draft+ .trim()+ .toLowerCase()+ .replaceAll('"', '')+ .replaceAll('\\', '')+ .replaceAll(',', '');+ draft = '';+ if (!tag || tags.includes(tag)) return;+ tags = [...tags, tag];+ }++ function removeTag(tag: string) {+ tags = tags.filter((t) => t !== tag);+ }++ function onKeydown(event: KeyboardEvent) {+ if (event.key === 'Enter') {+ event.preventDefault();+ addDraft();+ } else if (event.key === 'Backspace' && draft === '' && tags.length > 0) {+ tags = tags.slice(0, -1);+ }+ }+</script>++<div+ class="flex min-h-9 w-full flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent px-2 py-1.5 shadow-xs focus-within:ring-1 focus-within:ring-ring"+>+ {#each tags as tag (tag)}+ <Badge variant="secondary" class="gap-1">+ {tag}+ {#if !disabled}+ <button+ type="button"+ class="cursor-pointer rounded-full opacity-60 hover:opacity-100"+ onclick={() => removeTag(tag)}+ aria-label={`Remove tag ${tag}`}+ >+ <X class="size-3" />+ </button>+ {/if}+ </Badge>+ {/each}+ {#if !disabled}+ <input+ type="text"+ bind:value={draft}+ onkeydown={onKeydown}+ onblur={addDraft}+ {placeholder}+ class="min-w-[140px] flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"+ />+ {:else if tags.length === 0}+ <span class="text-sm text-muted-foreground">No tags</span>+ {/if}+</div>diff --git a/frontend/src/lib/components/traceway/toolbar-select.svelte b/frontend/src/lib/components/traceway/toolbar-select.sveltenew file mode 100644index 00000000..5f44f6d5--- /dev/null+++ b/frontend/src/lib/components/traceway/toolbar-select.svelte@@ -0,0 +1,28 @@+<script lang="ts">+ import * as Select from '$lib/components/ui/select';+ import { cn } from '$lib/utils.js';++ type Option = { value: string; label: string };++ interface Props {+ value?: string;+ options: Option[];+ class?: string;+ onChange?: (value: string) => void;+ }++ let { value = $bindable(''), options, class: className, onChange }: Props = $props();++ const label = $derived(options.find((o) => o.value === value)?.label ?? options[0]?.label ?? '');+</script>++<Select.Root type="single" bind:value onValueChange={(v) => onChange?.(v ?? '')}>+ <Select.Trigger class={cn('h-9 w-[140px]', className)}>+ {label}+ </Select.Trigger>+ <Select.Content>+ {#each options as option (option.value)}+ <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+</Select.Root>diff --git a/frontend/src/lib/components/turnstile-widget.svelte b/frontend/src/lib/components/turnstile-widget.svelteindex 5e872bf0..d3541138 100644--- a/frontend/src/lib/components/turnstile-widget.svelte+++ b/frontend/src/lib/components/turnstile-widget.svelte@@ -1,64 +1,64 @@<script lang="ts">- import { onMount, onDestroy } from 'svelte';- import { themeState } from '$lib/state/theme.svelte';+ import { onMount, onDestroy } from 'svelte';+ import { themeState } from '$lib/state/theme.svelte';- interface Props {- siteKey: string;- onVerify: (token: string) => void;- onError?: () => void;- }+ interface Props {+ siteKey: string;+ onVerify: (token: string) => void;+ onError?: () => void;+ }- let { siteKey, onVerify, onError }: Props = $props();+ let { siteKey, onVerify, onError }: Props = $props();- let container: HTMLDivElement;- let widgetId: string | null = null;+ let container: HTMLDivElement;+ let widgetId: string | null = null;- function loadScript(): Promise<void> {- return new Promise((resolve) => {- if (window.turnstile) {- resolve();- return;- }+ function loadScript(): Promise<void> {+ return new Promise((resolve) => {+ if (window.turnstile) {+ resolve();+ return;+ }- const existingScript = document.querySelector('script[src*="turnstile"]');- if (existingScript) {- window.onTurnstileLoad = resolve;- return;- }+ const existingScript = document.querySelector('script[src*="turnstile"]');+ if (existingScript) {+ window.onTurnstileLoad = resolve;+ return;+ }- window.onTurnstileLoad = resolve;- const script = document.createElement('script');- script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onTurnstileLoad';- script.async = true;- script.defer = true;- document.head.appendChild(script);- });- }+ window.onTurnstileLoad = resolve;+ const script = document.createElement('script');+ script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onTurnstileLoad';+ script.async = true;+ script.defer = true;+ document.head.appendChild(script);+ });+ }- function renderWidget() {- if (!window.turnstile || !container) return;+ function renderWidget() {+ if (!window.turnstile || !container) return;- widgetId = window.turnstile.render(container, {- sitekey: siteKey,- callback: onVerify,- 'error-callback': onError,- 'expired-callback': () => {- onVerify('');- },- theme: themeState.isDark ? 'dark' : 'light'- });- }+ widgetId = window.turnstile.render(container, {+ sitekey: siteKey,+ callback: onVerify,+ 'error-callback': onError,+ 'expired-callback': () => {+ onVerify('');+ },+ theme: themeState.isDark ? 'dark' : 'light'+ });+ }- onMount(async () => {- await loadScript();- renderWidget();- });+ onMount(async () => {+ await loadScript();+ renderWidget();+ });- onDestroy(() => {- if (widgetId && window.turnstile) {- window.turnstile.remove(widgetId);- }- });+ onDestroy(() => {+ if (widgetId && window.turnstile) {+ window.turnstile.remove(widgetId);+ }+ });</script><div bind:this={container} class="flex justify-center"></div>diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-action.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-action.svelteindex 7781925c..99b43253 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-action.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-action.svelte@@ -1,12 +1,12 @@<script lang="ts">- import { AlertDialog as AlertDialogPrimitive } from "bits-ui";- import { buttonVariants, type ButtonVariant } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";+ import { AlertDialog as AlertDialogPrimitive } from 'bits-ui';+ import { buttonVariants, type ButtonVariant } from '$lib/components/ui/button/index.js';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),class: className,- variant = "default",+ variant = 'default',...restProps}: AlertDialogPrimitive.ActionProps & { variant?: ButtonVariant } = $props();</script>diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-cancel.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-cancel.svelteindex 42667796..eba7fe16 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-cancel.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-cancel.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { AlertDialog as AlertDialogPrimitive } from "bits-ui";- import { buttonVariants } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";+ import { AlertDialog as AlertDialogPrimitive } from 'bits-ui';+ import { buttonVariants } from '$lib/components/ui/button/index.js';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,6 +12,6 @@<AlertDialogPrimitive.Cancelbind:ref- class={cn(buttonVariants({ variant: "outline" }), className)}+ class={cn(buttonVariants({ variant: 'outline' }), className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-description.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-description.svelteindex 2ec67dc2..82e3079c 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-description.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-description.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { AlertDialog as AlertDialogPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { AlertDialog as AlertDialogPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,6 +12,6 @@<AlertDialogPrimitive.Descriptionbind:refdata-slot="alert-dialog-description"- class={cn("text-muted-foreground text-sm", className)}+ class={cn('text-sm text-muted-foreground', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-footer.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-footer.svelteindex f78b97ab..94bbfaa9 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-footer.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-footer.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<divbind:this={ref}data-slot="alert-dialog-footer"- class={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}+ class={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-header.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-header.svelteindex c8fa7625..1f9604af 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-header.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-header.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<divbind:this={ref}data-slot="alert-dialog-header"- class={cn("flex flex-col gap-2 text-center sm:text-left", className)}+ class={cn('flex flex-col gap-2 text-center sm:text-left', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-overlay.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-overlay.svelteindex a64ee768..766b86bf 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-overlay.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-overlay.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { AlertDialog as AlertDialogPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { AlertDialog as AlertDialogPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@bind:refdata-slot="alert-dialog-overlay"class={cn(- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",+ 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-portal.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-portal.svelteindex f0a19a8c..dd3ac7d9 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-portal.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-portal.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { AlertDialog as AlertDialogPrimitive } from "bits-ui";+ import { AlertDialog as AlertDialogPrimitive } from 'bits-ui';let { ...restProps }: AlertDialogPrimitive.PortalProps = $props();</script>diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-title.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-title.svelteindex 7ef2b5fb..c2926999 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-title.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-title.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { AlertDialog as AlertDialogPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { AlertDialog as AlertDialogPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,6 +12,6 @@<AlertDialogPrimitive.Titlebind:refdata-slot="alert-dialog-title"- class={cn("text-lg font-semibold", className)}+ class={cn('text-lg font-semibold', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-trigger.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-trigger.svelteindex a798f1c2..995bc812 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-trigger.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-trigger.svelte@@ -1,10 +1,7 @@<script lang="ts">- import { AlertDialog as AlertDialogPrimitive } from "bits-ui";+ import { AlertDialog as AlertDialogPrimitive } from 'bits-ui';- let {- ref = $bindable(null),- ...restProps- }: AlertDialogPrimitive.TriggerProps = $props();+ let { ref = $bindable(null), ...restProps }: AlertDialogPrimitive.TriggerProps = $props();</script><AlertDialogPrimitive.Trigger bind:ref {...restProps} />diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog.svelteindex 7ea78bb4..cde7911a 100644--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog.svelte+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { AlertDialog as AlertDialogPrimitive } from "bits-ui";+ import { AlertDialog as AlertDialogPrimitive } from 'bits-ui';let { open = $bindable(false), ...restProps }: AlertDialogPrimitive.RootProps = $props();</script>diff --git a/frontend/src/lib/components/ui/alert-dialog/index.ts b/frontend/src/lib/components/ui/alert-dialog/index.tsindex 56622511..b6ae71b0 100644--- a/frontend/src/lib/components/ui/alert-dialog/index.ts+++ b/frontend/src/lib/components/ui/alert-dialog/index.ts@@ -1,14 +1,14 @@-import Root from "./alert-dialog.svelte";-import Portal from "./alert-dialog-portal.svelte";-import Trigger from "./alert-dialog-trigger.svelte";-import Overlay from "./alert-dialog-overlay.svelte";-import Content from "./alert-dialog-content.svelte";-import Header from "./alert-dialog-header.svelte";-import Footer from "./alert-dialog-footer.svelte";-import Title from "./alert-dialog-title.svelte";-import Description from "./alert-dialog-description.svelte";-import Action from "./alert-dialog-action.svelte";-import Cancel from "./alert-dialog-cancel.svelte";+import Root from './alert-dialog.svelte';+import Portal from './alert-dialog-portal.svelte';+import Trigger from './alert-dialog-trigger.svelte';+import Overlay from './alert-dialog-overlay.svelte';+import Content from './alert-dialog-content.svelte';+import Header from './alert-dialog-header.svelte';+import Footer from './alert-dialog-footer.svelte';+import Title from './alert-dialog-title.svelte';+import Description from './alert-dialog-description.svelte';+import Action from './alert-dialog-action.svelte';+import Cancel from './alert-dialog-cancel.svelte';export {Root,@@ -33,5 +33,5 @@ export {Title as AlertDialogTitle,Description as AlertDialogDescription,Action as AlertDialogAction,- Cancel as AlertDialogCancel,+ Cancel as AlertDialogCancel};diff --git a/frontend/src/lib/components/ui/alert/alert-description.svelte b/frontend/src/lib/components/ui/alert/alert-description.svelteindex 8b56aed2..ceccee5e 100644--- a/frontend/src/lib/components/ui/alert/alert-description.svelte+++ b/frontend/src/lib/components/ui/alert/alert-description.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="alert-description"class={cn(- "text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",+ 'col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/alert/alert-title.svelte b/frontend/src/lib/components/ui/alert/alert-title.svelteindex 77e45ad5..8a35d09d 100644--- a/frontend/src/lib/components/ui/alert/alert-title.svelte+++ b/frontend/src/lib/components/ui/alert/alert-title.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<divbind:this={ref}data-slot="alert-title"- class={cn("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight", className)}+ class={cn('col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/alert/index.ts b/frontend/src/lib/components/ui/alert/index.tsindex 97e21b4e..5e0f854d 100644--- a/frontend/src/lib/components/ui/alert/index.ts+++ b/frontend/src/lib/components/ui/alert/index.ts@@ -1,7 +1,7 @@-import Root from "./alert.svelte";-import Description from "./alert-description.svelte";-import Title from "./alert-title.svelte";-export { alertVariants, type AlertVariant } from "./alert.svelte";+import Root from './alert.svelte';+import Description from './alert-description.svelte';+import Title from './alert-title.svelte';+export { alertVariants, type AlertVariant } from './alert.svelte';export {Root,@@ -10,5 +10,5 @@ export {//Root as Alert,Description as AlertDescription,- Title as AlertTitle,+ Title as AlertTitle};diff --git a/frontend/src/lib/components/ui/attributes-grid/attributes-grid.svelte b/frontend/src/lib/components/ui/attributes-grid/attributes-grid.svelteindex b62c12d1..4d4c5095 100644--- a/frontend/src/lib/components/ui/attributes-grid/attributes-grid.svelte+++ b/frontend/src/lib/components/ui/attributes-grid/attributes-grid.svelte@@ -40,7 +40,7 @@<div><div class="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-3">- {#each visibleEntries() as [key, value]}+ {#each visibleEntries() as [key, value], __index (__index)}<AttributesViewtitle={key}{value}@@ -52,8 +52,8 @@{#if hiddenCount() > 0}<div class="flex justify-end"><button- onclick={() => expanded = true}- class="mt-2 text-xs text-muted-foreground hover:text-foreground transition-colors"+ onclick={() => (expanded = true)}+ class="mt-2 text-xs text-muted-foreground transition-colors hover:text-foreground">Show {hiddenCount()} more...</button>@@ -61,8 +61,8 @@{:else if expanded && entries().length > collapsedCount}<div class="flex justify-end"><button- onclick={() => expanded = false}- class="mt-2 text-xs text-muted-foreground hover:text-foreground transition-colors"+ onclick={() => (expanded = false)}+ class="mt-2 text-xs text-muted-foreground transition-colors hover:text-foreground">Show less</button>diff --git a/frontend/src/lib/components/ui/attributes-grid/attributes-view.svelte b/frontend/src/lib/components/ui/attributes-grid/attributes-view.svelteindex e6c85d00..433f38b7 100644--- a/frontend/src/lib/components/ui/attributes-grid/attributes-view.svelte+++ b/frontend/src/lib/components/ui/attributes-grid/attributes-view.svelte@@ -4,7 +4,8 @@<script lang="ts">import JSONTree from '@sveltejs/svelte-json-tree';- import { Copy, Check, Filter, FilterX } from 'lucide-svelte';+ import { Filter, FilterX } from '@lucide/svelte';+ import CopyButton from '$lib/components/traceway/copy-button.svelte';let {title,@@ -31,7 +32,6 @@: 'Excluding this value — click to clear');- let copied = $state(false);let showFull = $state(false);let clamped = $state(false);let valueEl = $state<HTMLElement | null>(null);@@ -53,14 +53,6 @@}return null;});-- async function copyToClipboard() {- await navigator.clipboard.writeText(value);- copied = true;- setTimeout(() => {- copied = false;- }, 2000);- }</script><div class="group relative flex flex-col gap-1 rounded-md bg-muted p-3">@@ -84,33 +76,28 @@{/if}</button>{/if}- <button- onclick={copyToClipboard}- class="{hoverRevealClass} transition-opacity text-muted-foreground hover:text-foreground"- title="Copy to clipboard"- >- {#if copied}- <Check class="h-3.5 w-3.5 text-green-500" />- {:else}- <Copy class="h-3.5 w-3.5" />- {/if}- </button>+ <CopyButton+ bare+ text={value}+ iconClass="h-3.5 w-3.5"+ class="{hoverRevealClass} p-0 transition-opacity hover:bg-transparent"+ /></div></div>{#if parsedJson()}- <div class="json-tree-container whitespace-normal overflow-x-auto">+ <div class="json-tree-container overflow-x-auto whitespace-normal"><JSONTree value={parsedJson()} /></div>{:else}<spanbind:this={valueEl}- class="font-mono text-sm whitespace-pre-wrap break-all {showFull ? '' : 'line-clamp-4'}"+ class="font-mono text-sm break-all whitespace-pre-wrap {showFull ? '' : 'line-clamp-4'}">{value}</span>{#if clamped || showFull}<buttononclick={() => (showFull = !showFull)}- class="self-start text-xs text-muted-foreground hover:text-foreground transition-colors"+ class="self-start text-xs text-muted-foreground transition-colors hover:text-foreground">{showFull ? 'Show less' : 'Show more...'}</button>diff --git a/frontend/src/lib/components/ui/avatar/avatar-fallback.svelte b/frontend/src/lib/components/ui/avatar/avatar-fallback.svelteindex 249d4a4a..4a452e9d 100644--- a/frontend/src/lib/components/ui/avatar/avatar-fallback.svelte+++ b/frontend/src/lib/components/ui/avatar/avatar-fallback.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Avatar as AvatarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Avatar as AvatarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,6 +12,6 @@<AvatarPrimitive.Fallbackbind:refdata-slot="avatar-fallback"- class={cn("bg-muted flex size-full items-center justify-center rounded-full", className)}+ class={cn('flex size-full items-center justify-center rounded-full bg-muted', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/avatar/avatar-image.svelte b/frontend/src/lib/components/ui/avatar/avatar-image.svelteindex 2bb9db4d..7ccc3ce3 100644--- a/frontend/src/lib/components/ui/avatar/avatar-image.svelte+++ b/frontend/src/lib/components/ui/avatar/avatar-image.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Avatar as AvatarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Avatar as AvatarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,6 +12,6 @@<AvatarPrimitive.Imagebind:refdata-slot="avatar-image"- class={cn("aspect-square size-full", className)}+ class={cn('aspect-square size-full', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/avatar/avatar.svelte b/frontend/src/lib/components/ui/avatar/avatar.svelteindex e37214d5..3fd4dc2a 100644--- a/frontend/src/lib/components/ui/avatar/avatar.svelte+++ b/frontend/src/lib/components/ui/avatar/avatar.svelte@@ -1,10 +1,10 @@<script lang="ts">- import { Avatar as AvatarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Avatar as AvatarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),- loadingStatus = $bindable("loading"),+ loadingStatus = $bindable('loading'),class: className,...restProps}: AvatarPrimitive.RootProps = $props();@@ -14,6 +14,6 @@bind:refbind:loadingStatusdata-slot="avatar"- class={cn("relative flex size-8 shrink-0 overflow-hidden rounded-full", className)}+ class={cn('relative flex size-8 shrink-0 overflow-hidden rounded-full', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/avatar/index.ts b/frontend/src/lib/components/ui/avatar/index.tsindex d06457be..9585f8ad 100644--- a/frontend/src/lib/components/ui/avatar/index.ts+++ b/frontend/src/lib/components/ui/avatar/index.ts@@ -1,6 +1,6 @@-import Root from "./avatar.svelte";-import Image from "./avatar-image.svelte";-import Fallback from "./avatar-fallback.svelte";+import Root from './avatar.svelte';+import Image from './avatar-image.svelte';+import Fallback from './avatar-fallback.svelte';export {Root,@@ -9,5 +9,5 @@ export {//Root as Avatar,Image as AvatarImage,- Fallback as AvatarFallback,+ Fallback as AvatarFallback};diff --git a/frontend/src/lib/components/ui/badge/badge.svelte b/frontend/src/lib/components/ui/badge/badge.svelteindex e3164ba7..0acc5eb2 100644--- a/frontend/src/lib/components/ui/badge/badge.svelte+++ b/frontend/src/lib/components/ui/badge/badge.svelte@@ -1,36 +1,35 @@<script lang="ts" module>- import { type VariantProps, tv } from "tailwind-variants";+ import { type VariantProps, tv } from 'tailwind-variants';export const badgeVariants = tv({- base: "focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] [&>svg]:pointer-events-none [&>svg]:size-3",+ base: 'focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] [&>svg]:pointer-events-none [&>svg]:size-3',variants: {variant: {- default:- "bg-primary text-primary-foreground [a&]:hover:bg-primary/90 border-transparent",+ default: 'bg-primary text-primary-foreground [a&]:hover:bg-primary/90 border-transparent',secondary:- "bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90 border-transparent",+ 'bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90 border-transparent',destructive:- "bg-destructive [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/70 border-transparent text-white",- outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",- },+ 'bg-destructive [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/70 border-transparent text-white',+ outline: 'text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground'+ }},defaultVariants: {- variant: "default",- },+ variant: 'default'+ }});- export type BadgeVariant = VariantProps<typeof badgeVariants>["variant"];+ export type BadgeVariant = VariantProps<typeof badgeVariants>['variant'];</script><script lang="ts">- import type { HTMLAnchorAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAnchorAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),href,class: className,- variant = "default",+ variant = 'default',children,...restProps}: WithElementRef<HTMLAnchorAttributes> & {@@ -39,7 +38,7 @@</script><svelte:element- this={href ? "a" : "span"}+ this={href ? 'a' : 'span'}bind:this={ref}data-slot="badge"{href}diff --git a/frontend/src/lib/components/ui/badge/index.ts b/frontend/src/lib/components/ui/badge/index.tsindex 64e0aa9b..f05fb87f 100644--- a/frontend/src/lib/components/ui/badge/index.ts+++ b/frontend/src/lib/components/ui/badge/index.ts@@ -1,2 +1,2 @@-export { default as Badge } from "./badge.svelte";-export { badgeVariants, type BadgeVariant } from "./badge.svelte";+export { default as Badge } from './badge.svelte';+export { badgeVariants, type BadgeVariant } from './badge.svelte';diff --git a/frontend/src/lib/components/ui/button/button.svelte b/frontend/src/lib/components/ui/button/button.svelteindex da4a5c50..4e689d49 100644--- a/frontend/src/lib/components/ui/button/button.svelte+++ b/frontend/src/lib/components/ui/button/button.svelte@@ -1,5 +1,6 @@<script lang="ts" module>import { cn, type WithElementRef } from '$lib/utils.js';+ import { resolveHref } from '$lib/utils/links';import type { HTMLAnchorAttributes, HTMLButtonAttributes } from 'svelte/elements';import { type VariantProps, tv } from 'tailwind-variants';@@ -64,10 +65,9 @@bind:this={ref}data-slot="button"class={cn(buttonVariants({ variant, size }), className)}- href={disabled ? undefined : href}- aria-disabled={disabled}- role={disabled ? 'link' : undefined}- tabindex={disabled ? -1 : undefined}+ {...disabled+ ? { 'aria-disabled': true, role: 'link', tabindex: -1 }+ : { href: resolveHref(href) }}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/button/index.ts b/frontend/src/lib/components/ui/button/index.tsindex fb585d76..5414d9d3 100644--- a/frontend/src/lib/components/ui/button/index.ts+++ b/frontend/src/lib/components/ui/button/index.ts@@ -2,8 +2,8 @@ import Root, {type ButtonProps,type ButtonSize,type ButtonVariant,- buttonVariants,-} from "./button.svelte";+ buttonVariants+} from './button.svelte';export {Root,@@ -13,5 +13,5 @@ export {buttonVariants,type ButtonProps,type ButtonSize,- type ButtonVariant,+ type ButtonVariant};diff --git a/frontend/src/lib/components/ui/calendar/calendar-caption.svelte b/frontend/src/lib/components/ui/calendar/calendar-caption.svelteindex 5c930370..670ee832 100644--- a/frontend/src/lib/components/ui/calendar/calendar-caption.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-caption.svelte@@ -1,9 +1,9 @@<script lang="ts">- import type { ComponentProps } from "svelte";- import type Calendar from "./calendar.svelte";- import CalendarMonthSelect from "./calendar-month-select.svelte";- import CalendarYearSelect from "./calendar-year-select.svelte";- import { DateFormatter, getLocalTimeZone, type DateValue } from "@internationalized/date";+ import type { ComponentProps } from 'svelte';+ import type Calendar from './calendar.svelte';+ import CalendarMonthSelect from './calendar-month-select.svelte';+ import CalendarYearSelect from './calendar-year-select.svelte';+ import { DateFormatter, getLocalTimeZone, type DateValue } from '@internationalized/date';let {captionLayout,@@ -14,13 +14,13 @@month,locale,placeholder = $bindable(),- monthIndex = 0,+ monthIndex = 0}: {- captionLayout: ComponentProps<typeof Calendar>["captionLayout"];- months: ComponentProps<typeof CalendarMonthSelect>["months"];- monthFormat: ComponentProps<typeof CalendarMonthSelect>["monthFormat"];- years: ComponentProps<typeof CalendarYearSelect>["years"];- yearFormat: ComponentProps<typeof CalendarYearSelect>["yearFormat"];+ captionLayout: ComponentProps<typeof Calendar>['captionLayout'];+ months: ComponentProps<typeof CalendarMonthSelect>['months'];+ monthFormat: ComponentProps<typeof CalendarMonthSelect>['monthFormat'];+ years: ComponentProps<typeof CalendarYearSelect>['years'];+ yearFormat: ComponentProps<typeof CalendarYearSelect>['yearFormat'];month: DateValue;placeholder: DateValue | undefined;locale: string;@@ -29,13 +29,13 @@function formatYear(date: DateValue) {const dateObj = date.toDate(getLocalTimeZone());- if (typeof yearFormat === "function") return yearFormat(dateObj.getFullYear());+ if (typeof yearFormat === 'function') return yearFormat(dateObj.getFullYear());return new DateFormatter(locale, { year: yearFormat }).format(dateObj);}function formatMonth(date: DateValue) {const dateObj = date.toDate(getLocalTimeZone());- if (typeof monthFormat === "function") return monthFormat(dateObj.getMonth() + 1);+ if (typeof monthFormat === 'function') return monthFormat(dateObj.getMonth() + 1);return new DateFormatter(locale, { month: monthFormat }).format(dateObj);}</script>@@ -58,15 +58,15 @@<CalendarYearSelect {years} {yearFormat} value={month.year} />{/snippet}-{#if captionLayout === "dropdown"}+{#if captionLayout === 'dropdown'}{@render MonthSelect()}{@render YearSelect()}-{:else if captionLayout === "dropdown-months"}+{:else if captionLayout === 'dropdown-months'}{@render MonthSelect()}{#if placeholder}{formatYear(placeholder)}{/if}-{:else if captionLayout === "dropdown-years"}+{:else if captionLayout === 'dropdown-years'}{#if placeholder}{formatMonth(placeholder)}{/if}diff --git a/frontend/src/lib/components/ui/calendar/calendar-cell.svelte b/frontend/src/lib/components/ui/calendar/calendar-cell.svelteindex 4cdb5481..12baef62 100644--- a/frontend/src/lib/components/ui/calendar/calendar-cell.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-cell.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,7 +12,7 @@<CalendarPrimitive.Cellbind:refclass={cn(- "relative size-(--cell-size) p-0 text-center text-sm focus-within:z-20 [&:first-child[data-selected]_[data-bits-day]]:rounded-s-md [&:last-child[data-selected]_[data-bits-day]]:rounded-e-md",+ 'relative size-(--cell-size) p-0 text-center text-sm focus-within:z-20 [&:first-child[data-selected]_[data-bits-day]]:rounded-s-md [&:last-child[data-selected]_[data-bits-day]]:rounded-e-md',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/calendar/calendar-day.svelte b/frontend/src/lib/components/ui/calendar/calendar-day.svelteindex 19d7bde7..c8c692c6 100644--- a/frontend/src/lib/components/ui/calendar/calendar-day.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-day.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { buttonVariants } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";- import { Calendar as CalendarPrimitive } from "bits-ui";+ import { buttonVariants } from '$lib/components/ui/button/index.js';+ import { cn } from '$lib/utils.js';+ import { Calendar as CalendarPrimitive } from 'bits-ui';let {ref = $bindable(null),@@ -13,22 +13,22 @@<CalendarPrimitive.Daybind:refclass={cn(- buttonVariants({ variant: "ghost" }),- "flex size-(--cell-size) flex-col items-center justify-center gap-1 p-0 leading-none font-normal whitespace-nowrap select-none",- "[&[data-today]:not([data-selected])]:bg-accent [&[data-today]:not([data-selected])]:text-accent-foreground [&[data-today][data-disabled]]:text-muted-foreground",- "data-[selected]:bg-primary dark:data-[selected]:hover:bg-accent/50 data-[selected]:text-primary-foreground",+ buttonVariants({ variant: 'ghost' }),+ 'flex size-(--cell-size) flex-col items-center justify-center gap-1 p-0 leading-none font-normal whitespace-nowrap select-none',+ '[&[data-today]:not([data-selected])]:bg-accent [&[data-today]:not([data-selected])]:text-accent-foreground [&[data-today][data-disabled]]:text-muted-foreground',+ 'data-[selected]:bg-primary data-[selected]:text-primary-foreground dark:data-[selected]:hover:bg-accent/50',// Outside months- "[&[data-outside-month]:not([data-selected])]:text-muted-foreground [&[data-outside-month]:not([data-selected])]:hover:text-accent-foreground",+ '[&[data-outside-month]:not([data-selected])]:text-muted-foreground [&[data-outside-month]:not([data-selected])]:hover:text-accent-foreground',// Disabled- "data-[disabled]:text-muted-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ 'data-[disabled]:pointer-events-none data-[disabled]:text-muted-foreground data-[disabled]:opacity-50',// Unavailable- "data-[unavailable]:text-muted-foreground data-[unavailable]:line-through",+ 'data-[unavailable]:text-muted-foreground data-[unavailable]:line-through',// hover- "dark:hover:text-accent-foreground",+ 'dark:hover:text-accent-foreground',// focus- "focus:border-ring focus:ring-ring/50 focus:relative",+ 'focus:relative focus:border-ring focus:ring-ring/50',// inner spans- "[&>span]:text-xs [&>span]:opacity-70",+ '[&>span]:text-xs [&>span]:opacity-70',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid-body.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid-body.svelteindex 8cd86dec..fb1d89b1 100644--- a/frontend/src/lib/components/ui/calendar/calendar-grid-body.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-grid-body.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid-head.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid-head.svelteindex 333edc47..b5b68457 100644--- a/frontend/src/lib/components/ui/calendar/calendar-grid-head.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-grid-head.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid-row.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid-row.svelteindex 90322369..2e7d9d86 100644--- a/frontend/src/lib/components/ui/calendar/calendar-grid-row.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-grid-row.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -9,4 +9,4 @@}: CalendarPrimitive.GridRowProps = $props();</script>-<CalendarPrimitive.GridRow bind:ref class={cn("flex", className)} {...restProps} />+<CalendarPrimitive.GridRow bind:ref class={cn('flex', className)} {...restProps} />diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid.svelteindex e0c8627f..bfa49dcf 100644--- a/frontend/src/lib/components/ui/calendar/calendar-grid.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-grid.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -11,6 +11,6 @@<CalendarPrimitive.Gridbind:ref- class={cn("mt-4 flex w-full border-collapse flex-col gap-1", className)}+ class={cn('mt-4 flex w-full border-collapse flex-col gap-1', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-head-cell.svelte b/frontend/src/lib/components/ui/calendar/calendar-head-cell.svelteindex 131807e2..7a1dea0e 100644--- a/frontend/src/lib/components/ui/calendar/calendar-head-cell.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-head-cell.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,7 +12,7 @@<CalendarPrimitive.HeadCellbind:refclass={cn(- "text-muted-foreground w-(--cell-size) rounded-md text-[0.8rem] font-normal",+ 'w-(--cell-size) rounded-md text-[0.8rem] font-normal text-muted-foreground',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/calendar/calendar-header.svelte b/frontend/src/lib/components/ui/calendar/calendar-header.svelteindex c39e955d..8ca9618e 100644--- a/frontend/src/lib/components/ui/calendar/calendar-header.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-header.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,7 +12,7 @@<CalendarPrimitive.Headerbind:refclass={cn(- "flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",+ 'flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/calendar/calendar-heading.svelte b/frontend/src/lib/components/ui/calendar/calendar-heading.svelteindex a9b9810c..7a85b55c 100644--- a/frontend/src/lib/components/ui/calendar/calendar-heading.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-heading.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -11,6 +11,6 @@<CalendarPrimitive.Headingbind:ref- class={cn("px-(--cell-size) text-sm font-medium", className)}+ class={cn('px-(--cell-size) text-sm font-medium', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-month-select.svelte b/frontend/src/lib/components/ui/calendar/calendar-month-select.svelteindex 8d88deb5..c504e1c2 100644--- a/frontend/src/lib/components/ui/calendar/calendar-month-select.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-month-select.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";- import ChevronDownIcon from "@lucide/svelte/icons/chevron-down";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';+ import ChevronDownIcon from '@lucide/svelte/icons/chevron-down';let {ref = $bindable(null),@@ -14,7 +14,7 @@<spanclass={cn(- "has-focus:border-ring border-input has-focus:ring-ring/50 relative flex rounded-md border shadow-xs has-focus:ring-[3px]",+ 'relative flex rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50',className)}>@@ -33,7 +33,7 @@{/each}</select><span- class="[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5"+ class="flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5 [&>svg]:text-muted-foreground"aria-hidden="true">{monthItems.find((item) => item.value === value)?.label || selectedMonthItem.label}diff --git a/frontend/src/lib/components/ui/calendar/calendar-month.svelte b/frontend/src/lib/components/ui/calendar/calendar-month.svelteindex e747fae7..799d2c5b 100644--- a/frontend/src/lib/components/ui/calendar/calendar-month.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-month.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { type WithElementRef, cn } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { type WithElementRef, cn } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -10,6 +10,6 @@}: WithElementRef<HTMLAttributes<HTMLElement>> = $props();</script>-<div {...restProps} bind:this={ref} class={cn("flex flex-col", className)}>+<div {...restProps} bind:this={ref} class={cn('flex flex-col', className)}>{@render children?.()}</div>diff --git a/frontend/src/lib/components/ui/calendar/calendar-months.svelte b/frontend/src/lib/components/ui/calendar/calendar-months.svelteindex f717a9d9..023cad39 100644--- a/frontend/src/lib/components/ui/calendar/calendar-months.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-months.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,7 +12,7 @@<divbind:this={ref}- class={cn("relative flex flex-col gap-4 md:flex-row", className)}+ class={cn('relative flex flex-col gap-4 md:flex-row', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/calendar/calendar-nav.svelte b/frontend/src/lib/components/ui/calendar/calendar-nav.svelteindex 27f33d79..2fea3e94 100644--- a/frontend/src/lib/components/ui/calendar/calendar-nav.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-nav.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<nav{...restProps}bind:this={ref}- class={cn("absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1", className)}+ class={cn('absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1', className)}>{@render children?.()}</nav>diff --git a/frontend/src/lib/components/ui/calendar/calendar-next-button.svelte b/frontend/src/lib/components/ui/calendar/calendar-next-button.svelteindex 5c5a78df..ab5ca599 100644--- a/frontend/src/lib/components/ui/calendar/calendar-next-button.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-next-button.svelte@@ -1,14 +1,14 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import ChevronRightIcon from "@lucide/svelte/icons/chevron-right";- import { buttonVariants, type ButtonVariant } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import ChevronRightIcon from '@lucide/svelte/icons/chevron-right';+ import { buttonVariants, type ButtonVariant } from '$lib/components/ui/button/index.js';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),class: className,children,- variant = "ghost",+ variant = 'ghost',...restProps}: CalendarPrimitive.NextButtonProps & {variant?: ButtonVariant;@@ -23,7 +23,7 @@bind:refclass={cn(buttonVariants({ variant }),- "size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180",+ 'size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180',className)}children={children || Fallback}diff --git a/frontend/src/lib/components/ui/calendar/calendar-prev-button.svelte b/frontend/src/lib/components/ui/calendar/calendar-prev-button.svelteindex 33cfd636..c39b48a7 100644--- a/frontend/src/lib/components/ui/calendar/calendar-prev-button.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-prev-button.svelte@@ -1,14 +1,14 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import ChevronLeftIcon from "@lucide/svelte/icons/chevron-left";- import { buttonVariants, type ButtonVariant } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import ChevronLeftIcon from '@lucide/svelte/icons/chevron-left';+ import { buttonVariants, type ButtonVariant } from '$lib/components/ui/button/index.js';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),class: className,children,- variant = "ghost",+ variant = 'ghost',...restProps}: CalendarPrimitive.PrevButtonProps & {variant?: ButtonVariant;@@ -23,7 +23,7 @@bind:refclass={cn(buttonVariants({ variant }),- "size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180",+ 'size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180',className)}children={children || Fallback}diff --git a/frontend/src/lib/components/ui/calendar/calendar-year-select.svelte b/frontend/src/lib/components/ui/calendar/calendar-year-select.svelteindex 226efdf4..f1a8101f 100644--- a/frontend/src/lib/components/ui/calendar/calendar-year-select.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar-year-select.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";- import ChevronDownIcon from "@lucide/svelte/icons/chevron-down";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';+ import ChevronDownIcon from '@lucide/svelte/icons/chevron-down';let {ref = $bindable(null),@@ -13,7 +13,7 @@<spanclass={cn(- "has-focus:border-ring border-input has-focus:ring-ring/50 relative flex rounded-md border shadow-xs has-focus:ring-[3px]",+ 'relative flex rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50',className)}>@@ -32,7 +32,7 @@{/each}</select><span- class="[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5"+ class="flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5 [&>svg]:text-muted-foreground"aria-hidden="true">{yearItems.find((item) => item.value === value)?.label || selectedYearItem.label}diff --git a/frontend/src/lib/components/ui/calendar/calendar.svelte b/frontend/src/lib/components/ui/calendar/calendar.svelteindex 29b6fff9..40ea1454 100644--- a/frontend/src/lib/components/ui/calendar/calendar.svelte+++ b/frontend/src/lib/components/ui/calendar/calendar.svelte@@ -1,41 +1,41 @@<script lang="ts">- import { Calendar as CalendarPrimitive } from "bits-ui";- import * as Calendar from "./index.js";- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";- import type { ButtonVariant } from "../button/button.svelte";- import { isEqualMonth, type DateValue } from "@internationalized/date";- import type { Snippet } from "svelte";+ import { Calendar as CalendarPrimitive } from 'bits-ui';+ import * as Calendar from './index.js';+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';+ import type { ButtonVariant } from '../button/button.svelte';+ import { isEqualMonth, type DateValue } from '@internationalized/date';+ import type { Snippet } from 'svelte';let {ref = $bindable(null),value = $bindable(),placeholder = $bindable(),class: className,- weekdayFormat = "short",- buttonVariant = "ghost",- captionLayout = "label",- locale = "en-US",+ weekdayFormat = 'short',+ buttonVariant = 'ghost',+ captionLayout = 'label',+ locale = 'en-US',months: monthsProp,years,monthFormat: monthFormatProp,- yearFormat = "numeric",+ yearFormat = 'numeric',day,disableDaysOutsideMonth = false,...restProps}: WithoutChildrenOrChild<CalendarPrimitive.RootProps> & {buttonVariant?: ButtonVariant;- captionLayout?: "dropdown" | "dropdown-months" | "dropdown-years" | "label";- months?: CalendarPrimitive.MonthSelectProps["months"];- years?: CalendarPrimitive.YearSelectProps["years"];- monthFormat?: CalendarPrimitive.MonthSelectProps["monthFormat"];- yearFormat?: CalendarPrimitive.YearSelectProps["yearFormat"];+ captionLayout?: 'dropdown' | 'dropdown-months' | 'dropdown-years' | 'label';+ months?: CalendarPrimitive.MonthSelectProps['months'];+ years?: CalendarPrimitive.YearSelectProps['years'];+ monthFormat?: CalendarPrimitive.MonthSelectProps['monthFormat'];+ yearFormat?: CalendarPrimitive.YearSelectProps['yearFormat'];day?: Snippet<[{ day: DateValue; outsideMonth: boolean }]>;} = $props();const monthFormat = $derived.by(() => {if (monthFormatProp) return monthFormatProp;- if (captionLayout.startsWith("dropdown")) return "short";- return "long";+ if (captionLayout.startsWith('dropdown')) return 'short';+ return 'long';});</script>@@ -50,7 +50,7 @@ get along, so we shut typescript up by casting `value` to `never`.{weekdayFormat}{disableDaysOutsideMonth}class={cn(- "bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",+ 'group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent',className)}{locale}@@ -97,7 +97,7 @@ get along, so we shut typescript up by casting `value` to `never`.{#if day}{@render day({day: date,- outsideMonth: !isEqualMonth(date, month.value),+ outsideMonth: !isEqualMonth(date, month.value)})}{:else}<Calendar.Day />diff --git a/frontend/src/lib/components/ui/calendar/index.ts b/frontend/src/lib/components/ui/calendar/index.tsindex f3a16d2d..180d173b 100644--- a/frontend/src/lib/components/ui/calendar/index.ts+++ b/frontend/src/lib/components/ui/calendar/index.ts@@ -1,21 +1,21 @@-import Root from "./calendar.svelte";-import Cell from "./calendar-cell.svelte";-import Day from "./calendar-day.svelte";-import Grid from "./calendar-grid.svelte";-import Header from "./calendar-header.svelte";-import Months from "./calendar-months.svelte";-import GridRow from "./calendar-grid-row.svelte";-import Heading from "./calendar-heading.svelte";-import GridBody from "./calendar-grid-body.svelte";-import GridHead from "./calendar-grid-head.svelte";-import HeadCell from "./calendar-head-cell.svelte";-import NextButton from "./calendar-next-button.svelte";-import PrevButton from "./calendar-prev-button.svelte";-import MonthSelect from "./calendar-month-select.svelte";-import YearSelect from "./calendar-year-select.svelte";-import Month from "./calendar-month.svelte";-import Nav from "./calendar-nav.svelte";-import Caption from "./calendar-caption.svelte";+import Root from './calendar.svelte';+import Cell from './calendar-cell.svelte';+import Day from './calendar-day.svelte';+import Grid from './calendar-grid.svelte';+import Header from './calendar-header.svelte';+import Months from './calendar-months.svelte';+import GridRow from './calendar-grid-row.svelte';+import Heading from './calendar-heading.svelte';+import GridBody from './calendar-grid-body.svelte';+import GridHead from './calendar-grid-head.svelte';+import HeadCell from './calendar-head-cell.svelte';+import NextButton from './calendar-next-button.svelte';+import PrevButton from './calendar-prev-button.svelte';+import MonthSelect from './calendar-month-select.svelte';+import YearSelect from './calendar-year-select.svelte';+import Month from './calendar-month.svelte';+import Nav from './calendar-nav.svelte';+import Caption from './calendar-caption.svelte';export {Day,@@ -36,5 +36,5 @@ export {MonthSelect,Caption,//- Root as Calendar,+ Root as Calendar};diff --git a/frontend/src/lib/components/ui/card/card-action.svelte b/frontend/src/lib/components/ui/card/card-action.svelteindex cc36c566..bbaafd22 100644--- a/frontend/src/lib/components/ui/card/card-action.svelte+++ b/frontend/src/lib/components/ui/card/card-action.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<divbind:this={ref}data-slot="card-action"- class={cn("col-start-2 row-span-2 row-start-1 self-start justify-self-end", className)}+ class={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/card/card-content.svelte b/frontend/src/lib/components/ui/card/card-content.svelteindex f15704e2..dc25f427 100644--- a/frontend/src/lib/components/ui/card/card-content.svelte+++ b/frontend/src/lib/components/ui/card/card-content.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -10,6 +10,6 @@}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();</script>-<div bind:this={ref} data-slot="card-content" class={cn("px-4", className)} {...restProps}>+<div bind:this={ref} data-slot="card-content" class={cn('px-4', className)} {...restProps}>{@render children?.()}</div>diff --git a/frontend/src/lib/components/ui/card/card-description.svelte b/frontend/src/lib/components/ui/card/card-description.svelteindex 9b20ac70..b46a1ade 100644--- a/frontend/src/lib/components/ui/card/card-description.svelte+++ b/frontend/src/lib/components/ui/card/card-description.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<pbind:this={ref}data-slot="card-description"- class={cn("text-muted-foreground text-sm", className)}+ class={cn('text-sm text-muted-foreground', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/card/card-footer.svelte b/frontend/src/lib/components/ui/card/card-footer.svelteindex a74bd61b..aa00bc09 100644--- a/frontend/src/lib/components/ui/card/card-footer.svelte+++ b/frontend/src/lib/components/ui/card/card-footer.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<divbind:this={ref}data-slot="card-footer"- class={cn("flex items-center px-4 [.border-t]:pt-6", className)}+ class={cn('flex items-center px-4 [.border-t]:pt-6', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/card/card-header.svelte b/frontend/src/lib/components/ui/card/card-header.svelteindex 3cf30e4a..391d25cf 100644--- a/frontend/src/lib/components/ui/card/card-header.svelte+++ b/frontend/src/lib/components/ui/card/card-header.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="card-header"class={cn(- "@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-4 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",+ '@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-4 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/card/card-title.svelte b/frontend/src/lib/components/ui/card/card-title.svelteindex 74472311..0eae8ec1 100644--- a/frontend/src/lib/components/ui/card/card-title.svelte+++ b/frontend/src/lib/components/ui/card/card-title.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<divbind:this={ref}data-slot="card-title"- class={cn("leading-none font-semibold", className)}+ class={cn('leading-none font-semibold', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/card/card.svelte b/frontend/src/lib/components/ui/card/card.svelteindex 3aa92ed1..8443e3b8 100644--- a/frontend/src/lib/components/ui/card/card.svelte+++ b/frontend/src/lib/components/ui/card/card.svelte@@ -13,10 +13,7 @@<divbind:this={ref}data-slot="card"- class={cn(- 'flex flex-col gap-4 rounded-md border bg-card py-4 text-card-foreground',- className- )}+ class={cn('flex flex-col gap-4 rounded-md border bg-card py-4 text-card-foreground', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/card/index.ts b/frontend/src/lib/components/ui/card/index.tsindex 4d3fce48..77d36747 100644--- a/frontend/src/lib/components/ui/card/index.ts+++ b/frontend/src/lib/components/ui/card/index.ts@@ -1,10 +1,10 @@-import Root from "./card.svelte";-import Content from "./card-content.svelte";-import Description from "./card-description.svelte";-import Footer from "./card-footer.svelte";-import Header from "./card-header.svelte";-import Title from "./card-title.svelte";-import Action from "./card-action.svelte";+import Root from './card.svelte';+import Content from './card-content.svelte';+import Description from './card-description.svelte';+import Footer from './card-footer.svelte';+import Header from './card-header.svelte';+import Title from './card-title.svelte';+import Action from './card-action.svelte';export {Root,@@ -21,5 +21,5 @@ export {Footer as CardFooter,Header as CardHeader,Title as CardTitle,- Action as CardAction,+ Action as CardAction};diff --git a/frontend/src/lib/components/ui/checkbox/checkbox.svelte b/frontend/src/lib/components/ui/checkbox/checkbox.svelteindex 3ebeaafe..635ec35a 100644--- a/frontend/src/lib/components/ui/checkbox/checkbox.svelte+++ b/frontend/src/lib/components/ui/checkbox/checkbox.svelte@@ -1,10 +1,10 @@<script lang="ts">- import { Checkbox as CheckboxPrimitive } from "bits-ui";- import CheckIcon from "@lucide/svelte/icons/check";- import MinusIcon from "@lucide/svelte/icons/minus";- import { cn } from "$lib/utils.js";+ import { Checkbox as CheckboxPrimitive } from 'bits-ui';+ import CheckIcon from '@lucide/svelte/icons/check';+ import MinusIcon from '@lucide/svelte/icons/minus';+ import { cn } from '$lib/utils.js';- type CheckedState = boolean | "indeterminate";+ type CheckedState = boolean | 'indeterminate';let {ref = $bindable(null),@@ -19,12 +19,12 @@onCheckedChange?: (checked: CheckedState) => void;class?: string;disabled?: boolean;- "aria-label"?: string;+ 'aria-label'?: string;} = $props();// Split checked state into checked and indeterminate for bits-uiconst isChecked = $derived(checked === true);- const isIndeterminate = $derived(checked === "indeterminate");+ const isIndeterminate = $derived(checked === 'indeterminate');function handleCheckedChange(value: boolean) {const newState: CheckedState = value;@@ -34,8 +34,8 @@function handleIndeterminateChange(value: boolean) {if (value) {- checked = "indeterminate";- onCheckedChange?.("indeterminate");+ checked = 'indeterminate';+ onCheckedChange?.('indeterminate');}}</script>@@ -48,11 +48,11 @@onIndeterminateChange={handleIndeterminateChange}{disabled}class={cn(- "peer size-4 shrink-0 rounded-[4px] border border-input dark:border-white bg-background transition-colors",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",- "disabled:cursor-not-allowed disabled:opacity-50",- "data-[state=checked]:bg-primary data-[state=checked]:border-primary data-[state=checked]:text-primary-foreground",- "data-[state=indeterminate]:bg-primary data-[state=indeterminate]:border-primary data-[state=indeterminate]:text-primary-foreground",+ 'peer size-4 shrink-0 rounded-[4px] border border-input bg-background transition-colors dark:border-white',+ 'focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ 'data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',+ 'data-[state=indeterminate]:border-primary data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/checkbox/index.ts b/frontend/src/lib/components/ui/checkbox/index.tsindex 396cf9cb..364848fa 100644--- a/frontend/src/lib/components/ui/checkbox/index.ts+++ b/frontend/src/lib/components/ui/checkbox/index.ts@@ -1 +1 @@-export { default as Checkbox } from "./checkbox.svelte";+export { default as Checkbox } from './checkbox.svelte';diff --git a/frontend/src/lib/components/ui/command/command-group.svelte b/frontend/src/lib/components/ui/command/command-group.svelteindex b425bb51..dfc36690 100644--- a/frontend/src/lib/components/ui/command/command-group.svelte+++ b/frontend/src/lib/components/ui/command/command-group.svelte@@ -25,9 +25,7 @@{...restProps}>{#if heading}- <CommandPrimitive.GroupHeading- class="px-2 py-1.5 text-xs font-medium text-muted-foreground"- >+ <CommandPrimitive.GroupHeading class="px-2 py-1.5 text-xs font-medium text-muted-foreground">{heading}</CommandPrimitive.GroupHeading>{/if}diff --git a/frontend/src/lib/components/ui/command/command-input.svelte b/frontend/src/lib/components/ui/command/command-input.svelteindex 601b979e..1d651b0e 100644--- a/frontend/src/lib/components/ui/command/command-input.svelte+++ b/frontend/src/lib/components/ui/command/command-input.svelte@@ -1,6 +1,6 @@<script lang="ts">import { Command as CommandPrimitive } from 'bits-ui';- import { Search } from 'lucide-svelte';+ import { Search } from '@lucide/svelte';import { cn } from '$lib/utils.js';let {diff --git a/frontend/src/lib/components/ui/command/command-item.svelte b/frontend/src/lib/components/ui/command/command-item.svelteindex 3e4e74ef..886d0f63 100644--- a/frontend/src/lib/components/ui/command/command-item.svelte+++ b/frontend/src/lib/components/ui/command/command-item.svelte@@ -14,7 +14,7 @@data-slot="command-item"data-command-item=""class={cn(- "relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",+ 'relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/command/command-shortcut.svelte b/frontend/src/lib/components/ui/command/command-shortcut.sveltedeleted file mode 100644index e8eaab5a..00000000--- a/frontend/src/lib/components/ui/command/command-shortcut.svelte+++ /dev/null@@ -1,20 +0,0 @@-<script lang="ts">- import type { HTMLAttributes } from 'svelte/elements';- import { cn } from '$lib/utils.js';-- let {- ref = $bindable(null),- class: className,- children,- ...restProps- }: HTMLAttributes<HTMLSpanElement> & { ref?: HTMLSpanElement | null } = $props();-</script>--<span- bind:this={ref}- data-slot="command-shortcut"- class={cn('ml-auto text-xs tracking-widest text-muted-foreground', className)}- {...restProps}->- {@render children?.()}-</span>diff --git a/frontend/src/lib/components/ui/command/index.ts b/frontend/src/lib/components/ui/command/index.tsindex 23b37a55..01fc0cd9 100644--- a/frontend/src/lib/components/ui/command/index.ts+++ b/frontend/src/lib/components/ui/command/index.ts@@ -6,7 +6,6 @@ import Input from './command-input.svelte';import Item from './command-item.svelte';import List from './command-list.svelte';import Separator from './command-separator.svelte';-import Shortcut from './command-shortcut.svelte';export {Root,@@ -17,7 +16,6 @@ export {Item,List,Separator,- Shortcut,//Root as Command,Dialog as CommandDialog,@@ -26,6 +24,5 @@ export {Input as CommandInput,Item as CommandItem,List as CommandList,- Separator as CommandSeparator,- Shortcut as CommandShortcut+ Separator as CommandSeparator};diff --git a/frontend/src/lib/components/ui/date-range-picker/date-range-picker.svelte b/frontend/src/lib/components/ui/date-range-picker/date-range-picker.sveltedeleted file mode 100644index 05a10576..00000000--- a/frontend/src/lib/components/ui/date-range-picker/date-range-picker.svelte+++ /dev/null@@ -1,210 +0,0 @@-<script lang="ts">- import * as Popover from "$lib/components/ui/popover";- import { Calendar } from "$lib/components/ui/calendar";- import { Button } from "$lib/components/ui/button";- import { Input } from "$lib/components/ui/input";- import { Label } from "$lib/components/ui/label";- import { CalendarDays, ChevronDown } from "@lucide/svelte";- import { CalendarDate, getLocalTimeZone, today } from "@internationalized/date";- import type { DateValue } from "@internationalized/date";-- type Props = {- fromDate: string;- toDate: string;- onApply: (from: string, to: string) => void;- class?: string;- };-- let { fromDate, toDate, onApply, class: className = '' }: Props = $props();-- let open = $state(false);- let fromCalendarOpen = $state(false);- let toCalendarOpen = $state(false);-- // Internal state for dates and times- let tempFromDate = $state<DateValue | undefined>(undefined);- let tempFromTime = $state('00:00');- let tempToDate = $state<DateValue | undefined>(undefined);- let tempToTime = $state('23:59');-- // Parse the ISO string into CalendarDate and time string- function parseDateTime(dateTimeStr: string): { date: DateValue | undefined; time: string } {- if (!dateTimeStr) return { date: undefined, time: '00:00' };- try {- const d = new Date(dateTimeStr);- const calDate = new CalendarDate(d.getFullYear(), d.getMonth() + 1, d.getDate());- const hours = d.getHours().toString().padStart(2, '0');- const minutes = d.getMinutes().toString().padStart(2, '0');- return { date: calDate, time: `${hours}:${minutes}` };- } catch {- return { date: undefined, time: '00:00' };- }- }-- // Combine CalendarDate and time string into ISO string- function combineDateTime(calDate: DateValue | undefined, time: string): string {- if (!calDate) return '';- const [hours, minutes] = time.split(':').map(Number);- const jsDate = calDate.toDate(getLocalTimeZone());- jsDate.setHours(hours || 0, minutes || 0, 0, 0);- return jsDate.toISOString().slice(0, 16);- }-- // Sync temp values when popover opens or props change- $effect(() => {- if (open) {- const from = parseDateTime(fromDate);- const to = parseDateTime(toDate);- tempFromDate = from.date;- tempFromTime = from.time;- tempToDate = to.date;- tempToTime = to.time;- }- });-- function handleApply() {- const from = combineDateTime(tempFromDate, tempFromTime);- const to = combineDateTime(tempToDate, tempToTime);- if (from && to) {- onApply(from, to);- }- open = false;- }-- function handleCancel() {- open = false;- }-- function formatDisplayDate(dateStr: string): string {- if (!dateStr) return '';- try {- const date = new Date(dateStr);- return date.toLocaleDateString('en-US', {- month: 'short',- day: 'numeric',- hour: '2-digit',- minute: '2-digit'- });- } catch {- return dateStr;- }- }-- function formatCalendarDate(date: DateValue | undefined): string {- if (!date) return 'Select date';- return date.toDate(getLocalTimeZone()).toLocaleDateString('en-US', {- month: 'short',- day: 'numeric',- year: 'numeric'- });- }-- const displayText = $derived(() => {- if (!fromDate || !toDate) return 'Select date range';- return `${formatDisplayDate(fromDate)} – ${formatDisplayDate(toDate)}`;- });-</script>--<Popover.Root bind:open>- <Popover.Trigger>- {#snippet child({ props })}- <Button- variant="outline"- class="h-9 min-w-[280px] justify-start text-left font-normal {className}"- {...props}- >- <CalendarDays class="mr-2 h-4 w-4 opacity-70" />- <span class="truncate">{displayText()}</span>- </Button>- {/snippet}- </Popover.Trigger>- <Popover.Content class="w-auto p-0" align="start">- <div class="p-4 space-y-4">- <div class="grid grid-cols-2 gap-6">- <!-- From Date/Time -->- <div class="space-y-3">- <Label class="text-xs font-medium text-muted-foreground">From</Label>-- <!-- Date Picker -->- <Popover.Root bind:open={fromCalendarOpen}>- <Popover.Trigger>- {#snippet child({ props })}- <Button- variant="outline"- class="w-full justify-between font-normal text-sm h-9"- {...props}- >- {formatCalendarDate(tempFromDate)}- <ChevronDown class="h-4 w-4 opacity-50" />- </Button>- {/snippet}- </Popover.Trigger>- <Popover.Content class="w-auto p-0" align="start">- <Calendar- type="single"- bind:value={tempFromDate}- onValueChange={() => {- fromCalendarOpen = false;- }}- captionLayout="dropdown"- />- </Popover.Content>- </Popover.Root>-- <!-- Time Input -->- <Input- type="time"- class="h-9 text-sm bg-background appearance-none [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none"- bind:value={tempFromTime}- />- </div>-- <!-- To Date/Time -->- <div class="space-y-3">- <Label class="text-xs font-medium text-muted-foreground">To</Label>-- <!-- Date Picker -->- <Popover.Root bind:open={toCalendarOpen}>- <Popover.Trigger>- {#snippet child({ props })}- <Button- variant="outline"- class="w-full justify-between font-normal text-sm h-9"- {...props}- >- {formatCalendarDate(tempToDate)}- <ChevronDown class="h-4 w-4 opacity-50" />- </Button>- {/snippet}- </Popover.Trigger>- <Popover.Content class="w-auto p-0" align="start">- <Calendar- type="single"- bind:value={tempToDate}- onValueChange={() => {- toCalendarOpen = false;- }}- captionLayout="dropdown"- />- </Popover.Content>- </Popover.Root>-- <!-- Time Input -->- <Input- type="time"- class="h-9 text-sm bg-background appearance-none [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none"- bind:value={tempToTime}- />- </div>- </div>- <div class="flex items-center justify-end gap-2 pt-2 border-t">- <Button variant="ghost" size="sm" onclick={handleCancel}>- Cancel- </Button>- <Button size="sm" onclick={handleApply}>- Apply- </Button>- </div>- </div>- </Popover.Content>-</Popover.Root>diff --git a/frontend/src/lib/components/ui/date-range-picker/index.ts b/frontend/src/lib/components/ui/date-range-picker/index.tsdeleted file mode 100644index 5e0f2727..00000000--- a/frontend/src/lib/components/ui/date-range-picker/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import DateRangePicker from "./date-range-picker.svelte";--export { DateRangePicker };diff --git a/frontend/src/lib/components/ui/datetime-picker/datetime-picker.svelte b/frontend/src/lib/components/ui/datetime-picker/datetime-picker.svelteindex e211110c..ee345b39 100644--- a/frontend/src/lib/components/ui/datetime-picker/datetime-picker.svelte+++ b/frontend/src/lib/components/ui/datetime-picker/datetime-picker.svelte@@ -1,268 +1,252 @@<script lang="ts">- import { Calendar } from "$lib/components/ui/calendar";- import * as Select from "$lib/components/ui/select";- import { cn } from "$lib/utils";- import { CalendarDate, CalendarDateTime, getLocalTimeZone, today, type DateValue } from "@internationalized/date";-- type Period = 'AM' | 'PM';-- interface Props {- value?: CalendarDateTime | CalendarDate;- onValueChange?: (value: CalendarDateTime) => void;- class?: string;- }-- let {- value = $bindable(),- onValueChange,- class: className- }: Props = $props();-- // Time state (12-hour format for display)- let hours = $state(12);- let minutes = $state(0);- let seconds = $state(0);- let period = $state<Period>('AM');-- // Initialize from value- $effect(() => {- if (value && 'hour' in value) {- const hour24 = value.hour;- period = hour24 >= 12 ? 'PM' : 'AM';- hours = hour24 % 12 || 12;- minutes = value.minute;- seconds = value.second;- }- });-- // Derived 24-hour value- const hour24 = $derived(() => {- if (period === 'AM') {- return hours === 12 ? 0 : hours;- } else {- return hours === 12 ? 12 : hours + 12;- }- });-- // Handle calendar date change- function handleDateChange(newDate: DateValue | undefined) {- if (!newDate) return;-- const dateTime = new CalendarDateTime(- newDate.year,- newDate.month,- newDate.day,- hour24(),- minutes,- seconds- );-- value = dateTime;- onValueChange?.(dateTime);- }-- // Handle time changes- function updateDateTime() {- if (!value) {- const now = today(getLocalTimeZone());- value = new CalendarDateTime(now.year, now.month, now.day, hour24(), minutes, seconds);- } else {- const dateTime = new CalendarDateTime(- value.year,- value.month,- value.day,- hour24(),- minutes,- seconds- );- value = dateTime;- onValueChange?.(dateTime);- }- }-- // Input handlers with validation- function handleHoursInput(e: Event) {- const input = e.target as HTMLInputElement;- let val = parseInt(input.value) || 0;- if (val < 1) val = 1;- if (val > 12) val = 12;- hours = val;- input.value = String(val).padStart(2, '0');- updateDateTime();- }-- function handleMinutesInput(e: Event) {- const input = e.target as HTMLInputElement;- let val = parseInt(input.value) || 0;- if (val < 0) val = 0;- if (val > 59) val = 59;- minutes = val;- input.value = String(val).padStart(2, '0');- updateDateTime();- }-- function handleSecondsInput(e: Event) {- const input = e.target as HTMLInputElement;- let val = parseInt(input.value) || 0;- if (val < 0) val = 0;- if (val > 59) val = 59;- seconds = val;- input.value = String(val).padStart(2, '0');- updateDateTime();- }-- function handlePeriodChange(newPeriod: string | undefined) {- if (newPeriod === 'AM' || newPeriod === 'PM') {- period = newPeriod;- updateDateTime();- }- }-- // Increment/decrement helpers- function incrementHours() {- hours = hours >= 12 ? 1 : hours + 1;- updateDateTime();- }-- function decrementHours() {- hours = hours <= 1 ? 12 : hours - 1;- updateDateTime();- }-- function incrementMinutes() {- if (minutes >= 59) {- minutes = 0;- incrementHours();- } else {- minutes++;- }- updateDateTime();- }-- function decrementMinutes() {- if (minutes <= 0) {- minutes = 59;- decrementHours();- } else {- minutes--;- }- updateDateTime();- }-- function incrementSeconds() {- if (seconds >= 59) {- seconds = 0;- incrementMinutes();- } else {- seconds++;- }- updateDateTime();- }-- function decrementSeconds() {- if (seconds <= 0) {- seconds = 59;- decrementMinutes();- } else {- seconds--;- }- updateDateTime();- }-- // Handle keyboard navigation- function handleKeyDown(e: KeyboardEvent, field: 'hours' | 'minutes' | 'seconds') {- if (e.key === 'ArrowUp') {- e.preventDefault();- if (field === 'hours') incrementHours();- else if (field === 'minutes') incrementMinutes();- else incrementSeconds();- } else if (e.key === 'ArrowDown') {- e.preventDefault();- if (field === 'hours') decrementHours();- else if (field === 'minutes') decrementMinutes();- else decrementSeconds();- }- }-- // Get calendar-compatible date value- const calendarValue = $derived(() => {- if (!value) return undefined;- return new CalendarDate(value.year, value.month, value.day);- });+ import { Calendar } from '$lib/components/ui/calendar';+ import * as Select from '$lib/components/ui/select';+ import { cn } from '$lib/utils';+ import {+ CalendarDate,+ CalendarDateTime,+ getLocalTimeZone,+ today,+ type DateValue+ } from '@internationalized/date';++ type Period = 'AM' | 'PM';++ interface Props {+ value?: CalendarDateTime | CalendarDate;+ onValueChange?: (value: CalendarDateTime) => void;+ class?: string;+ }++ let { value = $bindable(), onValueChange, class: className }: Props = $props();++ // Time state (12-hour format for display)+ let hours = $state(12);+ let minutes = $state(0);+ let seconds = $state(0);+ let period = $state<Period>('AM');++ // Initialize from value+ $effect(() => {+ if (value && 'hour' in value) {+ const hour24 = value.hour;+ period = hour24 >= 12 ? 'PM' : 'AM';+ hours = hour24 % 12 || 12;+ minutes = value.minute;+ seconds = value.second;+ }+ });++ // Derived 24-hour value+ const hour24 = $derived(() => {+ if (period === 'AM') {+ return hours === 12 ? 0 : hours;+ } else {+ return hours === 12 ? 12 : hours + 12;+ }+ });++ // Handle calendar date change+ function handleDateChange(newDate: DateValue | undefined) {+ if (!newDate) return;++ const dateTime = new CalendarDateTime(+ newDate.year,+ newDate.month,+ newDate.day,+ hour24(),+ minutes,+ seconds+ );++ value = dateTime;+ onValueChange?.(dateTime);+ }++ // Handle time changes+ function updateDateTime() {+ if (!value) {+ const now = today(getLocalTimeZone());+ value = new CalendarDateTime(now.year, now.month, now.day, hour24(), minutes, seconds);+ } else {+ const dateTime = new CalendarDateTime(+ value.year,+ value.month,+ value.day,+ hour24(),+ minutes,+ seconds+ );+ value = dateTime;+ onValueChange?.(dateTime);+ }+ }++ // Input handlers with validation+ function handleHoursInput(e: Event) {+ const input = e.target as HTMLInputElement;+ let val = parseInt(input.value) || 0;+ if (val < 1) val = 1;+ if (val > 12) val = 12;+ hours = val;+ input.value = String(val).padStart(2, '0');+ updateDateTime();+ }++ function handleMinutesInput(e: Event) {+ const input = e.target as HTMLInputElement;+ let val = parseInt(input.value) || 0;+ if (val < 0) val = 0;+ if (val > 59) val = 59;+ minutes = val;+ input.value = String(val).padStart(2, '0');+ updateDateTime();+ }++ function handlePeriodChange(newPeriod: string | undefined) {+ if (newPeriod === 'AM' || newPeriod === 'PM') {+ period = newPeriod;+ updateDateTime();+ }+ }++ // Increment/decrement helpers+ function incrementHours() {+ hours = hours >= 12 ? 1 : hours + 1;+ updateDateTime();+ }++ function decrementHours() {+ hours = hours <= 1 ? 12 : hours - 1;+ updateDateTime();+ }++ function incrementMinutes() {+ if (minutes >= 59) {+ minutes = 0;+ incrementHours();+ } else {+ minutes++;+ }+ updateDateTime();+ }++ function decrementMinutes() {+ if (minutes <= 0) {+ minutes = 59;+ decrementHours();+ } else {+ minutes--;+ }+ updateDateTime();+ }++ function incrementSeconds() {+ if (seconds >= 59) {+ seconds = 0;+ incrementMinutes();+ } else {+ seconds++;+ }+ updateDateTime();+ }++ function decrementSeconds() {+ if (seconds <= 0) {+ seconds = 59;+ decrementMinutes();+ } else {+ seconds--;+ }+ updateDateTime();+ }++ // Handle keyboard navigation+ function handleKeyDown(e: KeyboardEvent, field: 'hours' | 'minutes' | 'seconds') {+ if (e.key === 'ArrowUp') {+ e.preventDefault();+ if (field === 'hours') incrementHours();+ else if (field === 'minutes') incrementMinutes();+ else incrementSeconds();+ } else if (e.key === 'ArrowDown') {+ e.preventDefault();+ if (field === 'hours') decrementHours();+ else if (field === 'minutes') decrementMinutes();+ else decrementSeconds();+ }+ }++ // Get calendar-compatible date value+ const calendarValue = $derived(() => {+ if (!value) return undefined;+ return new CalendarDate(value.year, value.month, value.day);+ });</script>-<div class={cn("flex flex-col", className)}>- <!-- Calendar -->- <Calendar- type="single"- value={calendarValue()}- onValueChange={handleDateChange}- />-- <!-- Time Picker -->- <div class="border-t px-3 py-3">- <div class="flex items-end gap-2">- <!-- Hours -->- <div class="flex flex-col items-center gap-1">- <span class="text-xs text-muted-foreground">Hours</span>- <input- type="text"- inputmode="numeric"- class="w-10 h-9 text-center text-sm border rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring tabular-nums"- value={String(hours).padStart(2, '0')}- onchange={handleHoursInput}- onkeydown={(e) => handleKeyDown(e, 'hours')}- maxlength={2}- />- </div>-- <span class="text-sm font-medium text-muted-foreground pb-1">:</span>-- <!-- Minutes -->- <div class="flex flex-col items-center gap-1">- <span class="text-xs text-muted-foreground">Minutes</span>- <input- type="text"- inputmode="numeric"- class="w-10 h-9 text-center text-sm border rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring tabular-nums"- value={String(minutes).padStart(2, '0')}- onchange={handleMinutesInput}- onkeydown={(e) => handleKeyDown(e, 'minutes')}- maxlength={2}- />- </div>-- <span class="text-sm font-medium text-muted-foreground pb-1">:</span>-- <!-- Seconds (disabled - not passed between pages) -->- <div class="flex flex-col items-center gap-1">- <span class="text-xs text-muted-foreground">Seconds</span>- <input- type="text"- inputmode="numeric"- class="w-10 h-9 text-center text-sm border rounded-md bg-muted text-muted-foreground tabular-nums cursor-not-allowed"- value={String(seconds).padStart(2, '0')}- disabled- />- </div>-- <!-- Period (AM/PM) -->- <div class="flex flex-col items-center gap-1">- <span class="text-xs text-muted-foreground">Period</span>- <Select.Root- type="single"- value={period}- onValueChange={handlePeriodChange}- >- <Select.Trigger class="w-[60px] h-9 text-sm">- {period}- </Select.Trigger>- <Select.Content>- <Select.Item value="AM" label="AM">AM</Select.Item>- <Select.Item value="PM" label="PM">PM</Select.Item>- </Select.Content>- </Select.Root>- </div>- </div>- </div>+<div class={cn('flex flex-col', className)}>+ <!-- Calendar -->+ <Calendar type="single" value={calendarValue()} onValueChange={handleDateChange} />++ <!-- Time Picker -->+ <div class="border-t px-3 py-3">+ <div class="flex items-end gap-2">+ <!-- Hours -->+ <div class="flex flex-col items-center gap-1">+ <span class="text-xs text-muted-foreground">Hours</span>+ <input+ type="text"+ inputmode="numeric"+ class="h-9 w-10 rounded-md border bg-background text-center text-sm tabular-nums focus:ring-2 focus:ring-ring focus:outline-none"+ value={String(hours).padStart(2, '0')}+ onchange={handleHoursInput}+ onkeydown={(e) => handleKeyDown(e, 'hours')}+ maxlength={2}+ />+ </div>++ <span class="pb-1 text-sm font-medium text-muted-foreground">:</span>++ <!-- Minutes -->+ <div class="flex flex-col items-center gap-1">+ <span class="text-xs text-muted-foreground">Minutes</span>+ <input+ type="text"+ inputmode="numeric"+ class="h-9 w-10 rounded-md border bg-background text-center text-sm tabular-nums focus:ring-2 focus:ring-ring focus:outline-none"+ value={String(minutes).padStart(2, '0')}+ onchange={handleMinutesInput}+ onkeydown={(e) => handleKeyDown(e, 'minutes')}+ maxlength={2}+ />+ </div>++ <span class="pb-1 text-sm font-medium text-muted-foreground">:</span>++ <!-- Seconds (disabled - not passed between pages) -->+ <div class="flex flex-col items-center gap-1">+ <span class="text-xs text-muted-foreground">Seconds</span>+ <input+ type="text"+ inputmode="numeric"+ class="h-9 w-10 cursor-not-allowed rounded-md border bg-muted text-center text-sm text-muted-foreground tabular-nums"+ value={String(seconds).padStart(2, '0')}+ disabled+ />+ </div>++ <!-- Period (AM/PM) -->+ <div class="flex flex-col items-center gap-1">+ <span class="text-xs text-muted-foreground">Period</span>+ <Select.Root type="single" value={period} onValueChange={handlePeriodChange}>+ <Select.Trigger class="h-9 w-[60px] text-sm">+ {period}+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="AM" label="AM">AM</Select.Item>+ <Select.Item value="PM" label="PM">PM</Select.Item>+ </Select.Content>+ </Select.Root>+ </div>+ </div>+ </div></div>diff --git a/frontend/src/lib/components/ui/datetime-picker/index.ts b/frontend/src/lib/components/ui/datetime-picker/index.tsindex 07bc6beb..21e50b67 100644--- a/frontend/src/lib/components/ui/datetime-picker/index.ts+++ b/frontend/src/lib/components/ui/datetime-picker/index.ts@@ -1,3 +1,3 @@-import DateTimePicker from "./datetime-picker.svelte";+import DateTimePicker from './datetime-picker.svelte';export { DateTimePicker };diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-checkbox-group.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-checkbox-group.svelteindex e0e19718..c0bf94b5 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-checkbox-group.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-checkbox-group.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';let {ref = $bindable(null),diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-checkbox-item.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-checkbox-item.svelteindex b15896a0..c3beb65f 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-checkbox-item.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-checkbox-item.svelte@@ -1,9 +1,9 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";- import CheckIcon from "@lucide/svelte/icons/check";- import MinusIcon from "@lucide/svelte/icons/minus";- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";- import type { Snippet } from "svelte";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';+ import CheckIcon from '@lucide/svelte/icons/check';+ import MinusIcon from '@lucide/svelte/icons/minus';+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';+ import type { Snippet } from 'svelte';let {ref = $bindable(null),@@ -23,19 +23,17 @@bind:indeterminatedata-slot="dropdown-menu-checkbox-item"class={cn(- "focus:bg-accent focus:text-accent-foreground relative flex cursor-pointer items-center gap-2 rounded-sm py-1.5 ps-8 pe-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex cursor-pointer items-center gap-2 rounded-sm py-1.5 ps-8 pe-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className)}{...restProps}>{#snippet children({ checked, indeterminate })}- <span- class="pointer-events-none absolute start-2 flex size-3.5 items-center justify-center"- >+ <span class="pointer-events-none absolute start-2 flex size-3.5 items-center justify-center">{#if indeterminate}<MinusIcon class="size-4" />{:else}- <CheckIcon class={cn("size-4", !checked && "text-transparent")} />+ <CheckIcon class={cn('size-4', !checked && 'text-transparent')} />{/if}</span>{@render childrenProp?.()}diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-content.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-content.svelteindex 1e96782e..322c342c 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-content.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-content.svelte@@ -1,8 +1,8 @@<script lang="ts">- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";- import DropdownMenuPortal from "./dropdown-menu-portal.svelte";- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";- import type { ComponentProps } from "svelte";+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';+ import DropdownMenuPortal from './dropdown-menu-portal.svelte';+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';+ import type { ComponentProps } from 'svelte';let {ref = $bindable(null),@@ -21,7 +21,7 @@data-slot="dropdown-menu-content"{sideOffset}class={cn(- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--bits-dropdown-menu-content-available-height) min-w-[8rem] origin-(--bits-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md outline-none",+ 'z-50 max-h-(--bits-dropdown-menu-content-available-height) min-w-[8rem] origin-(--bits-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-group-heading.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-group-heading.svelteindex 433540fd..92b35d28 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-group-heading.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-group-heading.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";- import type { ComponentProps } from "svelte";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';+ import type { ComponentProps } from 'svelte';let {ref = $bindable(null),@@ -17,6 +17,6 @@bind:refdata-slot="dropdown-menu-group-heading"data-inset={inset}- class={cn("px-2 py-1.5 text-sm font-semibold data-[inset]:ps-8", className)}+ class={cn('px-2 py-1.5 text-sm font-semibold data-[inset]:ps-8', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-group.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-group.svelteindex aca1f7bd..261ab7e6 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-group.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-group.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';let { ref = $bindable(null), ...restProps }: DropdownMenuPrimitive.GroupProps = $props();</script>diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelteindex a973165a..768beabe 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelte@@ -1,16 +1,16 @@<script lang="ts">- import { cn } from "$lib/utils.js";- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";+ import { cn } from '$lib/utils.js';+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';let {ref = $bindable(null),class: className,inset,- variant = "default",+ variant = 'default',...restProps}: DropdownMenuPrimitive.ItemProps & {inset?: boolean;- variant?: "default" | "destructive";+ variant?: 'default' | 'destructive';} = $props();</script>@@ -20,7 +20,7 @@data-inset={inset}data-variant={variant}class={cn(- "data-highlighted:bg-accent data-highlighted:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:data-highlighted:bg-destructive/10 dark:data-[variant=destructive]:data-highlighted:bg-destructive/20 data-[variant=destructive]:data-highlighted:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed data-[inset]:ps-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[inset]:ps-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:data-highlighted:bg-destructive/10 data-[variant=destructive]:data-highlighted:text-destructive dark:data-[variant=destructive]:data-highlighted:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:!text-destructive",className)}{...restProps}diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-label.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-label.svelteindex 9681c2bb..da3afc31 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-label.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-label.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -17,7 +17,7 @@bind:this={ref}data-slot="dropdown-menu-label"data-inset={inset}- class={cn("px-2 py-1.5 text-sm font-semibold data-[inset]:ps-8", className)}+ class={cn('px-2 py-1.5 text-sm font-semibold data-[inset]:ps-8', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-portal.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-portal.svelteindex 274cfef7..089a25cc 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-portal.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-portal.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';let { ...restProps }: DropdownMenuPrimitive.PortalProps = $props();</script>diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-group.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-group.svelteindex 189aef40..3e987491 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-group.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-group.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';let {ref = $bindable(null),diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-item.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-item.svelteindex f466f79d..42d75176 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-item.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-item.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";- import CircleIcon from "@lucide/svelte/icons/circle";- import { cn, type WithoutChild } from "$lib/utils.js";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';+ import CircleIcon from '@lucide/svelte/icons/circle';+ import { cn, type WithoutChild } from '$lib/utils.js';let {ref = $bindable(null),@@ -15,15 +15,13 @@bind:refdata-slot="dropdown-menu-radio-item"class={cn(- "focus:bg-accent focus:text-accent-foreground relative flex cursor-pointer items-center gap-2 rounded-sm py-1.5 ps-8 pe-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex cursor-pointer items-center gap-2 rounded-sm py-1.5 ps-8 pe-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className)}{...restProps}>{#snippet children({ checked })}- <span- class="pointer-events-none absolute start-2 flex size-3.5 items-center justify-center"- >+ <span class="pointer-events-none absolute start-2 flex size-3.5 items-center justify-center">{#if checked}<CircleIcon class="size-2 fill-current" />{/if}diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-separator.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-separator.svelteindex 90f1b6f1..a076e43c 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-separator.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-separator.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,6 +12,6 @@<DropdownMenuPrimitive.Separatorbind:refdata-slot="dropdown-menu-separator"- class={cn("bg-border -mx-1 my-1 h-px", className)}+ class={cn('-mx-1 my-1 h-px bg-border', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-shortcut.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-shortcut.svelteindex 7c6e9c67..0b37bbd3 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-shortcut.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-shortcut.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<spanbind:this={ref}data-slot="dropdown-menu-shortcut"- class={cn("text-muted-foreground ms-auto text-xs tracking-widest", className)}+ class={cn('ms-auto text-xs tracking-widest text-muted-foreground', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelteindex 3f06dc49..56ca3e01 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@bind:refdata-slot="dropdown-menu-sub-content"class={cn(- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--bits-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",+ 'z-50 min-w-[8rem] origin-(--bits-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-trigger.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-trigger.svelteindex 93e598d1..65ad8285 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-trigger.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-trigger.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";- import ChevronRightIcon from "@lucide/svelte/icons/chevron-right";- import { cn } from "$lib/utils.js";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';+ import ChevronRightIcon from '@lucide/svelte/icons/chevron-right';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -19,7 +19,7 @@data-slot="dropdown-menu-sub-trigger"data-inset={inset}class={cn(- "data-highlighted:bg-accent data-highlighted:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed data-[inset]:ps-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[inset]:ps-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",className)}{...restProps}diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub.svelteindex f0445813..9cfa3b8c 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';let { open = $bindable(false), ...restProps }: DropdownMenuPrimitive.SubProps = $props();</script>diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-trigger.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-trigger.svelteindex cb053444..032b6453 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-trigger.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-trigger.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';let { ref = $bindable(null), ...restProps }: DropdownMenuPrimitive.TriggerProps = $props();</script>diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu.svelteindex cb4bc621..fbbb7908 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui";+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';let { open = $bindable(false), ...restProps }: DropdownMenuPrimitive.RootProps = $props();</script>diff --git a/frontend/src/lib/components/ui/dropdown-menu/index.ts b/frontend/src/lib/components/ui/dropdown-menu/index.tsindex 7850c6a3..b097e3fd 100644--- a/frontend/src/lib/components/ui/dropdown-menu/index.ts+++ b/frontend/src/lib/components/ui/dropdown-menu/index.ts@@ -1,20 +1,20 @@-import Root from "./dropdown-menu.svelte";-import Sub from "./dropdown-menu-sub.svelte";-import CheckboxGroup from "./dropdown-menu-checkbox-group.svelte";-import CheckboxItem from "./dropdown-menu-checkbox-item.svelte";-import Content from "./dropdown-menu-content.svelte";-import Group from "./dropdown-menu-group.svelte";-import Item from "./dropdown-menu-item.svelte";-import Label from "./dropdown-menu-label.svelte";-import RadioGroup from "./dropdown-menu-radio-group.svelte";-import RadioItem from "./dropdown-menu-radio-item.svelte";-import Separator from "./dropdown-menu-separator.svelte";-import Shortcut from "./dropdown-menu-shortcut.svelte";-import Trigger from "./dropdown-menu-trigger.svelte";-import SubContent from "./dropdown-menu-sub-content.svelte";-import SubTrigger from "./dropdown-menu-sub-trigger.svelte";-import GroupHeading from "./dropdown-menu-group-heading.svelte";-import Portal from "./dropdown-menu-portal.svelte";+import Root from './dropdown-menu.svelte';+import Sub from './dropdown-menu-sub.svelte';+import CheckboxGroup from './dropdown-menu-checkbox-group.svelte';+import CheckboxItem from './dropdown-menu-checkbox-item.svelte';+import Content from './dropdown-menu-content.svelte';+import Group from './dropdown-menu-group.svelte';+import Item from './dropdown-menu-item.svelte';+import Label from './dropdown-menu-label.svelte';+import RadioGroup from './dropdown-menu-radio-group.svelte';+import RadioItem from './dropdown-menu-radio-item.svelte';+import Separator from './dropdown-menu-separator.svelte';+import Shortcut from './dropdown-menu-shortcut.svelte';+import Trigger from './dropdown-menu-trigger.svelte';+import SubContent from './dropdown-menu-sub-content.svelte';+import SubTrigger from './dropdown-menu-sub-trigger.svelte';+import GroupHeading from './dropdown-menu-group-heading.svelte';+import Portal from './dropdown-menu-portal.svelte';export {CheckboxGroup,@@ -50,5 +50,5 @@ export {Sub,SubContent,SubTrigger,- Trigger,+ Trigger};diff --git a/frontend/src/lib/components/ui/error-display/error-display.svelte b/frontend/src/lib/components/ui/error-display/error-display.svelteindex 649994ea..5ab40394 100644--- a/frontend/src/lib/components/ui/error-display/error-display.svelte+++ b/frontend/src/lib/components/ui/error-display/error-display.svelte@@ -1,5 +1,4 @@<script lang="ts">- import { goto } from '$app/navigation';import { Button } from '$lib/components/ui/button';interface Props {diff --git a/frontend/src/lib/components/ui/impact-badge/impact-badge.svelte b/frontend/src/lib/components/ui/impact-badge/impact-badge.svelteindex 93e30669..59368edf 100644--- a/frontend/src/lib/components/ui/impact-badge/impact-badge.svelte+++ b/frontend/src/lib/components/ui/impact-badge/impact-badge.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { TriangleAlert, CheckCircle } from 'lucide-svelte';+ import { TriangleAlert, CheckCircle } from '@lucide/svelte';import * as Tooltip from '$lib/components/ui/tooltip';let {diff --git a/frontend/src/lib/components/ui/input/index.ts b/frontend/src/lib/components/ui/input/index.tsindex f47b6d3f..15c0933d 100644--- a/frontend/src/lib/components/ui/input/index.ts+++ b/frontend/src/lib/components/ui/input/index.ts@@ -1,7 +1,7 @@-import Root from "./input.svelte";+import Root from './input.svelte';export {Root,//- Root as Input,+ Root as Input};diff --git a/frontend/src/lib/components/ui/input/input.svelte b/frontend/src/lib/components/ui/input/input.svelteindex ff1a4c87..9089134c 100644--- a/frontend/src/lib/components/ui/input/input.svelte+++ b/frontend/src/lib/components/ui/input/input.svelte@@ -1,12 +1,12 @@<script lang="ts">- import type { HTMLInputAttributes, HTMLInputTypeAttribute } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLInputAttributes, HTMLInputTypeAttribute } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';- type InputType = Exclude<HTMLInputTypeAttribute, "file">;+ type InputType = Exclude<HTMLInputTypeAttribute, 'file'>;type Props = WithElementRef<- Omit<HTMLInputAttributes, "type"> &- ({ type: "file"; files?: FileList } | { type?: InputType; files?: undefined })+ Omit<HTMLInputAttributes, 'type'> &+ ({ type: 'file'; files?: FileList } | { type?: InputType; files?: undefined })>;let {@@ -15,19 +15,19 @@type,files = $bindable(),class: className,- "data-slot": dataSlot = "input",+ 'data-slot': dataSlot = 'input',...restProps}: Props = $props();</script>-{#if type === "file"}+{#if type === 'file'}<inputbind:this={ref}data-slot={dataSlot}class={cn(- "selection:bg-primary dark:bg-input/30 selection:text-primary-foreground border-input ring-offset-background placeholder:text-muted-foreground flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 pt-1.5 text-sm font-medium shadow-xs transition-[color,box-shadow] outline-none disabled:cursor-not-allowed disabled:opacity-50",- "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",- "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",+ 'flex h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 pt-1.5 text-sm font-medium shadow-xs ring-offset-background transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30',+ 'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50',+ 'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',className)}type="file"@@ -40,9 +40,9 @@bind:this={ref}data-slot={dataSlot}class={cn(- "border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",- "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",- "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",+ 'flex h-9 w-full min-w-0 rounded-md border border-input bg-background px-3 py-1 text-base shadow-xs ring-offset-background transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30',+ 'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50',+ 'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',className)}{type}diff --git a/frontend/src/lib/components/ui/label-value/index.ts b/frontend/src/lib/components/ui/label-value/index.tsindex 7862c763..1614b87c 100644--- a/frontend/src/lib/components/ui/label-value/index.ts+++ b/frontend/src/lib/components/ui/label-value/index.ts@@ -1,3 +1,3 @@-import LabelValue from "./label-value.svelte";+import LabelValue from './label-value.svelte';export { LabelValue };diff --git a/frontend/src/lib/components/ui/label-value/label-value.svelte b/frontend/src/lib/components/ui/label-value/label-value.svelteindex ae9d1942..71da1d9c 100644--- a/frontend/src/lib/components/ui/label-value/label-value.svelte+++ b/frontend/src/lib/components/ui/label-value/label-value.svelte@@ -1,10 +1,10 @@<script lang="ts">- import { cn } from "$lib/utils.js";+ import { cn } from '$lib/utils.js';let {label,value,- fallback = "-",+ fallback = '-',mono = false,truncate = false,large = false,@@ -26,9 +26,9 @@<p class="text-sm text-muted-foreground">{label}</p><pclass={cn(- !large && "text-sm",- mono && "font-mono",- truncate ? "truncate" : "break-all",+ !large && 'text-sm',+ mono && 'font-mono',+ truncate ? 'truncate' : 'break-all',valueClass)}title={truncate && typeof displayValue === 'string' ? displayValue : undefined}diff --git a/frontend/src/lib/components/ui/label/index.ts b/frontend/src/lib/components/ui/label/index.tsindex 8bfca0b3..808d1415 100644--- a/frontend/src/lib/components/ui/label/index.ts+++ b/frontend/src/lib/components/ui/label/index.ts@@ -1,7 +1,7 @@-import Root from "./label.svelte";+import Root from './label.svelte';export {Root,//- Root as Label,+ Root as Label};diff --git a/frontend/src/lib/components/ui/label/label.svelte b/frontend/src/lib/components/ui/label/label.svelteindex d71afbca..7fef72e9 100644--- a/frontend/src/lib/components/ui/label/label.svelte+++ b/frontend/src/lib/components/ui/label/label.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Label as LabelPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Label as LabelPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@bind:refdata-slot="label"class={cn(- "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",+ 'flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/loading-circle/index.ts b/frontend/src/lib/components/ui/loading-circle/index.tsindex fbd76ac5..e8e72bd7 100644--- a/frontend/src/lib/components/ui/loading-circle/index.ts+++ b/frontend/src/lib/components/ui/loading-circle/index.ts@@ -1,3 +1,3 @@-import LoadingCircle from "./loading-circle.svelte";+import LoadingCircle from './loading-circle.svelte';export { LoadingCircle };diff --git a/frontend/src/lib/components/ui/loading-circle/loading-circle.svelte b/frontend/src/lib/components/ui/loading-circle/loading-circle.svelteindex 8bc9f25a..e5f1c3b6 100644--- a/frontend/src/lib/components/ui/loading-circle/loading-circle.svelte+++ b/frontend/src/lib/components/ui/loading-circle/loading-circle.svelte@@ -1,31 +1,31 @@<script lang="ts" module>- import { tv, type VariantProps } from "tailwind-variants";+ import { tv, type VariantProps } from 'tailwind-variants';export const loadingCircleVariants = tv({- base: "text-muted-foreground dark:text-white",+ base: 'text-muted-foreground dark:text-white',variants: {size: {- sm: "h-4 w-4",- default: "h-6 w-6",- md: "h-8 w-8",- lg: "h-12 w-12",- xlg: "h-18 w-18"+ sm: 'h-4 w-4',+ default: 'h-6 w-6',+ md: 'h-8 w-8',+ lg: 'h-12 w-12',+ xlg: 'h-18 w-18'}},defaultVariants: {- size: "default"+ size: 'default'}});- export type LoadingCircleSize = VariantProps<typeof loadingCircleVariants>["size"];+ export type LoadingCircleSize = VariantProps<typeof loadingCircleVariants>['size'];</script><script lang="ts">- import { cn } from "$lib/utils.js";+ import { cn } from '$lib/utils.js';let {class: className,- size = "default"+ size = 'default'}: {class?: string;size?: LoadingCircleSize;diff --git a/frontend/src/lib/components/ui/non-root-chip/non-root-chip.svelte b/frontend/src/lib/components/ui/non-root-chip/non-root-chip.svelteindex 0459912e..3aef2723 100644--- a/frontend/src/lib/components/ui/non-root-chip/non-root-chip.svelte+++ b/frontend/src/lib/components/ui/non-root-chip/non-root-chip.svelte@@ -21,7 +21,7 @@<Tooltip.Trigger><Badgevariant="outline"- class="ml-2 text-xs border-amber-500 bg-amber-50 text-amber-700 dark:border-yellow-500 dark:bg-transparent dark:text-yellow-400"+ class="ml-2 border-amber-500 bg-amber-50 text-xs text-amber-700 dark:border-yellow-500 dark:bg-transparent dark:text-yellow-400">{label}</Badge>diff --git a/frontend/src/lib/components/ui/pagination-footer/pagination-footer.svelte b/frontend/src/lib/components/ui/pagination-footer/pagination-footer.svelteindex f23eb7fc..b65972dd 100644--- a/frontend/src/lib/components/ui/pagination-footer/pagination-footer.svelte+++ b/frontend/src/lib/components/ui/pagination-footer/pagination-footer.svelte@@ -1,14 +1,13 @@<script lang="ts">import { Button } from '$lib/components/ui/button';import * as Select from '$lib/components/ui/select';- import { ChevronLeft, ChevronRight } from 'lucide-svelte';+ import { ChevronLeft, ChevronRight } from '@lucide/svelte';let {currentPage,totalPages,pageSize,totalItems,- itemsShown,onPageChange,onPageSizeChange,loading = false,@@ -19,7 +18,6 @@totalPages: number;pageSize: number;totalItems: number;- itemsShown?: number;onPageChange: (page: number) => void;onPageSizeChange: (size: number) => void;loading?: boolean;@@ -28,11 +26,9 @@} = $props();const selectOptions = $derived(- pageSizeOptions.map((size) => ({ value: size.toString(), label: size.toString() }))- );-- const pageSizeLabel = $derived(- selectOptions.find((o) => o.value === pageSize.toString())?.label ?? pageSize.toString()+ [...new Set([...pageSizeOptions, pageSize])]+ .sort((a, b) => a - b)+ .map((size) => ({ value: size.toString(), label: size.toString() })));function handlePrevPage() {@@ -57,106 +53,51 @@const plural = $derived(totalItems === 1 ? '' : 's');</script>-<div class="flex flex-col items-center justify-between gap-1.5 px-2 sm:hidden">- <div class="flex w-[100%] justify-between">- <div class="flex flex-1 items-center text-sm text-muted-foreground">- {#if itemsShown !== undefined}- Showing {itemsShown} of {totalItems} {itemLabel}{plural}- {:else}- {totalItems} {itemLabel}{plural} total- {/if}- </div>-- <div class="flex items-center space-x-2">- <p class="text-sm font-medium">Rows per page</p>- <Select.Root type="single" value={pageSize.toString()} onValueChange={handlePageSizeSelect}>- <Select.Trigger class="h-8 w-[70px]">- {pageSizeLabel}- </Select.Trigger>- <Select.Content side="top">- {#each selectOptions as option}- <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- </div>-- <div class="flex w-[100%] justify-between">- <div class="flex w-[100px] items-center justify-start text-sm font-medium">- Page {currentPage} of {displayedPages}- </div>- <div class="flex items-center space-x-2">- <Button- variant="outline"- size="sm"- class="h-8 w-8 p-0"- onclick={handlePrevPage}- disabled={currentPage <= 1 || loading}- >- <span class="sr-only">Go to previous page</span>- <ChevronLeft class="h-4 w-4" />- </Button>- <Button- variant="outline"- size="sm"- class="h-8 w-8 p-0"- onclick={handleNextPage}- disabled={currentPage >= totalPages || loading}- >- <span class="sr-only">Go to next page</span>- <ChevronRight class="h-4 w-4" />- </Button>- </div>- </div>-</div>--<div class="hidden items-center justify-between px-2 sm:flex">- <div class="flex-1 text-sm text-muted-foreground">- {#if itemsShown !== undefined}- Showing {itemsShown} of {totalItems} {itemLabel}{plural}- {:else}- {totalItems} {itemLabel}{plural} total- {/if}- </div>- <div class="flex items-center space-x-6 lg:space-x-8">- <div class="flex items-center space-x-2">- <p class="text-sm font-medium">Rows per page</p>- <Select.Root type="single" value={pageSize.toString()} onValueChange={handlePageSizeSelect}>- <Select.Trigger class="h-8 w-[70px]">- {pageSizeLabel}- </Select.Trigger>- <Select.Content side="top">- {#each selectOptions as option}- <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- <div class="flex w-[100px] items-center justify-center text-sm font-medium">- Page {currentPage} of {displayedPages}+{#if totalItems > 0}+ <div class="flex flex-wrap items-center justify-between gap-x-6 gap-y-2 px-2">+ <div class="text-sm whitespace-nowrap text-muted-foreground">+ {totalItems}+ {itemLabel}{plural} total</div>- <div class="flex items-center space-x-2">- <Button- variant="outline"- size="sm"- class="h-8 w-8 p-0"- onclick={handlePrevPage}- disabled={currentPage <= 1 || loading}- >- <span class="sr-only">Go to previous page</span>- <ChevronLeft class="h-4 w-4" />- </Button>- <Button- variant="outline"- size="sm"- class="h-8 w-8 p-0"- onclick={handleNextPage}- disabled={currentPage >= totalPages || loading}- >- <span class="sr-only">Go to next page</span>- <ChevronRight class="h-4 w-4" />- </Button>+ <div class="flex flex-wrap items-center gap-x-6 gap-y-2">+ <div class="flex items-center space-x-2">+ <p class="text-sm font-medium whitespace-nowrap">Rows per page</p>+ <Select.Root type="single" value={pageSize.toString()} onValueChange={handlePageSizeSelect}>+ <Select.Trigger class="h-8 w-[70px]">+ {pageSize}+ </Select.Trigger>+ <Select.Content side="top">+ {#each selectOptions as option (option.value)}+ <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ <div class="text-sm font-medium whitespace-nowrap">+ Page {currentPage} of {displayedPages}+ </div>+ <div class="flex items-center space-x-2">+ <Button+ variant="outline"+ size="sm"+ class="h-8 w-8 p-0"+ onclick={handlePrevPage}+ disabled={currentPage <= 1 || loading}+ >+ <span class="sr-only">Go to previous page</span>+ <ChevronLeft class="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ size="sm"+ class="h-8 w-8 p-0"+ onclick={handleNextPage}+ disabled={currentPage >= totalPages || loading}+ >+ <span class="sr-only">Go to next page</span>+ <ChevronRight class="h-4 w-4" />+ </Button>+ </div></div></div>-</div>+{/if}diff --git a/frontend/src/lib/components/ui/pagination/index.ts b/frontend/src/lib/components/ui/pagination/index.tsdeleted file mode 100644index a769899d..00000000--- a/frontend/src/lib/components/ui/pagination/index.ts+++ /dev/null@@ -1,31 +0,0 @@-import Root from "./pagination.svelte";-import Content from "./pagination-content.svelte";-import Item from "./pagination-item.svelte";-import Link from "./pagination-link.svelte";-import PrevButton from "./pagination-prev-button.svelte";-import NextButton from "./pagination-next-button.svelte";-import Ellipsis from "./pagination-ellipsis.svelte";-import Previous from "./pagination-previous.svelte";-import Next from "./pagination-next.svelte";--export {- Root,- Content,- Item,- Link,- PrevButton, //old- NextButton, //old- Ellipsis,- Previous,- Next,- //- Root as Pagination,- Content as PaginationContent,- Item as PaginationItem,- Link as PaginationLink,- PrevButton as PaginationPrevButton, //old- NextButton as PaginationNextButton, //old- Ellipsis as PaginationEllipsis,- Previous as PaginationPrevious,- Next as PaginationNext,-};diff --git a/frontend/src/lib/components/ui/pagination/pagination-content.svelte b/frontend/src/lib/components/ui/pagination/pagination-content.sveltedeleted file mode 100644index ce650ce7..00000000--- a/frontend/src/lib/components/ui/pagination/pagination-content.svelte+++ /dev/null@@ -1,20 +0,0 @@-<script lang="ts">- import type { HTMLAttributes } from 'svelte/elements';- import { cn, type WithElementRef } from '$lib/utils.js';-- let {- ref = $bindable(null),- class: className,- children,- ...restProps- }: WithElementRef<HTMLAttributes<HTMLUListElement>> = $props();-</script>--<ul- bind:this={ref}- data-slot="pagination-content"- class={cn('flex flex-row items-center gap-1', className)}- {...restProps}->- {@render children?.()}-</ul>diff --git a/frontend/src/lib/components/ui/pagination/pagination-ellipsis.svelte b/frontend/src/lib/components/ui/pagination/pagination-ellipsis.sveltedeleted file mode 100644index 3be94c9c..00000000--- a/frontend/src/lib/components/ui/pagination/pagination-ellipsis.svelte+++ /dev/null@@ -1,22 +0,0 @@-<script lang="ts">- import EllipsisIcon from "@lucide/svelte/icons/ellipsis";- import { cn, type WithElementRef, type WithoutChildren } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";-- let {- ref = $bindable(null),- class: className,- ...restProps- }: WithoutChildren<WithElementRef<HTMLAttributes<HTMLSpanElement>>> = $props();-</script>--<span- bind:this={ref}- aria-hidden="true"- data-slot="pagination-ellipsis"- class={cn("flex size-9 items-center justify-center", className)}- {...restProps}->- <EllipsisIcon class="size-4" />- <span class="sr-only">More pages</span>-</span>diff --git a/frontend/src/lib/components/ui/pagination/pagination-item.svelte b/frontend/src/lib/components/ui/pagination/pagination-item.sveltedeleted file mode 100644index fd7ffc3a..00000000--- a/frontend/src/lib/components/ui/pagination/pagination-item.svelte+++ /dev/null@@ -1,14 +0,0 @@-<script lang="ts">- import type { HTMLLiAttributes } from "svelte/elements";- import type { WithElementRef } from "$lib/utils.js";-- let {- ref = $bindable(null),- children,- ...restProps- }: WithElementRef<HTMLLiAttributes> = $props();-</script>--<li bind:this={ref} data-slot="pagination-item" {...restProps}>- {@render children?.()}-</li>diff --git a/frontend/src/lib/components/ui/pagination/pagination-link.svelte b/frontend/src/lib/components/ui/pagination/pagination-link.sveltedeleted file mode 100644index 58b1a5ca..00000000--- a/frontend/src/lib/components/ui/pagination/pagination-link.svelte+++ /dev/null@@ -1,39 +0,0 @@-<script lang="ts">- import { Pagination as PaginationPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";- import { type Props, buttonVariants } from "$lib/components/ui/button/index.js";-- let {- ref = $bindable(null),- class: className,- size = "icon",- isActive,- page,- children,- ...restProps- }: PaginationPrimitive.PageProps &- Props & {- isActive: boolean;- } = $props();-</script>--{#snippet Fallback()}- {page.value}-{/snippet}--<PaginationPrimitive.Page- bind:ref- {page}- aria-current={isActive ? "page" : undefined}- data-slot="pagination-link"- data-active={isActive}- class={cn(- buttonVariants({- variant: isActive ? "outline" : "ghost",- size,- }),- className- )}- children={children || Fallback}- {...restProps}-/>diff --git a/frontend/src/lib/components/ui/pagination/pagination-next-button.svelte b/frontend/src/lib/components/ui/pagination/pagination-next-button.sveltedeleted file mode 100644index cc40ee30..00000000--- a/frontend/src/lib/components/ui/pagination/pagination-next-button.svelte+++ /dev/null@@ -1,33 +0,0 @@-<script lang="ts">- import { Pagination as PaginationPrimitive } from "bits-ui";- import ChevronRightIcon from "@lucide/svelte/icons/chevron-right";- import { buttonVariants } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";-- let {- ref = $bindable(null),- class: className,- children,- ...restProps- }: PaginationPrimitive.NextButtonProps = $props();-</script>--{#snippet Fallback()}- <span>Next</span>- <ChevronRightIcon class="size-4" />-{/snippet}--<PaginationPrimitive.NextButton- bind:ref- aria-label="Go to next page"- class={cn(- buttonVariants({- size: "default",- variant: "ghost",- class: "gap-1 px-2.5 sm:pe-2.5",- }),- className- )}- children={children || Fallback}- {...restProps}-/>diff --git a/frontend/src/lib/components/ui/pagination/pagination-next.svelte b/frontend/src/lib/components/ui/pagination/pagination-next.sveltedeleted file mode 100644index 5bb37f7b..00000000--- a/frontend/src/lib/components/ui/pagination/pagination-next.svelte+++ /dev/null@@ -1,29 +0,0 @@-<script lang="ts">- import { Pagination as PaginationPrimitive } from "bits-ui";- import ChevronRightIcon from "@lucide/svelte/icons/chevron-right";- import { buttonVariants } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";-- let {- ref = $bindable(null),- class: className,- ...restProps- }: PaginationPrimitive.NextButtonProps = $props();-</script>--<PaginationPrimitive.NextButton- bind:ref- aria-label="Go to next page"- class={cn(- buttonVariants({- size: "default",- variant: "ghost",- class: "gap-1 px-2.5 sm:pe-2.5",- }),- className- )}- {...restProps}->- <span class="hidden sm:block">Next</span>- <ChevronRightIcon /></PaginationPrimitive.NextButton->diff --git a/frontend/src/lib/components/ui/pagination/pagination-prev-button.svelte b/frontend/src/lib/components/ui/pagination/pagination-prev-button.sveltedeleted file mode 100644index 28caad5e..00000000--- a/frontend/src/lib/components/ui/pagination/pagination-prev-button.svelte+++ /dev/null@@ -1,33 +0,0 @@-<script lang="ts">- import { Pagination as PaginationPrimitive } from "bits-ui";- import ChevronLeftIcon from "@lucide/svelte/icons/chevron-left";- import { buttonVariants } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";-- let {- ref = $bindable(null),- class: className,- children,- ...restProps- }: PaginationPrimitive.PrevButtonProps = $props();-</script>--{#snippet Fallback()}- <ChevronLeftIcon class="size-4" />- <span>Previous</span>-{/snippet}--<PaginationPrimitive.PrevButton- bind:ref- aria-label="Go to previous page"- class={cn(- buttonVariants({- size: "default",- variant: "ghost",- class: "gap-1 px-2.5 sm:ps-2.5",- }),- className- )}- children={children || Fallback}- {...restProps}-/>diff --git a/frontend/src/lib/components/ui/pagination/pagination-previous.svelte b/frontend/src/lib/components/ui/pagination/pagination-previous.sveltedeleted file mode 100644index cf7c460f..00000000--- a/frontend/src/lib/components/ui/pagination/pagination-previous.svelte+++ /dev/null@@ -1,29 +0,0 @@-<script lang="ts">- import { Pagination as PaginationPrimitive } from "bits-ui";- import ChevronLeftIcon from "@lucide/svelte/icons/chevron-left";- import { buttonVariants } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";-- let {- ref = $bindable(null),- class: className,- ...restProps- }: PaginationPrimitive.PrevButtonProps = $props();-</script>--<PaginationPrimitive.PrevButton- bind:ref- aria-label="Go to previous page"- class={cn(- buttonVariants({- size: "default",- variant: "ghost",- class: "gap-1 px-2.5 sm:ps-2.5",- }),- className- )}- {...restProps}->- <ChevronLeftIcon />- <span class="hidden sm:block">Previous</span></PaginationPrimitive.PrevButton->diff --git a/frontend/src/lib/components/ui/pagination/pagination.svelte b/frontend/src/lib/components/ui/pagination/pagination.sveltedeleted file mode 100644index dac89a07..00000000--- a/frontend/src/lib/components/ui/pagination/pagination.svelte+++ /dev/null@@ -1,28 +0,0 @@-<script lang="ts">- import { Pagination as PaginationPrimitive } from 'bits-ui';-- import { cn } from '$lib/utils.js';-- let {- ref = $bindable(null),- class: className,- count = 0,- perPage = 10,- page = $bindable(1),- siblingCount = 1,- ...restProps- }: PaginationPrimitive.RootProps = $props();-</script>--<PaginationPrimitive.Root- bind:ref- bind:page- role="navigation"- aria-label="pagination"- data-slot="pagination"- class={cn('mx-auto flex w-full justify-center', className)}- {count}- {perPage}- {siblingCount}- {...restProps}-/>diff --git a/frontend/src/lib/components/ui/popover/index.ts b/frontend/src/lib/components/ui/popover/index.tsindex b79d12e5..c5937fb3 100644--- a/frontend/src/lib/components/ui/popover/index.ts+++ b/frontend/src/lib/components/ui/popover/index.ts@@ -1,8 +1,8 @@-import Root from "./popover.svelte";-import Close from "./popover-close.svelte";-import Content from "./popover-content.svelte";-import Trigger from "./popover-trigger.svelte";-import Portal from "./popover-portal.svelte";+import Root from './popover.svelte';+import Close from './popover-close.svelte';+import Content from './popover-content.svelte';+import Trigger from './popover-trigger.svelte';+import Portal from './popover-portal.svelte';export {Root,@@ -15,5 +15,5 @@ export {Content as PopoverContent,Trigger as PopoverTrigger,Close as PopoverClose,- Portal as PopoverPortal,+ Portal as PopoverPortal};diff --git a/frontend/src/lib/components/ui/popover/popover-close.svelte b/frontend/src/lib/components/ui/popover/popover-close.svelteindex c360925a..dc4dec4b 100644--- a/frontend/src/lib/components/ui/popover/popover-close.svelte+++ b/frontend/src/lib/components/ui/popover/popover-close.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Popover as PopoverPrimitive } from "bits-ui";+ import { Popover as PopoverPrimitive } from 'bits-ui';let { ref = $bindable(null), ...restProps }: PopoverPrimitive.CloseProps = $props();</script>diff --git a/frontend/src/lib/components/ui/popover/popover-content.svelte b/frontend/src/lib/components/ui/popover/popover-content.svelteindex 3d79f3c6..af649938 100644--- a/frontend/src/lib/components/ui/popover/popover-content.svelte+++ b/frontend/src/lib/components/ui/popover/popover-content.svelte@@ -1,14 +1,14 @@<script lang="ts">- import { Popover as PopoverPrimitive } from "bits-ui";- import PopoverPortal from "./popover-portal.svelte";- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";- import type { ComponentProps } from "svelte";+ import { Popover as PopoverPrimitive } from 'bits-ui';+ import PopoverPortal from './popover-portal.svelte';+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';+ import type { ComponentProps } from 'svelte';let {ref = $bindable(null),class: className,sideOffset = 4,- align = "center",+ align = 'center',portalProps,...restProps}: PopoverPrimitive.ContentProps & {@@ -23,7 +23,7 @@{sideOffset}{align}class={cn(- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--bits-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",+ 'z-50 w-72 origin-(--bits-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/popover/popover-portal.svelte b/frontend/src/lib/components/ui/popover/popover-portal.svelteindex dd8265fe..25efb877 100644--- a/frontend/src/lib/components/ui/popover/popover-portal.svelte+++ b/frontend/src/lib/components/ui/popover/popover-portal.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Popover as PopoverPrimitive } from "bits-ui";+ import { Popover as PopoverPrimitive } from 'bits-ui';let { ...restProps }: PopoverPrimitive.PortalProps = $props();</script>diff --git a/frontend/src/lib/components/ui/popover/popover-trigger.svelte b/frontend/src/lib/components/ui/popover/popover-trigger.svelteindex 586323c7..f21b1b33 100644--- a/frontend/src/lib/components/ui/popover/popover-trigger.svelte+++ b/frontend/src/lib/components/ui/popover/popover-trigger.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn } from "$lib/utils.js";- import { Popover as PopoverPrimitive } from "bits-ui";+ import { cn } from '$lib/utils.js';+ import { Popover as PopoverPrimitive } from 'bits-ui';let {ref = $bindable(null),@@ -12,6 +12,6 @@<PopoverPrimitive.Triggerbind:refdata-slot="popover-trigger"- class={cn("", className)}+ class={cn('', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/popover/popover.svelte b/frontend/src/lib/components/ui/popover/popover.svelteindex 6b1aa5f9..f39b867a 100644--- a/frontend/src/lib/components/ui/popover/popover.svelte+++ b/frontend/src/lib/components/ui/popover/popover.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Popover as PopoverPrimitive } from "bits-ui";+ import { Popover as PopoverPrimitive } from 'bits-ui';let { open = $bindable(false), ...restProps }: PopoverPrimitive.RootProps = $props();</script>diff --git a/frontend/src/lib/components/ui/root-filter/root-filter.svelte b/frontend/src/lib/components/ui/root-filter/root-filter.svelteindex 745598de..3a6193a6 100644--- a/frontend/src/lib/components/ui/root-filter/root-filter.svelte+++ b/frontend/src/lib/components/ui/root-filter/root-filter.svelte@@ -1,5 +1,5 @@<script lang="ts">- import * as Select from '$lib/components/ui/select';+ import ToolbarSelect from '$lib/components/traceway/toolbar-select.svelte';type Props = {value?: string;@@ -12,19 +12,6 @@{ value: 'root', label: 'Root' },{ value: 'non_root', label: 'Non-root' }];-- const label = $derived(options.find((o) => o.value === value)?.label ?? 'All');</script>-<Select.Root type="single" bind:value>- <Select.Trigger class="h-9 w-[120px] rounded-none border-r-0 shadow-none">- {label}- </Select.Trigger>- <Select.Content>- {#each options as option}- <Select.Item value={option.value} label={option.label}>- {option.label}- </Select.Item>- {/each}- </Select.Content>-</Select.Root>+<ToolbarSelect bind:value {options} class="w-[120px]" />diff --git a/frontend/src/lib/components/ui/scroll-area/index.ts b/frontend/src/lib/components/ui/scroll-area/index.tsindex e86a25b2..d5468067 100644--- a/frontend/src/lib/components/ui/scroll-area/index.ts+++ b/frontend/src/lib/components/ui/scroll-area/index.ts@@ -1,10 +1,10 @@-import Scrollbar from "./scroll-area-scrollbar.svelte";-import Root from "./scroll-area.svelte";+import Scrollbar from './scroll-area-scrollbar.svelte';+import Root from './scroll-area.svelte';export {Root,Scrollbar,//,Root as ScrollArea,- Scrollbar as ScrollAreaScrollbar,+ Scrollbar as ScrollAreaScrollbar};diff --git a/frontend/src/lib/components/ui/scroll-area/scroll-area-scrollbar.svelte b/frontend/src/lib/components/ui/scroll-area/scroll-area-scrollbar.svelteindex 8f5d9609..cfc54cff 100644--- a/frontend/src/lib/components/ui/scroll-area/scroll-area-scrollbar.svelte+++ b/frontend/src/lib/components/ui/scroll-area/scroll-area-scrollbar.svelte@@ -1,11 +1,11 @@<script lang="ts">- import { ScrollArea as ScrollAreaPrimitive } from "bits-ui";- import { cn, type WithoutChild } from "$lib/utils.js";+ import { ScrollArea as ScrollAreaPrimitive } from 'bits-ui';+ import { cn, type WithoutChild } from '$lib/utils.js';let {ref = $bindable(null),class: className,- orientation = "vertical",+ orientation = 'vertical',children,...restProps}: WithoutChild<ScrollAreaPrimitive.ScrollbarProps> = $props();@@ -16,9 +16,9 @@data-slot="scroll-area-scrollbar"{orientation}class={cn(- "flex touch-none p-px transition-colors select-none",- orientation === "vertical" && "h-full w-2.5 border-s border-s-transparent",- orientation === "horizontal" && "h-2.5 flex-col border-t border-t-transparent",+ 'flex touch-none p-px transition-colors select-none',+ orientation === 'vertical' && 'h-full w-2.5 border-s border-s-transparent',+ orientation === 'horizontal' && 'h-2.5 flex-col border-t border-t-transparent',className)}{...restProps}@@ -26,6 +26,6 @@{@render children?.()}<ScrollAreaPrimitive.Thumbdata-slot="scroll-area-thumb"- class="bg-border relative flex-1 rounded-full"+ class="relative flex-1 rounded-full bg-border"/></ScrollAreaPrimitive.Scrollbar>diff --git a/frontend/src/lib/components/ui/scroll-area/scroll-area.svelte b/frontend/src/lib/components/ui/scroll-area/scroll-area.svelteindex 86ee0326..cd1ddae9 100644--- a/frontend/src/lib/components/ui/scroll-area/scroll-area.svelte+++ b/frontend/src/lib/components/ui/scroll-area/scroll-area.svelte@@ -1,19 +1,19 @@<script lang="ts">- import { ScrollArea as ScrollAreaPrimitive } from "bits-ui";- import { Scrollbar } from "./index.js";- import { cn, type WithoutChild } from "$lib/utils.js";+ import { ScrollArea as ScrollAreaPrimitive } from 'bits-ui';+ import { Scrollbar } from './index.js';+ import { cn, type WithoutChild } from '$lib/utils.js';let {ref = $bindable(null),viewportRef = $bindable(null),class: className,- orientation = "vertical",- scrollbarXClasses = "",- scrollbarYClasses = "",+ orientation = 'vertical',+ scrollbarXClasses = '',+ scrollbarYClasses = '',children,...restProps}: WithoutChild<ScrollAreaPrimitive.RootProps> & {- orientation?: "vertical" | "horizontal" | "both" | undefined;+ orientation?: 'vertical' | 'horizontal' | 'both' | undefined;scrollbarXClasses?: string | undefined;scrollbarYClasses?: string | undefined;viewportRef?: HTMLElement | null;@@ -23,20 +23,20 @@<ScrollAreaPrimitive.Rootbind:refdata-slot="scroll-area"- class={cn("relative", className)}+ class={cn('relative', className)}{...restProps}><ScrollAreaPrimitive.Viewportbind:ref={viewportRef}data-slot="scroll-area-viewport"- class="ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] focus-visible:ring-4 focus-visible:outline-1"+ class="size-full rounded-[inherit] ring-ring/10 outline-ring/50 transition-[color,box-shadow] focus-visible:ring-4 focus-visible:outline-1 dark:ring-ring/20 dark:outline-ring/40">{@render children?.()}</ScrollAreaPrimitive.Viewport>- {#if orientation === "vertical" || orientation === "both"}+ {#if orientation === 'vertical' || orientation === 'both'}<Scrollbar orientation="vertical" class={scrollbarYClasses} />{/if}- {#if orientation === "horizontal" || orientation === "both"}+ {#if orientation === 'horizontal' || orientation === 'both'}<Scrollbar orientation="horizontal" class={scrollbarXClasses} />{/if}<ScrollAreaPrimitive.Corner />diff --git a/frontend/src/lib/components/ui/search-bar/search-bar.svelte b/frontend/src/lib/components/ui/search-bar/search-bar.svelteindex 1c52e363..96fa449f 100644--- a/frontend/src/lib/components/ui/search-bar/search-bar.svelte+++ b/frontend/src/lib/components/ui/search-bar/search-bar.svelte@@ -17,11 +17,9 @@onSearch: () => void;disabled?: boolean;/**- * Optional slot rendered between the type select and the Go button.- * Consumers can drop additional selects in here (e.g. a severity filter)- * so they visually belong to the same compound control. Your content is- * responsible for matching the 9-unit height and using rounded-none +- * border-r-0 to keep the joined look.+ * Optional slot for additional filters (extra selects, toggles). They render+ * as standalone controls after the joined search unit and wrap onto their+ * own row on narrow screens instead of squeezing the input.*/children?: Snippet;};@@ -39,34 +37,36 @@const typeLabel = $derived(typeOptions.find((o) => o.value === typeValue)?.label ?? '');</script>-<div class="flex">- <Input- {placeholder}- class="h-9 w-[250px] rounded-r-none border-r-0 shadow-none focus-visible:border-r focus-visible:border-ring focus-visible:ring-0 lg:w-[320px]"- bind:value- onkeydown={(e) => {- if (e.key === 'Enter') onSearch();- }}- />+<div class="flex flex-wrap items-center gap-2">+ <div class="flex min-w-fit flex-1 sm:min-w-0 sm:flex-initial">+ <Input+ {placeholder}+ class="h-9 w-full min-w-[140px] rounded-r-none border-r-0 shadow-none focus-visible:border-r focus-visible:border-ring focus-visible:ring-0 sm:w-[250px] lg:w-[320px]"+ bind:value+ onkeydown={(e) => {+ if (e.key === 'Enter') onSearch();+ }}+ />- {#if typeOptions.length > 0}- <Select.Root type="single" bind:value={typeValue}>- <Select.Trigger class="h-9 w-[110px] rounded-none border-r-0 shadow-none">- {typeLabel}- </Select.Trigger>- <Select.Content>- {#each typeOptions as option}- <Select.Item value={option.value} label={option.label}>- {option.label}- </Select.Item>- {/each}- </Select.Content>- </Select.Root>- {/if}+ {#if typeOptions.length > 0}+ <Select.Root type="single" bind:value={typeValue}>+ <Select.Trigger class="h-9 w-[110px] shrink-0 rounded-none border-r-0 shadow-none">+ {typeLabel}+ </Select.Trigger>+ <Select.Content>+ {#each typeOptions as option (option.value)}+ <Select.Item value={option.value} label={option.label}>+ {option.label}+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ {/if}- {@render children?.()}+ <Button variant="outline" class="h-9 rounded-l-none shadow-none" onclick={onSearch} {disabled}>+ Go+ </Button>+ </div>- <Button variant="outline" class="h-9 rounded-l-none shadow-none" onclick={onSearch} {disabled}>- Go- </Button>+ {@render children?.()}</div>diff --git a/frontend/src/lib/components/ui/select/index.ts b/frontend/src/lib/components/ui/select/index.tsindex 4dec358b..305c47ad 100644--- a/frontend/src/lib/components/ui/select/index.ts+++ b/frontend/src/lib/components/ui/select/index.ts@@ -1,14 +1,14 @@-import Root from "./select.svelte";-import Group from "./select-group.svelte";-import Label from "./select-label.svelte";-import Item from "./select-item.svelte";-import Content from "./select-content.svelte";-import Trigger from "./select-trigger.svelte";-import Separator from "./select-separator.svelte";-import ScrollDownButton from "./select-scroll-down-button.svelte";-import ScrollUpButton from "./select-scroll-up-button.svelte";-import GroupHeading from "./select-group-heading.svelte";-import Portal from "./select-portal.svelte";+import Root from './select.svelte';+import Group from './select-group.svelte';+import Label from './select-label.svelte';+import Item from './select-item.svelte';+import Content from './select-content.svelte';+import Trigger from './select-trigger.svelte';+import Separator from './select-separator.svelte';+import ScrollDownButton from './select-scroll-down-button.svelte';+import ScrollUpButton from './select-scroll-up-button.svelte';+import GroupHeading from './select-group-heading.svelte';+import Portal from './select-portal.svelte';export {Root,@@ -33,5 +33,5 @@ export {ScrollDownButton as SelectScrollDownButton,ScrollUpButton as SelectScrollUpButton,GroupHeading as SelectGroupHeading,- Portal as SelectPortal,+ Portal as SelectPortal};diff --git a/frontend/src/lib/components/ui/select/select-content.svelte b/frontend/src/lib/components/ui/select/select-content.svelteindex 1540da82..a4297355 100644--- a/frontend/src/lib/components/ui/select/select-content.svelte+++ b/frontend/src/lib/components/ui/select/select-content.svelte@@ -1,11 +1,11 @@<script lang="ts">- import { Select as SelectPrimitive } from "bits-ui";- import SelectPortal from "./select-portal.svelte";- import SelectScrollUpButton from "./select-scroll-up-button.svelte";- import SelectScrollDownButton from "./select-scroll-down-button.svelte";- import { cn, type WithoutChild } from "$lib/utils.js";- import type { ComponentProps } from "svelte";- import type { WithoutChildrenOrChild } from "$lib/utils.js";+ import { Select as SelectPrimitive } from 'bits-ui';+ import SelectPortal from './select-portal.svelte';+ import SelectScrollUpButton from './select-scroll-up-button.svelte';+ import SelectScrollDownButton from './select-scroll-down-button.svelte';+ import { cn, type WithoutChild } from '$lib/utils.js';+ import type { ComponentProps } from 'svelte';+ import type { WithoutChildrenOrChild } from '$lib/utils.js';let {ref = $bindable(null),@@ -27,7 +27,7 @@{preventScroll}data-slot="select-content"class={cn(- "bg-popover text-popover-foreground border-hair-2 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--bits-select-content-available-height) min-w-[8rem] origin-(--bits-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-[0_20px_60px_-20px_rgba(0,0,0,0.7),0_0_0_1px_rgba(255,255,255,0.03)] data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",+ 'border-hair-2 relative z-50 max-h-(--bits-select-content-available-height) min-w-[8rem] origin-(--bits-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-[0_20px_60px_-20px_rgba(0,0,0,0.7),0_0_0_1px_rgba(255,255,255,0.03)] data-[side=bottom]:translate-y-1 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:-translate-x-1 data-[side=left]:slide-in-from-end-2 data-[side=right]:translate-x-1 data-[side=right]:slide-in-from-start-2 data-[side=top]:-translate-y-1 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',className)}{...restProps}@@ -35,7 +35,7 @@<SelectScrollUpButton /><SelectPrimitive.Viewportclass={cn(- "h-(--bits-select-anchor-height) w-full min-w-(--bits-select-anchor-width) scroll-my-1 p-1"+ 'h-(--bits-select-anchor-height) w-full min-w-(--bits-select-anchor-width) scroll-my-1 p-1')}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/select/select-group-heading.svelte b/frontend/src/lib/components/ui/select/select-group-heading.svelteindex db6abefc..8f6d07d6 100644--- a/frontend/src/lib/components/ui/select/select-group-heading.svelte+++ b/frontend/src/lib/components/ui/select/select-group-heading.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { Select as SelectPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";- import type { ComponentProps } from "svelte";+ import { Select as SelectPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';+ import type { ComponentProps } from 'svelte';let {ref = $bindable(null),@@ -15,7 +15,7 @@bind:refdata-slot="select-group-heading"class={cn(- "text-muted-foreground px-2 py-1.5 text-[11px] font-medium uppercase tracking-wider",+ 'px-2 py-1.5 text-[11px] font-medium tracking-wider text-muted-foreground uppercase',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/select/select-group.svelte b/frontend/src/lib/components/ui/select/select-group.svelteindex 6ccea992..092ef0da 100644--- a/frontend/src/lib/components/ui/select/select-group.svelte+++ b/frontend/src/lib/components/ui/select/select-group.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Select as SelectPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Select as SelectPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@bind:refdata-slot="select-group"class={cn(- "[&:not(:first-child)]:mt-1 [&:not(:first-child)]:border-t [&:not(:first-child)]:border-hair [&:not(:first-child)]:pt-1",+ '[&:not(:first-child)]:border-hair [&:not(:first-child)]:mt-1 [&:not(:first-child)]:border-t [&:not(:first-child)]:pt-1',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/select/select-item.svelte b/frontend/src/lib/components/ui/select/select-item.svelteindex e2de4b09..1677252d 100644--- a/frontend/src/lib/components/ui/select/select-item.svelte+++ b/frontend/src/lib/components/ui/select/select-item.svelte@@ -1,7 +1,7 @@<script lang="ts">- import CheckIcon from "@lucide/svelte/icons/check";- import { Select as SelectPrimitive } from "bits-ui";- import { cn, type WithoutChild } from "$lib/utils.js";+ import CheckIcon from '@lucide/svelte/icons/check';+ import { Select as SelectPrimitive } from 'bits-ui';+ import { cn, type WithoutChild } from '$lib/utils.js';let {ref = $bindable(null),@@ -18,7 +18,7 @@{value}data-slot="select-item"class={cn(- "data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-pointer items-center gap-2 rounded-sm py-1.5 ps-2 pe-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",+ "relative flex w-full cursor-pointer items-center gap-2 rounded-sm py-1.5 ps-2 pe-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",className)}{...restProps}diff --git a/frontend/src/lib/components/ui/select/select-label.svelte b/frontend/src/lib/components/ui/select/select-label.svelteindex 46960259..8849c2a3 100644--- a/frontend/src/lib/components/ui/select/select-label.svelte+++ b/frontend/src/lib/components/ui/select/select-label.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<divbind:this={ref}data-slot="select-label"- class={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}+ class={cn('px-2 py-1.5 text-xs text-muted-foreground', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/select/select-portal.svelte b/frontend/src/lib/components/ui/select/select-portal.svelteindex 424bcddc..59c4b78e 100644--- a/frontend/src/lib/components/ui/select/select-portal.svelte+++ b/frontend/src/lib/components/ui/select/select-portal.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Select as SelectPrimitive } from "bits-ui";+ import { Select as SelectPrimitive } from 'bits-ui';let { ...restProps }: SelectPrimitive.PortalProps = $props();</script>diff --git a/frontend/src/lib/components/ui/select/select-scroll-down-button.svelte b/frontend/src/lib/components/ui/select/select-scroll-down-button.svelteindex 36292058..35021483 100644--- a/frontend/src/lib/components/ui/select/select-scroll-down-button.svelte+++ b/frontend/src/lib/components/ui/select/select-scroll-down-button.svelte@@ -1,7 +1,7 @@<script lang="ts">- import ChevronDownIcon from "@lucide/svelte/icons/chevron-down";- import { Select as SelectPrimitive } from "bits-ui";- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import ChevronDownIcon from '@lucide/svelte/icons/chevron-down';+ import { Select as SelectPrimitive } from 'bits-ui';+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<SelectPrimitive.ScrollDownButtonbind:refdata-slot="select-scroll-down-button"- class={cn("flex cursor-default items-center justify-center py-1", className)}+ class={cn('flex cursor-default items-center justify-center py-1', className)}{...restProps}><ChevronDownIcon class="size-4" />diff --git a/frontend/src/lib/components/ui/select/select-scroll-up-button.svelte b/frontend/src/lib/components/ui/select/select-scroll-up-button.svelteindex 1aa2300c..3d35e04c 100644--- a/frontend/src/lib/components/ui/select/select-scroll-up-button.svelte+++ b/frontend/src/lib/components/ui/select/select-scroll-up-button.svelte@@ -1,7 +1,7 @@<script lang="ts">- import ChevronUpIcon from "@lucide/svelte/icons/chevron-up";- import { Select as SelectPrimitive } from "bits-ui";- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import ChevronUpIcon from '@lucide/svelte/icons/chevron-up';+ import { Select as SelectPrimitive } from 'bits-ui';+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<SelectPrimitive.ScrollUpButtonbind:refdata-slot="select-scroll-up-button"- class={cn("flex cursor-default items-center justify-center py-1", className)}+ class={cn('flex cursor-default items-center justify-center py-1', className)}{...restProps}><ChevronUpIcon class="size-4" />diff --git a/frontend/src/lib/components/ui/select/select-separator.svelte b/frontend/src/lib/components/ui/select/select-separator.svelteindex 0eac3ebc..bfd1eb78 100644--- a/frontend/src/lib/components/ui/select/select-separator.svelte+++ b/frontend/src/lib/components/ui/select/select-separator.svelte@@ -1,7 +1,7 @@<script lang="ts">- import type { Separator as SeparatorPrimitive } from "bits-ui";- import { Separator } from "$lib/components/ui/separator/index.js";- import { cn } from "$lib/utils.js";+ import type { Separator as SeparatorPrimitive } from 'bits-ui';+ import { Separator } from '$lib/components/ui/separator/index.js';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,6 +13,6 @@<Separatorbind:refdata-slot="select-separator"- class={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}+ class={cn('pointer-events-none -mx-1 my-1 h-px bg-border', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/select/select-trigger.svelte b/frontend/src/lib/components/ui/select/select-trigger.svelteindex bbc8e040..f22aecea 100644--- a/frontend/src/lib/components/ui/select/select-trigger.svelte+++ b/frontend/src/lib/components/ui/select/select-trigger.svelte@@ -1,16 +1,16 @@<script lang="ts">- import { Select as SelectPrimitive } from "bits-ui";- import ChevronDownIcon from "@lucide/svelte/icons/chevron-down";- import { cn, type WithoutChild } from "$lib/utils.js";+ import { Select as SelectPrimitive } from 'bits-ui';+ import ChevronDownIcon from '@lucide/svelte/icons/chevron-down';+ import { cn, type WithoutChild } from '$lib/utils.js';let {ref = $bindable(null),class: className,children,- size = "default",+ size = 'default',...restProps}: WithoutChild<SelectPrimitive.TriggerProps> & {- size?: "sm" | "default";+ size?: 'sm' | 'default';} = $props();</script>@@ -19,7 +19,7 @@data-slot="select-trigger"data-size={size}class={cn(- "border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:ring-ring/40 aria-invalid:ring-destructive/40 aria-invalid:border-destructive bg-transparent dark:bg-input/30 dark:hover:bg-input/50 flex w-fit cursor-pointer items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none select-none focus-visible:ring-[2px] data-[state=open]:border-ring/60 disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "flex w-fit cursor-pointer items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none select-none focus-visible:ring-[2px] focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/40 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 data-[state=open]:border-ring/60 dark:bg-input/30 dark:hover:bg-input/50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",className)}{...restProps}diff --git a/frontend/src/lib/components/ui/select/select.svelte b/frontend/src/lib/components/ui/select/select.svelteindex 05eb6634..b9bf9ba5 100644--- a/frontend/src/lib/components/ui/select/select.svelte+++ b/frontend/src/lib/components/ui/select/select.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Select as SelectPrimitive } from "bits-ui";+ import { Select as SelectPrimitive } from 'bits-ui';let {open = $bindable(false),diff --git a/frontend/src/lib/components/ui/separator/index.ts b/frontend/src/lib/components/ui/separator/index.tsindex 82442d2c..768efac9 100644--- a/frontend/src/lib/components/ui/separator/index.ts+++ b/frontend/src/lib/components/ui/separator/index.ts@@ -1,7 +1,7 @@-import Root from "./separator.svelte";+import Root from './separator.svelte';export {Root,//- Root as Separator,+ Root as Separator};diff --git a/frontend/src/lib/components/ui/separator/separator.svelte b/frontend/src/lib/components/ui/separator/separator.svelteindex e11a6f5b..38286123 100644--- a/frontend/src/lib/components/ui/separator/separator.svelte+++ b/frontend/src/lib/components/ui/separator/separator.svelte@@ -1,11 +1,11 @@<script lang="ts">- import { Separator as SeparatorPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Separator as SeparatorPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),class: className,- "data-slot": dataSlot = "separator",+ 'data-slot': dataSlot = 'separator',...restProps}: SeparatorPrimitive.RootProps = $props();</script>@@ -14,7 +14,7 @@bind:refdata-slot={dataSlot}class={cn(- "bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",+ 'shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/severity-badge/index.ts b/frontend/src/lib/components/ui/severity-badge/index.tsindex 7fb28a39..111e9f5f 100644--- a/frontend/src/lib/components/ui/severity-badge/index.ts+++ b/frontend/src/lib/components/ui/severity-badge/index.ts@@ -1 +1,5 @@-export { default as SeverityBadge, severityFromNumber, type SeverityLevel } from './severity-badge.svelte';+export {+ default as SeverityBadge,+ severityFromNumber,+ type SeverityLevel+} from './severity-badge.svelte';diff --git a/frontend/src/lib/components/ui/severity-badge/severity-badge.svelte b/frontend/src/lib/components/ui/severity-badge/severity-badge.svelteindex 59c1b772..2c6e5a10 100644--- a/frontend/src/lib/components/ui/severity-badge/severity-badge.svelte+++ b/frontend/src/lib/components/ui/severity-badge/severity-badge.svelte@@ -84,7 +84,7 @@{#if config()}<span- class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium uppercase tracking-wide {config()+ class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium tracking-wide uppercase {config()?.bg} {config()?.text}">{config()?.label}diff --git a/frontend/src/lib/components/ui/sheet/index.ts b/frontend/src/lib/components/ui/sheet/index.tsindex 28d7da1c..781bc48f 100644--- a/frontend/src/lib/components/ui/sheet/index.ts+++ b/frontend/src/lib/components/ui/sheet/index.ts@@ -1,13 +1,13 @@-import Root from "./sheet.svelte";-import Portal from "./sheet-portal.svelte";-import Trigger from "./sheet-trigger.svelte";-import Close from "./sheet-close.svelte";-import Overlay from "./sheet-overlay.svelte";-import Content from "./sheet-content.svelte";-import Header from "./sheet-header.svelte";-import Footer from "./sheet-footer.svelte";-import Title from "./sheet-title.svelte";-import Description from "./sheet-description.svelte";+import Root from './sheet.svelte';+import Portal from './sheet-portal.svelte';+import Trigger from './sheet-trigger.svelte';+import Close from './sheet-close.svelte';+import Overlay from './sheet-overlay.svelte';+import Content from './sheet-content.svelte';+import Header from './sheet-header.svelte';+import Footer from './sheet-footer.svelte';+import Title from './sheet-title.svelte';+import Description from './sheet-description.svelte';export {Root,@@ -30,5 +30,5 @@ export {Header as SheetHeader,Footer as SheetFooter,Title as SheetTitle,- Description as SheetDescription,+ Description as SheetDescription};diff --git a/frontend/src/lib/components/ui/sheet/sheet-close.svelte b/frontend/src/lib/components/ui/sheet/sheet-close.svelteindex ae382c12..b0180c0c 100644--- a/frontend/src/lib/components/ui/sheet/sheet-close.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet-close.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Dialog as SheetPrimitive } from "bits-ui";+ import { Dialog as SheetPrimitive } from 'bits-ui';let { ref = $bindable(null), ...restProps }: SheetPrimitive.CloseProps = $props();</script>diff --git a/frontend/src/lib/components/ui/sheet/sheet-content.svelte b/frontend/src/lib/components/ui/sheet/sheet-content.svelteindex d99909ac..687ad0b0 100644--- a/frontend/src/lib/components/ui/sheet/sheet-content.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet-content.svelte@@ -1,36 +1,38 @@<script lang="ts" module>- import { tv, type VariantProps } from "tailwind-variants";+ import { tv, type VariantProps } from 'tailwind-variants';export const sheetVariants = tv({- base: "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",+ base: 'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500',variants: {side: {- top: "data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",- bottom: "data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",- left: "data-[state=closed]:slide-out-to-start data-[state=open]:slide-in-from-start inset-y-0 start-0 h-dvh w-3/4 border-e sm:max-w-sm",- right: "data-[state=closed]:slide-out-to-end data-[state=open]:slide-in-from-end inset-y-0 end-0 h-dvh w-3/4 border-s sm:max-w-sm",- },+ top: 'data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b',+ bottom:+ 'data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t',+ left: 'data-[state=closed]:slide-out-to-start data-[state=open]:slide-in-from-start inset-y-0 start-0 h-dvh w-3/4 border-e sm:max-w-sm',+ right:+ 'data-[state=closed]:slide-out-to-end data-[state=open]:slide-in-from-end inset-y-0 end-0 h-dvh w-3/4 border-s sm:max-w-sm'+ }},defaultVariants: {- side: "right",- },+ side: 'right'+ }});- export type Side = VariantProps<typeof sheetVariants>["side"];+ export type Side = VariantProps<typeof sheetVariants>['side'];</script><script lang="ts">- import { Dialog as SheetPrimitive } from "bits-ui";- import XIcon from "@lucide/svelte/icons/x";- import type { Snippet } from "svelte";- import SheetPortal from "./sheet-portal.svelte";- import SheetOverlay from "./sheet-overlay.svelte";- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";- import type { ComponentProps } from "svelte";+ import { Dialog as SheetPrimitive } from 'bits-ui';+ import XIcon from '@lucide/svelte/icons/x';+ import type { Snippet } from 'svelte';+ import SheetPortal from './sheet-portal.svelte';+ import SheetOverlay from './sheet-overlay.svelte';+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';+ import type { ComponentProps } from 'svelte';let {ref = $bindable(null),class: className,- side = "right",+ side = 'right',portalProps,children,...restProps@@ -51,7 +53,7 @@>{@render children?.()}<SheetPrimitive.Close- class="ring-offset-background focus-visible:ring-ring hover:bg-muted absolute end-2 top-2 rounded-md p-2 opacity-70 transition-opacity hover:opacity-100 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:pointer-events-none"+ class="absolute end-2 top-2 rounded-md p-2 opacity-70 ring-offset-background transition-opacity hover:bg-muted hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:pointer-events-none"><XIcon class="size-4" /><span class="sr-only">Close</span>diff --git a/frontend/src/lib/components/ui/sheet/sheet-description.svelte b/frontend/src/lib/components/ui/sheet/sheet-description.svelteindex 333b17a7..b6aae8e3 100644--- a/frontend/src/lib/components/ui/sheet/sheet-description.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet-description.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Dialog as SheetPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Dialog as SheetPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,6 +12,6 @@<SheetPrimitive.Descriptionbind:refdata-slot="sheet-description"- class={cn("text-muted-foreground text-sm", className)}+ class={cn('text-sm text-muted-foreground', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/sheet/sheet-footer.svelte b/frontend/src/lib/components/ui/sheet/sheet-footer.svelteindex dd9ed84b..aea83f78 100644--- a/frontend/src/lib/components/ui/sheet/sheet-footer.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet-footer.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<divbind:this={ref}data-slot="sheet-footer"- class={cn("mt-auto flex flex-col gap-2 p-4", className)}+ class={cn('mt-auto flex flex-col gap-2 p-4', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sheet/sheet-header.svelte b/frontend/src/lib/components/ui/sheet/sheet-header.svelteindex 757a6a56..00cd281d 100644--- a/frontend/src/lib/components/ui/sheet/sheet-header.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet-header.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<divbind:this={ref}data-slot="sheet-header"- class={cn("flex flex-col gap-1.5 p-4", className)}+ class={cn('flex flex-col gap-1.5 p-4', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sheet/sheet-overlay.svelte b/frontend/src/lib/components/ui/sheet/sheet-overlay.svelteindex 345e197b..cd637be3 100644--- a/frontend/src/lib/components/ui/sheet/sheet-overlay.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet-overlay.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Dialog as SheetPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Dialog as SheetPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@bind:refdata-slot="sheet-overlay"class={cn(- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",+ 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/sheet/sheet-portal.svelte b/frontend/src/lib/components/ui/sheet/sheet-portal.svelteindex f3085a3c..91e51786 100644--- a/frontend/src/lib/components/ui/sheet/sheet-portal.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet-portal.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Dialog as SheetPrimitive } from "bits-ui";+ import { Dialog as SheetPrimitive } from 'bits-ui';let { ...restProps }: SheetPrimitive.PortalProps = $props();</script>diff --git a/frontend/src/lib/components/ui/sheet/sheet-title.svelte b/frontend/src/lib/components/ui/sheet/sheet-title.svelteindex 9fda327e..75398971 100644--- a/frontend/src/lib/components/ui/sheet/sheet-title.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet-title.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Dialog as SheetPrimitive } from "bits-ui";- import { cn } from "$lib/utils.js";+ import { Dialog as SheetPrimitive } from 'bits-ui';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),@@ -12,6 +12,6 @@<SheetPrimitive.Titlebind:refdata-slot="sheet-title"- class={cn("text-foreground font-semibold", className)}+ class={cn('font-semibold text-foreground', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/sheet/sheet-trigger.svelte b/frontend/src/lib/components/ui/sheet/sheet-trigger.svelteindex e266975f..d95719a6 100644--- a/frontend/src/lib/components/ui/sheet/sheet-trigger.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet-trigger.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Dialog as SheetPrimitive } from "bits-ui";+ import { Dialog as SheetPrimitive } from 'bits-ui';let { ref = $bindable(null), ...restProps }: SheetPrimitive.TriggerProps = $props();</script>diff --git a/frontend/src/lib/components/ui/sheet/sheet.svelte b/frontend/src/lib/components/ui/sheet/sheet.svelteindex 5bf97839..d65b76b0 100644--- a/frontend/src/lib/components/ui/sheet/sheet.svelte+++ b/frontend/src/lib/components/ui/sheet/sheet.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Dialog as SheetPrimitive } from "bits-ui";+ import { Dialog as SheetPrimitive } from 'bits-ui';let { open = $bindable(false), ...restProps }: SheetPrimitive.RootProps = $props();</script>diff --git a/frontend/src/lib/components/ui/sidebar/constants.ts b/frontend/src/lib/components/ui/sidebar/constants.tsindex c5ce32ea..2b631dc1 100644--- a/frontend/src/lib/components/ui/sidebar/constants.ts+++ b/frontend/src/lib/components/ui/sidebar/constants.ts@@ -1,6 +1,6 @@-export const SIDEBAR_COOKIE_NAME = "sidebar:state";+export const SIDEBAR_COOKIE_NAME = 'sidebar:state';export const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;-export const SIDEBAR_WIDTH = "16rem";-export const SIDEBAR_WIDTH_MOBILE = "18rem";-export const SIDEBAR_WIDTH_ICON = "3.5rem";-export const SIDEBAR_KEYBOARD_SHORTCUT = "b";+export const SIDEBAR_WIDTH = '16rem';+export const SIDEBAR_WIDTH_MOBILE = '18rem';+export const SIDEBAR_WIDTH_ICON = '3.5rem';+export const SIDEBAR_KEYBOARD_SHORTCUT = 'b';diff --git a/frontend/src/lib/components/ui/sidebar/context.svelte.ts b/frontend/src/lib/components/ui/sidebar/context.svelte.tsindex 15248ada..6fa2aa31 100644--- a/frontend/src/lib/components/ui/sidebar/context.svelte.ts+++ b/frontend/src/lib/components/ui/sidebar/context.svelte.ts@@ -1,6 +1,6 @@-import { IsMobile } from "$lib/hooks/is-mobile.svelte.js";-import { getContext, setContext } from "svelte";-import { SIDEBAR_KEYBOARD_SHORTCUT } from "./constants.js";+import { IsMobile } from '$lib/hooks/is-mobile.svelte.js';+import { getContext, setContext } from 'svelte';+import { SIDEBAR_KEYBOARD_SHORTCUT } from './constants.js';type Getter<T> = () => T;@@ -24,9 +24,9 @@ class SidebarState {readonly props: SidebarStateProps;open = $derived.by(() => this.props.open());openMobile = $state(false);- setOpen: SidebarStateProps["setOpen"];+ setOpen: SidebarStateProps['setOpen'];#isMobile: IsMobile;- state = $derived.by(() => (this.open ? "expanded" : "collapsed"));+ state = $derived.by(() => (this.open ? 'expanded' : 'collapsed'));constructor(props: SidebarStateProps) {this.setOpen = props.setOpen;@@ -53,13 +53,11 @@ class SidebarState {};toggle = () => {- return this.#isMobile.current- ? (this.openMobile = !this.openMobile)- : this.setOpen(!this.open);+ return this.#isMobile.current ? (this.openMobile = !this.openMobile) : this.setOpen(!this.open);};}-const SYMBOL_KEY = "scn-sidebar";+const SYMBOL_KEY = 'scn-sidebar';/*** Instantiates a new `SidebarState` instance and sets it in the context.diff --git a/frontend/src/lib/components/ui/sidebar/index.ts b/frontend/src/lib/components/ui/sidebar/index.tsindex 318a3417..280e6407 100644--- a/frontend/src/lib/components/ui/sidebar/index.ts+++ b/frontend/src/lib/components/ui/sidebar/index.ts@@ -1,27 +1,27 @@-import { useSidebar } from "./context.svelte.js";-import Content from "./sidebar-content.svelte";-import Footer from "./sidebar-footer.svelte";-import GroupAction from "./sidebar-group-action.svelte";-import GroupContent from "./sidebar-group-content.svelte";-import GroupLabel from "./sidebar-group-label.svelte";-import Group from "./sidebar-group.svelte";-import Header from "./sidebar-header.svelte";-import Input from "./sidebar-input.svelte";-import Inset from "./sidebar-inset.svelte";-import MenuAction from "./sidebar-menu-action.svelte";-import MenuBadge from "./sidebar-menu-badge.svelte";-import MenuButton from "./sidebar-menu-button.svelte";-import MenuItem from "./sidebar-menu-item.svelte";-import MenuSkeleton from "./sidebar-menu-skeleton.svelte";-import MenuSubButton from "./sidebar-menu-sub-button.svelte";-import MenuSubItem from "./sidebar-menu-sub-item.svelte";-import MenuSub from "./sidebar-menu-sub.svelte";-import Menu from "./sidebar-menu.svelte";-import Provider from "./sidebar-provider.svelte";-import Rail from "./sidebar-rail.svelte";-import Separator from "./sidebar-separator.svelte";-import Trigger from "./sidebar-trigger.svelte";-import Root from "./sidebar.svelte";+import { useSidebar } from './context.svelte.js';+import Content from './sidebar-content.svelte';+import Footer from './sidebar-footer.svelte';+import GroupAction from './sidebar-group-action.svelte';+import GroupContent from './sidebar-group-content.svelte';+import GroupLabel from './sidebar-group-label.svelte';+import Group from './sidebar-group.svelte';+import Header from './sidebar-header.svelte';+import Input from './sidebar-input.svelte';+import Inset from './sidebar-inset.svelte';+import MenuAction from './sidebar-menu-action.svelte';+import MenuBadge from './sidebar-menu-badge.svelte';+import MenuButton from './sidebar-menu-button.svelte';+import MenuItem from './sidebar-menu-item.svelte';+import MenuSkeleton from './sidebar-menu-skeleton.svelte';+import MenuSubButton from './sidebar-menu-sub-button.svelte';+import MenuSubItem from './sidebar-menu-sub-item.svelte';+import MenuSub from './sidebar-menu-sub.svelte';+import Menu from './sidebar-menu.svelte';+import Provider from './sidebar-provider.svelte';+import Rail from './sidebar-rail.svelte';+import Separator from './sidebar-separator.svelte';+import Trigger from './sidebar-trigger.svelte';+import Root from './sidebar.svelte';export {Content,@@ -71,5 +71,5 @@ export {Separator as SidebarSeparator,Trigger as SidebarTrigger,Trigger,- useSidebar,+ useSidebar};diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-content.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-content.svelteindex 862dc6e8..22f4bcdb 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-content.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-content.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -14,10 +14,7 @@bind:this={ref}data-slot="sidebar-content"data-sidebar="content"- class={cn(- "flex min-h-0 flex-1 flex-col gap-2 overflow-x-hidden overflow-y-auto",- className- )}+ class={cn('flex min-h-0 flex-1 flex-col gap-2 overflow-x-hidden overflow-y-auto', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-footer.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-footer.svelteindex 6259cb95..24d67f66 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-footer.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-footer.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="sidebar-footer"data-sidebar="footer"- class={cn("flex flex-col gap-2 p-2", className)}+ class={cn('flex flex-col gap-2 p-2', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-group-action.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-group-action.svelteindex a76dfe17..a283bed3 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-group-action.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-group-action.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { Snippet } from "svelte";- import type { HTMLButtonAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { Snippet } from 'svelte';+ import type { HTMLButtonAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -15,15 +15,15 @@const mergedProps = $derived({class: cn(- "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute end-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",+ 'text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute end-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',// Increases the hit area of the button on mobile.- "after:absolute after:-inset-2 md:after:hidden",- "group-data-[collapsible=icon]:hidden",+ 'after:absolute after:-inset-2 md:after:hidden',+ 'group-data-[collapsible=icon]:hidden',className),- "data-slot": "sidebar-group-action",- "data-sidebar": "group-action",- ...restProps,+ 'data-slot': 'sidebar-group-action',+ 'data-sidebar': 'group-action',+ ...restProps});</script>diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-group-content.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-group-content.svelteindex 415255f1..fafaceef 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-group-content.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-group-content.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="sidebar-group-content"data-sidebar="group-content"- class={cn("w-full text-sm", className)}+ class={cn('w-full text-sm', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-group-label.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-group-label.svelteindex b2e72b67..c1c166ff 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-group-label.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-group-label.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { Snippet } from "svelte";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { Snippet } from 'svelte';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -15,13 +15,13 @@const mergedProps = $derived({class: cn(- "text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",- "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",+ 'text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',+ 'group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0',className),- "data-slot": "sidebar-group-label",- "data-sidebar": "group-label",- ...restProps,+ 'data-slot': 'sidebar-group-label',+ 'data-sidebar': 'group-label',+ ...restProps});</script>diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-group.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-group.svelteindex ec18a697..897445de 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-group.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-group.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="sidebar-group"data-sidebar="group"- class={cn("relative flex w-full min-w-0 flex-col p-2", className)}+ class={cn('relative flex w-full min-w-0 flex-col p-2', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-header.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-header.svelteindex a1b2db15..a5464746 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-header.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-header.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="sidebar-header"data-sidebar="header"- class={cn("flex flex-col gap-2 p-2", className)}+ class={cn('flex flex-col gap-2 p-2', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-input.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-input.svelteindex 19b36660..1a3610ba 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-input.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-input.svelte@@ -1,11 +1,11 @@<script lang="ts">- import type { ComponentProps } from "svelte";- import { Input } from "$lib/components/ui/input/index.js";- import { cn } from "$lib/utils.js";+ import type { ComponentProps } from 'svelte';+ import { Input } from '$lib/components/ui/input/index.js';+ import { cn } from '$lib/utils.js';let {ref = $bindable(null),- value = $bindable(""),+ value = $bindable(''),class: className,...restProps}: ComponentProps<typeof Input> = $props();@@ -16,6 +16,6 @@bind:valuedata-slot="sidebar-input"data-sidebar="input"- class={cn("bg-background h-8 w-full shadow-none", className)}+ class={cn('h-8 w-full bg-background shadow-none', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-inset.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-inset.svelteindex b7ac7b3a..a9dd813a 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-inset.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-inset.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -14,8 +14,8 @@bind:this={ref}data-slot="sidebar-inset"class={cn(- "bg-background relative flex min-w-0 w-full flex-1 flex-col",- "md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ms-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ms-2",+ 'relative flex w-full min-w-0 flex-1 flex-col bg-background',+ 'md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ms-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ms-2',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu-action.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu-action.svelteindex d3fe2954..6ec7cf44 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu-action.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu-action.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { Snippet } from "svelte";- import type { HTMLButtonAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { Snippet } from 'svelte';+ import type { HTMLButtonAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -17,20 +17,20 @@const mergedProps = $derived({class: cn(- "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute end-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",+ 'text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute end-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',// Increases the hit area of the button on mobile.- "after:absolute after:-inset-2 md:after:hidden",- "peer-data-[size=sm]/menu-button:top-1",- "peer-data-[size=default]/menu-button:top-1.5",- "peer-data-[size=lg]/menu-button:top-2.5",- "group-data-[collapsible=icon]:hidden",+ 'after:absolute after:-inset-2 md:after:hidden',+ 'peer-data-[size=sm]/menu-button:top-1',+ 'peer-data-[size=default]/menu-button:top-1.5',+ 'peer-data-[size=lg]/menu-button:top-2.5',+ 'group-data-[collapsible=icon]:hidden',showOnHover &&- "peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",+ 'peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0',className),- "data-slot": "sidebar-menu-action",- "data-sidebar": "menu-action",- ...restProps,+ 'data-slot': 'sidebar-menu-action',+ 'data-sidebar': 'menu-action',+ ...restProps});</script>diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu-badge.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu-badge.svelteindex e8ecdb47..876e023a 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu-badge.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu-badge.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -15,12 +15,12 @@data-slot="sidebar-menu-badge"data-sidebar="menu-badge"class={cn(- "text-sidebar-foreground pointer-events-none absolute end-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",- "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",- "peer-data-[size=sm]/menu-button:top-1",- "peer-data-[size=default]/menu-button:top-1.5",- "peer-data-[size=lg]/menu-button:top-2.5",- "group-data-[collapsible=icon]:hidden",+ 'pointer-events-none absolute end-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none',+ 'peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground',+ 'peer-data-[size=sm]/menu-button:top-1',+ 'peer-data-[size=default]/menu-button:top-1.5',+ 'peer-data-[size=lg]/menu-button:top-2.5',+ 'group-data-[collapsible=icon]:hidden',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu-button.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu-button.svelteindex d00f7ef6..ac313107 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu-button.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu-button.svelte@@ -1,47 +1,46 @@<script lang="ts" module>- import { tv, type VariantProps } from "tailwind-variants";+ import { tv, type VariantProps } from 'tailwind-variants';export const sidebarMenuButtonVariants = tv({- base: "peer/menu-button ring-sidebar-ring data-[active=false]:hover:bg-foreground/5 dark:data-[active=false]:hover:bg-white/8 active:bg-sidebar-accent data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground data-[state=open]:data-[active=false]:hover:bg-foreground/5 dark:data-[state=open]:data-[active=false]:hover:bg-white/8 flex w-full items-center gap-2.5 overflow-hidden rounded-md p-2 text-start text-[15px] font-medium outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pe-8 group-data-[collapsible=icon]:size-9! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:whitespace-nowrap [&>svg]:size-5 [&>svg]:shrink-0",+ base: 'peer/menu-button ring-sidebar-ring data-[active=false]:hover:bg-foreground/5 dark:data-[active=false]:hover:bg-white/8 active:bg-sidebar-accent data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground data-[state=open]:data-[active=false]:hover:bg-foreground/5 dark:data-[state=open]:data-[active=false]:hover:bg-white/8 flex w-full items-center gap-2.5 overflow-hidden rounded-md p-2 text-start text-[15px] font-medium outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pe-8 group-data-[collapsible=icon]:size-9! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:whitespace-nowrap [&>svg]:size-5 [&>svg]:shrink-0',variants: {variant: {- default: "data-[active=false]:hover:bg-foreground/5 dark:data-[active=false]:hover:bg-white/8",+ default:+ 'data-[active=false]:hover:bg-foreground/5 dark:data-[active=false]:hover:bg-white/8',outline:- "bg-background data-[active=false]:hover:bg-foreground/5 dark:data-[active=false]:hover:bg-white/8 shadow-[0_0_0_1px_var(--sidebar-border)] hover:shadow-[0_0_0_1px_var(--sidebar-border)]",+ 'bg-background data-[active=false]:hover:bg-foreground/5 dark:data-[active=false]:hover:bg-white/8 shadow-[0_0_0_1px_var(--sidebar-border)] hover:shadow-[0_0_0_1px_var(--sidebar-border)]'},size: {- default: "h-9",- sm: "h-7 text-xs",- lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",- },+ default: 'h-9',+ sm: 'h-7 text-xs',+ lg: 'h-12 text-sm group-data-[collapsible=icon]:p-0!'+ }},defaultVariants: {- variant: "default",- size: "default",- },+ variant: 'default',+ size: 'default'+ }});- export type SidebarMenuButtonVariant = VariantProps<- typeof sidebarMenuButtonVariants- >["variant"];- export type SidebarMenuButtonSize = VariantProps<typeof sidebarMenuButtonVariants>["size"];+ export type SidebarMenuButtonVariant = VariantProps<typeof sidebarMenuButtonVariants>['variant'];+ export type SidebarMenuButtonSize = VariantProps<typeof sidebarMenuButtonVariants>['size'];</script><script lang="ts">- import * as Tooltip from "$lib/components/ui/tooltip/index.js";- import { cn, type WithElementRef, type WithoutChildrenOrChild } from "$lib/utils.js";- import { mergeProps } from "bits-ui";- import type { ComponentProps, Snippet } from "svelte";- import type { HTMLAttributes } from "svelte/elements";- import { useSidebar } from "./context.svelte.js";+ import * as Tooltip from '$lib/components/ui/tooltip/index.js';+ import { cn, type WithElementRef, type WithoutChildrenOrChild } from '$lib/utils.js';+ import { mergeProps } from 'bits-ui';+ import type { ComponentProps, Snippet } from 'svelte';+ import type { HTMLAttributes } from 'svelte/elements';+ import { useSidebar } from './context.svelte.js';let {ref = $bindable(null),class: className,children,child,- variant = "default",- size = "default",+ variant = 'default',+ size = 'default',isActive = false,tooltipContent,tooltipContentProps,@@ -59,11 +58,11 @@const buttonProps = $derived({class: cn(sidebarMenuButtonVariants({ variant, size }), className),- "data-slot": "sidebar-menu-button",- "data-sidebar": "menu-button",- "data-size": size,- "data-active": isActive,- ...restProps,+ 'data-slot': 'sidebar-menu-button',+ 'data-sidebar': 'menu-button',+ 'data-size': size,+ 'data-active': isActive,+ ...restProps});</script>@@ -90,10 +89,10 @@<Tooltip.Contentside="right"align="center"- hidden={sidebar.state !== "collapsed" || sidebar.isMobile}+ hidden={sidebar.state !== 'collapsed' || sidebar.isMobile}{...tooltipContentProps}>- {#if typeof tooltipContent === "string"}+ {#if typeof tooltipContent === 'string'}{tooltipContent}{:else if tooltipContent}{@render tooltipContent()}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu-item.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu-item.svelteindex 4db44532..acd28606 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu-item.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu-item.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="sidebar-menu-item"data-sidebar="menu-item"- class={cn("group/menu-item relative", className)}+ class={cn('group/menu-item relative', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu-skeleton.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu-skeleton.svelteindex 68604e24..49a18f12 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu-skeleton.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu-skeleton.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import { Skeleton } from "$lib/components/ui/skeleton/index.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import { Skeleton } from '$lib/components/ui/skeleton/index.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -21,7 +21,7 @@bind:this={ref}data-slot="sidebar-menu-skeleton"data-sidebar="menu-skeleton"- class={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}+ class={cn('flex h-8 items-center gap-2 rounded-md px-2', className)}{...restProps}>{#if showIcon}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub-button.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub-button.svelteindex c8cd4ffe..ba5849b0 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub-button.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub-button.svelte@@ -1,36 +1,36 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { Snippet } from "svelte";- import type { HTMLAnchorAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { Snippet } from 'svelte';+ import type { HTMLAnchorAttributes } from 'svelte/elements';let {ref = $bindable(null),children,child,class: className,- size = "md",+ size = 'md',isActive = false,...restProps}: WithElementRef<HTMLAnchorAttributes> & {child?: Snippet<[{ props: Record<string, unknown> }]>;- size?: "sm" | "md";+ size?: 'sm' | 'md';isActive?: boolean;} = $props();const mergedProps = $derived({class: cn(- "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",- "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",- size === "sm" && "text-xs",- size === "md" && "text-sm",- "group-data-[collapsible=icon]:hidden",+ 'text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0',+ 'data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground',+ size === 'sm' && 'text-xs',+ size === 'md' && 'text-sm',+ 'group-data-[collapsible=icon]:hidden',className),- "data-slot": "sidebar-menu-sub-button",- "data-sidebar": "menu-sub-button",- "data-size": size,- "data-active": isActive,- ...restProps,+ 'data-slot': 'sidebar-menu-sub-button',+ 'data-sidebar': 'menu-sub-button',+ 'data-size': size,+ 'data-active': isActive,+ ...restProps});</script>diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub-item.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub-item.svelteindex 681d0f1d..4274f0e0 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub-item.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub-item.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="sidebar-menu-sub-item"data-sidebar="menu-sub-item"- class={cn("group/menu-sub-item relative", className)}+ class={cn('group/menu-sub-item relative', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub.svelteindex 76bd1d91..cfcaa794 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu-sub.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -15,8 +15,8 @@data-slot="sidebar-menu-sub"data-sidebar="menu-sub"class={cn(- "border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-s px-2.5 py-0.5",- "group-data-[collapsible=icon]:hidden",+ 'mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-s border-sidebar-border px-2.5 py-0.5',+ 'group-data-[collapsible=icon]:hidden',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu.svelteindex 946cccef..094f0f07 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="sidebar-menu"data-sidebar="menu"- class={cn("flex w-full min-w-0 flex-col gap-1", className)}+ class={cn('flex w-full min-w-0 flex-col gap-1', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-provider.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-provider.svelteindex b467587d..a6c9a5d2 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-provider.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-provider.svelte@@ -1,14 +1,14 @@<script lang="ts">- import * as Tooltip from "$lib/components/ui/tooltip/index.js";- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import * as Tooltip from '$lib/components/ui/tooltip/index.js';+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';import {SIDEBAR_COOKIE_MAX_AGE,SIDEBAR_COOKIE_NAME,SIDEBAR_WIDTH,- SIDEBAR_WIDTH_ICON,- } from "./constants.js";- import { setSidebar } from "./context.svelte.js";+ SIDEBAR_WIDTH_ICON+ } from './constants.js';+ import { setSidebar } from './context.svelte.js';let {ref = $bindable(null),@@ -31,7 +31,7 @@// This sets the cookie to keep the sidebar state.document.cookie = `${SIDEBAR_COOKIE_NAME}=${open}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;- },+ }});</script>@@ -42,7 +42,7 @@data-slot="sidebar-wrapper"style="--sidebar-width: {SIDEBAR_WIDTH}; --sidebar-width-icon: {SIDEBAR_WIDTH_ICON}; {style}"class={cn(- "group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-dvh w-full",+ 'group/sidebar-wrapper flex min-h-dvh w-full has-data-[variant=inset]:bg-sidebar',className)}bind:this={ref}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-rail.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-rail.svelteindex 704d54f7..33cf713d 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-rail.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-rail.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";- import { useSidebar } from "./context.svelte.js";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';+ import { useSidebar } from './context.svelte.js';let {ref = $bindable(null),@@ -22,12 +22,12 @@onclick={sidebar.toggle}title="Toggle Sidebar"class={cn(- "hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-end-4 group-data-[side=right]:start-0 after:absolute after:inset-y-0 after:start-[calc(1/2*100%-1px)] after:w-[2px] sm:flex",- "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",- "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",- "hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:start-full",- "[[data-side=left][data-collapsible=offcanvas]_&]:-end-2",- "[[data-side=right][data-collapsible=offcanvas]_&]:-start-2",+ 'absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-end-4 group-data-[side=right]:start-0 after:absolute after:inset-y-0 after:start-[calc(1/2*100%-1px)] after:w-[2px] hover:after:bg-sidebar-border sm:flex',+ 'in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize',+ '[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize',+ 'group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:start-full hover:group-data-[collapsible=offcanvas]:bg-sidebar',+ '[[data-side=left][data-collapsible=offcanvas]_&]:-end-2',+ '[[data-side=right][data-collapsible=offcanvas]_&]:-start-2',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-separator.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-separator.svelteindex 5a7dedac..45c1ebca 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-separator.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-separator.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { Separator } from "$lib/components/ui/separator/index.js";- import { cn } from "$lib/utils.js";- import type { ComponentProps } from "svelte";+ import { Separator } from '$lib/components/ui/separator/index.js';+ import { cn } from '$lib/utils.js';+ import type { ComponentProps } from 'svelte';let {ref = $bindable(null),@@ -14,6 +14,6 @@bind:refdata-slot="sidebar-separator"data-sidebar="separator"- class={cn("bg-sidebar-border", className)}+ class={cn('bg-sidebar-border', className)}{...restProps}/>diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-trigger.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-trigger.svelteindex 18251827..285e6c4f 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-trigger.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-trigger.svelte@@ -1,9 +1,9 @@<script lang="ts">- import { Button } from "$lib/components/ui/button/index.js";- import { cn } from "$lib/utils.js";- import PanelLeftIcon from "@lucide/svelte/icons/panel-left";- import type { ComponentProps } from "svelte";- import { useSidebar } from "./context.svelte.js";+ import { Button } from '$lib/components/ui/button/index.js';+ import { cn } from '$lib/utils.js';+ import PanelLeftIcon from '@lucide/svelte/icons/panel-left';+ import type { ComponentProps } from 'svelte';+ import { useSidebar } from './context.svelte.js';let {ref = $bindable(null),@@ -22,7 +22,7 @@data-slot="sidebar-trigger"variant="ghost"size="icon"- class={cn("size-7", className)}+ class={cn('size-7', className)}type="button"onclick={(e) => {onclick?.(e);diff --git a/frontend/src/lib/components/ui/skeleton/index.ts b/frontend/src/lib/components/ui/skeleton/index.tsindex 186db219..3120ce12 100644--- a/frontend/src/lib/components/ui/skeleton/index.ts+++ b/frontend/src/lib/components/ui/skeleton/index.ts@@ -1,7 +1,7 @@-import Root from "./skeleton.svelte";+import Root from './skeleton.svelte';export {Root,//- Root as Skeleton,+ Root as Skeleton};diff --git a/frontend/src/lib/components/ui/skeleton/skeleton.svelte b/frontend/src/lib/components/ui/skeleton/skeleton.svelteindex c7e3d26c..cdd10e00 100644--- a/frontend/src/lib/components/ui/skeleton/skeleton.svelte+++ b/frontend/src/lib/components/ui/skeleton/skeleton.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef, type WithoutChildren } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef, type WithoutChildren } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -12,6 +12,6 @@<divbind:this={ref}data-slot="skeleton"- class={cn("bg-accent animate-pulse rounded-md", className)}+ class={cn('animate-pulse rounded-md bg-accent', className)}{...restProps}></div>diff --git a/frontend/src/lib/components/ui/switch/index.ts b/frontend/src/lib/components/ui/switch/index.tsindex f5533db7..129f8f5c 100644--- a/frontend/src/lib/components/ui/switch/index.ts+++ b/frontend/src/lib/components/ui/switch/index.ts@@ -1,7 +1,7 @@-import Root from "./switch.svelte";+import Root from './switch.svelte';export {Root,//- Root as Switch,+ Root as Switch};diff --git a/frontend/src/lib/components/ui/switch/switch.svelte b/frontend/src/lib/components/ui/switch/switch.svelteindex 1bc165bf..acb8a15f 100644--- a/frontend/src/lib/components/ui/switch/switch.svelte+++ b/frontend/src/lib/components/ui/switch/switch.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Switch as SwitchPrimitive } from "bits-ui";- import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import { Switch as SwitchPrimitive } from 'bits-ui';+ import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';let {ref = $bindable(null),@@ -15,7 +15,7 @@bind:checkeddata-slot="switch"class={cn(- "peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 cursor-pointer items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",+ 'peer inline-flex h-[1.15rem] w-8 shrink-0 cursor-pointer items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80',className)}{...restProps}@@ -23,7 +23,7 @@<SwitchPrimitive.Thumbdata-slot="switch-thumb"class={cn(- "bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"+ 'pointer-events-none block size-4 rounded-full bg-background ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0 dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground')}/></SwitchPrimitive.Root>diff --git a/frontend/src/lib/components/ui/table-empty-state/index.ts b/frontend/src/lib/components/ui/table-empty-state/index.tsindex 841ba553..5650bbce 100644--- a/frontend/src/lib/components/ui/table-empty-state/index.ts+++ b/frontend/src/lib/components/ui/table-empty-state/index.ts@@ -1,3 +1,3 @@-import TableEmptyState from "./table-empty-state.svelte";+import TableEmptyState from './table-empty-state.svelte';export { TableEmptyState };diff --git a/frontend/src/lib/components/ui/table-empty-state/table-empty-state.svelte b/frontend/src/lib/components/ui/table-empty-state/table-empty-state.svelteindex 44302e35..03dd5a09 100644--- a/frontend/src/lib/components/ui/table-empty-state/table-empty-state.svelte+++ b/frontend/src/lib/components/ui/table-empty-state/table-empty-state.svelte@@ -1,10 +1,10 @@<script lang="ts">- import { cn } from "$lib/utils.js";- import * as Table from "$lib/components/ui/table/index.js";+ import { cn } from '$lib/utils.js';+ import * as Table from '$lib/components/ui/table/index.js';let {colspan,- message = "No data found.",+ message = 'No data found.',class: className}: {colspan: number;@@ -14,7 +14,13 @@</script><Table.Row>- <Table.Cell {colspan} class={cn("h-45 px-6 text-center text-muted-foreground whitespace-normal break-words", className)}>+ <Table.Cell+ {colspan}+ class={cn(+ 'h-45 px-6 text-center break-words whitespace-normal text-muted-foreground',+ className+ )}+ >{message}</Table.Cell></Table.Row>diff --git a/frontend/src/lib/components/ui/table/index.ts b/frontend/src/lib/components/ui/table/index.tsindex 14695c81..99239aee 100644--- a/frontend/src/lib/components/ui/table/index.ts+++ b/frontend/src/lib/components/ui/table/index.ts@@ -1,11 +1,11 @@-import Root from "./table.svelte";-import Body from "./table-body.svelte";-import Caption from "./table-caption.svelte";-import Cell from "./table-cell.svelte";-import Footer from "./table-footer.svelte";-import Head from "./table-head.svelte";-import Header from "./table-header.svelte";-import Row from "./table-row.svelte";+import Root from './table.svelte';+import Body from './table-body.svelte';+import Caption from './table-caption.svelte';+import Cell from './table-cell.svelte';+import Footer from './table-footer.svelte';+import Head from './table-head.svelte';+import Header from './table-header.svelte';+import Row from './table-row.svelte';export {Root,@@ -24,5 +24,5 @@ export {Footer as TableFooter,Head as TableHead,Header as TableHeader,- Row as TableRow,+ Row as TableRow};diff --git a/frontend/src/lib/components/ui/table/table-body.svelte b/frontend/src/lib/components/ui/table/table-body.svelteindex 29e96875..cf720f47 100644--- a/frontend/src/lib/components/ui/table/table-body.svelte+++ b/frontend/src/lib/components/ui/table/table-body.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<tbodybind:this={ref}data-slot="table-body"- class={cn("[&_tr:last-child]:border-0", className)}+ class={cn('[&_tr:last-child]:border-0', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/table/table-caption.svelte b/frontend/src/lib/components/ui/table/table-caption.svelteindex 4696cff5..7ad3aeed 100644--- a/frontend/src/lib/components/ui/table/table-caption.svelte+++ b/frontend/src/lib/components/ui/table/table-caption.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<captionbind:this={ref}data-slot="table-caption"- class={cn("text-muted-foreground mt-4 text-sm", className)}+ class={cn('mt-4 text-sm text-muted-foreground', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/table/table-cell.svelte b/frontend/src/lib/components/ui/table/table-cell.svelteindex 2c0c26a0..654f2f2f 100644--- a/frontend/src/lib/components/ui/table/table-cell.svelte+++ b/frontend/src/lib/components/ui/table/table-cell.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLTdAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLTdAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="table-cell"class={cn(- "bg-clip-padding p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pe-0",+ 'bg-clip-padding p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pe-0',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/table/table-footer.svelte b/frontend/src/lib/components/ui/table/table-footer.svelteindex b9b14ebf..565b2441 100644--- a/frontend/src/lib/components/ui/table/table-footer.svelte+++ b/frontend/src/lib/components/ui/table/table-footer.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<tfootbind:this={ref}data-slot="table-footer"- class={cn("bg-muted/50 border-t font-medium [&>tr]:last:border-b-0", className)}+ class={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/table/table-head.svelte b/frontend/src/lib/components/ui/table/table-head.svelteindex d6559fa4..b22c3fe9 100644--- a/frontend/src/lib/components/ui/table/table-head.svelte+++ b/frontend/src/lib/components/ui/table/table-head.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLThAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLThAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="table-head"class={cn(- "text-muted-foreground h-10 bg-muted/60 dark:bg-ink-1 bg-clip-padding px-2 text-start align-middle text-[15px] font-medium whitespace-nowrap [&:has([role=checkbox])]:pe-0",+ 'h-10 bg-muted/60 bg-clip-padding px-2 text-start align-middle text-[15px] font-medium whitespace-nowrap text-muted-foreground dark:bg-ink-1 [&:has([role=checkbox])]:pe-0',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/table/table-header.svelte b/frontend/src/lib/components/ui/table/table-header.svelteindex f47d2597..615b5d8e 100644--- a/frontend/src/lib/components/ui/table/table-header.svelte+++ b/frontend/src/lib/components/ui/table/table-header.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -13,7 +13,7 @@<theadbind:this={ref}data-slot="table-header"- class={cn("[&_tr]:border-b", className)}+ class={cn('[&_tr]:border-b', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/table/table-row.svelte b/frontend/src/lib/components/ui/table/table-row.svelteindex f877d6a2..2ae8cda8 100644--- a/frontend/src/lib/components/ui/table/table-row.svelte+++ b/frontend/src/lib/components/ui/table/table-row.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { cn, type WithElementRef } from "$lib/utils.js";- import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from '$lib/utils.js';+ import type { HTMLAttributes } from 'svelte/elements';let {ref = $bindable(null),@@ -14,7 +14,7 @@bind:this={ref}data-slot="table-row"class={cn(- "hover:[&,&>svelte-css-wrapper]:[&>td]:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",+ 'border-b transition-colors data-[state=selected]:bg-muted hover:[&,&>svelte-css-wrapper]:[&>td]:bg-muted/50',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/table/table.svelte b/frontend/src/lib/components/ui/table/table.svelteindex 59cf3c42..b5deca65 100644--- a/frontend/src/lib/components/ui/table/table.svelte+++ b/frontend/src/lib/components/ui/table/table.svelte@@ -1,6 +1,6 @@<script lang="ts">- import type { HTMLTableAttributes } from "svelte/elements";- import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLTableAttributes } from 'svelte/elements';+ import { cn, type WithElementRef } from '$lib/utils.js';let {ref = $bindable(null),@@ -14,7 +14,7 @@<tablebind:this={ref}data-slot="table"- class={cn("w-full caption-bottom bg-white text-sm dark:bg-transparent", className)}+ class={cn('w-full caption-bottom bg-white text-sm dark:bg-transparent', className)}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/tabs/index.ts b/frontend/src/lib/components/ui/tabs/index.tsindex 0084e101..97adf35d 100644--- a/frontend/src/lib/components/ui/tabs/index.ts+++ b/frontend/src/lib/components/ui/tabs/index.ts@@ -1,7 +1,7 @@-import Root from "./tabs.svelte";-import List from "./tabs-list.svelte";-import Trigger from "./tabs-trigger.svelte";-import Content from "./tabs-content.svelte";+import Root from './tabs.svelte';+import List from './tabs-list.svelte';+import Trigger from './tabs-trigger.svelte';+import Content from './tabs-content.svelte';export {Root,@@ -12,5 +12,5 @@ export {Root as Tabs,List as TabsList,Trigger as TabsTrigger,- Content as TabsContent,+ Content as TabsContent};diff --git a/frontend/src/lib/components/ui/tabs/tabs-content.svelte b/frontend/src/lib/components/ui/tabs/tabs-content.svelteindex 16ff156e..2342eb79 100644--- a/frontend/src/lib/components/ui/tabs/tabs-content.svelte+++ b/frontend/src/lib/components/ui/tabs/tabs-content.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Tabs as TabsPrimitive } from "bits-ui";- import { cn, type WithoutChild } from "$lib/utils.js";+ import { Tabs as TabsPrimitive } from 'bits-ui';+ import { cn, type WithoutChild } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<TabsPrimitive.Contentbind:refclass={cn(- "ring-offset-background focus-visible:ring-ring mt-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2",+ 'mt-4 ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/tabs/tabs-trigger.svelte b/frontend/src/lib/components/ui/tabs/tabs-trigger.svelteindex 3c32ccf8..12b360d6 100644--- a/frontend/src/lib/components/ui/tabs/tabs-trigger.svelte+++ b/frontend/src/lib/components/ui/tabs/tabs-trigger.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Tabs as TabsPrimitive } from "bits-ui";- import { cn, type WithoutChild } from "$lib/utils.js";+ import { Tabs as TabsPrimitive } from 'bits-ui';+ import { cn, type WithoutChild } from '$lib/utils.js';let {ref = $bindable(null),@@ -13,7 +13,7 @@<TabsPrimitive.Triggerbind:refclass={cn(- "ring-offset-background focus-visible:ring-ring data-[state=active]:bg-background data-[state=active]:text-foreground inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow",+ 'inline-flex items-center justify-center rounded-md px-3 py-1 text-sm font-medium whitespace-nowrap ring-offset-background transition-all focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/tabs/tabs.svelte b/frontend/src/lib/components/ui/tabs/tabs.svelteindex 1db821c5..5709c62c 100644--- a/frontend/src/lib/components/ui/tabs/tabs.svelte+++ b/frontend/src/lib/components/ui/tabs/tabs.svelte@@ -1,10 +1,7 @@<script lang="ts">- import { Tabs as TabsPrimitive } from "bits-ui";+ import { Tabs as TabsPrimitive } from 'bits-ui';- let {- value = $bindable(),- ...restProps- }: TabsPrimitive.RootProps = $props();+ let { value = $bindable(), ...restProps }: TabsPrimitive.RootProps = $props();</script><TabsPrimitive.Root bind:value {...restProps} />diff --git a/frontend/src/lib/components/ui/time-range-picker/index.ts b/frontend/src/lib/components/ui/time-range-picker/index.tsindex 2fb89ba2..bdcf9ce7 100644--- a/frontend/src/lib/components/ui/time-range-picker/index.ts+++ b/frontend/src/lib/components/ui/time-range-picker/index.ts@@ -1,3 +1,3 @@-import TimeRangePicker from "./time-range-picker.svelte";+import TimeRangePicker from './time-range-picker.svelte';export { TimeRangePicker };diff --git a/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte b/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelteindex 8bbef809..b7d474ca 100644--- a/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte+++ b/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte@@ -1,450 +1,508 @@<script lang="ts">- import { Button } from "$lib/components/ui/button";- import { DateTimePicker } from "$lib/components/ui/datetime-picker";- import * as Popover from "$lib/components/ui/popover";- import { Clock, ChevronDown, ChevronRight, Check } from "@lucide/svelte";- import { CalendarDate, CalendarDateTime, getLocalTimeZone, today } from "@internationalized/date";- import { getNow, luxonToCalendarDateTime } from "$lib/utils/formatters";- import { getTimezone } from "$lib/state/timezone.svelte";-- type TimeRangePreset = {- value: string;- label: string;- minutes: number;- };-- type PresetGroup = {- presets: TimeRangePreset[];- };-- interface Props {- fromDate?: CalendarDate;- toDate?: CalendarDate;- fromTime?: string;- toTime?: string;- preset?: string | null;- timezone?: string;- onApply?: (from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) => void;- }-- let {- fromDate = $bindable(today(getLocalTimeZone()).subtract({ days: 7 })),- toDate = $bindable(today(getLocalTimeZone())),- fromTime = $bindable('00:00'),- toTime = $bindable('23:59'),- preset = $bindable<string | null>('24h'),- timezone,- onApply- }: Props = $props();-- const tz = $derived(timezone ?? getTimezone());-- // Preset groups- const presetGroups: PresetGroup[] = [- {- presets: [- { value: '5m', label: '5 minutes', minutes: 5 },- { value: '30m', label: '30 minutes', minutes: 30 },- { value: '60m', label: '60 minutes', minutes: 60 },- ]- },- {- presets: [- { value: '3h', label: '3 hours', minutes: 180 },- { value: '6h', label: '6 hours', minutes: 360 },- { value: '12h', label: '12 hours', minutes: 720 },- { value: '24h', label: '24 hours', minutes: 1440 },- ]- },- {- presets: [- { value: '3d', label: '3 days', minutes: 4320 },- { value: '7d', label: '7 days', minutes: 10080 },- ]- },- {- presets: [- { value: '1M', label: '1 month', minutes: 43200 },- { value: '3M', label: '3 months', minutes: 129600 },- ]- }- ];-- let isOpen = $state(false);- let showCustom = $state(preset === null);- let selectedPreset = $state<string | null>(preset);-- // Flag to ignore external change detection when we're applying our own changes- let isApplyingInternally = $state(false);-- // Sync internal selectedPreset with external preset prop- $effect(() => {- if (preset !== selectedPreset) {- selectedPreset = preset;- showCustom = preset === null;-- // If preset is set, calculate the time range- if (preset) {- const presetDef = presetGroups.flatMap(g => g.presets).find(p => p.value === preset);- if (presetDef) {- const now = getNow(tz);- const fromDt = now.minus({ minutes: presetDef.minutes });- const fromParts = luxonToCalendarDateTime(fromDt);- const toParts = luxonToCalendarDateTime(now);-- tempFromDateTime = new CalendarDateTime(- fromParts.year,- fromParts.month,- fromParts.day,- fromParts.hour,- fromParts.minute,- fromParts.second- );- tempToDateTime = new CalendarDateTime(- toParts.year,- toParts.month,- toParts.day,- toParts.hour,- toParts.minute,- toParts.second- );- }- }- }- });-- // Track last known bound values to detect external changes- let lastFromDate = $state(fromDate);- let lastToDate = $state(toDate);- let lastFromTime = $state(fromTime);- let lastToTime = $state(toTime);-- // Detect external value changes and switch to custom mode- $effect(() => {- const fromDateChanged = fromDate.year !== lastFromDate.year ||- fromDate.month !== lastFromDate.month ||- fromDate.day !== lastFromDate.day;- const toDateChanged = toDate.year !== lastToDate.year ||- toDate.month !== lastToDate.month ||- toDate.day !== lastToDate.day;- const fromTimeChanged = fromTime !== lastFromTime;- const toTimeChanged = toTime !== lastToTime;-- if (fromDateChanged || toDateChanged || fromTimeChanged || toTimeChanged) {- // Update last known values- lastFromDate = fromDate;- lastToDate = toDate;- lastFromTime = fromTime;- lastToTime = toTime;-- // If picker is not open AND we're not applying internally, this was an external change- if (!isOpen && !isApplyingInternally) {- showCustom = true;- selectedPreset = null;-- // Sync temp values with the new bound values- const [fromHour, fromMinute] = fromTime.split(':').map(Number);- const [toHour, toMinute] = toTime.split(':').map(Number);- tempFromDateTime = new CalendarDateTime(- fromDate.year, fromDate.month, fromDate.day,- Number.isFinite(fromHour) ? fromHour : 0, Number.isFinite(fromMinute) ? fromMinute : 0, 0- );- tempToDateTime = new CalendarDateTime(- toDate.year, toDate.month, toDate.day,- Number.isFinite(toHour) ? toHour : 23, Number.isFinite(toMinute) ? toMinute : 59, 0- );- }- }- });-- // DateTime picker popover states- let fromPickerOpen = $state(false);- let toPickerOpen = $state(false);-- // Temporary CalendarDateTime values for custom selection- // Parse initial time from props instead of using hardcoded values- function parseInitialTime(timeStr: string, fallbackHour: number, fallbackMinute: number): { hour: number; minute: number } {- if (!timeStr) return { hour: fallbackHour, minute: fallbackMinute };- const [hour, minute] = timeStr.split(':').map(Number);- return { hour: hour ?? fallbackHour, minute: minute ?? fallbackMinute };- }-- const initialFromTimeParts = parseInitialTime(fromTime, 0, 0);- const initialToTimeParts = parseInitialTime(toTime, 23, 59);-- let tempFromDateTime = $state<CalendarDateTime>(- new CalendarDateTime(fromDate.year, fromDate.month, fromDate.day, initialFromTimeParts.hour, initialFromTimeParts.minute, 0)- );- let tempToDateTime = $state<CalendarDateTime>(- new CalendarDateTime(toDate.year, toDate.month, toDate.day, initialToTimeParts.hour, initialToTimeParts.minute, 59)- );-- // Track initial values when popover opens to detect changes- let initialFromDateTime = $state<CalendarDateTime | null>(null);- let initialToDateTime = $state<CalendarDateTime | null>(null);-- // Helper to compare two CalendarDateTime values- function dateTimesEqual(a: CalendarDateTime, b: CalendarDateTime): boolean {- return a.year === b.year &&- a.month === b.month &&- a.day === b.day &&- a.hour === b.hour &&- a.minute === b.minute;- }-- // Get display label for trigger button- const displayLabel = $derived(() => {- if (selectedPreset && !showCustom) {- const preset = presetGroups.flatMap(g => g.presets).find(p => p.value === selectedPreset);- return preset ? `Last ${preset.label}` : 'Select time range';- }- // For custom selection, show date and time range (no prefix)- if (tempFromDateTime && tempToDateTime) {- const fromDateStr = formatDateShort(tempFromDateTime);- const fromTimeStr = formatTime12h(tempFromDateTime);- const toDateStr = formatDateShort(tempToDateTime);- const toTimeStr = formatTime12h(tempToDateTime);- return `${fromDateStr} ${fromTimeStr} – ${toDateStr} ${toTimeStr}`;- }- return 'Select time range';- });-- function formatDateShort(dt: CalendarDateTime): string {- return new CalendarDate(dt.year, dt.month, dt.day)- .toDate(getLocalTimeZone())- .toLocaleDateString('en-US', { month: 'short', day: 'numeric' });- }-- // YY/MM/DD format for compact display- function formatDateCompact(dt: CalendarDateTime): string {- const year = String(dt.year).slice(-2);- const month = String(dt.month).padStart(2, '0');- const day = String(dt.day).padStart(2, '0');- return `${year}/${month}/${day}`;- }-- // Format time as 12h with AM/PM- function formatTime12h(dt: CalendarDateTime): string {- const hours = dt.hour;- const minutes = dt.minute;- const period = hours >= 12 ? 'PM' : 'AM';- const hours12 = hours % 12 || 12;- return `${hours12}:${String(minutes).padStart(2, '0')} ${period}`;- }-- function selectPreset(presetDef: TimeRangePreset) {- selectedPreset = presetDef.value;- preset = presetDef.value; // Sync with external prop- showCustom = false;-- // Calculate the date range for this preset using Luxon- const now = getNow(tz);- const fromDt = now.minus({ minutes: presetDef.minutes });- const fromParts = luxonToCalendarDateTime(fromDt);- const toParts = luxonToCalendarDateTime(now);-- tempFromDateTime = new CalendarDateTime(- fromParts.year,- fromParts.month,- fromParts.day,- fromParts.hour,- fromParts.minute,- fromParts.second- );- tempToDateTime = new CalendarDateTime(- toParts.year,- toParts.month,- toParts.day,- toParts.hour,- toParts.minute,- toParts.second- );-- applyAndClose();- }-- function toggleCustom() {- showCustom = !showCustom;- if (showCustom) {- selectedPreset = null;- preset = null; // Sync with external prop- }- }-- function resetToNow() {- const now = getNow(tz);- const nowParts = luxonToCalendarDateTime(now);- tempToDateTime = new CalendarDateTime(- nowParts.year, nowParts.month, nowParts.day,- nowParts.hour, nowParts.minute, nowParts.second- );- }-- function applyAndClose() {- isApplyingInternally = true;-- fromDate = new CalendarDate(tempFromDateTime.year, tempFromDateTime.month, tempFromDateTime.day);- toDate = new CalendarDate(tempToDateTime.year, tempToDateTime.month, tempToDateTime.day);- fromTime = `${String(tempFromDateTime.hour).padStart(2, '0')}:${String(tempFromDateTime.minute).padStart(2, '0')}`;- toTime = `${String(tempToDateTime.hour).padStart(2, '0')}:${String(tempToDateTime.minute).padStart(2, '0')}`;-- const currentPreset = showCustom ? null : selectedPreset;- preset = currentPreset;- onApply?.({ date: fromDate, time: fromTime }, { date: toDate, time: toTime }, currentPreset);-- setTimeout(() => { isApplyingInternally = false; }, 0);-- fromPickerOpen = false;- toPickerOpen = false;- isOpen = false;- }-- function handleOpenChange(open: boolean) {- if (open) {- // Capture initial values when opening- initialFromDateTime = new CalendarDateTime(- tempFromDateTime.year, tempFromDateTime.month, tempFromDateTime.day,- tempFromDateTime.hour, tempFromDateTime.minute, tempFromDateTime.second- );- initialToDateTime = new CalendarDateTime(- tempToDateTime.year, tempToDateTime.month, tempToDateTime.day,- tempToDateTime.hour, tempToDateTime.minute, tempToDateTime.second- );- } else {- // Skip if already applied by applyAndClose (Apply button was clicked)- if (isApplyingInternally) {- isOpen = open;- return;- }-- // Apply if closed by clicking outside and values have changed- const hasChanged = !initialFromDateTime || !initialToDateTime ||- !dateTimesEqual(tempFromDateTime, initialFromDateTime) ||- !dateTimesEqual(tempToDateTime, initialToDateTime);-- if (hasChanged) {- applyAndClose();- return; // applyAndClose handles setting isOpen- }-- // No changes - just close- fromPickerOpen = false;- toPickerOpen = false;- }- isOpen = open;- }-- function handleFromDateTimeChange(dt: CalendarDateTime) {- tempFromDateTime = dt;- }-- function handleToDateTimeChange(dt: CalendarDateTime) {- tempToDateTime = dt;- }+ import { Button } from '$lib/components/ui/button';+ import { DateTimePicker } from '$lib/components/ui/datetime-picker';+ import * as Popover from '$lib/components/ui/popover';+ import { Clock, ChevronDown, ChevronRight, Check } from '@lucide/svelte';+ import { CalendarDate, CalendarDateTime, getLocalTimeZone, today } from '@internationalized/date';+ import { getNow, luxonToCalendarDateTime } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';++ type TimeRangePreset = {+ value: string;+ label: string;+ minutes: number;+ };++ type PresetGroup = {+ presets: TimeRangePreset[];+ };++ interface Props {+ fromDate?: CalendarDate;+ toDate?: CalendarDate;+ fromTime?: string;+ toTime?: string;+ preset?: string | null;+ timezone?: string;+ onApply?: (+ from: { date: CalendarDate; time: string },+ to: { date: CalendarDate; time: string },+ preset: string | null+ ) => void;+ }++ let {+ fromDate = $bindable(today(getLocalTimeZone()).subtract({ days: 7 })),+ toDate = $bindable(today(getLocalTimeZone())),+ fromTime = $bindable('00:00'),+ toTime = $bindable('23:59'),+ preset = $bindable<string | null>('24h'),+ timezone,+ onApply+ }: Props = $props();++ const tz = $derived(timezone ?? getTimezone());++ // Preset groups+ const presetGroups: PresetGroup[] = [+ {+ presets: [+ { value: '5m', label: '5 minutes', minutes: 5 },+ { value: '30m', label: '30 minutes', minutes: 30 },+ { value: '60m', label: '60 minutes', minutes: 60 }+ ]+ },+ {+ presets: [+ { value: '3h', label: '3 hours', minutes: 180 },+ { value: '6h', label: '6 hours', minutes: 360 },+ { value: '12h', label: '12 hours', minutes: 720 },+ { value: '24h', label: '24 hours', minutes: 1440 }+ ]+ },+ {+ presets: [+ { value: '3d', label: '3 days', minutes: 4320 },+ { value: '7d', label: '7 days', minutes: 10080 }+ ]+ },+ {+ presets: [+ { value: '1M', label: '1 month', minutes: 43200 },+ { value: '3M', label: '3 months', minutes: 129600 }+ ]+ }+ ];++ let isOpen = $state(false);+ let showCustom = $state(preset === null);+ let selectedPreset = $state<string | null>(preset);++ // Flag to ignore external change detection when we're applying our own changes+ let isApplyingInternally = $state(false);++ // Sync internal selectedPreset with external preset prop+ $effect(() => {+ if (preset !== selectedPreset) {+ selectedPreset = preset;+ showCustom = preset === null;++ // If preset is set, calculate the time range+ if (preset) {+ const presetDef = presetGroups.flatMap((g) => g.presets).find((p) => p.value === preset);+ if (presetDef) {+ const now = getNow(tz);+ const fromDt = now.minus({ minutes: presetDef.minutes });+ const fromParts = luxonToCalendarDateTime(fromDt);+ const toParts = luxonToCalendarDateTime(now);++ tempFromDateTime = new CalendarDateTime(+ fromParts.year,+ fromParts.month,+ fromParts.day,+ fromParts.hour,+ fromParts.minute,+ fromParts.second+ );+ tempToDateTime = new CalendarDateTime(+ toParts.year,+ toParts.month,+ toParts.day,+ toParts.hour,+ toParts.minute,+ toParts.second+ );+ }+ }+ }+ });++ // Track last known bound values to detect external changes+ let lastFromDate = $state(fromDate);+ let lastToDate = $state(toDate);+ let lastFromTime = $state(fromTime);+ let lastToTime = $state(toTime);++ // Detect external value changes and switch to custom mode+ $effect(() => {+ const fromDateChanged =+ fromDate.year !== lastFromDate.year ||+ fromDate.month !== lastFromDate.month ||+ fromDate.day !== lastFromDate.day;+ const toDateChanged =+ toDate.year !== lastToDate.year ||+ toDate.month !== lastToDate.month ||+ toDate.day !== lastToDate.day;+ const fromTimeChanged = fromTime !== lastFromTime;+ const toTimeChanged = toTime !== lastToTime;++ if (fromDateChanged || toDateChanged || fromTimeChanged || toTimeChanged) {+ // Update last known values+ lastFromDate = fromDate;+ lastToDate = toDate;+ lastFromTime = fromTime;+ lastToTime = toTime;++ // If picker is not open AND we're not applying internally, this was an external change+ if (!isOpen && !isApplyingInternally) {+ showCustom = true;+ selectedPreset = null;++ // Sync temp values with the new bound values+ const [fromHour, fromMinute] = fromTime.split(':').map(Number);+ const [toHour, toMinute] = toTime.split(':').map(Number);+ tempFromDateTime = new CalendarDateTime(+ fromDate.year,+ fromDate.month,+ fromDate.day,+ Number.isFinite(fromHour) ? fromHour : 0,+ Number.isFinite(fromMinute) ? fromMinute : 0,+ 0+ );+ tempToDateTime = new CalendarDateTime(+ toDate.year,+ toDate.month,+ toDate.day,+ Number.isFinite(toHour) ? toHour : 23,+ Number.isFinite(toMinute) ? toMinute : 59,+ 0+ );+ }+ }+ });++ // DateTime picker popover states+ let fromPickerOpen = $state(false);+ let toPickerOpen = $state(false);++ // Temporary CalendarDateTime values for custom selection+ // Parse initial time from props instead of using hardcoded values+ function parseInitialTime(+ timeStr: string,+ fallbackHour: number,+ fallbackMinute: number+ ): { hour: number; minute: number } {+ if (!timeStr) return { hour: fallbackHour, minute: fallbackMinute };+ const [hour, minute] = timeStr.split(':').map(Number);+ return { hour: hour ?? fallbackHour, minute: minute ?? fallbackMinute };+ }++ const initialFromTimeParts = parseInitialTime(fromTime, 0, 0);+ const initialToTimeParts = parseInitialTime(toTime, 23, 59);++ let tempFromDateTime = $state<CalendarDateTime>(+ new CalendarDateTime(+ fromDate.year,+ fromDate.month,+ fromDate.day,+ initialFromTimeParts.hour,+ initialFromTimeParts.minute,+ 0+ )+ );+ let tempToDateTime = $state<CalendarDateTime>(+ new CalendarDateTime(+ toDate.year,+ toDate.month,+ toDate.day,+ initialToTimeParts.hour,+ initialToTimeParts.minute,+ 59+ )+ );++ // Track initial values when popover opens to detect changes+ let initialFromDateTime = $state<CalendarDateTime | null>(null);+ let initialToDateTime = $state<CalendarDateTime | null>(null);++ // Helper to compare two CalendarDateTime values+ function dateTimesEqual(a: CalendarDateTime, b: CalendarDateTime): boolean {+ return (+ a.year === b.year &&+ a.month === b.month &&+ a.day === b.day &&+ a.hour === b.hour &&+ a.minute === b.minute+ );+ }++ // Get display label for trigger button+ const displayLabel = $derived(() => {+ if (selectedPreset && !showCustom) {+ const preset = presetGroups.flatMap((g) => g.presets).find((p) => p.value === selectedPreset);+ return preset ? `Last ${preset.label}` : 'Select time range';+ }+ // For custom selection, show date and time range (no prefix)+ if (tempFromDateTime && tempToDateTime) {+ const fromDateStr = formatDateShort(tempFromDateTime);+ const fromTimeStr = formatTime12h(tempFromDateTime);+ const toDateStr = formatDateShort(tempToDateTime);+ const toTimeStr = formatTime12h(tempToDateTime);+ return `${fromDateStr} ${fromTimeStr} – ${toDateStr} ${toTimeStr}`;+ }+ return 'Select time range';+ });++ function formatDateShort(dt: CalendarDateTime): string {+ return new CalendarDate(dt.year, dt.month, dt.day)+ .toDate(getLocalTimeZone())+ .toLocaleDateString('en-US', { month: 'short', day: 'numeric' });+ }++ // YY/MM/DD format for compact display+ function formatDateCompact(dt: CalendarDateTime): string {+ const year = String(dt.year).slice(-2);+ const month = String(dt.month).padStart(2, '0');+ const day = String(dt.day).padStart(2, '0');+ return `${year}/${month}/${day}`;+ }++ // Format time as 12h with AM/PM+ function formatTime12h(dt: CalendarDateTime): string {+ const hours = dt.hour;+ const minutes = dt.minute;+ const period = hours >= 12 ? 'PM' : 'AM';+ const hours12 = hours % 12 || 12;+ return `${hours12}:${String(minutes).padStart(2, '0')} ${period}`;+ }++ function selectPreset(presetDef: TimeRangePreset) {+ selectedPreset = presetDef.value;+ preset = presetDef.value; // Sync with external prop+ showCustom = false;++ // Calculate the date range for this preset using Luxon+ const now = getNow(tz);+ const fromDt = now.minus({ minutes: presetDef.minutes });+ const fromParts = luxonToCalendarDateTime(fromDt);+ const toParts = luxonToCalendarDateTime(now);++ tempFromDateTime = new CalendarDateTime(+ fromParts.year,+ fromParts.month,+ fromParts.day,+ fromParts.hour,+ fromParts.minute,+ fromParts.second+ );+ tempToDateTime = new CalendarDateTime(+ toParts.year,+ toParts.month,+ toParts.day,+ toParts.hour,+ toParts.minute,+ toParts.second+ );++ applyAndClose();+ }++ function toggleCustom() {+ showCustom = !showCustom;+ if (showCustom) {+ selectedPreset = null;+ preset = null; // Sync with external prop+ }+ }++ function resetToNow() {+ const now = getNow(tz);+ const nowParts = luxonToCalendarDateTime(now);+ tempToDateTime = new CalendarDateTime(+ nowParts.year,+ nowParts.month,+ nowParts.day,+ nowParts.hour,+ nowParts.minute,+ nowParts.second+ );+ }++ function applyAndClose() {+ isApplyingInternally = true;++ fromDate = new CalendarDate(+ tempFromDateTime.year,+ tempFromDateTime.month,+ tempFromDateTime.day+ );+ toDate = new CalendarDate(tempToDateTime.year, tempToDateTime.month, tempToDateTime.day);+ fromTime = `${String(tempFromDateTime.hour).padStart(2, '0')}:${String(tempFromDateTime.minute).padStart(2, '0')}`;+ toTime = `${String(tempToDateTime.hour).padStart(2, '0')}:${String(tempToDateTime.minute).padStart(2, '0')}`;++ const currentPreset = showCustom ? null : selectedPreset;+ preset = currentPreset;+ onApply?.({ date: fromDate, time: fromTime }, { date: toDate, time: toTime }, currentPreset);++ setTimeout(() => {+ isApplyingInternally = false;+ }, 0);++ fromPickerOpen = false;+ toPickerOpen = false;+ isOpen = false;+ }++ function handleOpenChange(open: boolean) {+ if (open) {+ // Capture initial values when opening+ initialFromDateTime = new CalendarDateTime(+ tempFromDateTime.year,+ tempFromDateTime.month,+ tempFromDateTime.day,+ tempFromDateTime.hour,+ tempFromDateTime.minute,+ tempFromDateTime.second+ );+ initialToDateTime = new CalendarDateTime(+ tempToDateTime.year,+ tempToDateTime.month,+ tempToDateTime.day,+ tempToDateTime.hour,+ tempToDateTime.minute,+ tempToDateTime.second+ );+ } else {+ // Skip if already applied by applyAndClose (Apply button was clicked)+ if (isApplyingInternally) {+ isOpen = open;+ return;+ }++ // Apply if closed by clicking outside and values have changed+ const hasChanged =+ !initialFromDateTime ||+ !initialToDateTime ||+ !dateTimesEqual(tempFromDateTime, initialFromDateTime) ||+ !dateTimesEqual(tempToDateTime, initialToDateTime);++ if (hasChanged) {+ applyAndClose();+ return; // applyAndClose handles setting isOpen+ }++ // No changes - just close+ fromPickerOpen = false;+ toPickerOpen = false;+ }+ isOpen = open;+ }++ function handleFromDateTimeChange(dt: CalendarDateTime) {+ tempFromDateTime = dt;+ }++ function handleToDateTimeChange(dt: CalendarDateTime) {+ tempToDateTime = dt;+ }</script><Popover.Root bind:open={isOpen} onOpenChange={handleOpenChange}>- <Popover.Trigger class="w-full">- <Button variant="outline" class="h-9 justify-between gap-2 font-normal w-full">- <span class="flex items-center gap-2">- <Clock class="h-4 w-4 text-muted-foreground" />- <span class="truncate">{displayLabel()}</span>- </span>- <ChevronDown class="h-4 w-4 text-muted-foreground" />- </Button>- </Popover.Trigger>- <Popover.Content class="w-auto p-0" align="start">- <div class="flex">- <!-- Presets Column -->- <div class="w-[140px] border-r py-2">- {#each presetGroups as group, groupIndex}- {#if groupIndex > 0}- <div class="my-1 border-t mx-2"></div>- {/if}- {#each group.presets as preset}- <button- class="w-full px-3 py-1.5 text-left text-sm hover:bg-muted/50 flex items-center justify-between transition-colors {selectedPreset === preset.value && !showCustom ? 'bg-muted' : ''}"- onclick={() => selectPreset(preset)}- >- <span>{preset.label}</span>- {#if selectedPreset === preset.value && !showCustom}- <Check class="h-4 w-4 text-primary" />- {/if}- </button>- {/each}- {/each}- <div class="my-1 border-t mx-2"></div>- <button- class="w-full px-3 py-1.5 text-left text-sm hover:bg-muted/50 flex items-center justify-between transition-colors {showCustom ? 'bg-muted' : ''}"- onclick={toggleCustom}- >- <span>Set custom</span>- <ChevronRight class="h-4 w-4 text-muted-foreground" />- </button>- </div>-- <!-- Custom Section -->- {#if showCustom}- <div class="p-5 min-w-[380px]">- <div class="flex items-center justify-between mb-3">- <span class="text-xs font-medium text-muted-foreground uppercase tracking-wide">Custom</span>- <button- class="text-xs text-primary hover:underline"- onclick={resetToNow}- >- Reset to now- </button>- </div>-- <!-- Compact Date/Time Inputs Row -->- <div class="flex items-center gap-2 mb-4">- <!-- From DateTime -->- <Popover.Root bind:open={fromPickerOpen}>- <Popover.Trigger>- <button- class="h-9 px-3 text-sm border rounded-md text-left hover:bg-muted/50 transition-colors flex items-center gap-2 {fromPickerOpen ? 'ring-2 ring-ring' : ''}"- >- <span class="tabular-nums">{formatDateCompact(tempFromDateTime)}</span>- <span class="text-muted-foreground tabular-nums">{formatTime12h(tempFromDateTime)}</span>- </button>- </Popover.Trigger>- <Popover.Content class="w-auto p-0" align="start">- <DateTimePicker- value={tempFromDateTime}- onValueChange={handleFromDateTimeChange}- />- </Popover.Content>- </Popover.Root>-- <span class="text-muted-foreground text-xs">–</span>-- <!-- To DateTime -->- <Popover.Root bind:open={toPickerOpen}>- <Popover.Trigger>- <button- class="h-9 px-3 text-sm border rounded-md text-left hover:bg-muted/50 transition-colors flex items-center gap-2 {toPickerOpen ? 'ring-2 ring-ring' : ''}"- >- <span class="tabular-nums">{formatDateCompact(tempToDateTime)}</span>- <span class="text-muted-foreground tabular-nums">{formatTime12h(tempToDateTime)}</span>- </button>- </Popover.Trigger>- <Popover.Content class="w-auto p-0" align="start">- <DateTimePicker- value={tempToDateTime}- onValueChange={handleToDateTimeChange}- />- </Popover.Content>- </Popover.Root>- </div>-- <!-- Apply button -->- <div class="flex justify-end pt-2">- <Button size="sm" onclick={applyAndClose}>- Apply- </Button>- </div>- </div>- {/if}- </div>- </Popover.Content>+ <Popover.Trigger class="w-full">+ <Button variant="outline" class="h-9 w-full justify-between gap-2 font-normal">+ <span class="flex items-center gap-2">+ <Clock class="h-4 w-4 text-muted-foreground" />+ <span class="truncate">{displayLabel()}</span>+ </span>+ <ChevronDown class="h-4 w-4 text-muted-foreground" />+ </Button>+ </Popover.Trigger>+ <Popover.Content class="w-auto p-0" align="start">+ <div class="flex">+ <!-- Presets Column -->+ <div class="w-[140px] border-r py-2">+ {#each presetGroups as group, groupIndex (groupIndex)}+ {#if groupIndex > 0}+ <div class="mx-2 my-1 border-t"></div>+ {/if}+ {#each group.presets as preset, __index (__index)}+ <button+ class="flex w-full items-center justify-between px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/50 {selectedPreset ===+ preset.value && !showCustom+ ? 'bg-muted'+ : ''}"+ onclick={() => selectPreset(preset)}+ >+ <span>{preset.label}</span>+ {#if selectedPreset === preset.value && !showCustom}+ <Check class="h-4 w-4 text-primary" />+ {/if}+ </button>+ {/each}+ {/each}+ <div class="mx-2 my-1 border-t"></div>+ <button+ class="flex w-full items-center justify-between px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/50 {showCustom+ ? 'bg-muted'+ : ''}"+ onclick={toggleCustom}+ >+ <span>Set custom</span>+ <ChevronRight class="h-4 w-4 text-muted-foreground" />+ </button>+ </div>++ <!-- Custom Section -->+ {#if showCustom}+ <div class="min-w-[380px] p-5">+ <div class="mb-3 flex items-center justify-between">+ <span class="text-xs font-medium tracking-wide text-muted-foreground uppercase"+ >Custom</span+ >+ <button class="text-xs text-primary hover:underline" onclick={resetToNow}>+ Reset to now+ </button>+ </div>++ <!-- Compact Date/Time Inputs Row -->+ <div class="mb-4 flex items-center gap-2">+ <!-- From DateTime -->+ <Popover.Root bind:open={fromPickerOpen}>+ <Popover.Trigger>+ <button+ class="flex h-9 items-center gap-2 rounded-md border px-3 text-left text-sm transition-colors hover:bg-muted/50 {fromPickerOpen+ ? 'ring-2 ring-ring'+ : ''}"+ >+ <span class="tabular-nums">{formatDateCompact(tempFromDateTime)}</span>+ <span class="text-muted-foreground tabular-nums"+ >{formatTime12h(tempFromDateTime)}</span+ >+ </button>+ </Popover.Trigger>+ <Popover.Content class="w-auto p-0" align="start">+ <DateTimePicker value={tempFromDateTime} onValueChange={handleFromDateTimeChange} />+ </Popover.Content>+ </Popover.Root>++ <span class="text-xs text-muted-foreground">–</span>++ <!-- To DateTime -->+ <Popover.Root bind:open={toPickerOpen}>+ <Popover.Trigger>+ <button+ class="flex h-9 items-center gap-2 rounded-md border px-3 text-left text-sm transition-colors hover:bg-muted/50 {toPickerOpen+ ? 'ring-2 ring-ring'+ : ''}"+ >+ <span class="tabular-nums">{formatDateCompact(tempToDateTime)}</span>+ <span class="text-muted-foreground tabular-nums"+ >{formatTime12h(tempToDateTime)}</span+ >+ </button>+ </Popover.Trigger>+ <Popover.Content class="w-auto p-0" align="start">+ <DateTimePicker value={tempToDateTime} onValueChange={handleToDateTimeChange} />+ </Popover.Content>+ </Popover.Root>+ </div>++ <!-- Apply button -->+ <div class="flex justify-end pt-2">+ <Button size="sm" onclick={applyAndClose}>Apply</Button>+ </div>+ </div>+ {/if}+ </div>+ </Popover.Content></Popover.Root>diff --git a/frontend/src/lib/components/ui/tooltip/index.ts b/frontend/src/lib/components/ui/tooltip/index.tsindex 17186042..809e219e 100644--- a/frontend/src/lib/components/ui/tooltip/index.ts+++ b/frontend/src/lib/components/ui/tooltip/index.ts@@ -1,8 +1,8 @@-import Root from "./tooltip.svelte";-import Trigger from "./tooltip-trigger.svelte";-import Content from "./tooltip-content.svelte";-import Provider from "./tooltip-provider.svelte";-import Portal from "./tooltip-portal.svelte";+import Root from './tooltip.svelte';+import Trigger from './tooltip-trigger.svelte';+import Content from './tooltip-content.svelte';+import Provider from './tooltip-provider.svelte';+import Portal from './tooltip-portal.svelte';export {Root,@@ -15,5 +15,5 @@ export {Content as TooltipContent,Trigger as TooltipTrigger,Provider as TooltipProvider,- Portal as TooltipPortal,+ Portal as TooltipPortal};diff --git a/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte b/frontend/src/lib/components/ui/tooltip/tooltip-content.svelteindex 42c4cc8c..05bc3d69 100644--- a/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte+++ b/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte@@ -27,7 +27,7 @@{sideOffset}{side}class={cn(- 'z-50 max-w-[220px] origin-(--bits-tooltip-content-transform-origin) animate-in rounded-sm border border-transparent bg-foreground px-3 py-2 text-xs text-background shadow-[none] fade-in-0 zoom-in-95 dark:border-border data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',+ 'z-50 max-w-[220px] origin-(--bits-tooltip-content-transform-origin) animate-in rounded-sm border border-transparent bg-foreground px-3 py-2 text-xs text-background shadow-[none] fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 dark:border-border',className)}{...restProps}diff --git a/frontend/src/lib/components/ui/tooltip/tooltip-portal.svelte b/frontend/src/lib/components/ui/tooltip/tooltip-portal.svelteindex d234f7d7..7d328f01 100644--- a/frontend/src/lib/components/ui/tooltip/tooltip-portal.svelte+++ b/frontend/src/lib/components/ui/tooltip/tooltip-portal.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Tooltip as TooltipPrimitive } from "bits-ui";+ import { Tooltip as TooltipPrimitive } from 'bits-ui';let { ...restProps }: TooltipPrimitive.PortalProps = $props();</script>diff --git a/frontend/src/lib/components/ui/tooltip/tooltip-provider.svelte b/frontend/src/lib/components/ui/tooltip/tooltip-provider.svelteindex 8150bef2..b3bb5b74 100644--- a/frontend/src/lib/components/ui/tooltip/tooltip-provider.svelte+++ b/frontend/src/lib/components/ui/tooltip/tooltip-provider.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Tooltip as TooltipPrimitive } from "bits-ui";+ import { Tooltip as TooltipPrimitive } from 'bits-ui';let { ...restProps }: TooltipPrimitive.ProviderProps = $props();</script>diff --git a/frontend/src/lib/components/ui/tooltip/tooltip-trigger.svelte b/frontend/src/lib/components/ui/tooltip/tooltip-trigger.svelteindex d61af940..aa0147a0 100644--- a/frontend/src/lib/components/ui/tooltip/tooltip-trigger.svelte+++ b/frontend/src/lib/components/ui/tooltip/tooltip-trigger.svelte@@ -1,10 +1,10 @@<script lang="ts">- import { Tooltip as TooltipPrimitive } from "bits-ui";- import { getContext } from "svelte";+ import { Tooltip as TooltipPrimitive } from 'bits-ui';+ import { getContext } from 'svelte';let { ref = $bindable(null), ...restProps }: TooltipPrimitive.TriggerProps = $props();- const ctx = getContext<{ toggle: () => void }>("traceway-tooltip");+ const ctx = getContext<{ toggle: () => void }>('traceway-tooltip');function handleTouchStart(e: TouchEvent) {if (ctx) {@@ -14,4 +14,9 @@}</script>-<TooltipPrimitive.Trigger bind:ref data-slot="tooltip-trigger" ontouchstart={handleTouchStart} {...restProps} />+<TooltipPrimitive.Trigger+ bind:ref+ data-slot="tooltip-trigger"+ ontouchstart={handleTouchStart}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/tooltip/tooltip.svelte b/frontend/src/lib/components/ui/tooltip/tooltip.svelteindex 6c08e813..e6b56c6d 100644--- a/frontend/src/lib/components/ui/tooltip/tooltip.svelte+++ b/frontend/src/lib/components/ui/tooltip/tooltip.svelte@@ -1,6 +1,6 @@<script lang="ts">- import { Tooltip as TooltipPrimitive } from "bits-ui";- import { setContext } from "svelte";+ import { Tooltip as TooltipPrimitive } from 'bits-ui';+ import { setContext } from 'svelte';let { open = $bindable(false), ...restProps }: TooltipPrimitive.RootProps = $props();@@ -25,8 +25,8 @@open = true;setTimeout(() => {const handler = () => closeTooltip();- document.addEventListener("pointerdown", handler);- removeListener = () => document.removeEventListener("pointerdown", handler);+ document.addEventListener('pointerdown', handler);+ removeListener = () => document.removeEventListener('pointerdown', handler);}, 0);}@@ -38,7 +38,7 @@open = v;}- setContext("traceway-tooltip", { toggle });+ setContext('traceway-tooltip', { toggle });</script><TooltipPrimitive.Root bind:open {...restProps} onOpenChange={handleOpenChange} />diff --git a/frontend/src/lib/components/ui/traceway-table-header/index.ts b/frontend/src/lib/components/ui/traceway-table-header/index.tsindex c5b7e3c3..d4e64a75 100644--- a/frontend/src/lib/components/ui/traceway-table-header/index.ts+++ b/frontend/src/lib/components/ui/traceway-table-header/index.ts@@ -1,3 +1,3 @@-import TracewayTableHeader from "./traceway-table-header.svelte";+import TracewayTableHeader from './traceway-table-header.svelte';export { TracewayTableHeader };diff --git a/frontend/src/lib/components/ui/traceway-table-header/traceway-table-header.svelte b/frontend/src/lib/components/ui/traceway-table-header/traceway-table-header.svelteindex b07285c3..d7ab0aa8 100644--- a/frontend/src/lib/components/ui/traceway-table-header/traceway-table-header.svelte+++ b/frontend/src/lib/components/ui/traceway-table-header/traceway-table-header.svelte@@ -1,11 +1,11 @@<script lang="ts">- import { cn } from "$lib/utils.js";- import * as Table from "$lib/components/ui/table/index.js";- import * as Tooltip from "$lib/components/ui/tooltip/index.js";- import { Button } from "$lib/components/ui/button/index.js";- import { ArrowDown, ArrowUp, ArrowUpDown, CircleQuestionMark } from "lucide-svelte";+ import { cn } from '$lib/utils.js';+ import * as Table from '$lib/components/ui/table/index.js';+ import * as Tooltip from '$lib/components/ui/tooltip/index.js';+ import { Button } from '$lib/components/ui/button/index.js';+ import { ArrowDown, ArrowUp, ArrowUpDown, CircleQuestionMark } from '@lucide/svelte';- type SortDirection = "asc" | "desc";+ type SortDirection = 'asc' | 'desc';let {label,@@ -14,7 +14,7 @@currentSortField,sortDirection,onSort,- align = "left",+ align = 'left',class: className}: {label: string;@@ -23,27 +23,27 @@currentSortField?: string;sortDirection?: SortDirection;onSort?: (field: string) => void;- align?: "left" | "right";+ align?: 'left' | 'right';class?: string;} = $props();const isSortable = $derived(sortField !== undefined && onSort !== undefined);const isCurrentSort = $derived(isSortable && currentSortField === sortField);- const alignRight = $derived(align === "right");+ const alignRight = $derived(align === 'right');</script>-<Table.Head class={cn(alignRight && "text-right", className)}>+<Table.Head class={cn(alignRight && 'text-right', className)}>{#if isSortable}- <div class={cn("flex items-center", alignRight && "justify-end gap-1.5")}>+ <div class={cn('flex items-center', alignRight && 'justify-end gap-1.5')}><Buttonvariant="ghost"size="sm"- class={cn("h-8 text-[15px] font-medium", !alignRight && "-ml-3")}+ class={cn('h-8 text-[15px] font-medium', !alignRight && '-ml-3')}onclick={() => onSort?.(sortField!)}>{label}{#if isCurrentSort}- {#if sortDirection === "desc"}+ {#if sortDirection === 'desc'}<ArrowDown class="ml-2 h-4 w-4" />{:else}<ArrowUp class="ml-2 h-4 w-4" />@@ -64,7 +64,7 @@{/if}</div>{:else if tooltip}- <span class={cn("flex items-center gap-1.5", alignRight && "justify-end")}>+ <span class={cn('flex items-center gap-1.5', alignRight && 'justify-end')}>{label}<Tooltip.Root><Tooltip.Trigger>diff --git a/frontend/src/lib/components/ui/view-all-table-row/view-all-table-row.svelte b/frontend/src/lib/components/ui/view-all-table-row/view-all-table-row.svelteindex b2dc8e21..0a0aa4bf 100644--- a/frontend/src/lib/components/ui/view-all-table-row/view-all-table-row.svelte+++ b/frontend/src/lib/components/ui/view-all-table-row/view-all-table-row.svelte@@ -1,6 +1,6 @@<script lang="ts">import * as Table from '$lib/components/ui/table';- import { ArrowRight } from 'lucide-svelte';+ import { ArrowRight } from '@lucide/svelte';import { createRowClickHandlerWithNavigate } from '$lib/utils/navigation';let {@@ -16,8 +16,12 @@} = $props();</script>-<Table.Row class="cursor-pointer bg-muted/50 hover:bg-muted" onclick={createRowClickHandlerWithNavigate(href, onBeforeNavigate)}>+<Table.Row+ class="cursor-pointer bg-muted/50 hover:bg-muted"+ onclick={createRowClickHandlerWithNavigate(href, onBeforeNavigate)}+><Table.Cell {colspan} class="py-2 text-center text-sm text-muted-foreground">- {label} <ArrowRight class="inline h-3.5 w-3.5" />+ {label}+ <ArrowRight class="inline h-3.5 w-3.5" /></Table.Cell></Table.Row>diff --git a/frontend/src/lib/components/ui/warning-callout/warning-callout.svelte b/frontend/src/lib/components/ui/warning-callout/warning-callout.svelteindex 308f6e89..848839f7 100644--- a/frontend/src/lib/components/ui/warning-callout/warning-callout.svelte+++ b/frontend/src/lib/components/ui/warning-callout/warning-callout.svelte@@ -1,6 +1,6 @@<script lang="ts">import type { Snippet } from 'svelte';- import { TriangleAlert, OctagonAlert } from 'lucide-svelte';+ import { TriangleAlert, OctagonAlert } from '@lucide/svelte';import { cn } from '$lib/utils.js';let {@@ -44,7 +44,7 @@<div class="min-w-0 flex-1">{#if title}<div- class="font-black leading-tight {destructive ? 'text-destructive' : 'text-[#ffab01]'}"+ class="leading-tight font-black {destructive ? 'text-destructive' : 'text-[#ffab01]'}">{title}</div>diff --git a/frontend/src/lib/hooks/is-mobile.svelte.ts b/frontend/src/lib/hooks/is-mobile.svelte.tsindex 4829c00b..acbe8ef5 100644--- a/frontend/src/lib/hooks/is-mobile.svelte.ts+++ b/frontend/src/lib/hooks/is-mobile.svelte.ts@@ -1,4 +1,4 @@-import { MediaQuery } from "svelte/reactivity";+import { MediaQuery } from 'svelte/reactivity';const DEFAULT_MOBILE_BREAKPOINT = 768;diff --git a/frontend/src/lib/state/auth.svelte.ts b/frontend/src/lib/state/auth.svelte.tsindex fc5855f9..ddeb8025 100644--- a/frontend/src/lib/state/auth.svelte.ts+++ b/frontend/src/lib/state/auth.svelte.ts@@ -1,75 +1,79 @@import { clearNavDepth } from '$lib/utils/back-navigation';export interface UserOrganizationResponse {- id: number;- name: string;- role: string;- timezone: string;+ id: number;+ name: string;+ role: string;+ timezone: string;}class AuthState {- token = $state<string | null>(localStorage.getItem('AUTH_TOKEN'));- organizations = $state<UserOrganizationResponse[]>(- JSON.parse(localStorage.getItem('USER_ORGANIZATIONS') || '[]')- );+ token = $state<string | null>(localStorage.getItem('AUTH_TOKEN'));+ organizations = $state<UserOrganizationResponse[]>(+ JSON.parse(localStorage.getItem('USER_ORGANIZATIONS') || '[]')+ );- isAuthenticated = $derived(!!this.token);+ isAuthenticated = $derived(!!this.token);- constructor() {- $effect.root(() => {- $effect(() => {- if (this.token) {- localStorage.setItem('AUTH_TOKEN', this.token);- } else {- localStorage.removeItem('AUTH_TOKEN');- }- });- $effect(() => {- if (this.organizations.length > 0) {- localStorage.setItem('USER_ORGANIZATIONS', JSON.stringify(this.organizations));- } else {- localStorage.removeItem('USER_ORGANIZATIONS');- }- });- });- }+ constructor() {+ $effect.root(() => {+ $effect(() => {+ if (this.token) {+ localStorage.setItem('AUTH_TOKEN', this.token);+ } else {+ localStorage.removeItem('AUTH_TOKEN');+ }+ });+ $effect(() => {+ if (this.organizations.length > 0) {+ localStorage.setItem('USER_ORGANIZATIONS', JSON.stringify(this.organizations));+ } else {+ localStorage.removeItem('USER_ORGANIZATIONS');+ }+ });+ });+ }- setToken(token: string) {- this.token = token;- }+ setToken(token: string) {+ this.token = token;+ }- setOrganizations(organizations: UserOrganizationResponse[]) {- this.organizations = organizations;- }+ setOrganizations(organizations: UserOrganizationResponse[]) {+ this.organizations = organizations;+ }- getRoleForOrganization(organizationId: number): string | null {- const organization = this.organizations.find(o => o.id === organizationId);- return organization?.role || null;- }+ getRoleForOrganization(organizationId: number): string | null {+ const organization = this.organizations.find((o) => o.id === organizationId);+ return organization?.role || null;+ }- canManageOrganization(organizationId: number): boolean {- const role = this.getRoleForOrganization(organizationId);- return role === 'owner' || role === 'admin';- }+ canManageOrganization(organizationId: number): boolean {+ const role = this.getRoleForOrganization(organizationId);+ return role === 'owner' || role === 'admin';+ }- getTimezoneForOrganization(organizationId: number): string | null {- const organization = this.organizations.find(o => o.id === organizationId);- return organization?.timezone || null;- }+ canWriteOrganization(organizationId: number): boolean {+ return this.getRoleForOrganization(organizationId) !== 'readonly';+ }- updateOrganizationTimezone(organizationId: number, timezone: string) {- const organization = this.organizations.find(o => o.id === organizationId);- if (organization) {- organization.timezone = timezone;- this.organizations = [...this.organizations];- }- }+ getTimezoneForOrganization(organizationId: number): string | null {+ const organization = this.organizations.find((o) => o.id === organizationId);+ return organization?.timezone || null;+ }- logout() {- this.token = null;- this.organizations = [];- clearNavDepth();- }+ updateOrganizationTimezone(organizationId: number, timezone: string) {+ const organization = this.organizations.find((o) => o.id === organizationId);+ if (organization) {+ organization.timezone = timezone;+ this.organizations = [...this.organizations];+ }+ }++ logout() {+ this.token = null;+ this.organizations = [];+ clearNavDepth();+ }}export const authState = new AuthState();diff --git a/frontend/src/lib/state/monitors.svelte.ts b/frontend/src/lib/state/monitors.svelte.tsindex 27357e9d..20702bd0 100644--- a/frontend/src/lib/state/monitors.svelte.ts+++ b/frontend/src/lib/state/monitors.svelte.ts@@ -73,11 +73,63 @@ export interface CheckOverview extends SyntheticCheck {export interface CheckIncident {id: number;- checkId: number;- projectId: string;+ checkId: number | null;+ projectId: string | null;+ statusPageId: number | null;+ title: string;startedAt: string;resolvedAt: string | null;errorMessage: string;+ updatesCount?: number;+ postMortemId?: number | null;+}++export type IncidentUpdateStatus =+ | 'investigating'+ | 'identified'+ | 'monitoring'+ | 'update'+ | 'resolved';++export interface IncidentUpdate {+ id: number;+ incidentId: number;+ status: IncidentUpdateStatus;+ message: string;+ createdBy: number | null;+ createdAt: string;+}++export interface OrgIncident extends CheckIncident {+ checkName: string | null;+ statusPageName: string | null;+}++export function incidentDisplayTitle(incident: {+ title?: string | null;+ checkName?: string | null;+}): string {+ if (incident.title) return incident.title;+ return incident.checkName ? `${incident.checkName} is down` : 'Incident';+}++export interface PostMortemListItem {+ id: number;+ organizationId: number;+ projectId: string;+ incidentId: number | null;+ title: string;+ tags: string[];+ createdBy: number | null;+ updatedBy: number | null;+ createdByName: string | null;+ updatedByName: string | null;+ createdAt: string;+ updatedAt: string;+}++export interface PostMortem extends PostMortemListItem {+ contentMd: string;}export interface CheckResultEntry {diff --git a/frontend/src/lib/state/oncall.svelte.ts b/frontend/src/lib/state/oncall.svelte.tsindex b3ffb6b8..5d19d327 100644--- a/frontend/src/lib/state/oncall.svelte.ts+++ b/frontend/src/lib/state/oncall.svelte.ts@@ -3,470 +3,473 @@ import { authState } from './auth.svelte';import { projectsState } from './projects.svelte';export interface TeamMember {- teamId: number;- userId: number;- position: number;- name: string;- email: string;+ teamId: number;+ userId: number;+ position: number;+ name: string;+ email: string;}export interface TeamProject {- projectId: string;- name: string;+ projectId: string;+ name: string;}export interface Team {- id: number;- organizationId: number;- name: string;- description: string;- createdAt: string;- updatedAt: string;- memberCount: number;- projectCount: number;- scheduleCount: number;- members: TeamMember[];- projects: TeamProject[];+ id: number;+ organizationId: number;+ name: string;+ description: string;+ createdAt: string;+ updatedAt: string;+ memberCount: number;+ projectCount: number;+ scheduleCount: number;+ members: TeamMember[];+ projects: TeamProject[];}export interface ScheduleRestriction {- type: 'daily' | 'weekly';- startTime: string;- endTime: string;- startDay?: number;- endDay?: number;+ type: 'daily' | 'weekly';+ startTime: string;+ endTime: string;+ startDay?: number;+ endDay?: number;}export interface ScheduleLayer {- id?: string;- name: string;- rotationType: 'daily' | 'weekly' | 'custom';- handoffTime: string;- handoffDay?: number;- intervalDays?: number;- rotationStart: string;- userIds: number[];- restrictions: ScheduleRestriction[];+ id?: string;+ name: string;+ rotationType: 'daily' | 'weekly' | 'custom';+ handoffTime: string;+ handoffDay?: number;+ intervalDays?: number;+ rotationStart: string;+ userIds: number[];+ restrictions: ScheduleRestriction[];}export interface ScheduleDefinition {- schemaVersion: number;- layers: ScheduleLayer[];+ schemaVersion: number;+ layers: ScheduleLayer[];}export interface Schedule {- id: number;- organizationId: number;- teamId: number;- name: string;- description: string;- timezone: string;- definition: ScheduleDefinition;- createdBy: number;- createdAt: string;- updatedAt: string;+ id: number;+ organizationId: number;+ teamId: number;+ name: string;+ description: string;+ timezone: string;+ definition: ScheduleDefinition;+ createdBy: number;+ createdAt: string;+ updatedAt: string;}export interface ScheduleOverride {- id: number;- scheduleId: number;- userId: number;- startAt: string;- endAt: string;- createdBy: number;- createdAt: string;+ id: number;+ scheduleId: number;+ userId: number;+ startAt: string;+ endAt: string;+ createdBy: number;+ createdAt: string;}export interface TimelineShift {- userId: number;- layerId: string;- start: string;- end: string;- isOverride: boolean;+ userId: number;+ layerId: string;+ start: string;+ end: string;+ isOverride: boolean;}export interface TimelineLayer {- id: string;- name: string;- shifts: TimelineShift[];+ id: string;+ name: string;+ shifts: TimelineShift[];}export interface TimelineUser {- name: string;- email: string;+ name: string;+ email: string;}export interface TimelineResponse {- schedule: { id: number; name: string; timezone: string; teamId: number };- from: string;- to: string;- layers: TimelineLayer[];- final: TimelineShift[];- users: Record<string, TimelineUser | null>;+ schedule: { id: number; name: string; timezone: string; teamId: number };+ from: string;+ to: string;+ layers: TimelineLayer[];+ final: TimelineShift[];+ users: Record<string, TimelineUser | null>;}export interface OncallUser {- userId: number;- name: string;- email: string;+ userId: number;+ name: string;+ email: string;}export interface OverviewSchedule {- id: number;- name: string;- oncall: OncallUser[];- until: string | null;- nextUp: OncallUser | null;- nextAt: string | null;+ id: number;+ name: string;+ oncall: OncallUser[];+ until: string | null;+ nextUp: OncallUser | null;+ nextAt: string | null;}export interface OverviewTeam {- team: {- id: number;- name: string;- description: string;- memberCount: number;- projectCount: number;- scheduleCount: number;- };- schedules: OverviewSchedule[];+ team: {+ id: number;+ name: string;+ description: string;+ memberCount: number;+ projectCount: number;+ scheduleCount: number;+ };+ schedules: OverviewSchedule[];}export interface ProjectOncall {- team: { id: number; name: string } | null;- schedules: { id: number; name: string }[];- oncall: OncallUser[];+ team: { id: number; name: string } | null;+ schedules: { id: number; name: string }[];+ oncall: OncallUser[];}export interface OrgMember {- id: number;- email: string;- name: string;- role: string;+ id: number;+ email: string;+ name: string;+ role: string;}export type PolicyTargetType = 'schedule' | 'user' | 'team' | 'channel';export interface PolicyTarget {- type: PolicyTargetType;- id: number;+ type: PolicyTargetType;+ id: number;}export interface PolicyStep {- targets: PolicyTarget[];- delayMinutes: number;+ targets: PolicyTarget[];+ delayMinutes: number;}export interface PolicyDefinition {- schemaVersion: number;- steps: PolicyStep[];- repeatCount: number;- urgency?: 'auto' | 'high' | 'low' | '';+ schemaVersion: number;+ steps: PolicyStep[];+ repeatCount: number;+ urgency?: 'auto' | 'high' | 'low' | '';}export interface EscalationPolicy {- id: number;- organizationId: number;- name: string;- definition: PolicyDefinition;- createdBy: number;- createdAt: string;- updatedAt: string;+ id: number;+ organizationId: number;+ name: string;+ definition: PolicyDefinition;+ createdBy: number;+ createdAt: string;+ updatedAt: string;}export interface OncallPage {- id: number;- organizationId: number;- projectId: string;- policyId: number;- policySnapshot: PolicyDefinition;- ruleId: number;- ruleName: string;- ruleType: string;- subject: string;- body: string;- url: string;- severity: string;- urgency: '' | 'high' | 'low';- status: 'open' | 'acknowledged' | 'resolved';- eventCount: number;- lastEventAt: string;- escalationLevel: number;- repeatIteration: number;- nextEscalationAt: string | null;- lastEscalatedAt: string | null;- acknowledgedBy: number | null;- acknowledgedAt: string | null;- acknowledgedVia: '' | 'dashboard' | 'link';- resolvedBy: number | null;- resolvedAt: string | null;- createdAt: string;- updatedAt: string;- issueHash: string;- acknowledgedByName?: string;- resolvedByName?: string;+ id: number;+ organizationId: number;+ projectId: string;+ policyId: number;+ policySnapshot: PolicyDefinition;+ ruleId: number;+ ruleName: string;+ ruleType: string;+ subject: string;+ body: string;+ url: string;+ severity: string;+ urgency: '' | 'high' | 'low';+ status: 'open' | 'acknowledged' | 'resolved';+ eventCount: number;+ lastEventAt: string;+ escalationLevel: number;+ repeatIteration: number;+ nextEscalationAt: string | null;+ lastEscalatedAt: string | null;+ acknowledgedBy: number | null;+ acknowledgedAt: string | null;+ acknowledgedVia: '' | 'dashboard' | 'link';+ resolvedBy: number | null;+ resolvedAt: string | null;+ createdAt: string;+ updatedAt: string;+ issueHash: string;+ acknowledgedByName?: string;+ resolvedByName?: string;}export interface PageNotification {- id: number;- pageId: number;- level: number;- iteration: number;- userId: number | null;- targetDesc: string;- methodType: string;- status: 'pending' | 'sent' | 'failed' | 'cancelled';- errorMsg: string;- createdAt: string;- sentAt: string | null;- scheduledFor: string | null;+ id: number;+ pageId: number;+ level: number;+ iteration: number;+ userId: number | null;+ targetDesc: string;+ methodType: string;+ status: 'pending' | 'sent' | 'failed' | 'cancelled';+ errorMsg: string;+ createdAt: string;+ sentAt: string | null;+ scheduledFor: string | null;}export interface PageDetailResponse {- page: OncallPage;- notifications: PageNotification[];- users: Record<string, string>;+ page: OncallPage;+ notifications: PageNotification[];+ users: Record<string, string>;}export interface ContactMethod {- id: number;- userId: number;- methodType: 'email' | 'slack' | 'pushover' | 'telegram' | 'sms';- config: Record<string, string>;- enabled: boolean;- verified: boolean;- createdAt: string;+ id: number;+ userId: number;+ methodType: 'email' | 'slack' | 'pushover' | 'telegram' | 'sms';+ config: Record<string, string>;+ enabled: boolean;+ verified: boolean;+ createdAt: string;}export interface UserNotificationRuleStep {- id?: number;- contactMethodId: number;- delayMinutes: number;+ id?: number;+ contactMethodId: number;+ delayMinutes: number;}export function getCurrentUserFromToken(): { userId: number; email: string } | null {- const token = authState.token;- if (!token) return null;- try {- const payload = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));- if (typeof payload.userId !== 'number') return null;- return { userId: payload.userId, email: payload.email ?? '' };- } catch {- return null;- }+ const token = authState.token;+ if (!token) return null;+ try {+ const payload = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));+ if (typeof payload.userId !== 'number') return null;+ return { userId: payload.userId, email: payload.email ?? '' };+ } catch {+ return null;+ }}class OncallState {- teams = $state<Team[]>([]);- teamsLoading = $state(false);- teamsError = $state('');- schedules = $state<Schedule[]>([]);- schedulesLoading = $state(false);- schedulesError = $state('');- overview = $state<OverviewTeam[]>([]);- overviewLoading = $state(false);- overviewError = $state('');- policies = $state<EscalationPolicy[]>([]);- policiesLoading = $state(false);- policiesError = $state('');- openPagesCount = $state(0);-- canManage(organizationId: number): boolean {- return authState.canManageOrganization(organizationId);- }-- async refreshOpenCount() {- try {- const res = await api.get('/pages/open-count', {- projectId: projectsState.currentProjectId ?? undefined- });- this.openPagesCount = res.count ?? 0;- } catch {- // badge stays at its last value- }- }-- async loadTeams(organizationId: number) {- this.teamsLoading = true;- this.teamsError = '';- try {- const res = await api.get(`/organizations/${organizationId}/teams`);- this.teams = res.teams || [];- } catch (e: unknown) {- this.teamsError = e instanceof Error ? e.message : 'Failed to load teams';- this.teams = [];- } finally {- this.teamsLoading = false;- }- }-- async loadSchedules(organizationId: number) {- this.schedulesLoading = true;- this.schedulesError = '';- try {- const res = await api.get(`/organizations/${organizationId}/schedules`);- this.schedules = res.schedules || [];- } catch (e: unknown) {- this.schedulesError = e instanceof Error ? e.message : 'Failed to load schedules';- this.schedules = [];- } finally {- this.schedulesLoading = false;- }- }-- async loadOverview(organizationId: number) {- this.overviewLoading = true;- this.overviewError = '';- try {- const res = await api.get(`/organizations/${organizationId}/oncall/now`);- this.overview = res.teams || [];- } catch (e: unknown) {- this.overviewError = e instanceof Error ? e.message : 'Failed to load who is on call';- this.overview = [];- } finally {- this.overviewLoading = false;- }- }-- async createTeam(- organizationId: number,- body: { name: string; description: string; memberUserIds: number[]; projectIds: string[] }- ) {- const team = await api.post(`/organizations/${organizationId}/teams`, body);- await this.loadTeams(organizationId);- return team;- }-- async updateTeam(- organizationId: number,- teamId: number,- body: {- name: string;- description: string;- memberUserIds?: number[];- projectIds?: string[];- }- ) {- await api.put(`/organizations/${organizationId}/teams/${teamId}`, body);- }-- async updateTeamMembers(organizationId: number, teamId: number, userIds: number[]) {- await api.put(`/organizations/${organizationId}/teams/${teamId}/members`, { userIds });- }-- async updateTeamProjects(organizationId: number, teamId: number, projectIds: string[]) {- await api.put(`/organizations/${organizationId}/teams/${teamId}/projects`, { projectIds });- }-- async deleteTeam(organizationId: number, teamId: number) {- await api.delete(`/organizations/${organizationId}/teams/${teamId}`);- await this.loadTeams(organizationId);- }-- async createSchedule(- organizationId: number,- body: {- teamId: number;- name: string;- description: string;- timezone: string;- definition: ScheduleDefinition;- }- ) {- const schedule = await api.post(`/organizations/${organizationId}/schedules`, body);- await this.loadSchedules(organizationId);- return schedule;- }-- async updateSchedule(- organizationId: number,- scheduleId: number,- body: {- teamId: number;- name: string;- description: string;- timezone: string;- definition: ScheduleDefinition;- }- ) {- await api.put(`/organizations/${organizationId}/schedules/${scheduleId}`, body);- await this.loadSchedules(organizationId);- }-- async deleteSchedule(organizationId: number, scheduleId: number) {- await api.delete(`/organizations/${organizationId}/schedules/${scheduleId}`);- await this.loadSchedules(organizationId);- }-- async getSchedule(- organizationId: number,- scheduleId: number- ): Promise<{ schedule: Schedule; overrides: ScheduleOverride[] }> {- return await api.get(`/organizations/${organizationId}/schedules/${scheduleId}`);- }-- async getTimeline(- organizationId: number,- scheduleId: number,- from: string,- to: string- ): Promise<TimelineResponse> {- return await api.get(- `/organizations/${organizationId}/schedules/${scheduleId}/timeline?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`- );- }-- async createOverride(- organizationId: number,- scheduleId: number,- body: { userId: number; startAt: string; endAt: string }- ) {- return await api.post(`/organizations/${organizationId}/schedules/${scheduleId}/overrides`, body);- }-- async deleteOverride(organizationId: number, scheduleId: number, overrideId: number) {- await api.delete(- `/organizations/${organizationId}/schedules/${scheduleId}/overrides/${overrideId}`- );- }-- async getMembers(organizationId: number): Promise<OrgMember[]> {- return await api.get(`/organizations/${organizationId}/members`);- }-- async loadPolicies(organizationId: number) {- this.policiesLoading = true;- this.policiesError = '';- try {- const res = await api.get(`/organizations/${organizationId}/escalation-policies`);- this.policies = res.policies || [];- } catch (e: unknown) {- this.policiesError = e instanceof Error ? e.message : 'Failed to load escalation policies';- this.policies = [];- } finally {- this.policiesLoading = false;- }- }-- async createPolicy(organizationId: number, body: { name: string; definition: PolicyDefinition }) {- const policy = await api.post(`/organizations/${organizationId}/escalation-policies`, body);- await this.loadPolicies(organizationId);- return policy;- }-- async updatePolicy(- organizationId: number,- policyId: number,- body: { name: string; definition: PolicyDefinition }- ) {- await api.put(`/organizations/${organizationId}/escalation-policies/${policyId}`, body);- await this.loadPolicies(organizationId);- }-- async deletePolicy(organizationId: number, policyId: number) {- await api.delete(`/organizations/${organizationId}/escalation-policies/${policyId}`);- await this.loadPolicies(organizationId);- }+ teams = $state<Team[]>([]);+ teamsLoading = $state(false);+ teamsError = $state('');+ schedules = $state<Schedule[]>([]);+ schedulesLoading = $state(false);+ schedulesError = $state('');+ overview = $state<OverviewTeam[]>([]);+ overviewLoading = $state(false);+ overviewError = $state('');+ policies = $state<EscalationPolicy[]>([]);+ policiesLoading = $state(false);+ policiesError = $state('');+ openPagesCount = $state(0);++ canManage(organizationId: number): boolean {+ return authState.canManageOrganization(organizationId);+ }++ async refreshOpenCount() {+ try {+ const res = await api.get('/pages/open-count', {+ projectId: projectsState.currentProjectId ?? undefined+ });+ this.openPagesCount = res.count ?? 0;+ } catch {+ // badge stays at its last value+ }+ }++ async loadTeams(organizationId: number) {+ this.teamsLoading = true;+ this.teamsError = '';+ try {+ const res = await api.get(`/organizations/${organizationId}/teams`);+ this.teams = res.teams || [];+ } catch (e: unknown) {+ this.teamsError = e instanceof Error ? e.message : 'Failed to load teams';+ this.teams = [];+ } finally {+ this.teamsLoading = false;+ }+ }++ async loadSchedules(organizationId: number) {+ this.schedulesLoading = true;+ this.schedulesError = '';+ try {+ const res = await api.get(`/organizations/${organizationId}/schedules`);+ this.schedules = res.schedules || [];+ } catch (e: unknown) {+ this.schedulesError = e instanceof Error ? e.message : 'Failed to load schedules';+ this.schedules = [];+ } finally {+ this.schedulesLoading = false;+ }+ }++ async loadOverview(organizationId: number) {+ this.overviewLoading = true;+ this.overviewError = '';+ try {+ const res = await api.get(`/organizations/${organizationId}/oncall/now`);+ this.overview = res.teams || [];+ } catch (e: unknown) {+ this.overviewError = e instanceof Error ? e.message : 'Failed to load who is on call';+ this.overview = [];+ } finally {+ this.overviewLoading = false;+ }+ }++ async createTeam(+ organizationId: number,+ body: { name: string; description: string; memberUserIds: number[]; projectIds: string[] }+ ) {+ const team = await api.post(`/organizations/${organizationId}/teams`, body);+ await this.loadTeams(organizationId);+ return team;+ }++ async updateTeam(+ organizationId: number,+ teamId: number,+ body: {+ name: string;+ description: string;+ memberUserIds?: number[];+ projectIds?: string[];+ }+ ) {+ await api.put(`/organizations/${organizationId}/teams/${teamId}`, body);+ }++ async updateTeamMembers(organizationId: number, teamId: number, userIds: number[]) {+ await api.put(`/organizations/${organizationId}/teams/${teamId}/members`, { userIds });+ }++ async updateTeamProjects(organizationId: number, teamId: number, projectIds: string[]) {+ await api.put(`/organizations/${organizationId}/teams/${teamId}/projects`, { projectIds });+ }++ async deleteTeam(organizationId: number, teamId: number) {+ await api.delete(`/organizations/${organizationId}/teams/${teamId}`);+ await this.loadTeams(organizationId);+ }++ async createSchedule(+ organizationId: number,+ body: {+ teamId: number;+ name: string;+ description: string;+ timezone: string;+ definition: ScheduleDefinition;+ }+ ) {+ const schedule = await api.post(`/organizations/${organizationId}/schedules`, body);+ await this.loadSchedules(organizationId);+ return schedule;+ }++ async updateSchedule(+ organizationId: number,+ scheduleId: number,+ body: {+ teamId: number;+ name: string;+ description: string;+ timezone: string;+ definition: ScheduleDefinition;+ }+ ) {+ await api.put(`/organizations/${organizationId}/schedules/${scheduleId}`, body);+ await this.loadSchedules(organizationId);+ }++ async deleteSchedule(organizationId: number, scheduleId: number) {+ await api.delete(`/organizations/${organizationId}/schedules/${scheduleId}`);+ await this.loadSchedules(organizationId);+ }++ async getSchedule(+ organizationId: number,+ scheduleId: number+ ): Promise<{ schedule: Schedule; overrides: ScheduleOverride[] }> {+ return await api.get(`/organizations/${organizationId}/schedules/${scheduleId}`);+ }++ async getTimeline(+ organizationId: number,+ scheduleId: number,+ from: string,+ to: string+ ): Promise<TimelineResponse> {+ return await api.get(+ `/organizations/${organizationId}/schedules/${scheduleId}/timeline?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`+ );+ }++ async createOverride(+ organizationId: number,+ scheduleId: number,+ body: { userId: number; startAt: string; endAt: string }+ ) {+ return await api.post(+ `/organizations/${organizationId}/schedules/${scheduleId}/overrides`,+ body+ );+ }++ async deleteOverride(organizationId: number, scheduleId: number, overrideId: number) {+ await api.delete(+ `/organizations/${organizationId}/schedules/${scheduleId}/overrides/${overrideId}`+ );+ }++ async getMembers(organizationId: number): Promise<OrgMember[]> {+ return await api.get(`/organizations/${organizationId}/members`);+ }++ async loadPolicies(organizationId: number) {+ this.policiesLoading = true;+ this.policiesError = '';+ try {+ const res = await api.get(`/organizations/${organizationId}/escalation-policies`);+ this.policies = res.policies || [];+ } catch (e: unknown) {+ this.policiesError = e instanceof Error ? e.message : 'Failed to load escalation policies';+ this.policies = [];+ } finally {+ this.policiesLoading = false;+ }+ }++ async createPolicy(organizationId: number, body: { name: string; definition: PolicyDefinition }) {+ const policy = await api.post(`/organizations/${organizationId}/escalation-policies`, body);+ await this.loadPolicies(organizationId);+ return policy;+ }++ async updatePolicy(+ organizationId: number,+ policyId: number,+ body: { name: string; definition: PolicyDefinition }+ ) {+ await api.put(`/organizations/${organizationId}/escalation-policies/${policyId}`, body);+ await this.loadPolicies(organizationId);+ }++ async deletePolicy(organizationId: number, policyId: number) {+ await api.delete(`/organizations/${organizationId}/escalation-policies/${policyId}`);+ await this.loadPolicies(organizationId);+ }}export const oncallState = new OncallState();diff --git a/frontend/src/lib/state/organization.svelte.ts b/frontend/src/lib/state/organization.svelte.tsindex 107b86be..104c1ba4 100644--- a/frontend/src/lib/state/organization.svelte.ts+++ b/frontend/src/lib/state/organization.svelte.ts@@ -1,133 +1,152 @@import { api } from '$lib/api';export interface Organization {- id: number;- name: string;- timezone: string;- createdAt: string;+ id: number;+ name: string;+ timezone: string;+ createdAt: string;}export interface OrganizationMember {- id: number;- email: string;- name: string;- role: string;- createdAt: string;+ id: number;+ email: string;+ name: string;+ role: string;+ createdAt: string;}export interface Invitation {- id: number;- organizationId: number;- email: string;- role: string;- invitedBy: number;- inviterName: string;- status: string;- expiresAt: string;- acceptedAt?: string;- createdAt: string;+ id: number;+ organizationId: number;+ email: string;+ role: string;+ invitedBy: number;+ inviterName: string;+ status: string;+ expiresAt: string;+ acceptedAt?: string;+ createdAt: string;}export interface OrganizationSettings {- organization: Organization;- members: OrganizationMember[];- invitations: Invitation[];- userRole: string;+ organization: Organization;+ members: OrganizationMember[];+ invitations: Invitation[];+ userRole: string;}export interface MemberProjectRole {- projectId: string;- name: string;- framework: string;- role: string | null;+ projectId: string;+ name: string;+ framework: string;+ role: string | null;}export interface MemberProjectRolesResponse {- orgRole: string;- projectRoles: MemberProjectRole[];+ orgRole: string;+ projectRoles: MemberProjectRole[];}class OrganizationState {- currentOrganization = $state<Organization | null>(null);- members = $state<OrganizationMember[]>([]);- invitations = $state<Invitation[]>([]);- loading = $state(false);- error = $state<string | null>(null);- userRole = $state<string | null>(null);-- isOwner = $derived(this.userRole === 'owner');- isAdmin = $derived(this.userRole === 'admin');- canManage = $derived(this.userRole === 'owner' || this.userRole === 'admin');- memberCount = $derived(this.members.length + this.invitations.filter(i => i.status === 'pending').length);- canInvite = $derived(this.memberCount < 10);-- private loadSeq = 0;-- async loadSettings(organizationId: number) {- const seq = ++this.loadSeq;- this.loading = true;- this.error = null;-- try {- const response: OrganizationSettings = await api.get(`/organizations/${organizationId}/settings`);- if (seq !== this.loadSeq) return;- this.currentOrganization = response.organization;- this.members = response.members;- this.invitations = response.invitations;- this.userRole = response.userRole;- } catch (e: unknown) {- if (seq !== this.loadSeq) return;- this.error = e instanceof Error ? e.message : 'Failed to load settings';- } finally {- if (seq === this.loadSeq) {- this.loading = false;- }- }- }-- async inviteUser(organizationId: number, email: string, role: string) {- const response = await api.post(`/organizations/${organizationId}/invitations`, { email, role });- await this.loadSettings(organizationId);- return response;- }-- async revokeInvitation(organizationId: number, invitationId: number) {- await api.delete(`/organizations/${organizationId}/invitations/${invitationId}`);- await this.loadSettings(organizationId);- }-- async updateMemberRole(organizationId: number, userId: number, role: string) {- await api.put(`/organizations/${organizationId}/members/${userId}`, { role });- await this.loadSettings(organizationId);- }-- async removeMember(organizationId: number, userId: number) {- await api.delete(`/organizations/${organizationId}/members/${userId}`);- await this.loadSettings(organizationId);- }-- async getMemberProjectRoles(organizationId: number, userId: number): Promise<MemberProjectRolesResponse> {- return await api.get(`/organizations/${organizationId}/members/${userId}/project-roles`) as MemberProjectRolesResponse;- }-- async updateMemberProjectRole(organizationId: number, userId: number, projectId: string, role: string) {- await api.put(`/organizations/${organizationId}/members/${userId}/project-roles/${projectId}`, { role });- }-- async updateTimezone(organizationId: number, timezone: string) {- await api.put(`/organizations/${organizationId}/settings`, { timezone });- if (this.currentOrganization) {- this.currentOrganization = { ...this.currentOrganization, timezone };- }- }-- clear() {- this.currentOrganization = null;- this.members = [];- this.invitations = [];- this.userRole = null;- this.error = null;- }+ currentOrganization = $state<Organization | null>(null);+ members = $state<OrganizationMember[]>([]);+ invitations = $state<Invitation[]>([]);+ loading = $state(false);+ error = $state<string | null>(null);+ userRole = $state<string | null>(null);++ isOwner = $derived(this.userRole === 'owner');+ isAdmin = $derived(this.userRole === 'admin');+ canManage = $derived(this.userRole === 'owner' || this.userRole === 'admin');+ memberCount = $derived(+ this.members.length + this.invitations.filter((i) => i.status === 'pending').length+ );+ canInvite = $derived(this.memberCount < 10);++ private loadSeq = 0;++ async loadSettings(organizationId: number) {+ const seq = ++this.loadSeq;+ this.loading = true;+ this.error = null;++ try {+ const response: OrganizationSettings = await api.get(+ `/organizations/${organizationId}/settings`+ );+ if (seq !== this.loadSeq) return;+ this.currentOrganization = response.organization;+ this.members = response.members;+ this.invitations = response.invitations;+ this.userRole = response.userRole;+ } catch (e: unknown) {+ if (seq !== this.loadSeq) return;+ this.error = e instanceof Error ? e.message : 'Failed to load settings';+ } finally {+ if (seq === this.loadSeq) {+ this.loading = false;+ }+ }+ }++ async inviteUser(organizationId: number, email: string, role: string) {+ const response = await api.post(`/organizations/${organizationId}/invitations`, {+ email,+ role+ });+ await this.loadSettings(organizationId);+ return response;+ }++ async revokeInvitation(organizationId: number, invitationId: number) {+ await api.delete(`/organizations/${organizationId}/invitations/${invitationId}`);+ await this.loadSettings(organizationId);+ }++ async updateMemberRole(organizationId: number, userId: number, role: string) {+ await api.put(`/organizations/${organizationId}/members/${userId}`, { role });+ await this.loadSettings(organizationId);+ }++ async removeMember(organizationId: number, userId: number) {+ await api.delete(`/organizations/${organizationId}/members/${userId}`);+ await this.loadSettings(organizationId);+ }++ async getMemberProjectRoles(+ organizationId: number,+ userId: number+ ): Promise<MemberProjectRolesResponse> {+ return (await api.get(+ `/organizations/${organizationId}/members/${userId}/project-roles`+ )) as MemberProjectRolesResponse;+ }++ async updateMemberProjectRole(+ organizationId: number,+ userId: number,+ projectId: string,+ role: string+ ) {+ await api.put(`/organizations/${organizationId}/members/${userId}/project-roles/${projectId}`, {+ role+ });+ }++ async updateTimezone(organizationId: number, timezone: string) {+ await api.put(`/organizations/${organizationId}/settings`, { timezone });+ if (this.currentOrganization) {+ this.currentOrganization = { ...this.currentOrganization, timezone };+ }+ }++ clear() {+ this.currentOrganization = null;+ this.members = [];+ this.invitations = [];+ this.userRole = null;+ this.error = null;+ }}export const organizationState = new OrganizationState();diff --git a/frontend/src/lib/state/personal-access-tokens.svelte.ts b/frontend/src/lib/state/personal-access-tokens.svelte.tsindex e5f32521..b265450a 100644--- a/frontend/src/lib/state/personal-access-tokens.svelte.ts+++ b/frontend/src/lib/state/personal-access-tokens.svelte.ts@@ -36,7 +36,10 @@ class PersonalAccessTokensState {}async create(name: string, expiresInDays: number | null): Promise<CreatedToken> {- const res = (await api.post('/personal-access-tokens', { name, expiresInDays })) as CreatedToken;+ const res = (await api.post('/personal-access-tokens', {+ name,+ expiresInDays+ })) as CreatedToken;await this.load();return res;}diff --git a/frontend/src/lib/state/projects.svelte.ts b/frontend/src/lib/state/projects.svelte.tsindex 5e364843..15ff3ed9 100644--- a/frontend/src/lib/state/projects.svelte.ts+++ b/frontend/src/lib/state/projects.svelte.ts@@ -1,10 +1,53 @@import { api } from '$lib/api';import { authState } from './auth.svelte';-export type Framework = 'gin' | 'fiber' | 'chi' | 'fasthttp' | 'stdlib' | 'custom' | 'react' | 'svelte' | 'vuejs' | 'nextjs' | 'nestjs' | 'express' | 'remix' | 'jquery' | 'react-native' | 'hono' | 'cloudflare' | 'opentelemetry' | 'symfony' | 'laravel' | 'django' | 'flutter' | 'android' | 'ios';--export const FRONTEND_FRAMEWORKS: Framework[] = ['react', 'svelte', 'vuejs', 'jquery', 'react-native', 'flutter', 'android', 'ios'];-export const JS_FRAMEWORKS: Framework[] = ['react', 'svelte', 'vuejs', 'nextjs', 'nestjs', 'express', 'remix', 'jquery', 'react-native'];+export type Framework =+ | 'gin'+ | 'fiber'+ | 'chi'+ | 'fasthttp'+ | 'stdlib'+ | 'custom'+ | 'react'+ | 'svelte'+ | 'vuejs'+ | 'nextjs'+ | 'nestjs'+ | 'express'+ | 'remix'+ | 'jquery'+ | 'react-native'+ | 'hono'+ | 'cloudflare'+ | 'opentelemetry'+ | 'symfony'+ | 'laravel'+ | 'django'+ | 'flutter'+ | 'android'+ | 'ios';++export const FRONTEND_FRAMEWORKS: Framework[] = [+ 'react',+ 'svelte',+ 'vuejs',+ 'jquery',+ 'react-native',+ 'flutter',+ 'android',+ 'ios'+];+export const JS_FRAMEWORKS: Framework[] = [+ 'react',+ 'svelte',+ 'vuejs',+ 'nextjs',+ 'nestjs',+ 'express',+ 'remix',+ 'jquery',+ 'react-native'+];export const FRAMEWORK_LABELS: Record<Framework, string> = {gin: 'Gin',@@ -30,7 +73,7 @@ export const FRAMEWORK_LABELS: Record<Framework, string> = {django: 'Django',flutter: 'Flutter',android: 'Android',- ios: 'iOS',+ ios: 'iOS'};export const MOBILE_FRAMEWORKS: Framework[] = ['flutter', 'android', 'ios'];@@ -70,144 +113,175 @@ export function isCloudflareFramework(fw: Framework): boolean {}export interface Project {- id: string;- name: string;- token: string;- framework: Framework;- organizationId: number | null;- createdAt: string;- sourceMapToken: string | null;- backendUrl: string;- dropHealthyHealthchecks: boolean;- healthcheckPaths: string[] | null;- profileLabelAllowlist: string[] | null;- aiFlaggedTerms: string[] | null;- aiFlaggedLanguages: string[] | null;- role?: string;+ id: string;+ name: string;+ token: string;+ framework: Framework;+ organizationId: number | null;+ createdAt: string;+ sourceMapToken: string | null;+ backendUrl: string;+ dropHealthyHealthchecks: boolean;+ healthcheckPaths: string[] | null;+ profileLabelAllowlist: string[] | null;+ aiFlaggedTerms: string[] | null;+ aiFlaggedLanguages: string[] | null;+ role?: string;}export function isProjectReadonly(project: Project | null): boolean {- if (!project) return false;- if (project.role) return project.role === 'readonly';- if (!project.organizationId) return false;- return authState.getRoleForOrganization(project.organizationId) === 'readonly';+ if (!project) return false;+ if (project.role) return project.role === 'readonly';+ if (!project.organizationId) return false;+ return authState.getRoleForOrganization(project.organizationId) === 'readonly';}export interface ProjectWithToken extends Project {- token: string;+ token: string;}const PROJECTS_CACHE_KEY = 'PROJECTS_CACHE_V2';class ProjectsState {- projects = $state<Project[]>(- JSON.parse(localStorage.getItem(PROJECTS_CACHE_KEY) || '[]')- );- currentProjectId = $state<string | null>(localStorage.getItem('CURRENT_PROJECT_ID'));- loading = $state(false);- error = $state<string | null>(null);-- currentProject = $derived(- this.projects.find(p => p.id === this.currentProjectId) || this.projects[0] || null- );-- canManageCurrentProject = $derived.by(() => {- const organizationId = this.currentProject?.organizationId;- if (!organizationId) return false;- return authState.canManageOrganization(organizationId);- });-- canWriteCurrentProject = $derived(!isProjectReadonly(this.currentProject));-- constructor() {- $effect.root(() => {- $effect(() => {- if (this.currentProjectId) {- localStorage.setItem('CURRENT_PROJECT_ID', this.currentProjectId);- } else {- localStorage.removeItem('CURRENT_PROJECT_ID');- }- });- });- }-- setProjects(projects: Project[]) {- this.projects = projects;-- // If no current project selected or current project not in list, select first one- if (!this.currentProjectId || !this.projects.find(p => p.id === this.currentProjectId)) {- if (this.projects.length > 0) {- this.currentProjectId = this.projects[0].id;- }- }-- // Cache in localStorage- localStorage.setItem(PROJECTS_CACHE_KEY, JSON.stringify(this.projects));- }-- async loadProjects() {- this.loading = true;- this.error = null;-- try {- const response = await api.get('/projects');- this.setProjects(response)- } catch (e: unknown) {- const errorMessage = e instanceof Error ? e.message : 'Failed to load projects';- this.error = errorMessage;-- // Try to load from cache- const cached = localStorage.getItem(PROJECTS_CACHE_KEY);- if (cached) {- this.projects = JSON.parse(cached);- }- } finally {- this.loading = false;- }- }-- async createProject(name: string, framework: Framework = 'gin', organizationId?: number): Promise<ProjectWithToken> {- const response = await api.post('/projects', { name, framework, organizationId }, {- projectId: this.currentProjectId ?? undefined- });-- // Reload projects to refresh cache- await this.loadProjects();-- return response;- }-- async updateProject(id: string, name: string, framework: Framework, dropHealthyHealthchecks: boolean, healthcheckPaths: string[], profileLabelAllowlist: string[], aiFlaggedTerms: string[], aiFlaggedLanguages: string[]): Promise<Project> {- const response = await api.put('/projects', { name, framework, dropHealthyHealthchecks, healthcheckPaths, profileLabelAllowlist, aiFlaggedTerms, aiFlaggedLanguages }, {- projectId: id- });- await this.loadProjects();- return response;- }-- async deleteProject(id: string, name: string): Promise<void> {- await api.delete('/projects', { projectId: id }, { name });- await this.loadProjects();- }-- async generateSourceMapToken(): Promise<string> {- const resp = await api.post('/projects/source-map-token', {}, {- projectId: this.currentProjectId ?? undefined- });- await this.loadProjects();- return resp.sourceMapToken;- }-- selectProject(projectId: string) {- this.currentProjectId = projectId;- }-- initFromCache() {- const cached = localStorage.getItem(PROJECTS_CACHE_KEY);- if (cached) {- this.projects = JSON.parse(cached);- }- }+ projects = $state<Project[]>(JSON.parse(localStorage.getItem(PROJECTS_CACHE_KEY) || '[]'));+ currentProjectId = $state<string | null>(localStorage.getItem('CURRENT_PROJECT_ID'));+ loading = $state(false);+ error = $state<string | null>(null);++ currentProject = $derived(+ this.projects.find((p) => p.id === this.currentProjectId) || this.projects[0] || null+ );++ canManageCurrentProject = $derived.by(() => {+ const organizationId = this.currentProject?.organizationId;+ if (!organizationId) return false;+ return authState.canManageOrganization(organizationId);+ });++ canWriteCurrentProject = $derived(!isProjectReadonly(this.currentProject));++ constructor() {+ $effect.root(() => {+ $effect(() => {+ if (this.currentProjectId) {+ localStorage.setItem('CURRENT_PROJECT_ID', this.currentProjectId);+ } else {+ localStorage.removeItem('CURRENT_PROJECT_ID');+ }+ });+ });+ }++ setProjects(projects: Project[]) {+ this.projects = projects;++ // If no current project selected or current project not in list, select first one+ if (!this.currentProjectId || !this.projects.find((p) => p.id === this.currentProjectId)) {+ if (this.projects.length > 0) {+ this.currentProjectId = this.projects[0].id;+ }+ }++ // Cache in localStorage+ localStorage.setItem(PROJECTS_CACHE_KEY, JSON.stringify(this.projects));+ }++ async loadProjects() {+ this.loading = true;+ this.error = null;++ try {+ const response = await api.get('/projects');+ this.setProjects(response);+ } catch (e: unknown) {+ const errorMessage = e instanceof Error ? e.message : 'Failed to load projects';+ this.error = errorMessage;++ // Try to load from cache+ const cached = localStorage.getItem(PROJECTS_CACHE_KEY);+ if (cached) {+ this.projects = JSON.parse(cached);+ }+ } finally {+ this.loading = false;+ }+ }++ async createProject(+ name: string,+ framework: Framework = 'gin',+ organizationId?: number+ ): Promise<ProjectWithToken> {+ const response = await api.post(+ '/projects',+ { name, framework, organizationId },+ {+ projectId: this.currentProjectId ?? undefined+ }+ );++ // Reload projects to refresh cache+ await this.loadProjects();++ return response;+ }++ async updateProject(+ id: string,+ name: string,+ framework: Framework,+ dropHealthyHealthchecks: boolean,+ healthcheckPaths: string[],+ profileLabelAllowlist: string[],+ aiFlaggedTerms: string[],+ aiFlaggedLanguages: string[]+ ): Promise<Project> {+ const response = await api.put(+ '/projects',+ {+ name,+ framework,+ dropHealthyHealthchecks,+ healthcheckPaths,+ profileLabelAllowlist,+ aiFlaggedTerms,+ aiFlaggedLanguages+ },+ {+ projectId: id+ }+ );+ await this.loadProjects();+ return response;+ }++ async deleteProject(id: string, name: string): Promise<void> {+ await api.delete('/projects', { projectId: id }, { name });+ await this.loadProjects();+ }++ async generateSourceMapToken(): Promise<string> {+ const resp = await api.post(+ '/projects/source-map-token',+ {},+ {+ projectId: this.currentProjectId ?? undefined+ }+ );+ await this.loadProjects();+ return resp.sourceMapToken;+ }++ selectProject(projectId: string) {+ this.currentProjectId = projectId;+ }++ initFromCache() {+ const cached = localStorage.getItem(PROJECTS_CACHE_KEY);+ if (cached) {+ this.projects = JSON.parse(cached);+ }+ }}export const projectsState = new ProjectsState();diff --git a/frontend/src/lib/state/theme.svelte.ts b/frontend/src/lib/state/theme.svelte.tsindex 712a3040..4ea92002 100644--- a/frontend/src/lib/state/theme.svelte.ts+++ b/frontend/src/lib/state/theme.svelte.ts@@ -1,5 +1,5 @@export const themeState = $state({- isDark: true+ isDark: true});// app.html ships <html> with an anti-FOUC inline `background: #05070c` so the@@ -8,39 +8,39 @@ export const themeState = $state({// script) or a stale dark backdrop bleeds through wherever content does not// paint over <html>.function applyTheme(isDark: boolean) {- document.documentElement.classList.toggle('dark', isDark);- document.documentElement.style.colorScheme = isDark ? 'dark' : 'light';- document.documentElement.style.background = isDark ? '#05070c' : '';+ document.documentElement.classList.toggle('dark', isDark);+ document.documentElement.style.colorScheme = isDark ? 'dark' : 'light';+ document.documentElement.style.background = isDark ? '#05070c' : '';}export function initTheme() {- if (typeof document !== 'undefined') {- const stored = localStorage.getItem('traceway_theme');+ if (typeof document !== 'undefined') {+ const stored = localStorage.getItem('traceway_theme');- if (stored === 'dark' || stored === 'light') {- themeState.isDark = stored === 'dark';- } else {- themeState.isDark = true;- }+ if (stored === 'dark' || stored === 'light') {+ themeState.isDark = stored === 'dark';+ } else {+ themeState.isDark = true;+ }- applyTheme(themeState.isDark);+ applyTheme(themeState.isDark);- const observer = new MutationObserver(() => {- themeState.isDark = document.documentElement.classList.contains('dark');- });- observer.observe(document.documentElement, {- attributes: true,- attributeFilter: ['class']- });+ const observer = new MutationObserver(() => {+ themeState.isDark = document.documentElement.classList.contains('dark');+ });+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class']+ });- return () => {- observer.disconnect();- };- }+ return () => {+ observer.disconnect();+ };+ }}export function toggleTheme() {- themeState.isDark = !themeState.isDark;- applyTheme(themeState.isDark);- localStorage.setItem('traceway_theme', themeState.isDark ? 'dark' : 'light');+ themeState.isDark = !themeState.isDark;+ applyTheme(themeState.isDark);+ localStorage.setItem('traceway_theme', themeState.isDark ? 'dark' : 'light');}diff --git a/frontend/src/lib/types/dashboard.ts b/frontend/src/lib/types/dashboard.tsindex 2cf48ccc..5ca73a32 100644--- a/frontend/src/lib/types/dashboard.ts+++ b/frontend/src/lib/types/dashboard.ts@@ -89,3 +89,34 @@ export type MetricQueryResponse = {};export type ExplorerMetricsTab = 'application' | 'stats' | 'server' | 'explorer';++export type DashboardWidgetSource = {+ type: 'metric';+ name: string;+ aggregation: string;+ tagFilters?: Record<string, string>;+ groupBy?: string;+ label?: string;+};++export type DashboardWidgetConfig = {+ sources?: DashboardWidgetSource[];+ yAxisLabel?: string;+ showLegend?: boolean;+ unit?: string;+ colSpan?: number;+ size?: string;+ showSparkline?: boolean;+ min?: number;+ max?: number;+ baseColor?: string;+ thresholds?: Array<{ value: number; color: string }>;+ [key: string]: unknown;+};++export type DashboardWidget = {+ id: number | string;+ title: string;+ widgetType: string;+ config: DashboardWidgetConfig;+};diff --git a/frontend/src/lib/types/distributed-trace.ts b/frontend/src/lib/types/distributed-trace.tsindex e22d8eae..dad8a70e 100644--- a/frontend/src/lib/types/distributed-trace.ts+++ b/frontend/src/lib/types/distributed-trace.ts@@ -25,7 +25,7 @@ export type DistributedTraceNode = {totalCost: number;recordedAt: string;};- spans: any[];+ spans: Span[];exception?: {exceptionHash: string;stackTrace: string;@@ -37,3 +37,4 @@ export type DistributedTraceResponse = {distributedTraceId: string;nodes: DistributedTraceNode[];};+import type { Span } from '$lib/types/spans';diff --git a/frontend/src/lib/types/exceptions.ts b/frontend/src/lib/types/exceptions.tsindex 92b22d64..0b7e72f9 100644--- a/frontend/src/lib/types/exceptions.ts+++ b/frontend/src/lib/types/exceptions.ts@@ -1,34 +1,34 @@export type ExceptionGroup = {- exceptionHash: string;- stackTrace: string;- lastSeen: string;- firstSeen: string;- count: number;+ exceptionHash: string;+ stackTrace: string;+ lastSeen: string;+ firstSeen: string;+ count: number;};export type ExceptionOccurrence = {- id: string;- traceId: string | null;- traceType: 'endpoint' | 'task';- exceptionHash: string;- stackTrace: string;- recordedAt: string;- attributes: Record<string, string> | null;- appVersion: string;- serverName: string;- isMessage: boolean;- endpoint: string;- distributedTraceId?: string;+ id: string;+ traceId: string | null;+ traceType: 'endpoint' | 'task';+ exceptionHash: string;+ stackTrace: string;+ recordedAt: string;+ attributes: Record<string, string> | null;+ appVersion: string;+ serverName: string;+ isMessage: boolean;+ endpoint: string;+ distributedTraceId?: string;};export type LinkedTrace = {- id: string;- endpoint: string;- duration: number;- statusCode: number;- recordedAt: string;- traceType: 'endpoint' | 'task';- distributedTraceId?: string;+ id: string;+ endpoint: string;+ duration: number;+ statusCode: number;+ recordedAt: string;+ traceType: 'endpoint' | 'task';+ distributedTraceId?: string;};// Session recording shape returned by the backend's exception detail endpoints.@@ -37,55 +37,63 @@ export type LinkedTrace = {export type SessionLogLevel = 'debug' | 'info' | 'warn' | 'error';export interface SessionLogEvent {- type: 'log';- timestamp: string;- level: SessionLogLevel;- message: string;+ type: 'log';+ timestamp: string;+ level: SessionLogLevel;+ message: string;}export interface SessionNetworkEvent {- type: 'network';- timestamp: string;- method: string;- url: string;- durationMs: number;- statusCode?: number;- requestBytes?: number;- responseBytes?: number;- error?: string;+ type: 'network';+ timestamp: string;+ method: string;+ url: string;+ durationMs: number;+ statusCode?: number;+ requestBytes?: number;+ responseBytes?: number;+ error?: string;}export interface SessionNavigationEvent {- type: 'navigation';- timestamp: string;- /** push | pop | replace | remove */- action: string;- from?: string;- to?: string;+ type: 'navigation';+ timestamp: string;+ /** push | pop | replace | remove */+ action: string;+ from?: string;+ to?: string;}export interface SessionCustomEvent {- type: 'custom';- timestamp: string;- category: string;- name: string;- data?: Record<string, unknown>;+ type: 'custom';+ timestamp: string;+ category: string;+ name: string;+ data?: Record<string, unknown>;}-export type SessionActionEvent =- | SessionNetworkEvent- | SessionNavigationEvent- | SessionCustomEvent;+export type SessionActionEvent = SessionNetworkEvent | SessionNavigationEvent | SessionCustomEvent;++export interface FlutterVideoEvent {+ type: 'flutter_video';+ data: string;+ format: string;+ fps: number;+ durationSeconds: number;+}++export type SessionReplayEvent = (eventWithTime & { data?: { href?: string } }) | FlutterVideoEvent;export interface SessionRecording {- /** rrweb events (web SDKs) or MP4 chunk descriptors (Flutter SDK). */- events?: unknown[];- /** Console output snapshotted at exception capture (last ~10s, ≤200). */- logs?: SessionLogEvent[];- /** Network / navigation / custom actions snapshotted with the exception. */- actions?: SessionActionEvent[];- /** ISO 8601 timestamp of the first frame / first event. */- startedAt?: string;- /** ISO 8601 timestamp of the last frame / last event. */- endedAt?: string;+ /** rrweb events (web SDKs) or MP4 chunk descriptors (Flutter SDK). */+ events?: SessionReplayEvent[];+ /** Console output snapshotted at exception capture (last ~10s, ≤200). */+ logs?: SessionLogEvent[];+ /** Network / navigation / custom actions snapshotted with the exception. */+ actions?: SessionActionEvent[];+ /** ISO 8601 timestamp of the first frame / first event. */+ startedAt?: string;+ /** ISO 8601 timestamp of the last frame / last event. */+ endedAt?: string;}+import type { eventWithTime } from '@rrweb/types';diff --git a/frontend/src/lib/types/notifications.ts b/frontend/src/lib/types/notifications.tsnew file mode 100644index 00000000..4efda066--- /dev/null+++ b/frontend/src/lib/types/notifications.ts@@ -0,0 +1,52 @@+export type NotificationChannelConfig = {+ recipients?: string[];+ url?: string;+ method?: string;+ secret?: string;+ headers?: Record<string, string>;+ webhookUrl?: string;+ channel?: string;+ username?: string;+ token?: string;+ owner?: string;+ repo?: string;+ labels?: string[];+ userKey?: string;+ appToken?: string;+ device?: string;+ priority?: number;+ retry?: number;+ expire?: number;+ callback?: string;+ sound?: string;+ html?: boolean;+ ttl?: number;+ botToken?: string;+ chatId?: string;+ policyId?: number | null;+};++export type NotificationRuleConfig = {+ thresholdPercent?: number;+ lookbackMinutes?: number;+ minRequests?: number;+ endpoint?: string;+ thresholdMs?: number;+ thresholdApdex?: number;+ metricName?: string;+ operator?: string;+ thresholdValue?: number;+ aggregation?: string;+ tags?: Record<string, string>;+ dataType?: string;+ silenceMinutes?: number;+ thresholdCount?: number;+ taskName?: string;+ minExecutions?: number;+ dropPercent?: number;+ baselineWindowMinutes?: number;+ ignorePatterns?: string[];+ traceName?: string;+ thresholdCost?: number;+ terms?: string[];+};diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.tsindex 55b3a918..2e631394 100644--- a/frontend/src/lib/utils.ts+++ b/frontend/src/lib/utils.ts@@ -1,13 +1,11 @@-import { clsx, type ClassValue } from "clsx";-import { twMerge } from "tailwind-merge";+import { clsx, type ClassValue } from 'clsx';+import { twMerge } from 'tailwind-merge';export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs));}-// eslint-disable-next-line @typescript-eslint/no-explicit-any-export type WithoutChild<T> = T extends { child?: any } ? Omit<T, "child"> : T;-// eslint-disable-next-line @typescript-eslint/no-explicit-any-export type WithoutChildren<T> = T extends { children?: any } ? Omit<T, "children"> : T;+export type WithoutChild<T> = T extends { child?: unknown } ? Omit<T, 'child'> : T;+export type WithoutChildren<T> = T extends { children?: unknown } ? Omit<T, 'children'> : T;export type WithoutChildrenOrChild<T> = WithoutChildren<WithoutChild<T>>;export type WithElementRef<T, U extends HTMLElement = HTMLElement> = T & { ref?: U | null };diff --git a/frontend/src/lib/utils/ai-conversation.ts b/frontend/src/lib/utils/ai-conversation.tsindex 9a0b6d57..51b02927 100644--- a/frontend/src/lib/utils/ai-conversation.ts+++ b/frontend/src/lib/utils/ai-conversation.ts@@ -1,194 +1,230 @@export type ContentPart = {- type: string;- text?: string;- image_url?: { url: string };+ type: string;+ text?: string;+ image_url?: { url: string };};export type ToolCall = {- id?: string;- name: string;- arguments: string;+ id?: string;+ name: string;+ arguments: string;};export type ChatMessage = {- role: string;- content: string | ContentPart[];- toolCalls?: ToolCall[];- toolCallId?: string;+ role: string;+ content: string | ContentPart[];+ toolCalls?: ToolCall[];+ toolCallId?: string;};export type ConversationTurn = {- id: string;- traceName: string;- recordedAt: string;- duration: number;- model: string;- totalTokens: number;- totalCost: number;- input: string;- output: string;+ id: string;+ traceName: string;+ recordedAt: string;+ duration: number;+ model: string;+ totalTokens: number;+ totalCost: number;+ input: string;+ output: string;};export type TimelineEntry =- | { kind: 'message'; message: ChatMessage }- | { kind: 'turn-meta'; turn: ConversationTurn };--export function tryParseJson(str: string): any {- try {- return JSON.parse(str);- } catch {- return null;- }+ | { kind: 'message'; message: ChatMessage }+ | { kind: 'turn-meta'; turn: ConversationTurn };++type JsonRecord = Record<string, unknown>;++function isRecord(value: unknown): value is JsonRecord {+ return typeof value === 'object' && value !== null && !Array.isArray(value);}-function normalizeOpenAiToolCalls(rawCalls: any): ToolCall[] | undefined {- if (!Array.isArray(rawCalls) || rawCalls.length === 0) return undefined;- const calls: ToolCall[] = [];- for (const call of rawCalls) {- const name = call?.function?.name ?? call?.name;- if (!name) continue;- const args = call?.function?.arguments ?? call?.arguments ?? '';- calls.push({- id: call?.id,- name,- arguments: typeof args === 'string' ? args : JSON.stringify(args)- });- }- return calls.length > 0 ? calls : undefined;+function asString(value: unknown): string | undefined {+ return typeof value === 'string' ? value : undefined;}-function normalizeInputMessage(msg: any): ChatMessage | null {- if (!msg?.role) return null;-- // Anthropic-style content blocks may carry tool_use / tool_result parts.- if (Array.isArray(msg.content)) {- const toolCalls: ToolCall[] = [];- let toolCallId: string | undefined;- const parts: ContentPart[] = [];- for (const part of msg.content) {- if (part?.type === 'tool_use' && part.name) {- toolCalls.push({- id: part.id,- name: part.name,- arguments: JSON.stringify(part.input ?? {})- });- } else if (part?.type === 'tool_result') {- toolCallId = part.tool_use_id;- const inner = part.content;- if (typeof inner === 'string') {- parts.push({ type: 'text', text: inner });- } else if (Array.isArray(inner)) {- for (const innerPart of inner) {- if (innerPart?.type === 'text' && innerPart.text) {- parts.push({ type: 'text', text: innerPart.text });- }- }- }- } else if (part?.type) {- parts.push(part);- }- }- const message: ChatMessage = {- role: toolCallId ? 'tool' : msg.role,- content: parts- };- if (toolCalls.length > 0) message.toolCalls = toolCalls;- if (toolCallId) message.toolCallId = toolCallId;- return message;- }-- const toolCalls = normalizeOpenAiToolCalls(msg.tool_calls);- if (msg.content === undefined && !toolCalls) return null;- return {- role: msg.role,- content: msg.content ?? '',- toolCalls,- toolCallId: msg.tool_call_id- };+export function tryParseJson(str: string): unknown {+ try {+ return JSON.parse(str);+ } catch {+ return null;+ }+}++function normalizeOpenAiToolCalls(rawCalls: unknown): ToolCall[] | undefined {+ if (!Array.isArray(rawCalls) || rawCalls.length === 0) return undefined;+ const calls: ToolCall[] = [];+ for (const value of rawCalls) {+ if (!isRecord(value)) continue;+ const fn = isRecord(value.function) ? value.function : undefined;+ const name = asString(fn?.name) ?? asString(value.name);+ if (!name) continue;+ const args = fn?.arguments ?? value.arguments ?? '';+ calls.push({+ id: asString(value.id),+ name,+ arguments: typeof args === 'string' ? args : JSON.stringify(args)+ });+ }+ return calls.length > 0 ? calls : undefined;+}++function normalizeInputMessage(value: unknown): ChatMessage | null {+ if (!isRecord(value)) return null;+ const role = asString(value.role);+ if (!role) return null;++ // Anthropic-style content blocks may carry tool_use / tool_result parts.+ if (Array.isArray(value.content)) {+ const toolCalls: ToolCall[] = [];+ let toolCallId: string | undefined;+ const parts: ContentPart[] = [];+ for (const item of value.content) {+ if (!isRecord(item)) continue;+ const type = asString(item.type);+ if (type === 'tool_use' && asString(item.name)) {+ toolCalls.push({+ id: asString(item.id),+ name: asString(item.name)!,+ arguments: JSON.stringify(item.input ?? {})+ });+ } else if (type === 'tool_result') {+ toolCallId = asString(item.tool_use_id);+ const inner = item.content;+ if (typeof inner === 'string') {+ parts.push({ type: 'text', text: inner });+ } else if (Array.isArray(inner)) {+ for (const innerValue of inner) {+ if (isRecord(innerValue) && innerValue.type === 'text') {+ const text = asString(innerValue.text);+ if (text) parts.push({ type: 'text', text });+ }+ }+ }+ } else if (type) {+ const image = isRecord(item.image_url) ? asString(item.image_url.url) : undefined;+ parts.push({+ type,+ text: asString(item.text),+ image_url: image ? { url: image } : undefined+ });+ }+ }+ const message: ChatMessage = {+ role: toolCallId ? 'tool' : role,+ content: parts+ };+ if (toolCalls.length > 0) message.toolCalls = toolCalls;+ if (toolCallId) message.toolCallId = toolCallId;+ return message;+ }++ const toolCalls = normalizeOpenAiToolCalls(value.tool_calls);+ if (value.content === undefined && !toolCalls) return null;+ return {+ role,+ content: typeof value.content === 'string' ? value.content : '',+ toolCalls,+ toolCallId: asString(value.tool_call_id)+ };}function extractOutputMessage(output: string): ChatMessage | null {- const outputParsed = tryParseJson(output);- if (!outputParsed) return null;-- // OpenAI-style: {choices: [{message: {role, content, tool_calls}}]}- const choices = outputParsed?.choices;- if (Array.isArray(choices) && choices.length > 0) {- const msg = choices[0]?.message;- if (!msg) return null;- const toolCalls = normalizeOpenAiToolCalls(msg.tool_calls);- if (!msg.content && !toolCalls) return null;- return { role: msg.role || 'assistant', content: msg.content ?? '', toolCalls };- }-- // Anthropic-style: {content: [{type: "text"|"tool_use", ...}]}- if (Array.isArray(outputParsed?.content)) {- const text = outputParsed.content- .filter((c: any) => c.type === 'text')- .map((c: any) => c.text)- .join('');- const toolCalls: ToolCall[] = outputParsed.content- .filter((c: any) => c.type === 'tool_use' && c.name)- .map((c: any) => ({- id: c.id,- name: c.name,- arguments: JSON.stringify(c.input ?? {})- }));- if (!text && toolCalls.length === 0) return null;- return {- role: outputParsed.role || 'assistant',- content: text,- toolCalls: toolCalls.length > 0 ? toolCalls : undefined- };- }-- return null;+ const outputParsed = tryParseJson(output);+ if (!isRecord(outputParsed)) return null;++ // OpenAI-style: {choices: [{message: {role, content, tool_calls}}]}+ const choices = outputParsed.choices;+ if (Array.isArray(choices) && choices.length > 0) {+ const choice = isRecord(choices[0]) ? choices[0] : null;+ const msg = choice && isRecord(choice.message) ? choice.message : null;+ if (!msg) return null;+ const toolCalls = normalizeOpenAiToolCalls(msg.tool_calls);+ if (!msg.content && !toolCalls) return null;+ return {+ role: asString(msg.role) || 'assistant',+ content: asString(msg.content) ?? '',+ toolCalls+ };+ }++ // Anthropic-style: {content: [{type: "text"|"tool_use", ...}]}+ if (Array.isArray(outputParsed.content)) {+ const blocks = outputParsed.content.filter(isRecord);+ const text = blocks+ .filter((block) => block.type === 'text')+ .map((block) => asString(block.text) ?? '')+ .join('');+ const toolCalls: ToolCall[] = blocks+ .filter((block) => block.type === 'tool_use' && asString(block.name))+ .map((block) => ({+ id: asString(block.id),+ name: asString(block.name)!,+ arguments: JSON.stringify(block.input ?? {})+ }));+ if (!text && toolCalls.length === 0) return null;+ return {+ role: asString(outputParsed.role) || 'assistant',+ content: text,+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined+ };+ }++ return null;}export function parseInputMessages(input: string): ChatMessage[] | null {- const inputParsed = tryParseJson(input);- if (!inputParsed) return null;-- const inputMessages = inputParsed?.messages ?? (Array.isArray(inputParsed) ? inputParsed : null);- if (!Array.isArray(inputMessages)) return null;-- const messages: ChatMessage[] = [];- for (const msg of inputMessages) {- const normalized = normalizeInputMessage(msg);- if (normalized) messages.push(normalized);- }- return messages;+ const inputParsed = tryParseJson(input);+ if (!inputParsed) return null;++ const inputMessages = isRecord(inputParsed)+ ? inputParsed.messages+ : Array.isArray(inputParsed)+ ? inputParsed+ : null;+ if (!Array.isArray(inputMessages)) return null;++ const messages: ChatMessage[] = [];+ for (const msg of inputMessages) {+ const normalized = normalizeInputMessage(msg);+ if (normalized) messages.push(normalized);+ }+ return messages;}export function extractMessages(input: string, output: string): ChatMessage[] | null {- const messages = parseInputMessages(input);- if (!messages) return null;+ const messages = parseInputMessages(input);+ if (!messages) return null;- const outputMessage = extractOutputMessage(output);- if (outputMessage) messages.push(outputMessage);+ const outputMessage = extractOutputMessage(output);+ if (outputMessage) messages.push(outputMessage);- return messages.length > 0 ? messages : null;+ return messages.length > 0 ? messages : null;}// pairToolResults maps a tool call id to the tool message that carries its// result, so ToolCallBlock can render call and result together. Paired tool// messages should be hidden from the main message list.export function pairToolResults(messages: ChatMessage[]): Map<string, ChatMessage> {- const paired = new Map<string, ChatMessage>();- for (const msg of messages) {- if ((msg.role === 'tool' || msg.role === 'function') && msg.toolCallId && !paired.has(msg.toolCallId)) {- paired.set(msg.toolCallId, msg);- }- }- return paired;+ const paired = new Map<string, ChatMessage>();+ for (const msg of messages) {+ if (+ (msg.role === 'tool' || msg.role === 'function') &&+ msg.toolCallId &&+ !paired.has(msg.toolCallId)+ ) {+ paired.set(msg.toolCallId, msg);+ }+ }+ return paired;}function roleSequenceMatches(previous: ChatMessage[], current: ChatMessage[]): boolean {- if (current.length < previous.length) return false;- for (let i = 0; i < previous.length; i++) {- if (previous[i].role !== current[i].role) return false;- }- return true;+ if (current.length < previous.length) return false;+ for (let i = 0; i < previous.length; i++) {+ if (previous[i].role !== current[i].role) return false;+ }+ return true;}// buildConversationTimeline merges per-call payloads into one chat timeline.@@ -197,76 +233,76 @@ function roleSequenceMatches(previous: ChatMessage[], current: ChatMessage[]): b// when that fails (compacted histories, unparsable payloads) the caller// should fall back to per-turn rendering (signaled by returning null).export function buildConversationTimeline(turns: ConversationTurn[]): TimelineEntry[] | null {- const entries: TimelineEntry[] = [];- let previousInput: ChatMessage[] | null = null;-- for (const turn of turns) {- const inputMessages = parseInputMessages(turn.input);- if (!inputMessages) return null;-- let fresh = inputMessages;- if (previousInput && previousInput.length > 0) {- if (!roleSequenceMatches(previousInput, inputMessages)) return null;- fresh = inputMessages.slice(previousInput.length);- }- for (const message of fresh) {- entries.push({ kind: 'message', message });- }-- const outputMessage = extractOutputMessage(turn.output);- if (outputMessage) {- entries.push({ kind: 'message', message: outputMessage });- }- entries.push({ kind: 'turn-meta', turn });-- previousInput = inputMessages;- if (outputMessage) {- previousInput = [...inputMessages, outputMessage];- }- }-- return entries.length > 0 ? entries : null;+ const entries: TimelineEntry[] = [];+ let previousInput: ChatMessage[] | null = null;++ for (const turn of turns) {+ const inputMessages = parseInputMessages(turn.input);+ if (!inputMessages) return null;++ let fresh = inputMessages;+ if (previousInput && previousInput.length > 0) {+ if (!roleSequenceMatches(previousInput, inputMessages)) return null;+ fresh = inputMessages.slice(previousInput.length);+ }+ for (const message of fresh) {+ entries.push({ kind: 'message', message });+ }++ const outputMessage = extractOutputMessage(turn.output);+ if (outputMessage) {+ entries.push({ kind: 'message', message: outputMessage });+ }+ entries.push({ kind: 'turn-meta', turn });++ previousInput = inputMessages;+ if (outputMessage) {+ previousInput = [...inputMessages, outputMessage];+ }+ }++ return entries.length > 0 ? entries : null;}export function getMessageText(content: string | ContentPart[]): string {- if (typeof content === 'string') return content;- if (Array.isArray(content)) {- return content- .filter((p) => p.type === 'text' && p.text)- .map((p) => p.text!)- .join('\n');- }- return '';+ if (typeof content === 'string') return content;+ if (Array.isArray(content)) {+ return content+ .filter((p) => p.type === 'text' && p.text)+ .map((p) => p.text!)+ .join('\n');+ }+ return '';}export function getMessageImages(content: string | ContentPart[]): string[] {- if (!Array.isArray(content)) return [];- return content- .filter((p) => p.type === 'image_url' && p.image_url?.url)- .map((p) => p.image_url!.url);+ if (!Array.isArray(content)) return [];+ return content+ .filter((p) => p.type === 'image_url' && p.image_url?.url)+ .map((p) => p.image_url!.url);}export function getRoleLabel(role: string): string {- switch (role) {- case 'system':- return 'System';- case 'user':- return 'User';- case 'assistant':- return 'Assistant';- case 'tool':- return 'Tool';- case 'function':- return 'Function';- default:- return role;- }+ switch (role) {+ case 'system':+ return 'System';+ case 'user':+ return 'User';+ case 'assistant':+ return 'Assistant';+ case 'tool':+ return 'Tool';+ case 'function':+ return 'Function';+ default:+ return role;+ }}export function formatConversationContent(raw: string): string {- const parsed = tryParseJson(raw);- if (parsed) {- return JSON.stringify(parsed, null, 2);- }- return raw;+ const parsed = tryParseJson(raw);+ if (parsed) {+ return JSON.stringify(parsed, null, 2);+ }+ return raw;}diff --git a/frontend/src/lib/utils/ai-format.ts b/frontend/src/lib/utils/ai-format.tsindex d9062370..cbabb88e 100644--- a/frontend/src/lib/utils/ai-format.ts+++ b/frontend/src/lib/utils/ai-format.ts@@ -1,19 +1,19 @@export function formatCost(cost: number): string {- if (cost === 0) return '$0';- if (cost < 0.001) return `$${cost.toFixed(6)}`;- if (cost < 0.01) return `$${cost.toFixed(4)}`;- if (cost < 1) return `$${cost.toFixed(3)}`;- return `$${cost.toFixed(2)}`;+ if (cost === 0) return '$0';+ if (cost < 0.001) return `$${cost.toFixed(6)}`;+ if (cost < 0.01) return `$${cost.toFixed(4)}`;+ if (cost < 1) return `$${cost.toFixed(3)}`;+ return `$${cost.toFixed(2)}`;}export function formatCount(count: number): string {- if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}m`;- if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`;- return count.toLocaleString();+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}m`;+ if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`;+ return count.toLocaleString();}export function formatTokens(tokens: number): string {- if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;- if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;- return tokens.toLocaleString();+ if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;+ if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;+ return tokens.toLocaleString();}diff --git a/frontend/src/lib/utils/back-navigation.ts b/frontend/src/lib/utils/back-navigation.tsindex c107972b..ec866d82 100644--- a/frontend/src/lib/utils/back-navigation.ts+++ b/frontend/src/lib/utils/back-navigation.ts@@ -1,4 +1,4 @@-import { goto } from '$app/navigation';+import { gotoHref } from './navigation';const NAV_DEPTH_KEY = 'traceway_nav_depth';@@ -78,7 +78,7 @@ export function createSmartBackHandler(options: SmartBackOptions): (e: MouseEvenif (hasInternalHistory()) {history.back();} else {- goto(fallbackPath);+ gotoHref(fallbackPath);}};}diff --git a/frontend/src/lib/utils/errors.ts b/frontend/src/lib/utils/errors.tsnew file mode 100644index 00000000..861bcb59--- /dev/null+++ b/frontend/src/lib/utils/errors.ts@@ -0,0 +1,10 @@+export function getErrorStatus(error: unknown): number | undefined {+ if (!error || typeof error !== 'object' || !('status' in error)) return undefined;+ return typeof error.status === 'number' ? error.status : undefined;+}++export function getErrorMessage(error: unknown, fallback = ''): string {+ if (error instanceof Error) return error.message || fallback;+ if (!error || typeof error !== 'object' || !('message' in error)) return fallback;+ return typeof error.message === 'string' ? error.message || fallback : fallback;+}diff --git a/frontend/src/lib/utils/flame-ops.ts b/frontend/src/lib/utils/flame-ops.tsindex a58e8a1c..95223c33 100644--- a/frontend/src/lib/utils/flame-ops.ts+++ b/frontend/src/lib/utils/flame-ops.ts@@ -16,7 +16,12 @@ function sortTree(node: FlameGraphNode): void {}export function collapseRecursion(node: FlameGraphNode): FlameGraphNode {- const out: FlameGraphNode = { name: node.name, value: node.value, self: node.self ?? 0, children: [] };+ const out: FlameGraphNode = {+ name: node.name,+ value: node.value,+ self: node.self ?? 0,+ children: []+ };const byName = new Map<string, FlameGraphNode>();const addChild = (c: FlameGraphNode) => {diff --git a/frontend/src/lib/utils/formatters.ts b/frontend/src/lib/utils/formatters.tsindex 854f28b0..042c3ce5 100644--- a/frontend/src/lib/utils/formatters.ts+++ b/frontend/src/lib/utils/formatters.ts@@ -164,3 +164,8 @@ export function parseISO(dateStr: string, timezone?: string): DateTime {const tz = timezone ?? getTimezone();return DateTime.fromISO(dateStr, { zone: 'utc' }).setZone(tz);}++export function toLocalInputValue(date: Date): string {+ const pad = (n: number) => String(n).padStart(2, '0');+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;+}diff --git a/frontend/src/lib/utils/framework-code.ts b/frontend/src/lib/utils/framework-code.tsindex 831aa1f8..69409596 100644--- a/frontend/src/lib/utils/framework-code.ts+++ b/frontend/src/lib/utils/framework-code.ts@@ -592,16 +592,26 @@ captureException(new Error("Test error"));`;function getPackageName(framework: Framework): string {switch (framework) {- case 'react': return 'react';- case 'svelte': return 'svelte';- case 'vuejs': return 'vue';- case 'nextjs': return 'next';- case 'nestjs': return 'nest';- case 'express': return 'express';- case 'remix': return 'remix';- case 'jquery': return 'jquery';- case 'react-native': return 'react-native';- default: return 'react';+ case 'react':+ return 'react';+ case 'svelte':+ return 'svelte';+ case 'vuejs':+ return 'vue';+ case 'nextjs':+ return 'next';+ case 'nestjs':+ return 'nest';+ case 'express':+ return 'express';+ case 'remix':+ return 'remix';+ case 'jquery':+ return 'jquery';+ case 'react-native':+ return 'react-native';+ default:+ return 'react';}}@@ -630,12 +640,14 @@ export function getFrameworkLabel(framework: Framework): string {django: 'Django',flutter: 'Flutter',android: 'Android',- ios: 'iOS',+ ios: 'iOS'};return labels[framework] || framework;}-export function getCodeLanguage(framework: Framework): 'go' | 'javascript' | 'bash' | 'php' | 'python' {+export function getCodeLanguage(+ framework: Framework+): 'go' | 'javascript' | 'bash' | 'php' | 'python' {if (framework === 'symfony') return 'php';if (framework === 'laravel') return 'php';if (framework === 'django') return 'python';diff --git a/frontend/src/lib/utils/healthcheck.ts b/frontend/src/lib/utils/healthcheck.tsindex 6856c5b2..5a8dfd28 100644--- a/frontend/src/lib/utils/healthcheck.ts+++ b/frontend/src/lib/utils/healthcheck.ts@@ -1,13 +1,40 @@export const DEFAULT_HEALTHCHECK_PATHS = [- '/health', '/healthz', '/healthcheck', '/health-check', '/health_check',- '/ping', '/livez', '/readyz', '/live', '/ready', '/alive', '/up',- '/heartbeat', '/status', '/ht', '/actuator/health/*', '*/health'+ '/health',+ '/healthz',+ '/healthcheck',+ '/health-check',+ '/health_check',+ '/ping',+ '/livez',+ '/readyz',+ '/live',+ '/ready',+ '/alive',+ '/up',+ '/heartbeat',+ '/status',+ '/ht',+ '/actuator/health/*',+ '*/health'];const DEFAULT_PATH_SET = new Set([- '/health', '/healthz', '/healthcheck', '/health-check', '/health_check',- '/ping', '/livez', '/readyz', '/live', '/ready', '/alive', '/up',- '/heartbeat', '/status', '/ht', '/actuator/health'+ '/health',+ '/healthz',+ '/healthcheck',+ '/health-check',+ '/health_check',+ '/ping',+ '/livez',+ '/readyz',+ '/live',+ '/ready',+ '/alive',+ '/up',+ '/heartbeat',+ '/status',+ '/ht',+ '/actuator/health']);function matchesCustomPath(path: string, pattern: string): boolean {@@ -26,7 +53,10 @@ export function isHealthcheckEndpoint(endpoint: string, customPaths?: string[] |if (spaceIdx === -1) return false;const method = endpoint.slice(0, spaceIdx);if (method !== 'GET' && method !== 'HEAD') return false;- let path = endpoint.slice(spaceIdx + 1).trim().toLowerCase();+ let path = endpoint+ .slice(spaceIdx + 1)+ .trim()+ .toLowerCase();if (path.length > 1) path = path.replace(/\/+$/, '');if (DEFAULT_PATH_SET.has(path)) return true;if (path.startsWith('/actuator/health/')) return true;diff --git a/frontend/src/lib/utils/links.ts b/frontend/src/lib/utils/links.tsnew file mode 100644index 00000000..abd39414--- /dev/null+++ b/frontend/src/lib/utils/links.ts@@ -0,0 +1,13 @@+import { resolve } from '$app/paths';++export function splitHref(href: string): { pathname: string; suffix: string } {+ const suffixIndex = href.search(/[?#]/);+ if (suffixIndex === -1) return { pathname: href, suffix: '' };+ return { pathname: href.slice(0, suffixIndex), suffix: href.slice(suffixIndex) };+}++export function resolveHref(href: string): string {+ if (/^(?:[a-z][a-z\d+.-]*:)?\/\//i.test(href) || href.startsWith('#')) return href;+ const { pathname, suffix } = splitHref(href);+ return resolve((pathname || '/') as '/') + suffix;+}diff --git a/frontend/src/lib/utils/navigation.ts b/frontend/src/lib/utils/navigation.tsindex f187fe35..7aae4a43 100644--- a/frontend/src/lib/utils/navigation.ts+++ b/frontend/src/lib/utils/navigation.ts@@ -1,4 +1,14 @@import { goto } from '$app/navigation';+import { resolve } from '$app/paths';++import { splitHref } from './links';++export function gotoHref(href: string, options?: Parameters<typeof goto>[1]) {+ const { pathname, suffix } = splitHref(href);+ let destination = resolve((pathname || '/') as '/');+ destination += suffix;+ return goto(destination, options);+}// Only allow same-origin, absolute-path redirects. Reject absolute URLs// (https://evil.com), protocol-relative (//evil.com), and backslash tricks@@ -50,7 +60,7 @@ export function addStickyParamsToHref(href: string, ...stickyParams: string[]) {}}- stickyParams.forEach(stickyParam => {+ stickyParams.forEach((stickyParam) => {if (stickyParam === 'projectId') return;const currentValue = currentParams.get(stickyParam);if (currentValue !== null) {@@ -63,7 +73,11 @@ export function addStickyParamsToHref(href: string, ...stickyParams: string[]) {// in the future it would be really cool if we could bind the type here to get type safety and force the use of resolve :/// this also won't work with absolute paths - meh so be it-export function createRowClickHandlerWithNavigate(href: string, onBeforeNavigate: (() => void) | undefined, ...stickyParams: string[]) {+export function createRowClickHandlerWithNavigate(+ href: string,+ onBeforeNavigate: (() => void) | undefined,+ ...stickyParams: string[]+) {return (event: MouseEvent) => {onBeforeNavigate?.();@@ -72,12 +86,11 @@ export function createRowClickHandlerWithNavigate(href: string, onBeforeNavigateif (event.ctrlKey || event.metaKey) {window.open(finalHref, '_blank');} else {- // eslint-disable-next-line svelte/no-navigation-without-resolve- goto(finalHref);+ gotoHref(finalHref);}};}export function createRowClickHandler(href: string, ...stickyParams: string[]) {return createRowClickHandlerWithNavigate(href, undefined, ...stickyParams);-}\ No newline at end of file+}diff --git a/frontend/src/lib/utils/otel-setup.ts b/frontend/src/lib/utils/otel-setup.tsindex 9180102b..31594bfd 100644--- a/frontend/src/lib/utils/otel-setup.ts+++ b/frontend/src/lib/utils/otel-setup.ts@@ -208,7 +208,8 @@ http.ListenAndServe(":8080", mux)`,}};-const NODE_ZERO_CODE_INSTALL = 'npm install @opentelemetry/api @opentelemetry/auto-instrumentations-node';+const NODE_ZERO_CODE_INSTALL =+ 'npm install @opentelemetry/api @opentelemetry/auto-instrumentations-node';function nodeZeroCodeSteps(backendUrl: string,@@ -410,7 +411,8 @@ export function register() {return [{title: 'Add the Starter',- description: 'Add the OpenTelemetry Spring Boot starter to your Gradle build (a Maven dependency works the same way).',+ description:+ 'Add the OpenTelemetry Spring Boot starter to your Gradle build (a Maven dependency works the same way).',code: `implementation(platform("io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom:2.28.1"))implementation("io.opentelemetry.instrumentation:opentelemetry-spring-boot-starter")`,codeLanguage: 'gradle'diff --git a/frontend/src/lib/utils/profile-format.ts b/frontend/src/lib/utils/profile-format.tsindex b13b97bd..4c31df9d 100644--- a/frontend/src/lib/utils/profile-format.ts+++ b/frontend/src/lib/utils/profile-format.ts@@ -38,7 +38,16 @@ const TIME_TO_NS: Record<string, number> = {};const BYTE_UNITS = new Set(['bytes', 'byte', 'b']);-const COUNT_UNITS = new Set(['count', 'samples', 'sample', 'frames', 'objects', 'goroutines', 'none', '']);+const COUNT_UNITS = new Set([+ 'count',+ 'samples',+ 'sample',+ 'frames',+ 'objects',+ 'goroutines',+ 'none',+ ''+]);export function formatValue(unit: string, value: number): string {const u = (unit || '').toLowerCase();diff --git a/frontend/src/lib/utils/server-colors.ts b/frontend/src/lib/utils/server-colors.tsindex 9334c46d..13014588 100644--- a/frontend/src/lib/utils/server-colors.ts+++ b/frontend/src/lib/utils/server-colors.ts@@ -1,12 +1,12 @@export const SERVER_COLORS = [- '#e97a35', // Orange- '#2a9d8f', // Teal- '#4361ee', // Blue- '#d664ba', // Pink- '#e9c46a', // Yellow- '#9b5de5', // Purple- '#57cc99', // Green- '#ef476f' // Red+ '#e97a35', // Orange+ '#2a9d8f', // Teal+ '#4361ee', // Blue+ '#d664ba', // Pink+ '#e9c46a', // Yellow+ '#9b5de5', // Purple+ '#57cc99', // Green+ '#ef476f' // Red] as const;export function getServerColor(serverName: string, allServers: string[]): string {diff --git a/frontend/src/lib/utils/setup-storage.ts b/frontend/src/lib/utils/setup-storage.tsindex de8d5ab4..4feae4d8 100644--- a/frontend/src/lib/utils/setup-storage.ts+++ b/frontend/src/lib/utils/setup-storage.ts@@ -15,7 +15,9 @@ export function getSetupMode(): SetupMode {if (stored === 'ai' || stored === 'manual') {return stored;}- } catch {}+ } catch {+ return 'ai';+ }return 'ai';}@@ -25,7 +27,9 @@ export function setSetupMode(mode: SetupMode): void {try {localStorage.setItem(MODE_KEY, mode);- } catch {}+ } catch {+ return;+ }}export function getOtelTarget(): OtelTargetId {@@ -36,7 +40,9 @@ export function getOtelTarget(): OtelTargetId {if (stored && OTEL_TARGETS.some((t) => t.id === stored)) {return stored as OtelTargetId;}- } catch {}+ } catch {+ return OTEL_TARGETS[0].id;+ }return OTEL_TARGETS[0].id;}@@ -46,7 +52,9 @@ export function setOtelTarget(id: OtelTargetId): void {try {localStorage.setItem(OTEL_TARGET_KEY, id);- } catch {}+ } catch {+ return;+ }}export function getOtelFramework(): string | null {@@ -54,7 +62,9 @@ export function getOtelFramework(): string | null {try {return localStorage.getItem(OTEL_FRAMEWORK_KEY);- } catch {}+ } catch {+ return null;+ }return null;}@@ -64,5 +74,7 @@ export function setOtelFramework(id: string): void {try {localStorage.setItem(OTEL_FRAMEWORK_KEY, id);- } catch {}+ } catch {+ return;+ }}diff --git a/frontend/src/lib/utils/tabs.ts b/frontend/src/lib/utils/tabs.tsnew file mode 100644index 00000000..f8890951--- /dev/null+++ b/frontend/src/lib/utils/tabs.ts@@ -0,0 +1,5 @@+export const underlineTabTriggerClass =+ '-mb-px shrink-0 rounded-none border-b-2 border-transparent bg-transparent px-0 pt-0 pb-2.5 text-sm font-medium whitespace-nowrap text-muted-foreground shadow-none transition-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none';++export const underlineTabListClass =+ 'h-auto w-full justify-start gap-4 rounded-none border-b bg-transparent p-0';diff --git a/frontend/src/lib/utils/uptime.ts b/frontend/src/lib/utils/uptime.tsnew file mode 100644index 00000000..2067186b--- /dev/null+++ b/frontend/src/lib/utils/uptime.ts@@ -0,0 +1,5 @@+export function uptimeClass(uptime: number): string {+ if (uptime >= 99.9) return 'text-green-600 dark:text-green-400';+ if (uptime >= 99) return '';+ return 'text-red-600 dark:text-red-400';+}diff --git a/frontend/src/lib/utils/url-params.ts b/frontend/src/lib/utils/url-params.tsindex 6fffc04f..54db9746 100644--- a/frontend/src/lib/utils/url-params.ts+++ b/frontend/src/lib/utils/url-params.ts@@ -1,8 +1,8 @@import { browser } from '$app/environment';-import { goto } from '$app/navigation';import { CalendarDate } from '@internationalized/date';import { DateTime } from 'luxon';import { getNow, parseISO } from './formatters';+import { gotoHref } from './navigation';export const presetMinutes: Record<string, number> = {'5m': 5,@@ -18,7 +18,10 @@ export const presetMinutes: Record<string, number> = {'3M': 129600};-export function getTimeRangeFromPreset(presetValue: string, timezone: string): { from: Date; to: Date } {+export function getTimeRangeFromPreset(+ presetValue: string,+ timezone: string+): { from: Date; to: Date } {const minutes = presetMinutes[presetValue] || 360;const now = getNow(timezone);const from = now.minus({ minutes });@@ -82,7 +85,7 @@ export type UpdateUrlOptions = {};export function updateUrl(- params: Record<string, string | null | undefined>,+ params: Record<string, string | string[] | null | undefined>,options: UpdateUrlOptions = {}): void {if (!browser) return;@@ -96,7 +99,11 @@ export function updateUrl(}for (const [key, value] of Object.entries(params)) {- if (value != null && value !== '') {+ if (Array.isArray(value)) {+ for (const item of value) {+ urlParams.append(key, item);+ }+ } else if (value != null && value !== '') {urlParams.set(key, value);} else {urlParams.delete(key);@@ -105,10 +112,26 @@ export function updateUrl(const newUrl = `${window.location.pathname}?${urlParams.toString()}`;- // eslint-disable-next-line svelte/no-navigation-without-resolve- goto(newUrl, {+ gotoHref(newUrl, {replaceState: !pushToHistory,noScroll: true,keepFocus: true});}++export function setTabParam(tab: string, options: { param?: string; clear?: string[] } = {}): void {+ if (!browser) return;++ const { param = 'tab', clear = [] } = options;+ const url = new URL(window.location.href);+ url.searchParams.set(param, tab);+ for (const key of clear) {+ url.searchParams.delete(key);+ }++ gotoHref(url.pathname + url.search + url.hash, {+ replaceState: true,+ noScroll: true,+ keepFocus: true+ });+}diff --git a/frontend/src/routes/+error.svelte b/frontend/src/routes/+error.svelteindex 3d68fbfa..3a8fbdb7 100644--- a/frontend/src/routes/+error.svelte+++ b/frontend/src/routes/+error.svelte@@ -1,19 +1,20 @@<script lang="ts">import { resolve } from '$app/paths';- import { page } from '$app/state';- import { ErrorDisplay } from '$lib/components/ui/error-display';+ import { page } from '$app/state';+ import { ErrorDisplay } from '$lib/components/ui/error-display';import { createRowClickHandler } from '$lib/utils/navigation';- const status = $derived(page.status);- const errorMessage = $derived(page.error?.message);+ const status = $derived(page.status);+ const errorMessage = $derived(page.error?.message);</script><ErrorDisplay- {status}- title={status === 404 ? 'Page Not Found' : 'Something Went Wrong'}- description={errorMessage || (status === 404- ? "The page you're looking for doesn't exist or may have been moved."- : 'An unexpected error occurred. Please try again.')}- onBack={createRowClickHandler(resolve('/'))}- backLabel="Go to Dashboard"+ {status}+ title={status === 404 ? 'Page Not Found' : 'Something Went Wrong'}+ description={errorMessage ||+ (status === 404+ ? "The page you're looking for doesn't exist or may have been moved."+ : 'An unexpected error occurred. Please try again.')}+ onBack={createRowClickHandler(resolve('/'))}+ backLabel="Go to Dashboard"/>diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelteindex 16755599..21ce1792 100644--- a/frontend/src/routes/+layout.svelte+++ b/frontend/src/routes/+layout.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import { resolve } from '$app/paths';import './layout.css';import { goto, afterNavigate } from '$app/navigation';import { authState } from '$lib/state/auth.svelte';@@ -18,9 +19,10 @@import { WarningCallout } from '$lib/components/ui/warning-callout';import { onMount } from 'svelte';import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';- import { ChevronDown } from 'lucide-svelte';+ import { ChevronDown } from '@lucide/svelte';import { Toaster, toast } from 'svelte-sonner';import { page } from '$app/state';+ import { gotoHref } from '$lib/utils/navigation';import { setupTraceway } from '@tracewayapp/svelte';import { captureException } from '@tracewayapp/frontend';import * as Tooltip from '$lib/components/ui/tooltip';@@ -37,7 +39,8 @@let showEditProjectModal = $state(false);let showCommandPalette = $state(false);- const isMacPlatform = typeof navigator !== 'undefined' && /Mac|iP(hone|ad|od)/.test(navigator.platform);+ const isMacPlatform =+ typeof navigator !== 'undefined' && /Mac|iP(hone|ad|od)/.test(navigator.platform);function handleGlobalKeydown(e: KeyboardEvent) {if ((e.metaKey || e.ctrlKey) && e.key === 'k') {@@ -109,21 +112,23 @@.then((response) => (response.ok ? response.json() : null)).then((resolved) => {if (resolved?.slug) {- // eslint-disable-next-line svelte/no-navigation-without-resolve- goto(`/status/${resolved.slug}`, { replaceState: true });+ goto(resolve(`/status/${resolved.slug}` as '/'), { replaceState: true });} else {- // eslint-disable-next-line svelte/no-navigation-without-resolve- goto(`/login?returnTo=${encodeURIComponent(returnTo)}`, { replaceState: true });+ gotoHref(`/login?returnTo=${encodeURIComponent(returnTo)}`, {+ replaceState: true+ });}}).catch(() => {- // eslint-disable-next-line svelte/no-navigation-without-resolve- goto(`/login?returnTo=${encodeURIComponent(returnTo)}`, { replaceState: true });+ gotoHref(`/login?returnTo=${encodeURIComponent(returnTo)}`, {+ replaceState: true+ });});return;}- // eslint-disable-next-line svelte/no-navigation-without-resolve- goto(`/login?returnTo=${encodeURIComponent(returnTo)}`, { replaceState: true });+ gotoHref(`/login?returnTo=${encodeURIComponent(returnTo)}`, {+ replaceState: true+ });}});@@ -160,7 +165,7 @@) {const canonical = new URL(newUrl);canonical.searchParams.set('projectId', projectsState.currentProjectId);- goto(canonical.pathname + canonical.search, {+ gotoHref(canonical.pathname + canonical.search, {replaceState: true,noScroll: true,keepFocus: true@@ -171,7 +176,7 @@onMount(() => {document.getElementById('splash')?.remove();initTheme();- (window as any).captureException = captureException;+ window.captureException = captureException;if (authState.isAuthenticated) {projectsState.loadProjects();@@ -188,17 +193,17 @@function handleLogout() {authState.logout();- goto('/login');+ goto(resolve('/login'));}function handleProjectSelect(projectId: string) {- goto(`/?projectId=${projectId}`);+ gotoHref(`/?projectId=${projectId}`);}function handleAddProjectClick() {const orgs = authState.organizations;if (orgs.length > 0 && orgs.every((o) => o.role === 'readonly')) {- toast.error("You're not authorized to perform that action", { position: 'top-center' });+ toast.error("You're not authorized to perform that action");return;}showAddProjectModal = true;@@ -207,7 +212,7 @@function handleProjectCreated() {showAddProjectModal = false;// Optionally navigate to connection page to show token- goto('/connection');+ goto(resolve('/connection'));}const multiOrg = $derived(authState.organizations.length > 1);@@ -251,123 +256,131 @@{/snippet}<Tooltip.Provider delayDuration={0}>-<!-- This is not ideal, but because our layout is a top level route it can end up showing sidebar on the login page (after the login before the transition). -->-<!-- We could consider moving this to a lower level layout for the actual app, for now it's just a path check -->-{#if authState.isAuthenticated && !isPublicPath(page.url.pathname)}- <Sidebar.SidebarProvider- bind:open={sidebarOpen}- onOpenChange={(open) => localStorage.setItem(SIDEBAR_OPEN_KEY, String(open))}- >- <AppSidebar />- <Sidebar.SidebarInset>- <header class="flex h-12 shrink-0 items-center gap-2 border-b bg-white px-2 dark:bg-transparent">- <Sidebar.SidebarTrigger />- <div class="h-4 w-px bg-border"></div>- <h1 class="text-lg font-semibold">- <DropdownMenu.Root>- <DropdownMenu.Trigger- class="flex flex-row items-center gap-2 rounded-md px-2 py-1 transition-colors hover:bg-accent hover:text-accent-foreground"- >- {#if projectsState.currentProject}- <FrameworkIcon framework={projectsState.currentProject.framework} class="size-6 shrink-0" />- {/if}- <span>{projectsState.currentProject?.name || 'Select Project'}</span>- <ChevronDown size={16} />- </DropdownMenu.Trigger>- <DropdownMenu.Content align="start" class="w-56">- {#if multiOrg}- {#each groupedProjects as group (group.key)}+ <!-- This is not ideal, but because our layout is a top level route it can end up showing sidebar on the login page (after the login before the transition). -->+ <!-- We could consider moving this to a lower level layout for the actual app, for now it's just a path check -->+ {#if authState.isAuthenticated && !isPublicPath(page.url.pathname)}+ <Sidebar.SidebarProvider+ bind:open={sidebarOpen}+ onOpenChange={(open) => localStorage.setItem(SIDEBAR_OPEN_KEY, String(open))}+ >+ <AppSidebar />+ <Sidebar.SidebarInset>+ <header+ class="flex h-12 shrink-0 items-center gap-2 border-b bg-white px-2 dark:bg-transparent"+ >+ <Sidebar.SidebarTrigger />+ <div class="h-4 w-px bg-border"></div>+ <div class="text-lg font-semibold">+ <DropdownMenu.Root>+ <DropdownMenu.Trigger+ class="flex flex-row items-center gap-2 rounded-md px-2 py-1 transition-colors hover:bg-accent hover:text-accent-foreground"+ >+ {#if projectsState.currentProject}+ <FrameworkIcon+ framework={projectsState.currentProject.framework}+ class="size-6 shrink-0"+ />+ {/if}+ <span>{projectsState.currentProject?.name || 'Select Project'}</span>+ <ChevronDown size={16} />+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="start" class="w-56">+ {#if multiOrg}+ {#each groupedProjects as group (group.key)}+ <DropdownMenu.Group>+ <DropdownMenu.Label class="text-xs text-muted-foreground uppercase"+ >{group.name}</DropdownMenu.Label+ >+ {#each group.projects as project (project.id)}+ {@render projectItem(project, true)}+ {/each}+ </DropdownMenu.Group>+ {/each}+ {:else}<DropdownMenu.Group>- <DropdownMenu.Label class="text-xs text-muted-foreground uppercase">{group.name}</DropdownMenu.Label>- {#each group.projects as project (project.id)}- {@render projectItem(project, true)}+ <DropdownMenu.Label>Projects</DropdownMenu.Label>+ <DropdownMenu.Separator />+ {#each projectsState.projects as project (project.id)}+ {@render projectItem(project, false)}{/each}</DropdownMenu.Group>- {/each}- {:else}- <DropdownMenu.Group>- <DropdownMenu.Label>Projects</DropdownMenu.Label>- <DropdownMenu.Separator />- {#each projectsState.projects as project (project.id)}- {@render projectItem(project, false)}- {/each}- </DropdownMenu.Group>- {/if}- {#if projectsState.projects.length === 0}- <DropdownMenu.Item disabled>No projects yet</DropdownMenu.Item>- {/if}- <DropdownMenu.Separator />- {#if projectsState.canManageCurrentProject}- <DropdownMenu.Item onclick={() => showEditProjectModal = true} class="cursor-pointer">- <Pencil class="mr-2 h-4 w-4" />- Edit Project+ {/if}+ {#if projectsState.projects.length === 0}+ <DropdownMenu.Item disabled>No projects yet</DropdownMenu.Item>+ {/if}+ <DropdownMenu.Separator />+ {#if projectsState.canManageCurrentProject}+ <DropdownMenu.Item+ onclick={() => (showEditProjectModal = true)}+ class="cursor-pointer"+ >+ <Pencil class="mr-2 h-4 w-4" />+ Edit Project+ </DropdownMenu.Item>+ {/if}+ <DropdownMenu.Item onclick={handleAddProjectClick} class="cursor-pointer">+ <Plus class="mr-2 h-4 w-4" />+ Add Project</DropdownMenu.Item>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ </div>+ <div class="ml-auto flex items-center gap-2">+ <Button+ variant="ghost"+ size="icon"+ onclick={toggleTheme}+ title={themeState.isDark ? 'Switch to Light Mode' : 'Switch to Dark Mode'}+ >+ {#if themeState.isDark}+ <Sun class="h-5 w-5" />+ {:else}+ <Moon class="h-5 w-5" />{/if}- <DropdownMenu.Item onclick={handleAddProjectClick} class="cursor-pointer">- <Plus class="mr-2 h-4 w-4" />- Add Project- </DropdownMenu.Item>- </DropdownMenu.Content>- </DropdownMenu.Root>- </h1>- <div class="ml-auto flex items-center gap-2">- <Button- variant="ghost"- size="icon"- onclick={toggleTheme}- title={themeState.isDark ? 'Switch to Light Mode' : 'Switch to Dark Mode'}- >- {#if themeState.isDark}- <Sun class="h-5 w-5" />- {:else}- <Moon class="h-5 w-5" />- {/if}- </Button>- <Button variant="ghost" size="icon" onclick={handleLogout} title="Logout">- <LogOut class="h-5 w-5" />- </Button>- </div>- </header>- <main class="min-w-0 flex-1 p-4">- {#if timezoneMismatch}- <WarningCallout- class="mb-4"- title="Your browser's timezone differs from the organization's"- >- All times are shown in the organization's timezone ({zoneLabel(orgZone)}). Your- browser is on {zoneLabel(browserZone)}.- </WarningCallout>- {/if}- {#if CrossSiteNotificationBanner && bannerOrganizationId !== null}- <div class="mb-4">- <CrossSiteNotificationBanner organizationId={bannerOrganizationId} />+ </Button>+ <Button variant="ghost" size="icon" onclick={handleLogout} title="Logout">+ <LogOut class="h-5 w-5" />+ </Button></div>- {/if}- {@render children()}- </main>- </Sidebar.SidebarInset>- </Sidebar.SidebarProvider>-- <AddProjectModal- open={showAddProjectModal}- onOpenChange={(open) => (showAddProjectModal = open)}- onProjectCreated={handleProjectCreated}- />-- <EditProjectModal- open={showEditProjectModal}- onOpenChange={(open) => (showEditProjectModal = open)}- project={projectsState.currentProject}- />-- <DashboardCommand bind:open={showCommandPalette} />-- <Toaster position="bottom-right" />-{:else}- {#if isPublicPath(page.url.pathname)}+ </header>+ <main class="min-w-0 flex-1 p-4">+ {#if timezoneMismatch}+ <WarningCallout+ class="mb-4"+ title="Your browser's timezone differs from the organization's"+ >+ All times are shown in the organization's timezone ({zoneLabel(orgZone)}). Your+ browser is on {zoneLabel(browserZone)}.+ </WarningCallout>+ {/if}+ {#if CrossSiteNotificationBanner && bannerOrganizationId !== null}+ <div class="mb-4">+ <CrossSiteNotificationBanner organizationId={bannerOrganizationId} />+ </div>+ {/if}+ {@render children()}+ </main>+ </Sidebar.SidebarInset>+ </Sidebar.SidebarProvider>++ <AddProjectModal+ open={showAddProjectModal}+ onOpenChange={(open) => (showAddProjectModal = open)}+ onProjectCreated={handleProjectCreated}+ />++ <EditProjectModal+ open={showEditProjectModal}+ onOpenChange={(open) => (showEditProjectModal = open)}+ project={projectsState.currentProject}+ />++ <DashboardCommand bind:open={showCommandPalette} />++ <Toaster position="top-center" />+ {:else if isPublicPath(page.url.pathname)}<main class="h-screen w-screen">{@render children()}</main>{/if}-{/if}</Tooltip.Provider>diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelteindex 71de5ed5..e984a30d 100644--- a/frontend/src/routes/+page.svelte+++ b/frontend/src/routes/+page.svelte@@ -1,7 +1,9 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';+ import { resolve } from '$app/paths';import { onMount } from 'svelte';import { createRowClickHandler } from '$lib/utils/navigation';- import { formatDuration, formatRelativeTime, truncateStackTrace } from '$lib/utils/formatters';+ import { formatDuration, formatRelativeTime } from '$lib/utils/formatters';import { getTimezone } from '$lib/state/timezone.svelte';import { LoadingCircle } from '$lib/components/ui/loading-circle';import * as Table from '$lib/components/ui/table';@@ -13,12 +15,9 @@CircleQuestionMark,CircleCheck,RefreshCw,- Copy,- Check,Star,Unplug- } from 'lucide-svelte';- import * as Card from '$lib/components/ui/card';+ } from '@lucide/svelte';import WidgetGrid from '$lib/components/dashboard/widget-grid.svelte';import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';import { ImpactBadge } from '$lib/components/ui/impact-badge';@@ -28,22 +27,17 @@import { ErrorDisplay } from '$lib/components/ui/error-display';import {projectsState,- type ProjectWithToken,isFrontendFramework,- isJsFramework,isCloudflareFramework,isOtelFramework} from '$lib/state/projects.svelte';import { setSortState } from '$lib/utils/sort-storage';import { Button } from '$lib/components/ui/button';- import Highlight from 'svelte-highlight';import go from 'svelte-highlight/languages/go';import javascript from 'svelte-highlight/languages/javascript';import bash from 'svelte-highlight/languages/bash';import php from 'svelte-highlight/languages/php';import python from 'svelte-highlight/languages/python';- import { themeState } from '$lib/state/theme.svelte';- import 'svelte-highlight/styles/github-dark.css';import {getFrameworkCode,getInstallCommand,@@ -60,6 +54,11 @@import AiSetupSteps from '$lib/components/setup/ai-setup-steps.svelte';import OtelSetupSteps from '$lib/components/setup/otel-setup-steps.svelte';import OtelExporterConfig from '$lib/components/setup/otel-exporter-config.svelte';+ import CopyableInline from '$lib/components/setup/copyable-inline.svelte';+ import CopyableCodeBlock from '$lib/components/setup/copyable-code-block.svelte';+ import CopyButton from '$lib/components/traceway/copy-button.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import type { DashboardWidgetConfig } from '$lib/types/dashboard';const timezone = $derived(getTimezone());@@ -69,7 +68,7 @@isFrontendFramework(projectsState.currentProject.framework)) {// index redirects to issues on a frontend project- goto('issues');+ goto(resolve('/issues'));}});@@ -104,7 +103,7 @@widgetId: string;title: string;widgetType: string;- config: any;+ config: DashboardWidgetConfig;homePosition: number;homeColSpan: number;homeSize: string;@@ -116,7 +115,7 @@widgetId: string;title: string;widgetType: string;- config: any;+ config: DashboardWidgetConfig;position: number;isStarred: boolean;};@@ -136,10 +135,6 @@let projectWithToken = $derived(projectsState.currentProject);let setupMode = $state(getSetupMode());- let copiedInstall = $state(false);- let copiedCode = $state(false);- let copiedTesting = $state(false);- let copiedTesting2 = $state(false);let checking = $state(false);const sdkCode = $derived(@@ -201,11 +196,6 @@}}`);- let copiedCfEndpoint = $state(false);- let copiedCfAuth = $state(false);- let copiedCfWrangler = $state(false);- let copiedCfDeploy = $state(false);-const isOtel = $derived(projectWithToken ? isOtelFramework(projectWithToken.framework) : false);const isOtelGeneric = $derived(projectWithToken?.framework === 'opentelemetry');const otelBaseEndpoint = $derived(@@ -229,62 +219,6 @@ service:: '');- let copiedSdkLang = $state<string | null>(null);-- async function copyCfEndpoint() {- await navigator.clipboard.writeText(cfOtelEndpoint);- copiedCfEndpoint = true;- setTimeout(() => (copiedCfEndpoint = false), 2000);- }-- async function copyCfAuth() {- await navigator.clipboard.writeText(cfAuthHeader);- copiedCfAuth = true;- setTimeout(() => (copiedCfAuth = false), 2000);- }-- async function copyCfWrangler() {- await navigator.clipboard.writeText(cfWranglerConfig);- copiedCfWrangler = true;- setTimeout(() => (copiedCfWrangler = false), 2000);- }-- async function copyCfDeploy() {- await navigator.clipboard.writeText('npx wrangler deploy');- copiedCfDeploy = true;- setTimeout(() => (copiedCfDeploy = false), 2000);- }-- async function copySdkInstall(lang: string, cmd: string) {- await navigator.clipboard.writeText(cmd);- copiedSdkLang = lang;- setTimeout(() => (copiedSdkLang = null), 2000);- }-- async function copyInstall() {- await navigator.clipboard.writeText(installCommand);- copiedInstall = true;- setTimeout(() => (copiedInstall = false), 2000);- }-- async function copyCode() {- await navigator.clipboard.writeText(sdkCode);- copiedCode = true;- setTimeout(() => (copiedCode = false), 2000);- }-- async function copyTesting() {- await navigator.clipboard.writeText(testingRouteCode);- copiedTesting = true;- setTimeout(() => (copiedTesting = false), 2000);- }-- async function copyTesting2() {- await navigator.clipboard.writeText(testingRouteCode2);- copiedTesting2 = true;- setTimeout(() => (copiedTesting2 = false), 2000);- }-async function checkAgain() {checking = true;const hadDataBefore = data?.hasData ?? false;@@ -293,13 +227,9 @@ service:// Show success toast if data was receivedif (!hadDataBefore && data?.hasData) {- toast.success('Integration successful! Data received from your application.', {- position: 'top-center'- });+ toast.success('Integration successful! Data received from your application.');} else if (!data?.hasData) {- toast.warning('No data received yet', {- position: 'top-center'- });+ toast.warning('No data received yet');}}@@ -329,9 +259,9 @@ service:position: w.homePosition,isStarred: true}));- } catch (e: any) {- errorStatus = e.status || 0;- error = e.message || 'Failed to load dashboard data';+ } catch (e) {+ errorStatus = getErrorStatus(e) || 0;+ error = getErrorMessage(e) || 'Failed to load dashboard data';console.error(e);} finally {if (showFullPageLoading) {@@ -352,12 +282,12 @@ service:{ ids },{ projectId: projectsState.currentProjectId ?? undefined });- } catch (e: any) {+ } catch (e) {for (const w of starredWidgets) {w.position = previousPositions.get(w.id) ?? w.position;}- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to reorder widgets', { position: 'top-center' });+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to reorder widgets');}await loadDashboard(false);}@@ -376,11 +306,11 @@ service:await api.put(`/starred-widgets/${target.id}`, layout, {projectId: projectsState.currentProjectId ?? undefined});- } catch (e: any) {+ } catch (e) {target.config.colSpan = previous.colSpan;target.config.size = previous.size;- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to resize widget', { position: 'top-center' });+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to resize widget');}}}@@ -396,10 +326,10 @@ service:{},{ projectId: projectsState.currentProjectId ?? undefined });- } catch (e: any) {+ } catch (e) {starredWidgets = previous;- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to unstar widget', { position: 'top-center' });+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to unstar widget');}}}@@ -424,6 +354,8 @@ service:</script><div class="space-y-4">+ <PageHeader title="Dashboard" />+{#if error && !loading}<ErrorDisplaystatus={errorStatus === 404@@ -491,33 +423,11 @@ service:<div class="space-y-4 p-4"><div><p class="mb-2 text-sm font-medium">OTLP Traces Endpoint</p>- <div class="flex items-center gap-2">- <code class="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-sm break-all"- >{cfOtelEndpoint}</code- >- <Button variant="outline" size="sm" onclick={copyCfEndpoint}>- {#if copiedCfEndpoint}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>- </div>+ <CopyableInline value={cfOtelEndpoint} /></div><div><p class="mb-2 text-sm font-medium">Authorization Header</p>- <div class="flex items-center gap-2">- <code class="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-sm break-all"- >{cfAuthHeader}</code- >- <Button variant="outline" size="sm" onclick={copyCfAuth}>- {#if copiedCfAuth}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>- </div>+ <CopyableInline value={cfAuthHeader} /></div></div></div>@@ -538,26 +448,7 @@ service:</p></div><div class="p-4">- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyCfWrangler}>- {#if copiedCfWrangler}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={javascript} code={cfWranglerConfig} />- </div>- </div>+ <CopyableCodeBlock code={cfWranglerConfig} language={javascript} /></div></div>@@ -577,18 +468,7 @@ service:</p></div><div class="p-4">- <div class="flex items-center gap-2">- <code class="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-sm break-all"- >npx wrangler deploy</code- >- <Button variant="outline" size="sm" onclick={copyCfDeploy}>- {#if copiedCfDeploy}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>- </div>+ <CopyableInline value="npx wrangler deploy" /></div></div>{:else if isOtelGeneric}@@ -617,17 +497,7 @@ service:<code class="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-xs break-all">{sdk.installCommand}</code>- <Button- variant="outline"- size="sm"- onclick={() => copySdkInstall(sdk.label, sdk.installCommand)}- >- {#if copiedSdkLang === sdk.label}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>+ <CopyButton text={sdk.installCommand} /></div>{/each}<p class="ml-16 pt-1 text-xs text-muted-foreground">@@ -696,26 +566,7 @@ service:</div></div><div class="p-4">- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyInstall}>- {#if copiedInstall}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={bash} code={installCommand} />- </div>- </div>+ <CopyableCodeBlock code={installCommand} language={bash} /></div></div>@@ -737,26 +588,7 @@ service:</p></div><div class="p-4">- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyCode}>- {#if copiedCode}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={highlightLanguage} code={sdkCode} />- </div>- </div>+ <CopyableCodeBlock code={sdkCode} language={highlightLanguage} /></div></div>@@ -778,50 +610,12 @@ service:</p></div><div class="p-4">- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyTesting}>- {#if copiedTesting}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={highlightLanguage} code={testingRouteCode} />- </div>- </div>+ <CopyableCodeBlock code={testingRouteCode} language={highlightLanguage} />{#if testingRouteCode2}<div class="flex justify-center p-2 italic">or</div>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyTesting2}>- {#if copiedTesting2}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={highlightLanguage} code={testingRouteCode2} />- </div>- </div>+ <CopyableCodeBlock code={testingRouteCode2} language={highlightLanguage} />{/if}</div></div>@@ -860,11 +654,11 @@ service:<div class="space-y-6">{#if starredWidgets.length > 0}<div>- <div class="items-bottom mb-4 flex gap-1">+ <div class="mb-4 flex items-center gap-1"><div class="mr-2 flex h-8 w-8 items-center justify-center rounded-md bg-yellow-500/10"><Star class="h-5 w-5 fill-yellow-400 text-yellow-400" /></div>- <h2 class="text-2xl font-bold tracking-tight">Starred</h2>+ <h2 class="text-2xl font-semibold tracking-tight">Starred</h2><Tooltip.Root><Tooltip.Trigger class="pt-1"><CircleQuestionMark class="h-4 w-4 text-muted-foreground/60" />@@ -888,11 +682,11 @@ service:{#if !isFrontend}<!-- Endpoints --><div>- <div class="items-bottom mb-4 flex gap-1">+ <div class="mb-4 flex items-center gap-1"><div class="mr-2 flex h-8 w-8 items-center justify-center rounded-md bg-chart-1/10"><Gauge class="h-5 w-5 text-chart-1" /></div>- <h2 class="text-2xl font-bold tracking-tight">Endpoints</h2>+ <h2 class="text-2xl font-semibold tracking-tight">Endpoints</h2><Tooltip.Root><Tooltip.Trigger class="pt-1"><CircleQuestionMark class="h-4 w-4 text-muted-foreground/60" />@@ -938,9 +732,9 @@ service:</Table.Row></Table.Header><Table.Body>- {#each impactfulEndpoints as endpoint}+ {#each impactfulEndpoints as endpoint, __index (__index)}<Table.Row- class="cursor-pointer hover:bg-muted/50"+ class="cursor-pointer"onclick={createRowClickHandler(`/endpoints/${encodeURIComponent(endpoint.endpoint)}?preset=24h`)}@@ -978,8 +772,8 @@ service:<!-- Empty state card for endpoints --><div class="rounded-md border bg-card"><div class="flex flex-col items-center justify-center px-6 py-12 text-center">- <div class="mb-4 flex h-12 w-12 items-center justify-center rounded-full">- <CircleCheck class="h-12 w-12 text-green-500 dark:text-green-400" />+ <div class="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">+ <CircleCheck class="h-6 w-6 text-green-500 dark:text-green-400" /></div><h3 class="mb-2 text-lg font-semibold">All Endpoints Healthy</h3><p class="mb-4 max-w-sm text-sm text-muted-foreground">@@ -987,7 +781,7 @@ service:with slow response times or high error rates will appear here when detected.</p><a- href="/endpoints"+ href={resolve('/endpoints')}class="inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline"onclick={resetEndpointsSortToImpact}>@@ -1006,7 +800,7 @@ service:<div class="mr-2 flex h-8 w-8 items-center justify-center rounded-md bg-destructive/10"><Bug class="h-5 w-5 text-destructive" /></div>- <h2 class="text-2xl font-bold tracking-tight">Issues</h2>+ <h2 class="text-2xl font-semibold tracking-tight">Issues</h2><Tooltip.Root><Tooltip.Trigger class="pt-1"><CircleQuestionMark class="h-4 w-4 text-muted-foreground/60" />@@ -1040,11 +834,11 @@ service:</Table.Row></Table.Header><Table.Body>- {#each data.recentIssues as issue}+ {#each data.recentIssues as issue, __index (__index)}{@const issueFirstLine = issue.stackTrace.split('\n')[0]}{@const issueColon = issueFirstLine.indexOf(':')}<Table.Row- class="cursor-pointer hover:bg-muted/50"+ class="cursor-pointer"onclick={createRowClickHandler(`/issues/${issue.exceptionHash}`)}><Table.Cell class="max-w-[480px] py-3" title={issue.stackTrace}>@@ -1075,8 +869,8 @@ service:<!-- Empty state card for issues --><div class="rounded-md border bg-card"><div class="flex flex-col items-center justify-center px-6 py-12 text-center">- <div class="mb-4 flex h-12 w-12 items-center justify-center rounded-full">- <CircleCheck class="h-12 w-12 text-green-500 dark:text-green-400" />+ <div class="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">+ <CircleCheck class="h-6 w-6 text-green-500 dark:text-green-400" /></div><h3 class="mb-2 text-lg font-semibold">No Issues Found</h3><p class="mb-4 max-w-sm text-sm text-muted-foreground">@@ -1084,7 +878,7 @@ service:application, they will appear here for quick triage.</p><a- href="/issues"+ href={resolve('/issues')}class="inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline">View all issues@@ -1097,62 +891,3 @@ service:</div>{/if}</div>--<style>- /* Light theme - override dark theme defaults */- :global(.light-code .hljs) {- background: #f6f8fa;- color: #24292e;- }- :global(.light-code .hljs-keyword),- :global(.light-code .hljs-selector-tag) {- color: #d73a49;- }- :global(.light-code .hljs-string),- :global(.light-code .hljs-attr) {- color: #032f62;- }- :global(.light-code .hljs-function),- :global(.light-code .hljs-title) {- color: #6f42c1;- }- :global(.light-code .hljs-comment) {- color: #6a737d;- }- :global(.light-code .hljs-built_in) {- color: #005cc5;- }- :global(.light-code .hljs-meta) {- color: #d73a49;- }- :global(.light-code .hljs-variable) {- color: #24292e;- }-- /* Dark theme - ensure dark styles apply */- :global(.dark-code .hljs) {- background: #0d1117;- color: #c9d1d9;- }- :global(.dark-code .hljs-keyword),- :global(.dark-code .hljs-selector-tag) {- color: #ff7b72;- }- :global(.dark-code .hljs-string),- :global(.dark-code .hljs-attr) {- color: #a5d6ff;- }- :global(.dark-code .hljs-function),- :global(.dark-code .hljs-title) {- color: #d2a8ff;- }- :global(.dark-code .hljs-comment) {- color: #8b949e;- }- :global(.dark-code .hljs-built_in) {- color: #79c0ff;- }- :global(.dark-code .hljs-meta) {- color: #ff7b72;- }-</style>diff --git a/frontend/src/routes/accept-invitation/+page.svelte b/frontend/src/routes/accept-invitation/+page.svelteindex 8528a8f4..b515ff93 100644--- a/frontend/src/routes/accept-invitation/+page.svelte+++ b/frontend/src/routes/accept-invitation/+page.svelte@@ -1,5 +1,7 @@<script lang="ts">+ import { resolve } from '$app/paths';import { goto } from '$app/navigation';+ import { gotoHref } from '$lib/utils/navigation';import { page } from '$app/state';import { onMount } from 'svelte';import { Button } from '$lib/components/ui/button';@@ -12,9 +14,8 @@CardHeader,CardTitle} from '$lib/components/ui/card';- import { Alert, AlertDescription, AlertTitle } from '$lib/components/ui/alert';import { ErrorAlert } from '$lib/components/ui/error-alert';- import { CircleAlert, Check } from '@lucide/svelte';+ import { Check } from '@lucide/svelte';import { authState } from '$lib/state/auth.svelte';import { projectsState } from '$lib/state/projects.svelte';import { themeState } from '$lib/state/theme.svelte';@@ -94,7 +95,7 @@projectsState.setProjects(data.projects);success = true;- setTimeout(() => goto('/'), 1500);+ setTimeout(() => goto(resolve('/')), 1500);} catch (e) {error = e instanceof Error ? e.message : 'Failed to accept invitation';} finally {@@ -123,7 +124,7 @@const data = await response.json();projectsState.setProjects(data.projects);success = true;- setTimeout(() => goto('/'), 1500);+ setTimeout(() => goto(resolve('/')), 1500);} catch (e) {error = e instanceof Error ? e.message : 'Failed to accept invitation';} finally {@@ -133,7 +134,7 @@function handleLoginRedirect() {const returnTo = encodeURIComponent(`/accept-invitation?token=${token}`);- goto(`/login?returnTo=${returnTo}`);+ gotoHref(`/login?returnTo=${returnTo}`);}function getRoleLabel(role: string): string {@@ -184,7 +185,7 @@{:else if error && !invitationInfo}<ErrorAlert {error} /><div class="mt-4 text-center">- <Button variant="outline" onclick={() => goto('/login')}>Go to Login</Button>+ <Button variant="outline" onclick={() => goto(resolve('/login'))}>Go to Login</Button></div>{:else if invitationInfo}<div class="space-y-4">@@ -211,8 +212,9 @@</Button><div><p class="text-sm text-muted-foreground">- To go to the Login page <a href="/login" class="text-primary hover:underline"- >Click Here</a+ To go to the Login page <a+ href={resolve('/login')}+ class="text-primary hover:underline">Click Here</a></p></div>diff --git a/frontend/src/routes/account/+page.svelte b/frontend/src/routes/account/+page.svelteindex dde46d95..999b9e4a 100644--- a/frontend/src/routes/account/+page.svelte+++ b/frontend/src/routes/account/+page.svelte@@ -1,18 +1,56 @@<script lang="ts">+ import { page } from '$app/state';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import PageTabs from '$lib/components/traceway/page-tabs.svelte';+ import { setTabParam } from '$lib/utils/url-params';import PersonalAccessTokens from './personal-access-tokens.svelte';import ContactMethods from './contact-methods.svelte';import NotificationRules from './notification-rules.svelte';+ const TABS = [+ { value: 'tokens', label: 'Personal Access Tokens' },+ { value: 'contact-methods', label: 'Contact Methods' },+ { value: 'notification-rules', label: 'Notification Rules' }+ ];++ const activeTab = $derived.by(() => {+ const tab = page.url.searchParams.get('tab') || 'tokens';+ return TABS.some((t) => t.value === tab) ? tab : 'tokens';+ });+let methodsVersion = $state(0);+ let tokensSection = $state<PersonalAccessTokens>();+ let methodsSection = $state<ContactMethods>();++ const newAction = $derived.by(() => {+ if (activeTab === 'tokens') {+ return { label: 'New Token', onclick: () => tokensSection?.openCreate() };+ }+ if (activeTab === 'contact-methods') {+ return { label: 'New Contact Method', onclick: () => methodsSection?.openCreate() };+ }+ return undefined;+ });</script><div class="space-y-4">- <div>- <h1 class="text-3xl font-semibold tracking-tight">Account</h1>- </div>- <PersonalAccessTokens />- <ContactMethods onMethodsChanged={() => (methodsVersion += 1)} />- {#key methodsVersion}- <NotificationRules />- {/key}+ <PageHeader title="Account" />++ <PageTabs+ tabs={TABS}+ {activeTab}+ onTabChange={(tab) => setTabParam(tab)}+ actionLabel={newAction?.label}+ onAction={newAction?.onclick}+ />++ {#if activeTab === 'tokens'}+ <PersonalAccessTokens bind:this={tokensSection} />+ {:else if activeTab === 'contact-methods'}+ <ContactMethods bind:this={methodsSection} onMethodsChanged={() => (methodsVersion += 1)} />+ {:else}+ {#key methodsVersion}+ <NotificationRules />+ {/key}+ {/if}</div>diff --git a/frontend/src/routes/account/contact-method-dialog.svelte b/frontend/src/routes/account/contact-method-dialog.svelteindex 65a60c3e..3f96ae2b 100644--- a/frontend/src/routes/account/contact-method-dialog.svelte+++ b/frontend/src/routes/account/contact-method-dialog.svelte@@ -116,10 +116,12 @@<AlertDialog.Root {open} onOpenChange={(isOpen) => (open = isOpen)}><AlertDialog.Content class="max-h-[90vh] max-w-md overflow-y-auto"><AlertDialog.Header>- <AlertDialog.Title>{isEditing ? 'Edit Contact Method' : 'New Contact Method'}</AlertDialog.Title>+ <AlertDialog.Title+ >{isEditing ? 'Edit Contact Method' : 'New Contact Method'}</AlertDialog.Title+ ><AlertDialog.Description>{isEditing- ? 'Change where Traceway reaches you when you\'re paged'+ ? "Change where Traceway reaches you when you're paged": "Add a way for Traceway to reach you when you're paged"}</AlertDialog.Description></AlertDialog.Header>@@ -213,7 +215,12 @@{:else if methodType === 'sms'}<div class="space-y-2"><Label for="cm-sms-phone">Phone Number</Label>- <Input id="cm-sms-phone" bind:value={smsPhoneNumber} placeholder="+12025550123" required />+ <Input+ id="cm-sms-phone"+ bind:value={smsPhoneNumber}+ placeholder="+12025550123"+ required+ /><p class="text-xs text-muted-foreground">International format with country code (E.164)</p>diff --git a/frontend/src/routes/account/contact-methods.svelte b/frontend/src/routes/account/contact-methods.svelteindex e18811aa..e2887eed 100644--- a/frontend/src/routes/account/contact-methods.svelte+++ b/frontend/src/routes/account/contact-methods.svelte@@ -2,16 +2,16 @@import { onMount } from 'svelte';import { Button } from '$lib/components/ui/button';import * as Table from '$lib/components/ui/table';- import * as Alert from '$lib/components/ui/alert';- import * as AlertDialog from '$lib/components/ui/alert-dialog';import { Switch } from '$lib/components/ui/switch';import { Badge } from '$lib/components/ui/badge';- import { ErrorAlert } from '$lib/components/ui/error-alert';import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import InfoCallout from '$lib/components/traceway/info-callout.svelte';+ import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';import {- Plus,Trash2,- Info,Send,Mail,MessageSquare,@@ -37,9 +37,14 @@let loading = $state(true);let loadError = $state('');let showCreate = $state(false);++ export function openCreate() {+ showCreate = true;+ }let showEdit = $state(false);let methodToEdit = $state<ContactMethod | null>(null);let methodToDelete = $state<ContactMethod | null>(null);+ let deleteDialogOpen = $state(false);let deleting = $state(false);let deleteError = $state('');let testingId = $state<number | null>(null);@@ -127,13 +132,9 @@async function toggleEnabled(method: ContactMethod, enabled: boolean) {try {await api.put(`/contact-methods/${method.id}`, { enabled });- toast.success(`Successfully ${enabled ? 'enabled' : 'disabled'} the Contact Method`, {- position: 'top-center'- });+ toast.success(`Successfully ${enabled ? 'enabled' : 'disabled'} the Contact Method`);} catch (e: unknown) {- toast.error(e instanceof Error ? e.message : 'Failed to update contact method', {- position: 'top-center'- });+ toast.error(e instanceof Error ? e.message : 'Failed to update contact method');}loadMethods();}@@ -142,11 +143,9 @@testingId = method.id;try {await api.post(`/contact-methods/${method.id}/test`, {});- toast.success('Test notification sent', { position: 'top-center' });+ toast.success('Test notification sent');} catch (e: unknown) {- toast.error(e instanceof Error ? e.message : 'Failed to send test notification', {- position: 'top-center'- });+ toast.error(e instanceof Error ? e.message : 'Failed to send test notification');} finally {testingId = null;}@@ -158,7 +157,8 @@deleteError = '';try {await api.delete(`/contact-methods/${methodToDelete.id}`);- toast.success('Successfully deleted the Contact Method', { position: 'top-center' });+ toast.success('Successfully deleted the Contact Method');+ deleteDialogOpen = false;methodToDelete = null;loadMethods();onMethodsChanged?.();@@ -170,44 +170,23 @@}</script>-<div class="flex items-center justify-between">- <h2 class="text-xl font-semibold tracking-tight">Contact Methods</h2>- <Button variant="success" onclick={() => (showCreate = true)}>- <Plus class="mr-1 h-4 w-4" /> New Contact Method- </Button>-</div>--<Alert.Root- class="border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950/50 dark:text-blue-200"->- <Info class="text-blue-600 dark:text-blue-400" />- <Alert.Description class="text-blue-800 dark:text-blue-300">- When you're paged, Traceway notifies every enabled method. With none configured, your account- email is used.- </Alert.Description>-</Alert.Root>+<InfoCallout>+ When you're paged, Traceway notifies every enabled method. With none configured, your account+ email is used.+</InfoCallout>{#if loading}<div class="flex justify-center py-12"><LoadingCircle size="lg" /></div>{:else if loadError}- <div- class="flex flex-col items-center justify-center gap-3 rounded-md bg-muted py-20 text-center text-muted-foreground"- >- <p class="text-sm text-destructive">{loadError}</p>- <Button variant="outline" size="sm" onclick={() => loadMethods()}>Retry</Button>- </div>+ <ErrorRetryBox message={loadError} onRetry={() => loadMethods()} />{:else if methods.length === 0}- <div- class="flex flex-col items-center justify-center rounded-md bg-muted py-20 text-center text-muted-foreground"- >- <p class="mb-4">No contact methods yet. Pages fall back to your account email.</p>- <Button variant="success" onclick={() => (showCreate = true)}>- <Plus class="mr-1 h-4 w-4" />- Create your first Contact Method- </Button>- </div>+ <EmptyState+ message="No contact methods yet. Pages fall back to your account email."+ actionLabel="Create your first Contact Method"+ onAction={() => (showCreate = true)}+ />{:else}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root><Table.Header><Table.Row class="hover:bg-transparent">@@ -231,7 +210,10 @@<div class="flex items-center gap-2">{methodSummary(method)}{#if isUnsendableSms(method)}- <Badge variant="outline" title="This instance has no Twilio credentials configured">+ <Badge+ variant="outline"+ title="This instance has no Twilio credentials configured"+ >SMS unavailable</Badge>{:else if isUnverifiedSms(method)}@@ -294,6 +276,7 @@onclick={() => {deleteError = '';methodToDelete = method;+ deleteDialogOpen = true;}}><Trash2 class="h-4 w-4 text-destructive" />@@ -304,7 +287,7 @@{/each}</Table.Body></Table.Root>- </div>+ </TableContainer>{/if}<ContactMethodDialog@@ -341,31 +324,11 @@onVerified={() => loadMethods()}/>-<AlertDialog.Root- open={methodToDelete !== null}- onOpenChange={(open) => {- if (!open) {- methodToDelete = null;- deleteError = '';- }- }}->- <AlertDialog.Content>- <AlertDialog.Header>- <AlertDialog.Title>Delete Contact Method</AlertDialog.Title>- <AlertDialog.Description>- Are you sure you want to delete this {methodTypeLabels[methodToDelete?.methodType ?? ''] ??- ''} contact method? You will no longer be paged through it, and any step of your- notification rules that uses it is removed too. To change where it points, edit it instead.- </AlertDialog.Description>- </AlertDialog.Header>- <ErrorAlert error={deleteError} />- <AlertDialog.Footer>- <AlertDialog.Cancel disabled={deleting}>Cancel</AlertDialog.Cancel>- <Button variant="destructive" onclick={confirmDelete} disabled={deleting}>- <Trash2 class="mr-2 h-4 w-4" />- {deleting ? 'Deleting...' : 'Delete Contact Method'}- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>-</AlertDialog.Root>+<ConfirmDeleteDialog+ bind:open={deleteDialogOpen}+ entity="Contact Method"+ description={`Are you sure you want to delete this ${methodTypeLabels[methodToDelete?.methodType ?? ''] ?? ''} contact method? You will no longer be paged through it, and any step of your notification rules that uses it is removed too. To change where it points, edit it instead.`}+ error={deleteError}+ loading={deleting}+ onConfirm={confirmDelete}+/>diff --git a/frontend/src/routes/account/create-token-dialog.svelte b/frontend/src/routes/account/create-token-dialog.svelteindex e4735e73..d47e8009 100644--- a/frontend/src/routes/account/create-token-dialog.svelte+++ b/frontend/src/routes/account/create-token-dialog.svelte@@ -82,7 +82,13 @@Use this token to authenticate the Traceway CLI or scripts.</AlertDialog.Description></AlertDialog.Header>- <form onsubmit={(e) => { e.preventDefault(); handleCreate(); }} class="space-y-4">+ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleCreate();+ }}+ class="space-y-4"+ ><ErrorAlert {error} /><div class="space-y-2"><Label for="token-name">Name</Label>@@ -95,7 +101,7 @@{expiryOptions.find((o) => o.value === expiry)?.label || 'Select'}</Select.Trigger><Select.Content>- {#each expiryOptions as option}+ {#each expiryOptions as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content>diff --git a/frontend/src/routes/account/notification-rules.svelte b/frontend/src/routes/account/notification-rules.svelteindex 11ee0ea7..baba769d 100644--- a/frontend/src/routes/account/notification-rules.svelte+++ b/frontend/src/routes/account/notification-rules.svelte@@ -5,6 +5,7 @@import * as Select from '$lib/components/ui/select';import { ErrorAlert } from '$lib/components/ui/error-alert';import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';import { Plus, Check, Trash2, ChevronUp, ChevronDown } from '@lucide/svelte';import { toast } from 'svelte-sonner';import { api } from '$lib/api';@@ -231,22 +232,15 @@</div>{/snippet}-<div class="flex items-center justify-between">- <h2 class="text-xl font-semibold tracking-tight">Notification Rules</h2>-</div>-<p class="text-sm text-muted-foreground">- When a page targets you, these steps run for its urgency until you acknowledge. With no steps,- all your contact methods are notified immediately.+ When a page targets you, these steps run for its urgency until you acknowledge. With no steps, all+ your contact methods are notified immediately.</p>{#if loading}<div class="flex justify-center py-12"><LoadingCircle size="lg" /></div>{:else if loadError}- <div class="flex flex-col items-center justify-center gap-3 rounded-md bg-muted py-12 text-center">- <p class="text-sm text-destructive">{loadError}</p>- <Button variant="outline" size="sm" onclick={() => load()}>Retry</Button>- </div>+ <ErrorRetryBox message={loadError} onRetry={() => load()} />{:else}<div class="space-y-6"><ErrorAlert {error} />diff --git a/frontend/src/routes/account/personal-access-tokens.svelte b/frontend/src/routes/account/personal-access-tokens.svelteindex 7c79eec4..c5255b5f 100644--- a/frontend/src/routes/account/personal-access-tokens.svelte+++ b/frontend/src/routes/account/personal-access-tokens.svelte@@ -2,13 +2,17 @@import { onMount } from 'svelte';import { Button } from '$lib/components/ui/button';import * as Table from '$lib/components/ui/table';- import * as Alert from '$lib/components/ui/alert';- import * as AlertDialog from '$lib/components/ui/alert-dialog';import { Badge } from '$lib/components/ui/badge';- import { ErrorAlert } from '$lib/components/ui/error-alert';import { LoadingCircle } from '$lib/components/ui/loading-circle';- import { Plus, Trash2, Info } from '@lucide/svelte';+ import InfoCallout from '$lib/components/traceway/info-callout.svelte';+ import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import StatusPill from '$lib/components/traceway/status-pill.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';+ import { Trash2 } from '@lucide/svelte';import { toast } from 'svelte-sonner';+ import { formatDateTime } from '$lib/utils/formatters';import {personalAccessTokensState,type PersonalAccessToken@@ -16,7 +20,12 @@import CreateTokenDialog from './create-token-dialog.svelte';let showCreate = $state(false);++ export function openCreate() {+ showCreate = true;+ }let tokenToRevoke = $state<PersonalAccessToken | null>(null);+ let revokeDialogOpen = $state(false);let revoking = $state(false);let revokeError = $state('');@@ -24,11 +33,7 @@function formatDate(value: string | null): string {if (!value) return '';- return new Date(value).toLocaleDateString(undefined, {- year: 'numeric',- month: 'short',- day: 'numeric'- });+ return formatDateTime(value, { format: 'date' });}function isExpired(value: string | null): boolean {@@ -41,7 +46,8 @@revokeError = '';try {await personalAccessTokensState.revoke(tokenToRevoke.id);- toast.success('Successfully revoked the Token', { position: 'top-center' });+ toast.success('Successfully revoked the Token');+ revokeDialogOpen = false;tokenToRevoke = null;} catch (e: unknown) {revokeError = e instanceof Error ? e.message : 'Failed to revoke token';@@ -51,36 +57,25 @@}</script>-<div class="flex items-center justify-between">- <h2 class="text-xl font-semibold tracking-tight">Personal Access Tokens</h2>- <Button variant="success" onclick={() => (showCreate = true)}>- <Plus class="mr-1 h-4 w-4" /> New Token- </Button>-</div>--<Alert.Root- class="border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950/50 dark:text-blue-200"->- <Info class="text-blue-600 dark:text-blue-400" />- <Alert.Description class="text-blue-800 dark:text-blue-300">- Authenticate the Traceway CLI or scripts without a browser. Treat tokens like passwords.- </Alert.Description>-</Alert.Root>+<InfoCallout>+ Authenticate the Traceway CLI or scripts without a browser. Treat tokens like passwords.+</InfoCallout>{#if personalAccessTokensState.loading}<div class="flex justify-center py-12"><LoadingCircle size="lg" /></div>+{:else if personalAccessTokensState.error}+ <ErrorRetryBox+ message={personalAccessTokensState.error}+ onRetry={() => personalAccessTokensState.load()}+ />{:else if personalAccessTokensState.tokens.length === 0}- <div- class="flex flex-col items-center justify-center rounded-md bg-muted py-20 text-center text-muted-foreground"- >- <p class="mb-4">No tokens yet. Create one to get started.</p>- <Button variant="success" onclick={() => (showCreate = true)}>- <Plus class="mr-1 h-4 w-4" />- Create your first Token- </Button>- </div>+ <EmptyState+ message="No tokens yet. Create one to get started."+ actionLabel="Create your first Token"+ onAction={() => (showCreate = true)}+ />{:else}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root><Table.Header><Table.Row class="hover:bg-transparent">@@ -111,15 +106,21 @@{#if !token.expiresAt}<span class="text-muted-foreground">Never</span>{:else if isExpired(token.expiresAt)}- <Badge variant="outline" class="border-amber-200 bg-amber-50 text-amber-700"- >Expired</Badge- >+ <StatusPill tone="warning" label="Expired" />{:else}{formatDate(token.expiresAt)}{/if}</Table.Cell><Table.Cell>- <Button variant="ghost" size="icon" onclick={() => (tokenToRevoke = token)}>+ <Button+ variant="ghost"+ size="icon"+ onclick={() => {+ revokeError = '';+ tokenToRevoke = token;+ revokeDialogOpen = true;+ }}+ ><Trash2 class="h-4 w-4 text-destructive" /></Button></Table.Cell>@@ -127,35 +128,17 @@{/each}</Table.Body></Table.Root>- </div>+ </TableContainer>{/if}<CreateTokenDialog bind:open={showCreate} />-<AlertDialog.Root- open={tokenToRevoke !== null}- onOpenChange={(open) => {- if (!open) {- tokenToRevoke = null;- revokeError = '';- }- }}->- <AlertDialog.Content>- <AlertDialog.Header>- <AlertDialog.Title>Revoke Token</AlertDialog.Title>- <AlertDialog.Description>- This permanently revokes {tokenToRevoke?.name ? `"${tokenToRevoke.name}"` : 'this token'}.- Any CLI or script using it will stop working immediately.- </AlertDialog.Description>- </AlertDialog.Header>- <ErrorAlert error={revokeError} />- <AlertDialog.Footer>- <AlertDialog.Cancel disabled={revoking}>Cancel</AlertDialog.Cancel>- <Button variant="destructive" onclick={confirmRevoke} disabled={revoking}>- <Trash2 class="mr-2 h-4 w-4" />- {revoking ? 'Revoking…' : 'Revoke Token'}- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>-</AlertDialog.Root>+<ConfirmDeleteDialog+ bind:open={revokeDialogOpen}+ entity="Token"+ verb="Revoke"+ description={`This permanently revokes ${tokenToRevoke?.name ? `"${tokenToRevoke.name}"` : 'this token'}. Any CLI or script using it will stop working immediately.`}+ error={revokeError}+ loading={revoking}+ onConfirm={confirmRevoke}+/>diff --git a/frontend/src/routes/account/verify-code-dialog.svelte b/frontend/src/routes/account/verify-code-dialog.svelteindex 03bc9033..3db65a51 100644--- a/frontend/src/routes/account/verify-code-dialog.svelte+++ b/frontend/src/routes/account/verify-code-dialog.svelte@@ -16,7 +16,13 @@onVerified: () => void;}- let { open = $bindable(), methodId, phoneLabel, codeJustSent = false, onVerified }: Props = $props();+ let {+ open = $bindable(),+ methodId,+ phoneLabel,+ codeJustSent = false,+ onVerified+ }: Props = $props();let code = $state('');let loading = $state(false);@@ -61,7 +67,7 @@error = '';try {await api.post(`/contact-methods/${methodId}/verify`, { code: code.trim() });- toast.success('Successfully verified the Contact Method', { position: 'top-center' });+ toast.success('Successfully verified the Contact Method');open = false;onVerified();} catch (e: unknown) {@@ -77,7 +83,7 @@error = '';try {await api.post(`/contact-methods/${methodId}/resend-code`, {});- toast.success('Verification code sent', { position: 'top-center' });+ toast.success('Verification code sent');startCountdown();} catch (e: unknown) {error = e instanceof Error ? e.message : 'Failed to resend the code';diff --git a/frontend/src/routes/ack/[token]/+page.svelte b/frontend/src/routes/ack/[token]/+page.svelteindex 14776bea..31e9ede0 100644--- a/frontend/src/routes/ack/[token]/+page.svelte+++ b/frontend/src/routes/ack/[token]/+page.svelte@@ -1,8 +1,14 @@<script lang="ts">import { onMount } from 'svelte';import { Button } from '$lib/components/ui/button';- import { Badge } from '$lib/components/ui/badge';- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '$lib/components/ui/card';+ import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle+ } from '$lib/components/ui/card';+ import PageBadges from '$lib/components/traceway/page-badges.svelte';import { WarningCallout } from '$lib/components/ui/warning-callout';import { ErrorAlert } from '$lib/components/ui/error-alert';import { Check, CircleCheck } from '@lucide/svelte';@@ -127,18 +133,7 @@<div class="space-y-2"><h2 class="text-lg font-semibold">{info.subject || 'Page'}</h2><div class="flex flex-wrap items-center gap-2">- {#if info.severity === 'critical'}- <Badge variant="destructive">Critical</Badge>- {:else if info.severity === 'warning'}- <Badge class="bg-amber-500 text-white">Warning</Badge>- {:else if info.severity === 'info'}- <Badge variant="secondary">Info</Badge>- {/if}- {#if info.urgency === 'high'}- <Badge class="bg-rose-700 text-white">High urgency</Badge>- {:else if info.urgency === 'low'}- <Badge variant="secondary">Low urgency</Badge>- {/if}+ <PageBadges severity={info.severity} urgency={info.urgency} longUrgency /></div></div>diff --git a/frontend/src/routes/ai-traces/+page.svelte b/frontend/src/routes/ai-traces/+page.svelteindex aad4caed..f905b195 100644--- a/frontend/src/routes/ai-traces/+page.svelte+++ b/frontend/src/routes/ai-traces/+page.svelte@@ -1,412 +1,437 @@<script lang="ts">- import { onMount, onDestroy } from 'svelte';- import { api } from '$lib/api';- import { formatDuration, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';- import { getTimezone } from '$lib/state/timezone.svelte';- import * as Table from "$lib/components/ui/table";- import { LoadingCircle } from "$lib/components/ui/loading-circle";- import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";- import { TableEmptyState } from "$lib/components/ui/table-empty-state";- import { PaginationFooter } from "$lib/components/ui/pagination-footer";- import { TimeRangePicker } from "$lib/components/ui/time-range-picker";- import { SearchBar } from "$lib/components/ui/search-bar";- import { RootFilter } from "$lib/components/ui/root-filter";- import { NonRootChip } from "$lib/components/ui/non-root-chip";- import { browser } from '$app/environment';- import { CalendarDate } from "@internationalized/date";- import { projectsState } from '$lib/state/projects.svelte';- import { createRowClickHandler } from '$lib/utils/navigation';- import { resolve } from '$app/paths';- import PageHeader from '$lib/components/issues/page-header.svelte';- import { formatCost, formatCount, formatTokens } from '$lib/utils/ai-format';- import AiNavTabs from '$lib/components/ai/ai-nav-tabs.svelte';- import {- presetMinutes,- getTimeRangeFromPreset,- dateToCalendarDate,- dateToTimeString,- parseTimeRangeFromUrl,- getResolvedTimeRange,- updateUrl- } from '$lib/utils/url-params';- import {- getSortState,- setSortState,- handleSortClick,- type SortDirection- } from '$lib/utils/sort-storage';-- const timezone = $derived(getTimezone());- const initialTimezone = getTimezone();-- type AiTraceStats = {- traceName: string;- count: number;- p50Duration: number;- p95Duration: number;- avgDuration: number;- totalTokens: number;- totalCost: number;- avgInputTokens: number;- avgOutputTokens: number;- lastSeen: string;- hasRoot: boolean;- hasNonRoot: boolean;- };-- type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'total_tokens' | 'total_cost' | 'last_seen';-- let traces = $state<AiTraceStats[]>([]);- let loading = $state(true);- let error = $state('');-- // Pagination State- let page = $state(1);- let pageSize = $state(50);- let total = $state(0);- let totalPages = $state(0);-- // Parse URL params including search + rootFilter- function parseAiTracesUrlParams() {- if (!browser) return { preset: '24h', from: null, to: null, search: '', rootFilter: 'all' };- const params = new URLSearchParams(window.location.search);- const timeParams = parseTimeRangeFromUrl(timezone, '24h');- return {- ...timeParams,- search: params.get('search') || '',- rootFilter: params.get('rootFilter') || 'all'- };- }-- // Initialize from URL- const initialUrlParams = parseAiTracesUrlParams();- const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);-- // Search + rootFilter state- let searchQuery = $state(initialUrlParams.search);- let rootFilter = $state(initialUrlParams.rootFilter);-- // Date Range State- let selectedPreset = $state<string | null>(initialUrlParams.preset);- let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));- let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));- let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));- let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));-- // Update URL with current time range and search- function updateTimeRangeUrl(pushToHistory = true) {- const params: Record<string, string | null | undefined> = {};- if (selectedPreset) {- params.preset = selectedPreset;- } else {- params.from = getFromDateTimeUTC();- params.to = getToDateTimeUTC();- }- if (searchQuery.trim()) {- params.search = searchQuery.trim();- }- if (rootFilter && rootFilter !== 'all') {- params.rootFilter = rootFilter;- }- updateUrl(params, { pushToHistory });- }-- // Handle browser back/forward navigation- function handlePopState() {- const urlParams = parseAiTracesUrlParams();- const range = getResolvedTimeRange(urlParams, timezone);-- selectedPreset = urlParams.preset;- fromDate = dateToCalendarDate(range.from, timezone);- fromTime = dateToTimeString(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- toTime = dateToTimeString(range.to, timezone);- searchQuery = urlParams.search;- rootFilter = urlParams.rootFilter;-- page = 1;- loadData(false);- }-- // Sorting - persisted to localStorage- const SORT_STORAGE_KEY = 'ai-traces';- const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'total_cost', direction: 'desc' });- let orderBy = $state<SortField>(initialSort.field as SortField);- let sortDirection = $state<SortDirection>(initialSort.direction);-- // Combine date and time into UTC ISO datetime string- function getFromDateTimeUTC(): string {- const [hour, minute] = (fromTime || '00:00').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute }, timezone);- return toUTCISO(dt);- }-- function getToDateTimeUTC(): string {- const [hour, minute] = (toTime || '23:59').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: toDate.year, month: toDate.month, day: toDate.day, hour, minute }, timezone).endOf('minute');- return toUTCISO(dt);- }-- function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) {- fromDate = from.date;- fromTime = from.time;- toDate = to.date;- toTime = to.time;- selectedPreset = preset;- page = 1;- loadData(false);- }-- async function loadData(pushToHistory = true) {- loading = true;- error = '';-- if (selectedPreset) {- const range = getTimeRangeFromPreset(selectedPreset, timezone);- fromDate = dateToCalendarDate(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- fromTime = dateToTimeString(range.from, timezone);- toTime = dateToTimeString(range.to, timezone);- }-- // Update URL- updateTimeRangeUrl(pushToHistory);-- try {- const requestBody = {- fromDate: getFromDateTimeUTC(),- toDate: getToDateTimeUTC(),- orderBy: orderBy,- sortDirection: sortDirection,- pagination: {- page: page,- pageSize: pageSize- },- search: searchQuery.trim(),- rootFilter: rootFilter === 'all' ? '' : rootFilter- };-- const response = await api.post('/ai-traces/grouped', requestBody, { projectId: projectsState.currentProjectId ?? undefined });-- traces = response.data || [];- total = response.pagination.total;- totalPages = response.pagination.totalPages;- } catch (e: any) {- console.error(e);- error = e.message || 'Failed to load data';- } finally {- loading = false;- }- }-- function handlePageChange(newPage: number) {- if (newPage >= 1 && newPage <= totalPages) {- page = newPage;- loadData(false);- }- }-- function handlePageSizeChange(newPageSize: number) {- pageSize = newPageSize;- page = 1;- loadData(false);- }-- function handleSort(field: SortField) {- const newSort = handleSortClick(field, orderBy, sortDirection);- orderBy = newSort.field as SortField;- sortDirection = newSort.direction;- setSortState(SORT_STORAGE_KEY, newSort);- page = 1;- loadData(false);- }-- function handleSearch() {- page = 1;- loadData(true);- }-- onMount(() => {- // Add popstate listener for back/forward navigation- window.addEventListener('popstate', handlePopState);-- // Initial load with replaceState (don't push to history)- loadData(false);- });-- onDestroy(() => {- if (typeof window !== 'undefined') {- window.removeEventListener('popstate', handlePopState);- }- });+ import { getErrorMessage } from '$lib/utils/errors';+ import { onMount, onDestroy } from 'svelte';+ import { api } from '$lib/api';+ import {+ formatDuration,+ formatDateTime,+ toUTCISO,+ calendarDateTimeToLuxon+ } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import * as Table from '$lib/components/ui/table';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { TimeRangePicker } from '$lib/components/ui/time-range-picker';+ import { SearchBar } from '$lib/components/ui/search-bar';+ import { RootFilter } from '$lib/components/ui/root-filter';+ import { NonRootChip } from '$lib/components/ui/non-root-chip';+ import { browser } from '$app/environment';+ import { CalendarDate } from '@internationalized/date';+ import { projectsState } from '$lib/state/projects.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { resolve } from '$app/paths';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import { formatCost, formatCount, formatTokens } from '$lib/utils/ai-format';+ import AiNavTabs from '$lib/components/ai/ai-nav-tabs.svelte';+ import {+ getTimeRangeFromPreset,+ dateToCalendarDate,+ dateToTimeString,+ parseTimeRangeFromUrl,+ getResolvedTimeRange,+ updateUrl+ } from '$lib/utils/url-params';+ import {+ getSortState,+ setSortState,+ handleSortClick,+ type SortDirection+ } from '$lib/utils/sort-storage';++ const timezone = $derived(getTimezone());+ const initialTimezone = getTimezone();++ type AiTraceStats = {+ traceName: string;+ count: number;+ p50Duration: number;+ p95Duration: number;+ avgDuration: number;+ totalTokens: number;+ totalCost: number;+ avgInputTokens: number;+ avgOutputTokens: number;+ lastSeen: string;+ hasRoot: boolean;+ hasNonRoot: boolean;+ };++ type SortField =+ | 'count'+ | 'p50_duration'+ | 'p95_duration'+ | 'total_tokens'+ | 'total_cost'+ | 'last_seen';++ let traces = $state<AiTraceStats[]>([]);+ let loading = $state(true);+ let error = $state('');++ // Pagination State+ let page = $state(1);+ let pageSize = $state(50);+ let total = $state(0);+ let totalPages = $state(0);++ // Parse URL params including search + rootFilter+ function parseAiTracesUrlParams() {+ if (!browser) return { preset: '24h', from: null, to: null, search: '', rootFilter: 'all' };+ const params = new URLSearchParams(window.location.search);+ const timeParams = parseTimeRangeFromUrl(timezone, '24h');+ return {+ ...timeParams,+ search: params.get('search') || '',+ rootFilter: params.get('rootFilter') || 'all'+ };+ }++ // Initialize from URL+ const initialUrlParams = parseAiTracesUrlParams();+ const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);++ // Search + rootFilter state+ let searchQuery = $state(initialUrlParams.search);+ let rootFilter = $state(initialUrlParams.rootFilter);++ // Date Range State+ let selectedPreset = $state<string | null>(initialUrlParams.preset);+ let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));+ let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));+ let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));+ let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));++ // Update URL with current time range and search+ function updateTimeRangeUrl(pushToHistory = true) {+ const params: Record<string, string | null | undefined> = {};+ if (selectedPreset) {+ params.preset = selectedPreset;+ } else {+ params.from = getFromDateTimeUTC();+ params.to = getToDateTimeUTC();+ }+ if (searchQuery.trim()) {+ params.search = searchQuery.trim();+ }+ if (rootFilter && rootFilter !== 'all') {+ params.rootFilter = rootFilter;+ }+ updateUrl(params, { pushToHistory });+ }++ // Handle browser back/forward navigation+ function handlePopState() {+ const urlParams = parseAiTracesUrlParams();+ const range = getResolvedTimeRange(urlParams, timezone);++ selectedPreset = urlParams.preset;+ fromDate = dateToCalendarDate(range.from, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ toTime = dateToTimeString(range.to, timezone);+ searchQuery = urlParams.search;+ rootFilter = urlParams.rootFilter;++ page = 1;+ loadData(false);+ }++ // Sorting - persisted to localStorage+ const SORT_STORAGE_KEY = 'ai-traces';+ const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'total_cost', direction: 'desc' });+ let orderBy = $state<SortField>(initialSort.field as SortField);+ let sortDirection = $state<SortDirection>(initialSort.direction);++ // Combine date and time into UTC ISO datetime string+ function getFromDateTimeUTC(): string {+ const [hour, minute] = (fromTime || '00:00').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute },+ timezone+ );+ return toUTCISO(dt);+ }++ function getToDateTimeUTC(): string {+ const [hour, minute] = (toTime || '23:59').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: toDate.year, month: toDate.month, day: toDate.day, hour, minute },+ timezone+ ).endOf('minute');+ return toUTCISO(dt);+ }++ function handleTimeRangeChange(+ from: { date: CalendarDate; time: string },+ to: { date: CalendarDate; time: string },+ preset: string | null+ ) {+ fromDate = from.date;+ fromTime = from.time;+ toDate = to.date;+ toTime = to.time;+ selectedPreset = preset;+ page = 1;+ loadData(false);+ }++ async function loadData(pushToHistory = true) {+ loading = true;+ error = '';++ if (selectedPreset) {+ const range = getTimeRangeFromPreset(selectedPreset, timezone);+ fromDate = dateToCalendarDate(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toTime = dateToTimeString(range.to, timezone);+ }++ // Update URL+ updateTimeRangeUrl(pushToHistory);++ try {+ const requestBody = {+ fromDate: getFromDateTimeUTC(),+ toDate: getToDateTimeUTC(),+ orderBy: orderBy,+ sortDirection: sortDirection,+ pagination: {+ page: page,+ pageSize: pageSize+ },+ search: searchQuery.trim(),+ rootFilter: rootFilter === 'all' ? '' : rootFilter+ };++ const response = await api.post('/ai-traces/grouped', requestBody, {+ projectId: projectsState.currentProjectId ?? undefined+ });++ traces = response.data || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e) {+ console.error(e);+ error = getErrorMessage(e) || 'Failed to load data';+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData(false);+ }+ }++ function handlePageSizeChange(newPageSize: number) {+ pageSize = newPageSize;+ page = 1;+ loadData(false);+ }++ function handleSort(field: SortField) {+ const newSort = handleSortClick(field, orderBy, sortDirection);+ orderBy = newSort.field as SortField;+ sortDirection = newSort.direction;+ setSortState(SORT_STORAGE_KEY, newSort);+ page = 1;+ loadData(false);+ }++ function handleSearch() {+ page = 1;+ loadData(true);+ }++ onMount(() => {+ // Add popstate listener for back/forward navigation+ window.addEventListener('popstate', handlePopState);++ // Initial load with replaceState (don't push to history)+ loadData(false);+ });++ onDestroy(() => {+ if (typeof window !== 'undefined') {+ window.removeEventListener('popstate', handlePopState);+ }+ });</script><div class="space-y-4">- <!-- Header with Title and Time Range Filter -->- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">- <PageHeader title="AI Traces" />- <div class="flex flex-col">- <TimeRangePicker- bind:fromDate- bind:toDate- bind:fromTime- bind:toTime- bind:preset={selectedPreset}- onApply={handleTimeRangeChange}- />- </div>- </div>-- <AiNavTabs active="traces" />-- <!-- Search -->- <SearchBar- placeholder="Search traces..."- bind:value={searchQuery}- onSearch={handleSearch}- disabled={loading}- >- {#snippet children()}- <RootFilter bind:value={rootFilter} />- {/snippet}- </SearchBar>-- <!-- AI Traces Table -->- <div class="rounded-md border overflow-hidden">- <Table.Root>- {#if loading}- <Table.Body>- <Table.Row>- <Table.Cell colspan={7} class="h-48">- <div class="flex justify-center items-center h-full">- <LoadingCircle size="xlg" />- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if error}- <Table.Body>- <Table.Row>- <Table.Cell colspan={7} class="h-24 text-center text-red-500">- {error}- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if traces.length === 0}- <Table.Body>- <TableEmptyState colspan={7} message="No AI trace data available for your search parameters" />- </Table.Body>- {:else}- <Table.Header>- <Table.Row>- <TracewayTableHeader- label="Trace Name"- tooltip="The AI agent or workflow name"- />- <TracewayTableHeader- label="Calls"- tooltip="Total number of AI calls"- sortField="count"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[80px]"- />- <TracewayTableHeader- label="Typical"- tooltip="Median duration (P50)"- sortField="p50_duration"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Slow"- tooltip="95th percentile duration"- sortField="p95_duration"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Total Tokens"- tooltip="Total tokens consumed"- sortField="total_tokens"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[110px]"- />- <TracewayTableHeader- label="Total Cost"- tooltip="Total cost across all calls"- sortField="total_cost"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Last Seen"- tooltip="When the last call occurred"- sortField="last_seen"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- </Table.Row>- </Table.Header>- <Table.Body>- {#each traces as trace}- <!-- Trace names "conversations" and "users" are shadowed by the+ <PageHeader title="AI Traces">+ {#snippet actions()}+ <TimeRangePicker+ bind:fromDate+ bind:toDate+ bind:fromTime+ bind:toTime+ bind:preset={selectedPreset}+ onApply={handleTimeRangeChange}+ />+ {/snippet}+ </PageHeader>++ <AiNavTabs active="traces" />++ <!-- Search -->+ <SearchBar+ placeholder="Search traces..."+ bind:value={searchQuery}+ onSearch={handleSearch}+ disabled={loading}+ >+ <RootFilter bind:value={rootFilter} />+ </SearchBar>++ <!-- AI Traces Table -->+ <TableContainer>+ <Table.Root>+ {#if loading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={7} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if error}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={7} class="h-24 text-center text-red-500">+ {error}+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if traces.length === 0}+ <Table.Body>+ <TableEmptyState+ colspan={7}+ message="No AI trace data available for your search parameters"+ />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader label="Trace Name" tooltip="The AI agent or workflow name" />+ <TracewayTableHeader+ label="Calls"+ tooltip="Total number of AI calls"+ sortField="count"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[80px]"+ />+ <TracewayTableHeader+ label="Typical"+ tooltip="Median duration (P50)"+ sortField="p50_duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Slow"+ tooltip="95th percentile duration"+ sortField="p95_duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Total Tokens"+ tooltip="Total tokens consumed"+ sortField="total_tokens"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[110px]"+ />+ <TracewayTableHeader+ label="Total Cost"+ tooltip="Total cost across all calls"+ sortField="total_cost"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Last Seen"+ tooltip="When the last call occurred"+ sortField="last_seen"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each traces as trace, __index (__index)}+ <!-- Trace names "conversations" and "users" are shadowed by thestatic sibling routes, so those two names are unreachable here. -->- <Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={createRowClickHandler(resolve(`/ai-traces/${encodeURIComponent(trace.traceName)}`), 'preset', 'from', 'to')}- >- <Table.Cell class="font-mono text-sm">- {trace.traceName}- {#if trace.hasNonRoot}- <NonRootChip mixed={trace.hasRoot && trace.hasNonRoot} />- {/if}- </Table.Cell>- <Table.Cell class="tabular-nums">- {formatCount(trace.count)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {formatDuration(trace.p50Duration)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {formatDuration(trace.p95Duration)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {formatTokens(trace.totalTokens)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {formatCost(trace.totalCost)}- </Table.Cell>- <Table.Cell class="text-muted-foreground text-sm">- {new Date(trace.lastSeen).toLocaleDateString()}- </Table.Cell>- </Table.Row>- {/each}- </Table.Body>- {/if}- </Table.Root>- </div>-- <!-- Pagination Footer -->- <PaginationFooter- currentPage={page}- {totalPages}- {pageSize}- totalItems={total}- onPageChange={handlePageChange}- onPageSizeChange={handlePageSizeChange}- {loading}- itemLabel="trace"- />+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ resolve(`/ai-traces/${encodeURIComponent(trace.traceName)}`),+ 'preset',+ 'from',+ 'to'+ )}+ >+ <Table.Cell class="font-mono text-sm">+ {trace.traceName}+ {#if trace.hasNonRoot}+ <NonRootChip mixed={trace.hasRoot && trace.hasNonRoot} />+ {/if}+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ {formatCount(trace.count)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatDuration(trace.p50Duration)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatDuration(trace.p95Duration)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatTokens(trace.totalTokens)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatCost(trace.totalCost)}+ </Table.Cell>+ <Table.Cell class="text-sm text-muted-foreground">+ {formatDateTime(trace.lastSeen, { timezone, format: 'date' })}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </TableContainer>++ <!-- Pagination Footer -->+ <PaginationFooter+ currentPage={page}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={handlePageChange}+ onPageSizeChange={handlePageSizeChange}+ {loading}+ itemLabel="trace"+ /></div>diff --git a/frontend/src/routes/ai-traces/[traceName]/+page.svelte b/frontend/src/routes/ai-traces/[traceName]/+page.svelteindex 91b1ef48..d9ea40ad 100644--- a/frontend/src/routes/ai-traces/[traceName]/+page.svelte+++ b/frontend/src/routes/ai-traces/[traceName]/+page.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';import { onMount } from 'svelte';import { api } from '$lib/api';import {@@ -21,7 +22,10 @@import { createRowClickHandler } from '$lib/utils/navigation';import { createSmartBackHandler } from '$lib/utils/back-navigation';import PaginationFooter from '$lib/components/ui/pagination-footer/pagination-footer.svelte';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import StatRow from '$lib/components/traceway/stat-row.svelte';+ import StatTile from '$lib/components/traceway/stat-tile.svelte';import { formatCost, formatTokens } from '$lib/utils/ai-format';import { resolve } from '$app/paths';import {@@ -179,13 +183,13 @@stats = response.stats || null;total = response.pagination.total;totalPages = response.pagination.totalPages;- } catch (e: any) {+ } catch (e) {console.error(e);- errorStatus = e.status || 0;- if (e.status === 404) {+ errorStatus = getErrorStatus(e) || 0;+ if (getErrorStatus(e) === 404) {notFound = true;} else {- error = e.message || 'Failed to load data';+ error = getErrorMessage(e) || 'Failed to load data';}} finally {loading = false;@@ -240,13 +244,12 @@onRetry={() => loadData(false)}/>{:else}- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">- <PageHeader- title={decodeURIComponent(data.traceName)}- subtitle="AI trace instances"- onBack={createSmartBackHandler({ fallbackPath: resolve('/ai-traces') })}- />- <div class="flex flex-col">+ <PageHeader+ title={decodeURIComponent(data.traceName)}+ subtitle="AI trace instances"+ onBack={createSmartBackHandler({ fallbackPath: resolve('/ai-traces') })}+ >+ {#snippet actions()}<TimeRangePickerbind:fromDatebind:toDate@@ -255,39 +258,24 @@bind:preset={selectedPreset}onApply={handleTimeRangeChange}/>- </div>- </div>+ {/snippet}+ </PageHeader>{#if stats}- <div class="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-5">- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.avgDuration)}</p>- <p class="text-xs text-muted-foreground">Average duration</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.medianDuration)}</p>- <p class="text-xs text-muted-foreground">Median duration</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p95Duration)}</p>- <p class="text-xs text-muted-foreground">95th percentile</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatCost(stats.totalCost)}</p>- <p class="text-xs text-muted-foreground">Total cost</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatTokens(stats.totalTokens)}</p>- <p class="text-xs text-muted-foreground">Total tokens</p>- </div>- </div>+ <StatRow columns={5}>+ <StatTile label="Average duration" value={formatDurationMs(stats.avgDuration)} />+ <StatTile label="Median duration" value={formatDurationMs(stats.medianDuration)} />+ <StatTile label="95th percentile" value={formatDurationMs(stats.p95Duration)} />+ <StatTile label="Total cost" value={formatCost(stats.totalCost)} />+ <StatTile label="Total tokens" value={formatTokens(stats.totalTokens)} />+ </StatRow>{:else if loading}<div class="flex items-center justify-center py-8"><LoadingCircle size="lg" /></div>{/if}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root>{#if loading || traces.length > 0}<Table.Header>@@ -327,17 +315,17 @@{#if loading}<Table.Row><Table.Cell colspan={7} class="h-48">- <div class="flex items-center justify-center">- <LoadingCircle size="lg" />+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" /></div></Table.Cell></Table.Row>{:else if traces.length === 0}<TableEmptyState colspan={7} message="No AI traces found in this time range." />{:else}- {#each traces as trace}+ {#each traces as trace, __index (__index)}<Table.Row- class="cursor-pointer hover:bg-muted/50"+ class="cursor-pointer"onclick={createRowClickHandler(`/ai-traces/${encodeURIComponent(decodeURIComponent(data.traceName))}/${trace.id}?t=${encodeURIComponent(trace.recordedAt)}`,'preset',@@ -371,7 +359,7 @@{/if}</Table.Body></Table.Root>- </div>+ </TableContainer><PaginationFootercurrentPage={page}diff --git a/frontend/src/routes/ai-traces/[traceName]/[traceId]/+page.svelte b/frontend/src/routes/ai-traces/[traceName]/[traceId]/+page.svelteindex 116f6525..23f64c60 100644--- a/frontend/src/routes/ai-traces/[traceName]/[traceId]/+page.svelte+++ b/frontend/src/routes/ai-traces/[traceName]/[traceId]/+page.svelte@@ -9,7 +9,7 @@import { projectsState } from '$lib/state/projects.svelte';import { LabelValue } from '$lib/components/ui/label-value';import { AttributesGrid } from '$lib/components/ui/attributes-grid/index.js';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';import { createSmartBackHandler } from '$lib/utils/back-navigation';import { resolve } from '$app/paths';import TraceLogsPanel from '$lib/components/trace-logs/trace-logs-panel.svelte';@@ -194,13 +194,15 @@<p class="text-sm text-muted-foreground">Conversation</p><aclass="block truncate font-mono text-sm text-primary hover:underline"- href={addStickyParamsToHref(- resolve('/ai-traces/conversations/[conversationId]', {- conversationId: encodeURIComponent(trace.conversationId)- }),- 'preset',- 'from',- 'to'+ href={resolve(+ addStickyParamsToHref(+ resolve('/ai-traces/conversations/[conversationId]', {+ conversationId: encodeURIComponent(trace.conversationId)+ }),+ 'preset',+ 'from',+ 'to'+ ) as '/')}title={trace.conversationId}>@@ -285,7 +287,6 @@traceId={traceIdUuidToHex(trace.id)}distributedTraceId={trace.distributedTraceId ?? null}spans={[]}- rootSpan={{ id: trace.id, name: trace.traceName }}traceRecordedAt={trace.recordedAt}/>{/if}diff --git a/frontend/src/routes/ai-traces/conversations/+page.svelte b/frontend/src/routes/ai-traces/conversations/+page.svelteindex 452fcd20..f342444b 100644--- a/frontend/src/routes/ai-traces/conversations/+page.svelte+++ b/frontend/src/routes/ai-traces/conversations/+page.svelte@@ -1,618 +1,673 @@<script lang="ts">- import { onMount, onDestroy } from 'svelte';- import { api } from '$lib/api';- import { toUTCISO, calendarDateTimeToLuxon, formatDateTime } from '$lib/utils/formatters';- import { getTimezone } from '$lib/state/timezone.svelte';- import * as Table from "$lib/components/ui/table";- import * as Select from "$lib/components/ui/select";- import * as Tooltip from "$lib/components/ui/tooltip";- import { Badge } from "$lib/components/ui/badge";- import { LoadingCircle } from "$lib/components/ui/loading-circle";- import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";- import { TableEmptyState } from "$lib/components/ui/table-empty-state";- import { PaginationFooter } from "$lib/components/ui/pagination-footer";- import { TimeRangePicker } from "$lib/components/ui/time-range-picker";- import { SearchBar } from "$lib/components/ui/search-bar";- import { browser } from '$app/environment';- import { CalendarDate } from "@internationalized/date";- import { projectsState } from '$lib/state/projects.svelte';- import { createRowClickHandler } from '$lib/utils/navigation';- import { resolve } from '$app/paths';- import PageHeader from '$lib/components/issues/page-header.svelte';- import { formatCost, formatCount, formatTokens } from '$lib/utils/ai-format';- import AiNavTabs from '$lib/components/ai/ai-nav-tabs.svelte';- import FlaggedBadge from '$lib/components/ai/flagged-badge.svelte';- import FlaggedFilter from '$lib/components/ai/flagged-filter.svelte';- import EditProjectModal from '$lib/components/edit-project-modal.svelte';- import { Button } from '$lib/components/ui/button';- import { ShieldAlert, TrendingUp, X } from 'lucide-svelte';- import {- getTimeRangeFromPreset,- dateToCalendarDate,- dateToTimeString,- parseTimeRangeFromUrl,- getResolvedTimeRange,- updateUrl- } from '$lib/utils/url-params';- import {- getSortState,- setSortState,- handleSortClick,- type SortDirection- } from '$lib/utils/sort-storage';-- const timezone = $derived(getTimezone());- const initialTimezone = getTimezone();-- type ConversationRow = {- conversationId: string;- userId: string;- turns: number;- totalTokens: number;- totalCost: number;- toolCallCount: number;- toolNames: string[] | null;- models: string[] | null;- flagged: boolean;- flaggedTerms: string[] | null;- firstSeen: string;- lastSeen: string;- };-- type Thresholds = {- p95Cost: number;- p95Turns: number;- };-- type SortField = 'turns' | 'tool_call_count' | 'user_id' | 'total_tokens' | 'total_cost' | 'first_seen' | 'last_seen';-- let conversations = $state<ConversationRow[]>([]);- let thresholds = $state<Thresholds | null>(null);- let facetModels = $state<string[]>([]);- let facetTools = $state<string[]>([]);- let loading = $state(true);- let error = $state('');-- // Pagination State- let page = $state(1);- let pageSize = $state(50);- let total = $state(0);- let totalPages = $state(0);-- function parseConversationsUrlParams() {- if (!browser) return { preset: '24h', from: null, to: null, search: '', flagged: 'all', userId: '', model: '', tool: '' };- const params = new URLSearchParams(window.location.search);- const timeParams = parseTimeRangeFromUrl(timezone, '24h');- return {- ...timeParams,- search: params.get('search') || '',- flagged: params.get('flagged') === '1' ? 'flagged' : 'all',- userId: params.get('userId') || '',- model: params.get('model') || '',- tool: params.get('tool') || ''- };- }-- const initialUrlParams = parseConversationsUrlParams();- const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);-- let searchQuery = $state(initialUrlParams.search);- let flaggedFilter = $state(initialUrlParams.flagged);- let userIdFilter = $state(initialUrlParams.userId);- let modelFilter = $state(initialUrlParams.model);- let toolFilter = $state(initialUrlParams.tool);-- // Date Range State- let selectedPreset = $state<string | null>(initialUrlParams.preset);- let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));- let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));- let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));- let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));-- function updateTimeRangeUrl(pushToHistory = true) {- const params: Record<string, string | null | undefined> = {};- if (selectedPreset) {- params.preset = selectedPreset;- } else {- params.from = getFromDateTimeUTC();- params.to = getToDateTimeUTC();- }- if (searchQuery.trim()) {- params.search = searchQuery.trim();- }- params.flagged = flaggedFilter === 'flagged' ? '1' : null;- params.userId = userIdFilter || null;- params.model = modelFilter || null;- params.tool = toolFilter || null;- updateUrl(params, { pushToHistory });- }-- function handlePopState() {- const urlParams = parseConversationsUrlParams();- const range = getResolvedTimeRange(urlParams, timezone);-- selectedPreset = urlParams.preset;- fromDate = dateToCalendarDate(range.from, timezone);- fromTime = dateToTimeString(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- toTime = dateToTimeString(range.to, timezone);- searchQuery = urlParams.search;- flaggedFilter = urlParams.flagged;- userIdFilter = urlParams.userId;- modelFilter = urlParams.model;- toolFilter = urlParams.tool;-- page = 1;- loadData(false);- }-- const SORT_STORAGE_KEY = 'ai-conversations';- const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'last_seen', direction: 'desc' });- let orderBy = $state<SortField>(initialSort.field as SortField);- let sortDirection = $state<SortDirection>(initialSort.direction);-- function getFromDateTimeUTC(): string {- const [hour, minute] = (fromTime || '00:00').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute }, timezone);- return toUTCISO(dt);- }-- function getToDateTimeUTC(): string {- const [hour, minute] = (toTime || '23:59').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: toDate.year, month: toDate.month, day: toDate.day, hour, minute }, timezone).endOf('minute');- return toUTCISO(dt);- }-- function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) {- fromDate = from.date;- fromTime = from.time;- toDate = to.date;- toTime = to.time;- selectedPreset = preset;- page = 1;- loadData(false);- }-- async function loadData(pushToHistory = true) {- loading = true;- error = '';-- if (selectedPreset) {- const range = getTimeRangeFromPreset(selectedPreset, timezone);- fromDate = dateToCalendarDate(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- fromTime = dateToTimeString(range.from, timezone);- toTime = dateToTimeString(range.to, timezone);- }-- updateTimeRangeUrl(pushToHistory);-- try {- const requestBody = {- fromDate: getFromDateTimeUTC(),- toDate: getToDateTimeUTC(),- orderBy: orderBy,- sortDirection: sortDirection,- pagination: {- page: page,- pageSize: pageSize- },- search: searchQuery.trim(),- userId: userIdFilter,- model: modelFilter,- toolName: toolFilter,- flaggedOnly: flaggedFilter === 'flagged'- };-- const response = await api.post('/ai-conversations/grouped', requestBody, { projectId: projectsState.currentProjectId ?? undefined });-- conversations = response.data || [];- thresholds = response.thresholds || null;- facetModels = response.facets?.models || [];- facetTools = response.facets?.tools || [];- total = response.pagination.total;- totalPages = response.pagination.totalPages;- } catch (e: any) {- console.error(e);- error = e.message || 'Failed to load data';- } finally {- loading = false;- }- }-- function handlePageChange(newPage: number) {- if (newPage >= 1 && newPage <= totalPages) {- page = newPage;- loadData(false);- }- }-- function handlePageSizeChange(newPageSize: number) {- pageSize = newPageSize;- page = 1;- loadData(false);- }-- function handleSort(field: SortField) {- const newSort = handleSortClick(field, orderBy, sortDirection);- orderBy = newSort.field as SortField;- sortDirection = newSort.direction;- setSortState(SORT_STORAGE_KEY, newSort);- page = 1;- loadData(false);- }-- function handleSearch() {- page = 1;- loadData(true);- }-- function applyFilterChange() {- page = 1;- loadData(true);- }-- type FilterPillKind = 'user' | 'model' | 'tool' | 'flagged';-- const filterPills = $derived([- ...(userIdFilter ? [{ kind: 'user' as FilterPillKind, label: 'user', value: userIdFilter }] : []),- ...(modelFilter ? [{ kind: 'model' as FilterPillKind, label: 'model', value: modelFilter }] : []),- ...(toolFilter ? [{ kind: 'tool' as FilterPillKind, label: 'tool', value: toolFilter }] : []),- ...(flaggedFilter === 'flagged' ? [{ kind: 'flagged' as FilterPillKind, label: 'flagged', value: 'only' }] : [])- ]);-- function removeFilterPill(kind: FilterPillKind) {- if (kind === 'user') userIdFilter = '';- else if (kind === 'model') modelFilter = '';- else if (kind === 'tool') toolFilter = '';- else if (kind === 'flagged') flaggedFilter = 'all';- applyFilterChange();- }-- const hasActiveFilters = $derived(- !!(searchQuery.trim() || userIdFilter || modelFilter || toolFilter || flaggedFilter === 'flagged')- );-- function shortModelName(model: string): string {- const idx = model.lastIndexOf('/');- return idx >= 0 ? model.slice(idx + 1) : model;- }-- const modelFilterLabel = $derived(modelFilter ? shortModelName(modelFilter) : 'All models');- const toolFilterLabel = $derived(toolFilter || 'All tools');-- const isCostOutlier = (row: ConversationRow) =>- !!thresholds && thresholds.p95Cost > 0 && row.totalCost > thresholds.p95Cost;- const isTurnsOutlier = (row: ConversationRow) =>- !!thresholds && thresholds.p95Turns > 0 && row.turns > thresholds.p95Turns;-- // Reloads after the settings modal closes so new flagged terms and- // language packs are reflected (they only affect future ingests, but the- // project object itself is refreshed).- let showFlaggedTermsSettings = $state(false);- function onFlaggedTermsSettingsChange(open: boolean) {- showFlaggedTermsSettings = open;- }-- onMount(() => {- window.addEventListener('popstate', handlePopState);- loadData(false);- });-- onDestroy(() => {- if (typeof window !== 'undefined') {- window.removeEventListener('popstate', handlePopState);- }- });+ import { getErrorMessage } from '$lib/utils/errors';+ import { onMount, onDestroy } from 'svelte';+ import { api } from '$lib/api';+ import { toUTCISO, calendarDateTimeToLuxon, formatDateTime } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import * as Table from '$lib/components/ui/table';+ import * as Tooltip from '$lib/components/ui/tooltip';+ import { Badge } from '$lib/components/ui/badge';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { TimeRangePicker } from '$lib/components/ui/time-range-picker';+ import { SearchBar } from '$lib/components/ui/search-bar';+ import { browser } from '$app/environment';+ import { CalendarDate } from '@internationalized/date';+ import { projectsState } from '$lib/state/projects.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { resolve } from '$app/paths';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import ToolbarSelect from '$lib/components/traceway/toolbar-select.svelte';+ import { formatCost, formatCount, formatTokens } from '$lib/utils/ai-format';+ import AiNavTabs from '$lib/components/ai/ai-nav-tabs.svelte';+ import FlaggedBadge from '$lib/components/ai/flagged-badge.svelte';+ import FlaggedFilter from '$lib/components/ai/flagged-filter.svelte';+ import EditProjectModal from '$lib/components/edit-project-modal.svelte';+ import { Button } from '$lib/components/ui/button';+ import { ShieldAlert, TrendingUp, X } from '@lucide/svelte';+ import {+ getTimeRangeFromPreset,+ dateToCalendarDate,+ dateToTimeString,+ parseTimeRangeFromUrl,+ getResolvedTimeRange,+ updateUrl+ } from '$lib/utils/url-params';+ import {+ getSortState,+ setSortState,+ handleSortClick,+ type SortDirection+ } from '$lib/utils/sort-storage';++ const timezone = $derived(getTimezone());+ const initialTimezone = getTimezone();++ type ConversationRow = {+ conversationId: string;+ userId: string;+ turns: number;+ totalTokens: number;+ totalCost: number;+ toolCallCount: number;+ toolNames: string[] | null;+ models: string[] | null;+ flagged: boolean;+ flaggedTerms: string[] | null;+ firstSeen: string;+ lastSeen: string;+ };++ type Thresholds = {+ p95Cost: number;+ p95Turns: number;+ };++ type SortField =+ | 'turns'+ | 'tool_call_count'+ | 'user_id'+ | 'total_tokens'+ | 'total_cost'+ | 'first_seen'+ | 'last_seen';++ let conversations = $state<ConversationRow[]>([]);+ let thresholds = $state<Thresholds | null>(null);+ let facetModels = $state<string[]>([]);+ let facetTools = $state<string[]>([]);+ let loading = $state(true);+ let error = $state('');++ // Pagination State+ let page = $state(1);+ let pageSize = $state(50);+ let total = $state(0);+ let totalPages = $state(0);++ function parseConversationsUrlParams() {+ if (!browser)+ return {+ preset: '24h',+ from: null,+ to: null,+ search: '',+ flagged: 'all',+ userId: '',+ model: '',+ tool: ''+ };+ const params = new URLSearchParams(window.location.search);+ const timeParams = parseTimeRangeFromUrl(timezone, '24h');+ return {+ ...timeParams,+ search: params.get('search') || '',+ flagged: params.get('flagged') === '1' ? 'flagged' : 'all',+ userId: params.get('userId') || '',+ model: params.get('model') || '',+ tool: params.get('tool') || ''+ };+ }++ const initialUrlParams = parseConversationsUrlParams();+ const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);++ let searchQuery = $state(initialUrlParams.search);+ let flaggedFilter = $state(initialUrlParams.flagged);+ let userIdFilter = $state(initialUrlParams.userId);+ let modelFilter = $state(initialUrlParams.model);+ let toolFilter = $state(initialUrlParams.tool);++ // Date Range State+ let selectedPreset = $state<string | null>(initialUrlParams.preset);+ let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));+ let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));+ let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));+ let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));++ function updateTimeRangeUrl(pushToHistory = true) {+ const params: Record<string, string | null | undefined> = {};+ if (selectedPreset) {+ params.preset = selectedPreset;+ } else {+ params.from = getFromDateTimeUTC();+ params.to = getToDateTimeUTC();+ }+ if (searchQuery.trim()) {+ params.search = searchQuery.trim();+ }+ params.flagged = flaggedFilter === 'flagged' ? '1' : null;+ params.userId = userIdFilter || null;+ params.model = modelFilter || null;+ params.tool = toolFilter || null;+ updateUrl(params, { pushToHistory });+ }++ function handlePopState() {+ const urlParams = parseConversationsUrlParams();+ const range = getResolvedTimeRange(urlParams, timezone);++ selectedPreset = urlParams.preset;+ fromDate = dateToCalendarDate(range.from, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ toTime = dateToTimeString(range.to, timezone);+ searchQuery = urlParams.search;+ flaggedFilter = urlParams.flagged;+ userIdFilter = urlParams.userId;+ modelFilter = urlParams.model;+ toolFilter = urlParams.tool;++ page = 1;+ loadData(false);+ }++ const SORT_STORAGE_KEY = 'ai-conversations';+ const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'last_seen', direction: 'desc' });+ let orderBy = $state<SortField>(initialSort.field as SortField);+ let sortDirection = $state<SortDirection>(initialSort.direction);++ function getFromDateTimeUTC(): string {+ const [hour, minute] = (fromTime || '00:00').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute },+ timezone+ );+ return toUTCISO(dt);+ }++ function getToDateTimeUTC(): string {+ const [hour, minute] = (toTime || '23:59').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: toDate.year, month: toDate.month, day: toDate.day, hour, minute },+ timezone+ ).endOf('minute');+ return toUTCISO(dt);+ }++ function handleTimeRangeChange(+ from: { date: CalendarDate; time: string },+ to: { date: CalendarDate; time: string },+ preset: string | null+ ) {+ fromDate = from.date;+ fromTime = from.time;+ toDate = to.date;+ toTime = to.time;+ selectedPreset = preset;+ page = 1;+ loadData(false);+ }++ async function loadData(pushToHistory = true) {+ loading = true;+ error = '';++ if (selectedPreset) {+ const range = getTimeRangeFromPreset(selectedPreset, timezone);+ fromDate = dateToCalendarDate(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toTime = dateToTimeString(range.to, timezone);+ }++ updateTimeRangeUrl(pushToHistory);++ try {+ const requestBody = {+ fromDate: getFromDateTimeUTC(),+ toDate: getToDateTimeUTC(),+ orderBy: orderBy,+ sortDirection: sortDirection,+ pagination: {+ page: page,+ pageSize: pageSize+ },+ search: searchQuery.trim(),+ userId: userIdFilter,+ model: modelFilter,+ toolName: toolFilter,+ flaggedOnly: flaggedFilter === 'flagged'+ };++ const response = await api.post('/ai-conversations/grouped', requestBody, {+ projectId: projectsState.currentProjectId ?? undefined+ });++ conversations = response.data || [];+ thresholds = response.thresholds || null;+ facetModels = response.facets?.models || [];+ facetTools = response.facets?.tools || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e) {+ console.error(e);+ error = getErrorMessage(e) || 'Failed to load data';+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData(false);+ }+ }++ function handlePageSizeChange(newPageSize: number) {+ pageSize = newPageSize;+ page = 1;+ loadData(false);+ }++ function handleSort(field: SortField) {+ const newSort = handleSortClick(field, orderBy, sortDirection);+ orderBy = newSort.field as SortField;+ sortDirection = newSort.direction;+ setSortState(SORT_STORAGE_KEY, newSort);+ page = 1;+ loadData(false);+ }++ function handleSearch() {+ page = 1;+ loadData(true);+ }++ function applyFilterChange() {+ page = 1;+ loadData(true);+ }++ type FilterPillKind = 'user' | 'model' | 'tool' | 'flagged';++ const filterPills = $derived([+ ...(userIdFilter+ ? [{ kind: 'user' as FilterPillKind, label: 'user', value: userIdFilter }]+ : []),+ ...(modelFilter+ ? [{ kind: 'model' as FilterPillKind, label: 'model', value: modelFilter }]+ : []),+ ...(toolFilter ? [{ kind: 'tool' as FilterPillKind, label: 'tool', value: toolFilter }] : []),+ ...(flaggedFilter === 'flagged'+ ? [{ kind: 'flagged' as FilterPillKind, label: 'flagged', value: 'only' }]+ : [])+ ]);++ function removeFilterPill(kind: FilterPillKind) {+ if (kind === 'user') userIdFilter = '';+ else if (kind === 'model') modelFilter = '';+ else if (kind === 'tool') toolFilter = '';+ else if (kind === 'flagged') flaggedFilter = 'all';+ applyFilterChange();+ }++ const hasActiveFilters = $derived(+ !!(+ searchQuery.trim() ||+ userIdFilter ||+ modelFilter ||+ toolFilter ||+ flaggedFilter === 'flagged'+ )+ );++ function shortModelName(model: string): string {+ const idx = model.lastIndexOf('/');+ return idx >= 0 ? model.slice(idx + 1) : model;+ }++ const modelOptions = $derived([+ { value: '', label: 'All models' },+ ...facetModels.map((m) => ({ value: m, label: m }))+ ]);+ const toolOptions = $derived([+ { value: '', label: 'All tools' },+ ...facetTools.map((t) => ({ value: t, label: t }))+ ]);++ const isCostOutlier = (row: ConversationRow) =>+ !!thresholds && thresholds.p95Cost > 0 && row.totalCost > thresholds.p95Cost;+ const isTurnsOutlier = (row: ConversationRow) =>+ !!thresholds && thresholds.p95Turns > 0 && row.turns > thresholds.p95Turns;++ // Reloads after the settings modal closes so new flagged terms and+ // language packs are reflected (they only affect future ingests, but the+ // project object itself is refreshed).+ let showFlaggedTermsSettings = $state(false);+ function onFlaggedTermsSettingsChange(open: boolean) {+ showFlaggedTermsSettings = open;+ }++ onMount(() => {+ window.addEventListener('popstate', handlePopState);+ loadData(false);+ });++ onDestroy(() => {+ if (typeof window !== 'undefined') {+ window.removeEventListener('popstate', handlePopState);+ }+ });</script><div class="space-y-4">- <!-- Header with Title and Time Range Filter -->- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">- <PageHeader title="AI Conversations" />- <div class="flex flex-col">- <TimeRangePicker- bind:fromDate- bind:toDate- bind:fromTime- bind:toTime- bind:preset={selectedPreset}- onApply={handleTimeRangeChange}- />- </div>- </div>-- <div class="flex flex-wrap items-center justify-between gap-2">- <AiNavTabs active="conversations" />- {#if projectsState.canWriteCurrentProject}- <Button- variant="outline"- size="sm"- onclick={() => (showFlaggedTermsSettings = true)}- >- <ShieldAlert class="mr-1.5 h-4 w-4" />- Flagged terms- </Button>- {/if}- </div>-- <!-- Search + filters -->- <SearchBar- placeholder="Search conversations..."- bind:value={searchQuery}- onSearch={handleSearch}- disabled={loading}- >- {#snippet children()}- <FlaggedFilter bind:value={flaggedFilter} onChange={applyFilterChange} />- <Select.Root type="single" bind:value={modelFilter} onValueChange={applyFilterChange}>- <Select.Trigger class="h-9 w-[160px] rounded-none border-r-0 shadow-none">- <span class="truncate">{modelFilterLabel}</span>- </Select.Trigger>- <Select.Content>- <Select.Item value="" label="All models">All models</Select.Item>- {#each facetModels as model}- <Select.Item value={model} label={model}>{model}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- <Select.Root type="single" bind:value={toolFilter} onValueChange={applyFilterChange}>- <Select.Trigger class="h-9 w-[150px] rounded-none border-r-0 shadow-none">- <span class="truncate">{toolFilterLabel}</span>- </Select.Trigger>- <Select.Content>- <Select.Item value="" label="All tools">All tools</Select.Item>- {#each facetTools as tool}- <Select.Item value={tool} label={tool}>{tool}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- {/snippet}- </SearchBar>-- {#if filterPills.length > 0}- <div class="flex flex-wrap items-center gap-2">- {#each filterPills as pill (pill.kind)}- <span class="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 font-mono text-xs">- <span class="text-muted-foreground">{pill.label}</span>- <span>=</span>- <span class="max-w-[240px] truncate" title={pill.value}>{pill.value}</span>- <button- type="button"- aria-label="Remove {pill.label} filter"- class="ml-1 cursor-pointer text-muted-foreground hover:text-foreground"- onclick={() => removeFilterPill(pill.kind)}- >- <X class="h-3 w-3" />- </button>- </span>- {/each}- </div>- {/if}-- <!-- Conversations Table -->- <div class="rounded-md border overflow-hidden">- <Table.Root>- {#if loading}- <Table.Body>- <Table.Row>- <Table.Cell colspan={8} class="h-48">- <div class="flex justify-center items-center h-full">- <LoadingCircle size="xlg" />- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if error}- <Table.Body>- <TableEmptyState colspan={8} message={error} />- </Table.Body>- {:else if conversations.length === 0}- <Table.Body>- <TableEmptyState- colspan={8}- message={hasActiveFilters- ? 'No conversations match the current search and filters. Search covers conversation ids, users, models, tool names, and flagged terms.'- : 'No conversations found. They appear once your AI calls carry a gen_ai.conversation.id or session.id attribute (or share a distributed trace).'}- />- </Table.Body>- {:else}- <Table.Header>- <Table.Row>- <TracewayTableHeader- label="Conversation"- tooltip="The conversation id reported by your app"- />- <TracewayTableHeader- label="User"- tooltip="The user.id attribute on the calls"- sortField="user_id"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[140px]"- />- <TracewayTableHeader- label="Turns"- tooltip="Number of LLM calls in the conversation"- sortField="turns"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[90px]"- />- <TracewayTableHeader- label="Tools"- tooltip="Total tool calls across the conversation"- sortField="tool_call_count"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[90px]"- />- <TracewayTableHeader- label="Models"- tooltip="Models used in the conversation"- />- <TracewayTableHeader- label="Tokens"- tooltip="Total tokens used"- sortField="total_tokens"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Cost"- tooltip="Total cost of the conversation"- sortField="total_cost"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Last Seen"- tooltip="When the conversation last had a call"- sortField="last_seen"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[130px]"- />- </Table.Row>- </Table.Header>- <Table.Body>- {#each conversations as conv}- <Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={createRowClickHandler(resolve('/ai-traces/conversations/[conversationId]', { conversationId: encodeURIComponent(conv.conversationId) }), 'preset', 'from', 'to')}- >- <Table.Cell class="max-w-[280px] font-mono text-sm">- <div class="flex items-center gap-2">- <span class="truncate" title={conv.conversationId}>{conv.conversationId}</span>- {#if conv.flagged && conv.flaggedTerms?.length}- <FlaggedBadge terms={conv.flaggedTerms} />- {/if}- </div>- </Table.Cell>- <Table.Cell class="max-w-[140px] truncate font-mono text-sm" title={conv.userId}>- {conv.userId || '-'}- </Table.Cell>- <Table.Cell class="tabular-nums">- {#if isTurnsOutlier(conv)}- <Tooltip.Provider>- <Tooltip.Root>- <Tooltip.Trigger>- <span class="inline-flex items-center gap-1 font-semibold text-orange-600 dark:text-orange-400">- {formatCount(conv.turns)}- <TrendingUp class="h-3 w-3" />- </span>- </Tooltip.Trigger>- <Tooltip.Content>- <p class="text-xs">Above the 95th percentile turns for this period (P95: {Math.round(thresholds?.p95Turns ?? 0)})</p>- </Tooltip.Content>- </Tooltip.Root>- </Tooltip.Provider>- {:else}- {formatCount(conv.turns)}- {/if}- </Table.Cell>- <Table.Cell class="tabular-nums">- {#if conv.toolNames?.length}- <Tooltip.Provider>- <Tooltip.Root>- <Tooltip.Trigger>- <span>{formatCount(conv.toolCallCount)}</span>- </Tooltip.Trigger>- <Tooltip.Content>- <p class="max-w-xs text-xs">{conv.toolNames.join(', ')}</p>- </Tooltip.Content>- </Tooltip.Root>- </Tooltip.Provider>- {:else}- {formatCount(conv.toolCallCount)}- {/if}- </Table.Cell>- <Table.Cell>- {#if conv.models?.length}- <Tooltip.Provider>- <Tooltip.Root>- <Tooltip.Trigger>- <span class="inline-flex items-center gap-1">- <Badge variant="outline" class="font-mono text-xs">{shortModelName(conv.models[0])}</Badge>- {#if conv.models.length > 1}- <Badge variant="outline" class="text-xs">+{conv.models.length - 1}</Badge>- {/if}- </span>- </Tooltip.Trigger>- <Tooltip.Content>- <p class="max-w-xs text-xs">{conv.models.join(', ')}</p>- </Tooltip.Content>- </Tooltip.Root>- </Tooltip.Provider>- {:else}- <span class="text-muted-foreground">-</span>- {/if}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {formatTokens(conv.totalTokens)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {#if isCostOutlier(conv)}- <Tooltip.Provider>- <Tooltip.Root>- <Tooltip.Trigger>- <span class="inline-flex items-center gap-1 font-semibold text-orange-600 dark:text-orange-400">- {formatCost(conv.totalCost)}- <TrendingUp class="h-3 w-3" />- </span>- </Tooltip.Trigger>- <Tooltip.Content>- <p class="text-xs">Above the 95th percentile cost for this period (P95: {formatCost(thresholds?.p95Cost ?? 0)})</p>- </Tooltip.Content>- </Tooltip.Root>- </Tooltip.Provider>- {:else}- {formatCost(conv.totalCost)}- {/if}- </Table.Cell>- <Table.Cell class="text-muted-foreground text-sm">- <Tooltip.Provider>- <Tooltip.Root>- <Tooltip.Trigger>- <span>{formatDateTime(conv.lastSeen, { timezone })}</span>- </Tooltip.Trigger>- <Tooltip.Content>- <p class="text-xs">Started {formatDateTime(conv.firstSeen, { timezone })}</p>- </Tooltip.Content>- </Tooltip.Root>- </Tooltip.Provider>- </Table.Cell>- </Table.Row>- {/each}- </Table.Body>- {/if}- </Table.Root>- </div>-- <!-- Pagination Footer -->- <PaginationFooter- currentPage={page}- {totalPages}- {pageSize}- totalItems={total}- onPageChange={handlePageChange}- onPageSizeChange={handlePageSizeChange}- {loading}- itemLabel="conversation"- />+ <PageHeader title="AI Conversations">+ {#snippet actions()}+ {#if projectsState.canWriteCurrentProject}+ <Button variant="outline" size="sm" onclick={() => (showFlaggedTermsSettings = true)}>+ <ShieldAlert class="mr-2 h-4 w-4" />+ Flagged terms+ </Button>+ {/if}+ <TimeRangePicker+ bind:fromDate+ bind:toDate+ bind:fromTime+ bind:toTime+ bind:preset={selectedPreset}+ onApply={handleTimeRangeChange}+ />+ {/snippet}+ </PageHeader>++ <AiNavTabs active="conversations" />++ <!-- Search + filters -->+ <SearchBar+ placeholder="Search conversations..."+ bind:value={searchQuery}+ onSearch={handleSearch}+ disabled={loading}+ >+ <FlaggedFilter bind:value={flaggedFilter} onChange={applyFilterChange} />+ <ToolbarSelect+ bind:value={modelFilter}+ options={modelOptions}+ class="w-[160px]"+ onChange={applyFilterChange}+ />+ <ToolbarSelect+ bind:value={toolFilter}+ options={toolOptions}+ class="w-[150px]"+ onChange={applyFilterChange}+ />+ </SearchBar>++ {#if filterPills.length > 0}+ <div class="flex flex-wrap items-center gap-2">+ {#each filterPills as pill (pill.kind)}+ <span+ class="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 font-mono text-xs"+ >+ <span class="text-muted-foreground">{pill.label}</span>+ <span>=</span>+ <span class="max-w-[240px] truncate" title={pill.value}>{pill.value}</span>+ <button+ type="button"+ aria-label="Remove {pill.label} filter"+ class="ml-1 cursor-pointer text-muted-foreground hover:text-foreground"+ onclick={() => removeFilterPill(pill.kind)}+ >+ <X class="h-3 w-3" />+ </button>+ </span>+ {/each}+ </div>+ {/if}++ <!-- Conversations Table -->+ <TableContainer>+ <Table.Root>+ {#if loading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={8} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if error}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={8} class="h-24 text-center text-red-500">+ {error}+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if conversations.length === 0}+ <Table.Body>+ <TableEmptyState+ colspan={8}+ message={hasActiveFilters+ ? 'No conversations match the current search and filters. Search covers conversation ids, users, models, tool names, and flagged terms.'+ : 'No conversations found. They appear once your AI calls carry a gen_ai.conversation.id or session.id attribute (or share a distributed trace).'}+ />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader+ label="Conversation"+ tooltip="The conversation id reported by your app"+ />+ <TracewayTableHeader+ label="User"+ tooltip="The user.id attribute on the calls"+ sortField="user_id"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[140px]"+ />+ <TracewayTableHeader+ label="Turns"+ tooltip="Number of LLM calls in the conversation"+ sortField="turns"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[90px]"+ />+ <TracewayTableHeader+ label="Tools"+ tooltip="Total tool calls across the conversation"+ sortField="tool_call_count"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[90px]"+ />+ <TracewayTableHeader label="Models" tooltip="Models used in the conversation" />+ <TracewayTableHeader+ label="Tokens"+ tooltip="Total tokens used"+ sortField="total_tokens"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Cost"+ tooltip="Total cost of the conversation"+ sortField="total_cost"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Last Seen"+ tooltip="When the conversation last had a call"+ sortField="last_seen"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[130px]"+ />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each conversations as conv, __index (__index)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ resolve('/ai-traces/conversations/[conversationId]', {+ conversationId: encodeURIComponent(conv.conversationId)+ }),+ 'preset',+ 'from',+ 'to'+ )}+ >+ <Table.Cell class="max-w-[280px] font-mono text-sm">+ <div class="flex items-center gap-2">+ <span class="truncate" title={conv.conversationId}>{conv.conversationId}</span>+ {#if conv.flagged && conv.flaggedTerms?.length}+ <FlaggedBadge terms={conv.flaggedTerms} />+ {/if}+ </div>+ </Table.Cell>+ <Table.Cell class="max-w-[140px] truncate font-mono text-sm" title={conv.userId}>+ {conv.userId || '-'}+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ {#if isTurnsOutlier(conv)}+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span+ class="inline-flex items-center gap-1 font-semibold text-orange-600 dark:text-orange-400"+ >+ {formatCount(conv.turns)}+ <TrendingUp class="h-3 w-3" />+ </span>+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">+ Above the 95th percentile turns for this period (P95: {Math.round(+ thresholds?.p95Turns ?? 0+ )})+ </p>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+ {:else}+ {formatCount(conv.turns)}+ {/if}+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ {#if conv.toolNames?.length}+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span>{formatCount(conv.toolCallCount)}</span>+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="max-w-xs text-xs">{conv.toolNames.join(', ')}</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+ {:else}+ {formatCount(conv.toolCallCount)}+ {/if}+ </Table.Cell>+ <Table.Cell>+ {#if conv.models?.length}+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span class="inline-flex items-center gap-1">+ <Badge variant="outline" class="font-mono text-xs"+ >{shortModelName(conv.models[0])}</Badge+ >+ {#if conv.models.length > 1}+ <Badge variant="outline" class="text-xs"+ >+{conv.models.length - 1}</Badge+ >+ {/if}+ </span>+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="max-w-xs text-xs">{conv.models.join(', ')}</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+ {:else}+ <span class="text-muted-foreground">-</span>+ {/if}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatTokens(conv.totalTokens)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {#if isCostOutlier(conv)}+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span+ class="inline-flex items-center gap-1 font-semibold text-orange-600 dark:text-orange-400"+ >+ {formatCost(conv.totalCost)}+ <TrendingUp class="h-3 w-3" />+ </span>+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">+ Above the 95th percentile cost for this period (P95: {formatCost(+ thresholds?.p95Cost ?? 0+ )})+ </p>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+ {:else}+ {formatCost(conv.totalCost)}+ {/if}+ </Table.Cell>+ <Table.Cell class="text-sm text-muted-foreground">+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span>{formatDateTime(conv.lastSeen, { timezone })}</span>+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Started {formatDateTime(conv.firstSeen, { timezone })}</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </TableContainer>++ <!-- Pagination Footer -->+ <PaginationFooter+ currentPage={page}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={handlePageChange}+ onPageSizeChange={handlePageSizeChange}+ {loading}+ itemLabel="conversation"+ /></div><EditProjectModal- open={showFlaggedTermsSettings}- onOpenChange={onFlaggedTermsSettingsChange}- project={projectsState.currentProject}- initialTab="ai"+ open={showFlaggedTermsSettings}+ onOpenChange={onFlaggedTermsSettingsChange}+ project={projectsState.currentProject}+ initialTab="ai"/>diff --git a/frontend/src/routes/ai-traces/conversations/[conversationId]/+page.svelte b/frontend/src/routes/ai-traces/conversations/[conversationId]/+page.svelteindex 81463273..64245cf6 100644--- a/frontend/src/routes/ai-traces/conversations/[conversationId]/+page.svelte+++ b/frontend/src/routes/ai-traces/conversations/[conversationId]/+page.svelte@@ -7,7 +7,9 @@import { LoadingCircle } from '$lib/components/ui/loading-circle';import { ErrorDisplay } from '$lib/components/ui/error-display';import { projectsState } from '$lib/state/projects.svelte';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import StatRow from '$lib/components/traceway/stat-row.svelte';+ import StatTile from '$lib/components/traceway/stat-tile.svelte';import { createSmartBackHandler } from '$lib/utils/back-navigation';import { resolve } from '$app/paths';import { formatCost, formatTokens, formatCount } from '$lib/utils/ai-format';@@ -21,6 +23,7 @@import ConversationMessages from '$lib/components/ai/conversation-messages.svelte';import FlaggedBadge from '$lib/components/ai/flagged-badge.svelte';import { addStickyParamsToHref } from '$lib/utils/navigation';+ import { resolveHref } from '$lib/utils/links';type ApiTurn = ConversationTurn & {userId: string;@@ -78,7 +81,12 @@traceName: encodeURIComponent(turn.traceName),traceId: turn.id});- return addStickyParamsToHref(`${base}?t=${encodeURIComponent(turn.recordedAt)}`, 'preset', 'from', 'to');+ return addStickyParamsToHref(+ `${base}?t=${encodeURIComponent(turn.recordedAt)}`,+ 'preset',+ 'from',+ 'to'+ );}function conversationDurationLabel(stats: ConversationStats): string {@@ -154,47 +162,36 @@onRetry={loadData}/>{:else if stats}- <div class="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-6">- <div>- <p class="text-sm text-muted-foreground">Turns</p>- <p class="text-2xl font-semibold tabular-nums">{formatCount(stats.turns)}</p>- </div>- <div>- <p class="text-sm text-muted-foreground">Total cost</p>- <p class="text-2xl font-semibold tabular-nums">{formatCost(stats.totalCost)}</p>- </div>- <div>- <p class="text-sm text-muted-foreground">Total tokens</p>- <p class="text-2xl font-semibold tabular-nums">{formatTokens(stats.totalTokens)}</p>- </div>- <div>- <p class="text-sm text-muted-foreground">Tool calls</p>- <p class="text-2xl font-semibold tabular-nums">{formatCount(stats.toolCallCount)}</p>- </div>- <div class="min-w-0">- <p class="text-sm text-muted-foreground">User</p>+ <StatRow columns={3}>+ <StatTile label="Turns" value={formatCount(stats.turns)} />+ <StatTile label="Total cost" value={formatCost(stats.totalCost)} />+ <StatTile label="Total tokens" value={formatTokens(stats.totalTokens)} />+ <StatTile label="Tool calls" value={formatCount(stats.toolCallCount)} />+ <div class="min-w-0 px-6 py-4">+ <div class="text-xs font-medium text-muted-foreground">User</div>{#if stats.userId}<a- class="block truncate font-mono text-sm text-primary hover:underline"- href={addStickyParamsToHref(- `${resolve('/ai-traces/conversations')}?userId=${encodeURIComponent(stats.userId)}`,- 'preset',- 'from',- 'to'- )}+ class="mt-1 block truncate font-mono text-sm text-primary hover:underline"+ {...{+ href: resolveHref(+ addStickyParamsToHref(+ `/ai-traces/conversations?userId=${encodeURIComponent(stats.userId)}`,+ 'preset',+ 'from',+ 'to'+ )+ )+ }}title={stats.userId}>{stats.userId}</a>{:else}- <p class="text-sm text-muted-foreground">-</p>+ <div class="mt-1 text-sm text-muted-foreground">-</div>{/if}</div>- <div>- <p class="text-sm text-muted-foreground">Duration</p>- <p class="text-2xl font-semibold tabular-nums">{conversationDurationLabel(stats)}</p>- </div>- </div>+ <StatTile label="Duration" value={conversationDurationLabel(stats)} />+ </StatRow><Card.Root><Card.Header class="flex flex-row items-center justify-between">@@ -206,7 +203,9 @@{/if}</div><Card.Description>- {formatDateTime(stats.firstSeen, { timezone })} to {formatDateTime(stats.lastSeen, { timezone })}+ {formatDateTime(stats.firstSeen, { timezone })} to {formatDateTime(stats.lastSeen, {+ timezone+ })}</Card.Description></div><button@@ -219,19 +218,25 @@<Card.Content>{#if showRawJson}<div class="space-y-6">- {#each turns as turn, i}+ {#each turns as turn, i (i)}<div><p class="mb-2 text-xs font-medium tracking-wide text-muted-foreground uppercase">Turn {i + 1} · {formatDateTime(turn.recordedAt, { timezone })}</p>{#if turn.input}<div class="mb-2 max-h-96 overflow-auto rounded-md bg-muted p-4">- <pre class="font-mono text-sm break-words whitespace-pre-wrap">{formatConversationContent(turn.input)}</pre>+ <pre+ class="font-mono text-sm break-words whitespace-pre-wrap">{formatConversationContent(+ turn.input+ )}</pre></div>{/if}{#if turn.output}<div class="max-h-96 overflow-auto rounded-md bg-muted p-4">- <pre class="font-mono text-sm break-words whitespace-pre-wrap">{formatConversationContent(turn.output)}</pre>+ <pre+ class="font-mono text-sm break-words whitespace-pre-wrap">{formatConversationContent(+ turn.output+ )}</pre></div>{/if}</div>@@ -239,11 +244,13 @@</div>{:else if timeline}<div class="space-y-3">- {#each timeline as entry, i}+ {#each timeline as entry, i (i)}{#if entry.kind === 'message'}<ConversationMessages messages={[entry.message]} />{:else}- {@const turnNumber = timeline.slice(0, i + 1).filter((e) => e.kind === 'turn-meta').length}+ {@const turnNumber = timeline+ .slice(0, i + 1)+ .filter((e) => e.kind === 'turn-meta').length}<div class="flex items-center gap-2 py-1 text-xs text-muted-foreground"><div class="h-px flex-1 bg-border"></div><span class="whitespace-nowrap">@@ -252,12 +259,13 @@· <span class="font-mono">{entry.turn.model}</span>{/if}· {formatCost(entry.turn.totalCost)}- · {formatTokens(entry.turn.totalTokens)} tokens- · {formatDuration(entry.turn.duration)}+ · {formatTokens(entry.turn.totalTokens)} tokens · {formatDuration(+ entry.turn.duration+ )}·<aclass="text-primary hover:underline"- href={turnHref(entry.turn as ApiTurn)}+ {...{ href: resolveHref(turnHref(entry.turn as ApiTurn)) }}onclick={(e) => e.stopPropagation()}>View call →@@ -272,20 +280,23 @@<!-- Fallback: history prefix-matching failed; render each turn's ownparsed conversation as a separate section. --><div class="space-y-6">- {#each turns as turn, i}+ {#each turns as turn, i (i)}{@const messages = extractMessages(turn.input, turn.output)}<div class="rounded-md border p-4">- <div class="mb-3 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">+ <div+ class="mb-3 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground"+ ><span class="font-medium">Turn {i + 1}</span>{#if turn.model}· <span class="font-mono">{turn.model}</span>{/if}· {formatCost(turn.totalCost)}- · {formatTokens(turn.totalTokens)} tokens- · {formatDuration(turn.duration)}+ · {formatTokens(turn.totalTokens)} tokens · {formatDuration(turn.duration)}· {formatDateTime(turn.recordedAt, { timezone })}·- <a class="text-primary hover:underline" href={turnHref(turn)}>View call →</a>+ <a class="text-primary hover:underline" {...{ href: resolveHref(turnHref(turn)) }}+ >View call →</a+ ></div>{#if messages}<ConversationMessages {messages} />diff --git a/frontend/src/routes/ai-traces/users/+page.svelte b/frontend/src/routes/ai-traces/users/+page.svelteindex 062597b7..6151a149 100644--- a/frontend/src/routes/ai-traces/users/+page.svelte+++ b/frontend/src/routes/ai-traces/users/+page.svelte@@ -1,416 +1,444 @@<script lang="ts">- import { onMount, onDestroy } from 'svelte';- import { api } from '$lib/api';- import { toUTCISO, calendarDateTimeToLuxon, formatDateTime } from '$lib/utils/formatters';- import { getTimezone } from '$lib/state/timezone.svelte';- import * as Table from "$lib/components/ui/table";- import * as Tooltip from "$lib/components/ui/tooltip";- import { LoadingCircle } from "$lib/components/ui/loading-circle";- import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";- import { TableEmptyState } from "$lib/components/ui/table-empty-state";- import { PaginationFooter } from "$lib/components/ui/pagination-footer";- import { TimeRangePicker } from "$lib/components/ui/time-range-picker";- import { SearchBar } from "$lib/components/ui/search-bar";- import { browser } from '$app/environment';- import { CalendarDate } from "@internationalized/date";- import { projectsState } from '$lib/state/projects.svelte';- import { createRowClickHandler } from '$lib/utils/navigation';- import { resolve } from '$app/paths';- import PageHeader from '$lib/components/issues/page-header.svelte';- import { formatCost, formatCount, formatTokens } from '$lib/utils/ai-format';- import AiNavTabs from '$lib/components/ai/ai-nav-tabs.svelte';- import { TriangleAlert } from 'lucide-svelte';- import {- getTimeRangeFromPreset,- dateToCalendarDate,- dateToTimeString,- parseTimeRangeFromUrl,- getResolvedTimeRange,- updateUrl- } from '$lib/utils/url-params';- import {- getSortState,- setSortState,- handleSortClick,- type SortDirection- } from '$lib/utils/sort-storage';-- const timezone = $derived(getTimezone());- const initialTimezone = getTimezone();-- type UserRow = {- userId: string;- conversationCount: number;- totalCalls: number;- avgTurns: number;- minTurns: number;- medianTurns: number;- avgCostPerConversation: number;- totalCost: number;- flaggedConversationCount: number;- totalTokens: number;- lastSeen: string;- };-- type SortField = 'conversation_count' | 'total_calls' | 'median_turns' | 'avg_conversation_cost' | 'total_cost' | 'total_tokens' | 'flagged_conversation_count' | 'last_seen';-- let users = $state<UserRow[]>([]);- let loading = $state(true);- let error = $state('');-- // Pagination State- let page = $state(1);- let pageSize = $state(50);- let total = $state(0);- let totalPages = $state(0);-- function parseUsersUrlParams() {- if (!browser) return { preset: '24h', from: null, to: null, search: '' };- const params = new URLSearchParams(window.location.search);- const timeParams = parseTimeRangeFromUrl(timezone, '24h');- return {- ...timeParams,- search: params.get('search') || ''- };- }-- const initialUrlParams = parseUsersUrlParams();- const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);-- let searchQuery = $state(initialUrlParams.search);-- // Date Range State- let selectedPreset = $state<string | null>(initialUrlParams.preset);- let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));- let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));- let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));- let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));-- function updateTimeRangeUrl(pushToHistory = true) {- const params: Record<string, string | null | undefined> = {};- if (selectedPreset) {- params.preset = selectedPreset;- } else {- params.from = getFromDateTimeUTC();- params.to = getToDateTimeUTC();- }- if (searchQuery.trim()) {- params.search = searchQuery.trim();- }- updateUrl(params, { pushToHistory });- }-- function handlePopState() {- const urlParams = parseUsersUrlParams();- const range = getResolvedTimeRange(urlParams, timezone);-- selectedPreset = urlParams.preset;- fromDate = dateToCalendarDate(range.from, timezone);- fromTime = dateToTimeString(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- toTime = dateToTimeString(range.to, timezone);- searchQuery = urlParams.search;-- page = 1;- loadData(false);- }-- const SORT_STORAGE_KEY = 'ai-users';- const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'total_cost', direction: 'desc' });- let orderBy = $state<SortField>(initialSort.field as SortField);- let sortDirection = $state<SortDirection>(initialSort.direction);-- function getFromDateTimeUTC(): string {- const [hour, minute] = (fromTime || '00:00').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute }, timezone);- return toUTCISO(dt);- }-- function getToDateTimeUTC(): string {- const [hour, minute] = (toTime || '23:59').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: toDate.year, month: toDate.month, day: toDate.day, hour, minute }, timezone).endOf('minute');- return toUTCISO(dt);- }-- function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) {- fromDate = from.date;- fromTime = from.time;- toDate = to.date;- toTime = to.time;- selectedPreset = preset;- page = 1;- loadData(false);- }-- async function loadData(pushToHistory = true) {- loading = true;- error = '';-- if (selectedPreset) {- const range = getTimeRangeFromPreset(selectedPreset, timezone);- fromDate = dateToCalendarDate(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- fromTime = dateToTimeString(range.from, timezone);- toTime = dateToTimeString(range.to, timezone);- }-- updateTimeRangeUrl(pushToHistory);-- try {- const requestBody = {- fromDate: getFromDateTimeUTC(),- toDate: getToDateTimeUTC(),- orderBy: orderBy,- sortDirection: sortDirection,- pagination: {- page: page,- pageSize: pageSize- },- search: searchQuery.trim()- };-- const response = await api.post('/ai-users/grouped', requestBody, { projectId: projectsState.currentProjectId ?? undefined });-- users = response.data || [];- total = response.pagination.total;- totalPages = response.pagination.totalPages;- } catch (e: any) {- console.error(e);- error = e.message || 'Failed to load data';- } finally {- loading = false;- }- }-- function handlePageChange(newPage: number) {- if (newPage >= 1 && newPage <= totalPages) {- page = newPage;- loadData(false);- }- }-- function handlePageSizeChange(newPageSize: number) {- pageSize = newPageSize;- page = 1;- loadData(false);- }-- function handleSort(field: SortField) {- const newSort = handleSortClick(field, orderBy, sortDirection);- orderBy = newSort.field as SortField;- sortDirection = newSort.direction;- setSortState(SORT_STORAGE_KEY, newSort);- page = 1;- loadData(false);- }-- function handleSearch() {- page = 1;- loadData(true);- }-- function userConversationsHref(userId: string): string {- return `${resolve('/ai-traces/conversations')}?userId=${encodeURIComponent(userId)}`;- }-- onMount(() => {- window.addEventListener('popstate', handlePopState);- loadData(false);- });-- onDestroy(() => {- if (typeof window !== 'undefined') {- window.removeEventListener('popstate', handlePopState);- }- });+ import { getErrorMessage } from '$lib/utils/errors';+ import { onMount, onDestroy } from 'svelte';+ import { api } from '$lib/api';+ import { toUTCISO, calendarDateTimeToLuxon, formatDateTime } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import * as Table from '$lib/components/ui/table';+ import * as Tooltip from '$lib/components/ui/tooltip';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { TimeRangePicker } from '$lib/components/ui/time-range-picker';+ import { SearchBar } from '$lib/components/ui/search-bar';+ import { browser } from '$app/environment';+ import { CalendarDate } from '@internationalized/date';+ import { projectsState } from '$lib/state/projects.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { resolve } from '$app/paths';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import { formatCost, formatCount } from '$lib/utils/ai-format';+ import AiNavTabs from '$lib/components/ai/ai-nav-tabs.svelte';+ import { TriangleAlert } from '@lucide/svelte';+ import {+ getTimeRangeFromPreset,+ dateToCalendarDate,+ dateToTimeString,+ parseTimeRangeFromUrl,+ getResolvedTimeRange,+ updateUrl+ } from '$lib/utils/url-params';+ import {+ getSortState,+ setSortState,+ handleSortClick,+ type SortDirection+ } from '$lib/utils/sort-storage';++ const timezone = $derived(getTimezone());+ const initialTimezone = getTimezone();++ type UserRow = {+ userId: string;+ conversationCount: number;+ totalCalls: number;+ avgTurns: number;+ minTurns: number;+ medianTurns: number;+ avgCostPerConversation: number;+ totalCost: number;+ flaggedConversationCount: number;+ totalTokens: number;+ lastSeen: string;+ };++ type SortField =+ | 'conversation_count'+ | 'total_calls'+ | 'median_turns'+ | 'avg_conversation_cost'+ | 'total_cost'+ | 'total_tokens'+ | 'flagged_conversation_count'+ | 'last_seen';++ let users = $state<UserRow[]>([]);+ let loading = $state(true);+ let error = $state('');++ // Pagination State+ let page = $state(1);+ let pageSize = $state(50);+ let total = $state(0);+ let totalPages = $state(0);++ function parseUsersUrlParams() {+ if (!browser) return { preset: '24h', from: null, to: null, search: '' };+ const params = new URLSearchParams(window.location.search);+ const timeParams = parseTimeRangeFromUrl(timezone, '24h');+ return {+ ...timeParams,+ search: params.get('search') || ''+ };+ }++ const initialUrlParams = parseUsersUrlParams();+ const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);++ let searchQuery = $state(initialUrlParams.search);++ // Date Range State+ let selectedPreset = $state<string | null>(initialUrlParams.preset);+ let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));+ let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));+ let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));+ let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));++ function updateTimeRangeUrl(pushToHistory = true) {+ const params: Record<string, string | null | undefined> = {};+ if (selectedPreset) {+ params.preset = selectedPreset;+ } else {+ params.from = getFromDateTimeUTC();+ params.to = getToDateTimeUTC();+ }+ if (searchQuery.trim()) {+ params.search = searchQuery.trim();+ }+ updateUrl(params, { pushToHistory });+ }++ function handlePopState() {+ const urlParams = parseUsersUrlParams();+ const range = getResolvedTimeRange(urlParams, timezone);++ selectedPreset = urlParams.preset;+ fromDate = dateToCalendarDate(range.from, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ toTime = dateToTimeString(range.to, timezone);+ searchQuery = urlParams.search;++ page = 1;+ loadData(false);+ }++ const SORT_STORAGE_KEY = 'ai-users';+ const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'total_cost', direction: 'desc' });+ let orderBy = $state<SortField>(initialSort.field as SortField);+ let sortDirection = $state<SortDirection>(initialSort.direction);++ function getFromDateTimeUTC(): string {+ const [hour, minute] = (fromTime || '00:00').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute },+ timezone+ );+ return toUTCISO(dt);+ }++ function getToDateTimeUTC(): string {+ const [hour, minute] = (toTime || '23:59').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: toDate.year, month: toDate.month, day: toDate.day, hour, minute },+ timezone+ ).endOf('minute');+ return toUTCISO(dt);+ }++ function handleTimeRangeChange(+ from: { date: CalendarDate; time: string },+ to: { date: CalendarDate; time: string },+ preset: string | null+ ) {+ fromDate = from.date;+ fromTime = from.time;+ toDate = to.date;+ toTime = to.time;+ selectedPreset = preset;+ page = 1;+ loadData(false);+ }++ async function loadData(pushToHistory = true) {+ loading = true;+ error = '';++ if (selectedPreset) {+ const range = getTimeRangeFromPreset(selectedPreset, timezone);+ fromDate = dateToCalendarDate(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toTime = dateToTimeString(range.to, timezone);+ }++ updateTimeRangeUrl(pushToHistory);++ try {+ const requestBody = {+ fromDate: getFromDateTimeUTC(),+ toDate: getToDateTimeUTC(),+ orderBy: orderBy,+ sortDirection: sortDirection,+ pagination: {+ page: page,+ pageSize: pageSize+ },+ search: searchQuery.trim()+ };++ const response = await api.post('/ai-users/grouped', requestBody, {+ projectId: projectsState.currentProjectId ?? undefined+ });++ users = response.data || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e) {+ console.error(e);+ error = getErrorMessage(e) || 'Failed to load data';+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData(false);+ }+ }++ function handlePageSizeChange(newPageSize: number) {+ pageSize = newPageSize;+ page = 1;+ loadData(false);+ }++ function handleSort(field: SortField) {+ const newSort = handleSortClick(field, orderBy, sortDirection);+ orderBy = newSort.field as SortField;+ sortDirection = newSort.direction;+ setSortState(SORT_STORAGE_KEY, newSort);+ page = 1;+ loadData(false);+ }++ function handleSearch() {+ page = 1;+ loadData(true);+ }++ function userConversationsHref(userId: string): string {+ return `${resolve('/ai-traces/conversations')}?userId=${encodeURIComponent(userId)}`;+ }++ onMount(() => {+ window.addEventListener('popstate', handlePopState);+ loadData(false);+ });++ onDestroy(() => {+ if (typeof window !== 'undefined') {+ window.removeEventListener('popstate', handlePopState);+ }+ });</script><div class="space-y-4">- <!-- Header with Title and Time Range Filter -->- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">- <PageHeader title="AI Users" />- <div class="flex flex-col">- <TimeRangePicker- bind:fromDate- bind:toDate- bind:fromTime- bind:toTime- bind:preset={selectedPreset}- onApply={handleTimeRangeChange}- />- </div>- </div>-- <AiNavTabs active="users" />-- <!-- Search -->- <SearchBar- placeholder="Search users..."- bind:value={searchQuery}- onSearch={handleSearch}- disabled={loading}- />-- <!-- Users Table -->- <div class="rounded-md border overflow-hidden">- <Table.Root>- {#if loading}- <Table.Body>- <Table.Row>- <Table.Cell colspan={8} class="h-48">- <div class="flex justify-center items-center h-full">- <LoadingCircle size="xlg" />- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if error}- <Table.Body>- <TableEmptyState colspan={8} message={error} />- </Table.Body>- {:else if users.length === 0}- <Table.Body>- <TableEmptyState- colspan={8}- message={searchQuery.trim()- ? 'No users match the current search.'- : 'No users found. Per-user analytics appear once your AI calls carry both a user.id and a conversation id.'}- />- </Table.Body>- {:else}- <Table.Header>- <Table.Row>- <TracewayTableHeader- label="User"- tooltip="The user.id attribute on the calls"- />- <TracewayTableHeader- label="Conversations"- tooltip="Number of distinct conversations"- sortField="conversation_count"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[130px]"- />- <TracewayTableHeader- label="Calls"- tooltip="Total LLM calls across all conversations"- sortField="total_calls"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[90px]"- />- <TracewayTableHeader- label="Median Turns"- tooltip="Median conversation length in LLM calls"- sortField="median_turns"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[130px]"- />- <TracewayTableHeader- label="Avg Cost/Conv"- tooltip="Average cost per conversation"- sortField="avg_conversation_cost"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[130px]"- />- <TracewayTableHeader- label="Total Cost"- tooltip="Total cost across all conversations"- sortField="total_cost"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[110px]"- />- <TracewayTableHeader- label="Flagged"- tooltip="Conversations containing flagged terms"- sortField="flagged_conversation_count"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Last Seen"- tooltip="When this user last had a call"- sortField="last_seen"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[130px]"- />- </Table.Row>- </Table.Header>- <Table.Body>- {#each users as user}- <Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={createRowClickHandler(userConversationsHref(user.userId), 'preset', 'from', 'to')}- >- <Table.Cell class="max-w-[240px] truncate font-mono text-sm" title={user.userId}>- {user.userId}- </Table.Cell>- <Table.Cell class="tabular-nums">- {formatCount(user.conversationCount)}- </Table.Cell>- <Table.Cell class="tabular-nums">- {formatCount(user.totalCalls)}- </Table.Cell>- <Table.Cell class="tabular-nums">- <Tooltip.Provider>- <Tooltip.Root>- <Tooltip.Trigger>- <span>{user.medianTurns.toFixed(1)}</span>- </Tooltip.Trigger>- <Tooltip.Content>- <p class="text-xs">avg {user.avgTurns.toFixed(1)} · min {user.minTurns}</p>- </Tooltip.Content>- </Tooltip.Root>- </Tooltip.Provider>- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {formatCost(user.avgCostPerConversation)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {formatCost(user.totalCost)}- </Table.Cell>- <Table.Cell class="tabular-nums">- {#if user.flaggedConversationCount > 0}- <span class="inline-flex items-center gap-1 font-medium text-red-600 dark:text-red-400">- <TriangleAlert class="h-3 w-3" />- {formatCount(user.flaggedConversationCount)}- </span>- {:else}- <span class="text-muted-foreground">0</span>- {/if}- </Table.Cell>- <Table.Cell class="text-muted-foreground text-sm">- {formatDateTime(user.lastSeen, { timezone })}- </Table.Cell>- </Table.Row>- {/each}- </Table.Body>- {/if}- </Table.Root>- </div>-- <!-- Pagination Footer -->- <PaginationFooter- currentPage={page}- {totalPages}- {pageSize}- totalItems={total}- onPageChange={handlePageChange}- onPageSizeChange={handlePageSizeChange}- {loading}- itemLabel="user"- />+ <PageHeader title="AI Users">+ {#snippet actions()}+ <TimeRangePicker+ bind:fromDate+ bind:toDate+ bind:fromTime+ bind:toTime+ bind:preset={selectedPreset}+ onApply={handleTimeRangeChange}+ />+ {/snippet}+ </PageHeader>++ <AiNavTabs active="users" />++ <!-- Search -->+ <SearchBar+ placeholder="Search users..."+ bind:value={searchQuery}+ onSearch={handleSearch}+ disabled={loading}+ />++ <!-- Users Table -->+ <TableContainer>+ <Table.Root>+ {#if loading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={8} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if error}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={8} class="h-24 text-center text-red-500">+ {error}+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if users.length === 0}+ <Table.Body>+ <TableEmptyState+ colspan={8}+ message={searchQuery.trim()+ ? 'No users match the current search.'+ : 'No users found. Per-user analytics appear once your AI calls carry both a user.id and a conversation id.'}+ />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader label="User" tooltip="The user.id attribute on the calls" />+ <TracewayTableHeader+ label="Conversations"+ tooltip="Number of distinct conversations"+ sortField="conversation_count"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[130px]"+ />+ <TracewayTableHeader+ label="Calls"+ tooltip="Total LLM calls across all conversations"+ sortField="total_calls"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[90px]"+ />+ <TracewayTableHeader+ label="Median Turns"+ tooltip="Median conversation length in LLM calls"+ sortField="median_turns"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[130px]"+ />+ <TracewayTableHeader+ label="Avg Cost/Conv"+ tooltip="Average cost per conversation"+ sortField="avg_conversation_cost"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[130px]"+ />+ <TracewayTableHeader+ label="Total Cost"+ tooltip="Total cost across all conversations"+ sortField="total_cost"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[110px]"+ />+ <TracewayTableHeader+ label="Flagged"+ tooltip="Conversations containing flagged terms"+ sortField="flagged_conversation_count"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Last Seen"+ tooltip="When this user last had a call"+ sortField="last_seen"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[130px]"+ />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each users as user, __index (__index)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ userConversationsHref(user.userId),+ 'preset',+ 'from',+ 'to'+ )}+ >+ <Table.Cell class="max-w-[240px] truncate font-mono text-sm" title={user.userId}>+ {user.userId}+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ {formatCount(user.conversationCount)}+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ {formatCount(user.totalCalls)}+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span>{user.medianTurns.toFixed(1)}</span>+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">avg {user.avgTurns.toFixed(1)} · min {user.minTurns}</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatCost(user.avgCostPerConversation)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatCost(user.totalCost)}+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ {#if user.flaggedConversationCount > 0}+ <span+ class="inline-flex items-center gap-1 font-medium text-red-600 dark:text-red-400"+ >+ <TriangleAlert class="h-3 w-3" />+ {formatCount(user.flaggedConversationCount)}+ </span>+ {:else}+ <span class="text-muted-foreground">0</span>+ {/if}+ </Table.Cell>+ <Table.Cell class="text-sm text-muted-foreground">+ {formatDateTime(user.lastSeen, { timezone })}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </TableContainer>++ <!-- Pagination Footer -->+ <PaginationFooter+ currentPage={page}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={handlePageChange}+ onPageSizeChange={handlePageSizeChange}+ {loading}+ itemLabel="user"+ /></div>diff --git a/frontend/src/routes/auth/callback/+page.svelte b/frontend/src/routes/auth/callback/+page.svelteindex 2a3813c3..4bd3d17f 100644--- a/frontend/src/routes/auth/callback/+page.svelte+++ b/frontend/src/routes/auth/callback/+page.svelte@@ -1,61 +1,60 @@<script lang="ts">- import { goto } from '$app/navigation';- import { onMount } from 'svelte';- import { authState } from '$lib/state/auth.svelte';- import { projectsState } from '$lib/state/projects.svelte';- import { consumeSsoReturnTo, safeLocalPath } from '$lib/utils/navigation';- import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";- import { ErrorAlert } from "$lib/components/ui/error-alert";- import { CircleAlert } from "@lucide/svelte";- import { LoadingCircle } from '$lib/components/ui/loading-circle';-- let error = $state('');-- onMount(async () => {- const fragment = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : '';- const params = new URLSearchParams(fragment);- const token = params.get('token');- const needsSetup = params.get('needsSetup') === 'true';-- history.replaceState(null, '', window.location.pathname);-- if (!token) {- error = 'Missing authentication token.';- setTimeout(() => goto('/login?error=oauth_failed'), 1500);- return;- }-- authState.setToken(token);-- if (needsSetup) {- // Leave the stashed returnTo in place: finish-setup consumes it.- goto('/finish-setup');- return;- }-- try {- const response = await fetch('/api/me/login-bundle', {- headers: { 'Authorization': `Bearer ${token}` }- });- if (!response.ok) {- throw new Error('Failed to load account');- }- const data = await response.json();- authState.setOrganizations(data.organizations || []);- projectsState.setProjects(data.projects || []);- goto(safeLocalPath(consumeSsoReturnTo()));- } catch {- authState.logout();- error = 'Failed to load your account. Please try logging in again.';- setTimeout(() => goto('/login?error=oauth_failed'), 1500);- }- });+ import { resolve } from '$app/paths';+ import { goto } from '$app/navigation';+ import { onMount } from 'svelte';+ import { authState } from '$lib/state/auth.svelte';+ import { projectsState } from '$lib/state/projects.svelte';+ import { consumeSsoReturnTo, gotoHref, safeLocalPath } from '$lib/utils/navigation';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';++ let error = $state('');++ onMount(async () => {+ const fragment = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : '';+ const params = new URLSearchParams(fragment);+ const token = params.get('token');+ const needsSetup = params.get('needsSetup') === 'true';++ history.replaceState(null, '', window.location.pathname);++ if (!token) {+ error = 'Missing authentication token.';+ setTimeout(() => gotoHref('/login?error=oauth_failed'), 1500);+ return;+ }++ authState.setToken(token);++ if (needsSetup) {+ // Leave the stashed returnTo in place: finish-setup consumes it.+ goto(resolve('/finish-setup'));+ return;+ }++ try {+ const response = await fetch('/api/me/login-bundle', {+ headers: { Authorization: `Bearer ${token}` }+ });+ if (!response.ok) {+ throw new Error('Failed to load account');+ }+ const data = await response.json();+ authState.setOrganizations(data.organizations || []);+ projectsState.setProjects(data.projects || []);+ gotoHref(safeLocalPath(consumeSsoReturnTo()));+ } catch {+ authState.logout();+ error = 'Failed to load your account. Please try logging in again.';+ setTimeout(() => gotoHref('/login?error=oauth_failed'), 1500);+ }+ });</script><div class="flex h-screen w-full items-center justify-center px-4">- {#if error}- <ErrorAlert {error} class="max-w-md" />- {:else}- <LoadingCircle size="xlg" />- {/if}+ {#if error}+ <ErrorAlert {error} class="max-w-md" />+ {:else}+ <LoadingCircle size="xlg" />+ {/if}</div>diff --git a/frontend/src/routes/connection/+page.svelte b/frontend/src/routes/connection/+page.svelteindex 90cc53ef..406b95dc 100644--- a/frontend/src/routes/connection/+page.svelte+++ b/frontend/src/routes/connection/+page.svelte@@ -6,25 +6,20 @@CardHeader,CardTitle} from '$lib/components/ui/card';- import { Button } from '$lib/components/ui/button';- import { Copy, Check } from 'lucide-svelte';import {projectsState,- type ProjectWithToken,isJsFramework,isOtelFramework,isCloudflareFramework,supportsSymbolUpload} from '$lib/state/projects.svelte';import FrameworkIcon from '$lib/components/framework-icon.svelte';- import Highlight from 'svelte-highlight';+ import PageHeader from '$lib/components/traceway/page-header.svelte';import go from 'svelte-highlight/languages/go';import javascript from 'svelte-highlight/languages/javascript';import bash from 'svelte-highlight/languages/bash';import php from 'svelte-highlight/languages/php';import python from 'svelte-highlight/languages/python';- import { themeState } from '$lib/state/theme.svelte';- import 'svelte-highlight/styles/github-dark.css';import {getFrameworkCode,getInstallCommand,@@ -36,15 +31,11 @@import OtelSetupSteps from '$lib/components/setup/otel-setup-steps.svelte';import OtelExporterConfig from '$lib/components/setup/otel-exporter-config.svelte';import SourceMapUploadCard from '$lib/components/setup/source-map-upload-card.svelte';+ import CopyableInline from '$lib/components/setup/copyable-inline.svelte';+ import CopyableCodeBlock from '$lib/components/setup/copyable-code-block.svelte';let projectWithToken = $derived(projectsState.currentProject);let setupMode = $state(getSetupMode());- let copiedCode = $state(false);- let copiedInstall = $state(false);- let copiedCfEndpoint = $state(false);- let copiedCfAuth = $state(false);- let copiedCfWrangler = $state(false);- let copiedCfDeploy = $state(false);const isOtel = $derived(projectWithToken ? isOtelFramework(projectWithToken.framework) : false);const isOtelGeneric = $derived(projectWithToken?.framework === 'opentelemetry');@@ -131,49 +122,10 @@ service:const showSymbolUpload = $derived(projectWithToken ? supportsSymbolUpload(projectWithToken.framework) : false);-- async function copyCode() {- await navigator.clipboard.writeText(sdkCode);- copiedCode = true;- setTimeout(() => (copiedCode = false), 2000);- }-- async function copyInstall() {- await navigator.clipboard.writeText(installCommand);- copiedInstall = true;- setTimeout(() => (copiedInstall = false), 2000);- }-- async function copyCfEndpoint() {- await navigator.clipboard.writeText(cloudflareOtelEndpoint);- copiedCfEndpoint = true;- setTimeout(() => (copiedCfEndpoint = false), 2000);- }-- async function copyCfAuth() {- await navigator.clipboard.writeText(cloudflareAuthHeader);- copiedCfAuth = true;- setTimeout(() => (copiedCfAuth = false), 2000);- }-- async function copyCfWrangler() {- await navigator.clipboard.writeText(wranglerConfig);- copiedCfWrangler = true;- setTimeout(() => (copiedCfWrangler = false), 2000);- }-- async function copyCfDeploy() {- await navigator.clipboard.writeText('npx wrangler deploy');- copiedCfDeploy = true;- setTimeout(() => (copiedCfDeploy = false), 2000);- }</script><div class="space-y-4">- <div>- <h2 class="text-3xl font-semibold tracking-tight">Connection</h2>- <p class="text-muted-foreground">Connect your application to Traceway using the SDK</p>- </div>+ <PageHeader title="Connection" description="Connect your application to Traceway using the SDK" />{#if projectWithToken}<SetupModeTabs mode={setupMode} onModeChange={(m) => (setupMode = m)} />@@ -218,77 +170,25 @@ service:<p class="mb-2 text-xs text-muted-foreground">Enter this URL when creating your OTLP destination in the Cloudflare dashboard.</p>- <div class="flex items-center gap-2">- <code class="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-sm break-all"- >{cloudflareOtelEndpoint}</code- >- <Button variant="outline" size="sm" onclick={copyCfEndpoint}>- {#if copiedCfEndpoint}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>- </div>+ <CopyableInline value={cloudflareOtelEndpoint} /></div><div><p class="mb-2 text-sm font-medium">Step 2: Authorization Header</p><p class="mb-2 text-xs text-muted-foreground">Add this as an authorization header in your OTLP destination settings.</p>- <div class="flex items-center gap-2">- <code class="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-sm break-all"- >{cloudflareAuthHeader}</code- >- <Button variant="outline" size="sm" onclick={copyCfAuth}>- {#if copiedCfAuth}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>- </div>+ <CopyableInline value={cloudflareAuthHeader} /></div><div><p class="mb-2 text-sm font-medium">Step 3: wrangler.jsonc</p><p class="mb-2 text-xs text-muted-foreground">Enable observability traces in your wrangler.jsonc configuration file.</p>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyCfWrangler}>- {#if copiedCfWrangler}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={javascript} code={wranglerConfig} />- </div>- </div>+ <CopyableCodeBlock code={wranglerConfig} language={javascript} /></div><div><p class="mb-2 text-sm font-medium">Step 4: Deploy</p>- <div class="flex items-center gap-2">- <code class="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-sm break-all"- >npx wrangler deploy</code- >- <Button variant="outline" size="sm" onclick={copyCfDeploy}>- {#if copiedCfDeploy}- <Check class="h-4 w-4 text-green-500" />- {:else}- <Copy class="h-4 w-4" />- {/if}- </Button>- </div>+ <CopyableInline value="npx wrangler deploy" /></div></div></CardContent>@@ -305,26 +205,7 @@ service:</CardDescription></CardHeader><CardContent>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyCode}>- {#if copiedCode}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={highlightLanguage} code={sdkCode} />- </div>- </div>+ <CopyableCodeBlock code={sdkCode} language={highlightLanguage} /></CardContent></Card>@@ -334,26 +215,7 @@ service:<CardDescription>{installDescription}</CardDescription></CardHeader><CardContent>- <div class="relative">- <div class="absolute top-2 right-2 z-10">- <Button variant="outline" size="sm" onclick={copyInstall}>- {#if copiedInstall}- <Check class="mr-2 h-4 w-4 text-green-500" />- Copied!- {:else}- <Copy class="mr-2 h-4 w-4" />- Copy- {/if}- </Button>- </div>- <div- class="overflow-x-auto rounded-md text-sm {themeState.isDark- ? 'dark-code'- : 'light-code'}"- >- <Highlight language={bash} code={installCommand} />- </div>- </div>+ <CopyableCodeBlock code={installCommand} language={bash} /></CardContent></Card>{#if showSymbolUpload}@@ -370,65 +232,3 @@ service:</Card>{/if}</div>--<style>- /* Light theme - override dark theme defaults */- :global(.light-code .hljs-name) {- color: #4ba3f7;- }- :global(.light-code .hljs) {- background: #f6f8fa;- color: #24292e;- }- :global(.light-code .hljs-keyword),- :global(.light-code .hljs-selector-tag) {- color: #d73a49;- }- :global(.light-code .hljs-string),- :global(.light-code .hljs-attr) {- color: #032f62;- }- :global(.light-code .hljs-function),- :global(.light-code .hljs-title) {- color: #6f42c1;- }- :global(.light-code .hljs-comment) {- color: #6a737d;- }- :global(.light-code .hljs-built_in) {- color: #005cc5;- }- :global(.light-code .hljs-meta) {- color: #d73a49;- }- :global(.light-code .hljs-variable) {- color: #24292e;- }-- /* Dark theme - ensure dark styles apply */- :global(.dark-code .hljs) {- background: #0d1117;- color: #c9d1d9;- }- :global(.dark-code .hljs-keyword),- :global(.dark-code .hljs-selector-tag) {- color: #ff7b72;- }- :global(.dark-code .hljs-string),- :global(.dark-code .hljs-attr) {- color: #a5d6ff;- }- :global(.dark-code .hljs-function),- :global(.dark-code .hljs-title) {- color: #d2a8ff;- }- :global(.dark-code .hljs-comment) {- color: #8b949e;- }- :global(.dark-code .hljs-built_in) {- color: #79c0ff;- }- :global(.dark-code .hljs-meta) {- color: #ff7b72;- }-</style>diff --git a/frontend/src/routes/dashboards/+page.svelte b/frontend/src/routes/dashboards/+page.svelteindex be4798c1..6f4f9449 100644--- a/frontend/src/routes/dashboards/+page.svelte+++ b/frontend/src/routes/dashboards/+page.svelte@@ -1,5 +1,8 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';+ import { resolve } from '$app/paths';import { onMount } from 'svelte';+ import { SvelteURLSearchParams } from 'svelte/reactivity';import { Button } from '$lib/components/ui/button';import { Input } from '$lib/components/ui/input';import { Checkbox } from '$lib/components/ui/checkbox';@@ -39,13 +42,16 @@Share2,CircleMinus,Search- } from 'lucide-svelte';+ } from '@lucide/svelte';import { WarningCallout } from '$lib/components/ui/warning-callout';import { ErrorAlert } from '$lib/components/ui/error-alert';import { ErrorDisplay } from '$lib/components/ui/error-display';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import FormField from '$lib/components/traceway/form-field.svelte';+ import EmptyState from '$lib/components/traceway/empty-state.svelte';import * as DropdownMenu from '$lib/components/ui/dropdown-menu';import { toast } from 'svelte-sonner';- import type { DiscoveredMetric } from '$lib/types/dashboard';+ import type { DashboardWidgetConfig, DiscoveredMetric } from '$lib/types/dashboard';const timezone = $derived(getTimezone());const initialTimezone = getTimezone();@@ -54,7 +60,7 @@id: string;title: string;widgetType: string;- config: any;+ config: DashboardWidgetConfig;position: number;isStarred?: boolean;};@@ -121,7 +127,11 @@let showWidgetConfig = $state(false);let editingWidget = $state<Widget | null>(null);- let widgetPrefill = $state<{ title: string; widgetType: string; config: any } | null>(null);+ let widgetPrefill = $state<{+ title: string;+ widgetType: string;+ config: DashboardWidgetConfig;+ } | null>(null);let availableMetrics = $state<DiscoveredMetric[]>([]);let widgetConfigError = $state('');@@ -196,8 +206,8 @@});$effect(() => {- dashboards;- lastUpdated;+ void dashboards;+ void lastUpdated;if (tabsRowEl) {requestAnimationFrame(() => checkOverflow());}@@ -232,9 +242,9 @@if (dashboards.length > 0 && !dashboards.some((d) => String(d.id) === activeTabId)) {activeTabId = String(dashboards[0].id);}- } catch (e: any) {+ } catch (e) {console.error('Failed to load dashboards:', e);- listError = e?.message || 'Failed to load dashboards';+ listError = getErrorMessage(e) || 'Failed to load dashboards';} finally {loading = false;}@@ -253,7 +263,7 @@if (seq !== loadSeq) return;activeDashboard = {...result,- widgets: (result.widgets ?? []).map((w: any, i: number) => ({ ...w, position: i }))+ widgets: (result.widgets ?? []).map((w: Widget, i: number) => ({ ...w, position: i }))};lastUpdated = new Date();} catch (e) {@@ -333,10 +343,10 @@{ dashboardIds },{ projectId: projectsState.currentProjectId ?? undefined });- } catch (e: any) {+ } catch (e) {dashboards = previous;- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to reorder dashboards', { position: 'top-center' });+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to reorder dashboards');}await loadDashboards();}@@ -356,9 +366,9 @@newName = '';await loadDashboards();activeTabId = String(dashboard.id);- } catch (e: any) {- if (e?.status === 422 || e?.status === 403) {- createError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422 || getErrorStatus(e) === 403) {+ createError = getErrorMessage(e);} else {console.error('Failed to create dashboard:', e);}@@ -387,9 +397,9 @@showRenameDialog = false;activeDashboard.name = renameName;await loadDashboards();- } catch (e: any) {- if (e?.status === 422 || e?.status === 403) {- renameError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422 || getErrorStatus(e) === 403) {+ renameError = getErrorMessage(e);} else {console.error('Failed to rename dashboard:', e);}@@ -410,9 +420,9 @@activeTabId = '';activeDashboard = null;await loadDashboards();- } catch (e: any) {- if (e?.status === 422 || e?.status === 403) {- deleteError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422 || getErrorStatus(e) === 403) {+ deleteError = getErrorMessage(e);} else {console.error('Failed to delete dashboard:', e);}@@ -426,16 +436,19 @@removing = true;removeError = '';try {- await api.delete(`/dashboards/${activeDashboard.id}/apply/${projectsState.currentProjectId}`, {- projectId: projectsState.currentProjectId ?? undefined- });+ await api.delete(+ `/dashboards/${activeDashboard.id}/apply/${projectsState.currentProjectId}`,+ {+ projectId: projectsState.currentProjectId ?? undefined+ }+ );showRemoveDialog = false;activeTabId = '';activeDashboard = null;await loadDashboards();- } catch (e: any) {- if (e?.status === 422 || e?.status === 403) {- removeError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422 || getErrorStatus(e) === 403) {+ removeError = getErrorMessage(e);} else {console.error('Failed to remove dashboard from project:', e);}@@ -468,21 +481,26 @@async function saveJson() {if (!activeDashboard) return;jsonError = '';- let parsed: any;+ let parsed: unknown;try {parsed = JSON.parse(jsonText);} catch {jsonError = 'The document is not valid JSON.';return;}+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ jsonError = 'The document must contain a JSON object.';+ return;+ }+ const document = parsed as Record<string, unknown>;jsonSaving = true;try {await api.put(`/dashboards/${activeDashboard.id}`,{- name: parsed.name,- description: parsed.description ?? '',- definition: { schemaVersion: 1, widgets: parsed.widgets ?? [] }+ name: document.name,+ description: document.description ?? '',+ definition: { schemaVersion: 1, widgets: document.widgets ?? [] }},{ projectId: projectsState.currentProjectId ?? undefined });@@ -490,9 +508,9 @@showJsonDialog = false;await loadDashboards();await loadDashboardWidgets(activeTabId);- } catch (e: any) {- if (e?.status === 422 || e?.status === 403) {- jsonError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422 || getErrorStatus(e) === 403) {+ jsonError = getErrorMessage(e);} else {console.error('Failed to save dashboard JSON:', e);}@@ -519,8 +537,8 @@});const slug = activeDashboard.name.toLowerCase().replace(/[^a-z0-9]+/g, '-');downloadJson(`${slug || 'dashboard'}.dashboard.json`, doc);- } catch (e: any) {- toast.error(e?.message || 'Failed to export dashboard', { position: 'top-center' });+ } catch (e) {+ toast.error(getErrorMessage(e) || 'Failed to export dashboard');}}@@ -552,11 +570,11 @@if (activeTabId && dashboards.some((d) => String(d.id) === activeTabId)) {await loadDashboardWidgets(activeTabId);}- } catch (e: any) {- if (e?.status === 422) {- applyError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422) {+ applyError = getErrorMessage(e);} else {- applyError = e?.message || 'Failed to apply dashboard';+ applyError = getErrorMessage(e) || 'Failed to apply dashboard';}} finally {applying = false;@@ -579,7 +597,7 @@async function importDashboards() {importError = '';- let parsed: any;+ let parsed: unknown;try {parsed = JSON.parse(importText);} catch {@@ -594,20 +612,18 @@{ projectId: projectsState.currentProjectId ?? undefined });const count = (result.dashboards ?? []).length;- toast.success(`Successfully imported ${count} Dashboard${count === 1 ? '' : 's'}`, {- position: 'top-center'- });+ toast.success(`Successfully imported ${count} Dashboard${count === 1 ? '' : 's'}`);showImportDialog = false;importText = '';await loadDashboards();if (result.dashboards?.length) {activeTabId = String(result.dashboards[0].id);}- } catch (e: any) {- if (e?.status === 422) {- importError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422) {+ importError = getErrorMessage(e);} else {- importError = e?.message || 'Failed to import dashboards';+ importError = getErrorMessage(e) || 'Failed to import dashboards';}} finally {importing = false;@@ -616,7 +632,7 @@async function importGrafana() {grafanaError = '';- let parsed: any;+ let parsed: unknown;try {parsed = JSON.parse(grafanaText);} catch {@@ -630,7 +646,7 @@{ grafana: parsed },{ projectId: projectsState.currentProjectId ?? undefined });- toast.success('Successfully imported the Dashboard', { position: 'top-center' });+ toast.success('Successfully imported the Dashboard');grafanaWarnings = result.warnings ?? [];grafanaText = '';await loadDashboards();@@ -640,11 +656,11 @@if (grafanaWarnings.length === 0) {showGrafanaDialog = false;}- } catch (e: any) {- if (e?.status === 422) {- grafanaError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422) {+ grafanaError = getErrorMessage(e);} else {- grafanaError = e?.message || 'Failed to import the Grafana dashboard';+ grafanaError = getErrorMessage(e) || 'Failed to import the Grafana dashboard';}} finally {grafanaImporting = false;@@ -755,9 +771,9 @@showDeleteWidgetDialog = false;deletingWidget = null;await loadDashboardWidgets(activeTabId);- } catch (e: any) {- if (e?.status === 422 || e?.status === 403) {- deleteWidgetError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422 || getErrorStatus(e) === 403) {+ deleteWidgetError = getErrorMessage(e);} else {console.error('Failed to delete widget:', e);}@@ -778,10 +794,10 @@{},{ projectId: projectsState.currentProjectId ?? undefined });- } catch (e: any) {+ } catch (e) {target.isStarred = previous;- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to update star', { position: 'top-center' });+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to update star');}}}@@ -799,12 +815,12 @@{ widgetIds },{ projectId: projectsState.currentProjectId ?? undefined });- } catch (e: any) {+ } catch (e) {for (const w of activeDashboard.widgets) {w.position = previousPositions.get(w.id) ?? w.position;}- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to reorder widgets', { position: 'top-center' });+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to reorder widgets');}await loadDashboardWidgets(activeTabId);}@@ -822,11 +838,11 @@},{ projectId: projectsState.currentProjectId ?? undefined });- toast.success('Successfully duplicated the Widget', { position: 'top-center' });+ toast.success('Successfully duplicated the Widget');await loadDashboardWidgets(activeTabId);- } catch (e: any) {- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to duplicate widget', { position: 'top-center' });+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to duplicate widget');}}}@@ -843,15 +859,19 @@{ title: target.title, widgetType: target.widgetType, config: target.config },{ projectId: projectsState.currentProjectId ?? undefined });- } catch (e: any) {+ } catch (e) {target.config = previousConfig;- if (e?.status !== 403) {- toast.error(e?.message || 'Failed to resize widget', { position: 'top-center' });+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to resize widget');}}}- async function handleWidgetSave(data: { title: string; widgetType: string; config: any }) {+ async function handleWidgetSave(data: {+ title: string;+ widgetType: string;+ config: DashboardWidgetConfig;+ }) {if (!activeDashboard) return;widgetConfigError = '';@@ -871,9 +891,9 @@editingWidget = null;widgetPrefill = null;await loadDashboardWidgets(activeTabId);- } catch (e: any) {- if (e?.status === 422 || e?.status === 403) {- widgetConfigError = e.message;+ } catch (e) {+ if (getErrorStatus(e) === 422 || getErrorStatus(e) === 403) {+ widgetConfigError = getErrorMessage(e);} else {console.error('Failed to save widget:', e);}@@ -889,7 +909,7 @@if (search === handledSearch) return;handledSearch = search;- const params = new URLSearchParams(search);+ const params = new SvelteURLSearchParams(search);const action = params.get('action');const dashboardParam = params.get('dashboard');const addMetric = params.get('addMetric');@@ -899,7 +919,9 @@params.delete('dashboard');params.delete('addMetric');const query = params.toString();- replaceState(page.url.pathname + (query ? '?' + query : ''), {});+ let target = resolve(page.url.pathname as '/');+ target += query ? '?' + query : '';+ replaceState(target, {});if (action === 'create') showCreateDialog = true;else if (action === 'import') showImportDialog = true;@@ -956,33 +978,32 @@<svelte:window onkeydown={handlePageKeydown} /><div class="space-y-4">- <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">- <h2 class="text-3xl font-semibold tracking-tight">Dashboards</h2>- {#if dashboards.length > 0}- <div class="flex items-center gap-2">- <button- class="inline-flex h-9 items-center gap-2 rounded-md border border-input bg-background px-3 text-sm text-muted-foreground shadow-xs transition-colors hover:bg-muted hover:text-foreground sm:w-64"- onclick={() => (showPalette = true)}- >- <Search class="h-4 w-4 shrink-0" />- <span class="flex-1 truncate text-left">Add or find dashboards...</span>- <kbd- class="pointer-events-none hidden h-5 shrink-0 items-center gap-0.5 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium sm:inline-flex"+ <PageHeader title="Dashboards">+ {#snippet actions()}+ {#if dashboards.length > 0}+ <button+ class="inline-flex h-9 items-center gap-2 rounded-md border border-input bg-background px-3 text-sm text-muted-foreground shadow-xs transition-colors hover:bg-muted hover:text-foreground @2xl:w-64"+ onclick={() => (showPalette = true)}>- {isMac ? '⌘' : 'Ctrl'}K- </kbd>- </button>- <TimeRangePicker- bind:fromDate- bind:toDate- bind:fromTime- bind:toTime- bind:preset={selectedPreset}- onApply={handleTimeRangeChange}- />- </div>- {/if}- </div>+ <Search class="h-4 w-4 shrink-0" />+ <span class="flex-1 truncate text-left">Add or find dashboards...</span>+ <kbd+ class="pointer-events-none hidden h-5 shrink-0 items-center gap-0.5 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium sm:inline-flex"+ >+ {isMac ? '⌘' : 'Ctrl'}K+ </kbd>+ </button>+ <TimeRangePicker+ bind:fromDate+ bind:toDate+ bind:fromTime+ bind:toTime+ bind:preset={selectedPreset}+ onApply={handleTimeRangeChange}+ />+ {/if}+ {/snippet}+ </PageHeader>{#if loading}<div class="flex items-center justify-center py-20">@@ -996,13 +1017,16 @@onRetry={() => loadDashboards()}/>{:else if dashboards.length === 0}- <div class="flex flex-col items-center justify-center rounded-md bg-muted py-20 text-center">- <p class="mb-4 text-muted-foreground">No dashboards yet.</p>- <Button onclick={() => (showPalette = true)}>- <Search class="mr-1 h-4 w-4" />- Browse Dashboards & Templates- </Button>- </div>+ <EmptyState+ message="No dashboards yet."+ actionLabel="Browse Dashboards & Templates"+ actionVariant="default"+ onAction={() => (showPalette = true)}+ >+ {#snippet icon()}+ <Search class="h-6 w-6 text-muted-foreground" />+ {/snippet}+ </EmptyState>{:else}<Tabs.Root value={activeTabId} onValueChange={handleTabChange}><div class="flex items-center gap-2" bind:this={tabsRowEl}>@@ -1168,10 +1192,12 @@<LoadingCircle size="xlg" /></div>{:else if loadError && activeTabId === String(dashboard.id)}- <div class="flex flex-col items-center justify-center gap-3 rounded-md bg-muted py-20 text-center">+ <div+ class="flex flex-col items-center justify-center gap-3 rounded-md bg-muted py-20 text-center"+ ><p class="text-muted-foreground">{loadError}</p><Button variant="outline" onclick={() => loadDashboardWidgets(activeTabId)}>- <RefreshCw class="mr-1 h-4 w-4" />+ <RefreshCw class="mr-2 h-4 w-4" />Retry</Button></div>@@ -1231,21 +1257,20 @@<AlertDialog.Title>New Dashboard</AlertDialog.Title></AlertDialog.Header><ErrorAlert error={createError} />- <div class="space-y-4">- <div>- <label class="text-sm font-medium" for="new-dashboard-name">Name</label>- <Input- id="new-dashboard-name"- bind:value={newName}- placeholder="My Dashboard"- maxlength={100}- />- </div>- </div>+ <FormField label="Name" for="new-dashboard-name">+ <Input+ id="new-dashboard-name"+ bind:value={newName}+ placeholder="My Dashboard"+ maxlength={100}+ />+ </FormField><AlertDialog.Footer>- <Button variant="outline" onclick={() => (showCreateDialog = false)}>Cancel</Button>+ <Button variant="outline" onclick={() => (showCreateDialog = false)} disabled={creating}>+ Cancel+ </Button><Button variant="success" onclick={createDashboard} disabled={creating}>- {#if creating}Creating...{:else}<Plus class="mr-1 h-4 w-4" /> New Dashboard{/if}+ {#if creating}Creating...{:else}<Plus class="mr-2 h-4 w-4" /> New Dashboard{/if}</Button></AlertDialog.Footer></AlertDialog.Content>@@ -1262,21 +1287,20 @@<AlertDialog.Title>Rename Dashboard</AlertDialog.Title></AlertDialog.Header><ErrorAlert error={renameError} />- <div class="space-y-4">- <div>- <label class="text-sm font-medium" for="rename-dashboard-name">Name</label>- <Input- id="rename-dashboard-name"- bind:value={renameName}- placeholder="My Dashboard"- maxlength={100}- />- </div>- </div>+ <FormField label="Name" for="rename-dashboard-name">+ <Input+ id="rename-dashboard-name"+ bind:value={renameName}+ placeholder="My Dashboard"+ maxlength={100}+ />+ </FormField><AlertDialog.Footer>- <Button variant="outline" onclick={() => (showRenameDialog = false)}>Cancel</Button>+ <Button variant="outline" onclick={() => (showRenameDialog = false)} disabled={renaming}>+ Cancel+ </Button><Button onclick={renameDashboard} disabled={renaming}>- {#if renaming}Updating...{:else}<Check class="mr-1 h-4 w-4" /> Update Dashboard{/if}+ {#if renaming}Updating...{:else}<Check class="mr-2 h-4 w-4" /> Update Dashboard{/if}</Button></AlertDialog.Footer></AlertDialog.Content>@@ -1304,9 +1328,11 @@></textarea></div><AlertDialog.Footer>- <Button variant="outline" onclick={() => (showJsonDialog = false)}>Cancel</Button>+ <Button variant="outline" onclick={() => (showJsonDialog = false)} disabled={jsonSaving}>+ Cancel+ </Button><Button onclick={saveJson} disabled={jsonSaving}>- {#if jsonSaving}Updating...{:else}<Check class="mr-1 h-4 w-4" /> Update Dashboard{/if}+ {#if jsonSaving}Updating...{:else}<Check class="mr-2 h-4 w-4" /> Update Dashboard{/if}</Button></AlertDialog.Footer></AlertDialog.Content>@@ -1326,10 +1352,10 @@</AlertDialog.Description></AlertDialog.Header><WarningCallout title="Shared across projects">- This is a single shared dashboard. Checking a project shows it in that project's tabs.- Nothing is copied or overwritten, but edits made from any project apply to all of them.- Unchecking a project removes the dashboard from its tabs, including any of its widgets- starred on that project's homepage.+ This is a single shared dashboard. Checking a project shows it in that project's tabs. Nothing+ is copied or overwritten, but edits made from any project apply to all of them. Unchecking a+ project removes the dashboard from its tabs, including any of its widgets starred on that+ project's homepage.</WarningCallout><ErrorAlert error={applyError} /><div class="max-h-72 space-y-2 overflow-y-auto">@@ -1349,9 +1375,11 @@{/each}</div><AlertDialog.Footer>- <Button variant="outline" onclick={() => (showApplyDialog = false)}>Cancel</Button>+ <Button variant="outline" onclick={() => (showApplyDialog = false)} disabled={applying}>+ Cancel+ </Button><Button onclick={saveApply} disabled={applying}>- {#if applying}Applying...{:else}<Check class="mr-1 h-4 w-4" /> Update Dashboard{/if}+ {#if applying}Applying...{:else}<Check class="mr-2 h-4 w-4" /> Update Dashboard{/if}</Button></AlertDialog.Footer></AlertDialog.Content>@@ -1380,14 +1408,16 @@class="h-64 w-full resize-y rounded-md border border-input bg-transparent p-3 font-mono text-xs shadow-xs focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"></textarea><Button variant="outline" size="sm" onclick={() => readFileInto((t) => (importText = t))}>- <Upload class="mr-1 h-4 w-4" />+ <Upload class="mr-2 h-4 w-4" />Load from file</Button></div><AlertDialog.Footer>- <Button variant="outline" onclick={() => (showImportDialog = false)}>Cancel</Button>+ <Button variant="outline" onclick={() => (showImportDialog = false)} disabled={importing}>+ Cancel+ </Button><Button variant="success" onclick={importDashboards} disabled={importing}>- {#if importing}Importing...{:else}<Plus class="mr-1 h-4 w-4" /> Import Dashboards{/if}+ {#if importing}Importing...{:else}<Plus class="mr-2 h-4 w-4" /> Import Dashboards{/if}</Button></AlertDialog.Footer></AlertDialog.Content>@@ -1414,7 +1444,7 @@{#if grafanaWarnings.length > 0}<WarningCallout title="Imported with warnings"><div class="max-h-48 space-y-1 overflow-y-auto">- {#each grafanaWarnings as warning}+ {#each grafanaWarnings as warning, __index (__index)}<div class="text-xs">{warning}</div>{/each}</div>@@ -1428,7 +1458,7 @@class="h-64 w-full resize-y rounded-md border border-input bg-transparent p-3 font-mono text-xs shadow-xs focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"></textarea><Button variant="outline" size="sm" onclick={() => readFileInto((t) => (grafanaText = t))}>- <Upload class="mr-1 h-4 w-4" />+ <Upload class="mr-2 h-4 w-4" />Load from file</Button></div>@@ -1436,12 +1466,18 @@<AlertDialog.Footer>{#if grafanaWarnings.length > 0}<Button onclick={() => (showGrafanaDialog = false)}>- <Check class="mr-1 h-4 w-4" /> Done+ <Check class="mr-2 h-4 w-4" /> Done</Button>{:else}- <Button variant="outline" onclick={() => (showGrafanaDialog = false)}>Cancel</Button>+ <Button+ variant="outline"+ onclick={() => (showGrafanaDialog = false)}+ disabled={grafanaImporting}+ >+ Cancel+ </Button><Button variant="success" onclick={importGrafana} disabled={grafanaImporting}>- {#if grafanaImporting}Importing...{:else}<Plus class="mr-1 h-4 w-4" /> Import Dashboard{/if}+ {#if grafanaImporting}Importing...{:else}<Plus class="mr-2 h-4 w-4" /> Import Dashboard{/if}</Button>{/if}</AlertDialog.Footer>@@ -1468,7 +1504,7 @@Cancel</Button><Button variant="destructive" onclick={removeFromProject} disabled={removing}>- <Trash2 class="mr-1 h-4 w-4" />+ <Trash2 class="mr-2 h-4 w-4" />{removing ? 'Removing...' : 'Remove Dashboard'}</Button></AlertDialog.Footer>@@ -1497,7 +1533,7 @@Cancel</Button><Button variant="destructive" onclick={deleteDashboard} disabled={deleting}>- <Trash2 class="mr-1 h-4 w-4" />+ <Trash2 class="mr-2 h-4 w-4" />{deleting ? 'Deleting...' : 'Delete Dashboard'}</Button></AlertDialog.Footer>@@ -1525,7 +1561,7 @@disabled={deletingWidgetLoading}>Cancel</Button><Button variant="destructive" onclick={confirmDeleteWidget} disabled={deletingWidgetLoading}>- <Trash2 class="mr-1 h-4 w-4" />+ <Trash2 class="mr-2 h-4 w-4" />{deletingWidgetLoading ? 'Deleting...' : 'Delete Widget'}</Button></AlertDialog.Footer>diff --git a/frontend/src/routes/device/+page.svelte b/frontend/src/routes/device/+page.svelteindex 49665a80..a96eaded 100644--- a/frontend/src/routes/device/+page.svelte+++ b/frontend/src/routes/device/+page.svelte@@ -1,11 +1,17 @@<script lang="ts">- import { goto } from '$app/navigation';import { page } from '$app/state';+ import { gotoHref } from '$lib/utils/navigation';import { onMount } from 'svelte';import { Button } from '$lib/components/ui/button';import { Input } from '$lib/components/ui/input';import { Label } from '$lib/components/ui/label';- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '$lib/components/ui/card';+ import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle+ } from '$lib/components/ui/card';import { Alert, AlertDescription, AlertTitle } from '$lib/components/ui/alert';import { WarningCallout } from '$lib/components/ui/warning-callout';import { ErrorAlert } from '$lib/components/ui/error-alert';@@ -43,7 +49,7 @@function loginRedirect() {const target = `/device${userCode ? `?user_code=${encodeURIComponent(userCode)}` : ''}`;- goto(`/login?returnTo=${encodeURIComponent(target)}`);+ gotoHref(`/login?returnTo=${encodeURIComponent(target)}`);}async function lookup(code: string) {@@ -186,7 +192,7 @@<p class="text-center text-muted-foreground"><strong>{info.clientName}</strong> is requesting access to your Traceway account.</p>- <div class="font-mono text-4xl font-semibold tracking-[0.3em] text-center py-4">+ <div class="py-4 text-center font-mono text-4xl font-semibold tracking-[0.3em]">{info.userCode}</div><p class="text-center text-sm text-muted-foreground">diff --git a/frontend/src/routes/endpoints/+page.svelte b/frontend/src/routes/endpoints/+page.svelteindex 68347ffa..07e371f6 100644--- a/frontend/src/routes/endpoints/+page.svelte+++ b/frontend/src/routes/endpoints/+page.svelte@@ -1,614 +1,622 @@<script lang="ts">- import { onMount, onDestroy } from 'svelte';- import { api } from '$lib/api';- import { formatDuration, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';- import { getTimezone } from '$lib/state/timezone.svelte';- import * as Table from "$lib/components/ui/table";- import * as Card from "$lib/components/ui/card";- import { Button } from "$lib/components/ui/button";- import { LoadingCircle } from "$lib/components/ui/loading-circle";- import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js";- import { ChevronDown, Check } from 'lucide-svelte';- import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";- import { ImpactBadge } from "$lib/components/ui/impact-badge";- import { Badge } from "$lib/components/ui/badge";- import { TableEmptyState } from "$lib/components/ui/table-empty-state";- import { PaginationFooter } from "$lib/components/ui/pagination-footer";- import { TimeRangePicker } from "$lib/components/ui/time-range-picker";- import { SearchBar } from "$lib/components/ui/search-bar";- import { RootFilter } from "$lib/components/ui/root-filter";- import { NonRootChip } from "$lib/components/ui/non-root-chip";- import EndpointName from "$lib/components/endpoint-name.svelte";- import { browser } from '$app/environment';- import { CalendarDate } from "@internationalized/date";- import { projectsState } from '$lib/state/projects.svelte';- import { isHealthcheckEndpoint } from '$lib/utils/healthcheck';- import { createRowClickHandler } from '$lib/utils/navigation';- import { resolve } from '$app/paths';- import PageHeader from '$lib/components/issues/page-header.svelte';- import D3StackedAreaChart from '$lib/components/dashboard/d3-stacked-area-chart.svelte';- import D3HorizontalBarChart from '$lib/components/dashboard/d3-horizontal-bar-chart.svelte';- import {- presetMinutes,- getTimeRangeFromPreset,- dateToCalendarDate,- dateToTimeString,- parseTimeRangeFromUrl,- getResolvedTimeRange,- updateUrl- } from '$lib/utils/url-params';- import {- getSortState,- setSortState,- handleSortClick,- type SortDirection- } from '$lib/utils/sort-storage';+ import { getErrorMessage } from '$lib/utils/errors';+ import { onMount, onDestroy } from 'svelte';+ import { api } from '$lib/api';+ import { formatDuration, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import * as Table from '$lib/components/ui/table';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';import { ChartLine } from '@lucide/svelte';-- const timezone = $derived(getTimezone());- const initialTimezone = getTimezone();- const dropHealthyHealthchecks = $derived(projectsState.currentProject?.dropHealthyHealthchecks ?? false);- const healthcheckPaths = $derived(projectsState.currentProject?.healthcheckPaths ?? []);-- type EndpointStats = {- endpoint: string;- count: number;- p50Duration: number;- p95Duration: number;- p99Duration: number;- avgDuration: number;- lastSeen: string;- impact: number;- impactReason: string;- isStream?: boolean;- hasRoot: boolean;- hasNonRoot: boolean;- };-- type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'p99_duration' | 'last_seen' | 'impact';-- type ChartDataPoint = {- timestamp: Date;- endpoint: string;- value: number;- };-- type ChartResponse = {- endpoints: string[];- series: { timestamp: string; endpoint: string; value: number }[];- };-- // Metric options for the chart- const metricOptions = [- { value: 'total_time', label: 'Total time' },- { value: 'p50', label: 'Average response time' },- { value: 'p95', label: 'Slow response time' },- { value: 'p99', label: 'Awful response time' }- ];-- let endpoints = $state<EndpointStats[]>([]);- let loading = $state(true);- let error = $state('');-- // Chart state- let chartEndpoints = $state<string[]>([]);- let chartSeries = $state<ChartDataPoint[]>([]);- let chartLoading = $state(true);- let selectedMetric = $state('total_time');-- // Pagination State- let page = $state(1);- let pageSize = $state(50);- let total = $state(0);- let totalPages = $state(0);-- // Parse URL params including search + rootFilter- function parseEndpointsUrlParams() {- if (!browser) return { preset: '24h', from: null, to: null, search: '', rootFilter: 'all' };- const params = new URLSearchParams(window.location.search);- const timeParams = parseTimeRangeFromUrl(timezone, '24h');- return {- ...timeParams,- search: params.get('search') || '',- rootFilter: params.get('rootFilter') || 'all'- };- }-- // Initialize from URL- const initialUrlParams = parseEndpointsUrlParams();- const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);-- // Search + rootFilter state- let searchQuery = $state(initialUrlParams.search);- let rootFilter = $state(initialUrlParams.rootFilter);-- // Date Range State- let selectedPreset = $state<string | null>(initialUrlParams.preset);- let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));- let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));- let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));- let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));-- // Update URL with current time range and search- function updateTimeRangeUrl(pushToHistory = true) {- const params: Record<string, string | null | undefined> = {};- if (selectedPreset) {- params.preset = selectedPreset;- } else {- params.from = getFromDateTimeUTC();- params.to = getToDateTimeUTC();- }- if (searchQuery.trim()) {- params.search = searchQuery.trim();- }- if (rootFilter && rootFilter !== 'all') {- params.rootFilter = rootFilter;- }- updateUrl(params, { pushToHistory });- }-- // Handle browser back/forward navigation- function handlePopState() {- const urlParams = parseEndpointsUrlParams();- const range = getResolvedTimeRange(urlParams, timezone);-- selectedPreset = urlParams.preset;- fromDate = dateToCalendarDate(range.from, timezone);- fromTime = dateToTimeString(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- toTime = dateToTimeString(range.to, timezone);- searchQuery = urlParams.search;- rootFilter = urlParams.rootFilter;-- page = 1;- loadData(false);- }-- // Sorting - persisted to localStorage- const SORT_STORAGE_KEY = 'endpoints';- const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'impact', direction: 'desc' });- let orderBy = $state<SortField>(initialSort.field as SortField);- let sortDirection = $state<SortDirection>(initialSort.direction);-- // Page size options- const pageSizeOptions = [- { value: "10", label: "10" },- { value: "20", label: "20" },- { value: "50", label: "50" },- { value: "100", label: "100" }- ];-- const pageSizeLabel = $derived(pageSizeOptions.find(o => o.value === pageSize.toString())?.label ?? pageSize.toString());-- // Combine date and time into UTC ISO datetime string- function getFromDateTimeUTC(): string {- const [hour, minute] = (fromTime || '00:00').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute }, timezone);- return toUTCISO(dt);- }-- function getToDateTimeUTC(): string {- const [hour, minute] = (toTime || '23:59').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: toDate.year, month: toDate.month, day: toDate.day, hour, minute }, timezone).endOf('minute');- return toUTCISO(dt);- }-- function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) {- fromDate = from.date;- fromTime = from.time;- toDate = to.date;- toTime = to.time;- selectedPreset = preset;- page = 1;- loadData(false);- }-- // Format count with k/m suffixes- function formatCount(count: number): string {- if (count >= 1_000_000) {- return `${(count / 1_000_000).toFixed(1)}m`;- } else if (count >= 1_000) {- return `${(count / 1_000).toFixed(1)}k`;- }- return count.toLocaleString();- }-- // Calculate interval based on time range- function calculateInterval(from: Date, to: Date): number {- const diffMs = to.getTime() - from.getTime();- const diffHours = diffMs / (1000 * 60 * 60);-- if (diffHours <= 1) return 1; // 1 minute- if (diffHours <= 6) return 5; // 5 minutes- if (diffHours <= 24 * 7) return 60; // 1 hour- return 240; // 4 hours- }-- async function loadChartData() {- chartLoading = true;-- try {- const fromStr = getFromDateTimeUTC();- const toStr = getToDateTimeUTC();- const interval = calculateInterval(new Date(fromStr), new Date(toStr));-- const response = await api.post('/endpoints/chart', {- fromDate: fromStr,- toDate: toStr,- metricType: selectedMetric,- intervalMinutes: interval- }, { projectId: projectsState.currentProjectId ?? undefined }) as ChartResponse;-- chartEndpoints = response.endpoints || [];- chartSeries = (response.series || []).map((s: { timestamp: string; endpoint: string; value: number }) => ({- timestamp: new Date(s.timestamp),- endpoint: s.endpoint,- value: s.value- }));- } catch (e: any) {- console.error('Failed to load chart data:', e);- chartEndpoints = [];- chartSeries = [];- } finally {- chartLoading = false;- }- }-- async function loadData(pushToHistory = true) {- loading = true;- error = '';-- if (selectedPreset) {- const range = getTimeRangeFromPreset(selectedPreset, timezone);- fromDate = dateToCalendarDate(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- fromTime = dateToTimeString(range.from, timezone);- toTime = dateToTimeString(range.to, timezone);- }-- // Update URL- updateTimeRangeUrl(pushToHistory);-- try {- const requestBody = {- fromDate: getFromDateTimeUTC(),- toDate: getToDateTimeUTC(),- orderBy: orderBy,- sortDirection: sortDirection,- pagination: {- page: page,- pageSize: pageSize- },- search: searchQuery.trim(),- rootFilter: rootFilter === 'all' ? '' : rootFilter- };-- const response = await api.post('/endpoints/grouped', requestBody, { projectId: projectsState.currentProjectId ?? undefined });-- endpoints = response.data || [];- total = response.pagination.total;- totalPages = response.pagination.totalPages;- } catch (e: any) {- console.error(e);- error = e.message || 'Failed to load data';- } finally {- loading = false;- }-- // Also load chart data- loadChartData();- }-- function handlePageChange(newPage: number) {- if (newPage >= 1 && newPage <= totalPages) {- page = newPage;- loadData(false); // Don't push to history for pagination- }- }-- function handlePageSizeChange(newPageSize: number) {- pageSize = newPageSize;- page = 1;- loadData(false); // Don't push to history for pagination- }-- function handleSort(field: SortField) {- const newSort = handleSortClick(field, orderBy, sortDirection);- orderBy = newSort.field as SortField;- sortDirection = newSort.direction;- setSortState(SORT_STORAGE_KEY, newSort);- page = 1;- loadData(false);- }-- function handleMetricChange(value: string) {- selectedMetric = value;- loadChartData();- }-- function handleSearch() {- page = 1;- loadData(true);- }-- function handleChartRangeSelect(from: Date, to: Date) {- selectedPreset = null;- fromDate = new CalendarDate(from.getFullYear(), from.getMonth() + 1, from.getDate());- fromTime = `${String(from.getHours()).padStart(2, '0')}:${String(from.getMinutes()).padStart(2, '0')}`;- toDate = new CalendarDate(to.getFullYear(), to.getMonth() + 1, to.getDate());- toTime = `${String(to.getHours()).padStart(2, '0')}:${String(to.getMinutes()).padStart(2, '0')}`;- page = 1;- loadData(true);- }-- const selectedMetricLabel = $derived(metricOptions.find(o => o.value === selectedMetric)?.label ?? 'Total time');-- // Format total time (input is milliseconds, not nanoseconds)- function formatTotalTime(ms: number): string {- if (ms >= 3600000) { // >= 1 hour- return `${(ms / 3600000).toFixed(1)}h`;- } else if (ms >= 60000) { // >= 1 minute- return `${(ms / 60000).toFixed(1)}m`;- } else if (ms >= 1000) { // >= 1 second- return `${(ms / 1000).toFixed(1)}s`;- } else if (ms < 1) {- return `${(ms * 1000).toFixed(0)}µs`;- }- return `${Math.round(ms)}ms`;- }-- // Check if we should use bar chart (for percentile metrics)- const useBarChart = $derived(selectedMetric !== 'total_time');-- // Get top 8 endpoints for bar chart based on selected metric- // Sort by the selected metric to show the worst (slowest) endpoints first- const barChartData = $derived.by(() => {- if (!useBarChart || endpoints.length === 0) return [];-- const metricKey = selectedMetric === 'p50' ? 'p50Duration'- : selectedMetric === 'p95' ? 'p95Duration'- : 'p99Duration';-- return [...endpoints]- .sort((a, b) => b[metricKey] - a[metricKey])- .slice(0, 8)- .map(ep => ({- endpoint: ep.endpoint,- value: ep[metricKey]- }));- });--- onMount(() => {- // Add popstate listener for back/forward navigation- window.addEventListener('popstate', handlePopState);-- // Initial load with replaceState (don't push to history)- loadData(false);- });-- onDestroy(() => {- if (typeof window !== 'undefined') {- window.removeEventListener('popstate', handlePopState);- }- });+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import { ImpactBadge } from '$lib/components/ui/impact-badge';+ import { Badge } from '$lib/components/ui/badge';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { TimeRangePicker } from '$lib/components/ui/time-range-picker';+ import { SearchBar } from '$lib/components/ui/search-bar';+ import { RootFilter } from '$lib/components/ui/root-filter';+ import { NonRootChip } from '$lib/components/ui/non-root-chip';+ import EndpointName from '$lib/components/endpoint-name.svelte';+ import { browser } from '$app/environment';+ import { CalendarDate } from '@internationalized/date';+ import { projectsState } from '$lib/state/projects.svelte';+ import { isHealthcheckEndpoint } from '$lib/utils/healthcheck';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { resolve } from '$app/paths';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import ChartCard from '$lib/components/traceway/chart-card.svelte';+ import ToolbarSelect from '$lib/components/traceway/toolbar-select.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import D3StackedAreaChart from '$lib/components/dashboard/d3-stacked-area-chart.svelte';+ import D3HorizontalBarChart from '$lib/components/dashboard/d3-horizontal-bar-chart.svelte';+ import {+ getTimeRangeFromPreset,+ dateToCalendarDate,+ dateToTimeString,+ parseTimeRangeFromUrl,+ getResolvedTimeRange,+ updateUrl+ } from '$lib/utils/url-params';+ import {+ getSortState,+ setSortState,+ handleSortClick,+ type SortDirection+ } from '$lib/utils/sort-storage';++ const timezone = $derived(getTimezone());+ const initialTimezone = getTimezone();+ const dropHealthyHealthchecks = $derived(+ projectsState.currentProject?.dropHealthyHealthchecks ?? false+ );+ const healthcheckPaths = $derived(projectsState.currentProject?.healthcheckPaths ?? []);++ type EndpointStats = {+ endpoint: string;+ count: number;+ p50Duration: number;+ p95Duration: number;+ p99Duration: number;+ avgDuration: number;+ lastSeen: string;+ impact: number;+ impactReason: string;+ isStream?: boolean;+ hasRoot: boolean;+ hasNonRoot: boolean;+ };++ type SortField =+ | 'count'+ | 'p50_duration'+ | 'p95_duration'+ | 'p99_duration'+ | 'last_seen'+ | 'impact';++ type ChartDataPoint = {+ timestamp: Date;+ endpoint: string;+ value: number;+ };++ type ChartResponse = {+ endpoints: string[];+ series: { timestamp: string; endpoint: string; value: number }[];+ };++ // Metric options for the chart+ const metricOptions = [+ { value: 'total_time', label: 'Total time' },+ { value: 'p50', label: 'Average response time' },+ { value: 'p95', label: 'Slow response time' },+ { value: 'p99', label: 'Awful response time' }+ ];++ let endpoints = $state<EndpointStats[]>([]);+ let loading = $state(true);+ let error = $state('');++ // Chart state+ let chartEndpoints = $state<string[]>([]);+ let chartSeries = $state<ChartDataPoint[]>([]);+ let chartLoading = $state(true);+ let selectedMetric = $state('total_time');++ // Pagination State+ let page = $state(1);+ let pageSize = $state(50);+ let total = $state(0);+ let totalPages = $state(0);++ // Parse URL params including search + rootFilter+ function parseEndpointsUrlParams() {+ if (!browser) return { preset: '24h', from: null, to: null, search: '', rootFilter: 'all' };+ const params = new URLSearchParams(window.location.search);+ const timeParams = parseTimeRangeFromUrl(timezone, '24h');+ return {+ ...timeParams,+ search: params.get('search') || '',+ rootFilter: params.get('rootFilter') || 'all'+ };+ }++ // Initialize from URL+ const initialUrlParams = parseEndpointsUrlParams();+ const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);++ // Search + rootFilter state+ let searchQuery = $state(initialUrlParams.search);+ let rootFilter = $state(initialUrlParams.rootFilter);++ // Date Range State+ let selectedPreset = $state<string | null>(initialUrlParams.preset);+ let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));+ let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));+ let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));+ let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));++ // Update URL with current time range and search+ function updateTimeRangeUrl(pushToHistory = true) {+ const params: Record<string, string | null | undefined> = {};+ if (selectedPreset) {+ params.preset = selectedPreset;+ } else {+ params.from = getFromDateTimeUTC();+ params.to = getToDateTimeUTC();+ }+ if (searchQuery.trim()) {+ params.search = searchQuery.trim();+ }+ if (rootFilter && rootFilter !== 'all') {+ params.rootFilter = rootFilter;+ }+ updateUrl(params, { pushToHistory });+ }++ // Handle browser back/forward navigation+ function handlePopState() {+ const urlParams = parseEndpointsUrlParams();+ const range = getResolvedTimeRange(urlParams, timezone);++ selectedPreset = urlParams.preset;+ fromDate = dateToCalendarDate(range.from, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ toTime = dateToTimeString(range.to, timezone);+ searchQuery = urlParams.search;+ rootFilter = urlParams.rootFilter;++ page = 1;+ loadData(false);+ }++ // Sorting - persisted to localStorage+ const SORT_STORAGE_KEY = 'endpoints';+ const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'impact', direction: 'desc' });+ let orderBy = $state<SortField>(initialSort.field as SortField);+ let sortDirection = $state<SortDirection>(initialSort.direction);++ // Combine date and time into UTC ISO datetime string+ function getFromDateTimeUTC(): string {+ const [hour, minute] = (fromTime || '00:00').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute },+ timezone+ );+ return toUTCISO(dt);+ }++ function getToDateTimeUTC(): string {+ const [hour, minute] = (toTime || '23:59').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: toDate.year, month: toDate.month, day: toDate.day, hour, minute },+ timezone+ ).endOf('minute');+ return toUTCISO(dt);+ }++ function handleTimeRangeChange(+ from: { date: CalendarDate; time: string },+ to: { date: CalendarDate; time: string },+ preset: string | null+ ) {+ fromDate = from.date;+ fromTime = from.time;+ toDate = to.date;+ toTime = to.time;+ selectedPreset = preset;+ page = 1;+ loadData(false);+ }++ // Format count with k/m suffixes+ function formatCount(count: number): string {+ if (count >= 1_000_000) {+ return `${(count / 1_000_000).toFixed(1)}m`;+ } else if (count >= 1_000) {+ return `${(count / 1_000).toFixed(1)}k`;+ }+ return count.toLocaleString();+ }++ // Calculate interval based on time range+ function calculateInterval(from: Date, to: Date): number {+ const diffMs = to.getTime() - from.getTime();+ const diffHours = diffMs / (1000 * 60 * 60);++ if (diffHours <= 1) return 1; // 1 minute+ if (diffHours <= 6) return 5; // 5 minutes+ if (diffHours <= 24 * 7) return 60; // 1 hour+ return 240; // 4 hours+ }++ async function loadChartData() {+ chartLoading = true;++ try {+ const fromStr = getFromDateTimeUTC();+ const toStr = getToDateTimeUTC();+ const interval = calculateInterval(new Date(fromStr), new Date(toStr));++ const response = (await api.post(+ '/endpoints/chart',+ {+ fromDate: fromStr,+ toDate: toStr,+ metricType: selectedMetric,+ intervalMinutes: interval+ },+ { projectId: projectsState.currentProjectId ?? undefined }+ )) as ChartResponse;++ chartEndpoints = response.endpoints || [];+ chartSeries = (response.series || []).map(+ (s: { timestamp: string; endpoint: string; value: number }) => ({+ timestamp: new Date(s.timestamp),+ endpoint: s.endpoint,+ value: s.value+ })+ );+ } catch (e) {+ console.error('Failed to load chart data:', e);+ chartEndpoints = [];+ chartSeries = [];+ } finally {+ chartLoading = false;+ }+ }++ async function loadData(pushToHistory = true) {+ loading = true;+ error = '';++ if (selectedPreset) {+ const range = getTimeRangeFromPreset(selectedPreset, timezone);+ fromDate = dateToCalendarDate(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toTime = dateToTimeString(range.to, timezone);+ }++ // Update URL+ updateTimeRangeUrl(pushToHistory);++ try {+ const requestBody = {+ fromDate: getFromDateTimeUTC(),+ toDate: getToDateTimeUTC(),+ orderBy: orderBy,+ sortDirection: sortDirection,+ pagination: {+ page: page,+ pageSize: pageSize+ },+ search: searchQuery.trim(),+ rootFilter: rootFilter === 'all' ? '' : rootFilter+ };++ const response = await api.post('/endpoints/grouped', requestBody, {+ projectId: projectsState.currentProjectId ?? undefined+ });++ endpoints = response.data || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e) {+ console.error(e);+ error = getErrorMessage(e) || 'Failed to load data';+ } finally {+ loading = false;+ }++ // Also load chart data+ loadChartData();+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData(false); // Don't push to history for pagination+ }+ }++ function handlePageSizeChange(newPageSize: number) {+ pageSize = newPageSize;+ page = 1;+ loadData(false); // Don't push to history for pagination+ }++ function handleSort(field: SortField) {+ const newSort = handleSortClick(field, orderBy, sortDirection);+ orderBy = newSort.field as SortField;+ sortDirection = newSort.direction;+ setSortState(SORT_STORAGE_KEY, newSort);+ page = 1;+ loadData(false);+ }++ function handleMetricChange(value: string) {+ selectedMetric = value;+ loadChartData();+ }++ function handleSearch() {+ page = 1;+ loadData(true);+ }++ function handleChartRangeSelect(from: Date, to: Date) {+ selectedPreset = null;+ fromDate = new CalendarDate(from.getFullYear(), from.getMonth() + 1, from.getDate());+ fromTime = `${String(from.getHours()).padStart(2, '0')}:${String(from.getMinutes()).padStart(2, '0')}`;+ toDate = new CalendarDate(to.getFullYear(), to.getMonth() + 1, to.getDate());+ toTime = `${String(to.getHours()).padStart(2, '0')}:${String(to.getMinutes()).padStart(2, '0')}`;+ page = 1;+ loadData(true);+ }++ // Format total time (input is milliseconds, not nanoseconds)+ function formatTotalTime(ms: number): string {+ if (ms >= 3600000) {+ // >= 1 hour+ return `${(ms / 3600000).toFixed(1)}h`;+ } else if (ms >= 60000) {+ // >= 1 minute+ return `${(ms / 60000).toFixed(1)}m`;+ } else if (ms >= 1000) {+ // >= 1 second+ return `${(ms / 1000).toFixed(1)}s`;+ } else if (ms < 1) {+ return `${(ms * 1000).toFixed(0)}µs`;+ }+ return `${Math.round(ms)}ms`;+ }++ // Check if we should use bar chart (for percentile metrics)+ const useBarChart = $derived(selectedMetric !== 'total_time');++ // Get top 8 endpoints for bar chart based on selected metric+ // Sort by the selected metric to show the worst (slowest) endpoints first+ const barChartData = $derived.by(() => {+ if (!useBarChart || endpoints.length === 0) return [];++ const metricKey =+ selectedMetric === 'p50'+ ? 'p50Duration'+ : selectedMetric === 'p95'+ ? 'p95Duration'+ : 'p99Duration';++ return [...endpoints]+ .sort((a, b) => b[metricKey] - a[metricKey])+ .slice(0, 8)+ .map((ep) => ({+ endpoint: ep.endpoint,+ value: ep[metricKey]+ }));+ });++ onMount(() => {+ // Add popstate listener for back/forward navigation+ window.addEventListener('popstate', handlePopState);++ // Initial load with replaceState (don't push to history)+ loadData(false);+ });++ onDestroy(() => {+ if (typeof window !== 'undefined') {+ window.removeEventListener('popstate', handlePopState);+ }+ });</script><div class="space-y-4">- <!-- Header with Title and Time Range Filter -->- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">-- <PageHeader title="Endpoints" />-- <div class="flex flex-col">- <TimeRangePicker- bind:fromDate- bind:toDate- bind:fromTime- bind:toTime- bind:preset={selectedPreset}- onApply={handleTimeRangeChange}- />- </div>- </div>-- <!-- Search -->- <SearchBar- placeholder="Search endpoints..."- bind:value={searchQuery}- onSearch={handleSearch}- disabled={loading}- >- {#snippet children()}- <RootFilter bind:value={rootFilter} />- {/snippet}- </SearchBar>-- <!-- Performance Chart -->- <Card.Root class="pt-2">- <Card.Header class="flex flex-row items-center justify-between space-y-0 border-b [.border-b]:pb-2 pl-3">- <Card.Title class="text-base font-medium flex items-center gap-2">- <ChartLine class="h-3.5 w-3.5 text-muted-foreground" />- <DropdownMenu.Root>- <DropdownMenu.Trigger class="flex items-center text-sm gap-0.5 font-[400] text-muted-foreground">- {selectedMetricLabel}- <ChevronDown class="h-3 w-3 text-muted-foreground" />- </DropdownMenu.Trigger>- <DropdownMenu.Content align="start" class="w-[200px]">- {#each metricOptions as option}- <DropdownMenu.Item- onclick={() => handleMetricChange(option.value)}- class="flex items-center justify-between cursor-pointer"- >- <span>{option.label}</span>- {#if option.value === selectedMetric}- <Check class="h-4 w-4" />- {/if}- </DropdownMenu.Item>- {/each}- </DropdownMenu.Content>- </DropdownMenu.Root>- </Card.Title>- </Card.Header>- <Card.Content>- {#if chartLoading && !useBarChart}- <div class="flex justify-center items-center h-[220px]">- <LoadingCircle size="xlg" />- </div>- {:else if useBarChart}- {#if loading}- <div class="flex justify-center items-center h-[220px]">- <LoadingCircle size="xlg" />- </div>- {:else}- <D3HorizontalBarChart- data={barChartData}- formatValue={formatDuration}- />- {/if}- {:else}- <D3StackedAreaChart- endpoints={chartEndpoints}- series={chartSeries}- formatValue={formatTotalTime}- onRangeSelect={handleChartRangeSelect}- />- {/if}- </Card.Content>- </Card.Root>-- <!-- Endpoints Table -->- <div class="rounded-md border overflow-hidden">- <Table.Root>- {#if loading}- <Table.Body>- <Table.Row>- <Table.Cell colspan={6} class="h-48">- <div class="flex justify-center items-center h-full">- <LoadingCircle size="xlg" />- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if error}- <Table.Body>- <Table.Row>- <Table.Cell colspan={6} class="h-24 text-center text-red-500">- {error}- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if endpoints.length === 0}- <Table.Body>- <TableEmptyState colspan={6} message="No endpoint data available for your search parameters" />- </Table.Body>- {:else}- <Table.Header>- <Table.Row>- <TracewayTableHeader- label="Endpoint"- tooltip="The API route or page being accessed"- class="max-w-[50%]"- />- <TracewayTableHeader- label="Calls"- tooltip="Total number of requests"- sortField="count"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Typical"- tooltip="Median response time (P50)"- sortField="p50_duration"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Slow"- tooltip="95th percentile - slowest 5% of requests"- sortField="p95_duration"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Awful"- tooltip="99th percentile - slowest 1% of requests"- sortField="p99_duration"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Impact"- tooltip="Impact score based on Apdex, error rates, P99 latency, and request volume"- sortField="impact"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- align="right"- class="w-[120px]"- />- </Table.Row>- </Table.Header>- <Table.Body>- {#each endpoints as endpoint}- <Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={createRowClickHandler(resolve(`/endpoints/${encodeURIComponent(endpoint.endpoint)}`), 'preset', 'from', 'to')}- >- <Table.Cell class="font-mono text-sm max-w-[50%] break-all whitespace-normal">- <span class="inline-flex items-center gap-2">- <span><EndpointName endpoint={endpoint.endpoint} /></span>- {#if endpoint.isStream}- <Badge variant="outline" class="font-sans text-xs" title="Streaming response (SSE / WebSocket / long-poll). Excluded from latency, Apdex, and impact scoring.">Stream</Badge>- {/if}- {#if dropHealthyHealthchecks && isHealthcheckEndpoint(endpoint.endpoint, healthcheckPaths)}- <Badge variant="outline" class="font-sans text-xs" title="Healthcheck endpoint. Only failed requests (status 400+) are stored, so counts and error rates reflect failures only. Configure in project settings.">Healthcheck</Badge>- {/if}- {#if endpoint.hasNonRoot}- <NonRootChip mixed={endpoint.hasRoot && endpoint.hasNonRoot} />- {/if}- </span>- </Table.Cell>- <Table.Cell class="tabular-nums">- {formatCount(endpoint.count)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums text-muted-foreground">- {endpoint.isStream ? '—' : formatDuration(endpoint.p50Duration)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums text-muted-foreground">- {endpoint.isStream ? '—' : formatDuration(endpoint.p95Duration)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums text-muted-foreground">- {endpoint.isStream ? '—' : formatDuration(endpoint.p99Duration)}- </Table.Cell>- <Table.Cell class="text-right">- <ImpactBadge score={endpoint.impact} reason={endpoint.impactReason} />- </Table.Cell>- </Table.Row>- {/each}- </Table.Body>- {/if}- </Table.Root>- </div>-- <!-- Pagination Footer -->- <PaginationFooter- currentPage={page}- {totalPages}- {pageSize}- totalItems={total}- onPageChange={handlePageChange}- onPageSizeChange={handlePageSizeChange}- {loading}- itemLabel="endpoint"- />+ <PageHeader title="Endpoints">+ {#snippet actions()}+ <TimeRangePicker+ bind:fromDate+ bind:toDate+ bind:fromTime+ bind:toTime+ bind:preset={selectedPreset}+ onApply={handleTimeRangeChange}+ />+ {/snippet}+ </PageHeader>++ <!-- Search -->+ <SearchBar+ placeholder="Search endpoints..."+ bind:value={searchQuery}+ onSearch={handleSearch}+ disabled={loading}+ >+ <RootFilter bind:value={rootFilter} />+ </SearchBar>++ <!-- Performance Chart -->+ <ChartCard+ title="Performance"+ loading={useBarChart ? loading : chartLoading}+ empty={useBarChart ? barChartData.length === 0 : chartEndpoints.length === 0}+ >+ {#snippet icon()}+ <ChartLine class="h-3.5 w-3.5 text-muted-foreground" />+ {/snippet}+ {#snippet controls()}+ <ToolbarSelect+ bind:value={selectedMetric}+ options={metricOptions}+ class="w-44"+ onChange={handleMetricChange}+ />+ {/snippet}+ {#if useBarChart}+ <D3HorizontalBarChart data={barChartData} formatValue={formatDuration} />+ {:else}+ <D3StackedAreaChart+ endpoints={chartEndpoints}+ series={chartSeries}+ formatValue={formatTotalTime}+ onRangeSelect={handleChartRangeSelect}+ />+ {/if}+ </ChartCard>++ <!-- Endpoints Table -->+ <TableContainer minWidth="860px">+ <Table.Root>+ {#if loading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={6} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if error}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={6} class="h-24 text-center text-red-500">+ {error}+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if endpoints.length === 0}+ <Table.Body>+ <TableEmptyState+ colspan={6}+ message="No endpoint data available for your search parameters"+ />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader+ label="Endpoint"+ tooltip="The API route or page being accessed"+ class="max-w-[50%]"+ />+ <TracewayTableHeader+ label="Calls"+ tooltip="Total number of requests"+ sortField="count"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Typical"+ tooltip="Median response time (P50)"+ sortField="p50_duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Slow"+ tooltip="95th percentile - slowest 5% of requests"+ sortField="p95_duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Awful"+ tooltip="99th percentile - slowest 1% of requests"+ sortField="p99_duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Impact"+ tooltip="Impact score based on Apdex, error rates, P99 latency, and request volume"+ sortField="impact"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ align="right"+ class="w-[120px]"+ />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each endpoints as endpoint, __index (__index)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ resolve(`/endpoints/${encodeURIComponent(endpoint.endpoint)}`),+ 'preset',+ 'from',+ 'to'+ )}+ >+ <Table.Cell class="font-mono text-sm">+ <div class="flex max-w-[560px] items-center gap-2">+ <span class="min-w-0 truncate" title={endpoint.endpoint}+ ><EndpointName endpoint={endpoint.endpoint} /></span+ >+ {#if endpoint.isStream}+ <Badge+ variant="outline"+ class="shrink-0 font-sans text-xs"+ title="Streaming response (SSE / WebSocket / long-poll). Excluded from latency, Apdex, and impact scoring."+ >Stream</Badge+ >+ {/if}+ {#if dropHealthyHealthchecks && isHealthcheckEndpoint(endpoint.endpoint, healthcheckPaths)}+ <Badge+ variant="outline"+ class="shrink-0 font-sans text-xs"+ title="Healthcheck endpoint. Only failed requests (status 400+) are stored, so counts and error rates reflect failures only. Configure in project settings."+ >Healthcheck</Badge+ >+ {/if}+ {#if endpoint.hasNonRoot}+ <NonRootChip mixed={endpoint.hasRoot && endpoint.hasNonRoot} />+ {/if}+ </div>+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ {formatCount(endpoint.count)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground tabular-nums">+ {endpoint.isStream ? '—' : formatDuration(endpoint.p50Duration)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground tabular-nums">+ {endpoint.isStream ? '—' : formatDuration(endpoint.p95Duration)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground tabular-nums">+ {endpoint.isStream ? '—' : formatDuration(endpoint.p99Duration)}+ </Table.Cell>+ <Table.Cell class="text-right">+ <ImpactBadge score={endpoint.impact} reason={endpoint.impactReason} />+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </TableContainer>++ <!-- Pagination Footer -->+ <PaginationFooter+ currentPage={page}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={handlePageChange}+ onPageSizeChange={handlePageSizeChange}+ {loading}+ itemLabel="endpoint"+ /></div>diff --git a/frontend/src/routes/endpoints/[endpoint]/+page.svelte b/frontend/src/routes/endpoints/[endpoint]/+page.svelteindex 3ab33b93..6e769131 100644--- a/frontend/src/routes/endpoints/[endpoint]/+page.svelte+++ b/frontend/src/routes/endpoints/[endpoint]/+page.svelte@@ -1,5 +1,7 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';import { onMount, onDestroy } from 'svelte';+ import { SvelteURLSearchParams } from 'svelte/reactivity';import { api } from '$lib/api';import {formatDuration,@@ -15,7 +17,7 @@import { Button } from '$lib/components/ui/button';import { LoadingCircle } from '$lib/components/ui/loading-circle';import { TimeRangePicker } from '$lib/components/ui/time-range-picker';- import { ArrowLeft, Check, Snail } from '@lucide/svelte';+ import { Check, Snail } from '@lucide/svelte';import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';import { TableEmptyState } from '$lib/components/ui/table-empty-state';import { CalendarDate } from '@internationalized/date';@@ -24,15 +26,19 @@import { isHealthcheckEndpoint } from '$lib/utils/healthcheck';import AttributesDisplay from '$lib/components/attributes-display.svelte';import { createRowClickHandler } from '$lib/utils/navigation';- import { goto } from '$app/navigation';+ import { gotoHref } from '$lib/utils/navigation';import PaginationFooter from '$lib/components/ui/pagination-footer/pagination-footer.svelte';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import StatRow from '$lib/components/traceway/stat-row.svelte';+ import StatTile from '$lib/components/traceway/stat-tile.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import FormField from '$lib/components/traceway/form-field.svelte';+ import { ErrorAlert } from '$lib/components/ui/error-alert';import { Input } from '$lib/components/ui/input';import * as AlertDialog from '$lib/components/ui/alert-dialog';import * as Tooltip from '$lib/components/ui/tooltip';import { Badge } from '$lib/components/ui/badge';import { toast } from 'svelte-sonner';- import { resolve } from '$app/paths';import {presetMinutes,getTimeRangeFromPreset,@@ -145,6 +151,7 @@let reason = $state('');let showSlowDialog = $state(false);let slowLoading = $state(false);+ let slowError = $state('');let offsetInput = $state('');let reasonInput = $state('');@@ -168,18 +175,18 @@}function goBackToEndpoints(event: MouseEvent) {- const params = new URLSearchParams();+ const params = new SvelteURLSearchParams();if (selectedPreset) {params.set('preset', selectedPreset);} else {params.set('from', getFromDateTimeUTC());params.set('to', getToDateTimeUTC());}- const href = resolve('/endpoints') + '?' + params.toString();+ const href = '/endpoints?' + params.toString();if (event.ctrlKey || event.metaKey) {window.open(href, '_blank');} else {- goto(href);+ gotoHref(href);}}@@ -245,13 +252,13 @@stats = response.stats || null;total = response.pagination.total;totalPages = response.pagination.totalPages;- } catch (e: any) {+ } catch (e) {console.error(e);- errorStatus = e.status || 0;- if (e.status === 404) {+ errorStatus = getErrorStatus(e) || 0;+ if (getErrorStatus(e) === 404) {notFound = true;} else {- error = e.message || 'Failed to load data';+ error = getErrorMessage(e) || 'Failed to load data';}} finally {loading = false;@@ -296,19 +303,24 @@async function saveSlowEndpoint() {slowLoading = true;+ slowError = '';try {const value = parseInt(offsetInput) || 0;await api.post('/endpoints/slow',- { endpoint: decodeURIComponent(data.endpoint), offsetMs: Math.max(0, value), reason: reasonInput },+ {+ endpoint: decodeURIComponent(data.endpoint),+ offsetMs: Math.max(0, value),+ reason: reasonInput+ },{ projectId: projectsState.currentProjectId ?? undefined });offsetMs = Math.max(0, value);reason = reasonInput;showSlowDialog = false;toast.success('Successfully updated the Expected Performance', { position: 'top-center' });- } catch (e: any) {- toast.error(e.message || 'Failed to save');+ } catch (e) {+ slowError = getErrorMessage(e) || 'Failed to save';} finally {slowLoading = false;}@@ -360,40 +372,45 @@onRetry={() => loadData(false)}/>{:else}- <!-- Header with Title and Time Range Filter -->- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">- <PageHeader- title={decodeURIComponent(data.endpoint)}- subtitle="Trace instances for this endpoint"- onBack={goBackToEndpoints}- >- {#snippet trailing()}- {#if stats?.isStream}- <Tooltip.Root>- <Tooltip.Trigger>- <Badge variant="outline" class="font-sans">Stream</Badge>- </Tooltip.Trigger>- <Tooltip.Content side="bottom" class="max-w-xs">- Streaming endpoint. Latency metrics aren't tracked.- </Tooltip.Content>- </Tooltip.Root>- {/if}- {#if (projectsState.currentProject?.dropHealthyHealthchecks ?? false) && isHealthcheckEndpoint(decodeURIComponent(data.endpoint), projectsState.currentProject?.healthcheckPaths)}- <Tooltip.Root>- <Tooltip.Trigger>- <Badge variant="outline" class="font-sans">Healthcheck</Badge>- </Tooltip.Trigger>- <Tooltip.Content side="bottom" class="max-w-xs">- Only failed requests (status 400+) are stored for this endpoint, so counts and error rates reflect failures only. Configure in project settings.- </Tooltip.Content>- </Tooltip.Root>- {/if}- {/snippet}- </PageHeader>-- <div class="flex items-start gap-2">+ <PageHeader+ title={decodeURIComponent(data.endpoint)}+ subtitle="Trace instances for this endpoint"+ onBack={goBackToEndpoints}+ >+ {#snippet trailing()}+ {#if stats?.isStream}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <Badge variant="outline" class="font-sans">Stream</Badge>+ </Tooltip.Trigger>+ <Tooltip.Content side="bottom" class="max-w-xs">+ Streaming endpoint. Latency metrics aren't tracked.+ </Tooltip.Content>+ </Tooltip.Root>+ {/if}+ {#if (projectsState.currentProject?.dropHealthyHealthchecks ?? false) && isHealthcheckEndpoint(decodeURIComponent(data.endpoint), projectsState.currentProject?.healthcheckPaths)}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <Badge variant="outline" class="font-sans">Healthcheck</Badge>+ </Tooltip.Trigger>+ <Tooltip.Content side="bottom" class="max-w-xs">+ Only failed requests (status 400+) are stored for this endpoint, so counts and error+ rates reflect failures only. Configure in project settings.+ </Tooltip.Content>+ </Tooltip.Root>+ {/if}+ {/snippet}+ {#snippet actions()}{#if !stats?.isStream}- <Button variant="outline" onclick={() => { offsetInput = offsetMs > 0 ? String(offsetMs) : ''; reasonInput = reason; showSlowDialog = true; }}>+ <Button+ variant="outline"+ onclick={() => {+ offsetInput = offsetMs > 0 ? String(offsetMs) : '';+ reasonInput = reason;+ slowError = '';+ showSlowDialog = true;+ }}+ ><Snail class="h-4 w-4" />{offsetMs > 0 ? `+${offsetMs}ms offset` : 'Expected Performance'}</Button>@@ -406,11 +423,13 @@bind:preset={selectedPreset}onApply={handleTimeRangeChange}/>- </div>- </div>+ {/snippet}+ </PageHeader>{#if offsetMs > 0 && !stats?.isStream}- <div class="flex items-center gap-2 rounded-md border border-border bg-muted/50 px-4 py-3 text-sm">+ <div+ class="flex items-center gap-2 rounded-md border border-border bg-muted/50 px-4 py-3 text-sm"+ ><Snail class="h-4 w-4 shrink-0 text-muted-foreground" /><span><span class="font-medium">Expected Performance:</span> +{offsetMs}ms offset applied.@@ -424,53 +443,21 @@<!-- Endpoint Stats -->{#if stats}{#if stats.isStream}- <div class="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-3">- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{stats.count.toLocaleString()}</p>- <p class="text-xs text-muted-foreground">Connections</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{stats.errorRate.toFixed(2)} %</p>- <p class="text-xs text-muted-foreground">Average error rate</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{stats.throughput.toFixed(0)} rpm</p>- <p class="text-xs text-muted-foreground">Average throughput</p>- </div>- </div>+ <StatRow columns={3}>+ <StatTile label="Connections" value={stats.count.toLocaleString()} />+ <StatTile label="Average error rate" value={`${stats.errorRate.toFixed(2)} %`} />+ <StatTile label="Average throughput" value={`${stats.throughput.toFixed(0)} rpm`} />+ </StatRow>{:else}- <div class="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-7">- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.avgDuration)}</p>- <p class="text-xs text-muted-foreground">Average response time</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">- {formatDurationMs(stats.medianDuration)}- </p>- <p class="text-xs text-muted-foreground">Median response time</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p95Duration)}</p>- <p class="text-xs text-muted-foreground">95th percentile response time</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p99Duration)}</p>- <p class="text-xs text-muted-foreground">99th percentile response time</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{stats.apdex.toFixed(2)}</p>- <p class="text-xs text-muted-foreground">Apdex score</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{stats.errorRate.toFixed(2)} %</p>- <p class="text-xs text-muted-foreground">Average error rate</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{stats.throughput.toFixed(0)} rpm</p>- <p class="text-xs text-muted-foreground">Average throughput</p>- </div>- </div>+ <StatRow columns={4}>+ <StatTile label="Average response time" value={formatDurationMs(stats.avgDuration)} />+ <StatTile label="Median response time" value={formatDurationMs(stats.medianDuration)} />+ <StatTile label="95th percentile" value={formatDurationMs(stats.p95Duration)} />+ <StatTile label="99th percentile" value={formatDurationMs(stats.p99Duration)} />+ <StatTile label="Apdex score" value={stats.apdex.toFixed(2)} />+ <StatTile label="Average error rate" value={`${stats.errorRate.toFixed(2)} %`} />+ <StatTile label="Average throughput" value={`${stats.throughput.toFixed(0)} rpm`} />+ </StatRow>{/if}{:else if loading}<div class="flex items-center justify-center py-8">@@ -479,7 +466,7 @@{/if}<!-- Traces Table -->- <div class="overflow-hidden rounded-md border">+ <TableContainer minWidth="960px"><Table.Root>{#if loading || transactions.length > 0}<Table.Header>@@ -527,17 +514,17 @@{#if loading}<Table.Row><Table.Cell colspan={8} class="h-48">- <div class="flex items-center justify-center">- <LoadingCircle size="lg" />+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" /></div></Table.Cell></Table.Row>{:else if transactions.length === 0}<TableEmptyState colspan={8} message="No traces found in this time range." />{:else}- {#each transactions as transaction}+ {#each transactions as transaction, __index (__index)}<Table.Row- class="cursor-pointer hover:bg-muted/50"+ class="cursor-pointer"onclick={createRowClickHandler(`/endpoints/${encodeURIComponent(decodeURIComponent(data.endpoint))}/${transaction.id}?t=${encodeURIComponent(transaction.recordedAt)}`,'preset',@@ -574,7 +561,7 @@{/if}</Table.Body></Table.Root>- </div>+ </TableContainer><!-- Pagination Footer --><PaginationFooter@@ -585,7 +572,7 @@onPageChange={handlePageChange}onPageSizeChange={handlePageSizeChange}{loading}- itemLabel="endpoint"+ itemLabel="trace"/>{/if}</div>@@ -595,29 +582,43 @@<AlertDialog.Header><AlertDialog.Title>Expected Performance</AlertDialog.Title><AlertDialog.Description>- Set a time offset for endpoints that are expected to be slow (e.g., report generation, data exports).- The offset adjusts impact score thresholds so the endpoint isn't flagged as unhealthy.+ Set a time offset for endpoints that are expected to be slow (e.g., report generation, data+ exports). The offset adjusts impact score thresholds so the endpoint isn't flagged as+ unhealthy.</AlertDialog.Description></AlertDialog.Header>- <div class="space-y-4 py-4">- <div>- <label for="offset-input" class="text-sm font-medium">Offset (ms)</label>- <Input id="offset-input" type="number" bind:value={offsetInput} placeholder="e.g., 2000" min="0" class="mt-1.5" />- <p class="text-xs text-muted-foreground mt-1.5">- How many extra milliseconds above the default 750ms threshold are acceptable for this endpoint.- Set to 0 to remove the offset.- </p>- </div>- <div>- <label for="reason-input" class="text-sm font-medium">Reason</label>- <Input id="reason-input" type="text" bind:value={reasonInput} placeholder="e.g., generates large PDF reports" class="mt-1.5" />- <p class="text-xs text-muted-foreground mt-1.5">- Explain why this endpoint is expected to be slow.- </p>- </div>+ <div class="space-y-4">+ <FormField+ label="Offset (ms)"+ for="offset-input"+ hint="How many extra milliseconds above the default 750ms threshold are acceptable for this endpoint. Set to 0 to remove the offset."+ >+ <Input+ id="offset-input"+ type="number"+ bind:value={offsetInput}+ placeholder="e.g., 2000"+ min="0"+ />+ </FormField>+ <FormField+ label="Reason"+ for="reason-input"+ hint="Explain why this endpoint is expected to be slow."+ >+ <Input+ id="reason-input"+ type="text"+ bind:value={reasonInput}+ placeholder="e.g., generates large PDF reports"+ />+ </FormField>+ <ErrorAlert error={slowError} /></div><AlertDialog.Footer>- <Button variant="outline" onclick={() => showSlowDialog = false} disabled={slowLoading}>Cancel</Button>+ <Button variant="outline" onclick={() => (showSlowDialog = false)} disabled={slowLoading}+ >Cancel</Button+ ><Button onclick={saveSlowEndpoint} disabled={slowLoading}><Check class="mr-2 h-4 w-4" />{slowLoading ? 'Updating...' : 'Update Expected Performance'}diff --git a/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelte b/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelteindex e076e82d..3c3c7ec0 100644--- a/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelte+++ b/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelte@@ -10,13 +10,15 @@import { LoadingCircle } from '$lib/components/ui/loading-circle';import { ErrorDisplay } from '$lib/components/ui/error-display';import { projectsState } from '$lib/state/projects.svelte';- import { ArrowLeft, ArrowRight, TriangleAlert, ClipboardList } from 'lucide-svelte';+ import { ArrowRight, TriangleAlert, ClipboardList } from '@lucide/svelte';import { LabelValue } from '$lib/components/ui/label-value';import { AttributesGrid } from '$lib/components/ui/attributes-grid/index.js';import SpanWaterfall from '$lib/components/spans/span-waterfall.svelte';import SpanEmptyState from '$lib/components/spans/span-empty-state.svelte';import type { TraceDetailResponse } from '$lib/types/spans';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';import { createSmartBackHandler } from '$lib/utils/back-navigation';import { resolve } from '$app/paths';import DistributedTraceCard from '$lib/components/distributed-trace/distributed-trace-card.svelte';@@ -180,7 +182,7 @@<Buttonvariant="outline"size="sm"- onclick={() => goto(`/issues/${response!.exception!.exceptionHash}`)}+ onclick={() => goto(resolve(`/issues/${response!.exception!.exceptionHash}`))}>View Full Exception<ArrowRight class="ml-2 h-4 w-4" />@@ -203,44 +205,49 @@</Card.Description></Card.Header><Card.Content class="px-0 pb-0">- <Table.Root>- <Table.Header>- <Table.Row>- <Table.Head class="pl-6">Message</Table.Head>- <Table.Head class="w-[180px]">Recorded At</Table.Head>- <Table.Head class="w-[100px] pr-6">Attributes</Table.Head>- </Table.Row>- </Table.Header>- <Table.Body>- {#each response.messages as message}- <Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={() => goto(`/issues/${message.exceptionHash}/${message.id}`)}- >- <Table.Cell class="pl-6">- <div class="max-w-md truncate font-mono text-sm">- {message.stackTrace.split('\n')[0]}- </div>- </Table.Cell>- <Table.Cell class="font-mono text-sm text-muted-foreground">- {formatDateTime(message.recordedAt, { timezone })}- </Table.Cell>- <Table.Cell class="pr-6">- {#if message.attributes && Object.keys(message.attributes).length > 0}- <span class="text-xs text-muted-foreground">- {Object.keys(message.attributes).length} key{Object.keys(message.attributes)- .length === 1- ? ''- : 's'}- </span>- {:else}- <span class="text-xs text-muted-foreground">-</span>- {/if}- </Table.Cell>+ <TableContainer class="rounded-none border-0">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <Table.Head class="pl-6">Message</Table.Head>+ <Table.Head class="w-[180px]">Recorded At</Table.Head>+ <Table.Head class="w-[100px] pr-6">Attributes</Table.Head></Table.Row>- {/each}- </Table.Body>- </Table.Root>+ </Table.Header>+ <Table.Body>+ {#each response.messages as message, __index (__index)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ `/issues/${message.exceptionHash}/${message.id}`+ )}+ >+ <Table.Cell class="pl-6">+ <div class="max-w-md truncate font-mono text-sm">+ {message.stackTrace.split('\n')[0]}+ </div>+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {formatDateTime(message.recordedAt, { timezone })}+ </Table.Cell>+ <Table.Cell class="pr-6">+ {#if message.attributes && Object.keys(message.attributes).length > 0}+ <span class="text-xs text-muted-foreground">+ {Object.keys(message.attributes).length} key{Object.keys(+ message.attributes+ ).length === 1+ ? ''+ : 's'}+ </span>+ {:else}+ <span class="text-xs text-muted-foreground">-</span>+ {/if}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer></Card.Content></Card.Root>{/if}@@ -274,10 +281,6 @@traceId={traceIdUuidToHex(response.endpoint.id)}distributedTraceId={response.endpoint.distributedTraceId ?? null}spans={response.spans ?? []}- rootSpan={{- id: response.endpoint.spanId ?? response.endpoint.id,- name: response.endpoint.endpoint- }}traceRecordedAt={response.endpoint.recordedAt}/>diff --git a/frontend/src/routes/finish-setup/+page.svelte b/frontend/src/routes/finish-setup/+page.svelteindex 1abeef5d..7ea0c9bf 100644--- a/frontend/src/routes/finish-setup/+page.svelte+++ b/frontend/src/routes/finish-setup/+page.svelte@@ -1,129 +1,152 @@<script lang="ts">- import { goto } from '$app/navigation';- import { onMount } from 'svelte';- import { Button } from "$lib/components/ui/button";- import { Input } from "$lib/components/ui/input";- import { Label } from "$lib/components/ui/label";- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "$lib/components/ui/card";- import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";- import { ErrorAlert } from "$lib/components/ui/error-alert";- import * as Select from "$lib/components/ui/select";- import { CircleAlert, Check } from "@lucide/svelte";- import { authState } from '$lib/state/auth.svelte';- import { projectsState, type Framework } from '$lib/state/projects.svelte';- import { themeState } from '$lib/state/theme.svelte';- import FrameworkCombobox from '$lib/components/framework-combobox.svelte';- import { consumeSsoReturnTo, safeLocalPath } from '$lib/utils/navigation';+ import { resolve } from '$app/paths';+ import { goto } from '$app/navigation';+ import { gotoHref } from '$lib/utils/navigation';+ import { onMount } from 'svelte';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle+ } from '$lib/components/ui/card';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import * as Select from '$lib/components/ui/select';+ import { Check } from '@lucide/svelte';+ import { authState } from '$lib/state/auth.svelte';+ import { projectsState, type Framework } from '$lib/state/projects.svelte';+ import { themeState } from '$lib/state/theme.svelte';+ import FrameworkCombobox from '$lib/components/framework-combobox.svelte';+ import { consumeSsoReturnTo, safeLocalPath } from '$lib/utils/navigation';- const DEFAULT_FRAMEWORK: Framework = 'opentelemetry';+ const DEFAULT_FRAMEWORK: Framework = 'opentelemetry';- let organizationName = $state('');- let timezone = $state(Intl.DateTimeFormat().resolvedOptions().timeZone);- let projectName = $state('');- let framework = $state<Framework>(DEFAULT_FRAMEWORK);- let error = $state('');- let loading = $state(false);+ let organizationName = $state('');+ let timezone = $state(Intl.DateTimeFormat().resolvedOptions().timeZone);+ let projectName = $state('');+ let framework = $state<Framework>(DEFAULT_FRAMEWORK);+ let error = $state('');+ let loading = $state(false);- const timezones = Intl.supportedValuesOf('timeZone');+ const timezones = Intl.supportedValuesOf('timeZone');- onMount(() => {- if (!authState.token) {- goto('/login');- }- });+ onMount(() => {+ if (!authState.token) {+ goto(resolve('/login'));+ }+ });- async function handleSubmit() {- loading = true;- error = '';- try {- const response = await fetch('/api/auth/finish-setup', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'Authorization': `Bearer ${authState.token}`,- },- body: JSON.stringify({ organizationName, timezone, projectName, framework })- });+ async function handleSubmit() {+ loading = true;+ error = '';+ try {+ const response = await fetch('/api/auth/finish-setup', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${authState.token}`+ },+ body: JSON.stringify({ organizationName, timezone, projectName, framework })+ });- if (!response.ok) {- const data = await response.json().catch(() => ({}));- throw new Error(data.error || 'Setup failed');- }+ if (!response.ok) {+ const data = await response.json().catch(() => ({}));+ throw new Error(data.error || 'Setup failed');+ }- const data = await response.json();- authState.setToken(data.token);- authState.setOrganizations(data.organizations || []);- projectsState.setProjects(data.projects);- goto(safeLocalPath(consumeSsoReturnTo()));- } catch (e) {- error = e instanceof Error ? e.message : 'Setup failed';- } finally {- loading = false;- }- }+ const data = await response.json();+ authState.setToken(data.token);+ authState.setOrganizations(data.organizations || []);+ projectsState.setProjects(data.projects);+ gotoHref(safeLocalPath(consumeSsoReturnTo()));+ } catch (e) {+ error = e instanceof Error ? e.message : 'Setup failed';+ } finally {+ loading = false;+ }+ }</script><div class="flex min-h-screen w-full items-center justify-center px-4 py-8">- <Card class="w-[400px]">- <CardHeader>- <CardTitle class="text-2xl">- <div class="flex flex-row items-center justify-center gap-2">- {#if themeState.isDark}- <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />- {:else}- <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />- {/if}- </div>- </CardTitle>- <CardDescription class="text-center">- Finish setting up your account- </CardDescription>- </CardHeader>- <CardContent>- {#if error}- <ErrorAlert {error} class="mb-4" />- {/if}- <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="grid w-full items-center gap-4">- <div class="flex flex-col space-y-1.5">- <Label for="organizationName">Organization Name</Label>- <Input id="organizationName" type="text" bind:value={organizationName} placeholder="Your company or team" required />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="timezone">Timezone</Label>- <Select.Root type="single" bind:value={timezone}>- <Select.Trigger class="w-full">- <span>{timezone}</span>- </Select.Trigger>- <Select.Content class="max-h-60">- {#each timezones as tz}- <Select.Item value={tz}>- {#snippet children({ selected })}- <span>{tz}</span>- {#if selected}- <Check class="absolute end-2 size-4" />- {/if}- {/snippet}- </Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- <div class="flex flex-col space-y-1.5">- <Label for="projectName">Project Name</Label>- <Input id="projectName" type="text" bind:value={projectName} placeholder="My App" required />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="framework">Framework</Label>- <FrameworkCombobox bind:value={framework} />- </div>- <Button type="submit" disabled={loading} class="w-full mt-2">- {#if loading}- Finishing setup...- {:else}- Finish setup- {/if}- </Button>- </form>- </CardContent>- </Card>+ <Card class="w-[400px]">+ <CardHeader>+ <CardTitle class="text-2xl">+ <div class="flex flex-row items-center justify-center gap-2">+ {#if themeState.isDark}+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />+ {:else}+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />+ {/if}+ </div>+ </CardTitle>+ <CardDescription class="text-center">Finish setting up your account</CardDescription>+ </CardHeader>+ <CardContent>+ {#if error}+ <ErrorAlert {error} class="mb-4" />+ {/if}+ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleSubmit();+ }}+ class="grid w-full items-center gap-4"+ >+ <div class="flex flex-col space-y-1.5">+ <Label for="organizationName">Organization Name</Label>+ <Input+ id="organizationName"+ type="text"+ bind:value={organizationName}+ placeholder="Your company or team"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="timezone">Timezone</Label>+ <Select.Root type="single" bind:value={timezone}>+ <Select.Trigger class="w-full">+ <span>{timezone}</span>+ </Select.Trigger>+ <Select.Content class="max-h-60">+ {#each timezones as tz, __index (__index)}+ <Select.Item value={tz}>+ {#snippet children({ selected })}+ <span>{tz}</span>+ {#if selected}+ <Check class="absolute end-2 size-4" />+ {/if}+ {/snippet}+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="projectName">Project Name</Label>+ <Input+ id="projectName"+ type="text"+ bind:value={projectName}+ placeholder="My App"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="framework">Framework</Label>+ <FrameworkCombobox bind:value={framework} />+ </div>+ <Button type="submit" disabled={loading} class="mt-2 w-full">+ {#if loading}+ Finishing setup...+ {:else}+ Finish setup+ {/if}+ </Button>+ </form>+ </CardContent>+ </Card></div>diff --git a/frontend/src/routes/forgot-password/+page.svelte b/frontend/src/routes/forgot-password/+page.svelteindex 123fcdd0..94f83bb6 100644--- a/frontend/src/routes/forgot-password/+page.svelte+++ b/frontend/src/routes/forgot-password/+page.svelte@@ -1,93 +1,106 @@<script lang="ts">- import { Button } from "$lib/components/ui/button";- import { Input } from "$lib/components/ui/input";- import { Label } from "$lib/components/ui/label";- import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "$lib/components/ui/card";- import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";- import { ErrorAlert } from "$lib/components/ui/error-alert";- import { CircleAlert, CircleCheck } from "@lucide/svelte";- import { themeState } from '$lib/state/theme.svelte';+ import { resolve } from '$app/paths';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '$lib/components/ui/card';+ import { Alert, AlertDescription, AlertTitle } from '$lib/components/ui/alert';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { CircleCheck } from '@lucide/svelte';+ import { themeState } from '$lib/state/theme.svelte';- let email = $state('');- let error = $state('');- let loading = $state(false);- let success = $state(false);+ let email = $state('');+ let error = $state('');+ let loading = $state(false);+ let success = $state(false);- async function handleSubmit() {- loading = true;- error = '';+ async function handleSubmit() {+ loading = true;+ error = '';- try {- const response = await fetch('/api/forgot-password', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify({ email })- });+ try {+ const response = await fetch('/api/forgot-password', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({ email })+ });- if (!response.ok) {- const data = await response.json();- throw new Error(data.error || 'Failed to process request');- }+ if (!response.ok) {+ const data = await response.json();+ throw new Error(data.error || 'Failed to process request');+ }- success = true;- } catch (e) {- error = e instanceof Error ? e.message : 'An unexpected error occurred';- } finally {- loading = false;- }- }+ success = true;+ } catch (e) {+ error = e instanceof Error ? e.message : 'An unexpected error occurred';+ } finally {+ loading = false;+ }+ }</script><div class="flex h-screen w-full items-center justify-center px-4">- <Card class="w-[350px]">- <CardHeader>- <CardTitle class="text-2xl">- <div class="flex flex-row items-center justify-center gap-2">- {#if themeState.isDark}- <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />- {:else}- <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />- {/if}- </div>- </CardTitle>- </CardHeader>- <CardContent>- {#if success}- <Alert class="mb-4 bg-green-50 border-green-200">- <CircleCheck class="h-4 w-4 text-green-700" />- <AlertTitle class="text-green-800">Check your email</AlertTitle>- <AlertDescription class="text-green-700">- If an account exists with this email, a password reset link will be sent to it.- </AlertDescription>- </Alert>- {:else}- {#if error}- <ErrorAlert {error} class="mb-4" />- {/if}- <p class="text-sm text-muted-foreground mb-4">- Enter your email address and we'll send you a link to reset your password.- </p>- <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="grid w-full items-center gap-4">- <div class="flex flex-col space-y-1.5">- <Label for="email">Email</Label>- <Input id="email" type="email" bind:value={email} placeholder="[email protected]" required />- </div>- <Button type="submit" disabled={loading} class="w-full">- {#if loading}- Sending...- {:else}- Send Reset Link- {/if}- </Button>- </form>- {/if}- </CardContent>- <CardFooter class="flex flex-col justify-center">- <p class="text-sm text-muted-foreground">- <a href="/login" class="text-primary hover:underline">Back to Login</a>- </p>- </CardFooter>- </Card>+ <Card class="w-[350px]">+ <CardHeader>+ <CardTitle class="text-2xl">+ <div class="flex flex-row items-center justify-center gap-2">+ {#if themeState.isDark}+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />+ {:else}+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />+ {/if}+ </div>+ </CardTitle>+ </CardHeader>+ <CardContent>+ {#if success}+ <Alert class="mb-4 border-green-200 bg-green-50">+ <CircleCheck class="h-4 w-4 text-green-700" />+ <AlertTitle class="text-green-800">Check your email</AlertTitle>+ <AlertDescription class="text-green-700">+ If an account exists with this email, a password reset link will be sent to it.+ </AlertDescription>+ </Alert>+ {:else}+ {#if error}+ <ErrorAlert {error} class="mb-4" />+ {/if}+ <p class="mb-4 text-sm text-muted-foreground">+ Enter your email address and we'll send you a link to reset your password.+ </p>+ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleSubmit();+ }}+ class="grid w-full items-center gap-4"+ >+ <div class="flex flex-col space-y-1.5">+ <Label for="email">Email</Label>+ <Input+ id="email"+ type="email"+ bind:value={email}+ placeholder="[email protected]"+ required+ />+ </div>+ <Button type="submit" disabled={loading} class="w-full">+ {#if loading}+ Sending...+ {:else}+ Send Reset Link+ {/if}+ </Button>+ </form>+ {/if}+ </CardContent>+ <CardFooter class="flex flex-col justify-center">+ <p class="text-sm text-muted-foreground">+ <a href={resolve('/login')} class="text-primary hover:underline">Back to Login</a>+ </p>+ </CardFooter>+ </Card></div>diff --git a/frontend/src/routes/issues/+page.svelte b/frontend/src/routes/issues/+page.svelteindex 32857116..a4794591 100644--- a/frontend/src/routes/issues/+page.svelte+++ b/frontend/src/routes/issues/+page.svelte@@ -1,5 +1,7 @@<script lang="ts">+ import { getErrorMessage } from '$lib/utils/errors';import { onMount, onDestroy } from 'svelte';+ import { SvelteSet } from 'svelte/reactivity';import { browser } from '$app/environment';import { createRowClickHandler } from '$lib/utils/navigation';import { api } from '$lib/api';@@ -17,6 +19,9 @@import { TableEmptyState } from '$lib/components/ui/table-empty-state';import { PaginationFooter } from '$lib/components/ui/pagination-footer';import { TimeRangePicker } from '$lib/components/ui/time-range-picker';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import BulkActionsBar from '$lib/components/traceway/bulk-actions-bar.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';import { CalendarDate } from '@internationalized/date';import {parseTimeRangeFromUrl,@@ -111,14 +116,6 @@{ value: 'messages', label: 'Messages' }];- // Page size options- const pageSizeOptions = [- { value: '10', label: '10' },- { value: '20', label: '20' },- { value: '50', label: '50' },- { value: '100', label: '100' }- ];-// Helper functions for date/time conversionfunction getFromDateTimeUTC(): string {const [hour, minute] = fromTime.split(':').map(Number);@@ -192,9 +189,9 @@// Clear selection when data changesselectedHashes = new Set();- } catch (e: any) {+ } catch (e) {console.error(e);- error = e.message || 'Failed to load data';+ error = getErrorMessage(e) || 'Failed to load data';} finally {loading = false;}@@ -265,7 +262,7 @@}function toggleSelect(hash: string) {- const newSet = new Set(selectedHashes);+ const newSet = new SvelteSet(selectedHashes);if (newSet.has(hash)) {newSet.delete(hash);} else {@@ -293,14 +290,12 @@{ projectId: projectsState.currentProjectId ?? undefined });- toast.success('Successfully archived the Issue' + (selectedHashes.size > 1 ? 's' : ''), {- position: 'top-center'- });+ toast.success('Successfully archived the Issue' + (selectedHashes.size > 1 ? 's' : ''));selectedHashes = new Set();await loadData();- } catch (e: any) {+ } catch (e) {console.error('Archive failed:', e);- error = e.message || 'Failed to archive issues';+ error = getErrorMessage(e) || 'Failed to archive issues';throw e;} finally {archiving = false;@@ -320,10 +315,8 @@</script><div class="space-y-4">- <!-- Row 1: Title + TimeRangePicker -->- <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">- <h2 class="text-3xl font-semibold tracking-tight">Issues</h2>- <div class="w-full sm:w-auto">+ <PageHeader title="Issues">+ {#snippet actions()}<TimeRangePickerbind:fromDatebind:toDate@@ -332,10 +325,9 @@bind:preset={selectedPreset}onApply={handleTimeRangeChange}/>- </div>- </div>+ {/snippet}+ </PageHeader>- <!-- Row 2: Search --><SearchBarplaceholder="Search exceptions..."bind:value={searchQuery}@@ -345,31 +337,25 @@disabled={loading}/>- <!-- Archive Toolbar - shown when items selected -->{#if selectedCount > 0}- <div- class="flex animate-in items-center gap-3 rounded-md border bg-muted/50 p-3 duration-200 fade-in slide-in-from-top-1"+ <BulkActionsBar+ count={selectedCount}+ itemLabel="issue"+ onClear={() => (selectedHashes = new Set())}>- <span class="text-sm font-medium"- >{selectedCount} issue{selectedCount === 1 ? '' : 's'} selected</span- ><Buttonvariant="outline"size="sm"onclick={() => (showArchiveDialog = true)}disabled={archiving}- class="gap-1.5">- <Archive class="h-4 w-4" />+ <Archive class="mr-2 h-4 w-4" />Archive</Button>- <Button variant="ghost" size="sm" onclick={() => (selectedHashes = new Set())}>- Clear selection- </Button>- </div>+ </BulkActionsBar>{/if}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root>{#if loading}<Table.Body>@@ -436,7 +422,7 @@<Table.Body>{#each exceptions as exception (exception.exceptionHash)}<Table.Row- class="group cursor-pointer hover:bg-muted/50"+ class="group cursor-pointer"data-state={isSelected(exception.exceptionHash) ? 'selected' : undefined}><Table.Cell class="pl-4" onclick={(e) => e.stopPropagation()}>@@ -507,7 +493,7 @@</Table.Body>{/if}</Table.Root>- </div>+ </TableContainer><!-- Pagination Footer --><PaginationFooterdiff --git a/frontend/src/routes/issues/[exceptionHash]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/+page.svelteindex 5f9da920..6ba2582c 100644--- a/frontend/src/routes/issues/[exceptionHash]/+page.svelte+++ b/frontend/src/routes/issues/[exceptionHash]/+page.svelte@@ -1,17 +1,17 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';import { onMount } from 'svelte';import { page } from '$app/state';import { goto } from '$app/navigation';import { api } from '$lib/api';- import { Button } from '$lib/components/ui/button';import { LoadingCircle } from '$lib/components/ui/loading-circle';import { ErrorDisplay } from '$lib/components/ui/error-display';import { projectsState, isJsFramework, isJsLanguage } from '$lib/state/projects.svelte';- import { StackTraceCard, EventCard, EventsTable, PageHeader } from '$lib/components/issues';+ import { StackTraceCard, EventCard, EventsTable } from '$lib/components/issues';+ import PageHeader from '$lib/components/traceway/page-header.svelte';import { toast } from 'svelte-sonner';import ArchiveConfirmationDialog from '$lib/components/archive-confirmation-dialog.svelte';import OncallOwner from '$lib/components/traceway/oncall-owner.svelte';- import Archive from '@lucide/svelte/icons/archive';import type {ExceptionGroup,ExceptionOccurrence,@@ -49,7 +49,9 @@));const hasMoreOccurrences = $derived(total > 10);- const firstLineOfStackTrace = $derived(latestOccurrence?.stackTrace.split('\n')[0] || 'Exception');+ const firstLineOfStackTrace = $derived(+ latestOccurrence?.stackTrace.split('\n')[0] || 'Exception'+ );async function loadData() {loading = true;@@ -105,12 +107,12 @@console.warn('Could not load linked trace:', txError);}}- } catch (e: any) {+ } catch (e) {console.error(e);- if (e.status === 404) {+ if (getErrorStatus(e) === 404) {notFound = true;} else {- error = e.message || 'Failed to load exception details';+ error = getErrorMessage(e) || 'Failed to load exception details';}} finally {loading = false;@@ -125,9 +127,9 @@{ hashes: [exceptionHash], resolvePages },{ projectId: projectsState.currentProjectId ?? undefined });- toast.success('Successfully archived the Issue', { position: 'top-center' });- goto('/issues');- } catch (e: any) {+ toast.success('Successfully archived the Issue');+ goto(resolve('/issues'));+ } catch (e) {console.error('Archive failed:', e);throw e;} finally {@@ -141,14 +143,15 @@</script><div class="space-y-6">- <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">- <PageHeader- title={firstLineOfStackTrace}- subtitle="Exception Hash: {exceptionHash}"- onBack={createSmartBackHandler({ fallbackPath: resolve('/issues') })}- />- <OncallOwner />- </div>+ <PageHeader+ title={firstLineOfStackTrace}+ subtitle="Exception Hash: {exceptionHash}"+ onBack={createSmartBackHandler({ fallbackPath: resolve('/issues') })}+ >+ {#snippet actions()}+ <OncallOwner />+ {/snippet}+ </PageHeader>{#if loading && !group}<div class="flex items-center justify-center py-20">diff --git a/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.svelteindex ac940ea7..a8bb9ddf 100644--- a/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.svelte+++ b/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.svelte@@ -1,218 +1,234 @@<script lang="ts">- import { api } from '$lib/api';- import { LoadingCircle } from "$lib/components/ui/loading-circle";- import { ErrorDisplay } from "$lib/components/ui/error-display";- import { projectsState, isJsFramework, isJsLanguage } from '$lib/state/projects.svelte';- import { getTimezone } from '$lib/state/timezone.svelte';- import { formatDateTime } from '$lib/utils/formatters';- import { StackTraceCard, EventCard, EventsTable, PageHeader } from '$lib/components/issues';- import type { ExceptionOccurrence, LinkedTrace, SessionRecording } from '$lib/types/exceptions';+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';+ import { api } from '$lib/api';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { ErrorDisplay } from '$lib/components/ui/error-display';+ import { projectsState, isJsFramework, isJsLanguage } from '$lib/state/projects.svelte';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import { formatDateTime } from '$lib/utils/formatters';+ import { StackTraceCard, EventCard, EventsTable } from '$lib/components/issues';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import type { ExceptionOccurrence, LinkedTrace, SessionRecording } from '$lib/types/exceptions';import { createSmartBackHandler } from '$lib/utils/back-navigation';import { resolve } from '$app/paths';import ArchiveConfirmationDialog from '$lib/components/archive-confirmation-dialog.svelte';import { goto } from '$app/navigation';import { toast } from 'svelte-sonner';- let { data } = $props();-- const timezone = $derived(getTimezone());-- let occurrence = $state<ExceptionOccurrence | null>(null);- let allOccurrences = $state<ExceptionOccurrence[]>([]);- let loading = $state(true);- let error = $state('');- let notFound = $state(false);- let total = $state(0);- let linkedTrace = $state<LinkedTrace | null>(null);- let sessionRecording = $state<SessionRecording | null>(null);- let sessionId = $state<string | null>(null);- let showArchiveDialog = $state(false);- let archiving = $state(false);--- const isMessage = $derived(occurrence?.isMessage ?? false);- const isJavaScript = $derived(- (projectsState.currentProject?.framework- ? isJsFramework(projectsState.currentProject.framework)- : false) || isJsLanguage(occurrence?.attributes?.['telemetry.sdk.language'])- );- const isFlutter = $derived(projectsState.currentProject?.framework === 'flutter');- const isIOS = $derived(- projectsState.currentProject?.framework === 'ios' ||- ['ios', 'swift'].includes(- (occurrence?.attributes?.['telemetry.sdk.language'] ?? '').toLowerCase()- )- );- const firstLineOfStackTrace = $derived(occurrence?.stackTrace.split('\n')[0] || 'Exception');- const hasMoreOccurrences = $derived(total > 10);- const subtitleText = $derived(occurrence ? `Event from ${formatDateTime(occurrence.recordedAt, { timezone })}` : 'Loading...');-- async function loadData() {- loading = true;- error = '';- notFound = false;- linkedTrace = null;- sessionRecording = null;-- try {- // Load the specific exception by ID- const exceptionResponse = await api.post(`/exception-stack-traces/by-id/${data.exceptionId}`, data.recordedAt ? { recordedAt: data.recordedAt } : {}, { projectId: projectsState.currentProjectId ?? undefined });- occurrence = exceptionResponse.exception;- sessionRecording = exceptionResponse.sessionRecording ?? null;- sessionId = exceptionResponse.sessionId ?? null;-- if (!occurrence) {- notFound = true;- return;- }-- // Load all occurrences for this hash (for the events table)- const response = await api.post(`/exception-stack-traces/${data.exceptionHash}`, {- pagination: {- page: 1,- pageSize: 10- }- }, { projectId: projectsState.currentProjectId ?? undefined });-- allOccurrences = response.occurrences || [];- total = response.pagination.total;-- // Load linked trace if this occurrence has a traceId- if (occurrence.traceId) {- try {- const isTask = occurrence.traceType === 'task';- console.log('DEBUG linked trace:', {- traceId: occurrence.traceId,- traceType: occurrence.traceType,- isTask- });- const endpoint = isTask ? '/tasks' : '/endpoints';- const txResponse = await api.post(- `${endpoint}/${occurrence.traceId}`,- {},- { projectId: projectsState.currentProjectId ?? undefined }- );- const txData = isTask ? txResponse.task : txResponse.endpoint;- if (txData) {- linkedTrace = {- id: txData.id,- endpoint: isTask ? txData.taskName : txData.endpoint,- duration: txData.duration,- statusCode: txData.statusCode || 0,- recordedAt: txData.recordedAt,- traceType: isTask ? 'task' : 'endpoint',- distributedTraceId: txData.distributedTraceId- };- }- } catch (txError) {- console.error('Failed to load linked trace:', {- error: txError,- traceId: occurrence.traceId,- traceType: occurrence.traceType- });- }- }- } catch (e: any) {- console.error(e);- if (e.status === 404) {- notFound = true;- } else {- error = e.message || 'Failed to load exception details';- }- } finally {- loading = false;- }- }-- async function archiveIssue(resolvePages: boolean) {- archiving = true;- try {- await api.post(- '/exception-stack-traces/archive',- { hashes: [data.exceptionHash], resolvePages },- { projectId: projectsState.currentProjectId ?? undefined }- );- toast.success('Successfully archived the Issue', { position: 'top-center' });- goto(resolve("/issues"));- } catch (e: any) {- console.error('Archive failed:', e);- throw e;- } finally {- archiving = false;- }- }-- $effect(() => {- data.exceptionId;- loadData();- });+ let { data } = $props();++ const timezone = $derived(getTimezone());++ let occurrence = $state<ExceptionOccurrence | null>(null);+ let allOccurrences = $state<ExceptionOccurrence[]>([]);+ let loading = $state(true);+ let error = $state('');+ let notFound = $state(false);+ let total = $state(0);+ let linkedTrace = $state<LinkedTrace | null>(null);+ let sessionRecording = $state<SessionRecording | null>(null);+ let sessionId = $state<string | null>(null);+ let showArchiveDialog = $state(false);+ let archiving = $state(false);++ const isMessage = $derived(occurrence?.isMessage ?? false);+ const isJavaScript = $derived(+ (projectsState.currentProject?.framework+ ? isJsFramework(projectsState.currentProject.framework)+ : false) || isJsLanguage(occurrence?.attributes?.['telemetry.sdk.language'])+ );+ const isFlutter = $derived(projectsState.currentProject?.framework === 'flutter');+ const isIOS = $derived(+ projectsState.currentProject?.framework === 'ios' ||+ ['ios', 'swift'].includes(+ (occurrence?.attributes?.['telemetry.sdk.language'] ?? '').toLowerCase()+ )+ );+ const firstLineOfStackTrace = $derived(occurrence?.stackTrace.split('\n')[0] || 'Exception');+ const hasMoreOccurrences = $derived(total > 10);+ const subtitleText = $derived(+ occurrence ? `Event from ${formatDateTime(occurrence.recordedAt, { timezone })}` : 'Loading...'+ );++ async function loadData() {+ loading = true;+ error = '';+ notFound = false;+ linkedTrace = null;+ sessionRecording = null;++ try {+ // Load the specific exception by ID+ const exceptionResponse = await api.post(+ `/exception-stack-traces/by-id/${data.exceptionId}`,+ data.recordedAt ? { recordedAt: data.recordedAt } : {},+ { projectId: projectsState.currentProjectId ?? undefined }+ );+ occurrence = exceptionResponse.exception;+ sessionRecording = exceptionResponse.sessionRecording ?? null;+ sessionId = exceptionResponse.sessionId ?? null;++ if (!occurrence) {+ notFound = true;+ return;+ }++ // Load all occurrences for this hash (for the events table)+ const response = await api.post(+ `/exception-stack-traces/${data.exceptionHash}`,+ {+ pagination: {+ page: 1,+ pageSize: 10+ }+ },+ { projectId: projectsState.currentProjectId ?? undefined }+ );++ allOccurrences = response.occurrences || [];+ total = response.pagination.total;++ // Load linked trace if this occurrence has a traceId+ if (occurrence.traceId) {+ try {+ const isTask = occurrence.traceType === 'task';+ console.log('DEBUG linked trace:', {+ traceId: occurrence.traceId,+ traceType: occurrence.traceType,+ isTask+ });+ const endpoint = isTask ? '/tasks' : '/endpoints';+ const txResponse = await api.post(+ `${endpoint}/${occurrence.traceId}`,+ {},+ { projectId: projectsState.currentProjectId ?? undefined }+ );+ const txData = isTask ? txResponse.task : txResponse.endpoint;+ if (txData) {+ linkedTrace = {+ id: txData.id,+ endpoint: isTask ? txData.taskName : txData.endpoint,+ duration: txData.duration,+ statusCode: txData.statusCode || 0,+ recordedAt: txData.recordedAt,+ traceType: isTask ? 'task' : 'endpoint',+ distributedTraceId: txData.distributedTraceId+ };+ }+ } catch (txError) {+ console.error('Failed to load linked trace:', {+ error: txError,+ traceId: occurrence.traceId,+ traceType: occurrence.traceType+ });+ }+ }+ } catch (e) {+ console.error(e);+ if (getErrorStatus(e) === 404) {+ notFound = true;+ } else {+ error = getErrorMessage(e) || 'Failed to load exception details';+ }+ } finally {+ loading = false;+ }+ }++ async function archiveIssue(resolvePages: boolean) {+ archiving = true;+ try {+ await api.post(+ '/exception-stack-traces/archive',+ { hashes: [data.exceptionHash], resolvePages },+ { projectId: projectsState.currentProjectId ?? undefined }+ );+ toast.success('Successfully archived the Issue');+ goto(resolve('/issues'));+ } catch (e) {+ console.error('Archive failed:', e);+ throw e;+ } finally {+ archiving = false;+ }+ }++ $effect(() => {+ void data.exceptionId;+ loadData();+ });</script><div class="space-y-6">- <PageHeader- title={firstLineOfStackTrace}- subtitle={subtitleText}- onBack={createSmartBackHandler({ fallbackPath: resolve("/issues/[exceptionHash]", {exceptionHash: data.exceptionHash}) })}- />-- {#if loading && !occurrence}- <div class="flex items-center justify-center py-20">- <LoadingCircle size="xlg" />- </div>- {:else if notFound}- <ErrorDisplay- status={404}- title="Event Not Found"- description="The specific event you're looking for doesn't exist or may have been removed."- onBack={createSmartBackHandler({ fallbackPath: resolve('/issues/[exceptionHash]', {exceptionHash: data.exceptionHash}) })}- backLabel="Back to Exception"- onRetry={() => loadData()}- />- {:else if error}- <ErrorDisplay- status={400}- title="Something Went Wrong"- description={error}- onBack={createSmartBackHandler({ fallbackPath: resolve('/issues/[exceptionHash]', {exceptionHash: data.exceptionHash}) })}- backLabel="Back to Exception"- onRetry={() => loadData()}- />- {:else if occurrence}- <StackTraceCard- stackTrace={occurrence.stackTrace}- {isMessage}- {isJavaScript}- {isFlutter}- {isIOS}- bind:showArchiveDialog={showArchiveDialog}- bind:archiving={archiving}- />-- <EventCard- {occurrence}- {linkedTrace}- {sessionRecording}- {sessionId}- title="Event"- description="Details for this specific occurrence"- />-- <EventsTable- occurrences={allOccurrences}- exceptionHash={data.exceptionHash}- {total}- hasMore={hasMoreOccurrences}- showViewAll={true}- currentExceptionId={data.exceptionId}- />- {/if}+ <PageHeader+ title={firstLineOfStackTrace}+ subtitle={subtitleText}+ onBack={createSmartBackHandler({+ fallbackPath: resolve('/issues/[exceptionHash]', { exceptionHash: data.exceptionHash })+ })}+ />++ {#if loading && !occurrence}+ <div class="flex items-center justify-center py-20">+ <LoadingCircle size="xlg" />+ </div>+ {:else if notFound}+ <ErrorDisplay+ status={404}+ title="Event Not Found"+ description="The specific event you're looking for doesn't exist or may have been removed."+ onBack={createSmartBackHandler({+ fallbackPath: resolve('/issues/[exceptionHash]', { exceptionHash: data.exceptionHash })+ })}+ backLabel="Back to Exception"+ onRetry={() => loadData()}+ />+ {:else if error}+ <ErrorDisplay+ status={400}+ title="Something Went Wrong"+ description={error}+ onBack={createSmartBackHandler({+ fallbackPath: resolve('/issues/[exceptionHash]', { exceptionHash: data.exceptionHash })+ })}+ backLabel="Back to Exception"+ onRetry={() => loadData()}+ />+ {:else if occurrence}+ <StackTraceCard+ stackTrace={occurrence.stackTrace}+ {isMessage}+ {isJavaScript}+ {isFlutter}+ {isIOS}+ bind:showArchiveDialog+ bind:archiving+ />++ <EventCard+ {occurrence}+ {linkedTrace}+ {sessionRecording}+ {sessionId}+ title="Event"+ description="Details for this specific occurrence"+ />++ <EventsTable+ occurrences={allOccurrences}+ exceptionHash={data.exceptionHash}+ {total}+ hasMore={hasMoreOccurrences}+ showViewAll={true}+ currentExceptionId={data.exceptionId}+ />+ {/if}</div>-<ArchiveConfirmationDialog- open={showArchiveDialog}- onOpenChange={(open) => showArchiveDialog = open}- count={1}- hashes={[data.exceptionHash]}- onConfirm={archiveIssue}+ open={showArchiveDialog}+ onOpenChange={(open) => (showArchiveDialog = open)}+ count={1}+ hashes={[data.exceptionHash]}+ onConfirm={archiveIssue}/>diff --git a/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.ts b/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.tsindex fd9c1c69..d2ec08c8 100644--- a/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.ts+++ b/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.ts@@ -1,9 +1,9 @@export const prerender = false;export function load({ params, url }) {- return {- exceptionHash: params.exceptionHash,- exceptionId: params.exceptionId,- recordedAt: url.searchParams.get('t')- };+ return {+ exceptionHash: params.exceptionHash,+ exceptionId: params.exceptionId,+ recordedAt: url.searchParams.get('t')+ };}diff --git a/frontend/src/routes/issues/[exceptionHash]/events/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/events/+page.svelteindex 16f50a50..3bbe7be7 100644--- a/frontend/src/routes/issues/[exceptionHash]/events/+page.svelte+++ b/frontend/src/routes/issues/[exceptionHash]/events/+page.svelte@@ -1,284 +1,289 @@<script lang="ts">- import { onMount } from 'svelte';- import { page } from '$app/state';- import { goto } from '$app/navigation';- import { createRowClickHandler } from '$lib/utils/navigation';- import { createSmartBackHandler } from '$lib/utils/back-navigation';- import { truncateStackTrace, formatDateTime } from '$lib/utils/formatters';- import { getTimezone } from '$lib/state/timezone.svelte';- import { api } from '$lib/api';- import { Button } from "$lib/components/ui/button";- import * as Card from "$lib/components/ui/card";- import * as Table from "$lib/components/ui/table";- import * as Select from "$lib/components/ui/select";- import { LoadingCircle } from "$lib/components/ui/loading-circle";- import { ErrorDisplay } from "$lib/components/ui/error-display";- import { projectsState, isFrontendFramework } from '$lib/state/projects.svelte';- import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";- import { TableEmptyState } from "$lib/components/ui/table-empty-state";- import { PaginationFooter } from "$lib/components/ui/pagination-footer";- import { toast } from 'svelte-sonner';- import ArchiveConfirmationDialog from '$lib/components/archive-confirmation-dialog.svelte';- import Archive from '@lucide/svelte/icons/archive';+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';+ import { onMount } from 'svelte';+ import { page } from '$app/state';+ import { goto } from '$app/navigation';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { createSmartBackHandler } from '$lib/utils/back-navigation';+ import { truncateStackTrace, formatDateTime } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import { api } from '$lib/api';+ import { Button } from '$lib/components/ui/button';+ import * as Card from '$lib/components/ui/card';+ import * as Table from '$lib/components/ui/table';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { ErrorDisplay } from '$lib/components/ui/error-display';+ import { projectsState, isFrontendFramework } from '$lib/state/projects.svelte';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { toast } from 'svelte-sonner';+ import ArchiveConfirmationDialog from '$lib/components/archive-confirmation-dialog.svelte';+ import Archive from '@lucide/svelte/icons/archive';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';import { resolve } from '$app/paths';- const timezone = $derived(getTimezone());- const isFrontend = $derived(- projectsState.currentProject?.framework- ? isFrontendFramework(projectsState.currentProject.framework)- : false- );+ const timezone = $derived(getTimezone());+ const isFrontend = $derived(+ projectsState.currentProject?.framework+ ? isFrontendFramework(projectsState.currentProject.framework)+ : false+ );- type ExceptionGroup = {- exceptionHash: string;- stackTrace: string;- lastSeen: string;- firstSeen: string;- count: number;- };+ type ExceptionGroup = {+ exceptionHash: string;+ stackTrace: string;+ lastSeen: string;+ firstSeen: string;+ count: number;+ };- type ExceptionOccurrence = {- id: string;- traceId: string | null;- exceptionHash: string;- stackTrace: string;- recordedAt: string;- serverName: string;- appVersion: string;- endpoint: string;- };+ type ExceptionOccurrence = {+ id: string;+ traceId: string | null;+ exceptionHash: string;+ stackTrace: string;+ recordedAt: string;+ serverName: string;+ appVersion: string;+ endpoint: string;+ };- let group = $state<ExceptionGroup | null>(null);- let occurrences = $state<ExceptionOccurrence[]>([]);- let loading = $state(true);- let error = $state('');- let notFound = $state(false);- let showArchiveDialog = $state(false);- let archiving = $state(false);+ let group = $state<ExceptionGroup | null>(null);+ let occurrences = $state<ExceptionOccurrence[]>([]);+ let loading = $state(true);+ let error = $state('');+ let notFound = $state(false);+ let showArchiveDialog = $state(false);+ let archiving = $state(false);- // Pagination state- let currentPage = $state(1);- let pageSize = $state(50);- let total = $state(0);- let totalPages = $state(0);+ // Pagination state+ let currentPage = $state(1);+ let pageSize = $state(50);+ let total = $state(0);+ let totalPages = $state(0);- // Page size options- const pageSizeOptions = [- { value: "10", label: "10" },- { value: "20", label: "20" },- { value: "50", label: "50" },- { value: "100", label: "100" }- ];+ async function loadData() {+ loading = true;+ error = '';+ notFound = false;- const pageSizeLabel = $derived(pageSizeOptions.find(o => o.value === pageSize.toString())?.label ?? pageSize.toString());+ try {+ const exceptionHash = page.params.exceptionHash;+ const response = await api.post(+ `/exception-stack-traces/${exceptionHash}`,+ {+ pagination: {+ page: currentPage,+ pageSize: pageSize+ }+ },+ { projectId: projectsState.currentProjectId ?? undefined }+ );- async function loadData() {- loading = true;- error = '';- notFound = false;+ group = response.group;+ occurrences = response.occurrences || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e) {+ console.error(e);+ if (getErrorStatus(e) === 404) {+ notFound = true;+ } else {+ error = getErrorMessage(e) || 'Failed to load exception details';+ }+ } finally {+ loading = false;+ }+ }- try {- const exceptionHash = page.params.exceptionHash;- const response = await api.post(`/exception-stack-traces/${exceptionHash}`, {- pagination: {- page: currentPage,- pageSize: pageSize- }- }, { projectId: projectsState.currentProjectId ?? undefined });+ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ currentPage = newPage;+ loadData();+ }+ }- group = response.group;- occurrences = response.occurrences || [];- total = response.pagination.total;- totalPages = response.pagination.totalPages;- } catch (e: any) {- console.error(e);- if (e.status === 404) {- notFound = true;- } else {- error = e.message || 'Failed to load exception details';- }- } finally {- loading = false;- }- }+ function handlePageSizeChange(newPageSize: number) {+ pageSize = newPageSize;+ currentPage = 1;+ loadData();+ }- function handlePageChange(newPage: number) {- if (newPage >= 1 && newPage <= totalPages) {- currentPage = newPage;- loadData();- }- }+ async function archiveIssue(resolvePages: boolean) {+ archiving = true;+ try {+ await api.post(+ '/exception-stack-traces/archive',+ { hashes: [page.params.exceptionHash], resolvePages },+ { projectId: projectsState.currentProjectId ?? undefined }+ );+ toast.success('Successfully archived the Issue');+ goto(resolve('/issues'));+ } catch (e) {+ console.error('Archive failed:', e);+ throw e;+ } finally {+ archiving = false;+ }+ }- function handlePageSizeChange(newPageSize: number) {- pageSize = newPageSize;- currentPage = 1;- loadData();- }-- async function archiveIssue(resolvePages: boolean) {- archiving = true;- try {- await api.post(- '/exception-stack-traces/archive',- { hashes: [page.params.exceptionHash], resolvePages },- { projectId: projectsState.currentProjectId ?? undefined }- );- toast.success('Successfully archived the Issue', { position: 'top-center' });- goto('/issues');- } catch (e: any) {- console.error('Archive failed:', e);- throw e;- } finally {- archiving = false;- }- }-- onMount(() => {- loadData();- });+ onMount(() => {+ loadData();+ });</script><div class="space-y-6">- <!-- Header -->- <div class="flex items-center justify-between">- <Button variant="outline" size="sm" onclick={createSmartBackHandler({ fallbackPath: resolve('/issues/[exceptionHash]', {exceptionHash: page.params.exceptionHash ?? ''}) })}>- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2">- <path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>- </svg>- Back to Issue- </Button>- {#if group}- <Button- variant="outline"- size="sm"- onclick={() => showArchiveDialog = true}- disabled={archiving}- class="gap-1.5"- >- <Archive class="h-4 w-4" />- Archive- </Button>- {/if}- </div>+ <PageHeader+ title="Events"+ subtitle={page.params.exceptionHash}+ onBack={createSmartBackHandler({+ fallbackPath: resolve('/issues/[exceptionHash]', {+ exceptionHash: page.params.exceptionHash ?? ''+ })+ })}+ >+ {#snippet actions()}+ {#if group}+ <Button+ variant="outline"+ size="sm"+ onclick={() => (showArchiveDialog = true)}+ disabled={archiving}+ >+ <Archive class="mr-2 h-4 w-4" />+ Archive+ </Button>+ {/if}+ {/snippet}+ </PageHeader>- {#if loading && !group}- <div class="flex items-center justify-center py-20">- <LoadingCircle size="xlg" />- </div>- {:else if notFound}- <ErrorDisplay- status={404}- title="Exception Not Found"- description="The exception you're looking for doesn't exist or may have been removed."- onBack={createSmartBackHandler({ fallbackPath: resolve('/issues') })}- backLabel="Back to Issues"- onRetry={() => loadData()}- identifier={page.params.exceptionHash}- />- {:else if error}- <ErrorDisplay- status={400}- title="Something Went Wrong"- description={error}- onBack={createSmartBackHandler({ fallbackPath: resolve('/issues') })}- backLabel="Back to Issues"- onRetry={() => loadData()}- />- {:else if group}- <!-- Issue Summary -->- <Card.Root>- <Card.Header class="pb-3">- <Card.Title class="text-lg">All Events</Card.Title>- <Card.Description class="font-mono text-sm">- {truncateStackTrace(group.stackTrace, 80)}- </Card.Description>- </Card.Header>- </Card.Root>+ {#if loading && !group}+ <div class="flex items-center justify-center py-20">+ <LoadingCircle size="xlg" />+ </div>+ {:else if notFound}+ <ErrorDisplay+ status={404}+ title="Exception Not Found"+ description="The exception you're looking for doesn't exist or may have been removed."+ onBack={createSmartBackHandler({ fallbackPath: resolve('/issues') })}+ backLabel="Back to Issues"+ onRetry={() => loadData()}+ identifier={page.params.exceptionHash}+ />+ {:else if error}+ <ErrorDisplay+ status={400}+ title="Something Went Wrong"+ description={error}+ onBack={createSmartBackHandler({ fallbackPath: resolve('/issues') })}+ backLabel="Back to Issues"+ onRetry={() => loadData()}+ />+ {:else if group}+ <!-- Issue Summary -->+ <Card.Root>+ <Card.Header class="pb-3">+ <Card.Title class="text-lg">All Events</Card.Title>+ <Card.Description class="font-mono text-sm">+ {truncateStackTrace(group.stackTrace, 80)}+ </Card.Description>+ </Card.Header>+ </Card.Root>- <!-- Events Table -->- <div class="rounded-md border overflow-hidden">- <Table.Root>- {#if loading || occurrences.length > 0}- <Table.Header>- <Table.Row>- <TracewayTableHeader- label="Recorded At"- tooltip="When this occurrence was recorded"- />- {#if isFrontend}- <TracewayTableHeader- label="Title"- tooltip="Exception message from the first line of the stack trace"- />- {:else}- <TracewayTableHeader- label="Server"- tooltip="Server instance where error occurred"- />- <TracewayTableHeader- label="Trace"- tooltip="Trace ID if this occurred during a request"- />- {/if}- </Table.Row>- </Table.Header>- {/if}- <Table.Body>- {#if loading}- <Table.Row>- <Table.Cell colspan={isFrontend ? 2 : 3} class="h-48">- <div class="flex items-center justify-center">- <LoadingCircle size="lg" />- </div>- </Table.Cell>- </Table.Row>- {:else if occurrences.length === 0}- <TableEmptyState colspan={isFrontend ? 2 : 3} message="No events found." />- {:else}- {#each occurrences as occurrence}- <Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={createRowClickHandler(`/issues/${page.params.exceptionHash}/${occurrence.id}`, 'preset', 'from', 'to')}- >- <Table.Cell>{formatDateTime(occurrence.recordedAt, { timezone })}</Table.Cell>- {#if isFrontend}- <Table.Cell class="font-mono text-sm text-muted-foreground truncate max-w-[400px]" title={occurrence.stackTrace.split('\n')[0]}>- {truncateStackTrace(occurrence.stackTrace, 60)}- </Table.Cell>- {:else}- <Table.Cell class="font-mono text-sm text-muted-foreground">- {occurrence.serverName || '-'}- </Table.Cell>- <Table.Cell class="font-mono text-sm">- {occurrence.traceId || '-'}- </Table.Cell>- {/if}- </Table.Row>- {/each}- {/if}- </Table.Body>- </Table.Root>- </div>+ <!-- Events Table -->+ <TableContainer>+ <Table.Root>+ {#if loading || occurrences.length > 0}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader+ label="Recorded At"+ tooltip="When this occurrence was recorded"+ />+ {#if isFrontend}+ <TracewayTableHeader+ label="Title"+ tooltip="Exception message from the first line of the stack trace"+ />+ {:else}+ <TracewayTableHeader+ label="Server"+ tooltip="Server instance where error occurred"+ />+ <TracewayTableHeader+ label="Trace"+ tooltip="Trace ID if this occurred during a request"+ />+ {/if}+ </Table.Row>+ </Table.Header>+ {/if}+ <Table.Body>+ {#if loading}+ <Table.Row>+ <Table.Cell colspan={isFrontend ? 2 : 3} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ {:else if occurrences.length === 0}+ <TableEmptyState colspan={isFrontend ? 2 : 3} message="No events found." />+ {:else}+ {#each occurrences as occurrence, __index (__index)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ `/issues/${page.params.exceptionHash}/${occurrence.id}`,+ 'preset',+ 'from',+ 'to'+ )}+ >+ <Table.Cell>{formatDateTime(occurrence.recordedAt, { timezone })}</Table.Cell>+ {#if isFrontend}+ <Table.Cell+ class="max-w-[400px] truncate font-mono text-sm text-muted-foreground"+ title={occurrence.stackTrace.split('\n')[0]}+ >+ {truncateStackTrace(occurrence.stackTrace, 60)}+ </Table.Cell>+ {:else}+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {occurrence.serverName || '-'}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm">+ {occurrence.traceId || '-'}+ </Table.Cell>+ {/if}+ </Table.Row>+ {/each}+ {/if}+ </Table.Body>+ </Table.Root>+ </TableContainer>- <!-- Pagination Footer -->- <PaginationFooter- {currentPage}- {totalPages}- {pageSize}- totalItems={total}- itemsShown={occurrences.length}- onPageChange={handlePageChange}- onPageSizeChange={handlePageSizeChange}- {loading}- itemLabel="event"- />- {/if}+ <!-- Pagination Footer -->+ <PaginationFooter+ {currentPage}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={handlePageChange}+ onPageSizeChange={handlePageSizeChange}+ {loading}+ itemLabel="event"+ />+ {/if}</div><ArchiveConfirmationDialog- open={showArchiveDialog}- onOpenChange={(open) => showArchiveDialog = open}- count={1}- hashes={page.params.exceptionHash ? [page.params.exceptionHash] : []}- onConfirm={archiveIssue}+ open={showArchiveDialog}+ onOpenChange={(open) => (showArchiveDialog = open)}+ count={1}+ hashes={page.params.exceptionHash ? [page.params.exceptionHash] : []}+ onConfirm={archiveIssue}/>diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelteindex 6f0d2f78..aa7cd159 100644--- a/frontend/src/routes/login/+page.svelte+++ b/frontend/src/routes/login/+page.svelte@@ -1,151 +1,178 @@<script lang="ts">- import { goto } from '$app/navigation';- import { page } from '$app/state';- import { Button } from "$lib/components/ui/button";- import { Input } from "$lib/components/ui/input";- import { Label } from "$lib/components/ui/label";- import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "$lib/components/ui/card";- import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";- import { ErrorAlert } from "$lib/components/ui/error-alert";- import { CircleAlert } from "@lucide/svelte";- import { authState } from '$lib/state/auth.svelte';- import { projectsState } from '$lib/state/projects.svelte';- import { themeState } from '$lib/state/theme.svelte';+ import { resolve } from '$app/paths';+ import { goto } from '$app/navigation';+ import { gotoHref } from '$lib/utils/navigation';+ import { page } from '$app/state';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '$lib/components/ui/card';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { authState } from '$lib/state/auth.svelte';+ import { projectsState } from '$lib/state/projects.svelte';+ import { themeState } from '$lib/state/theme.svelte';import { toast } from 'svelte-sonner';- import OauthButtons from '$lib/components/oauth-buttons.svelte';- import { safeLocalPath } from '$lib/utils/navigation';+ import OauthButtons from '$lib/components/oauth-buttons.svelte';+ import { safeLocalPath } from '$lib/utils/navigation';- const ERROR_MESSAGES: Record<string, string> = {- oauth_failed: 'Sign-in failed. Please try again.',- oauth_no_email: "We couldn't read an email address from that account. Please make sure it has a verified email and try again.",- invite_required: 'This server is invite-only. Ask an admin to invite you.',- };+ const ERROR_MESSAGES: Record<string, string> = {+ oauth_failed: 'Sign-in failed. Please try again.',+ oauth_no_email:+ "We couldn't read an email address from that account. Please make sure it has a verified email and try again.",+ invite_required: 'This server is invite-only. Ask an admin to invite you.'+ };- let email = $state('');- let password = $state('');- const initialError = page.url.searchParams.get('error');+ let email = $state('');+ let password = $state('');+ const initialError = page.url.searchParams.get('error');- let error = $state(initialError ? (ERROR_MESSAGES[initialError] ?? 'Sign-in failed. Please try again.') : '');- let loading = $state(false);- let passwordLoginEnabled = $state(true);- let providersLoaded = $state(false);+ let error = $state(+ initialError ? (ERROR_MESSAGES[initialError] ?? 'Sign-in failed. Please try again.') : ''+ );+ let loading = $state(false);+ let passwordLoginEnabled = $state(true);+ let providersLoaded = $state(false);- if (initialError) {- const cleanUrl = new URL(window.location.href);- cleanUrl.searchParams.delete('error');- window.history.replaceState({}, '', cleanUrl.pathname + cleanUrl.search);- }+ if (initialError) {+ const cleanUrl = new URL(window.location.href);+ cleanUrl.searchParams.delete('error');+ window.history.replaceState({}, '', cleanUrl.pathname + cleanUrl.search);+ }- // Get returnTo parameter for redirecting after login- const returnTo = $derived(page.url.searchParams.get('returnTo'));+ // Get returnTo parameter for redirecting after login+ const returnTo = $derived(page.url.searchParams.get('returnTo'));- if (!__CLOUD_MODE__) {- $effect(() => {- // Wait for providers to load - if password login is disabled, skip the /register redirect.- if (!providersLoaded) return;- if (!passwordLoginEnabled) return;+ if (!__CLOUD_MODE__) {+ $effect(() => {+ // Wait for providers to load - if password login is disabled, skip the /register redirect.+ if (!providersLoaded) return;+ if (!passwordLoginEnabled) return;- loading = true;- fetch('/api/has-organizations', {- method: 'GET',- })- .then(response => response.json())- .then((response) => {- if (response.hasOrganizations) {- loading = false- } else {- goto("/register")- }- }).catch(() => {- toast.error("An unexpected error has occured. The page will refresh in 5 seconds.")- setTimeout(() => {- window.location.reload()- }, 5000)- });- })- }+ loading = true;+ fetch('/api/has-organizations', {+ method: 'GET'+ })+ .then((response) => response.json())+ .then((response) => {+ if (response.hasOrganizations) {+ loading = false;+ } else {+ goto(resolve('/register'));+ }+ })+ .catch(() => {+ toast.error('An unexpected error has occurred. The page will refresh in 5 seconds.');+ setTimeout(() => {+ window.location.reload();+ }, 5000);+ });+ });+ }- async function handleLogin() {- loading = true;- error = '';- try {- const response = await fetch('/api/login', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify({ email, password })- });+ async function handleLogin() {+ loading = true;+ error = '';+ try {+ const response = await fetch('/api/login', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({ email, password })+ });- if (!response.ok) {- const data = await response.json();- throw new Error(data.error || 'Invalid credentials');- }+ if (!response.ok) {+ const data = await response.json();+ throw new Error(data.error || 'Invalid credentials');+ }- const data = await response.json();+ const data = await response.json();- authState.setToken(data.token);- authState.setOrganizations(data.organizations || []);- projectsState.setProjects(data.projects);+ authState.setToken(data.token);+ authState.setOrganizations(data.organizations || []);+ projectsState.setProjects(data.projects);- // Redirect to returnTo if provided (validated same-origin), otherwise dashboard- goto(safeLocalPath(returnTo));- } catch (e) {- error = e instanceof Error ? e.message : 'Invalid email or password';- } finally {- loading = false;- }- }+ // Redirect to returnTo if provided (validated same-origin), otherwise dashboard+ gotoHref(safeLocalPath(returnTo));+ } catch (e) {+ error = e instanceof Error ? e.message : 'Invalid email or password';+ } finally {+ loading = false;+ }+ }</script><div class="flex h-screen w-full items-center justify-center px-4">- <Card class="w-[350px]">- <CardHeader>- <CardTitle class="text-2xl">- <div class="flex flex-row items-center justify-center gap-2">- {#if themeState.isDark}- <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />- {:else}- <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />- {/if}- </div>- </CardTitle>- </CardHeader>- <CardContent>- {#if error}- <ErrorAlert {error} class="mb-4" />- {/if}- <OauthButtons bind:passwordLoginEnabled bind:loaded={providersLoaded} />- {#if providersLoaded && passwordLoginEnabled}- <form onsubmit={(e) => { e.preventDefault(); handleLogin(); }} class="grid w-full items-center gap-4">- <div class="flex flex-col space-y-1.5">- <Label for="email">Email</Label>- <Input id="email" type="email" bind:value={email} placeholder="[email protected]" required />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="password">Password</Label>- <Input id="password" type="password" bind:value={password} placeholder="Password" required />- <a href="/forgot-password" class="text-sm text-primary hover:underline self-end">Forgot password?</a>- </div>- <Button type="submit" disabled={loading} class="w-full">- {#if loading}- Logging in...- {:else}- Login- {/if}- </Button>- </form>- {/if}- </CardContent>+ <Card class="w-[350px]">+ <CardHeader>+ <CardTitle class="text-2xl">+ <div class="flex flex-row items-center justify-center gap-2">+ {#if themeState.isDark}+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />+ {:else}+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />+ {/if}+ </div>+ </CardTitle>+ </CardHeader>+ <CardContent>+ {#if error}+ <ErrorAlert {error} class="mb-4" />+ {/if}+ <OauthButtons bind:passwordLoginEnabled bind:loaded={providersLoaded} />+ {#if providersLoaded && passwordLoginEnabled}+ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleLogin();+ }}+ class="grid w-full items-center gap-4"+ >+ <div class="flex flex-col space-y-1.5">+ <Label for="email">Email</Label>+ <Input+ id="email"+ type="email"+ bind:value={email}+ placeholder="[email protected]"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="password">Password</Label>+ <Input+ id="password"+ type="password"+ bind:value={password}+ placeholder="Password"+ required+ />+ <a+ href={resolve('/forgot-password')}+ class="self-end text-sm text-primary hover:underline">Forgot password?</a+ >+ </div>+ <Button type="submit" disabled={loading} class="w-full">+ {#if loading}+ Logging in...+ {:else}+ Login+ {/if}+ </Button>+ </form>+ {/if}+ </CardContent>- <!-- If the backend is running in the cloud mode we'll allow registration to take place -->- <!-- If we're running in the self hosted mode - we will not allow register -->- {#if __CLOUD_MODE__}- <CardFooter class="flex flex-col justify-center">- <p class="text-sm text-muted-foreground">- Don't have an account? <a href="/register" class="text-primary hover:underline">Create account</a>- </p>- </CardFooter>- {/if}- </Card>+ <!-- If the backend is running in the cloud mode we'll allow registration to take place -->+ <!-- If we're running in the self hosted mode - we will not allow register -->+ {#if __CLOUD_MODE__}+ <CardFooter class="flex flex-col justify-center">+ <p class="text-sm text-muted-foreground">+ Don't have an account? <a href={resolve('/register')} class="text-primary hover:underline"+ >Create account</a+ >+ </p>+ </CardFooter>+ {/if}+ </Card></div>diff --git a/frontend/src/routes/logs/+page.svelte b/frontend/src/routes/logs/+page.svelteindex 8d7e55c7..45b48125 100644--- a/frontend/src/routes/logs/+page.svelte+++ b/frontend/src/routes/logs/+page.svelte@@ -1,7 +1,7 @@<script lang="ts">+ import { getErrorMessage } from '$lib/utils/errors';import { onMount, onDestroy, tick } from 'svelte';import { browser } from '$app/environment';- import { goto } from '$app/navigation';import { api } from '$lib/api';import * as Table from '$lib/components/ui/table';import { SearchBar } from '$lib/components/ui/search-bar';@@ -19,6 +19,10 @@import * as Tooltip from '$lib/components/ui/tooltip';import ExpandedLogRow from '$lib/components/trace-logs/expanded-log-row.svelte';import LogMessage from '$lib/components/trace-logs/log-message.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import ToolbarSelect from '$lib/components/traceway/toolbar-select.svelte';+ import FormField from '$lib/components/traceway/form-field.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';import { Check, Play, Plus, X } from '@lucide/svelte';import { CalendarDate } from '@internationalized/date';import {@@ -26,7 +30,8 @@getResolvedTimeRange,getTimeRangeFromPreset,dateToCalendarDate,- dateToTimeString+ dateToTimeString,+ updateUrl} from '$lib/utils/url-params';import { calendarDateTimeToLuxon, toUTCISO, formatDateTime } from '$lib/utils/formatters';import {@@ -361,7 +366,10 @@// Displayed attribute keys are prefixed `resource.` / `scope.`; log// attributes are unprefixed.- function displayKeyToFilter(displayKey: string): { scope: AttributeFilter['scope']; key: string } {+ function displayKeyToFilter(displayKey: string): {+ scope: AttributeFilter['scope'];+ key: string;+ } {if (displayKey.startsWith('resource.')) {return { scope: 'resource', key: displayKey.slice('resource.'.length) };}@@ -371,10 +379,7 @@return { scope: 'log', key: displayKey };}- function attributeFilterState(- displayKey: string,- value: string- ): 'none' | 'include' | 'exclude' {+ function attributeFilterState(displayKey: string, value: string): 'none' | 'include' | 'exclude' {const { scope, key } = displayKeyToFilter(displayKey);// Contains filters are ignored: an attribute tile reflects (and toggles)// only exact-match filters for its value.@@ -393,7 +398,10 @@(f) => !f.contains && f.scope === scope && f.key === key && f.value === value);if (existing === -1) {- attributeFilters = [...attributeFilters, { scope, key, value, exclude: false, contains: false }];+ attributeFilters = [+ ...attributeFilters,+ { scope, key, value, exclude: false, contains: false }+ ];} else {attributeFilters = attributeFilters.filter((_, i) => i !== existing);}@@ -440,7 +448,9 @@// Pills for the active meta filters, shown next to the attribute chips.const metaFilterChips = $derived([...(bodyFilter ? [{ field: 'body' as const, label: 'body', value: bodyFilter }] : []),- ...(traceIdFilter ? [{ field: 'traceId' as const, label: 'trace_id', value: traceIdFilter }] : []),+ ...(traceIdFilter+ ? [{ field: 'traceId' as const, label: 'trace_id', value: traceIdFilter }]+ : []),...(spanIdFilter ? [{ field: 'spanId' as const, label: 'span_id', value: spanIdFilter }] : []),...(scopeNameFilter? [{ field: 'scopeName' as const, label: 'scope', value: scopeNameFilter }]@@ -474,10 +484,6 @@{ value: '21', label: 'FATAL' }];- const severityTriggerLabel = $derived(- severityOptions.find((o) => Number(o.value) === minSeverity)?.label ?? 'All levels'- );-function getFromDateTimeUTC(): string {const [hour, minute] = fromTime.split(':').map(Number);const luxonDt = calendarDateTimeToLuxon(@@ -497,28 +503,23 @@}function updateLogsUrl(pushToHistory = true) {- if (!browser) return;- const urlParams = new URLSearchParams();- if (selectedPreset) {- urlParams.set('preset', selectedPreset);- } else {- urlParams.set('from', getFromDateTimeUTC());- urlParams.set('to', getToDateTimeUTC());- }- if (searchQuery.trim()) urlParams.set('search', searchQuery.trim());- if (searchType !== 'body') urlParams.set('searchType', searchType);- if (minSeverity > 0) urlParams.set('minSeverity', String(minSeverity));- if (serviceName.trim()) urlParams.set('service', serviceName.trim());- if (traceIdFilter.trim()) urlParams.set('traceId', traceIdFilter.trim());- if (spanIdFilter.trim()) urlParams.set('spanId', spanIdFilter.trim());- if (scopeNameFilter.trim()) urlParams.set('scopeName', scopeNameFilter.trim());- if (bodyFilter) urlParams.set('body', bodyFilter);- for (const f of attributeFilters) {- urlParams.append('attr', formatAttributeFilter(f));- }- const newUrl = `${window.location.pathname}?${urlParams.toString()}`;- // eslint-disable-next-line svelte/no-navigation-without-resolve- goto(newUrl, { replaceState: !pushToHistory, noScroll: true, keepFocus: true });+ updateUrl(+ {+ preset: selectedPreset || null,+ from: selectedPreset ? null : getFromDateTimeUTC(),+ to: selectedPreset ? null : getToDateTimeUTC(),+ search: searchQuery.trim() || null,+ searchType: searchType !== 'body' ? searchType : null,+ minSeverity: minSeverity > 0 ? String(minSeverity) : null,+ service: serviceName.trim() || null,+ traceId: traceIdFilter.trim() || null,+ spanId: spanIdFilter.trim() || null,+ scopeName: scopeNameFilter.trim() || null,+ body: bodyFilter || null,+ attr: attributeFilters.map(formatAttributeFilter)+ },+ { pushToHistory }+ );}function removeAttributeFilter(index: number) {@@ -580,10 +581,10 @@liveExtra = 0;scrollEl?.scrollTo({ top: 0 });scrollTop = 0;- } catch (e: any) {+ } catch (e) {if (gen !== requestGen) return;console.error(e);- error = e.message || 'Failed to load logs';+ error = getErrorMessage(e) || 'Failed to load logs';} finally {if (gen === requestGen) loading = false;}@@ -615,9 +616,9 @@logs = [...logs, ...fresh];loadedPages += 1;total = response.pagination.total;- } catch (e: any) {+ } catch (e) {console.error(e);- loadMoreError = e.message || 'Failed to load more logs';+ loadMoreError = getErrorMessage(e) || 'Failed to load more logs';} finally {loadingMore = false;}@@ -808,9 +809,8 @@</script><div class="space-y-4">- <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">- <h2 class="text-3xl font-semibold tracking-tight">Logs</h2>- <div class="flex w-full items-center gap-2 sm:w-auto">+ <PageHeader title="Logs">+ {#snippet actions()}{#if selectedPreset === null}<Tooltip.Root><!-- buttonVariants sets aria-disabled:pointer-events-none, which would@@ -818,7 +818,7 @@<Tooltip.Triggerclass="{buttonVariants({variant: 'outline'- })} shrink-0 !pointer-events-auto !cursor-not-allowed opacity-50"+ })} !pointer-events-auto shrink-0 !cursor-not-allowed opacity-50"aria-disabled="true"><Play class="h-4 w-4" />@@ -849,36 +849,24 @@bind:preset={selectedPreset}onApply={handleTimeRangeChange}/>- </div>- </div>-- <div class="flex flex-col gap-3 sm:flex-row sm:items-start">- <div class="flex-1">- <SearchBar- placeholder="Search logs..."- bind:value={searchQuery}- bind:typeValue={searchType}- typeOptions={searchTypeOptions}- onSearch={handleSearch}- disabled={loading}- >- <Select.Root- type="single"- value={String(minSeverity)}- onValueChange={handleSeverityChange}- >- <Select.Trigger class="h-9 w-[130px] rounded-none border-r-0 shadow-none">- {severityTriggerLabel}- </Select.Trigger>- <Select.Content>- {#each severityOptions as opt (opt.value)}- <Select.Item value={opt.value} label={opt.label}>{opt.label}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- </SearchBar>- </div>- </div>+ {/snippet}+ </PageHeader>++ <SearchBar+ placeholder="Search logs..."+ bind:value={searchQuery}+ bind:typeValue={searchType}+ typeOptions={searchTypeOptions}+ onSearch={handleSearch}+ disabled={loading}+ >+ <ToolbarSelect+ value={String(minSeverity)}+ options={severityOptions}+ class="w-[130px]"+ onChange={handleSeverityChange}+ />+ </SearchBar><div class="flex flex-wrap items-center gap-2"><button@@ -891,7 +879,9 @@Add filter</button>{#each metaFilterChips as chip (chip.field)}- <span class="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs font-mono">+ <span+ class="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 font-mono text-xs"+ ><Tooltip.Root><Tooltip.Trigger class="inline-flex cursor-default items-center gap-1"><span class="text-muted-foreground">{chip.label}</span>@@ -912,7 +902,7 @@{/each}{#each attributeFilters as f, i (i)}<span- class="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs font-mono"+ class="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 font-mono text-xs"><buttontype="button"@@ -948,16 +938,14 @@</AlertDialog.Description></AlertDialog.Header><div class="flex flex-col gap-3">- <label class="flex flex-col gap-1 text-sm">- <span class="font-medium">Attribute key</span>+ <FormField label="Attribute key"><Inputplaceholder="resource.service.name"bind:value={dialogKey}onkeydown={handleDialogKeydown}/>- </label>- <div class="flex flex-col gap-1 text-sm">- <span class="font-medium">Operator</span>+ </FormField>+ <FormField label="Operator"><Select.Roottype="single"value={dialogOperator}@@ -978,15 +966,14 @@{/each}</Select.Content></Select.Root>- </div>- <label class="flex flex-col gap-1 text-sm">- <span class="font-medium">Value</span>+ </FormField>+ <FormField label="Value"><Inputplaceholder="backend-service"bind:value={dialogValue}onkeydown={handleDialogKeydown}/>- </label>+ </FormField>{#if dialogError}<p class="text-xs text-red-500">{dialogError}</p>{/if}@@ -1004,146 +991,146 @@</AlertDialog.Content></AlertDialog.Root>- <div class="overflow-hidden rounded-md border">+ <TableContainer><divbind:this={scrollEl}bind:clientHeight={viewportH}onscroll={() => (scrollTop = scrollEl?.scrollTop ?? 0)}class="overflow-auto [&_[data-slot=table-container]]:overflow-visible">- <Table.Root>- {#if loading}- <Table.Body>- <Table.Row>- <Table.Cell colspan={5} class="h-48">- <div class="flex h-full items-center justify-center">- <LoadingCircle size="xlg" />- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if error}- <Table.Body>- <Table.Row>- <Table.Cell colspan={5} class="h-24 text-center text-red-500">- {error}- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if logs.length === 0}- <Table.Body>- <TableEmptyState colspan={5} message="No logs found." />- </Table.Body>- {:else}- <!-- Solid thead bg so rows can't show through the translucent th+ <Table.Root>+ {#if loading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={5} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if error}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={5} class="h-24 text-center text-red-500">+ {error}+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if logs.length === 0}+ <Table.Body>+ <TableEmptyState colspan={5} message="No logs found." />+ </Table.Body>+ {:else}+ <!-- Solid thead bg so rows can't show through the translucent thbg-muted/60 while it is sticky; the th keeps its own darkerbackground on top, same look as the endpoints table. -->- <Table.Header class="sticky top-0 z-10 bg-background">- <Table.Row>- <TracewayTableHeader- label="Timestamp"- tooltip="Log event time"- class="w-[180px]"- sortField="timestamp"- currentSortField={sortField}- {sortDirection}- onSort={handleSort}- />- <TracewayTableHeader- label="Level"- tooltip="Log severity"- class="w-[90px]"- sortField="severity_number"- currentSortField={sortField}- {sortDirection}- onSort={handleSort}- />- <TracewayTableHeader label="Message" tooltip="Log body (click row to expand)" />- <TracewayTableHeader- label="Service"- tooltip="Emitting service"- class="w-[160px]"- sortField="service_name"- currentSortField={sortField}- {sortDirection}- onSort={handleSort}- />- <TracewayTableHeader- label="Trace"- tooltip="Linked trace ID (if present)"- class="w-[110px]"- />- </Table.Row>- </Table.Header>- <Table.Body>- {#if topPad > 0}- <tr aria-hidden="true" style="height: {topPad}px"></tr>- {/if}- {#each visibleLogs as log (log.id)}- <Table.Row- data-log-id={log.id}- class="group cursor-pointer hover:bg-muted/50"- onclick={() => toggleExpanded(log.id)}- >- <Table.Cell class="text-muted-foreground tabular-nums">- {formatDateTime(log.timestamp, { timezone })}- </Table.Cell>- <Table.Cell>- <SeverityBadge- severityText={log.severityText}- severityNumber={log.severityNumber}+ <Table.Header class="sticky top-0 z-10 bg-background">+ <Table.Row>+ <TracewayTableHeader+ label="Timestamp"+ tooltip="Log event time"+ class="w-[180px]"+ sortField="timestamp"+ currentSortField={sortField}+ {sortDirection}+ onSort={handleSort}+ />+ <TracewayTableHeader+ label="Level"+ tooltip="Log severity"+ class="w-[90px]"+ sortField="severity_number"+ currentSortField={sortField}+ {sortDirection}+ onSort={handleSort}+ />+ <TracewayTableHeader label="Message" tooltip="Log body (click row to expand)" />+ <TracewayTableHeader+ label="Service"+ tooltip="Emitting service"+ class="w-[160px]"+ sortField="service_name"+ currentSortField={sortField}+ {sortDirection}+ onSort={handleSort}+ />+ <TracewayTableHeader+ label="Trace"+ tooltip="Linked trace ID (if present)"+ class="w-[110px]"+ />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#if topPad > 0}+ <tr aria-hidden="true" style="height: {topPad}px"></tr>+ {/if}+ {#each visibleLogs as log (log.id)}+ <Table.Row+ data-log-id={log.id}+ class="group cursor-pointer"+ onclick={() => toggleExpanded(log.id)}+ >+ <Table.Cell class="text-muted-foreground tabular-nums">+ {formatDateTime(log.timestamp, { timezone })}+ </Table.Cell>+ <Table.Cell>+ <SeverityBadge+ severityText={log.severityText}+ severityNumber={log.severityNumber}+ />+ </Table.Cell>+ <Table.Cell class="max-w-[600px] truncate font-mono text-sm">+ <LogMessage body={log.body} attributes={log.logAttributes} />+ </Table.Cell>+ <Table.Cell class="truncate text-muted-foreground">+ {log.serviceName || '—'}+ </Table.Cell>+ <Table.Cell class="font-mono text-xs">+ {#if log.traceId}+ <span class="text-muted-foreground" title={log.traceId}>+ {log.traceId.slice(0, 8)}…+ </span>+ {:else}+ <span class="text-muted-foreground">—</span>+ {/if}+ </Table.Cell>+ </Table.Row>+ {#if expandedId === log.id}+ <ExpandedLogRow+ {log}+ colspan={5}+ filterStateFor={attributeFilterState}+ onFilterToggle={toggleAttributeFilter}+ metaFilterStateFor={metaFilterState}+ onMetaFilterToggle={toggleMetaFilter}/>- </Table.Cell>- <Table.Cell class="max-w-[600px] truncate font-mono text-sm">- <LogMessage body={log.body} attributes={log.logAttributes} />- </Table.Cell>- <Table.Cell class="truncate text-muted-foreground">- {log.serviceName || '—'}- </Table.Cell>- <Table.Cell class="font-mono text-xs">- {#if log.traceId}- <span class="text-muted-foreground" title={log.traceId}>- {log.traceId.slice(0, 8)}…+ {/if}+ {/each}+ {#if bottomPad > 0}+ <tr aria-hidden="true" style="height: {bottomPad}px"></tr>+ {/if}+ <Table.Row>+ <Table.Cell colspan={5}>+ <div class="flex items-center justify-center gap-3 py-1">+ {#if logs.length < displayTotal}+ <Button variant="outline" size="sm" onclick={loadMore} disabled={loadingMore}>+ {loadingMore ? 'Loading…' : `Load ${pageSize} more`}+ </Button>+ {/if}+ {#if loadMoreError}+ <span class="text-xs text-red-500">{loadMoreError}</span>+ {/if}+ <span class="text-xs text-muted-foreground">+ Showing {logs.length.toLocaleString()} of {displayTotal.toLocaleString()} logs</span>- {:else}- <span class="text-muted-foreground">—</span>- {/if}+ </div></Table.Cell></Table.Row>- {#if expandedId === log.id}- <ExpandedLogRow- {log}- colspan={5}- filterStateFor={attributeFilterState}- onFilterToggle={toggleAttributeFilter}- metaFilterStateFor={metaFilterState}- onMetaFilterToggle={toggleMetaFilter}- />- {/if}- {/each}- {#if bottomPad > 0}- <tr aria-hidden="true" style="height: {bottomPad}px"></tr>- {/if}- <Table.Row class="hover:bg-transparent">- <Table.Cell colspan={5}>- <div class="flex items-center justify-center gap-3 py-1">- {#if logs.length < displayTotal}- <Button variant="outline" size="sm" onclick={loadMore} disabled={loadingMore}>- {loadingMore ? 'Loading…' : `Load ${pageSize} more`}- </Button>- {/if}- {#if loadMoreError}- <span class="text-xs text-red-500">{loadMoreError}</span>- {/if}- <span class="text-xs text-muted-foreground">- Showing {logs.length.toLocaleString()} of {displayTotal.toLocaleString()} logs- </span>- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {/if}- </Table.Root>+ </Table.Body>+ {/if}+ </Table.Root></div>- </div>+ </TableContainer></div>diff --git a/frontend/src/routes/monitors/+page.svelte b/frontend/src/routes/monitors/+page.svelteindex 1c0940d9..2cc5a0c6 100644--- a/frontend/src/routes/monitors/+page.svelte+++ b/frontend/src/routes/monitors/+page.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import { getErrorMessage } from '$lib/utils/errors';import { onMount, onDestroy } from 'svelte';import { api } from '$lib/api';import { formatDurationMs } from '$lib/utils/formatters';@@ -8,21 +9,24 @@import { TableEmptyState } from '$lib/components/ui/table-empty-state';import { SearchBar } from '$lib/components/ui/search-bar';import InfoCallout from '$lib/components/traceway/info-callout.svelte';- import TabsRow from '$lib/components/traceway/tabs-row.svelte';+ import PageTabs from '$lib/components/traceway/page-tabs.svelte';import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';import CheckStatusBadge from '$lib/components/synthetics/check-status-badge.svelte';import MonitorTypeBadge from '$lib/components/synthetics/monitor-type-badge.svelte';import MonitorSheet from './monitor-sheet.svelte';import StatusPagesTab from './status-pages-tab.svelte';+ import PostMortemsTab from './post-mortems-tab.svelte';import { browser } from '$app/environment';import { page } from '$app/state';- import { goto } from '$app/navigation';import { projectsState } from '$lib/state/projects.svelte';+ import { authState } from '$lib/state/auth.svelte';import { monitorsState, type CheckOverview } from '$lib/state/monitors.svelte';import { createRowClickHandler } from '$lib/utils/navigation';import { resolve } from '$app/paths';- import PageHeader from '$lib/components/issues/page-header.svelte';- import { updateUrl } from '$lib/utils/url-params';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import { updateUrl, setTabParam } from '$lib/utils/url-params';+ import { uptimeClass } from '$lib/utils/uptime';import {getSortState,setSortState,@@ -44,35 +48,38 @@let dialogOpen = $state(false);let statusPagesTab = $state<{ openCreate: () => void } | null>(null);+ let postMortemsTab = $state<{ openCreate: () => void } | null>(null);const TABS = $derived([{ value: 'monitors', label: 'Monitors' },...(projectsState.canManageCurrentProject? [{ value: 'status-pages', label: 'Status Pages' }]- : [])+ : []),+ { value: 'post-mortems', label: 'Post-Mortems' }]);const tabDescriptions: Record<string, string> = {monitors:'Monitors probe your services from the outside on a schedule: an HTTP request, a TCP connect, or a full browser flow. A monitor goes down only after the configured number of consecutive failures.','status-pages':- 'A status page publishes the uptime of selected monitors at /status/<slug> with no login required. Brand it with your title and logo, and optionally serve it from your own domain via a CNAME.'+ 'A status page publishes the uptime of selected monitors at /status/<slug> with no login required. Brand it with your title and logo, and optionally serve it from your own domain via a CNAME.',+ 'post-mortems':+ 'Post-mortems are internal write-ups of incidents: what happened, why, and what changes. Tag them and search past write-ups when a similar incident hits again. They never appear on public status pages.'};+ const canWritePostMortems = $derived.by(() => {+ const orgId = projectsState.currentProject?.organizationId;+ if (!orgId) return false;+ return authState.canWriteOrganization(orgId);+ });+const activeTab = $derived.by(() => {const tab = page.url.searchParams.get('tab') || 'monitors';return TABS.some((t) => t.value === tab) ? tab : 'monitors';});function setTab(tab: string) {- const url = new URL(window.location.href);- if (tab === 'monitors') {- url.searchParams.delete('tab');- } else {- url.searchParams.set('tab', tab);- url.searchParams.delete('search');- }- goto(url.toString(), { replaceState: true, noScroll: true });+ setTabParam(tab, { clear: tab === 'monitors' ? [] : ['search'] });if (tab === 'monitors') {loadData(false);}@@ -87,6 +94,11 @@if (activeTab === 'status-pages') {return { label: 'New Status Page', onclick: () => statusPagesTab?.openCreate() };}+ if (activeTab === 'post-mortems') {+ return canWritePostMortems+ ? { label: 'New Post-Mortem', onclick: () => postMortemsTab?.openCreate() }+ : null;+ }return null;});@@ -137,9 +149,9 @@);checks = response.checks || [];monitorsState.refreshDownCount();- } catch (e: any) {+ } catch (e) {console.error(e);- error = e.message || 'Failed to load data';+ error = getErrorMessage(e) || 'Failed to load data';} finally {loading = false;}@@ -213,12 +225,6 @@return `${Math.floor(diffHours / 24)}d ago`;}- function uptimeClass(uptime: number): string {- if (uptime >= 99.9) return 'text-green-600 dark:text-green-400';- if (uptime >= 99) return '';- return 'text-red-600 dark:text-red-400';- }-onMount(() => {window.addEventListener('popstate', handlePopState);if (activeTab === 'monitors') {@@ -236,7 +242,7 @@<div class="space-y-4"><PageHeader title="Monitors" />- <TabsRow+ <PageTabstabs={TABS}{activeTab}onTabChange={setTab}@@ -273,7 +279,7 @@<EmptyState message="No monitors yet." />{/if}{:else}- <div class="overflow-hidden rounded-md border">+ <TableContainer minWidth="820px"><Table.Root>{#if visibleChecks.length === 0}<Table.Body>@@ -336,15 +342,17 @@</Table.Row></Table.Header><Table.Body>- {#each visibleChecks as check}+ {#each visibleChecks as check, __index (__index)}{@const uptime = uptimePct(check)}<Table.Row- class="cursor-pointer hover:bg-muted/50"+ class="cursor-pointer"onclick={createRowClickHandler(resolve(`/monitors/${check.id}`))}>- <Table.Cell class="max-w-[40%] font-medium break-all whitespace-normal">+ <Table.Cell class="font-medium whitespace-normal">{check.name}- <div class="mt-0.5 font-mono text-xs font-normal text-muted-foreground">+ <div+ class="mt-0.5 max-w-[420px] truncate font-mono text-xs font-normal text-muted-foreground"+ >{#if check.checkType === 'http'}{check.config?.method || 'GET'}{check.config?.url}@@ -397,10 +405,12 @@</Table.Body>{/if}</Table.Root>- </div>+ </TableContainer>{/if}{:else if activeTab === 'status-pages'}<StatusPagesTab bind:this={statusPagesTab} />+ {:else if activeTab === 'post-mortems'}+ <PostMortemsTab bind:this={postMortemsTab} />{/if}</div>diff --git a/frontend/src/routes/monitors/[checkId]/+page.svelte b/frontend/src/routes/monitors/[checkId]/+page.svelteindex ec671767..706153bf 100644--- a/frontend/src/routes/monitors/[checkId]/+page.svelte+++ b/frontend/src/routes/monitors/[checkId]/+page.svelte@@ -1,13 +1,13 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';import { onMount } from 'svelte';+ import { SvelteURLSearchParams } from 'svelte/reactivity';import { api } from '$lib/api';- import { formatDurationMs } from '$lib/utils/formatters';+ import { formatDurationMs, formatDateTime } from '$lib/utils/formatters';import * as Table from '$lib/components/ui/table';import * as Card from '$lib/components/ui/card';import * as AlertDialog from '$lib/components/ui/alert-dialog';- import * as Select from '$lib/components/ui/select';import { Button } from '$lib/components/ui/button';- import { Badge } from '$lib/components/ui/badge';import { LoadingCircle } from '$lib/components/ui/loading-circle';import { ErrorDisplay } from '$lib/components/ui/error-display';import { TableEmptyState } from '$lib/components/ui/table-empty-state';@@ -15,14 +15,24 @@import CheckStatusBadge from '$lib/components/synthetics/check-status-badge.svelte';import MonitorTypeBadge from '$lib/components/synthetics/monitor-type-badge.svelte';import MonitorSheet from '../monitor-sheet.svelte';+ import NewPostMortemDialog from '../new-post-mortem-dialog.svelte';import D3LineChart from '$lib/components/dashboard/d3-line-chart.svelte';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import StatRow from '$lib/components/traceway/stat-row.svelte';+ import StatTile from '$lib/components/traceway/stat-tile.svelte';+ import StatusPill from '$lib/components/traceway/status-pill.svelte';+ import ChartCard from '$lib/components/traceway/chart-card.svelte';+ import ToolbarSelect from '$lib/components/traceway/toolbar-select.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';+ import { uptimeClass } from '$lib/utils/uptime';import { browser } from '$app/environment';import { goto } from '$app/navigation';import { resolve } from '$app/paths';import { projectsState } from '$lib/state/projects.svelte';import {monitorsState,+ incidentDisplayTitle,type SyntheticCheck,type CheckIncident,type CheckResultEntry,@@ -30,13 +40,31 @@} from '$lib/state/monitors.svelte';import { createSmartBackHandler } from '$lib/utils/back-navigation';import { authState } from '$lib/state/auth.svelte';- import { Activity, ChartLine, Check as CheckIcon, History, Image as ImageIcon, Pause, Pencil, Play, ScrollText, Trash2, TriangleAlert } from '@lucide/svelte';+ import {+ Activity,+ ChartLine,+ FileText,+ History,+ Image as ImageIcon,+ Pause,+ Pencil,+ Play,+ ScrollText,+ Trash2,+ TriangleAlert+ } from '@lucide/svelte';import { toast } from 'svelte-sonner';let { data } = $props();const checkId = data.checkId;+ const canWritePostMortems = $derived.by(() => {+ const orgId = projectsState.currentProject?.organizationId;+ if (!orgId) return false;+ return authState.canWriteOrganization(orgId);+ });+let check = $state<SyntheticCheck | null>(null);let incidents = $state<CheckIncident[]>([]);let loading = $state(true);@@ -62,10 +90,6 @@{ value: 'down', label: 'Down' },{ value: 'missed', label: 'Missed' }];- const resultFilterLabel = $derived(- resultFilterOptions.find((o) => o.value === resultFilter)?.label || 'All results'- );-function onResultFilterChange() {page = 1;loadResults();@@ -73,6 +97,8 @@let editOpen = $state(false);let deleteOpen = $state(false);+ let newPostMortemOpen = $state(false);+ let newPostMortemIncident = $state<CheckIncident | null>(null);let deleting = $state(false);let runningNow = $state(false);let togglingPause = $state(false);@@ -116,11 +142,11 @@});check = response.check;incidents = response.incidents || [];- } catch (e: any) {- if (e.status === 404) {+ } catch (e) {+ if (getErrorStatus(e) === 404) {notFound = true;} else {- error = e.message || 'Failed to load the monitor';+ error = getErrorMessage(e) || 'Failed to load the monitor';}}}@@ -194,14 +220,14 @@{},{ projectId: projectsState.currentProjectId ?? undefined });- toast.success('Run queued', { position: 'top-center' });+ toast.success('Run queued');setTimeout(() => {loadCheck();loadResults();}, 3000);- } catch (e: any) {- if (e?.status !== 403) {- toast.error(e.message || 'Failed to queue the run', { position: 'top-center' });+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to queue the run');}} finally {runningNow = false;@@ -227,9 +253,9 @@);check = response;toast.success('Successfully updated the Monitor', { position: 'top-center' });- } catch (e: any) {- if (e?.status !== 403) {- toast.error(e.message || 'Failed to update the monitor', { position: 'top-center' });+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to update the monitor');}} finally {togglingPause = false;@@ -242,12 +268,12 @@await api.delete(`/synthetics/checks/${checkId}`, {projectId: projectsState.currentProjectId ?? undefined});- toast.success('Successfully deleted the Monitor', { position: 'top-center' });+ toast.success('Successfully deleted the Monitor');monitorsState.refreshDownCount();goto(resolve('/monitors'));- } catch (e: any) {- if (e?.status !== 403) {- toast.error(e.message || 'Failed to delete the monitor', { position: 'top-center' });+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to delete the monitor');}deleting = false;deleteOpen = false;@@ -289,7 +315,11 @@const stepMs = calculateInterval(rangeFrom, rangeTo) * 60000;const byBucket = new Map(series.map((p) => [new Date(p.bucket).getTime(), p]));const cells: CheckSeriesPoint[] = [];- for (let t = Math.floor(fromMs / stepMs) * stepMs; t <= toMs && cells.length < 400; t += stepMs) {+ for (+ let t = Math.floor(fromMs / stepMs) * stepMs;+ t <= toMs && cells.length < 400;+ t += stepMs+ ) {cells.push(byBucket.get(t) ?? {bucket: new Date(t).toISOString(),@@ -314,15 +344,11 @@function bucketTitle(point: CheckSeriesPoint): string {const measured = point.total - point.missed;- const when = new Date(point.bucket).toLocaleString();+ const when = formatDateTime(point.bucket, { format: 'short' });if (measured === 0) return `${when}: no data`;return `${when}: ${point.up}/${measured} up${point.missed > 0 ? `, ${point.missed} missed` : ''}`;}- function formatTime(iso: string): string {- return new Date(iso).toLocaleString();- }-let screenshotOpen = $state(false);let screenshotUrl = $state('');let screenshotLoading = $state(false);@@ -335,7 +361,7 @@screenshotUrl = '';}try {- const params = new URLSearchParams({ key });+ const params = new SvelteURLSearchParams({ key });if (projectsState.currentProjectId) {params.set('projectId', projectsState.currentProjectId);}@@ -346,7 +372,7 @@screenshotUrl = URL.createObjectURL(await response.blob());} catch {screenshotOpen = false;- toast.error('Failed to load the screenshot', { position: 'top-center' });+ toast.error('Failed to load the screenshot');} finally {screenshotLoading = false;}@@ -373,7 +399,7 @@outputLoading = true;outputText = '';try {- const params = new URLSearchParams({ key });+ const params = new SvelteURLSearchParams({ key });if (projectsState.currentProjectId) {params.set('projectId', projectsState.currentProjectId);}@@ -384,7 +410,7 @@outputText = await response.text();} catch {outputOpen = false;- toast.error('Failed to load the run output', { position: 'top-center' });+ toast.error('Failed to load the run output');} finally {outputLoading = false;}@@ -431,285 +457,245 @@/>{:else if check}<div class="space-y-4">- <div class="flex items-center justify-between gap-4">- <PageHeader- title={check.name}- onBack={createSmartBackHandler({ fallbackPath: '/monitors' })}- />- <span class="shrink-0 text-sm text-muted-foreground">Last {WINDOW_DAYS} days</span>- </div>-- <div class="flex flex-wrap items-center gap-3">- <CheckStatusBadge status={check.currentStatus} enabled={check.enabled} />- <MonitorTypeBadge type={check.checkType} />- <span class="min-w-0 font-mono text-sm break-all text-muted-foreground">- {#if check.checkType === 'http'}- {check.config?.method || 'GET'} {check.config?.url}- {:else if check.checkType === 'tcp'}- {check.config?.host}:{check.config?.port}+ <PageHeader title={check.name} onBack={createSmartBackHandler({ fallbackPath: '/monitors' })}>+ {#snippet meta()}+ {#if check}+ <CheckStatusBadge status={check.currentStatus} enabled={check.enabled} />+ <MonitorTypeBadge type={check.checkType} />+ <span class="min-w-0 font-mono text-sm break-all text-muted-foreground">+ {#if check.checkType === 'http'}+ {check.config?.method || 'GET'} {check.config?.url}+ {:else if check.checkType === 'tcp'}+ {check.config?.host}:{check.config?.port}+ {/if}+ </span>+ <span class="text-sm text-muted-foreground">Last {WINDOW_DAYS} days</span>{/if}- </span>- <div class="flex-1"></div>- {#if projectsState.canWriteCurrentProject}- <Button variant="outline" size="sm" onclick={runNow} disabled={runningNow || !check.enabled}>- <Play class="mr-1.5 h-4 w-4" />- {runningNow ? 'Queueing...' : 'Run now'}- </Button>- <Button variant="outline" size="sm" onclick={togglePause} disabled={togglingPause}>- {#if check.enabled}- <Pause class="mr-1.5 h-4 w-4" />- Pause- {:else}- <Play class="mr-1.5 h-4 w-4" />- Resume- {/if}- </Button>- <Button variant="outline" size="sm" onclick={() => (editOpen = true)}>- <Pencil class="mr-1.5 h-4 w-4" />- Edit- </Button>- <Button variant="destructiveOutline" size="sm" onclick={() => (deleteOpen = true)}>- <Trash2 class="mr-1.5 h-4 w-4" />- Delete- </Button>- {/if}- </div>-- <Card.Root class="py-0">- <div class="grid grid-cols-2 divide-y divide-border sm:grid-cols-4 sm:divide-x sm:divide-y-0">- <div class="px-6 py-4">- <div class="text-xs font-medium text-muted-foreground">Uptime</div>- <div- class="mt-1 text-2xl font-semibold tabular-nums {rangeAggregates.uptime === null- ? 'text-muted-foreground'- : rangeAggregates.uptime >= 99.9- ? 'text-green-600 dark:text-green-400'- : rangeAggregates.uptime >= 99- ? ''- : 'text-red-600 dark:text-red-400'}"+ {/snippet}+ {#snippet actions()}+ {#if check && projectsState.canWriteCurrentProject}+ <Button+ variant="outline"+ size="sm"+ onclick={runNow}+ disabled={runningNow || !check.enabled}>- {rangeAggregates.uptime === null- ? '—'- : `${rangeAggregates.uptime.toFixed(rangeAggregates.uptime === 100 ? 0 : 2)}%`}- </div>- </div>- <div class="px-6 py-4">- <div class="text-xs font-medium text-muted-foreground">Avg latency</div>- <div class="mt-1 text-2xl font-semibold tabular-nums">- {rangeAggregates.avgLatency === null ? '—' : formatDurationMs(rangeAggregates.avgLatency)}- </div>- </div>- <div class="px-6 py-4">- <div class="text-xs font-medium text-muted-foreground">Interval</div>- <div class="mt-1 text-2xl font-semibold tabular-nums">- {check.intervalSeconds >= 3600- ? `${check.intervalSeconds / 3600}h`- : check.intervalSeconds >= 60- ? `${check.intervalSeconds / 60}m`- : `${check.intervalSeconds}s`}- </div>- </div>- <div class="px-6 py-4">- <div class="text-xs font-medium text-muted-foreground">Incidents (recent)</div>+ <Play class="mr-2 h-4 w-4" />+ {runningNow ? 'Queueing...' : 'Run now'}+ </Button>+ <Button variant="outline" size="sm" onclick={togglePause} disabled={togglingPause}>+ {#if check.enabled}+ <Pause class="mr-2 h-4 w-4" />+ Pause+ {:else}+ <Play class="mr-2 h-4 w-4" />+ Resume+ {/if}+ </Button>+ <Button variant="outline" size="sm" onclick={() => (editOpen = true)}>+ <Pencil class="mr-2 h-4 w-4" />+ Edit+ </Button>+ <Button variant="destructiveOutline" size="sm" onclick={() => (deleteOpen = true)}>+ <Trash2 class="mr-2 h-4 w-4" />+ Delete+ </Button>+ {/if}+ {/snippet}+ </PageHeader>++ <StatRow columns={4}>+ <StatTile+ label="Uptime"+ value={rangeAggregates.uptime === null+ ? '—'+ : `${rangeAggregates.uptime.toFixed(rangeAggregates.uptime === 100 ? 0 : 2)}%`}+ valueClass={rangeAggregates.uptime === null+ ? 'text-muted-foreground'+ : uptimeClass(rangeAggregates.uptime)}+ />+ <StatTile+ label="Avg latency"+ value={rangeAggregates.avgLatency === null+ ? '—'+ : formatDurationMs(rangeAggregates.avgLatency)}+ />+ <StatTile+ label="Interval"+ value={check.intervalSeconds >= 3600+ ? `${check.intervalSeconds / 3600}h`+ : check.intervalSeconds >= 60+ ? `${check.intervalSeconds / 60}m`+ : `${check.intervalSeconds}s`}+ />+ <StatTile+ label="Incidents (recent)"+ value={incidents.length}+ valueClass={incidents.some((i) => !i.resolvedAt) ? 'text-red-600 dark:text-red-400' : ''}+ />+ </StatRow>++ <ChartCard+ title="Availability"+ loading={seriesLoading}+ empty={series.length === 0}+ emptyMessage="No probe data in the last {WINDOW_DAYS} days"+ height={64}+ >+ {#snippet icon()}+ <Activity class="h-3.5 w-3.5 text-muted-foreground" />+ {/snippet}+ <div class="flex h-9 items-stretch gap-[3px]">+ {#each paddedSeries as point, __index (__index)}<div- class="mt-1 text-2xl font-semibold tabular-nums {incidents.some((i) => !i.resolvedAt)- ? 'text-red-600 dark:text-red-400'- : ''}"- >- {incidents.length}- </div>- </div>+ class="min-w-0 flex-1 rounded-[3px] transition-transform hover:scale-y-110 {bucketClass(+ point+ )}"+ title={bucketTitle(point)}+ ></div>+ {/each}</div>- </Card.Root>-- <Card.Root class="pt-2 gap-3">- <Card.Header class="border-b [.border-b]:pb-2 pl-3">- <Card.Title class="flex items-center gap-2 text-base font-medium">- <Activity class="h-3.5 w-3.5 text-muted-foreground" />- <span class="text-sm font-[400] text-muted-foreground">Availability</span>- </Card.Title>- </Card.Header>- <Card.Content class="pb-4">- {#if seriesLoading}- <div class="flex h-16 items-center justify-center">- <LoadingCircle />- </div>- {:else if series.length === 0}- <div class="flex h-16 items-center justify-center text-sm text-muted-foreground">- No probe data in the last {WINDOW_DAYS} days- </div>- {:else}- <div class="flex h-9 items-stretch gap-[3px]">- {#each paddedSeries as point}- <div- class="min-w-0 flex-1 rounded-[3px] transition-transform hover:scale-y-110 {bucketClass(- point- )}"- title={bucketTitle(point)}- ></div>- {/each}- </div>- <div class="mt-1.5 flex justify-between text-xs text-muted-foreground">- <span>{new Date(paddedSeries[0].bucket).toLocaleString()}</span>- <span>Now</span>- </div>- {/if}- </Card.Content>- </Card.Root>-- <Card.Root class="pt-2 gap-3">- <Card.Header class="border-b [.border-b]:pb-2 pl-3">- <Card.Title class="flex items-center gap-2 text-base font-medium">- <ChartLine class="h-3.5 w-3.5 text-muted-foreground" />- <span class="text-sm font-[400] text-muted-foreground">Latency</span>- </Card.Title>- </Card.Header>- <Card.Content>- {#if seriesLoading}- <div class="flex h-[220px] items-center justify-center">- <LoadingCircle size="xlg" />- </div>- {:else if latencySeries[0].data.length === 0}- <div class="flex h-[220px] items-center justify-center text-sm text-muted-foreground">- No latency data in the last {WINDOW_DAYS} days- </div>- {:else}- <D3LineChart series={latencySeries} formatValue={formatDurationMs} unit="ms" />- {/if}- </Card.Content>- </Card.Root>+ <div class="mt-1.5 flex justify-between text-xs text-muted-foreground">+ <span>{formatDateTime(paddedSeries[0].bucket, { format: 'short' })}</span>+ <span>Now</span>+ </div>+ </ChartCard>++ <ChartCard+ title="Latency"+ loading={seriesLoading}+ empty={latencySeries[0].data.length === 0}+ emptyMessage="No latency data in the last {WINDOW_DAYS} days"+ >+ {#snippet icon()}+ <ChartLine class="h-3.5 w-3.5 text-muted-foreground" />+ {/snippet}+ <D3LineChart series={latencySeries} formatValue={formatDurationMs} unit="ms" />+ </ChartCard><Card.Root class="gap-0 pt-2 pb-0"><Card.Header- class="flex flex-row flex-wrap items-center justify-between gap-3 space-y-0 border-b [.border-b]:pb-2 pl-3"+ class="flex flex-row flex-wrap items-center justify-between gap-3 space-y-0 border-b pl-3 [.border-b]:pb-2"><Card.Title class="flex items-center gap-2 text-base font-medium"><History class="h-3.5 w-3.5 text-muted-foreground" /><span class="text-sm font-[400] text-muted-foreground">Run history</span></Card.Title>- <Select.Root type="single" bind:value={resultFilter} onValueChange={onResultFilterChange}>- <Select.Trigger class="h-8 w-[130px] text-xs">{resultFilterLabel}</Select.Trigger>- <Select.Content>- {#each resultFilterOptions as option}- <Select.Item value={option.value}>{option.label}</Select.Item>- {/each}- </Select.Content>- </Select.Root>+ <ToolbarSelect+ bind:value={resultFilter}+ options={resultFilterOptions}+ class="w-[130px]"+ onChange={onResultFilterChange}+ /></Card.Header><Card.Content class="overflow-hidden rounded-b-xl p-0">- <Table.Root>- {#if resultsLoading}- <Table.Body>- <Table.Row>- <Table.Cell colspan={runHistoryColumns} class="h-32">- <div class="flex h-full items-center justify-center">- <LoadingCircle size="xlg" />- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if results.length === 0}- <Table.Body>- <TableEmptyState colspan={runHistoryColumns} message="No runs in the last {WINDOW_DAYS} days" />- </Table.Body>- {:else}- <Table.Header>- <Table.Row>- <Table.Head>Time</Table.Head>- <Table.Head class="w-[100px]">Result</Table.Head>- <Table.Head class="w-[110px]">Latency</Table.Head>- {#if !isBrowserCheck}- <Table.Head class="w-[90px]">Status code</Table.Head>- {/if}- <Table.Head>Error</Table.Head>- {#if isBrowserCheck}- <Table.Head class="w-[44px]"><span class="sr-only">Screenshot</span></Table.Head>- <Table.Head class="w-[44px]"><span class="sr-only">Logs</span></Table.Head>- {/if}- </Table.Row>- </Table.Header>- <Table.Body>- {#each results as result}- <Table.Row>- <Table.Cell class="text-sm whitespace-nowrap">- {formatTime(result.recordedAt)}- <span class="ml-1 text-xs text-muted-foreground">via {result.executedBy}</span>- </Table.Cell>- <Table.Cell>- {#if result.status === 'up'}- <span- class="inline-flex items-center gap-1 rounded-full bg-green-500/15 px-2 py-0.5 text-xs font-medium text-green-600 dark:text-green-400"- >- <CheckIcon class="h-3 w-3" />- Up- </span>- {:else if result.status === 'down'}- <span- class="inline-flex items-center rounded-full bg-red-500/15 px-2 py-0.5 text-xs font-medium text-red-600 dark:text-red-400"- >- Down- </span>- {:else}- <span- class="inline-flex items-center rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground"- >- Missed- </span>- {/if}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums text-muted-foreground">- {result.status === 'missed' ? '—' : formatDurationMs(result.latencyMs)}- </Table.Cell>- {#if !isBrowserCheck}- <Table.Cell class="font-mono text-sm tabular-nums text-muted-foreground">- {result.statusCode > 0 ? result.statusCode : '—'}+ <TableContainer class="rounded-none border-0" minWidth="640px">+ <Table.Root>+ {#if resultsLoading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={runHistoryColumns} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div></Table.Cell>- {/if}- <Table.Cell class="max-w-[300px] min-w-[120px] text-xs text-muted-foreground">- {#if result.errorMessage}- <button- type="button"- class="line-clamp-2 w-full cursor-pointer text-left break-all"- title="View the full error"- onclick={() => viewError(result.errorMessage)}+ </Table.Row>+ </Table.Body>+ {:else if results.length === 0}+ <Table.Body>+ <TableEmptyState+ colspan={runHistoryColumns}+ message="No runs in the last {WINDOW_DAYS} days"+ />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <Table.Head>Time</Table.Head>+ <Table.Head class="w-[100px]">Result</Table.Head>+ <Table.Head class="w-[110px]">Latency</Table.Head>+ {#if !isBrowserCheck}+ <Table.Head class="w-[90px]">Status code</Table.Head>+ {/if}+ <Table.Head>Error</Table.Head>+ {#if isBrowserCheck}+ <Table.Head class="w-[44px]"><span class="sr-only">Screenshot</span></Table.Head>- {result.errorMessage}- </button>+ <Table.Head class="w-[44px]"><span class="sr-only">Logs</span></Table.Head>{/if}- </Table.Cell>- {#if isBrowserCheck}- <Table.Cell class="px-1 text-center">- {#if result.screenshotKey}- <Button- variant="ghost"- size="icon"- class="h-7 w-7"- title="View the screenshot"- onclick={() => viewScreenshot(result.screenshotKey)}+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each results as result, __index (__index)}+ <Table.Row>+ <Table.Cell class="text-sm whitespace-nowrap">+ {formatDateTime(result.recordedAt, { format: 'short' })}+ <span class="ml-1 text-xs text-muted-foreground">via {result.executedBy}</span>- <ImageIcon class="h-4 w-4" />- </Button>+ </Table.Cell>+ <Table.Cell>+ {#if result.status === 'up'}+ <StatusPill tone="success" dot label="Up" />+ {:else if result.status === 'down'}+ <StatusPill tone="danger" label="Down" />+ {:else}+ <StatusPill tone="neutral" label="Missed" />+ {/if}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground tabular-nums">+ {result.status === 'missed' ? '—' : formatDurationMs(result.latencyMs)}+ </Table.Cell>+ {#if !isBrowserCheck}+ <Table.Cell class="font-mono text-sm text-muted-foreground tabular-nums">+ {result.statusCode > 0 ? result.statusCode : '—'}+ </Table.Cell>{/if}- </Table.Cell>- <Table.Cell class="px-1 text-center">- {#if result.outputKey}- <Button- variant="ghost"- size="icon"- class="h-7 w-7"- title="View the logs"- onclick={() => viewOutput(result.outputKey)}- >- <ScrollText class="h-4 w-4" />- </Button>+ <Table.Cell class="max-w-[300px] min-w-[120px] text-xs text-muted-foreground">+ {#if result.errorMessage}+ <button+ type="button"+ class="line-clamp-2 w-full cursor-pointer text-left break-all"+ title="View the full error"+ onclick={() => viewError(result.errorMessage)}+ >+ {result.errorMessage}+ </button>+ {/if}+ </Table.Cell>+ {#if isBrowserCheck}+ <Table.Cell class="px-1 text-center">+ {#if result.screenshotKey}+ <Button+ variant="ghost"+ size="icon"+ class="h-7 w-7"+ title="View the screenshot"+ onclick={() => viewScreenshot(result.screenshotKey)}+ >+ <ImageIcon class="h-4 w-4" />+ </Button>+ {/if}+ </Table.Cell>+ <Table.Cell class="px-1 text-center">+ {#if result.outputKey}+ <Button+ variant="ghost"+ size="icon"+ class="h-7 w-7"+ title="View the logs"+ onclick={() => viewOutput(result.outputKey)}+ >+ <ScrollText class="h-4 w-4" />+ </Button>+ {/if}+ </Table.Cell>{/if}- </Table.Cell>- {/if}- </Table.Row>- {/each}- </Table.Body>- {/if}- </Table.Root>+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </TableContainer></Card.Content></Card.Root>@@ -725,8 +711,8 @@/>{#if incidents.length > 0}- <Card.Root class="pt-2 gap-3">- <Card.Header class="border-b [.border-b]:pb-2 pl-3">+ <Card.Root class="gap-3 pt-2">+ <Card.Header class="border-b pl-3 [.border-b]:pb-2"><Card.Title class="flex items-center gap-2 text-base font-medium"><TriangleAlert class="h-3.5 w-3.5 text-muted-foreground" /><span class="text-sm font-[400] text-muted-foreground">Incidents</span>@@ -734,13 +720,20 @@</Card.Header><Card.Content class="pb-4"><div class="space-y-2">- {#each incidents as incident}- <div class="flex items-start justify-between gap-4 rounded-md border p-3 text-sm">+ {#each incidents as incident, __index (__index)}+ <div+ class="flex flex-col gap-2 rounded-md border p-3 text-sm sm:flex-row sm:items-start sm:justify-between sm:gap-4"+ ><div class="min-w-0">- <div class="font-medium">- {formatTime(incident.startedAt)}+ {#if incident.title}+ <div class="font-medium">{incident.title}</div>+ {/if}+ <div class={incident.title ? 'text-xs text-muted-foreground' : 'font-medium'}>+ {formatDateTime(incident.startedAt, { format: 'short' })}{#if incident.resolvedAt}- <span class="text-muted-foreground">→ {formatTime(incident.resolvedAt)}</span>+ <span class="text-muted-foreground">+ → {formatDateTime(incident.resolvedAt, { format: 'short' })}+ </span>{/if}</div>{#if incident.errorMessage}@@ -749,19 +742,34 @@</div>{/if}</div>- {#if incident.resolvedAt}- <span- class="inline-flex shrink-0 items-center rounded-full bg-green-500/15 px-2 py-0.5 text-xs font-medium text-green-600 dark:text-green-400"- >- Resolved- </span>- {:else}- <span- class="inline-flex shrink-0 items-center rounded-full bg-red-500/15 px-2 py-0.5 text-xs font-medium text-red-600 dark:text-red-400"- >- Ongoing- </span>- {/if}+ <div class="flex shrink-0 items-center gap-2">+ {#if incident.postMortemId}+ <a+ class="inline-flex items-center gap-1 text-xs text-primary underline-offset-2 hover:underline"+ href={resolve(`/monitors/post-mortems/${incident.postMortemId}`)}+ >+ <FileText class="h-3.5 w-3.5" />+ Post-mortem+ </a>+ {:else if canWritePostMortems}+ <button+ type="button"+ class="inline-flex cursor-pointer items-center gap-1 text-xs text-muted-foreground underline-offset-2 hover:text-primary hover:underline"+ onclick={() => {+ newPostMortemIncident = incident;+ newPostMortemOpen = true;+ }}+ >+ <FileText class="h-3.5 w-3.5" />+ Write post-mortem+ </button>+ {/if}+ {#if incident.resolvedAt}+ <StatusPill tone="success" label="Resolved" />+ {:else}+ <StatusPill tone="danger" label="Ongoing" />+ {/if}+ </div></div>{/each}</div>@@ -772,23 +780,21 @@<MonitorSheet bind:open={editOpen} {check} onSaved={() => loadAll()} />- <AlertDialog.Root bind:open={deleteOpen}>- <AlertDialog.Content interactOutsideBehavior={deleting ? 'ignore' : 'close'}>- <AlertDialog.Header>- <AlertDialog.Title>Delete Monitor</AlertDialog.Title>- <AlertDialog.Description>- This permanently deletes "{check.name}" along with its run history and incidents.- </AlertDialog.Description>- </AlertDialog.Header>- <AlertDialog.Footer>- <AlertDialog.Cancel disabled={deleting}>Cancel</AlertDialog.Cancel>- <Button variant="destructive" onclick={deleteCheck} disabled={deleting}>- <Trash2 class="mr-2 h-4 w-4" />- {deleting ? 'Deleting...' : 'Delete Monitor'}- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>- </AlertDialog.Root>+ <NewPostMortemDialog+ bind:open={newPostMortemOpen}+ incidentId={newPostMortemIncident?.id ?? null}+ incidentLabel={newPostMortemIncident+ ? incidentDisplayTitle({ title: newPostMortemIncident.title, checkName: check?.name ?? null })+ : ''}+ />++ <ConfirmDeleteDialog+ bind:open={deleteOpen}+ entity="Monitor"+ description={`This permanently deletes "${check.name}" along with its run history and incidents.`}+ loading={deleting}+ onConfirm={deleteCheck}+ /><AlertDialog.Root bind:open={outputOpen}><AlertDialog.Content class="sm:max-w-3xl">@@ -841,9 +847,7 @@<AlertDialog.Content class="sm:max-w-3xl"><AlertDialog.Header><AlertDialog.Title>Run error</AlertDialog.Title>- <AlertDialog.Description>- Full error message reported by this run.- </AlertDialog.Description>+ <AlertDialog.Description>Full error message reported by this run.</AlertDialog.Description></AlertDialog.Header><preclass="max-h-[60vh] overflow-auto rounded-md border bg-muted/50 p-3 font-mono text-xs break-all whitespace-pre-wrap">{errorText}</pre>diff --git a/frontend/src/routes/monitors/[checkId]/+page.ts b/frontend/src/routes/monitors/[checkId]/+page.tsindex 17cc01a0..b6b49cb8 100644--- a/frontend/src/routes/monitors/[checkId]/+page.ts+++ b/frontend/src/routes/monitors/[checkId]/+page.ts@@ -13,6 +13,9 @@ export const load: PageLoad = ({ params, url }) => {if (params.checkId === 'runners') {throw redirect(301, '/monitors');}+ if (params.checkId === 'post-mortems') {+ throw redirect(301, '/monitors?tab=post-mortems');+ }if (!authState.isAuthenticated) throw redirect(302, '/login');return {checkId: params.checkId,diff --git a/frontend/src/routes/monitors/monitor-sheet.svelte b/frontend/src/routes/monitors/monitor-sheet.svelteindex 9bff7e17..90aaebbe 100644--- a/frontend/src/routes/monitors/monitor-sheet.svelte+++ b/frontend/src/routes/monitors/monitor-sheet.svelte@@ -10,9 +10,10 @@import { ErrorAlert } from '$lib/components/ui/error-alert';import { CodeEditor } from '$lib/components/ui/code-editor';import KeyValueRows from '$lib/components/synthetics/key-value-rows.svelte';+ import { underlineTabTriggerClass, underlineTabListClass } from '$lib/utils/tabs';import { projectsState } from '$lib/state/projects.svelte';import type { SyntheticCheck, CheckConfig, CheckType } from '$lib/state/monitors.svelte';- import { Check, Globe, Plus } from '@lucide/svelte';+ import { Check, Plus } from '@lucide/svelte';import { toast } from 'svelte-sonner';interface Props {@@ -27,9 +28,6 @@let loading = $state(false);let error = $state('');- const tabTriggerClass =- '-mb-px shrink-0 rounded-none border-b-2 border-transparent bg-transparent px-0 pb-2.5 pt-0 text-sm font-medium text-muted-foreground shadow-none transition-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none';-// Common fieldslet name = $state('');let checkType = $state<CheckType>('http');@@ -342,7 +340,7 @@ test('page loads', async ({ page }) => {<Select.Root type="single" bind:value={checkType} disabled={loading || isEditing}><Select.Trigger class="w-full">{checkTypeLabel}</Select.Trigger><Select.Content>- {#each checkTypeOptions as option}+ {#each checkTypeOptions as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content>@@ -356,7 +354,7 @@ test('page loads', async ({ page }) => {<Select.Root type="single" bind:value={intervalSeconds} disabled={loading}><Select.Trigger class="w-full">{intervalLabel}</Select.Trigger><Select.Content class="max-h-64 overflow-y-auto">- {#each intervalOptions as option}+ {#each intervalOptions as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content>@@ -398,7 +396,7 @@ test('page loads', async ({ page }) => {{httpMethod}</Select.Trigger><Select.Content>- {#each methodOptions as method}+ {#each methodOptions as method, __index (__index)}<Select.Item value={method}>{method}</Select.Item>{/each}</Select.Content>@@ -413,17 +411,17 @@ test('page loads', async ({ page }) => {</div><Tabs.Root bind:value={requestTab}>- <Tabs.List- class="flex h-auto w-full items-center justify-start gap-5 rounded-none border-b bg-transparent p-0"- >- <Tabs.Trigger value="headers" class={tabTriggerClass}>+ <Tabs.List class={underlineTabListClass}>+ <Tabs.Trigger value="headers" class={underlineTabTriggerClass}>Headers{headerCount > 0 ? ` (${headerCount})` : ''}</Tabs.Trigger>- <Tabs.Trigger value="auth" class={tabTriggerClass}>+ <Tabs.Trigger value="auth" class={underlineTabTriggerClass}>Auth{authType !== 'none' ? ' •' : ''}</Tabs.Trigger>- <Tabs.Trigger value="body" class={tabTriggerClass}>Body</Tabs.Trigger>- <Tabs.Trigger value="expected" class={tabTriggerClass}>Expected results</Tabs.Trigger>+ <Tabs.Trigger value="body" class={underlineTabTriggerClass}>Body</Tabs.Trigger>+ <Tabs.Trigger value="expected" class={underlineTabTriggerClass}>+ Expected results+ </Tabs.Trigger></Tabs.List></Tabs.Root>@@ -440,7 +438,7 @@ test('page loads', async ({ page }) => {<Select.Root type="single" bind:value={authType} disabled={loading}><Select.Trigger class="w-[220px]">{authLabel}</Select.Trigger><Select.Content>- {#each authOptions as option}+ {#each authOptions as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content>@@ -503,8 +501,8 @@ test('page loads', async ({ page }) => {</div>{:else}<p class="text-sm text-muted-foreground">- {httpMethod} requests are sent without a body. Switch the method to POST, PUT, PATCH,- or DELETE to add one.+ {httpMethod} requests are sent without a body. Switch the method to POST, PUT, PATCH, or+ DELETE to add one.</p>{/if}{:else}diff --git a/frontend/src/routes/monitors/new-post-mortem-dialog.svelte b/frontend/src/routes/monitors/new-post-mortem-dialog.sveltenew file mode 100644index 00000000..90081733--- /dev/null+++ b/frontend/src/routes/monitors/new-post-mortem-dialog.svelte@@ -0,0 +1,99 @@+<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { Plus } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import { api } from '$lib/api';+ import { goto } from '$app/navigation';+ import { resolve } from '$app/paths';+ import { projectsState } from '$lib/state/projects.svelte';++ interface Props {+ open: boolean;+ incidentId?: number | null;+ incidentLabel?: string;+ }++ let { open = $bindable(), incidentId = null, incidentLabel = '' }: Props = $props();++ const projectId = $derived(projectsState.currentProjectId);++ let title = $state('');+ let saving = $state(false);+ let dialogError = $state('');++ $effect(() => {+ if (open) {+ title = '';+ dialogError = '';+ }+ });++ async function create() {+ if (projectId === null) return;+ saving = true;+ dialogError = '';+ try {+ const created = await api.post(+ '/post-mortems',+ { title, contentMd: '', tags: [], incidentId },+ { projectId: projectId ?? undefined }+ );+ toast.success('Successfully created the Post-Mortem', { position: 'top-center' });+ open = false;+ goto(resolve(`/monitors/post-mortems/${created.id}`));+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ dialogError = e instanceof Error ? getErrorMessage(e) : 'Failed to create the post-mortem';+ }+ } finally {+ saving = false;+ }+ }+</script>++<AlertDialog.Root bind:open>+ <AlertDialog.Content class="sm:max-w-md" interactOutsideBehavior={saving ? 'ignore' : 'close'}>+ <AlertDialog.Header>+ <AlertDialog.Title>New Post-Mortem</AlertDialog.Title>+ <AlertDialog.Description>+ {#if incidentId}+ Linked to: {incidentLabel || `incident #${incidentId}`}.+ {/if}+ The post-mortem is created right away; you write the document, add tags, and manage the incident+ link on the next screen.+ </AlertDialog.Description>+ </AlertDialog.Header>++ <form+ onsubmit={(e) => {+ e.preventDefault();+ create();+ }}+ class="space-y-4"+ >+ <ErrorAlert error={dialogError} />+ <div class="space-y-2">+ <Label for="new-post-mortem-title">Title</Label>+ <Input+ id="new-post-mortem-title"+ bind:value={title}+ placeholder="What went wrong, in one line"+ disabled={saving}+ />+ </div>+ </form>++ <AlertDialog.Footer>+ <AlertDialog.Cancel disabled={saving}>Cancel</AlertDialog.Cancel>+ <Button variant="success" onclick={create} disabled={saving}>+ <Plus class="mr-2 h-4 w-4" />+ {saving ? 'Creating...' : 'New Post-Mortem'}+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+</AlertDialog.Root>diff --git a/frontend/src/routes/monitors/post-mortems-tab.svelte b/frontend/src/routes/monitors/post-mortems-tab.sveltenew file mode 100644index 00000000..3c37ae19--- /dev/null+++ b/frontend/src/routes/monitors/post-mortems-tab.svelte@@ -0,0 +1,229 @@+<script lang="ts">+ import { untrack } from 'svelte';+ import { SvelteURLSearchParams } from 'svelte/reactivity';+ import * as Table from '$lib/components/ui/table';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { SearchBar } from '$lib/components/ui/search-bar';+ import { Badge } from '$lib/components/ui/badge';+ import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import NewPostMortemDialog from './new-post-mortem-dialog.svelte';+ import { FileText, Link2, X } from '@lucide/svelte';+ import { api } from '$lib/api';+ import { resolve } from '$app/paths';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { formatRelativeTimeAgo } from '$lib/utils/formatters';+ import { projectsState } from '$lib/state/projects.svelte';+ import { type PostMortemListItem } from '$lib/state/monitors.svelte';++ let items = $state<PostMortemListItem[]>([]);+ let loading = $state(true);+ let error = $state('');+ let searchQuery = $state('');+ let tagFilters = $state<string[]>([]);+ let currentPage = $state(1);+ let pageSize = $state(25);+ let total = $state(0);+ let totalPages = $state(0);++ const projectId = $derived(projectsState.currentProjectId);+ const canWrite = $derived(projectsState.canWriteCurrentProject);++ let createOpen = $state(false);++ export function openCreate() {+ createOpen = true;+ }++ let loadSeq = 0;++ async function load() {+ if (projectId === null) return;+ const seq = ++loadSeq;+ loading = true;+ error = '';+ try {+ const params = new SvelteURLSearchParams();+ if (searchQuery.trim()) params.set('search', searchQuery.trim());+ for (const tag of tagFilters) params.append('tag', tag);+ params.set('page', String(currentPage));+ params.set('pageSize', String(pageSize));+ const res = await api.get(`/post-mortems?${params}`, { projectId: projectId ?? undefined });+ if (seq !== loadSeq) return;+ items = res.data || [];+ total = res.pagination?.total || 0;+ totalPages = res.pagination?.totalPages || 0;+ } catch (e) {+ if (seq !== loadSeq) return;+ error = e instanceof Error ? e.message : 'Failed to load post-mortems';+ } finally {+ if (seq === loadSeq) loading = false;+ }+ }++ $effect(() => {+ void projectId;+ untrack(() => {+ searchQuery = '';+ tagFilters = [];+ currentPage = 1;+ load();+ });+ });++ function handleSearch() {+ currentPage = 1;+ load();+ }++ function toggleTag(tag: string) {+ tagFilters = tagFilters.includes(tag)+ ? tagFilters.filter((t) => t !== tag)+ : [...tagFilters, tag];+ currentPage = 1;+ load();+ }++ const hasFilters = $derived(searchQuery.trim() !== '' || tagFilters.length > 0);+</script>++<div class="space-y-4">+ <SearchBar+ placeholder="Search post-mortems..."+ bind:value={searchQuery}+ onSearch={handleSearch}+ disabled={loading}+ />++ {#if tagFilters.length > 0}+ <div class="flex flex-wrap items-center gap-1.5">+ {#each tagFilters as tag (tag)}+ <span+ class="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 font-mono text-xs"+ >+ <span class="text-muted-foreground">tag</span>+ <span>=</span>+ <span>{tag}</span>+ <button+ type="button"+ aria-label="Remove filter"+ class="ml-1 cursor-pointer text-muted-foreground hover:text-foreground"+ onclick={() => toggleTag(tag)}+ >+ <X class="h-3 w-3" />+ </button>+ </span>+ {/each}+ </div>+ {/if}++ {#if loading}+ <div class="flex h-48 items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ {:else if error}+ <div class="rounded-md border py-16 text-center text-red-500">{error}</div>+ {:else if items.length === 0 && !hasFilters}+ {#if canWrite}+ <EmptyState+ message="No post-mortems yet. Write one after your next incident so the lessons stick around."+ actionLabel="Write your first Post-Mortem"+ onAction={openCreate}+ />+ {:else}+ <EmptyState message="No post-mortems yet." />+ {/if}+ {:else}+ <TableContainer>+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <Table.Head>Title</Table.Head>+ <Table.Head>Tags</Table.Head>+ <Table.Head class="w-[110px]">Incident</Table.Head>+ <Table.Head class="w-[140px]">Updated</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#if items.length === 0}+ <TableEmptyState colspan={4} message="No post-mortems match your search." />+ {:else}+ {#each items as item (item.id)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(resolve(`/monitors/post-mortems/${item.id}`))}+ >+ <Table.Cell>+ <div class="flex items-center gap-2 font-medium">+ <FileText class="size-4 shrink-0 text-muted-foreground" />+ {item.title}+ </div>+ </Table.Cell>+ <Table.Cell>+ {#if item.tags.length > 0}+ <div class="flex flex-wrap gap-1">+ {#each item.tags as tag (tag)}+ <button+ type="button"+ class="cursor-pointer"+ title={`Filter by tag "${tag}"`}+ onclick={(e) => {+ e.stopPropagation();+ toggleTag(tag);+ }}+ >+ <Badge variant={tagFilters.includes(tag) ? 'default' : 'secondary'}>+ {tag}+ </Badge>+ </button>+ {/each}+ </div>+ {:else}+ <span class="text-muted-foreground">—</span>+ {/if}+ </Table.Cell>+ <Table.Cell>+ {#if item.incidentId}+ <span class="flex items-center gap-1 text-sm text-muted-foreground">+ <Link2 class="size-3.5" /> Linked+ </span>+ {:else}+ <span class="text-muted-foreground">—</span>+ {/if}+ </Table.Cell>+ <Table.Cell class="text-muted-foreground">+ <div>{formatRelativeTimeAgo(item.updatedAt)}</div>+ {#if item.updatedByName || item.createdByName}+ <div class="text-xs">by {item.updatedByName || item.createdByName}</div>+ {/if}+ </Table.Cell>+ </Table.Row>+ {/each}+ {/if}+ </Table.Body>+ </Table.Root>+ </TableContainer>++ <PaginationFooter+ {currentPage}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={(page) => {+ currentPage = page;+ load();+ }}+ onPageSizeChange={(size) => {+ pageSize = size;+ currentPage = 1;+ load();+ }}+ {loading}+ itemLabel="post-mortem"+ />+ {/if}+</div>++<NewPostMortemDialog bind:open={createOpen} />diff --git a/frontend/src/routes/monitors/post-mortems/[id]/+page.svelte b/frontend/src/routes/monitors/post-mortems/[id]/+page.sveltenew file mode 100644index 00000000..672c9393--- /dev/null+++ b/frontend/src/routes/monitors/post-mortems/[id]/+page.svelte@@ -0,0 +1,401 @@+<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';+ import { untrack } from 'svelte';+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { ErrorDisplay } from '$lib/components/ui/error-display';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';+ import TagsInput from '$lib/components/traceway/tags-input.svelte';+ import MarkdownEditor from '$lib/components/post-mortems/markdown-editor.svelte';+ import ActivitySheet from '$lib/components/post-mortems/activity-sheet.svelte';+ import { Check, History, Link2, Plus, Trash2, X } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import { api } from '$lib/api';+ import { gotoHref } from '$lib/utils/navigation';+ import { createSmartBackHandler } from '$lib/utils/back-navigation';+ import { formatDateTime } from '$lib/utils/formatters';+ import { projectsState } from '$lib/state/projects.svelte';+ import {+ incidentDisplayTitle,+ type OrgIncident,+ type PostMortem+ } from '$lib/state/monitors.svelte';++ let { data } = $props();++ const postMortemId = $derived(data.id);+ const projectId = $derived(projectsState.currentProjectId);+ const organizationId = $derived(projectsState.currentProject?.organizationId ?? null);+ const canWrite = $derived(projectsState.canWriteCurrentProject);++ let loading = $state(true);+ let notFound = $state(false);+ let error = $state('');+ let formError = $state('');+ let saving = $state(false);+ let deleteOpen = $state(false);+ let deleting = $state(false);+ let activityOpen = $state(false);++ let title = $state('');+ let tags = $state<string[]>([]);+ let contentMd = $state('');+ let linkedIncidentId = $state('');++ let incidents = $state<OrgIncident[]>([]);++ let markdownEditor = $state<{ flushPendingChanges: () => void } | null>(null);++ let tagsDialogOpen = $state(false);+ let dialogTags = $state<string[]>([]);+ let incidentDialogOpen = $state(false);+ let incidentSearch = $state('');++ let loadSeq = 0;++ async function loadAll() {+ if (projectId === null || organizationId === null) return;+ const seq = ++loadSeq;+ loading = true;+ notFound = false;+ error = '';+ formError = '';+ try {+ const [postMortem, incidentsRes] = (await Promise.all([+ api.get(`/post-mortems/${postMortemId}`, { projectId: projectId ?? undefined }),+ api.get(`/organizations/${organizationId}/incidents`, { skipProjectId: true })+ ])) as [PostMortem, { incidents?: OrgIncident[] }];+ if (seq !== loadSeq) return;+ title = postMortem.title;+ tags = postMortem.tags || [];+ contentMd = postMortem.contentMd;+ linkedIncidentId = postMortem.incidentId ? String(postMortem.incidentId) : '';+ incidents = incidentsRes.incidents || [];+ if (linkedIncidentId && !incidents.some((i) => String(i.id) === linkedIncidentId)) {+ try {+ const linked = await api.get(+ `/organizations/${organizationId}/incidents/${linkedIncidentId}/updates`,+ { skipProjectId: true }+ );+ if (seq !== loadSeq) return;+ if (linked.incident) incidents = [linked.incident, ...incidents];+ } catch {+ linkedIncidentId = '';+ }+ }+ } catch (e) {+ if (seq !== loadSeq) return;+ if (getErrorStatus(e) === 404) {+ notFound = true;+ } else {+ error = e instanceof Error ? getErrorMessage(e) : 'Failed to load the post-mortem';+ }+ } finally {+ if (seq === loadSeq) loading = false;+ }+ }++ $effect(() => {+ void postMortemId;+ void projectId;+ void organizationId;+ untrack(() => loadAll());+ });++ function incidentLabel(incident: OrgIncident): string {+ return `${incidentDisplayTitle(incident)} · ${formatDateTime(incident.startedAt, { format: 'short' })}`;+ }++ // Auto incidents from other projects are excluded: the post-mortem belongs+ // to this project, manual (status page) incidents carry no project.+ const selectableIncidents = $derived(+ incidents.filter(+ (incident) =>+ (!incident.postMortemId || String(incident.id) === linkedIncidentId) &&+ (!incident.projectId ||+ incident.projectId === projectId ||+ String(incident.id) === linkedIncidentId)+ )+ );++ const linkedIncidentLabel = $derived.by(() => {+ if (!linkedIncidentId) return 'Not linked';+ const incident = incidents.find((i) => String(i.id) === linkedIncidentId);+ return incident ? incidentLabel(incident) : `Incident #${linkedIncidentId}`;+ });++ const filteredDialogIncidents = $derived.by(() => {+ const query = incidentSearch.trim().toLowerCase();+ if (!query) return selectableIncidents;+ return selectableIncidents.filter((incident) =>+ incidentLabel(incident).toLowerCase().includes(query)+ );+ });++ function openIncidentDialog() {+ incidentSearch = '';+ incidentDialogOpen = true;+ }++ function linkIncident(incident: OrgIncident) {+ linkedIncidentId = String(incident.id);+ incidentDialogOpen = false;+ }++ function openTagsDialog() {+ dialogTags = [...tags];+ tagsDialogOpen = true;+ }++ function applyTags() {+ tags = dialogTags;+ tagsDialogOpen = false;+ }++ function removeTag(tag: string) {+ tags = tags.filter((t) => t !== tag);+ }++ async function save() {+ if (projectId === null) return;+ markdownEditor?.flushPendingChanges();+ saving = true;+ formError = '';+ try {+ const updated = (await api.put(+ `/post-mortems/${postMortemId}`,+ {+ title,+ contentMd,+ tags,+ incidentId: linkedIncidentId ? parseInt(linkedIncidentId, 10) : null+ },+ { projectId: projectId ?? undefined }+ )) as PostMortem;+ title = updated.title;+ tags = updated.tags || [];+ toast.success('Successfully updated the Post-Mortem', { position: 'top-center' });+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ formError = e instanceof Error ? getErrorMessage(e) : 'Failed to save the post-mortem';+ }+ } finally {+ saving = false;+ }+ }++ async function deletePostMortem() {+ if (projectId === null) return;+ deleting = true;+ try {+ await api.delete(`/post-mortems/${postMortemId}`, { projectId: projectId ?? undefined });+ toast.success('Successfully deleted the Post-Mortem');+ gotoHref('/monitors?tab=post-mortems');+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to delete the post-mortem');+ }+ }+ deleting = false;+ deleteOpen = false;+ }++ const backHandler = createSmartBackHandler({ fallbackPath: '/monitors?tab=post-mortems' });+</script>++{#if loading}+ <div class="flex h-64 items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+{:else if notFound}+ <ErrorDisplay+ status={404}+ title="Post-mortem not found"+ description="This post-mortem does not exist or belongs to a different project."+ onBack={backHandler}+ backLabel="Back to Post-Mortems"+ />+{:else if error}+ <ErrorDisplay+ status={400}+ title="Error"+ description={error}+ onRetry={() => loadAll()}+ onBack={backHandler}+ backLabel="Back to Post-Mortems"+ />+{:else}+ <div class="space-y-4">+ <PageHeader title={canWrite ? 'Post-Mortem' : title || 'Post-Mortem'} onBack={backHandler}>+ {#snippet actions()}+ <Button variant="outline" size="sm" onclick={() => (activityOpen = true)}>+ <History class="mr-2 h-4 w-4" />+ Activity+ </Button>+ {#if canWrite}+ <Button variant="destructiveOutline" size="sm" onclick={() => (deleteOpen = true)}>+ <Trash2 class="mr-2 h-4 w-4" />+ Delete+ </Button>+ <Button size="sm" onclick={save} disabled={saving}>+ <Check class="mr-2 h-4 w-4" />+ {saving ? 'Updating...' : 'Update Post-Mortem'}+ </Button>+ {/if}+ {/snippet}+ </PageHeader>++ <ErrorAlert error={formError} />++ {#if canWrite}+ <div class="space-y-2">+ <Label for="post-mortem-title">Title</Label>+ <Input+ id="post-mortem-title"+ bind:value={title}+ placeholder="What went wrong, in one line"+ disabled={saving}+ />+ </div>+ {/if}++ {#if canWrite || tags.length > 0 || linkedIncidentId}+ <div class="flex flex-wrap items-center gap-2">+ {#if linkedIncidentId}+ <span+ class="inline-flex items-center gap-1.5 rounded-full bg-muted px-3 py-0.5 text-xs font-medium"+ >+ <Link2 class="h-3 w-3 shrink-0 text-muted-foreground" />+ <span class="max-w-[320px] truncate">{linkedIncidentLabel}</span>+ {#if canWrite}+ <button+ type="button"+ aria-label="Unlink incident"+ class="ml-0.5 cursor-pointer text-muted-foreground hover:text-foreground"+ onclick={() => (linkedIncidentId = '')}+ disabled={saving}+ >+ <X class="h-3 w-3" />+ </button>+ {/if}+ </span>+ {:else if canWrite}+ <button+ type="button"+ class="inline-flex cursor-pointer 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={openIncidentDialog}+ disabled={saving}+ >+ <Link2 class="h-3 w-3" />+ Link incident+ </button>+ {/if}+ {#each tags as tag (tag)}+ <span+ class="inline-flex items-center gap-1 rounded-full bg-muted px-2.5 py-0.5 text-xs font-medium"+ >+ {tag}+ {#if canWrite}+ <button+ type="button"+ aria-label={`Remove tag ${tag}`}+ class="ml-0.5 cursor-pointer text-muted-foreground hover:text-foreground"+ onclick={() => removeTag(tag)}+ disabled={saving}+ >+ <X class="h-3 w-3" />+ </button>+ {/if}+ </span>+ {/each}+ {#if canWrite}+ <button+ type="button"+ class="inline-flex cursor-pointer 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={openTagsDialog}+ disabled={saving}+ >+ <Plus class="h-3 w-3" />+ Add tags+ </button>+ {/if}+ </div>+ {/if}++ {#key postMortemId}+ <MarkdownEditor+ bind:this={markdownEditor}+ bind:value={contentMd}+ readonly={!canWrite || saving}+ />+ {/key}+ </div>++ <ConfirmDeleteDialog+ bind:open={deleteOpen}+ entity="Post-Mortem"+ description={`This permanently deletes "${title}". Linked incidents keep their public timeline.`}+ loading={deleting}+ onConfirm={deletePostMortem}+ />++ <AlertDialog.Root bind:open={incidentDialogOpen}>+ <AlertDialog.Content class="sm:max-w-lg">+ <AlertDialog.Header>+ <AlertDialog.Title>Link Incident</AlertDialog.Title>+ <AlertDialog.Description>+ Link this post-mortem to the incident it covers. Incidents that already have a+ post-mortem are not listed.+ </AlertDialog.Description>+ </AlertDialog.Header>+ <div class="space-y-3">+ <Input bind:value={incidentSearch} placeholder="Search incidents..." />+ <div class="max-h-72 overflow-y-auto rounded-md border">+ {#each filteredDialogIncidents as incident (incident.id)}+ <button+ type="button"+ class="flex w-full cursor-pointer flex-col items-start gap-0.5 border-b px-3 py-2 text-left text-sm last:border-b-0 hover:bg-accent"+ onclick={() => linkIncident(incident)}+ >+ <span class="font-medium">{incidentDisplayTitle(incident)}</span>+ <span class="text-xs text-muted-foreground">+ {formatDateTime(incident.startedAt, { format: 'short' })}+ </span>+ </button>+ {:else}+ <div class="py-8 text-center text-sm text-muted-foreground">No incidents found</div>+ {/each}+ </div>+ </div>+ <AlertDialog.Footer>+ <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>+ </AlertDialog.Footer>+ </AlertDialog.Content>+ </AlertDialog.Root>++ <AlertDialog.Root bind:open={tagsDialogOpen}>+ <AlertDialog.Content class="sm:max-w-md">+ <AlertDialog.Header>+ <AlertDialog.Title>Add Tags</AlertDialog.Title>+ <AlertDialog.Description>+ Type a tag and press Enter; add as many as you need.+ </AlertDialog.Description>+ </AlertDialog.Header>+ <TagsInput bind:tags={dialogTags} />+ <AlertDialog.Footer>+ <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>+ <Button onclick={applyTags}>+ <Check class="mr-2 h-4 w-4" />+ Apply Tags+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+ </AlertDialog.Root>++ <ActivitySheet bind:open={activityOpen} {postMortemId} />+{/if}diff --git a/frontend/src/routes/monitors/post-mortems/[id]/+page.ts b/frontend/src/routes/monitors/post-mortems/[id]/+page.tsnew file mode 100644index 00000000..d7558a9a--- /dev/null+++ b/frontend/src/routes/monitors/post-mortems/[id]/+page.ts@@ -0,0 +1,13 @@+import { redirect } from '@sveltejs/kit';+import { authState } from '$lib/state/auth.svelte';+import type { PageLoad } from './$types';++export const prerender = false;++export const load: PageLoad = ({ params }) => {+ if (params.id === 'new') {+ throw redirect(301, '/monitors?tab=post-mortems');+ }+ if (!authState.isAuthenticated) throw redirect(302, '/login');+ return { id: params.id };+};diff --git a/frontend/src/routes/monitors/record-incident-dialog.svelte b/frontend/src/routes/monitors/record-incident-dialog.sveltenew file mode 100644index 00000000..0f1a3904--- /dev/null+++ b/frontend/src/routes/monitors/record-incident-dialog.svelte@@ -0,0 +1,147 @@+<script lang="ts">+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import { Checkbox } from '$lib/components/ui/checkbox';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { Plus } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import { api } from '$lib/api';+ import { toLocalInputValue } from '$lib/utils/formatters';+ import { projectsState } from '$lib/state/projects.svelte';++ interface Props {+ open: boolean;+ statusPage: { id: number; name: string } | null;+ onSaved: () => void;+ }++ let { open = $bindable(), statusPage, onSaved }: Props = $props();++ const organizationId = $derived(projectsState.currentProject?.organizationId ?? null);++ let title = $state('');+ let message = $state('');+ let startedAt = $state('');+ let alreadyResolved = $state(false);+ let resolvedAt = $state('');+ let saving = $state(false);+ let dialogError = $state('');++ $effect(() => {+ if (open) {+ title = '';+ message = '';+ startedAt = toLocalInputValue(new Date());+ alreadyResolved = false;+ resolvedAt = toLocalInputValue(new Date());+ dialogError = '';+ }+ });++ async function save() {+ if (!statusPage || organizationId === null) return;+ saving = true;+ dialogError = '';+ try {+ await api.post(+ `/organizations/${organizationId}/status-pages/${statusPage.id}/incidents`,+ {+ title: title.trim(),+ message: message.trim(),+ startedAt: startedAt ? new Date(startedAt).toISOString() : '',+ resolvedAt: alreadyResolved && resolvedAt ? new Date(resolvedAt).toISOString() : ''+ },+ { skipProjectId: true }+ );+ toast.success('Successfully created the Incident', { position: 'top-center' });+ open = false;+ onSaved();+ } catch (e) {+ dialogError = e instanceof Error ? e.message : 'Failed to record the incident';+ } finally {+ saving = false;+ }+ }+</script>++<AlertDialog.Root bind:open>+ <AlertDialog.Content class="sm:max-w-lg" interactOutsideBehavior={saving ? 'ignore' : 'close'}>+ <AlertDialog.Header>+ <AlertDialog.Title>Record Incident</AlertDialog.Title>+ <AlertDialog.Description>+ Publishes an incident on "{statusPage?.name}" for an outage the monitors did not catch. It+ does not change any monitor's uptime numbers.+ </AlertDialog.Description>+ </AlertDialog.Header>++ <form+ onsubmit={(e) => {+ e.preventDefault();+ save();+ }}+ class="space-y-4"+ >+ <ErrorAlert error={dialogError} />+ <div class="space-y-2">+ <Label for="incident-title">Title</Label>+ <Input+ id="incident-title"+ bind:value={title}+ placeholder="Degraded performance for the API"+ disabled={saving}+ />+ </div>+ <div class="space-y-2">+ <Label for="incident-message">First update (optional)</Label>+ <textarea+ id="incident-message"+ bind:value={message}+ rows="3"+ placeholder="We are investigating reports of degraded performance."+ disabled={saving}+ class="w-full resize-y rounded-md border border-input bg-transparent p-3 text-sm shadow-xs focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"+ ></textarea>+ </div>+ <div class="grid gap-4 sm:grid-cols-2">+ <div class="space-y-2">+ <Label for="incident-started">Started at</Label>+ <Input+ id="incident-started"+ type="datetime-local"+ bind:value={startedAt}+ disabled={saving}+ />+ </div>+ <div class="space-y-2">+ <Label for="incident-resolved" class={alreadyResolved ? '' : 'text-muted-foreground'}>+ Resolved at+ </Label>+ <Input+ id="incident-resolved"+ type="datetime-local"+ bind:value={resolvedAt}+ disabled={saving || !alreadyResolved}+ />+ </div>+ </div>+ <label class="flex cursor-pointer items-center gap-2 text-sm">+ <Checkbox+ checked={alreadyResolved}+ onCheckedChange={(checked) => (alreadyResolved = checked === true)}+ disabled={saving}+ />+ Already resolved (recording it after the fact)+ </label>+ </form>++ <AlertDialog.Footer>+ <AlertDialog.Cancel disabled={saving}>Cancel</AlertDialog.Cancel>+ <Button variant="success" onclick={save} disabled={saving}>+ <Plus class="mr-2 h-4 w-4" />+ {saving ? 'Creating...' : 'New Incident'}+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+</AlertDialog.Root>diff --git a/frontend/src/routes/monitors/status-pages-tab.svelte b/frontend/src/routes/monitors/status-pages-tab.svelteindex 103bdeed..45dffaea 100644--- a/frontend/src/routes/monitors/status-pages-tab.svelte+++ b/frontend/src/routes/monitors/status-pages-tab.svelte@@ -1,9 +1,13 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';import { api } from '$lib/api';import * as AlertDialog from '$lib/components/ui/alert-dialog';import * as Table from '$lib/components/ui/table';import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import StatusPill from '$lib/components/traceway/status-pill.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';import { Button } from '$lib/components/ui/button';import { Input } from '$lib/components/ui/input';import { Label } from '$lib/components/ui/label';@@ -13,8 +17,19 @@import { projectsState } from '$lib/state/projects.svelte';import { authState } from '$lib/state/auth.svelte';import type { SyntheticCheck } from '$lib/state/monitors.svelte';- import { Check, ExternalLink, Globe, ImageUp, Pencil, Plus, Trash2 } from '@lucide/svelte';+ import {+ Check,+ ExternalLink,+ Globe,+ ImageUp,+ Pencil,+ Plus,+ Siren,+ Trash2+ } from '@lucide/svelte';import { toast } from 'svelte-sonner';+ import { goto } from '$app/navigation';+ import { resolve } from '$app/paths';interface StatusPage {id: number;@@ -50,6 +65,10 @@let deleteTarget = $state<StatusPage | null>(null);let deleting = $state(false);+ function openIncidents(page: StatusPage) {+ goto(resolve(`/monitors/status-pages/${page.id}/incidents`));+ }+async function loadAll() {if (!organizationId) return;loading = true;@@ -160,7 +179,7 @@dialogOpen = false;loadAll();} catch (e) {- dialogError = e instanceof Error ? e.message : 'Failed to save the status page';+ dialogError = e instanceof Error ? getErrorMessage(e) : 'Failed to save the status page';} finally {saving = false;}@@ -173,12 +192,12 @@await api.delete(`/organizations/${organizationId}/status-pages/${deleteTarget.id}`, {skipProjectId: true});- toast.success('Successfully deleted the Status Page', { position: 'top-center' });+ toast.success('Successfully deleted the Status Page');deleteTarget = null;loadAll();- } catch (e: any) {- if (e?.status !== 403) {- toast.error(e.message || 'Failed to delete the status page', { position: 'top-center' });+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to delete the status page');}} finally {deleting = false;@@ -197,7 +216,7 @@onAction={openCreate}/>{:else}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root><Table.Header><Table.Row>@@ -206,12 +225,12 @@<TracewayTableHeader label="Custom domain" class="w-[200px]" /><TracewayTableHeader label="Monitors" class="w-[100px]" /><TracewayTableHeader label="Visibility" class="w-[110px]" />- <TracewayTableHeader label="" align="right" class="w-[90px]" />+ <TracewayTableHeader label="" align="right" class="w-[160px]" /></Table.Row></Table.Header><Table.Body>- {#each pages as page}- <Table.Row class="group hover:bg-muted/50">+ {#each pages as page, __index (__index)}+ <Table.Row class="group"><Table.Cell class="font-medium">{page.name}{#if page.description}@@ -223,7 +242,7 @@<Table.Cell><aclass="inline-flex items-center gap-1 font-mono text-xs text-primary underline-offset-2 hover:underline"- href={`/status/${page.slug}`}+ href={resolve(`/status/${page.slug}`)}target="_blank"rel="noopener">@@ -239,22 +258,24 @@</Table.Cell><Table.Cell>{#if page.isPublic}- <span- class="inline-flex items-center gap-1 rounded-full bg-green-500/15 px-2 py-0.5 text-xs font-medium text-green-600 dark:text-green-400"- >+ <StatusPill tone="success"><Globe class="h-3 w-3" />Public- </span>+ </StatusPill>{:else}- <span- class="inline-flex items-center rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground"- >- Private- </span>+ <StatusPill tone="neutral" label="Private" />{/if}</Table.Cell><Table.Cell class="text-right"><div class="flex justify-end gap-1">+ <Button+ variant="ghost"+ size="icon-sm"+ onclick={() => openIncidents(page)}+ title="Incidents"+ >+ <Siren class="h-4 w-4" />+ </Button><Button variant="ghost" size="icon-sm" onclick={() => openEdit(page)} title="Edit"><Pencil class="h-4 w-4" /></Button>@@ -272,7 +293,7 @@{/each}</Table.Body></Table.Root>- </div>+ </TableContainer>{/if}<AlertDialog.Root open={dialogOpen} onOpenChange={(v) => (dialogOpen = v)}>@@ -354,7 +375,7 @@onclick={() => logoInput?.click()}disabled={saving}>- <ImageUp class="mr-1.5 h-4 w-4" />+ <ImageUp class="mr-2 h-4 w-4" />{logoFile ? logoFile.name : editing?.logoKey ? 'Replace logo' : 'Upload logo'}</Button></div>@@ -387,7 +408,7 @@<p class="text-sm text-muted-foreground">Create a monitor first.</p>{:else}<div class="max-h-48 space-y-1 overflow-y-auto rounded-md border p-2">- {#each checks as check}+ {#each checks as check, __index (__index)}<labelclass="flex cursor-pointer items-center gap-2 rounded p-1.5 text-sm hover:bg-muted/50">@@ -428,20 +449,10 @@</AlertDialog.Content></AlertDialog.Root>-<AlertDialog.Root open={deleteTarget !== null} onOpenChange={(v) => !v && (deleteTarget = null)}>- <AlertDialog.Content interactOutsideBehavior={deleting ? 'ignore' : 'close'}>- <AlertDialog.Header>- <AlertDialog.Title>Delete Status Page</AlertDialog.Title>- <AlertDialog.Description>- "{deleteTarget?.name}" at /status/{deleteTarget?.slug} will stop working immediately.- </AlertDialog.Description>- </AlertDialog.Header>- <AlertDialog.Footer>- <AlertDialog.Cancel disabled={deleting}>Cancel</AlertDialog.Cancel>- <Button variant="destructive" onclick={deletePage} disabled={deleting}>- <Trash2 class="mr-2 h-4 w-4" />- {deleting ? 'Deleting...' : 'Delete Status Page'}- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>-</AlertDialog.Root>+<ConfirmDeleteDialog+ bind:open={() => deleteTarget !== null, (v) => !v && (deleteTarget = null)}+ entity="Status Page"+ description={`"${deleteTarget?.name}" at /status/${deleteTarget?.slug} will stop working immediately.`}+ loading={deleting}+ onConfirm={deletePage}+/>diff --git a/frontend/src/routes/monitors/status-pages/[pageId]/incidents/+page.svelte b/frontend/src/routes/monitors/status-pages/[pageId]/incidents/+page.sveltenew file mode 100644index 00000000..aa5efc69--- /dev/null+++ b/frontend/src/routes/monitors/status-pages/[pageId]/incidents/+page.svelte@@ -0,0 +1,500 @@+<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';+ import { untrack } from 'svelte';+ import * as Select from '$lib/components/ui/select';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { ErrorDisplay } from '$lib/components/ui/error-display';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import StatusPill from '$lib/components/traceway/status-pill.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';+ import RecordIncidentDialog from '../../../record-incident-dialog.svelte';+ import NewPostMortemDialog from '../../../new-post-mortem-dialog.svelte';+ import {+ Check,+ ChevronDown,+ ChevronRight,+ FileText,+ Megaphone,+ Pencil,+ Send,+ Trash2+ } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import { api } from '$lib/api';+ import { goto } from '$app/navigation';+ import { resolve } from '$app/paths';+ import { createSmartBackHandler } from '$lib/utils/back-navigation';+ import { formatDateTime } from '$lib/utils/formatters';+ import { projectsState } from '$lib/state/projects.svelte';+ import {+ incidentDisplayTitle,+ type IncidentUpdate,+ type IncidentUpdateStatus,+ type OrgIncident+ } from '$lib/state/monitors.svelte';++ let { data } = $props();++ const organizationId = $derived(projectsState.currentProject?.organizationId ?? null);+ const canManage = $derived(projectsState.canManageCurrentProject);++ let statusPageName = $state('');+ let incidents = $state<OrgIncident[]>([]);+ let loading = $state(true);+ let notFound = $state(false);+ let error = $state('');+ let currentPage = $state(1);+ let pageSize = $state(25);+ let total = $state(0);+ let totalPages = $state(0);++ let expandedId = $state<number | null>(null);+ let updates = $state<IncidentUpdate[]>([]);+ let updatesLoading = $state(false);++ let updateStatus = $state<IncidentUpdateStatus>('investigating');+ let updateMessage = $state('');+ let posting = $state(false);++ let editingTitle = $state(false);+ let titleDraft = $state('');+ let savingTitle = $state(false);++ let deleteTarget = $state<OrgIncident | null>(null);+ let deleting = $state(false);+ let recordOpen = $state(false);++ const statusOptions: { value: IncidentUpdateStatus; label: string }[] = [+ { value: 'investigating', label: 'Investigating' },+ { value: 'identified', label: 'Identified' },+ { value: 'monitoring', label: 'Monitoring' },+ { value: 'update', label: 'Update' },+ { value: 'resolved', label: 'Resolved' }+ ];++ const statusLabel = $derived(+ statusOptions.find((o) => o.value === updateStatus)?.label || 'Status'+ );++ let loadSeq = 0;++ async function loadIncidents() {+ if (organizationId === null) return;+ const seq = ++loadSeq;+ loading = true;+ error = '';+ try {+ const params = new URLSearchParams({+ page: String(currentPage),+ pageSize: String(pageSize)+ });+ const res = await api.get(+ `/organizations/${organizationId}/status-pages/${data.pageId}/incidents?${params}`,+ { skipProjectId: true }+ );+ if (seq !== loadSeq) return;+ statusPageName = res.statusPage?.name || '';+ incidents = res.data || [];+ total = res.pagination?.total || 0;+ totalPages = res.pagination?.totalPages || 0;+ } catch (e) {+ if (seq !== loadSeq) return;+ if (getErrorStatus(e) === 404) {+ notFound = true;+ } else {+ error = e instanceof Error ? getErrorMessage(e) : 'Failed to load incidents';+ }+ } finally {+ if (seq === loadSeq) loading = false;+ }+ }++ $effect(() => {+ void organizationId;+ void data.pageId;+ untrack(() => {+ expandedId = null;+ loadIncidents();+ });+ });++ async function loadUpdates(incidentId: number) {+ updatesLoading = true;+ updates = [];+ try {+ const res = await api.get(+ `/organizations/${organizationId}/incidents/${incidentId}/updates`,+ {+ skipProjectId: true+ }+ );+ updates = res.updates || [];+ } catch {+ updates = [];+ } finally {+ updatesLoading = false;+ }+ }++ function toggleExpand(incident: OrgIncident) {+ editingTitle = false;+ if (expandedId === incident.id) {+ expandedId = null;+ return;+ }+ expandedId = incident.id;+ updateStatus = incident.resolvedAt ? 'update' : 'investigating';+ updateMessage = '';+ loadUpdates(incident.id);+ }++ async function postUpdate(incident: OrgIncident, status: IncidentUpdateStatus = updateStatus) {+ posting = true;+ try {+ await api.post(+ `/organizations/${organizationId}/incidents/${incident.id}/updates`,+ { status, message: updateMessage.trim() },+ { skipProjectId: true }+ );+ updateMessage = '';+ await Promise.all([loadUpdates(incident.id), loadIncidents()]);+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to post the update');+ }+ } finally {+ posting = false;+ }+ }++ let deleteUpdateTarget = $state<{ incident: OrgIncident; update: IncidentUpdate } | null>(null);+ let deletingUpdate = $state(false);++ async function deleteUpdate() {+ if (!deleteUpdateTarget) return;+ const { incident, update } = deleteUpdateTarget;+ deletingUpdate = true;+ try {+ await api.delete(+ `/organizations/${organizationId}/incidents/${incident.id}/updates/${update.id}`,+ { skipProjectId: true }+ );+ deleteUpdateTarget = null;+ await loadUpdates(incident.id);+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to delete the update');+ }+ } finally {+ deletingUpdate = false;+ }+ }++ function startTitleEdit(incident: OrgIncident) {+ editingTitle = true;+ titleDraft = incident.title || '';+ }++ async function saveTitle(incident: OrgIncident) {+ savingTitle = true;+ try {+ await api.put(+ `/organizations/${organizationId}/incidents/${incident.id}`,+ { title: titleDraft.trim() },+ { skipProjectId: true }+ );+ editingTitle = false;+ await loadIncidents();+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to update the title');+ }+ } finally {+ savingTitle = false;+ }+ }++ async function deleteIncident() {+ if (!deleteTarget) return;+ deleting = true;+ try {+ await api.delete(`/organizations/${organizationId}/incidents/${deleteTarget.id}`, {+ skipProjectId: true+ });+ toast.success('Successfully deleted the Incident');+ deleteTarget = null;+ expandedId = null;+ await loadIncidents();+ } catch (e) {+ if (getErrorStatus(e) !== 403) {+ toast.error(getErrorMessage(e) || 'Failed to delete the incident');+ }+ } finally {+ deleting = false;+ }+ }++ let newPostMortemOpen = $state(false);+ let newPostMortemIncident = $state<OrgIncident | null>(null);++ function openPostMortem(incident: OrgIncident) {+ if (incident.postMortemId) {+ goto(resolve(`/monitors/post-mortems/${incident.postMortemId}`));+ } else {+ newPostMortemIncident = incident;+ newPostMortemOpen = true;+ }+ }++ const backHandler = createSmartBackHandler({ fallbackPath: '/monitors?tab=status-pages' });+</script>++{#if notFound}+ <ErrorDisplay+ status={404}+ title="Status page not found"+ description="This status page does not exist or belongs to a different organization."+ onBack={backHandler}+ backLabel="Back to Status Pages"+ />+{:else}+ <div class="space-y-4">+ <PageHeader+ title={statusPageName ? `Incidents · ${statusPageName}` : 'Incidents'}+ description="Everything the public Past Incidents section of this status page shows. Post public timeline updates, name incidents, and attach post-mortems."+ onBack={backHandler}+ >+ {#snippet actions()}+ {#if canManage}+ <Button variant="success" size="sm" onclick={() => (recordOpen = true)}>+ <Megaphone class="mr-2 h-4 w-4" />+ Record Incident+ </Button>+ {/if}+ {/snippet}+ </PageHeader>++ {#if loading}+ <div class="flex h-48 items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ {:else if error}+ <div class="rounded-md border py-16 text-center text-red-500">{error}</div>+ {:else if incidents.length === 0}+ <div class="rounded-md border py-16 text-center text-sm text-muted-foreground">+ No incidents recorded on this status page yet.+ </div>+ {:else}+ <div class="space-y-3">+ {#each incidents as incident (incident.id)}+ <div class="rounded-md border">+ <button+ type="button"+ class="flex w-full cursor-pointer items-center gap-2 p-3 text-left"+ onclick={() => toggleExpand(incident)}+ >+ {#if expandedId === incident.id}+ <ChevronDown class="size-4 shrink-0 text-muted-foreground" />+ {:else}+ <ChevronRight class="size-4 shrink-0 text-muted-foreground" />+ {/if}+ <div class="min-w-0 flex-1">+ <div class="truncate text-sm font-medium">{incidentDisplayTitle(incident)}</div>+ <div class="text-xs text-muted-foreground">+ {formatDateTime(incident.startedAt, { format: 'short' })}+ {#if incident.statusPageId}+ · manual+ {:else if incident.checkName}+ · {incident.checkName}+ {/if}+ {#if incident.updatesCount}+ · {incident.updatesCount} update{incident.updatesCount === 1 ? '' : 's'}+ {/if}+ </div>+ </div>+ {#if incident.resolvedAt}+ <StatusPill tone="success" label="Resolved" />+ {:else}+ <StatusPill tone="danger" label="Ongoing" />+ {/if}+ </button>++ {#if expandedId === incident.id}+ <div class="space-y-4 border-t p-3">+ <div class="flex flex-wrap items-center gap-2">+ {#if canManage}+ {#if editingTitle}+ <Input+ bind:value={titleDraft}+ placeholder="Public incident title"+ class="h-8 w-full sm:w-auto sm:flex-1"+ disabled={savingTitle}+ />+ <Button+ size="sm"+ variant="outline"+ onclick={() => saveTitle(incident)}+ disabled={savingTitle}+ >+ <Check class="mr-2 h-4 w-4" />+ Save+ </Button>+ {:else}+ <Button size="sm" variant="outline" onclick={() => startTitleEdit(incident)}>+ <Pencil class="mr-2 h-4 w-4" />+ {incident.title ? 'Rename' : 'Set title'}+ </Button>+ {/if}+ {/if}+ <Button size="sm" variant="outline" onclick={() => openPostMortem(incident)}>+ <FileText class="mr-2 h-4 w-4" />+ {incident.postMortemId ? 'View post-mortem' : 'Write post-mortem'}+ </Button>+ {#if canManage && incident.statusPageId && !incident.resolvedAt}+ <Button+ size="sm"+ variant="outline"+ onclick={() => postUpdate(incident, 'resolved')}+ disabled={posting}+ >+ <Check class="mr-2 h-4 w-4" />+ Resolve+ </Button>+ {/if}+ {#if canManage && incident.statusPageId}+ <Button+ size="sm"+ variant="destructiveOutline"+ onclick={() => (deleteTarget = incident)}+ >+ <Trash2 class="mr-2 h-4 w-4" />+ Delete+ </Button>+ {/if}+ </div>++ {#if canManage}+ <div class="flex flex-col gap-2 sm:flex-row sm:items-start">+ <Select.Root type="single" bind:value={updateStatus} disabled={posting}>+ <Select.Trigger class="w-full shrink-0 sm:w-[150px]">+ {statusLabel}+ </Select.Trigger>+ <Select.Content>+ {#each statusOptions.filter((o) => o.value !== 'resolved' || !!incident.statusPageId || !!incident.resolvedAt) as option (option.value)}+ <Select.Item value={option.value}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ <div class="flex min-w-0 flex-1 gap-2">+ <Input+ bind:value={updateMessage}+ placeholder="Public update message..."+ class="min-w-0 flex-1"+ disabled={posting}+ onkeydown={(e) => {+ if (e.key === 'Enter') postUpdate(incident);+ }}+ />+ <Button+ size="sm"+ class="h-9 shrink-0"+ onclick={() => postUpdate(incident)}+ disabled={posting}+ >+ <Send class="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>+ {/if}++ {#if updatesLoading}+ <div class="flex justify-center py-4"><LoadingCircle size="md" /></div>+ {:else if updates.length === 0}+ <p class="text-sm text-muted-foreground">No updates yet.</p>+ {:else}+ <div class="space-y-3">+ {#each updates as update (update.id)}+ <div class="group flex items-start gap-2 text-sm">+ <div class="min-w-0 flex-1">+ <span class="font-semibold capitalize">{update.status}</span>+ {#if update.message}+ <span class="text-foreground/90"> - {update.message}</span>+ {/if}+ <div class="text-xs text-muted-foreground">+ {formatDateTime(update.createdAt, { format: 'short' })}+ </div>+ </div>+ {#if canManage}+ <Button+ variant="ghost"+ size="icon-sm"+ class="text-destructive opacity-60 hover:text-destructive hover:opacity-100 sm:opacity-0 sm:group-hover:opacity-100"+ title="Delete update"+ onclick={() => (deleteUpdateTarget = { incident, update })}+ >+ <Trash2 class="h-3.5 w-3.5" />+ </Button>+ {/if}+ </div>+ {/each}+ </div>+ {/if}+ </div>+ {/if}+ </div>+ {/each}+ </div>++ <PaginationFooter+ {currentPage}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={(page) => {+ currentPage = page;+ expandedId = null;+ loadIncidents();+ }}+ onPageSizeChange={(size) => {+ pageSize = size;+ currentPage = 1;+ expandedId = null;+ loadIncidents();+ }}+ {loading}+ itemLabel="incident"+ />+ {/if}+ </div>++ <RecordIncidentDialog+ bind:open={recordOpen}+ statusPage={statusPageName ? { id: parseInt(data.pageId, 10), name: statusPageName } : null}+ onSaved={() => loadIncidents()}+ />++ <NewPostMortemDialog+ bind:open={newPostMortemOpen}+ incidentId={newPostMortemIncident?.id ?? null}+ incidentLabel={newPostMortemIncident ? incidentDisplayTitle(newPostMortemIncident) : ''}+ />++ <ConfirmDeleteDialog+ bind:open={() => deleteUpdateTarget !== null, (v) => !v && (deleteUpdateTarget = null)}+ entity="Update"+ description={`This removes the "${deleteUpdateTarget?.update.status}" update from the public timeline.`}+ loading={deletingUpdate}+ onConfirm={deleteUpdate}+ />++ <ConfirmDeleteDialog+ bind:open={() => deleteTarget !== null, (v) => !v && (deleteTarget = null)}+ entity="Incident"+ description={`This removes "${deleteTarget ? incidentDisplayTitle(deleteTarget) : ''}" and its updates from the status page. A linked post-mortem is kept.`}+ loading={deleting}+ onConfirm={deleteIncident}+ />+{/if}diff --git a/frontend/src/routes/monitors/status-pages/[pageId]/incidents/+page.ts b/frontend/src/routes/monitors/status-pages/[pageId]/incidents/+page.tsnew file mode 100644index 00000000..36edc8fd--- /dev/null+++ b/frontend/src/routes/monitors/status-pages/[pageId]/incidents/+page.ts@@ -0,0 +1,10 @@+import { redirect } from '@sveltejs/kit';+import { authState } from '$lib/state/auth.svelte';+import type { PageLoad } from './$types';++export const prerender = false;++export const load: PageLoad = ({ params }) => {+ if (!authState.isAuthenticated) throw redirect(302, '/login');+ return { pageId: params.pageId };+};diff --git a/frontend/src/routes/notifications/+page.svelte b/frontend/src/routes/notifications/+page.svelteindex 861e4ab7..56fdc8d2 100644--- a/frontend/src/routes/notifications/+page.svelte+++ b/frontend/src/routes/notifications/+page.svelte@@ -1,8 +1,9 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';+ import { resolveHref } from '$lib/utils/links';import { onMount, onDestroy } from 'svelte';import { browser } from '$app/environment';import { page } from '$app/state';- import { goto } from '$app/navigation';import { api } from '$lib/api';import { projectsState } from '$lib/state/projects.svelte';import { getTimezone } from '$lib/state/timezone.svelte';@@ -13,9 +14,15 @@import { toast } from 'svelte-sonner';import * as Table from '$lib/components/ui/table';import * as AlertDialog from '$lib/components/ui/alert-dialog';- import TabsRow from '$lib/components/traceway/tabs-row.svelte';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import PageTabs from '$lib/components/traceway/page-tabs.svelte';import InfoCallout from '$lib/components/traceway/info-callout.svelte';import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';+ import PageBadges from '$lib/components/traceway/page-badges.svelte';import { Pencil, Trash2, Zap, ZapOff, Clock, Send } from '@lucide/svelte';import { SearchBar } from '$lib/components/ui/search-bar';import { TableEmptyState } from '$lib/components/ui/table-empty-state';@@ -27,7 +34,8 @@getTimeRangeFromPreset,dateToCalendarDate,dateToTimeString,- updateUrl+ updateUrl,+ setTabParam} from '$lib/utils/url-params';import { calendarDateTimeToLuxon, toUTCISO } from '$lib/utils/formatters';@@ -35,13 +43,14 @@import RuleDialog from './rule-dialog.svelte';import SnoozeDialog from './snooze-dialog.svelte';import { ruleTypeLabels } from './rule-types';+ import type { NotificationChannelConfig, NotificationRuleConfig } from '$lib/types/notifications';interface NotificationChannel {id: number;projectId: string;name: string;channelType: string;- config: any;+ config: NotificationChannelConfig;enabled: boolean;createdAt: string;}@@ -52,7 +61,7 @@channelId: number;name: string;ruleType: string;- config: any;+ config: NotificationRuleConfig;enabled: boolean;cooldownMinutes: number;severity: string;@@ -90,7 +99,8 @@const tabDescriptions: Record<string, string> = {channels:'Channels define where your notifications are delivered, such as Email, Slack, Webhooks, GitHub Issues, or Pushover. Create a channel first, then attach it to a rule.',- rules: 'Rules define when notifications are triggered. Each rule monitors a specific condition and sends an alert through the attached channel when that condition is met.',+ rules:+ 'Rules define when notifications are triggered. Each rule monitors a specific condition and sends an alert through the attached channel when that condition is met.',history:'A log of all notifications that have been sent, including their status and the rule that triggered them.'};@@ -104,14 +114,7 @@const activeTab = $derived(page.url.searchParams.get('tab') || 'channels');function setTab(tab: string) {- const url = new URL(window.location.href);- url.searchParams.set('tab', tab);- if (tab !== 'history') {- url.searchParams.delete('preset');- url.searchParams.delete('from');- url.searchParams.delete('to');- }- goto(url.toString(), { replaceState: true, noScroll: true });+ setTabParam(tab, { clear: tab !== 'history' ? ['preset', 'from', 'to'] : [] });if (tab === 'history') {loadHistory(false);}@@ -119,12 +122,15 @@let channels = $state<NotificationChannel[]>([]);let channelsLoading = $state(true);+ let channelsError = $state('');let rules = $state<NotificationRule[]>([]);let rulesLoading = $state(true);+ let rulesError = $state('');let history = $state<NotificationHistory[]>([]);let historyLoading = $state(true);+ let historyError = $state('');let historyPage = $state(1);let historyPageSize = $state(25);let historyTotal = $state(0);@@ -187,9 +193,11 @@let showDeleteChannelDialog = $state(false);let deletingChannel = $state<NotificationChannel | null>(null);+ let deleteChannelLoading = $state(false);let showDeleteRuleDialog = $state(false);let deletingRule = $state<NotificationRule | null>(null);+ let deleteRuleLoading = $state(false);let showToggleRuleDialog = $state(false);let togglingRule = $state<NotificationRule | null>(null);@@ -202,13 +210,15 @@async function loadChannels() {channelsLoading = true;+ channelsError = '';try {const res = await api.get('/notification-channels', {projectId: projectsState.currentProjectId ?? undefined});channels = res.channels || [];- } catch {+ } catch (e: unknown) {channels = [];+ channelsError = e instanceof Error ? getErrorMessage(e) : 'Failed to load channels';} finally {channelsLoading = false;}@@ -216,13 +226,15 @@async function loadRules() {rulesLoading = true;+ rulesError = '';try {const res = await api.get('/notification-rules', {projectId: projectsState.currentProjectId ?? undefined});rules = res.rules || [];- } catch {+ } catch (e: unknown) {rules = [];+ rulesError = e instanceof Error ? getErrorMessage(e) : 'Failed to load rules';} finally {rulesLoading = false;}@@ -230,6 +242,7 @@async function loadHistory(pushToHistory = true) {historyLoading = true;+ historyError = '';if (selectedPreset) {const range = getTimeRangeFromPreset(selectedPreset, timezone);@@ -255,8 +268,11 @@history = res.data || [];historyTotal = res.pagination?.total || 0;historyTotalPages = res.pagination?.totalPages || 0;- } catch {+ } catch (e: unknown) {history = [];+ historyTotal = 0;+ historyTotalPages = 0;+ historyError = e instanceof Error ? getErrorMessage(e) : 'Failed to load history';} finally {historyLoading = false;}@@ -274,17 +290,20 @@async function deleteChannel() {if (!deletingChannel) return;+ deleteChannelLoading = true;try {await api.delete(`/notification-channels/${deletingChannel.id}`, {projectId: projectsState.currentProjectId ?? undefined});- toast.success('Successfully deleted the Channel', { position: 'top-center' });+ toast.success('Successfully deleted the Channel');showDeleteChannelDialog = false;deletingChannel = null;loadChannels();loadRules();} catch {- toast.error('Failed to delete channel', { position: 'top-center' });+ toast.error('Failed to delete channel');+ } finally {+ deleteChannelLoading = false;}}@@ -304,14 +323,14 @@{},{ projectId: projectsState.currentProjectId ?? undefined });- toast.success('Test notification sent', { position: 'top-center' });+ toast.success('Test notification sent');showTestChannelDialog = false;testingChannel = null;- } catch (e: any) {- if (e.status === 422) {- testError = e.message || 'Validation failed';+ } catch (e) {+ if (getErrorStatus(e) === 422) {+ testError = getErrorMessage(e) || 'Validation failed';} else {- toast.error('An unexpected error has occurred', { position: 'top-center' });+ toast.error('An unexpected error has occurred');showTestChannelDialog = false;testingChannel = null;}@@ -327,16 +346,19 @@async function deleteRule() {if (!deletingRule) return;+ deleteRuleLoading = true;try {await api.delete(`/notification-rules/${deletingRule.id}`, {projectId: projectsState.currentProjectId ?? undefined});- toast.success('Successfully deleted the Rule', { position: 'top-center' });+ toast.success('Successfully deleted the Rule');showDeleteRuleDialog = false;deletingRule = null;loadRules();} catch {- toast.error('Failed to delete rule', { position: 'top-center' });+ toast.error('Failed to delete rule');+ } finally {+ deleteRuleLoading = false;}}@@ -355,12 +377,12 @@{},{ projectId: projectsState.currentProjectId ?? undefined });- toast.success(`Successfully ${action} the Rule`, { position: 'top-center' });+ toast.success(`Successfully ${action} the Rule`);showToggleRuleDialog = false;togglingRule = null;loadRules();} catch {- toast.error('Failed to toggle rule', { position: 'top-center' });+ toast.error('Failed to toggle rule');} finally {togglingLoading = false;}@@ -468,11 +490,9 @@</script><div class="space-y-4">- <div>- <h1 class="text-3xl font-semibold tracking-tight">Alerts</h1>- </div>+ <PageHeader title="Alerts" />- <TabsRow+ <PageTabstabs={TABS}{activeTab}onTabChange={setTab}@@ -485,6 +505,8 @@{#if activeTab === 'channels'}{#if channelsLoading}<div class="flex justify-center py-12"><LoadingCircle size="xlg" /></div>+ {:else if channelsError}+ <ErrorRetryBox message={channelsError} onRetry={() => loadChannels()} />{:else if channels.length === 0}<EmptyStatemessage="No channels yet. Create one to get started."@@ -492,7 +514,7 @@onAction={openNewChannel}/>{:else}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root><Table.Header><Table.Row>@@ -504,13 +526,12 @@</Table.Row></Table.Header><Table.Body>- {#each channels as channel}+ {#each channels as channel, __index (__index)}<Table.Row><Table.Cell class="font-medium">{channel.name}</Table.Cell><Table.Cell><Badge variant="outline"- >{channelTypeLabels[channel.channelType] ||- channel.channelType}</Badge+ >{channelTypeLabels[channel.channelType] || channel.channelType}</Badge></Table.Cell><Table.Cell>@@ -555,11 +576,13 @@{/each}</Table.Body></Table.Root>- </div>+ </TableContainer>{/if}{:else if activeTab === 'rules'}{#if rulesLoading}<div class="flex justify-center py-12"><LoadingCircle size="xlg" /></div>+ {:else if rulesError}+ <ErrorRetryBox message={rulesError} onRetry={() => loadRules()} />{:else if rules.length === 0}<EmptyStatemessage="No rules yet. Create one to get started."@@ -567,7 +590,7 @@onAction={openNewRule}/>{:else}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root><Table.Header><Table.Row>@@ -579,12 +602,10 @@</Table.Row></Table.Header><Table.Body>- {#each rules as rule}+ {#each rules as rule, __index (__index)}<Table.Row><Table.Cell class="font-medium">{rule.name}</Table.Cell>- <Table.Cell- >{ruleTypeLabels[rule.ruleType] || rule.ruleType}</Table.Cell- >+ <Table.Cell>{ruleTypeLabels[rule.ruleType] || rule.ruleType}</Table.Cell><Table.Cell><Badge variant="outline">{rule.channelName}</Badge></Table.Cell>@@ -641,7 +662,7 @@{/each}</Table.Body></Table.Root>- </div>+ </TableContainer>{/if}{:else if activeTab === 'history'}<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">@@ -663,76 +684,76 @@</div></div>- <div class="overflow-hidden rounded-md border">- <Table.Root>- {#if historyLoading}- <Table.Body>- <Table.Row>- <Table.Cell colspan={6} class="h-48">- <div class="flex h-full items-center justify-center">- <LoadingCircle size="xlg" />- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if history.length === 0}- <Table.Body>- <TableEmptyState colspan={6} message="No Historic Alerts found." />- </Table.Body>- {:else}- <Table.Header>- <Table.Row>- <Table.Head>Severity</Table.Head>- <Table.Head>Rule</Table.Head>- <Table.Head>Subject</Table.Head>- <Table.Head>Channel</Table.Head>- <Table.Head>Status</Table.Head>- <Table.Head>Sent At</Table.Head>- </Table.Row>- </Table.Header>- <Table.Body>- {#each history as item}+ {#if historyError && !historyLoading}+ <ErrorRetryBox message={historyError} onRetry={() => loadHistory(false)} />+ {:else}+ <TableContainer>+ <Table.Root>+ {#if historyLoading}+ <Table.Body><Table.Row>- <Table.Cell>- {#if item.severity === 'critical'}- <Badge variant="destructive">Critical</Badge>- {:else if item.severity === 'warning'}- <Badge class="bg-amber-500 text-white">Warning</Badge>- {:else}- <Badge variant="secondary">Info</Badge>- {/if}- </Table.Cell>- <Table.Cell class="font-medium">{item.ruleName}</Table.Cell>- <Table.Cell class="max-w-xs truncate">- {#if item.url}- <a href={item.url} class="text-blue-600 hover:underline dark:text-blue-400">{item.subject}</a>- {:else}- {item.subject}- {/if}- </Table.Cell>- <Table.Cell>{item.channelName}</Table.Cell>- <Table.Cell>- {#if item.status === 'sent'}- <Badge class="bg-green-600 text-white">Sent</Badge>- {:else if item.status === 'failed'}- <Badge variant="destructive">Failed</Badge>- {:else if item.status === 'deduped'}- <Badge variant="secondary" title="Folded into a page that was already open">- Deduped- </Badge>- {:else}- <Badge variant="secondary">Skipped</Badge>- {/if}+ <Table.Cell colspan={6} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div></Table.Cell>- <Table.Cell class="text-muted-foreground"- >{formatDate(item.createdAt)}</Table.Cell- ></Table.Row>- {/each}- </Table.Body>- {/if}- </Table.Root>- </div>+ </Table.Body>+ {:else if history.length === 0}+ <Table.Body>+ <TableEmptyState colspan={6} message="No Historic Alerts found." />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <Table.Head>Severity</Table.Head>+ <Table.Head>Rule</Table.Head>+ <Table.Head>Subject</Table.Head>+ <Table.Head>Channel</Table.Head>+ <Table.Head>Status</Table.Head>+ <Table.Head>Sent At</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each history as item, __index (__index)}+ <Table.Row>+ <Table.Cell>+ <PageBadges severity={item.severity} fallback />+ </Table.Cell>+ <Table.Cell class="font-medium">{item.ruleName}</Table.Cell>+ <Table.Cell class="max-w-xs truncate">+ {#if item.url}+ <a+ {...{ href: resolveHref(item.url) }}+ class="text-blue-600 hover:underline dark:text-blue-400">{item.subject}</a+ >+ {:else}+ {item.subject}+ {/if}+ </Table.Cell>+ <Table.Cell>{item.channelName}</Table.Cell>+ <Table.Cell>+ {#if item.status === 'sent'}+ <Badge class="bg-green-600 text-white">Sent</Badge>+ {:else if item.status === 'failed'}+ <Badge variant="destructive">Failed</Badge>+ {:else if item.status === 'deduped'}+ <Badge variant="secondary" title="Folded into a page that was already open">+ Deduped+ </Badge>+ {:else}+ <Badge variant="secondary">Skipped</Badge>+ {/if}+ </Table.Cell>+ <Table.Cell class="text-muted-foreground">{formatDate(item.createdAt)}</Table.Cell+ >+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </TableContainer>+ {/if}<PaginationFootercurrentPage={historyPage}@@ -774,41 +795,21 @@}}/>-<AlertDialog.Root bind:open={showDeleteChannelDialog}>- <AlertDialog.Content interactOutsideBehavior="close">- <AlertDialog.Header>- <AlertDialog.Title>Delete Channel</AlertDialog.Title>- <AlertDialog.Description>- Are you sure you want to delete "{deletingChannel?.name}"? This action cannot be undone.- </AlertDialog.Description>- </AlertDialog.Header>- <AlertDialog.Footer>- <Button variant="outline" onclick={() => (showDeleteChannelDialog = false)}>Cancel</Button>- <Button variant="destructive" onclick={deleteChannel}>- <Trash2 class="mr-1 h-4 w-4" />- Delete Channel- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>-</AlertDialog.Root>+<ConfirmDeleteDialog+ bind:open={showDeleteChannelDialog}+ entity="Channel"+ description={`Are you sure you want to delete "${deletingChannel?.name}"? This action cannot be undone.`}+ loading={deleteChannelLoading}+ onConfirm={deleteChannel}+/>-<AlertDialog.Root bind:open={showDeleteRuleDialog}>- <AlertDialog.Content interactOutsideBehavior="close">- <AlertDialog.Header>- <AlertDialog.Title>Delete Rule</AlertDialog.Title>- <AlertDialog.Description>- Are you sure you want to delete "{deletingRule?.name}"? This action cannot be undone.- </AlertDialog.Description>- </AlertDialog.Header>- <AlertDialog.Footer>- <Button variant="outline" onclick={() => (showDeleteRuleDialog = false)}>Cancel</Button>- <Button variant="destructive" onclick={deleteRule}>- <Trash2 class="mr-1 h-4 w-4" />- Delete Rule- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>-</AlertDialog.Root>+<ConfirmDeleteDialog+ bind:open={showDeleteRuleDialog}+ entity="Rule"+ description={`Are you sure you want to delete "${deletingRule?.name}"? This action cannot be undone.`}+ loading={deleteRuleLoading}+ onConfirm={deleteRule}+/><AlertDialog.Root bind:open={showToggleRuleDialog}><AlertDialog.Content@@ -822,9 +823,19 @@</AlertDialog.Description></AlertDialog.Header><AlertDialog.Footer>- <Button variant="outline" onclick={() => (showToggleRuleDialog = false)} disabled={togglingLoading}>Cancel</Button>+ <Button+ variant="outline"+ onclick={() => (showToggleRuleDialog = false)}+ disabled={togglingLoading}>Cancel</Button+ ><Button onclick={confirmToggleRule} disabled={togglingLoading}>- {togglingRule?.enabled ? 'Disable' : 'Enable'}+ {#if togglingRule?.enabled}+ <ZapOff class="mr-2 h-4 w-4" />+ Disable Rule+ {:else}+ <Zap class="mr-2 h-4 w-4" />+ Enable Rule+ {/if}</Button></AlertDialog.Footer></AlertDialog.Content>@@ -839,21 +850,24 @@<AlertDialog.Title>Test Channel</AlertDialog.Title><AlertDialog.Description>{#if testingChannel?.channelType === 'escalation'}- Testing "{testingChannel?.name}" opens a real page and notifies whoever is on call, exactly- as a firing rule would. Resolve the page from On-Call when you are done.+ Testing "{testingChannel?.name}" opens a real page and notifies whoever is on call,+ exactly as a firing rule would. Resolve the page from On-Call when you are done.{:else}Send a test notification to "{testingChannel?.name}"? This will deliver a test messagethrough the configured channel.{/if}</AlertDialog.Description></AlertDialog.Header>- {#if testError}- <p class="text-sm text-destructive">{testError}</p>- {/if}+ <ErrorAlert error={testError} /><AlertDialog.Footer>- <Button variant="outline" onclick={() => (showTestChannelDialog = false)} disabled={testingLoading}>Cancel</Button>+ <Button+ variant="outline"+ onclick={() => (showTestChannelDialog = false)}+ disabled={testingLoading}>Cancel</Button+ ><Button onclick={confirmTestChannel} disabled={testingLoading}>- <Send class="h-4 w-4" /> {testingLoading ? 'Sending...' : 'Send Test'}+ <Send class="h-4 w-4" />+ {testingLoading ? 'Sending...' : 'Send Test'}</Button></AlertDialog.Footer></AlertDialog.Content>diff --git a/frontend/src/routes/notifications/channel-dialog.svelte b/frontend/src/routes/notifications/channel-dialog.svelteindex 825b6756..99dfba82 100644--- a/frontend/src/routes/notifications/channel-dialog.svelte+++ b/frontend/src/routes/notifications/channel-dialog.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import { resolveHref } from '$lib/utils/links';import * as AlertDialog from '$lib/components/ui/alert-dialog';import { Button } from '$lib/components/ui/button';import { Input } from '$lib/components/ui/input';@@ -9,13 +10,14 @@import { toast } from 'svelte-sonner';import { api } from '$lib/api';import { projectsState } from '$lib/state/projects.svelte';+ import type { NotificationChannelConfig } from '$lib/types/notifications';interface NotificationChannel {id: number;projectId: string;name: string;channelType: string;- config: any;+ config: NotificationChannelConfig;enabled: boolean;createdAt: string;}@@ -169,11 +171,11 @@}}- function buildConfig(): any {+ function buildConfig(): NotificationChannelConfig {if (channelType === 'email') {return { recipients: emailRecipients.filter((e) => e.trim() !== '') };} else if (channelType === 'webhook') {- const config: any = { url: webhookUrl };+ const config: NotificationChannelConfig = { url: webhookUrl };if (webhookMethod !== 'POST') config.method = webhookMethod;if (webhookSecret) config.secret = webhookSecret;const headers: Record<string, string> = {};@@ -183,12 +185,12 @@if (Object.keys(headers).length > 0) config.headers = headers;return config;} else if (channelType === 'slack') {- const config: any = { webhookUrl: slackWebhookUrl };+ const config: NotificationChannelConfig = { webhookUrl: slackWebhookUrl };if (slackChannel) config.channel = slackChannel;if (slackUsername) config.username = slackUsername;return config;} else if (channelType === 'github') {- const config: any = {+ const config: NotificationChannelConfig = {token: githubToken,owner: githubOwner,repo: githubRepo@@ -200,7 +202,7 @@if (labels.length > 0) config.labels = labels;return config;} else if (channelType === 'pushover') {- const config: any = {+ const config: NotificationChannelConfig = {userKey: pushoverUserKey,appToken: pushoverAppToken};@@ -325,7 +327,7 @@{channelTypeOptions.find((o) => o.value === channelType)?.label || 'Select type'}</Select.Trigger><Select.Content>- {#each channelTypeOptions as option}+ {#each channelTypeOptions as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content>@@ -335,11 +337,13 @@{#if channelType === 'email'}<div class="space-y-2"><Label>Recipients</Label>- {#each emailRecipients as _, index}+ {#each emailRecipients as recipient, index (index)}<div class="flex gap-2"><Inputtype="email"- bind:value={emailRecipients[index]}+ value={recipient}+ oninput={(event) =>+ (emailRecipients[index] = (event.currentTarget as HTMLInputElement).value)}placeholder="[email protected]"/>{#if emailRecipients.length > 1}@@ -388,14 +392,10 @@</div><div class="space-y-2"><Label>Headers (optional)</Label>- {#each webhookHeaders as _, index}+ {#each webhookHeaders as header, index (index)}<div class="flex gap-2">- <Input- bind:value={webhookHeaders[index].key}- placeholder="Header name"- class="flex-1"- />- <Input bind:value={webhookHeaders[index].value} placeholder="Value" class="flex-1" />+ <Input bind:value={header.key} placeholder="Header name" class="flex-1" />+ <Input bind:value={header.value} placeholder="Value" class="flex-1" /><Buttonvariant="ghost"size="icon"@@ -561,8 +561,9 @@{#if escalationPoliciesLoaded && escalationPolicies.length === 0}<p class="text-sm text-muted-foreground">No escalation policies yet — create one on the- <a href="/on-call?tab=policies" class="text-blue-600 hover:underline dark:text-blue-400"- >On-Call page</a+ <a+ {...{ href: resolveHref('/on-call?tab=policies') }}+ class="text-blue-600 hover:underline dark:text-blue-400">On-Call page</a>.</p>{:else}@@ -589,7 +590,6 @@</p></div>{/if}-</form><AlertDialog.Footer>diff --git a/frontend/src/routes/notifications/rule-dialog.svelte b/frontend/src/routes/notifications/rule-dialog.svelteindex 9f1a1325..3590594d 100644--- a/frontend/src/routes/notifications/rule-dialog.svelte+++ b/frontend/src/routes/notifications/rule-dialog.svelte@@ -11,13 +11,14 @@import { api } from '$lib/api';import { projectsState, isFrontendFramework } from '$lib/state/projects.svelte';import { ruleTypeOptions } from './rule-types';+ import type { NotificationChannelConfig, NotificationRuleConfig } from '$lib/types/notifications';interface NotificationChannel {id: number;projectId: string;name: string;channelType: string;- config: any;+ config: NotificationChannelConfig;enabled: boolean;createdAt: string;}@@ -28,7 +29,7 @@channelId: number;name: string;ruleType: string;- config: any;+ config: NotificationRuleConfig;enabled: boolean;cooldownMinutes: number;severity: string;@@ -88,8 +89,7 @@const isEditing = $derived(rule !== null);const isFrontendProject = $derived(- !!projectsState.currentProject &&- isFrontendFramework(projectsState.currentProject.framework)+ !!projectsState.currentProject && isFrontendFramework(projectsState.currentProject.framework));const visibleRuleTypes = $derived(@@ -117,8 +117,7 @@'Fires when the cumulative cost of a single AI conversation (over the last 24 hours) exceeds the threshold. Catches runaway agent loops and expensive sessions.',ai_flagged_content:'Fires when an AI conversation matches a flagged content term. Uses the built-in profanity list plus custom terms from the project’s AI settings; optionally narrow to specific terms below.',- error_regression:- 'Fires when an error that was previously archived (resolved) occurs again.',+ error_regression: 'Fires when an error that was previously archived (resolved) occurs again.',check_down:'Fires when a monitor transitions to down (after its failure threshold), and sends a recovery notice when it comes back up. Applies to every monitor in this project.',error_rate_threshold:@@ -283,7 +282,7 @@}}- function buildConfig(): any {+ function buildConfig(): NotificationRuleConfig {switch (ruleType) {case 'error_rate_threshold':return { thresholdPercent, lookbackMinutes, minRequests };@@ -387,7 +386,7 @@</script><AlertDialog.Root {open} onOpenChange={handleOpenChange}>- <AlertDialog.Content class="max-w-lg max-h-[85vh] overflow-y-auto">+ <AlertDialog.Content class="max-h-[85vh] max-w-lg overflow-y-auto"><AlertDialog.Header><AlertDialog.Title>{isEditing ? 'Edit Rule' : 'New Rule'}</AlertDialog.Title><AlertDialog.Description>@@ -408,23 +407,17 @@<div class="space-y-2"><Label for="rule-name">Name</Label>- <Input- id="rule-name"- bind:value={name}- placeholder="e.g. High Error Rate"- required- />+ <Input id="rule-name" bind:value={name} placeholder="e.g. High Error Rate" required /></div><div class="space-y-2"><Label for="rule-channel">Channel</Label><Select.Root type="single" bind:value={channelId}><Select.Trigger class="w-full">- {channels.find((c) => c.id.toString() === channelId)?.name ||- 'Select channel'}+ {channels.find((c) => c.id.toString() === channelId)?.name || 'Select channel'}</Select.Trigger><Select.Content>- {#each channels as ch}+ {#each channels as ch, __index (__index)}<Select.Item value={ch.id.toString()}>{ch.name}</Select.Item>{/each}</Select.Content>@@ -438,7 +431,7 @@{ruleTypeOptions.find((o) => o.value === ruleType)?.label || 'Select type'}</Select.Trigger><Select.Content>- {#each visibleRuleTypes as option}+ {#each visibleRuleTypes as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content>@@ -446,13 +439,17 @@</div>{#if ruleTypeDescriptions[ruleType]}- <Alert.Root class="bg-amber-50 border-amber-200 text-amber-900 dark:bg-amber-950/50 dark:border-amber-800 dark:text-amber-200 ">+ <Alert.Root+ class="border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-200 "+ ><TriangleAlert class="text-amber-600 dark:text-amber-400" />- <Alert.Description class="text-amber-800 dark:text-amber-300">{ruleTypeDescriptions[ruleType]}</Alert.Description>+ <Alert.Description class="text-amber-800 dark:text-amber-300"+ >{ruleTypeDescriptions[ruleType]}</Alert.Description+ ></Alert.Root>{/if}- <div class="rounded-md border p-3 space-y-3">+ <div class="space-y-3 rounded-md border p-3"><p class="text-sm font-medium text-muted-foreground">Rule Configuration</p>{#if ruleType === 'error_rate_threshold'}@@ -468,21 +465,11 @@</div><div class="space-y-2"><Label for="cfg-lookback">Lookback (minutes)</Label>- <Input- id="cfg-lookback"- type="number"- bind:value={lookbackMinutes}- min="1"- />+ <Input id="cfg-lookback" type="number" bind:value={lookbackMinutes} min="1" /></div><div class="space-y-2"><Label for="cfg-min-req">Min Requests</Label>- <Input- id="cfg-min-req"- type="number"- bind:value={minRequests}- min="1"- />+ <Input id="cfg-min-req" type="number" bind:value={minRequests} min="1" /></div>{:else if ruleType === 'endpoint_p95_threshold' || ruleType === 'endpoint_p99_threshold'}<div class="space-y-2">@@ -491,21 +478,11 @@</div><div class="space-y-2"><Label for="cfg-threshold-ms">Threshold (ms)</Label>- <Input- id="cfg-threshold-ms"- type="number"- bind:value={thresholdMs}- min="1"- />+ <Input id="cfg-threshold-ms" type="number" bind:value={thresholdMs} min="1" /></div><div class="space-y-2"><Label for="cfg-lookback-p">Lookback (minutes)</Label>- <Input- id="cfg-lookback-p"- type="number"- bind:value={lookbackMinutes}- min="1"- />+ <Input id="cfg-lookback-p" type="number" bind:value={lookbackMinutes} min="1" /></div>{:else if ruleType === 'apdex_drop'}<div class="space-y-2">@@ -521,30 +498,16 @@</div><div class="space-y-2"><Label for="cfg-lookback-a">Lookback (minutes)</Label>- <Input- id="cfg-lookback-a"- type="number"- bind:value={lookbackMinutes}- min="1"- />+ <Input id="cfg-lookback-a" type="number" bind:value={lookbackMinutes} min="1" /></div><div class="space-y-2"><Label for="cfg-min-req-a">Min Requests</Label>- <Input- id="cfg-min-req-a"- type="number"- bind:value={minRequests}- min="1"- />+ <Input id="cfg-min-req-a" type="number" bind:value={minRequests} min="1" /></div>{:else if ruleType === 'metric_threshold'}<div class="space-y-2"><Label for="cfg-metric">Metric Name</Label>- <Input- id="cfg-metric"- bind:value={metricName}- placeholder="cpu.used_pcnt"- />+ <Input id="cfg-metric" bind:value={metricName} placeholder="cpu.used_pcnt" /></div><div class="space-y-2"><Label for="cfg-operator">Operator</Label>@@ -553,7 +516,7 @@{operatorOptions.find((o) => o.value === operator)?.label || operator}</Select.Trigger><Select.Content>- {#each operatorOptions as option}+ {#each operatorOptions as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content>@@ -561,22 +524,16 @@</div><div class="space-y-2"><Label for="cfg-value">Threshold Value</Label>- <Input- id="cfg-value"- type="number"- bind:value={thresholdValue}- step="0.1"- />+ <Input id="cfg-value" type="number" bind:value={thresholdValue} step="0.1" /></div><div class="space-y-2"><Label for="cfg-agg">Aggregation</Label><Select.Root type="single" bind:value={aggregation}><Select.Trigger class="w-full">- {aggregationOptions.find((o) => o.value === aggregation)?.label ||- aggregation}+ {aggregationOptions.find((o) => o.value === aggregation)?.label || aggregation}</Select.Trigger><Select.Content>- {#each aggregationOptions as option}+ {#each aggregationOptions as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content>@@ -584,12 +541,7 @@</div><div class="space-y-2"><Label for="cfg-lookback-m">Lookback (minutes)</Label>- <Input- id="cfg-lookback-m"- type="number"- bind:value={lookbackMinutes}- min="1"- />+ <Input id="cfg-lookback-m" type="number" bind:value={lookbackMinutes} min="1" /></div>{:else if ruleType === 'no_data'}<div class="space-y-2">@@ -599,7 +551,7 @@{dataTypeOptions.find((o) => o.value === dataType)?.label || dataType}</Select.Trigger><Select.Content>- {#each dataTypeOptions as option}+ {#each dataTypeOptions as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content>@@ -607,31 +559,16 @@</div><div class="space-y-2"><Label for="cfg-silence">Silence (minutes)</Label>- <Input- id="cfg-silence"- type="number"- bind:value={silenceMinutes}- min="1"- />+ <Input id="cfg-silence" type="number" bind:value={silenceMinutes} min="1" /></div>{:else if ruleType === 'error_count_threshold'}<div class="space-y-2"><Label for="cfg-count">Threshold Count</Label>- <Input- id="cfg-count"- type="number"- bind:value={thresholdCount}- min="1"- />+ <Input id="cfg-count" type="number" bind:value={thresholdCount} min="1" /></div><div class="space-y-2"><Label for="cfg-lookback-ec">Lookback (minutes)</Label>- <Input- id="cfg-lookback-ec"- type="number"- bind:value={lookbackMinutes}- min="1"- />+ <Input id="cfg-lookback-ec" type="number" bind:value={lookbackMinutes} min="1" /></div>{:else if ruleType === 'task_duration_threshold'}<div class="space-y-2">@@ -640,21 +577,11 @@</div><div class="space-y-2"><Label for="cfg-threshold-ms-t">Threshold (ms)</Label>- <Input- id="cfg-threshold-ms-t"- type="number"- bind:value={thresholdMs}- min="1"- />+ <Input id="cfg-threshold-ms-t" type="number" bind:value={thresholdMs} min="1" /></div><div class="space-y-2"><Label for="cfg-lookback-td">Lookback (minutes)</Label>- <Input- id="cfg-lookback-td"- type="number"- bind:value={lookbackMinutes}- min="1"- />+ <Input id="cfg-lookback-td" type="number" bind:value={lookbackMinutes} min="1" /></div>{:else if ruleType === 'task_failure_rate'}<div class="space-y-2">@@ -673,59 +600,29 @@</div><div class="space-y-2"><Label for="cfg-lookback-tf">Lookback (minutes)</Label>- <Input- id="cfg-lookback-tf"- type="number"- bind:value={lookbackMinutes}- min="1"- />+ <Input id="cfg-lookback-tf" type="number" bind:value={lookbackMinutes} min="1" /></div><div class="space-y-2"><Label for="cfg-min-exec">Min Executions</Label>- <Input- id="cfg-min-exec"- type="number"- bind:value={minExecutions}- min="1"- />+ <Input id="cfg-min-exec" type="number" bind:value={minExecutions} min="1" /></div>{:else if ruleType === 'throughput_drop'}<div class="space-y-2"><Label for="cfg-drop">Drop (%)</Label>- <Input- id="cfg-drop"- type="number"- bind:value={dropPercent}- step="0.1"- min="0"- />+ <Input id="cfg-drop" type="number" bind:value={dropPercent} step="0.1" min="0" /></div><div class="space-y-2"><Label for="cfg-lookback-tp">Lookback (minutes)</Label>- <Input- id="cfg-lookback-tp"- type="number"- bind:value={lookbackMinutes}- min="1"- />+ <Input id="cfg-lookback-tp" type="number" bind:value={lookbackMinutes} min="1" /></div><div class="space-y-2"><Label for="cfg-baseline">Baseline Window (minutes)</Label>- <Input- id="cfg-baseline"- type="number"- bind:value={baselineWindowMinutes}- min="1"- />+ <Input id="cfg-baseline" type="number" bind:value={baselineWindowMinutes} min="1" /></div>{:else if ruleType === 'endpoint_error_rate'}<div class="space-y-2"><Label for="cfg-endpoint-er">Endpoint</Label>- <Input- id="cfg-endpoint-er"- bind:value={endpoint}- placeholder="POST /api/checkout"- />+ <Input id="cfg-endpoint-er" bind:value={endpoint} placeholder="POST /api/checkout" /></div><div class="space-y-2"><Label for="cfg-threshold-er">Threshold (%)</Label>@@ -739,21 +636,11 @@</div><div class="space-y-2"><Label for="cfg-lookback-er">Lookback (minutes)</Label>- <Input- id="cfg-lookback-er"- type="number"- bind:value={lookbackMinutes}- min="1"- />+ <Input id="cfg-lookback-er" type="number" bind:value={lookbackMinutes} min="1" /></div><div class="space-y-2"><Label for="cfg-min-req-er">Min Requests</Label>- <Input- id="cfg-min-req-er"- type="number"- bind:value={minRequests}- min="1"- />+ <Input id="cfg-min-req-er" type="number" bind:value={minRequests} min="1" /></div>{:else if ruleType === 'new_error'}<div class="space-y-2">@@ -767,12 +654,7 @@{:else if ruleType === 'impact_score_critical' || ruleType === 'impact_score_high' || ruleType === 'impact_score_medium'}<div class="space-y-2"><Label for="cfg-min-req-impact">Min Requests</Label>- <Input- id="cfg-min-req-impact"- type="number"- bind:value={minRequests}- min="1"- />+ <Input id="cfg-min-req-impact" type="number" bind:value={minRequests} min="1" /></div>{:else if ruleType === 'ai_trace_cost'}<div class="space-y-2">@@ -821,12 +703,7 @@<div class="space-y-2"><Label for="rule-cooldown">Cooldown (minutes)</Label>- <Input- id="rule-cooldown"- type="number"- bind:value={cooldownMinutes}- min="1"- />+ <Input id="rule-cooldown" type="number" bind:value={cooldownMinutes} min="1" /></div><div class="space-y-2">@@ -836,13 +713,12 @@{severityOptions.find((o) => o.value === severity)?.label || 'Auto (default)'}</Select.Trigger><Select.Content>- {#each severityOptions as option}+ {#each severityOptions as option, __index (__index)}<Select.Item value={option.value}>{option.label}</Select.Item>{/each}</Select.Content></Select.Root></div>-</form><AlertDialog.Footer>diff --git a/frontend/src/routes/notifications/snooze-dialog.svelte b/frontend/src/routes/notifications/snooze-dialog.svelteindex e66e3518..10e80c01 100644--- a/frontend/src/routes/notifications/snooze-dialog.svelte+++ b/frontend/src/routes/notifications/snooze-dialog.svelte@@ -34,10 +34,10 @@{ durationMinutes },{ projectId: projectsState.currentProjectId ?? undefined });- toast.success('Rule snoozed', { position: 'top-center' });+ toast.success('Rule snoozed');onSaved();} catch {- toast.error('Failed to snooze rule', { position: 'top-center' });+ toast.error('Failed to snooze rule');} finally {loading = false;}@@ -53,10 +53,10 @@{ durationMinutes: 0 },{ projectId: projectsState.currentProjectId ?? undefined });- toast.success('Snooze cleared', { position: 'top-center' });+ toast.success('Snooze cleared');onSaved();} catch {- toast.error('Failed to clear snooze', { position: 'top-center' });+ toast.error('Failed to clear snooze');} finally {loading = false;}@@ -77,7 +77,7 @@</AlertDialog.Header><div class="grid gap-2">- {#each presets as preset}+ {#each presets as preset, __index (__index)}<Buttonvariant="outline"class="w-full justify-start"diff --git a/frontend/src/routes/oauth/authorize/+page.svelte b/frontend/src/routes/oauth/authorize/+page.svelteindex a792590f..1db452a2 100644--- a/frontend/src/routes/oauth/authorize/+page.svelte+++ b/frontend/src/routes/oauth/authorize/+page.svelte@@ -1,9 +1,15 @@<script lang="ts">- import { goto } from '$app/navigation';import { page } from '$app/state';+ import { gotoHref } from '$lib/utils/navigation';import { onMount } from 'svelte';import { Button } from '$lib/components/ui/button';- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '$lib/components/ui/card';+ import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle+ } from '$lib/components/ui/card';import { Alert, AlertDescription, AlertTitle } from '$lib/components/ui/alert';import { ErrorAlert } from '$lib/components/ui/error-alert';import { CircleAlert, ShieldCheck } from '@lucide/svelte';@@ -43,16 +49,19 @@function loginRedirect() {const target = page.url.pathname + page.url.search;- goto(`/login?returnTo=${encodeURIComponent(target)}`);+ gotoHref(`/login?returnTo=${encodeURIComponent(target)}`);}async function lookupClient() {status = 'loading';error = '';try {- const res = await fetch(`/api/oauth/client?client_id=${encodeURIComponent(params.clientId ?? '')}`, {- headers: { Authorization: `Bearer ${authState.token}` }- });+ const res = await fetch(+ `/api/oauth/client?client_id=${encodeURIComponent(params.clientId ?? '')}`,+ {+ headers: { Authorization: `Bearer ${authState.token}` }+ }+ );if (res.status === 401) {authState.logout();loginRedirect();@@ -105,7 +114,8 @@}if (!res.ok) {status = 'error';- error = 'The authorization request was rejected. Restart the connection from your application.';+ error =+ 'The authorization request was rejected. Restart the connection from your application.';return;}const data = await res.json();@@ -194,8 +204,8 @@<CircleAlert class="h-4 w-4" /><AlertTitle>Unknown application</AlertTitle><AlertDescription>- We don't recognize the application making this request. Restart the connection from- your application.+ We don't recognize the application making this request. Restart the connection from your+ application.</AlertDescription></Alert>{:else}diff --git a/frontend/src/routes/on-call/+page.svelte b/frontend/src/routes/on-call/+page.svelteindex 3351d3f9..84836bd6 100644--- a/frontend/src/routes/on-call/+page.svelte+++ b/frontend/src/routes/on-call/+page.svelte@@ -1,13 +1,15 @@<script lang="ts">import { onMount } from 'svelte';import { page } from '$app/state';- import { goto } from '$app/navigation';import { authState } from '$lib/state/auth.svelte';import { projectsState } from '$lib/state/projects.svelte';import { oncallState } from '$lib/state/oncall.svelte';- import * as Select from '$lib/components/ui/select';- import TabsRow from '$lib/components/traceway/tabs-row.svelte';+ import { setTabParam } from '$lib/utils/url-params';+ import PageTabs from '$lib/components/traceway/page-tabs.svelte';import InfoCallout from '$lib/components/traceway/info-callout.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import OrgSwitcher from '$lib/components/traceway/org-switcher.svelte';+ import EmptyState from '$lib/components/traceway/empty-state.svelte';import OverviewTab from './overview-tab.svelte';import TeamsTab from './teams-tab.svelte';import SchedulesTab from './schedules-tab.svelte';@@ -90,9 +92,7 @@}function setTab(tab: string) {- const url = new URL(window.location.href);- url.searchParams.set('tab', tab);- goto(url.toString(), { replaceState: true, noScroll: true });+ setTabParam(tab);}$effect(() => {@@ -104,42 +104,26 @@onMount(() => {if (deepLinkPageId !== null) {- const url = new URL(window.location.href);- url.searchParams.set('tab', 'pages');- url.searchParams.delete('page');- url.searchParams.delete('projectId');- goto(url.toString(), { replaceState: true, noScroll: true });+ setTabParam('pages', { clear: ['page', 'projectId'] });}});</script><div class="space-y-4">- <div class="flex flex-wrap items-center justify-between gap-4">- <h1 class="text-3xl font-semibold tracking-tight">On-Call</h1>- {#if orgs.length > 1}- <div class="flex items-center gap-2">- <span class="text-sm text-muted-foreground">Organization</span>- <Select.Root- type="single"- value={currentOrganizationId !== null ? String(currentOrganizationId) : undefined}- onValueChange={(val) => {- if (val) selectedOrgId = Number(val);- }}- >- <Select.Trigger class="w-[220px]">- {currentOrganizationName || 'Select organization'}- </Select.Trigger>- <Select.Content>- {#each orgs as org (org.id)}- <Select.Item value={String(org.id)}>{org.name}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- {/if}- </div>-- <TabsRow+ <PageHeader title="On-Call">+ {#snippet actions()}+ {#if orgs.length > 1}+ <OrgSwitcher+ organizations={orgs.map((o) => ({ id: o.id, name: o.name }))}+ {currentOrganizationId}+ {currentOrganizationName}+ onChange={(id) => (selectedOrgId = id)}+ />+ {/if}+ {/snippet}+ </PageHeader>++ <PageTabstabs={TABS}{activeTab}onTabChange={setTab}@@ -152,11 +136,7 @@{/if}{#if currentOrganizationId === null}- <div- class="flex flex-col items-center justify-center rounded-md bg-muted py-20 text-center text-muted-foreground"- >- <p>You are not a member of any organization yet.</p>- </div>+ <EmptyState message="You are not a member of any organization yet." />{:else if activeTab === 'pages'}<PagesTab {deepLinkPageId} />{:else if activeTab === 'overview'}diff --git a/frontend/src/routes/on-call/layer-editor.svelte b/frontend/src/routes/on-call/layer-editor.svelteindex ed0402c6..99370c54 100644--- a/frontend/src/routes/on-call/layer-editor.svelte+++ b/frontend/src/routes/on-call/layer-editor.svelte@@ -6,14 +6,7 @@import { Label } from '$lib/components/ui/label';import * as Select from '$lib/components/ui/select';import { ErrorAlert } from '$lib/components/ui/error-alert';- import {- Plus,- Check,- Trash2,- ChevronUp,- ChevronDown,- X- } from '@lucide/svelte';+ import { Plus, Check, Trash2, ChevronUp, ChevronDown, X } from '@lucide/svelte';import { toast } from 'svelte-sonner';import {oncallState,@@ -66,8 +59,7 @@// by a day for users whose local date differs from the schedule-local date.function todayISODate(): string {return (- DateTime.now().setZone(schedule.timezone).toISODate() ??- new Date().toISOString().slice(0, 10)+ DateTime.now().setZone(schedule.timezone).toISODate() ?? new Date().toISOString().slice(0, 10));}@@ -351,7 +343,9 @@{#if restriction.type === 'weekly'}<Select.Roottype="single"- value={restriction.startDay !== undefined ? String(restriction.startDay) : undefined}+ value={restriction.startDay !== undefined+ ? String(restriction.startDay)+ : undefined}onValueChange={(val) => {if (val) restriction.startDay = Number(val);}}@@ -404,7 +398,7 @@<div class="flex items-center justify-between"><Button variant="outline" size="sm" onclick={addLayer}>- <Plus class="mr-1 h-4 w-4" /> Add Layer+ <Plus class="mr-2 h-4 w-4" /> Add Layer</Button><div class="flex gap-2"><Button variant="outline" onclick={onCancel} disabled={loading}>Cancel</Button>diff --git a/frontend/src/routes/on-call/override-dialog.svelte b/frontend/src/routes/on-call/override-dialog.svelteindex 5b993008..4bf46704 100644--- a/frontend/src/routes/on-call/override-dialog.svelte+++ b/frontend/src/routes/on-call/override-dialog.svelte@@ -7,11 +7,8 @@import { ErrorAlert } from '$lib/components/ui/error-alert';import { Plus } from '@lucide/svelte';import { toast } from 'svelte-sonner';- import {- oncallState,- getCurrentUserFromToken,- type Schedule- } from '$lib/state/oncall.svelte';+ import { oncallState, getCurrentUserFromToken, type Schedule } from '$lib/state/oncall.svelte';+ import { toLocalInputValue } from '$lib/utils/formatters';interface Props {open: boolean;@@ -43,11 +40,6 @@return list;});- function toLocalInputValue(date: Date): string {- const pad = (n: number) => String(n).padStart(2, '0');- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;- }-$effect(() => {if (open) {const now = new Date();diff --git a/frontend/src/routes/on-call/overview-tab.svelte b/frontend/src/routes/on-call/overview-tab.svelteindex 52f290e3..79810bad 100644--- a/frontend/src/routes/on-call/overview-tab.svelte+++ b/frontend/src/routes/on-call/overview-tab.svelte@@ -7,8 +7,9 @@CardTitle} from '$lib/components/ui/card';import { Badge } from '$lib/components/ui/badge';- import { Button } from '$lib/components/ui/button';import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import EmptyState from '$lib/components/traceway/empty-state.svelte';import * as Avatar from '$lib/components/ui/avatar';import { CalendarClock, FolderGit2 } from '@lucide/svelte';import { oncallState, type OncallUser } from '$lib/state/oncall.svelte';@@ -45,21 +46,17 @@{#if oncallState.overviewLoading}<div class="flex justify-center py-12"><LoadingCircle size="xlg" /></div>{:else if oncallState.overviewError}- <div- class="flex flex-col items-center justify-center gap-3 rounded-md bg-muted py-20 text-center text-muted-foreground"- >- <p class="text-sm text-destructive">{oncallState.overviewError}</p>- <Button variant="outline" size="sm" onclick={() => oncallState.loadOverview(organizationId)}>- Retry- </Button>- </div>+ <ErrorRetryBox+ message={oncallState.overviewError}+ onRetry={() => oncallState.loadOverview(organizationId)}+ />{:else if overview.length === 0}- <div- class="flex flex-col items-center justify-center rounded-md bg-muted py-20 text-center text-muted-foreground"- >- <p class="mb-4">Create a team to get started.</p>- <Button variant="outline" onclick={onGoToTeams}>Go to Teams</Button>- </div>+ <EmptyState+ message="Create a team to get started."+ actionLabel="Go to Teams"+ actionVariant="outline"+ onAction={onGoToTeams}+ />{:else}<div class="grid gap-4 lg:grid-cols-2">{#each overview as entry (entry.team.id)}diff --git a/frontend/src/routes/on-call/page-actions.ts b/frontend/src/routes/on-call/page-actions.tsindex a139e33a..dca71977 100644--- a/frontend/src/routes/on-call/page-actions.ts+++ b/frontend/src/routes/on-call/page-actions.ts@@ -24,12 +24,12 @@ export async function runPageAction(id: number, action: 'acknowledge' | 'resolve{},{ projectId: projectsState.currentProjectId ?? undefined });- toast.success(`Page ${done}`, { position: 'top-center' });+ toast.success(`Page ${done}`);} catch (e: unknown) {if ((e as { status?: number }).status === 409) {- toast.error(`Page is already ${await conflictStatus(id)}`, { position: 'top-center' });+ toast.error(`Page is already ${await conflictStatus(id)}`);} else {- toast.error(`Failed to ${action} page`, { position: 'top-center' });+ toast.error(`Failed to ${action} page`);}}oncallState.refreshOpenCount();@@ -57,21 +57,19 @@ export async function runBulkPageAction(const count = (action === 'acknowledge' ? res.acknowledged : res.resolved) ?? 0;const archived = res.archivedIssues ?? 0;if (count === 0 && archived === 0) {- toast.error(- ids.length === 1 ? `Page was already ${done}` : `Pages were already ${done}`,- { position: 'top-center' }- );+ toast.error(ids.length === 1 ? `Page was already ${done}` : `Pages were already ${done}`);} else {- let message = count === 1 && ids.length === 1 ? `Page ${done}` : `${count} ${pluralPages(count)} ${done}`;+ let message =+ count === 1 && ids.length === 1 ? `Page ${done}` : `${count} ${pluralPages(count)} ${done}`;if (archived > 0) {message += ` and ${archived} issue${archived === 1 ? '' : 's'} archived`;}- toast.success(message, { position: 'top-center' });+ toast.success(message);}oncallState.refreshOpenCount();return true;} catch {- toast.error(`Failed to ${action} ${pluralPages(ids.length)}`, { position: 'top-center' });+ toast.error(`Failed to ${action} ${pluralPages(ids.length)}`);oncallState.refreshOpenCount();return false;}diff --git a/frontend/src/routes/on-call/page-detail-sheet.svelte b/frontend/src/routes/on-call/page-detail-sheet.svelteindex 17435e2b..ccb4ca1c 100644--- a/frontend/src/routes/on-call/page-detail-sheet.svelte+++ b/frontend/src/routes/on-call/page-detail-sheet.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import { resolveHref } from '$lib/utils/links';import * as Sheet from '$lib/components/ui/sheet';import { Button } from '$lib/components/ui/button';import { LoadingCircle } from '$lib/components/ui/loading-circle';@@ -9,7 +10,7 @@import { type PageDetailResponse, type PageNotification } from '$lib/state/oncall.svelte';import { formatDateTime, formatRelativeTimeAgo } from '$lib/utils/formatters';import { runPageAction } from './page-actions';- import PageBadges from './page-badges.svelte';+ import PageBadges from '$lib/components/traceway/page-badges.svelte';import ResolvePageDialog from './resolve-page-dialog.svelte';import EscalationChain from '$lib/components/traceway/escalation-chain.svelte';@@ -52,9 +53,7 @@} catch (e: unknown) {if (seq !== loadSeq) return;const status = (e as { status?: number }).status;- toast.error(status === 404 ? 'Page not found' : 'Failed to load page', {- position: 'top-center'- });+ toast.error(status === 404 ? 'Page not found' : 'Failed to load page');open = false;} finally {if (seq === loadSeq) loading = false;@@ -80,10 +79,7 @@}function formatClock(value: string): string {- return new Date(value).toLocaleTimeString(undefined, {- hour: '2-digit',- minute: '2-digit'- });+ return formatDateTime(value, { format: 'time' });}let resolveDialogOpen = $state(false);@@ -146,7 +142,7 @@{#if pageData.url}<a- href={pageData.url}+ {...{ href: resolveHref(pageData.url) }}class="inline-flex items-center gap-1 text-sm text-blue-600 hover:underline dark:text-blue-400"><ExternalLink class="h-3.5 w-3.5" />@@ -157,9 +153,9 @@{#if pageData.body}<div class="space-y-1"><div class="text-xs text-muted-foreground">Details</div>- <p- class="text-sm whitespace-pre-wrap {bodyExpanded ? '' : 'line-clamp-6'}"- >{pageData.body}</p>+ <p class="text-sm whitespace-pre-wrap {bodyExpanded ? '' : 'line-clamp-6'}">+ {pageData.body}+ </p>{#if pageData.body.length > 300 || pageData.body.split('\n').length > 6}<Buttonvariant="link"@@ -243,7 +239,9 @@{/if}</div>{#if notification.status === 'failed' && notification.errorMsg}- <div class="text-xs break-words text-destructive">{notification.errorMsg}</div>+ <div class="text-xs break-words text-destructive">+ {notification.errorMsg}+ </div>{/if}{#if !scheduled}<div class="text-xs text-muted-foreground">@@ -268,7 +266,9 @@{:else}Acknowledged by {userName(pageData.acknowledgedBy)}{/if}- <div class="text-xs text-muted-foreground">{formatTime(pageData.acknowledgedAt)}</div>+ <div class="text-xs text-muted-foreground">+ {formatTime(pageData.acknowledgedAt)}+ </div></div></div>{/if}@@ -288,11 +288,11 @@<Sheet.Footer class="flex-row justify-end border-t px-6">{#if pageData.status === 'open'}<Button variant="outline" onclick={acknowledge} disabled={actionLoading}>- <Check class="mr-1 h-4 w-4" /> Acknowledge+ <Check class="mr-2 h-4 w-4" /> Acknowledge</Button>{/if}<Button onclick={() => (resolveDialogOpen = true)} disabled={actionLoading}>- <CheckCheck class="mr-1 h-4 w-4" /> Resolve+ <CheckCheck class="mr-2 h-4 w-4" /> Resolve</Button></Sheet.Footer>{/if}@@ -300,8 +300,4 @@</Sheet.Content></Sheet.Root>-<ResolvePageDialog- bind:open={resolveDialogOpen}- pages={pageData ? [pageData] : []}- onResolved={onResolved}-/>+<ResolvePageDialog bind:open={resolveDialogOpen} pages={pageData ? [pageData] : []} {onResolved} />diff --git a/frontend/src/routes/on-call/pages-tab.svelte b/frontend/src/routes/on-call/pages-tab.svelteindex 3a1e97f7..8bb79277 100644--- a/frontend/src/routes/on-call/pages-tab.svelte+++ b/frontend/src/routes/on-call/pages-tab.svelte@@ -1,18 +1,21 @@<script lang="ts">import { onMount } from 'svelte';+ import { SvelteSet } from 'svelte/reactivity';import { Button } from '$lib/components/ui/button';import { Checkbox } from '$lib/components/ui/checkbox';import * as Table from '$lib/components/ui/table';import { LoadingCircle } from '$lib/components/ui/loading-circle';import { TableEmptyState } from '$lib/components/ui/table-empty-state';import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import BulkActionsBar from '$lib/components/traceway/bulk-actions-bar.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';import { Check, CheckCheck } from '@lucide/svelte';import { api } from '$lib/api';import { formatDateTime, formatRelativeTimeAgo } from '$lib/utils/formatters';import { projectsState } from '$lib/state/projects.svelte';import { type OncallPage } from '$lib/state/oncall.svelte';import { runPageAction } from './page-actions';- import PageBadges from './page-badges.svelte';+ import PageBadges from '$lib/components/traceway/page-badges.svelte';import PageDetailSheet from './page-detail-sheet.svelte';import ResolvePageDialog from './resolve-page-dialog.svelte';import AcknowledgePagesDialog from './acknowledge-pages-dialog.svelte';@@ -65,9 +68,7 @@// swaps Status for who/when acknowledged, resolved drops Actions and shows// both who/when columns.const showStatus = $derived(statusFilter === 'active' || statusFilter === 'open');- const showAcknowledged = $derived(- statusFilter === 'acknowledged' || statusFilter === 'resolved'- );+ const showAcknowledged = $derived(statusFilter === 'acknowledged' || statusFilter === 'resolved');const showResolved = $derived(statusFilter === 'resolved');const showActions = $derived(statusFilter !== 'resolved');const colCount = $derived(selectable ? 8 : 7);@@ -181,7 +182,7 @@}function toggleSelect(id: number) {- const newSet = new Set(selectedIds);+ const newSet = new SvelteSet(selectedIds);if (newSet.has(id)) {newSet.delete(id);} else {@@ -222,14 +223,14 @@{/each}</div>- <!-- Bulk actions toolbar - shown when items selected -->{#if selectable && selectedCount > 0}- <div- class="flex animate-in items-center gap-3 rounded-md border bg-muted/50 p-3 duration-200 fade-in slide-in-from-top-1"+ <BulkActionsBar+ count={selectedCount}+ itemLabel="page"+ onClear={() => (selectedIds = new Set())}>- <span class="text-sm font-medium"- >{selectedCount} page{selectedCount === 1 ? '' : 's'} selected</span- >+ <!-- Reachable even though the bar needs a selection: on the active tab a+ selection of only-acknowledged pages has nothing left to acknowledge. --><Buttonvariant="outline"size="sm"@@ -244,13 +245,10 @@<CheckCheck class="h-4 w-4" />Resolve</Button>- <Button variant="ghost" size="sm" onclick={() => (selectedIds = new Set())}>- Clear selection- </Button>- </div>+ </BulkActionsBar>{/if}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root>{#if loading}<Table.Body>@@ -400,7 +398,7 @@</Table.Body>{/if}</Table.Root>- </div>+ </TableContainer><PaginationFooter{currentPage}@@ -415,4 +413,8 @@<PageDetailSheet bind:open={sheetOpen} pageId={selectedPageId} onChanged={loadPages} /><ResolvePageDialog bind:open={resolveDialogOpen} pages={resolveTargets} onResolved={loadPages} />-<AcknowledgePagesDialog bind:open={ackDialogOpen} pages={selectedOpenPages} onAcknowledged={loadPages} />+<AcknowledgePagesDialog+ bind:open={ackDialogOpen}+ pages={selectedOpenPages}+ onAcknowledged={loadPages}+/>diff --git a/frontend/src/routes/on-call/policies-tab.svelte b/frontend/src/routes/on-call/policies-tab.svelteindex 687750e8..e6032b1e 100644--- a/frontend/src/routes/on-call/policies-tab.svelte+++ b/frontend/src/routes/on-call/policies-tab.svelte@@ -1,6 +1,5 @@<script lang="ts">import { Button } from '$lib/components/ui/button';- import * as AlertDialog from '$lib/components/ui/alert-dialog';import {Card,CardContent,@@ -8,9 +7,10 @@CardHeader,CardTitle} from '$lib/components/ui/card';- import { ErrorAlert } from '$lib/components/ui/error-alert';import { LoadingCircle } from '$lib/components/ui/loading-circle';import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';import { Pencil, Trash2 } from '@lucide/svelte';import { toast } from 'svelte-sonner';import { api } from '$lib/api';@@ -42,6 +42,7 @@let editingPolicy = $state<EscalationPolicy | null>(null);let deletingPolicy = $state<EscalationPolicy | null>(null);+ let deleteDialogOpen = $state(false);let deleting = $state(false);let deleteError = $state('');@@ -122,7 +123,8 @@deleteError = '';try {await oncallState.deletePolicy(organizationId, deletingPolicy.id);- toast.success('Successfully deleted the Policy', { position: 'top-center' });+ toast.success('Successfully deleted the Policy');+ deleteDialogOpen = false;deletingPolicy = null;} catch (e: unknown) {deleteError = e instanceof Error ? e.message : 'Failed to delete policy';@@ -135,16 +137,12 @@<div class="space-y-4">{#if oncallState.policiesLoading}<div class="flex justify-center py-12"><LoadingCircle size="xlg" /></div>- {:else if oncallState.policiesError}- <div- class="flex flex-col items-center justify-center gap-3 rounded-md bg-muted py-20 text-center text-muted-foreground"- >- <p class="text-sm text-destructive">{oncallState.policiesError}</p>- <Button variant="outline" size="sm" onclick={() => oncallState.loadPolicies(organizationId)}>- Retry- </Button>- </div>-{:else if oncallState.policies.length === 0}+ {:else if oncallState.policiesError}+ <ErrorRetryBox+ message={oncallState.policiesError}+ onRetry={() => oncallState.loadPolicies(organizationId)}+ />+ {:else if oncallState.policies.length === 0}<EmptyStatemessage="No escalation policies yet. Define who gets paged, and in what order."actionLabel={canManage ? 'Create your first Policy' : undefined}@@ -177,6 +175,7 @@onclick={() => {deleteError = '';deletingPolicy = policy;+ deleteDialogOpen = true;}}><Trash2 class="h-4 w-4" />@@ -205,29 +204,11 @@}}/>-<AlertDialog.Root- open={deletingPolicy !== null}- onOpenChange={(open) => {- if (!open) {- deletingPolicy = null;- deleteError = '';- }- }}->- <AlertDialog.Content>- <AlertDialog.Header>- <AlertDialog.Title>Delete Policy</AlertDialog.Title>- <AlertDialog.Description>- Are you sure you want to delete "{deletingPolicy?.name}"? This action cannot be undone.- </AlertDialog.Description>- </AlertDialog.Header>- <ErrorAlert error={deleteError} />- <AlertDialog.Footer>- <AlertDialog.Cancel disabled={deleting}>Cancel</AlertDialog.Cancel>- <Button variant="destructive" onclick={confirmDelete} disabled={deleting}>- <Trash2 class="mr-1 h-4 w-4" />- {deleting ? 'Deleting...' : 'Delete Policy'}- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>-</AlertDialog.Root>+<ConfirmDeleteDialog+ bind:open={deleteDialogOpen}+ entity="Policy"+ description={`Are you sure you want to delete "${deletingPolicy?.name}"? This action cannot be undone.`}+ error={deleteError}+ loading={deleting}+ onConfirm={confirmDelete}+/>diff --git a/frontend/src/routes/on-call/policy-dialog.svelte b/frontend/src/routes/on-call/policy-dialog.svelteindex fc3e8739..1011b716 100644--- a/frontend/src/routes/on-call/policy-dialog.svelte+++ b/frontend/src/routes/on-call/policy-dialog.svelte@@ -5,7 +5,18 @@import { Label } from '$lib/components/ui/label';import * as Select from '$lib/components/ui/select';import { ErrorAlert } from '$lib/components/ui/error-alert';- import { Plus, Check, Trash2, X, ChevronUp, ChevronDown, Calendar, User, Users, Bell } from '@lucide/svelte';+ import {+ Plus,+ Check,+ Trash2,+ X,+ ChevronUp,+ ChevronDown,+ Calendar,+ User,+ Users,+ Bell+ } from '@lucide/svelte';import { toast } from 'svelte-sonner';import {oncallState,@@ -30,8 +41,14 @@onSaved: () => void;}- let { open = $bindable(), organizationId, policy, targetOptions, labels, onSaved }: Props =- $props();+ let {+ open = $bindable(),+ organizationId,+ policy,+ targetOptions,+ labels,+ onSaved+ }: Props = $props();interface StepDraft {delayMinutes: number;@@ -289,7 +306,7 @@</div><div class="flex items-center gap-2">- <Label for="step-delay-{index}" class="whitespace-nowrap text-xs font-normal">+ <Label for="step-delay-{index}" class="text-xs font-normal whitespace-nowrap">Escalate after</Label><Input@@ -312,7 +329,14 @@<div class="space-y-2"><Label for="policy-repeat">Repeat</Label>- <Input id="policy-repeat" type="number" min={0} max={5} class="w-20" bind:value={repeatCount} />+ <Input+ id="policy-repeat"+ type="number"+ min={0}+ max={5}+ class="w-20"+ bind:value={repeatCount}+ /><p class="text-xs text-muted-foreground">After the last step, repeat the chain N more times.</p>diff --git a/frontend/src/routes/on-call/resolve-page-dialog.svelte b/frontend/src/routes/on-call/resolve-page-dialog.svelteindex afb131ac..2790b0db 100644--- a/frontend/src/routes/on-call/resolve-page-dialog.svelte+++ b/frontend/src/routes/on-call/resolve-page-dialog.svelte@@ -17,9 +17,7 @@let loading = $state(false);let archiveIssues = $state(true);- const linkedIssueCount = $derived(- new Set(pages.map((p) => p.issueHash).filter(Boolean)).size- );+ const linkedIssueCount = $derived(new Set(pages.map((p) => p.issueHash).filter(Boolean)).size);// Archiving is a write on the issues while resolving is not, so the option// is only offered when pages are issue-linked and the user can write.const canArchiveIssues = $derived(linkedIssueCount > 0 && projectsState.canWriteCurrentProject);diff --git a/frontend/src/routes/on-call/schedule-detail.svelte b/frontend/src/routes/on-call/schedule-detail.svelteindex 56c73318..f9d2f35a 100644--- a/frontend/src/routes/on-call/schedule-detail.svelte+++ b/frontend/src/routes/on-call/schedule-detail.svelte@@ -9,15 +9,11 @@} from '$lib/components/ui/card';import { Button } from '$lib/components/ui/button';import { Badge } from '$lib/components/ui/badge';- import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';import { LoadingCircle } from '$lib/components/ui/loading-circle';import { Pencil, Trash2, Plus, Layers } from '@lucide/svelte';import { toast } from 'svelte-sonner';- import {- oncallState,- type Schedule,- type ScheduleOverride- } from '$lib/state/oncall.svelte';+ import { oncallState, type Schedule, type ScheduleOverride } from '$lib/state/oncall.svelte';import { formatDateTime } from '$lib/utils/formatters';import ScheduleDialog from './schedule-dialog.svelte';import ScheduleTimeline from './schedule-timeline.svelte';@@ -41,8 +37,11 @@let editDialogOpen = $state(false);let overrideDialogOpen = $state(false);let showDeleteDialog = $state(false);+ let deletingSchedule = $state(false);let showLayerEditor = $state(false);let overrideToDelete = $state<ScheduleOverride | null>(null);+ let showDeleteOverrideDialog = $state(false);+ let deletingOverride = $state(false);let timelineRefreshKey = $state(0);const team = $derived(oncallState.teams.find((t) => t.id === schedule?.teamId));@@ -67,30 +66,32 @@}async function handleDeleteSchedule() {+ deletingSchedule = true;try {await oncallState.deleteSchedule(organizationId, scheduleId);- toast.success('Successfully deleted the Schedule', { position: 'top-center' });+ toast.success('Successfully deleted the Schedule');showDeleteDialog = false;onDeleted();} catch (e) {- toast.error(e instanceof Error ? e.message : 'Failed to delete schedule', {- position: 'top-center'- });+ toast.error(e instanceof Error ? e.message : 'Failed to delete schedule');+ } finally {+ deletingSchedule = false;}}async function handleDeleteOverride() {if (!overrideToDelete) return;+ deletingOverride = true;try {await oncallState.deleteOverride(organizationId, scheduleId, overrideToDelete.id);- toast.success('Successfully deleted the Override', { position: 'top-center' });+ toast.success('Successfully deleted the Override');overrides = overrides.filter((o) => o.id !== overrideToDelete!.id);timelineRefreshKey += 1;} catch (e) {- toast.error(e instanceof Error ? e.message : 'Failed to delete override', {- position: 'top-center'- });+ toast.error(e instanceof Error ? e.message : 'Failed to delete override');} finally {+ deletingOverride = false;+ showDeleteOverrideDialog = false;overrideToDelete = null;}}@@ -121,12 +122,8 @@</div>{#if canManage}<div class="flex shrink-0 gap-1">- <Button- variant="outline"- size="sm"- onclick={() => (showLayerEditor = !showLayerEditor)}- >- <Layers class="mr-1 h-4 w-4" /> Edit Layers+ <Button variant="outline" size="sm" onclick={() => (showLayerEditor = !showLayerEditor)}>+ <Layers class="mr-2 h-4 w-4" /> Edit Layers</Button><Button variant="ghost" size="icon" title="Edit" onclick={() => (editDialogOpen = true)}><Pencil class="h-4 w-4" />@@ -165,7 +162,7 @@<div class="flex items-center justify-between"><h3 class="text-sm font-medium">Overrides (next 30 days) · {schedule.timezone}</h3><Button size="sm" variant="outline" onclick={() => (overrideDialogOpen = true)}>- <Plus class="mr-1 h-4 w-4" /> Add Override+ <Plus class="mr-2 h-4 w-4" /> Add Override</Button></div>{#if overrides.length === 0}@@ -190,7 +187,10 @@variant="ghost"size="icon"title="Delete"- onclick={() => (overrideToDelete = override)}+ onclick={() => {+ overrideToDelete = override;+ showDeleteOverrideDialog = true;+ }}><Trash2 class="h-4 w-4" /></Button>@@ -224,46 +224,19 @@}}/>- <AlertDialog.Root bind:open={showDeleteDialog}>- <AlertDialog.Content>- <AlertDialog.Header>- <AlertDialog.Title>Delete Schedule</AlertDialog.Title>- <AlertDialog.Description>- Are you sure you want to delete "{schedule.name}"? This action cannot be undone.- </AlertDialog.Description>- </AlertDialog.Header>- <AlertDialog.Footer>- <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>- <AlertDialog.Action variant="destructive" onclick={handleDeleteSchedule}>- <Trash2 class="mr-2 h-4 w-4" />- Delete Schedule- </AlertDialog.Action>- </AlertDialog.Footer>- </AlertDialog.Content>- </AlertDialog.Root>+ <ConfirmDeleteDialog+ bind:open={showDeleteDialog}+ entity="Schedule"+ description={`Are you sure you want to delete "${schedule.name}"? This action cannot be undone.`}+ loading={deletingSchedule}+ onConfirm={handleDeleteSchedule}+ />- <AlertDialog.Root- open={overrideToDelete !== null}- onOpenChange={(open) => {- if (!open) overrideToDelete = null;- }}- >- <AlertDialog.Content>- <AlertDialog.Header>- <AlertDialog.Title>Delete Override</AlertDialog.Title>- <AlertDialog.Description>- Are you sure you want to delete the override for {overrideToDelete- ? userLabel(overrideToDelete.userId)- : ''}?- </AlertDialog.Description>- </AlertDialog.Header>- <AlertDialog.Footer>- <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>- <AlertDialog.Action variant="destructive" onclick={handleDeleteOverride}>- <Trash2 class="mr-2 h-4 w-4" />- Delete Override- </AlertDialog.Action>- </AlertDialog.Footer>- </AlertDialog.Content>- </AlertDialog.Root>+ <ConfirmDeleteDialog+ bind:open={showDeleteOverrideDialog}+ entity="Override"+ description={`Are you sure you want to delete the override for ${overrideToDelete ? userLabel(overrideToDelete.userId) : ''}?`}+ loading={deletingOverride}+ onConfirm={handleDeleteOverride}+ />{/if}diff --git a/frontend/src/routes/on-call/schedule-dialog.svelte b/frontend/src/routes/on-call/schedule-dialog.svelteindex 3a59dfed..5af149a7 100644--- a/frontend/src/routes/on-call/schedule-dialog.svelte+++ b/frontend/src/routes/on-call/schedule-dialog.svelte@@ -89,9 +89,7 @@<AlertDialog.Header><AlertDialog.Title>{isEditing ? 'Edit Schedule' : 'New Schedule'}</AlertDialog.Title><AlertDialog.Description>- {isEditing- ? 'Update the schedule details'- : 'Create an on-call schedule for a team'}+ {isEditing ? 'Update the schedule details' : 'Create an on-call schedule for a team'}</AlertDialog.Description></AlertDialog.Header>diff --git a/frontend/src/routes/on-call/schedule-timeline.svelte b/frontend/src/routes/on-call/schedule-timeline.svelteindex d23ab461..ce8bc3d3 100644--- a/frontend/src/routes/on-call/schedule-timeline.svelte+++ b/frontend/src/routes/on-call/schedule-timeline.svelte@@ -117,8 +117,7 @@const ticks = $derived.by(() => {const result: { pos: number; label: string }[] = [];- const step =- preset === 'day' ? { hours: 3 } : preset === 'month' ? { days: 2 } : { days: 1 };+ const step = preset === 'day' ? { hours: 3 } : preset === 'month' ? { days: 2 } : { days: 1 };let cursor = rangeFrom;while (cursor < rangeTo) {const pos = ((cursor.toMillis() - rangeFrom.toMillis()) / totalMs) * 100;@@ -233,7 +232,7 @@{:else if timeline}<div class="overflow-x-auto rounded-md border"><div class="grid min-w-[640px] grid-cols-[140px_1fr]" class:opacity-60={loading}>- <div class="border-b border-r px-3 py-1.5 text-xs text-muted-foreground">+ <div class="border-r border-b px-3 py-1.5 text-xs text-muted-foreground">{tz}</div><div class="relative h-7 border-b">@@ -249,7 +248,7 @@{#each rows as row (row.id)}<div- class="flex items-center border-b border-r px-3 py-2 text-sm {row.id === '__final__'+ class="flex items-center border-r border-b px-3 py-2 text-sm {row.id === '__final__'? 'font-medium': ''}">@@ -281,9 +280,7 @@{userName(shift.userId)}</span>{#if shift.isOverride && width > 14}- <span- class="ml-1.5 shrink-0 rounded bg-white/25 px-1 text-[9px] uppercase"- >+ <span class="ml-1.5 shrink-0 rounded bg-white/25 px-1 text-[9px] uppercase">Override</span>{/if}diff --git a/frontend/src/routes/on-call/schedules-tab.svelte b/frontend/src/routes/on-call/schedules-tab.svelteindex 4522b6e3..5e7f5d77 100644--- a/frontend/src/routes/on-call/schedules-tab.svelte+++ b/frontend/src/routes/on-call/schedules-tab.svelte@@ -1,9 +1,10 @@<script lang="ts">- import { Button } from '$lib/components/ui/button';import { Badge } from '$lib/components/ui/badge';import * as Table from '$lib/components/ui/table';import { LoadingCircle } from '$lib/components/ui/loading-circle';import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';import { oncallState, type Schedule } from '$lib/state/oncall.svelte';import ScheduleDialog from './schedule-dialog.svelte';import ScheduleDetail from './schedule-detail.svelte';@@ -43,23 +44,19 @@<div class="space-y-4">{#if oncallState.schedulesLoading}<div class="flex justify-center py-12"><LoadingCircle size="xlg" /></div>- {:else if oncallState.schedulesError}- <div- class="flex flex-col items-center justify-center gap-3 rounded-md bg-muted py-20 text-center text-muted-foreground"- >- <p class="text-sm text-destructive">{oncallState.schedulesError}</p>- <Button variant="outline" size="sm" onclick={() => oncallState.loadSchedules(organizationId)}>- Retry- </Button>- </div>-{:else if schedules.length === 0}+ {:else if oncallState.schedulesError}+ <ErrorRetryBox+ message={oncallState.schedulesError}+ onRetry={() => oncallState.loadSchedules(organizationId)}+ />+ {:else if schedules.length === 0}<EmptyStatemessage="No schedules yet. Create one to get started."actionLabel={canManage ? 'Create your first Schedule' : undefined}onAction={openNew}/>{:else}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root><Table.Header><Table.Row>@@ -85,7 +82,7 @@{/each}</Table.Body></Table.Root>- </div>+ </TableContainer>{/if}{#if selectedScheduleId !== null}diff --git a/frontend/src/routes/on-call/team-dialog.svelte b/frontend/src/routes/on-call/team-dialog.svelteindex 1ee33bc1..f53afa01 100644--- a/frontend/src/routes/on-call/team-dialog.svelte+++ b/frontend/src/routes/on-call/team-dialog.svelte@@ -62,9 +62,7 @@function populateFromTeam(t: Team) {name = t.name;description = t.description;- selectedUserIds = [...t.members]- .sort((a, b) => a.position - b.position)- .map((m) => m.userId);+ selectedUserIds = [...t.members].sort((a, b) => a.position - b.position).map((m) => m.userId);selectedProjectIds = t.projects.map((p) => p.projectId);error = '';}@@ -181,7 +179,9 @@{:else}<div class="max-h-44 space-y-1 overflow-y-auto rounded-md border p-2">{#each members as member (member.id)}- <label class="flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 hover:bg-accent">+ <label+ class="flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 hover:bg-accent"+ ><Checkboxchecked={selectedUserIds.includes(member.id)}onCheckedChange={(checked) => toggleMember(member.id, checked === true)}@@ -245,7 +245,9 @@{:else}<div class="max-h-36 space-y-1 overflow-y-auto rounded-md border p-2">{#each orgProjects as project (project.id)}- <label class="flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 hover:bg-accent">+ <label+ class="flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 hover:bg-accent"+ ><Checkboxchecked={selectedProjectIds.includes(project.id)}onCheckedChange={(checked) => toggleProject(project.id, checked === true)}diff --git a/frontend/src/routes/on-call/teams-tab.svelte b/frontend/src/routes/on-call/teams-tab.svelteindex a1cffafe..4d47481b 100644--- a/frontend/src/routes/on-call/teams-tab.svelte+++ b/frontend/src/routes/on-call/teams-tab.svelte@@ -2,10 +2,12 @@import { Button } from '$lib/components/ui/button';import { Badge } from '$lib/components/ui/badge';import * as Table from '$lib/components/ui/table';- import * as AlertDialog from '$lib/components/ui/alert-dialog';import * as Avatar from '$lib/components/ui/avatar';import { LoadingCircle } from '$lib/components/ui/loading-circle';import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';import { Pencil, Trash2 } from '@lucide/svelte';import { toast } from 'svelte-sonner';import { oncallState, type Team } from '$lib/state/oncall.svelte';@@ -21,6 +23,8 @@let teamDialogOpen = $state(false);let editingTeam = $state<Team | null>(null);let teamToDelete = $state<Team | null>(null);+ let deleteDialogOpen = $state(false);+ let deleting = $state(false);const teams = $derived(oncallState.teams);@@ -46,15 +50,16 @@async function handleDeleteTeam() {if (!teamToDelete) return;+ deleting = true;try {await oncallState.deleteTeam(organizationId, teamToDelete.id);- toast.success('Successfully deleted the Team', { position: 'top-center' });+ toast.success('Successfully deleted the Team');oncallState.loadSchedules(organizationId);} catch (e) {- toast.error(e instanceof Error ? e.message : 'Failed to delete team', {- position: 'top-center'- });+ toast.error(e instanceof Error ? e.message : 'Failed to delete team');} finally {+ deleting = false;+ deleteDialogOpen = false;teamToDelete = null;}}@@ -63,23 +68,19 @@<div class="space-y-4">{#if oncallState.teamsLoading}<div class="flex justify-center py-12"><LoadingCircle size="xlg" /></div>- {:else if oncallState.teamsError}- <div- class="flex flex-col items-center justify-center gap-3 rounded-md bg-muted py-20 text-center text-muted-foreground"- >- <p class="text-sm text-destructive">{oncallState.teamsError}</p>- <Button variant="outline" size="sm" onclick={() => oncallState.loadTeams(organizationId)}>- Retry- </Button>- </div>-{:else if teams.length === 0}+ {:else if oncallState.teamsError}+ <ErrorRetryBox+ message={oncallState.teamsError}+ onRetry={() => oncallState.loadTeams(organizationId)}+ />+ {:else if teams.length === 0}<EmptyStatemessage="No teams yet. Create a team to get started."actionLabel={canManage ? 'Create your first Team' : undefined}onAction={openNew}/>{:else}- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root><Table.Header><Table.Row>@@ -143,7 +144,10 @@variant="ghost"size="icon"title="Delete"- onclick={() => (teamToDelete = team)}+ onclick={() => {+ teamToDelete = team;+ deleteDialogOpen = true;+ }}><Trash2 class="h-4 w-4" /></Button>@@ -154,7 +158,7 @@{/each}</Table.Body></Table.Root>- </div>+ </TableContainer>{/if}</div>@@ -168,26 +172,10 @@}}/>-<AlertDialog.Root- open={teamToDelete !== null}- onOpenChange={(open) => {- if (!open) teamToDelete = null;- }}->- <AlertDialog.Content>- <AlertDialog.Header>- <AlertDialog.Title>Delete Team</AlertDialog.Title>- <AlertDialog.Description>- Are you sure you want to delete "{teamToDelete?.name}"? Its schedules will be deleted as- well. This action cannot be undone.- </AlertDialog.Description>- </AlertDialog.Header>- <AlertDialog.Footer>- <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>- <AlertDialog.Action variant="destructive" onclick={handleDeleteTeam}>- <Trash2 class="mr-2 h-4 w-4" />- Delete Team- </AlertDialog.Action>- </AlertDialog.Footer>- </AlertDialog.Content>-</AlertDialog.Root>+<ConfirmDeleteDialog+ bind:open={deleteDialogOpen}+ entity="Team"+ description={`Are you sure you want to delete "${teamToDelete?.name}"? Its schedules will be deleted as well. This action cannot be undone.`}+ loading={deleting}+ onConfirm={handleDeleteTeam}+/>diff --git a/frontend/src/routes/profiles/+page.svelte b/frontend/src/routes/profiles/+page.svelteindex 90d0f61e..c1d43e49 100644--- a/frontend/src/routes/profiles/+page.svelte+++ b/frontend/src/routes/profiles/+page.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import { getErrorMessage } from '$lib/utils/errors';import { onMount, onDestroy } from 'svelte';import { api } from '$lib/api';import { formatRelativeTime, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';@@ -15,7 +16,8 @@import { projectsState } from '$lib/state/projects.svelte';import { createRowClickHandler } from '$lib/utils/navigation';import { resolve } from '$app/paths';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';import ExperimentalBanner from '$lib/components/profiles/experimental-banner.svelte';import {getTimeRangeFromPreset,@@ -69,7 +71,10 @@const max = Math.max(...values, 1);const step = 100 / (values.length - 1);return values- .map((v, i) => `${i === 0 ? 'M' : 'L'} ${(i * step).toFixed(1)} ${(16 - (v / max) * 15).toFixed(1)}`)+ .map(+ (v, i) =>+ `${i === 0 ? 'M' : 'L'} ${(i * step).toFixed(1)} ${(16 - (v / max) * 15).toFixed(1)}`+ ).join(' ');}@@ -187,9 +192,9 @@groups = response.data || [];total = response.pagination.total;totalPages = response.pagination.totalPages;- } catch (e: any) {+ } catch (e) {console.error(e);- error = e.message || 'Failed to load data';+ error = getErrorMessage(e) || 'Failed to load data';} finally {loading = false;}@@ -230,10 +235,8 @@</script><div class="space-y-4">- <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">- <PageHeader title="Profiles" />-- <div class="w-full sm:w-auto">+ <PageHeader title="Profiles">+ {#snippet actions()}<TimeRangePickerbind:fromDatebind:toDate@@ -242,8 +245,8 @@bind:preset={selectedPreset}onApply={handleTimeRangeChange}/>- </div>- </div>+ {/snippet}+ </PageHeader><ExperimentalBanner />@@ -254,7 +257,7 @@disabled={loading}/>- <div class="overflow-hidden rounded-md border">+ <TableContainer><Table.Root>{#if loading}<Table.Body>@@ -330,7 +333,7 @@<Table.Body>{#each groups as group (group.serviceName + '::' + group.type)}<Table.Row- class="cursor-pointer hover:bg-muted/50"+ class="cursor-pointer"onclick={createRowClickHandler(detailHref(group), 'preset', 'from', 'to')}><Table.Cell class="font-mono text-sm">{group.serviceName}</Table.Cell>@@ -367,7 +370,7 @@</Table.Body>{/if}</Table.Root>- </div>+ </TableContainer><PaginationFootercurrentPage={page}diff --git a/frontend/src/routes/profiles/[service]/+page.svelte b/frontend/src/routes/profiles/[service]/+page.svelteindex 4c8a9591..ffcd6507 100644--- a/frontend/src/routes/profiles/[service]/+page.svelte+++ b/frontend/src/routes/profiles/[service]/+page.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';import { onMount, onDestroy } from 'svelte';import { api } from '$lib/api';import { authState } from '$lib/state/auth.svelte';@@ -7,14 +8,16 @@import { LoadingCircle } from '$lib/components/ui/loading-circle';import { TimeRangePicker } from '$lib/components/ui/time-range-picker';import { ErrorDisplay } from '$lib/components/ui/error-display';- import * as Tabs from '$lib/components/ui/tabs';import * as Select from '$lib/components/ui/select';import { GitCompareArrows, Download, Layers, Gauge, X } from '@lucide/svelte';- import { goto } from '$app/navigation';import { resolve } from '$app/paths';import { createSmartBackHandler } from '$lib/utils/back-navigation';import { projectsState } from '$lib/state/projects.svelte';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import PageTabs from '$lib/components/traceway/page-tabs.svelte';+ import StatRow from '$lib/components/traceway/stat-row.svelte';+ import StatTile from '$lib/components/traceway/stat-tile.svelte';+ import ChartCard from '$lib/components/traceway/chart-card.svelte';import ExperimentalBanner from '$lib/components/profiles/experimental-banner.svelte';import FlameGraph from '$lib/components/profiles/flame-graph.svelte';import ProfileSeriesChart, {@@ -86,30 +89,6 @@// svelte-ignore state_referenced_locallylet activeType = $state(data.type ?? '');- let tabsListEl = $state<HTMLElement | null>(null);- let hasOverflow = $state(false);-- function checkOverflow() {- if (tabsListEl) {- hasOverflow = tabsListEl.scrollWidth > tabsListEl.clientWidth;- }- }-- $effect(() => {- if (!tabsListEl) return;- const observer = new ResizeObserver(() => checkOverflow());- observer.observe(tabsListEl);- checkOverflow();- return () => observer.disconnect();- });-- $effect(() => {- availableTypes;- if (tabsListEl) {- requestAnimationFrame(() => checkOverflow());- }- });-function getInitialRange(): { preset: string | null; from: Date; to: Date } {if (data.preset && presetMinutes[data.preset]) {const range = getTimeRangeFromPreset(data.preset, timezone);@@ -372,12 +351,12 @@if (selectedFrame && !flameData) selectedFrame = null;if (compareMode) await loadCompare(isGauge);- } catch (e: any) {- if (e?.status === 404) {+ } catch (e) {+ if (getErrorStatus(e) === 404) {notFound = true;} else {console.error(e);- error = e.message || 'Failed to load profile';+ error = getErrorMessage(e) || 'Failed to load profile';}} finally {loading = false;@@ -479,7 +458,7 @@})});if (!res.ok) {- toast.error('Failed to export profile', { position: 'top-center' });+ toast.error('Failed to export profile');return;}const blob = await res.blob();@@ -493,7 +472,7 @@URL.revokeObjectURL(objectUrl);} catch (e) {console.error(e);- toast.error('Failed to export profile', { position: 'top-center' });+ toast.error('Failed to export profile');} finally {downloading = false;}@@ -512,14 +491,11 @@</script><div class="space-y-4">- <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">- <PageHeader- title={data.service}- subtitle="Profiles"- onBack={createSmartBackHandler({ fallbackPath: resolve('/profiles') })}- />-- <div class="flex flex-col">+ <PageHeader+ title={data.service}+ onBack={createSmartBackHandler({ fallbackPath: resolve('/profiles') })}+ >+ {#snippet actions()}<TimeRangePickerbind:fromDatebind:toDate@@ -528,47 +504,17 @@bind:preset={selectedPreset}onApply={handleTimeRangeChange}/>- </div>- </div>+ {/snippet}+ </PageHeader><ExperimentalBanner />{#if availableTypes.length}- <Tabs.Root value={activeType} onValueChange={handleTypeChange}>- <div class="flex items-center" class:gap-2={!hasOverflow}>- {#if hasOverflow}- <Select.Root- type="single"- value={activeType}- onValueChange={(v) => {- if (v) handleTypeChange(v);- }}- >- <Select.Trigger size="sm" class="w-full" data-testid="type-overflow-select">- {activeType ? humanizeType(activeType) : 'Select type'}- </Select.Trigger>- <Select.Content>- {#each availableTypes as meta (meta.type)}- <Select.Item value={meta.type}>{humanizeType(meta.type)}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- {/if}- <div- class="flex min-w-0 items-center overflow-hidden"- class:invisible={hasOverflow}- class:h-0={hasOverflow}- class:w-0={hasOverflow}- bind:this={tabsListEl}- >- <Tabs.List>- {#each availableTypes as meta (meta.type)}- <Tabs.Trigger value={meta.type}>{humanizeType(meta.type)}</Tabs.Trigger>- {/each}- </Tabs.List>- </div>- </div>- </Tabs.Root>+ <PageTabs+ tabs={availableTypes.map((meta) => ({ value: meta.type, label: humanizeType(meta.type) }))}+ activeTab={activeType}+ onTabChange={handleTypeChange}+ />{/if}<div class="flex flex-wrap items-center gap-2">@@ -633,35 +579,28 @@{:else if error}<ErrorDisplay status={400} title="Error" description={error} onRetry={() => loadData()} />{:else}- <div class="grid gap-4 sm:grid-cols-2">- <div class="rounded-md border p-4">- <div class="text-sm text-muted-foreground">- Total {activeType ? humanizeType(activeType) : ''}- </div>- <div class="text-2xl font-bold tabular-nums">- {formatValue(activeUnit, totalValue)}- </div>- </div>- <div class="rounded-md border p-4">- <div class="text-sm text-muted-foreground">- Peak {rateActive+ <StatRow columns={2}>+ <StatTile+ label={activeType ? `Total ${humanizeType(activeType)}` : 'Total'}+ value={formatValue(activeUnit, totalValue)}+ />+ <StatTile+ label={`Peak ${+ rateActive? rateUnitIsTime? '(utilization)': '(rate)': activeIsGauge? '(avg/bucket)'- : '(sum/bucket)'}- </div>- <div class="text-2xl font-bold tabular-nums">- {rateActive ? formatRate(activeUnit, seriesPeak) : formatValue(activeUnit, seriesPeak)}- </div>- </div>- </div>+ : '(sum/bucket)'+ }`}+ value={rateActive+ ? formatRate(activeUnit, seriesPeak)+ : formatValue(activeUnit, seriesPeak)}+ />+ </StatRow>- <div class="rounded-md border p-4">- <div class="mb-1 text-sm text-muted-foreground">- Trend{groupBy ? ` · by ${groupByLabel.toLowerCase()}` : ''}- </div>+ <ChartCard title={`Trend${groupBy ? ` · by ${groupByLabel.toLowerCase()}` : ''}`}><ProfileSeriesChartseries={groupBy ? [] : series}groups={groupBy ? breakdown : []}@@ -669,7 +608,7 @@isRate={rateActive}onSelectRange={handleBrushSelect}/>- </div>+ </ChartCard><div class="space-y-3 rounded-md border p-4"><div class="flex flex-wrap items-center gap-2">diff --git a/frontend/src/routes/register/+page.svelte b/frontend/src/routes/register/+page.svelteindex 69e8c459..97748e2e 100644--- a/frontend/src/routes/register/+page.svelte+++ b/frontend/src/routes/register/+page.svelte@@ -1,241 +1,289 @@<script lang="ts">- import { goto } from '$app/navigation';- import { page } from '$app/state';- import { Button } from "$lib/components/ui/button";- import { Input } from "$lib/components/ui/input";- import { Label } from "$lib/components/ui/label";- import { Card, CardContent, CardFooter, CardHeader, CardTitle, CardDescription } from "$lib/components/ui/card";- import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";- import { ErrorAlert } from "$lib/components/ui/error-alert";- import * as Select from "$lib/components/ui/select";- import { CircleAlert, Check } from "@lucide/svelte";- import { authState } from '$lib/state/auth.svelte';- import { projectsState, FRAMEWORK_LABELS, type Framework } from '$lib/state/projects.svelte';- import { themeState } from '$lib/state/theme.svelte';- import { toast } from 'svelte-sonner';- import FrameworkCombobox from '$lib/components/framework-combobox.svelte';- import TurnstileWidget from '$lib/components/turnstile-widget.svelte';- import OauthButtons from '$lib/components/oauth-buttons.svelte';-- const DEFAULT_FRAMEWORK: Framework = 'opentelemetry';-- function parseFrameworkParam(value: string | null): Framework {- if (!value) return DEFAULT_FRAMEWORK;- return (value in FRAMEWORK_LABELS ? value : DEFAULT_FRAMEWORK) as Framework;- }-- let email = $state(page.url.searchParams.get('email') ?? '');- let name = $state('');- let password = $state('');- let confirmPassword = $state('');- let organizationName = $state('');- let timezone = $state(Intl.DateTimeFormat().resolvedOptions().timeZone);- let projectName = $state('');- let framework = $state<Framework>(parseFrameworkParam(page.url.searchParams.get('framework')));- let error = $state('');- let loading = $state(false);- let captchaToken = $state('');- let passwordLoginEnabled = $state(true);- let providersLoaded = $state(false);-- const turnstileSiteKey = __TURNSTILE_SITE_KEY__;- const captchaEnabled = turnstileSiteKey !== '';-- const timezones = Intl.supportedValuesOf('timeZone');-- if (!__CLOUD_MODE__) {- $effect(() => {- if (!providersLoaded) return;-- // Password login is disabled - this page is inaccessible, send to login.- if (!passwordLoginEnabled) {- goto("/login");- return;- }-- // if we're not in the cloud mode we have to check if an organization exists and if it does we should go to the login page- loading = true;- fetch('/api/has-organizations', {- method: 'GET',- })- .then(response => response.json())- .then((response) => {- if (response.hasOrganizations) {- goto("/login")- }- loading = false- }).catch(() => {- toast.error("An unexpected error has occured. The page will refresh in 5 seconds.")- setTimeout(() => {- window.location.reload()- }, 5000)- });- })- }-- async function handleRegister() {- if (password !== confirmPassword) {- error = 'Passwords do not match';- return;- }-- if (password.length < 8) {- error = 'Password must be at least 8 characters';- return;- }-- if (captchaEnabled && !captchaToken) {- error = 'Please complete the captcha';- return;- }-- loading = true;- error = '';-- try {- const response = await fetch('/api/register', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify({- email,- name,- password,- organizationName,- timezone,- projectName,- framework,- captchaToken- })- });-- if (!response.ok) {- const data = await response.json();- throw new Error(data.error || 'Registration failed');- }-- const data = await response.json();-- authState.setToken(data.token);- authState.setOrganizations(data.organizations || []);- projectsState.setProjects(data.projects);-- goto('/');- } catch (e) {- error = e instanceof Error ? e.message : 'Registration failed';- } finally {- loading = false;- }- }+ import { resolve } from '$app/paths';+ import { goto } from '$app/navigation';+ import { page } from '$app/state';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import {+ Card,+ CardContent,+ CardFooter,+ CardHeader,+ CardTitle,+ CardDescription+ } from '$lib/components/ui/card';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import * as Select from '$lib/components/ui/select';+ import { Check } from '@lucide/svelte';+ import { authState } from '$lib/state/auth.svelte';+ import { projectsState, FRAMEWORK_LABELS, type Framework } from '$lib/state/projects.svelte';+ import { themeState } from '$lib/state/theme.svelte';+ import { toast } from 'svelte-sonner';+ import FrameworkCombobox from '$lib/components/framework-combobox.svelte';+ import TurnstileWidget from '$lib/components/turnstile-widget.svelte';+ import OauthButtons from '$lib/components/oauth-buttons.svelte';++ const DEFAULT_FRAMEWORK: Framework = 'opentelemetry';++ function parseFrameworkParam(value: string | null): Framework {+ if (!value) return DEFAULT_FRAMEWORK;+ return (value in FRAMEWORK_LABELS ? value : DEFAULT_FRAMEWORK) as Framework;+ }++ let email = $state(page.url.searchParams.get('email') ?? '');+ let name = $state('');+ let password = $state('');+ let confirmPassword = $state('');+ let organizationName = $state('');+ let timezone = $state(Intl.DateTimeFormat().resolvedOptions().timeZone);+ let projectName = $state('');+ let framework = $state<Framework>(parseFrameworkParam(page.url.searchParams.get('framework')));+ let error = $state('');+ let loading = $state(false);+ let captchaToken = $state('');+ let passwordLoginEnabled = $state(true);+ let providersLoaded = $state(false);++ const turnstileSiteKey = __TURNSTILE_SITE_KEY__;+ const captchaEnabled = turnstileSiteKey !== '';++ const timezones = Intl.supportedValuesOf('timeZone');++ if (!__CLOUD_MODE__) {+ $effect(() => {+ if (!providersLoaded) return;++ // Password login is disabled - this page is inaccessible, send to login.+ if (!passwordLoginEnabled) {+ goto(resolve('/login'));+ return;+ }++ // if we're not in the cloud mode we have to check if an organization exists and if it does we should go to the login page+ loading = true;+ fetch('/api/has-organizations', {+ method: 'GET'+ })+ .then((response) => response.json())+ .then((response) => {+ if (response.hasOrganizations) {+ goto(resolve('/login'));+ }+ loading = false;+ })+ .catch(() => {+ toast.error('An unexpected error has occurred. The page will refresh in 5 seconds.');+ setTimeout(() => {+ window.location.reload();+ }, 5000);+ });+ });+ }++ async function handleRegister() {+ if (password !== confirmPassword) {+ error = 'Passwords do not match';+ return;+ }++ if (password.length < 8) {+ error = 'Password must be at least 8 characters';+ return;+ }++ if (captchaEnabled && !captchaToken) {+ error = 'Please complete the captcha';+ return;+ }++ loading = true;+ error = '';++ try {+ const response = await fetch('/api/register', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ email,+ name,+ password,+ organizationName,+ timezone,+ projectName,+ framework,+ captchaToken+ })+ });++ if (!response.ok) {+ const data = await response.json();+ throw new Error(data.error || 'Registration failed');+ }++ const data = await response.json();++ authState.setToken(data.token);+ authState.setOrganizations(data.organizations || []);+ projectsState.setProjects(data.projects);++ goto(resolve('/'));+ } catch (e) {+ error = e instanceof Error ? e.message : 'Registration failed';+ } finally {+ loading = false;+ }+ }</script><div class="flex min-h-screen w-full items-center justify-center px-4 py-8">- <Card class="w-[400px]">- <CardHeader>- <CardTitle class="text-2xl">- <div class="flex flex-row items-center justify-center gap-2">- {#if themeState.isDark}- <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />- {:else}- <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />- {/if}- </div>- </CardTitle>- <CardDescription class="text-center">- Create your account- </CardDescription>- </CardHeader>- <CardContent>- {#if error}- <ErrorAlert {error} class="mb-4" />- {/if}- <OauthButtons bind:passwordLoginEnabled bind:loaded={providersLoaded} />- {#if providersLoaded && passwordLoginEnabled}- <form onsubmit={(e) => { e.preventDefault(); handleRegister(); }} class="grid w-full items-center gap-4">- <div class="flex flex-col space-y-1.5">- <Label for="email">Email</Label>- <Input id="email" type="email" bind:value={email} placeholder="[email protected]" required />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="name">Name</Label>- <Input id="name" type="text" bind:value={name} placeholder="Your name" required />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="password">Password</Label>- <Input id="password" type="password" bind:value={password} placeholder="Password (min 8 characters)" required />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="confirmPassword">Confirm Password</Label>- <Input id="confirmPassword" type="password" bind:value={confirmPassword} placeholder="Confirm password" required />- </div>-- <div class="flex items-center gap-3 mt-2">- <div class="flex-1 border-t"></div>- <p class="text-sm text-muted-foreground">Organization & Project</p>- <div class="flex-1 border-t"></div>- </div>-- <div class="flex flex-col space-y-1.5">- <Label for="organizationName">Organization Name</Label>- <Input id="organizationName" type="text" bind:value={organizationName} placeholder="Your company or team" required />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="timezone">Timezone</Label>- <Select.Root type="single" bind:value={timezone}>- <Select.Trigger class="w-full">- <span>{timezone}</span>- </Select.Trigger>- <Select.Content class="max-h-60">- {#each timezones as tz}- <Select.Item value={tz}>- {#snippet children({ selected })}- <span>{tz}</span>- {#if selected}- <Check class="absolute end-2 size-4" />- {/if}- {/snippet}- </Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- <div class="flex flex-col space-y-1.5">- <Label for="projectName">Project Name</Label>- <Input id="projectName" type="text" bind:value={projectName} placeholder="My App" required />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="framework">Framework</Label>- <FrameworkCombobox bind:value={framework} />- </div>-- {#if captchaEnabled}- <div class="flex flex-col space-y-1.5 mt-2">- <TurnstileWidget- siteKey={turnstileSiteKey}- onVerify={(token) => captchaToken = token}- onError={() => captchaToken = ''}- />- </div>- {/if}-- <Button type="submit" disabled={loading || (captchaEnabled && !captchaToken)} class="w-full mt-2">- {#if loading}- Creating account...- {:else}- Create Account- {/if}- </Button>- </form>- {/if}- </CardContent>-- {#if __CLOUD_MODE__}- <CardFooter class="flex flex-col justify-center">- <p class="text-sm text-muted-foreground">- Already have an account? <a href="/login" class="text-primary hover:underline">Login</a>- </p>- </CardFooter>- {/if}- </Card>+ <Card class="w-[400px]">+ <CardHeader>+ <CardTitle class="text-2xl">+ <div class="flex flex-row items-center justify-center gap-2">+ {#if themeState.isDark}+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />+ {:else}+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />+ {/if}+ </div>+ </CardTitle>+ <CardDescription class="text-center">Create your account</CardDescription>+ </CardHeader>+ <CardContent>+ {#if error}+ <ErrorAlert {error} class="mb-4" />+ {/if}+ <OauthButtons bind:passwordLoginEnabled bind:loaded={providersLoaded} />+ {#if providersLoaded && passwordLoginEnabled}+ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleRegister();+ }}+ class="grid w-full items-center gap-4"+ >+ <div class="flex flex-col space-y-1.5">+ <Label for="email">Email</Label>+ <Input+ id="email"+ type="email"+ bind:value={email}+ placeholder="[email protected]"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="name">Name</Label>+ <Input id="name" type="text" bind:value={name} placeholder="Your name" required />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="password">Password</Label>+ <Input+ id="password"+ type="password"+ bind:value={password}+ placeholder="Password (min 8 characters)"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="confirmPassword">Confirm Password</Label>+ <Input+ id="confirmPassword"+ type="password"+ bind:value={confirmPassword}+ placeholder="Confirm password"+ required+ />+ </div>++ <div class="mt-2 flex items-center gap-3">+ <div class="flex-1 border-t"></div>+ <p class="text-sm text-muted-foreground">Organization & Project</p>+ <div class="flex-1 border-t"></div>+ </div>++ <div class="flex flex-col space-y-1.5">+ <Label for="organizationName">Organization Name</Label>+ <Input+ id="organizationName"+ type="text"+ bind:value={organizationName}+ placeholder="Your company or team"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="timezone">Timezone</Label>+ <Select.Root type="single" bind:value={timezone}>+ <Select.Trigger class="w-full">+ <span>{timezone}</span>+ </Select.Trigger>+ <Select.Content class="max-h-60">+ {#each timezones as tz, __index (__index)}+ <Select.Item value={tz}>+ {#snippet children({ selected })}+ <span>{tz}</span>+ {#if selected}+ <Check class="absolute end-2 size-4" />+ {/if}+ {/snippet}+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="projectName">Project Name</Label>+ <Input+ id="projectName"+ type="text"+ bind:value={projectName}+ placeholder="My App"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="framework">Framework</Label>+ <FrameworkCombobox bind:value={framework} />+ </div>++ {#if captchaEnabled}+ <div class="mt-2 flex flex-col space-y-1.5">+ <TurnstileWidget+ siteKey={turnstileSiteKey}+ onVerify={(token) => (captchaToken = token)}+ onError={() => (captchaToken = '')}+ />+ </div>+ {/if}++ <Button+ type="submit"+ disabled={loading || (captchaEnabled && !captchaToken)}+ class="mt-2 w-full"+ >+ {#if loading}+ Creating account...+ {:else}+ Create Account+ {/if}+ </Button>+ </form>+ {/if}+ </CardContent>++ {#if __CLOUD_MODE__}+ <CardFooter class="flex flex-col justify-center">+ <p class="text-sm text-muted-foreground">+ Already have an account? <a href={resolve('/login')} class="text-primary hover:underline"+ >Login</a+ >+ </p>+ </CardFooter>+ {/if}+ </Card></div>diff --git a/frontend/src/routes/register/+page.ts b/frontend/src/routes/register/+page.tsindex 47889b84..98a094a3 100644--- a/frontend/src/routes/register/+page.ts+++ b/frontend/src/routes/register/+page.ts@@ -2,10 +2,10 @@ import { redirect } from '@sveltejs/kit';import type { PageLoad } from './$types';export const load: PageLoad = () => {- // Check if user is already authenticated- const token = localStorage.getItem('AUTH_TOKEN');- if (token) {- throw redirect(302, '/');- }- return {};+ // Check if user is already authenticated+ const token = localStorage.getItem('AUTH_TOKEN');+ if (token) {+ throw redirect(302, '/');+ }+ return {};};diff --git a/frontend/src/routes/reset-password/+page.svelte b/frontend/src/routes/reset-password/+page.svelteindex 1112fb68..5e0a5124 100644--- a/frontend/src/routes/reset-password/+page.svelte+++ b/frontend/src/routes/reset-password/+page.svelte@@ -1,162 +1,181 @@<script lang="ts">- import { goto } from '$app/navigation';- import { page } from '$app/state';- import { Button } from "$lib/components/ui/button";- import { Input } from "$lib/components/ui/input";- import { Label } from "$lib/components/ui/label";- import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "$lib/components/ui/card";- import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";- import { ErrorAlert } from "$lib/components/ui/error-alert";- import { CircleAlert, CircleCheck, Loader2 } from "@lucide/svelte";- import { themeState } from '$lib/state/theme.svelte';+ import { resolve } from '$app/paths';+ import { goto } from '$app/navigation';+ import { page } from '$app/state';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '$lib/components/ui/card';+ import { Alert, AlertDescription, AlertTitle } from '$lib/components/ui/alert';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { CircleAlert, CircleCheck, Loader2 } from '@lucide/svelte';+ import { themeState } from '$lib/state/theme.svelte';- let password = $state('');- let confirmPassword = $state('');- let error = $state('');- let loading = $state(false);- let success = $state(false);- let validating = $state(true);- let tokenValid = $state(false);- let email = $state('');+ let password = $state('');+ let confirmPassword = $state('');+ let error = $state('');+ let loading = $state(false);+ let success = $state(false);+ let validating = $state(true);+ let tokenValid = $state(false);+ let email = $state('');- const token = $derived(page.url.searchParams.get('token'));+ const token = $derived(page.url.searchParams.get('token'));- $effect(() => {- if (token) {- validateToken(token);- } else {- validating = false;- tokenValid = false;- }- });+ $effect(() => {+ if (token) {+ validateToken(token);+ } else {+ validating = false;+ tokenValid = false;+ }+ });- async function validateToken(token: string) {- try {- const response = await fetch(`/api/password-reset/${token}`);- const data = await response.json();+ async function validateToken(token: string) {+ try {+ const response = await fetch(`/api/password-reset/${token}`);+ const data = await response.json();- if (data.valid) {- tokenValid = true;- email = data.email;- } else {- tokenValid = false;- }- } catch {- tokenValid = false;- } finally {- validating = false;- }- }+ if (data.valid) {+ tokenValid = true;+ email = data.email;+ } else {+ tokenValid = false;+ }+ } catch {+ tokenValid = false;+ } finally {+ validating = false;+ }+ }- async function handleSubmit() {- if (password !== confirmPassword) {- error = 'Passwords do not match';- return;- }+ async function handleSubmit() {+ if (password !== confirmPassword) {+ error = 'Passwords do not match';+ return;+ }- if (password.length < 8) {- error = 'Password must be at least 8 characters';- return;- }+ if (password.length < 8) {+ error = 'Password must be at least 8 characters';+ return;+ }- loading = true;- error = '';+ loading = true;+ error = '';- try {- const response = await fetch(`/api/password-reset/${token}`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify({ password })- });+ try {+ const response = await fetch(`/api/password-reset/${token}`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({ password })+ });- if (!response.ok) {- const data = await response.json();- throw new Error(data.error || 'Failed to reset password');- }+ if (!response.ok) {+ const data = await response.json();+ throw new Error(data.error || 'Failed to reset password');+ }- success = true;- setTimeout(() => {- goto('/login');- }, 2000);- } catch (e) {- error = e instanceof Error ? e.message : 'An unexpected error occurred';- } finally {- loading = false;- }- }+ success = true;+ setTimeout(() => {+ goto(resolve('/login'));+ }, 2000);+ } catch (e) {+ error = e instanceof Error ? e.message : 'An unexpected error occurred';+ } finally {+ loading = false;+ }+ }</script><div class="flex h-screen w-full items-center justify-center px-4">- <Card class="w-[350px]">- <CardHeader>- <CardTitle class="text-2xl">- <div class="flex flex-row items-center justify-center gap-2">- {#if themeState.isDark}- <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />- {:else}- <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />- {/if}- </div>- </CardTitle>- </CardHeader>- <CardContent>- {#if validating}- <div class="flex flex-col items-center justify-center py-8">- <Loader2 class="h-8 w-8 animate-spin text-muted-foreground" />- <p class="mt-4 text-sm text-muted-foreground">Validating reset link...</p>- </div>- {:else if !tokenValid}- <Alert variant="destructive">- <CircleAlert class="h-4 w-4" />- <AlertTitle>Invalid Link</AlertTitle>- <AlertDescription>- This password reset link is invalid or has expired. Please request a new one.- </AlertDescription>- </Alert>- {:else if success}- <Alert class="bg-green-50 border-green-200">- <CircleCheck class="h-4 w-4 text-green-700" />- <AlertTitle class="text-green-800">Password Reset</AlertTitle>- <AlertDescription class="text-green-700">- Your password has been reset successfully. Redirecting to login...- </AlertDescription>- </Alert>- {:else}- {#if error}- <ErrorAlert {error} class="mb-4" />- {/if}- <p class="text-sm text-muted-foreground mb-4">- Enter a new password for your account.- </p>- <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="grid w-full items-center gap-4">- <div class="flex flex-col space-y-1.5">- <Label for="email">Email</Label>- <Input id="email" type="email" value={email} disabled class="bg-muted" />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="password">New Password</Label>- <Input id="password" type="password" bind:value={password} placeholder="New password" required minlength={8} />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="confirmPassword">Confirm Password</Label>- <Input id="confirmPassword" type="password" bind:value={confirmPassword} placeholder="Confirm password" required minlength={8} />- </div>- <Button type="submit" disabled={loading} class="w-full">- {#if loading}- Resetting...- {:else}- Reset Password- {/if}- </Button>- </form>- {/if}- </CardContent>- <CardFooter class="flex flex-col justify-center">- <p class="text-sm text-muted-foreground">- <a href="/login" class="text-primary hover:underline">Back to Login</a>- </p>- </CardFooter>- </Card>+ <Card class="w-[350px]">+ <CardHeader>+ <CardTitle class="text-2xl">+ <div class="flex flex-row items-center justify-center gap-2">+ {#if themeState.isDark}+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />+ {:else}+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />+ {/if}+ </div>+ </CardTitle>+ </CardHeader>+ <CardContent>+ {#if validating}+ <div class="flex flex-col items-center justify-center py-8">+ <Loader2 class="h-8 w-8 animate-spin text-muted-foreground" />+ <p class="mt-4 text-sm text-muted-foreground">Validating reset link...</p>+ </div>+ {:else if !tokenValid}+ <Alert variant="destructive">+ <CircleAlert class="h-4 w-4" />+ <AlertTitle>Invalid Link</AlertTitle>+ <AlertDescription>+ This password reset link is invalid or has expired. Please request a new one.+ </AlertDescription>+ </Alert>+ {:else if success}+ <Alert class="border-green-200 bg-green-50">+ <CircleCheck class="h-4 w-4 text-green-700" />+ <AlertTitle class="text-green-800">Password Reset</AlertTitle>+ <AlertDescription class="text-green-700">+ Your password has been reset successfully. Redirecting to login...+ </AlertDescription>+ </Alert>+ {:else}+ {#if error}+ <ErrorAlert {error} class="mb-4" />+ {/if}+ <p class="mb-4 text-sm text-muted-foreground">Enter a new password for your account.</p>+ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleSubmit();+ }}+ class="grid w-full items-center gap-4"+ >+ <div class="flex flex-col space-y-1.5">+ <Label for="email">Email</Label>+ <Input id="email" type="email" value={email} disabled class="bg-muted" />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="password">New Password</Label>+ <Input+ id="password"+ type="password"+ bind:value={password}+ placeholder="New password"+ required+ minlength={8}+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="confirmPassword">Confirm Password</Label>+ <Input+ id="confirmPassword"+ type="password"+ bind:value={confirmPassword}+ placeholder="Confirm password"+ required+ minlength={8}+ />+ </div>+ <Button type="submit" disabled={loading} class="w-full">+ {#if loading}+ Resetting...+ {:else}+ Reset Password+ {/if}+ </Button>+ </form>+ {/if}+ </CardContent>+ <CardFooter class="flex flex-col justify-center">+ <p class="text-sm text-muted-foreground">+ <a href={resolve('/login')} class="text-primary hover:underline">Back to Login</a>+ </p>+ </CardFooter>+ </Card></div>diff --git a/frontend/src/routes/sessions/+page.svelte b/frontend/src/routes/sessions/+page.svelteindex 1492db07..4c79d719 100644--- a/frontend/src/routes/sessions/+page.svelte+++ b/frontend/src/routes/sessions/+page.svelte@@ -1,473 +1,503 @@<script lang="ts">- import { onMount, onDestroy } from 'svelte';- import { api } from '$lib/api';- import { formatDuration, formatRelativeTime, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';- import { getTimezone } from '$lib/state/timezone.svelte';- import * as Table from "$lib/components/ui/table";- import { LoadingCircle } from "$lib/components/ui/loading-circle";- import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";- import { TableEmptyState } from "$lib/components/ui/table-empty-state";- import { PaginationFooter } from "$lib/components/ui/pagination-footer";- 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 Tooltip from '$lib/components/ui/tooltip';- import { Button } from '$lib/components/ui/button';- import { Input } from '$lib/components/ui/input';- import Plus from '@lucide/svelte/icons/plus';- import X from '@lucide/svelte/icons/x';- import Info from '@lucide/svelte/icons/info';- import { CalendarDate } from "@internationalized/date";- import { browser } from '$app/environment';- import { goto } from '$app/navigation';- import { projectsState } from '$lib/state/projects.svelte';- import { createRowClickHandler } from '$lib/utils/navigation';- import { resolve } from '$app/paths';- import PageHeader from '$lib/components/issues/page-header.svelte';- import {- getTimeRangeFromPreset,- dateToCalendarDate,- dateToTimeString,- parseTimeRangeFromUrl,- getResolvedTimeRange,- updateUrl- } from '$lib/utils/url-params';- import {- getSortState,- setSortState,- handleSortClick,- type SortDirection- } from '$lib/utils/sort-storage';-- const timezone = $derived(getTimezone());- const initialTimezone = getTimezone();-- type Session = {- id: string;- startedAt: string;- endedAt?: string | null;- duration: number;- clientIP: string;- appVersion: string;- serverName: string;- };-- type SortField = 'started_at' | 'duration';-- let sessions = $state<Session[]>([]);- let loading = $state(true);- let error = $state('');-- 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[] };- const params = new URLSearchParams(window.location.search);- const attrs: AttributeFilter[] = [];- for (const raw of params.getAll('attr')) {- const parsed = parseAttributeFilter(raw);- if (parsed) attrs.push(parsed);- }- return {- ...timeParams,- search: params.get('search') ?? '',- attributeFilters: attrs- };- }-- const initialUrlParams = parseSessionsUrlParams();- const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);-- let selectedPreset = $state<string | null>(initialUrlParams.preset);- let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));- let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));- let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));- let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));- let searchQuery = $state(initialUrlParams.search);- let attributeFilters = $state<AttributeFilter[]>(initialUrlParams.attributeFilters);-- let addFilterOpen = $state(false);- let dialogKey = $state('');- let dialogValue = $state('');- let dialogError = $state('');-- function openAddFilterDialog() {- dialogKey = '';- dialogValue = '';- dialogError = '';- addFilterOpen = true;- }-- function submitDialogFilter() {- const key = dialogKey.trim();- if (!key) {- 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 }];- }- addFilterOpen = false;- page = 1;- loadData(true);- }-- function handleDialogKeydown(e: KeyboardEvent) {- if (e.key === 'Enter') {- e.preventDefault();- submitDialogFilter();- }- }-- function removeAttributeFilter(index: number) {- attributeFilters = attributeFilters.filter((_, i) => i !== index);- page = 1;- loadData(true);- }-- function updateTimeRangeUrl(pushToHistory = true) {- if (!browser) return;- const params = new URLSearchParams();- if (selectedPreset) {- params.set('preset', selectedPreset);- } else {- params.set('from', getFromDateTimeUTC());- params.set('to', getToDateTimeUTC());- }- if (searchQuery.trim()) params.set('search', searchQuery.trim());- for (const f of attributeFilters) {- params.append('attr', `${f.key}=${f.value}`);- }- const newUrl = `${window.location.pathname}?${params.toString()}`;- // eslint-disable-next-line svelte/no-navigation-without-resolve- goto(newUrl, { replaceState: !pushToHistory, noScroll: true, keepFocus: true });- }-- function handlePopState() {- const urlParams = parseSessionsUrlParams();- const range = getResolvedTimeRange(urlParams, timezone);- selectedPreset = urlParams.preset;- fromDate = dateToCalendarDate(range.from, timezone);- fromTime = dateToTimeString(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- toTime = dateToTimeString(range.to, timezone);- searchQuery = urlParams.search;- attributeFilters = urlParams.attributeFilters;- page = 1;- loadData(false);- }-- function handleSearch() {- page = 1;- loadData(true);- }-- const SORT_STORAGE_KEY = 'sessions';- const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'started_at', direction: 'desc' });- let orderBy = $state<SortField>(initialSort.field as SortField);- let sortDirection = $state<SortDirection>(initialSort.direction);-- function getFromDateTimeUTC(): string {- const [hour, minute] = (fromTime || '00:00').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute }, timezone);- return toUTCISO(dt);- }-- function getToDateTimeUTC(): string {- const [hour, minute] = (toTime || '23:59').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: toDate.year, month: toDate.month, day: toDate.day, hour, minute }, timezone).endOf('minute');- return toUTCISO(dt);- }-- function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) {- fromDate = from.date;- fromTime = from.time;- toDate = to.date;- toTime = to.time;- selectedPreset = preset;- page = 1;- loadData(true);- }-- function shortId(id: string): string {- return id.split('-')[0] ?? id.slice(0, 8);- }-- const ABANDONED_AFTER_MS = 15 * 60_000;-- function durationLabel(s: Session): string {- if (s.endedAt) return formatDuration(s.duration);- const startedMs = Date.parse(s.startedAt);- if (Number.isFinite(startedMs) && Date.now() - startedMs >= ABANDONED_AFTER_MS) {- return 'Abandoned';- }- return 'in progress';- }-- async function loadData(pushToHistory = true) {- loading = true;- error = '';-- if (selectedPreset) {- const range = getTimeRangeFromPreset(selectedPreset, timezone);- fromDate = dateToCalendarDate(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- fromTime = dateToTimeString(range.from, timezone);- toTime = dateToTimeString(range.to, timezone);- }-- updateTimeRangeUrl(pushToHistory);-- try {- const requestBody = {- fromDate: getFromDateTimeUTC(),- toDate: getToDateTimeUTC(),- orderBy,- sortDirection,- search: searchQuery.trim(),- attributeFilters,- pagination: { page, pageSize }- };-- const response = await api.post('/sessions', requestBody, { projectId: projectsState.currentProjectId ?? undefined });-- sessions = response.data || [];- total = response.pagination.total;- totalPages = response.pagination.totalPages;- } catch (e: any) {- console.error(e);- error = e.message || 'Failed to load data';- } finally {- loading = false;- }- }-- function handlePageChange(newPage: number) {- if (newPage >= 1 && newPage <= totalPages) {- page = newPage;- loadData(false);- }- }-- function handlePageSizeChange(newPageSize: number) {- pageSize = newPageSize;- page = 1;- loadData(false);- }-- function handleSort(field: SortField) {- const newSort = handleSortClick(field, orderBy, sortDirection);- orderBy = newSort.field as SortField;- sortDirection = newSort.direction;- setSortState(SORT_STORAGE_KEY, newSort);- page = 1;- loadData(false);- }-- onMount(() => {- window.addEventListener('popstate', handlePopState);- loadData(false);- });-- onDestroy(() => {- if (typeof window !== 'undefined') {- window.removeEventListener('popstate', handlePopState);- }- });+ import { getErrorMessage } from '$lib/utils/errors';+ import { onMount, onDestroy } from 'svelte';+ import { api } from '$lib/api';+ import {+ formatDuration,+ formatRelativeTime,+ toUTCISO,+ calendarDateTimeToLuxon+ } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import * as Table from '$lib/components/ui/table';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ 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 Tooltip from '$lib/components/ui/tooltip';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import Plus from '@lucide/svelte/icons/plus';+ import X from '@lucide/svelte/icons/x';+ import Info from '@lucide/svelte/icons/info';+ import { CalendarDate } from '@internationalized/date';+ import { browser } from '$app/environment';+ import { projectsState } from '$lib/state/projects.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { resolve } from '$app/paths';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import FormField from '$lib/components/traceway/form-field.svelte';+ import {+ getTimeRangeFromPreset,+ dateToCalendarDate,+ dateToTimeString,+ parseTimeRangeFromUrl,+ getResolvedTimeRange,+ updateUrl+ } from '$lib/utils/url-params';+ import {+ getSortState,+ setSortState,+ handleSortClick,+ type SortDirection+ } from '$lib/utils/sort-storage';++ const timezone = $derived(getTimezone());+ const initialTimezone = getTimezone();++ type Session = {+ id: string;+ startedAt: string;+ endedAt?: string | null;+ duration: number;+ clientIP: string;+ appVersion: string;+ serverName: string;+ };++ type SortField = 'started_at' | 'duration';++ let sessions = $state<Session[]>([]);+ let loading = $state(true);+ let error = $state('');++ 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[] };+ const params = new URLSearchParams(window.location.search);+ const attrs: AttributeFilter[] = [];+ for (const raw of params.getAll('attr')) {+ const parsed = parseAttributeFilter(raw);+ if (parsed) attrs.push(parsed);+ }+ return {+ ...timeParams,+ search: params.get('search') ?? '',+ attributeFilters: attrs+ };+ }++ const initialUrlParams = parseSessionsUrlParams();+ const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);++ let selectedPreset = $state<string | null>(initialUrlParams.preset);+ let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));+ let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));+ let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));+ let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));+ let searchQuery = $state(initialUrlParams.search);+ let attributeFilters = $state<AttributeFilter[]>(initialUrlParams.attributeFilters);++ let addFilterOpen = $state(false);+ let dialogKey = $state('');+ let dialogValue = $state('');+ let dialogError = $state('');++ function openAddFilterDialog() {+ dialogKey = '';+ dialogValue = '';+ dialogError = '';+ addFilterOpen = true;+ }++ function submitDialogFilter() {+ const key = dialogKey.trim();+ if (!key) {+ 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 }];+ }+ addFilterOpen = false;+ page = 1;+ loadData(true);+ }++ function handleDialogKeydown(e: KeyboardEvent) {+ if (e.key === 'Enter') {+ e.preventDefault();+ submitDialogFilter();+ }+ }++ function removeAttributeFilter(index: number) {+ attributeFilters = attributeFilters.filter((_, i) => i !== index);+ page = 1;+ loadData(true);+ }++ function updateSessionsUrl(pushToHistory = true) {+ updateUrl(+ {+ preset: selectedPreset || null,+ from: selectedPreset ? null : getFromDateTimeUTC(),+ to: selectedPreset ? null : getToDateTimeUTC(),+ search: searchQuery.trim() || null,+ attr: attributeFilters.map((f) => `${f.key}=${f.value}`)+ },+ { pushToHistory }+ );+ }++ function handlePopState() {+ const urlParams = parseSessionsUrlParams();+ const range = getResolvedTimeRange(urlParams, timezone);+ selectedPreset = urlParams.preset;+ fromDate = dateToCalendarDate(range.from, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ toTime = dateToTimeString(range.to, timezone);+ searchQuery = urlParams.search;+ attributeFilters = urlParams.attributeFilters;+ page = 1;+ loadData(false);+ }++ function handleSearch() {+ page = 1;+ loadData(true);+ }++ const SORT_STORAGE_KEY = 'sessions';+ const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'started_at', direction: 'desc' });+ let orderBy = $state<SortField>(initialSort.field as SortField);+ let sortDirection = $state<SortDirection>(initialSort.direction);++ function getFromDateTimeUTC(): string {+ const [hour, minute] = (fromTime || '00:00').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute },+ timezone+ );+ return toUTCISO(dt);+ }++ function getToDateTimeUTC(): string {+ const [hour, minute] = (toTime || '23:59').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: toDate.year, month: toDate.month, day: toDate.day, hour, minute },+ timezone+ ).endOf('minute');+ return toUTCISO(dt);+ }++ function handleTimeRangeChange(+ from: { date: CalendarDate; time: string },+ to: { date: CalendarDate; time: string },+ preset: string | null+ ) {+ fromDate = from.date;+ fromTime = from.time;+ toDate = to.date;+ toTime = to.time;+ selectedPreset = preset;+ page = 1;+ loadData(true);+ }++ function shortId(id: string): string {+ return id.split('-')[0] ?? id.slice(0, 8);+ }++ const ABANDONED_AFTER_MS = 15 * 60_000;++ function durationLabel(s: Session): string {+ if (s.endedAt) return formatDuration(s.duration);+ const startedMs = Date.parse(s.startedAt);+ if (Number.isFinite(startedMs) && Date.now() - startedMs >= ABANDONED_AFTER_MS) {+ return 'Abandoned';+ }+ return 'in progress';+ }++ async function loadData(pushToHistory = true) {+ loading = true;+ error = '';++ if (selectedPreset) {+ const range = getTimeRangeFromPreset(selectedPreset, timezone);+ fromDate = dateToCalendarDate(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toTime = dateToTimeString(range.to, timezone);+ }++ updateSessionsUrl(pushToHistory);++ try {+ const requestBody = {+ fromDate: getFromDateTimeUTC(),+ toDate: getToDateTimeUTC(),+ orderBy,+ sortDirection,+ search: searchQuery.trim(),+ attributeFilters,+ pagination: { page, pageSize }+ };++ const response = await api.post('/sessions', requestBody, {+ projectId: projectsState.currentProjectId ?? undefined+ });++ sessions = response.data || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e) {+ console.error(e);+ error = getErrorMessage(e) || 'Failed to load data';+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData(false);+ }+ }++ function handlePageSizeChange(newPageSize: number) {+ pageSize = newPageSize;+ page = 1;+ loadData(false);+ }++ function handleSort(field: SortField) {+ const newSort = handleSortClick(field, orderBy, sortDirection);+ orderBy = newSort.field as SortField;+ sortDirection = newSort.direction;+ setSortState(SORT_STORAGE_KEY, newSort);+ page = 1;+ loadData(false);+ }++ onMount(() => {+ window.addEventListener('popstate', handlePopState);+ loadData(false);+ });++ onDestroy(() => {+ if (typeof window !== 'undefined') {+ window.removeEventListener('popstate', handlePopState);+ }+ });</script><div class="space-y-4">- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">- <div class="flex items-start gap-2">- <PageHeader title="Sessions" />- <Tooltip.Root>- <Tooltip.Trigger class="mt-2 text-muted-foreground/60 hover:text-muted-foreground">- <Info class="h-4 w-4" />- </Tooltip.Trigger>- <Tooltip.Content side="right" class="max-w-xs">- <p class="text-xs">- Sessions are full recordings of user interactions and are only recorded when manually enabled- (<code class="font-mono">recordAllSessions: true</code> in the SDK init options).- </p>- </Tooltip.Content>- </Tooltip.Root>- </div>- <div class="flex flex-col">- <TimeRangePicker- bind:fromDate- bind:toDate- bind:fromTime- bind:toTime- bind:preset={selectedPreset}- onApply={handleTimeRangeChange}- />- </div>- </div>-- <SearchBar- placeholder="Search by session ID..."- bind:value={searchQuery}- onSearch={handleSearch}- />-- <div class="flex flex-wrap items-center gap-2">- <button- type="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}- disabled={loading}- >- <Plus class="h-3 w-3" />- Add filter- </button>- {#each attributeFilters as f, i (i)}- <span class="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs font-mono">- <span class="text-muted-foreground">{f.key}</span>- <span>=</span>- <span>{f.value || '""'}</span>- <button- type="button"- aria-label="Remove filter"- class="ml-1 text-muted-foreground hover:text-foreground"- onclick={() => removeAttributeFilter(i)}- >- <X class="h-3 w-3" />- </button>- </span>- {/each}- </div>-- <AlertDialog.Root open={addFilterOpen} onOpenChange={(open) => (addFilterOpen = open)}>- <AlertDialog.Content>- <AlertDialog.Header>- <AlertDialog.Title>Add 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.- </AlertDialog.Description>- </AlertDialog.Header>- <div class="flex flex-col gap-3">- <label class="flex flex-col gap-1 text-sm">- <span class="font-medium">Attribute key</span>- <Input- placeholder="userAgent"- bind:value={dialogKey}- onkeydown={handleDialogKeydown}- />- </label>- <label class="flex flex-col gap-1 text-sm">- <span class="font-medium">Value</span>- <Input- placeholder="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)..."- bind:value={dialogValue}- onkeydown={handleDialogKeydown}- />- </label>- {#if dialogError}- <p class="text-xs text-red-500">{dialogError}</p>- {/if}- </div>- <AlertDialog.Footer>- <Button variant="outline" onclick={() => (addFilterOpen = false)}>Cancel</Button>- <Button onclick={submitDialogFilter}>- <Plus class="h-4 w-4" /> Add filter- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>- </AlertDialog.Root>-- <div class="rounded-md border overflow-hidden">- <Table.Root>- {#if loading}- <Table.Body>- <Table.Row>- <Table.Cell colspan={4} class="h-48">- <div class="flex justify-center items-center h-full">- <LoadingCircle size="xlg" />- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if error}- <Table.Body>- <Table.Row>- <Table.Cell colspan={4} class="h-24 text-center text-red-500">- {error}- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if sessions.length === 0}- <Table.Body>- <TableEmptyState colspan={4} message="No sessions recorded yet. Enable recordAllSessions in the SDK to start capturing them." />- </Table.Body>- {:else}- <Table.Header>- <Table.Row>- <TracewayTableHeader label="Session" tooltip="Session UUID. Open to play back the recording." />- <TracewayTableHeader- label="Started"- tooltip="When the session began"- sortField="started_at"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[160px]"- />- <TracewayTableHeader- label="Duration"- tooltip="Wall-clock length of the session"- sortField="duration"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[120px]"- />- <TracewayTableHeader label="Version" tooltip="App version reported by the SDK" class="w-[120px]" />- </Table.Row>- </Table.Header>- <Table.Body>- {#each sessions as session}- <Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={createRowClickHandler(`${resolve(`/sessions/${session.id}`)}?t=${encodeURIComponent(session.startedAt)}`, 'preset', 'from', 'to')}- >- <Table.Cell class="font-mono text-sm">{shortId(session.id)}</Table.Cell>- <Table.Cell class="text-sm">{formatRelativeTime(session.startedAt, timezone)}</Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {durationLabel(session)}- </Table.Cell>- <Table.Cell class="font-mono text-sm">{session.appVersion || '—'}</Table.Cell>- </Table.Row>- {/each}- </Table.Body>- {/if}- </Table.Root>- </div>-- <PaginationFooter- currentPage={page}- {totalPages}- {pageSize}- totalItems={total}- onPageChange={handlePageChange}- onPageSizeChange={handlePageSizeChange}- {loading}- itemLabel="session"- />+ <PageHeader title="Sessions">+ {#snippet trailing()}+ <Tooltip.Root>+ <Tooltip.Trigger class="text-muted-foreground/60 hover:text-muted-foreground">+ <Info class="h-4 w-4" />+ </Tooltip.Trigger>+ <Tooltip.Content side="right" class="max-w-xs">+ <p class="text-xs">+ Sessions are full recordings of user interactions and are only recorded when manually+ enabled (<code class="font-mono">recordAllSessions: true</code> in the SDK init options).+ </p>+ </Tooltip.Content>+ </Tooltip.Root>+ {/snippet}+ {#snippet actions()}+ <TimeRangePicker+ bind:fromDate+ bind:toDate+ bind:fromTime+ bind:toTime+ bind:preset={selectedPreset}+ onApply={handleTimeRangeChange}+ />+ {/snippet}+ </PageHeader>++ <SearchBar+ placeholder="Search by session ID..."+ bind:value={searchQuery}+ onSearch={handleSearch}+ disabled={loading}+ />++ <div class="flex flex-wrap items-center gap-2">+ <button+ type="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}+ disabled={loading}+ >+ <Plus class="h-3 w-3" />+ Add filter+ </button>+ {#each attributeFilters as f, i (i)}+ <span+ class="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="Remove filter"+ class="ml-1 text-muted-foreground hover:text-foreground"+ onclick={() => removeAttributeFilter(i)}+ >+ <X class="h-3 w-3" />+ </button>+ </span>+ {/each}+ </div>++ <AlertDialog.Root open={addFilterOpen} onOpenChange={(open) => (addFilterOpen = open)}>+ <AlertDialog.Content>+ <AlertDialog.Header>+ <AlertDialog.Title>Add 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.+ </AlertDialog.Description>+ </AlertDialog.Header>+ <div class="flex flex-col gap-3">+ <FormField label="Attribute key">+ <Input placeholder="userAgent" bind:value={dialogKey} onkeydown={handleDialogKeydown} />+ </FormField>+ <FormField label="Value">+ <Input+ placeholder="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)..."+ bind:value={dialogValue}+ onkeydown={handleDialogKeydown}+ />+ </FormField>+ {#if dialogError}+ <p class="text-xs text-red-500">{dialogError}</p>+ {/if}+ </div>+ <AlertDialog.Footer>+ <Button variant="outline" onclick={() => (addFilterOpen = false)}>Cancel</Button>+ <Button onclick={submitDialogFilter}>+ <Plus class="h-4 w-4" /> Add filter+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+ </AlertDialog.Root>++ <TableContainer>+ <Table.Root>+ {#if loading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={4} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if error}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={4} class="h-24 text-center text-red-500">+ {error}+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if sessions.length === 0}+ <Table.Body>+ <TableEmptyState+ colspan={4}+ message="No sessions recorded yet. Enable recordAllSessions in the SDK to start capturing them."+ />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader+ label="Session"+ tooltip="Session UUID. Open to play back the recording."+ />+ <TracewayTableHeader+ label="Started"+ tooltip="When the session began"+ sortField="started_at"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[160px]"+ />+ <TracewayTableHeader+ label="Duration"+ tooltip="Wall-clock length of the session"+ sortField="duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[120px]"+ />+ <TracewayTableHeader+ label="Version"+ tooltip="App version reported by the SDK"+ class="w-[120px]"+ />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each sessions as session, __index (__index)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ `${resolve(`/sessions/${session.id}`)}?t=${encodeURIComponent(session.startedAt)}`,+ 'preset',+ 'from',+ 'to'+ )}+ >+ <Table.Cell class="font-mono text-sm">{shortId(session.id)}</Table.Cell>+ <Table.Cell class="text-sm"+ >{formatRelativeTime(session.startedAt, timezone)}</Table.Cell+ >+ <Table.Cell class="font-mono text-sm tabular-nums">+ {durationLabel(session)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm">{session.appVersion || '—'}</Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </TableContainer>++ <PaginationFooter+ currentPage={page}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={handlePageChange}+ onPageSizeChange={handlePageSizeChange}+ {loading}+ itemLabel="session"+ /></div>diff --git a/frontend/src/routes/sessions/[sessionId]/+page.svelte b/frontend/src/routes/sessions/[sessionId]/+page.svelteindex 1ee4b993..0c3607e5 100644--- a/frontend/src/routes/sessions/[sessionId]/+page.svelte+++ b/frontend/src/routes/sessions/[sessionId]/+page.svelte@@ -1,260 +1,282 @@<script lang="ts">- import { onMount } from 'svelte';- import { resolve } from '$app/paths';- import { goto } from '$app/navigation';- import { page as pageState } from '$app/state';- import { api } from '$lib/api';- import { projectsState } from '$lib/state/projects.svelte';- import { getTimezone } from '$lib/state/timezone.svelte';- import { formatDuration, formatDateTime } from '$lib/utils/formatters';- import { createSmartBackHandler } from '$lib/utils/back-navigation';- import * as Card from '$lib/components/ui/card';- import * as Table from '$lib/components/ui/table';- import * as Tabs from '$lib/components/ui/tabs';- import { Button } from '$lib/components/ui/button';- import { LoadingCircle } from '$lib/components/ui/loading-circle';- import { LabelValue } from '$lib/components/ui/label-value';- import { AttributesGrid } from '$lib/components/ui/attributes-grid';- import { TableEmptyState } from '$lib/components/ui/table-empty-state';- import SessionReplay from '$lib/components/issues/session-replay.svelte';- import SessionLogsTable from '$lib/components/issues/session-logs-table.svelte';- import SessionActionsTable from '$lib/components/issues/session-actions-table.svelte';- import { ErrorDisplay } from '$lib/components/ui/error-display';- import PageHeader from '$lib/components/issues/page-header.svelte';- import { ArrowRight } from 'lucide-svelte';+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';+ import { onMount } from 'svelte';+ import { resolve } from '$app/paths';+ import { page as pageState } from '$app/state';+ import { api } from '$lib/api';+ import { projectsState } from '$lib/state/projects.svelte';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import { formatDuration, formatDateTime } from '$lib/utils/formatters';+ import { createSmartBackHandler } from '$lib/utils/back-navigation';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import * as Card from '$lib/components/ui/card';+ import * as Table from '$lib/components/ui/table';+ import * as Tabs from '$lib/components/ui/tabs';+ import { Button } from '$lib/components/ui/button';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { LabelValue } from '$lib/components/ui/label-value';+ import { AttributesGrid } from '$lib/components/ui/attributes-grid';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import SessionReplay from '$lib/components/issues/session-replay.svelte';+ import SessionLogsTable from '$lib/components/issues/session-logs-table.svelte';+ import SessionActionsTable from '$lib/components/issues/session-actions-table.svelte';+ import { ErrorDisplay } from '$lib/components/ui/error-display';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import { ArrowRight } from '@lucide/svelte';+ import type {+ SessionActionEvent,+ SessionLogEvent,+ SessionReplayEvent+ } from '$lib/types/exceptions';- type Session = {- id: string;- startedAt: string;- endedAt?: string | null;- duration: number;- clientIP: string;- appVersion: string;- serverName: string;- attributes?: Record<string, string> | null;- };+ type Session = {+ id: string;+ startedAt: string;+ endedAt?: string | null;+ duration: number;+ clientIP: string;+ appVersion: string;+ serverName: string;+ attributes?: Record<string, string> | null;+ };- type SessionException = {- id: string;- exceptionHash: string;- stackTrace: string;- recordedAt: string;- isMessage: boolean;- };+ type SessionException = {+ id: string;+ exceptionHash: string;+ stackTrace: string;+ recordedAt: string;+ isMessage: boolean;+ };- const timezone = $derived(getTimezone());- const sessionId = $derived(pageState.params.sessionId);+ const timezone = $derived(getTimezone());+ const sessionId = $derived(pageState.params.sessionId);- let session = $state<Session | null>(null);- let exceptions = $state<SessionException[]>([]);- let recordingEvents = $state<unknown[] | null>(null);- let recordingLogs = $state<any[]>([]);- let recordingActions = $state<any[]>([]);- let loading = $state(true);- let error = $state('');- let notFound = $state(false);+ let session = $state<Session | null>(null);+ let exceptions = $state<SessionException[]>([]);+ let recordingEvents = $state<SessionReplayEvent[] | null>(null);+ let recordingLogs = $state<SessionLogEvent[]>([]);+ let recordingActions = $state<SessionActionEvent[]>([]);+ let loading = $state(true);+ let error = $state('');+ let notFound = $state(false);- let currentTimeMs = $state(0);- let replayRef = $state<{ seek: (ms: number) => void } | null>(null);+ let currentTimeMs = $state(0);+ let replayRef = $state<{ seek: (ms: number) => void } | null>(null);- function handleSeek(offsetMs: number) {- replayRef?.seek(offsetMs);- }+ function handleSeek(offsetMs: number) {+ replayRef?.seek(offsetMs);+ }- const hasLogs = $derived(recordingLogs.length > 0);- const hasActions = $derived(recordingActions.length > 0);- const defaultTab = $derived(hasLogs ? 'logs' : 'actions');+ const hasLogs = $derived(recordingLogs.length > 0);+ const hasActions = $derived(recordingActions.length > 0);+ const defaultTab = $derived(hasLogs ? 'logs' : 'actions');- const ABANDONED_AFTER_MS = 15 * 60_000;+ const ABANDONED_AFTER_MS = 15 * 60_000;- function durationLabel(s: Session | null): string {- if (!s) return '—';- if (s.endedAt) return formatDuration(s.duration);- const startedMs = Date.parse(s.startedAt);- if (Number.isFinite(startedMs) && Date.now() - startedMs >= ABANDONED_AFTER_MS) {- return 'Abandoned';- }- return 'in progress';- }+ function durationLabel(s: Session | null): string {+ if (!s) return '—';+ if (s.endedAt) return formatDuration(s.duration);+ const startedMs = Date.parse(s.startedAt);+ if (Number.isFinite(startedMs) && Date.now() - startedMs >= ABANDONED_AFTER_MS) {+ return 'Abandoned';+ }+ return 'in progress';+ }- async function loadAll() {- loading = true;- error = '';- notFound = false;+ async function loadAll() {+ loading = true;+ error = '';+ notFound = false;- try {- const startedAt = pageState.url.searchParams.get('t');- const detail = await api.post(`/sessions/${sessionId}`, startedAt ? { startedAt } : {}, {- projectId: projectsState.currentProjectId ?? undefined- });- session = detail.session;- exceptions = detail.exceptions || [];+ try {+ const startedAt = pageState.url.searchParams.get('t');+ const detail = await api.post(`/sessions/${sessionId}`, startedAt ? { startedAt } : {}, {+ projectId: projectsState.currentProjectId ?? undefined+ });+ session = detail.session;+ exceptions = detail.exceptions || [];- const recording = await api.get(`/sessions/${sessionId}/recording`, {- projectId: projectsState.currentProjectId ?? undefined- });- recordingEvents = recording?.events ?? [];- recordingLogs = recording?.logs ?? [];- recordingActions = recording?.actions ?? [];- } catch (e: any) {- if (e?.status === 404) {- notFound = true;- } else {- error = e?.message || 'Failed to load session';- }- } finally {- loading = false;- }- }+ const recording = await api.get(`/sessions/${sessionId}/recording`, {+ projectId: projectsState.currentProjectId ?? undefined+ });+ recordingEvents = recording?.events ?? [];+ recordingLogs = recording?.logs ?? [];+ recordingActions = recording?.actions ?? [];+ } catch (e) {+ if (getErrorStatus(e) === 404) {+ notFound = true;+ } else {+ error = getErrorMessage(e) || 'Failed to load session';+ }+ } finally {+ loading = false;+ }+ }- onMount(() => {- loadAll();- });-- function gotoIssue(hash: string) {- goto(resolve(`/issues/${hash}`));- }+ onMount(() => {+ loadAll();+ });</script>-<div class="space-y-4">- <PageHeader title="Session" onBack={createSmartBackHandler({ fallbackPath: resolve('/sessions') })} />+<div class="space-y-6">+ <PageHeader+ title="Session"+ onBack={createSmartBackHandler({ fallbackPath: resolve('/sessions') })}+ />- {#if loading}- <div class="flex justify-center items-center h-64">- <LoadingCircle size="xlg" />- </div>- {:else if notFound}- <ErrorDisplay status={404} title="Session not found" description="This session does not exist or has been pruned." onRetry={loadAll} />- {:else if error}- <ErrorDisplay status={500} title="Error" description={error} onRetry={loadAll} />- {:else if session}- <Card.Root>- <Card.Header>- <Card.Title>Overview</Card.Title>- </Card.Header>- <Card.Content class="grid grid-cols-2 gap-4 sm:grid-cols-3">- <LabelValue label="Started" value={formatDateTime(session.startedAt, { timezone })} />- <LabelValue label="Duration" value={durationLabel(session)} />- <LabelValue label="App version" value={session.appVersion || '—'} />- </Card.Content>- </Card.Root>+ {#if loading}+ <div class="flex h-64 items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ {:else if notFound}+ <ErrorDisplay+ status={404}+ title="Session not found"+ description="This session does not exist or has been pruned."+ onRetry={loadAll}+ />+ {:else if error}+ <ErrorDisplay status={500} title="Error" description={error} onRetry={loadAll} />+ {:else if session}+ <Card.Root>+ <Card.Header>+ <Card.Title>Overview</Card.Title>+ </Card.Header>+ <Card.Content class="grid grid-cols-2 gap-4 sm:grid-cols-3">+ <LabelValue label="Started" value={formatDateTime(session.startedAt, { timezone })} />+ <LabelValue label="Duration" value={durationLabel(session)} />+ <LabelValue label="App version" value={session.appVersion || '—'} />+ </Card.Content>+ </Card.Root>- {#if session.attributes && Object.keys(session.attributes).length > 0}- <Card.Root>- <Card.Header>- <Card.Title>Attributes</Card.Title>- </Card.Header>- <Card.Content>- <AttributesGrid attributes={session.attributes} collapsedCount={6} />- </Card.Content>- </Card.Root>- {/if}+ {#if session.attributes && Object.keys(session.attributes).length > 0}+ <Card.Root>+ <Card.Header>+ <Card.Title>Attributes</Card.Title>+ </Card.Header>+ <Card.Content>+ <AttributesGrid attributes={session.attributes} collapsedCount={6} />+ </Card.Content>+ </Card.Root>+ {/if}- {#if recordingEvents && recordingEvents.length > 0}- <Card.Root class="pb-0">- <Card.Header class="gap-0">- <Card.Title>Session Replay</Card.Title>- </Card.Header>- <Card.Content class="p-0">- {#key recordingEvents}- <SessionReplay- bind:this={replayRef}- events={recordingEvents as any}- onTimeUpdate={(ms) => (currentTimeMs = ms)}- />- {/key}- </Card.Content>- </Card.Root>- {:else}- <Card.Root>- <Card.Header>- <Card.Title>Session Replay</Card.Title>- </Card.Header>- <Card.Content class="text-sm text-muted-foreground">- No replay data has been uploaded for this session yet.- </Card.Content>- </Card.Root>- {/if}+ {#if recordingEvents && recordingEvents.length > 0}+ <Card.Root class="pb-0">+ <Card.Header class="gap-0">+ <Card.Title>Session Replay</Card.Title>+ </Card.Header>+ <Card.Content class="p-0">+ {#key recordingEvents}+ <SessionReplay+ bind:this={replayRef}+ events={recordingEvents}+ onTimeUpdate={(ms) => (currentTimeMs = ms)}+ />+ {/key}+ </Card.Content>+ </Card.Root>+ {:else}+ <Card.Root>+ <Card.Header>+ <Card.Title>Session Replay</Card.Title>+ </Card.Header>+ <Card.Content class="text-sm text-muted-foreground">+ No replay data has been uploaded for this session yet.+ </Card.Content>+ </Card.Root>+ {/if}- {#if hasLogs || hasActions}- <Card.Root>- <Card.Header>- <Card.Title>Session Context</Card.Title>- <Card.Description>- Console output and recorded actions across the session. Times are offsets from session start.- </Card.Description>- </Card.Header>- <Card.Content>- <Tabs.Root value={defaultTab}>- <Tabs.List class="mb-4">- {#if hasLogs}- <Tabs.Trigger value="logs">Logs ({recordingLogs.length})</Tabs.Trigger>- {/if}- {#if hasActions}- <Tabs.Trigger value="actions">Actions ({recordingActions.length})</Tabs.Trigger>- {/if}- </Tabs.List>- {#if hasLogs}- <Tabs.Content value="logs">- <SessionLogsTable- logs={recordingLogs}- startedAt={session.startedAt}- {currentTimeMs}- onSeek={handleSeek}- />- </Tabs.Content>- {/if}- {#if hasActions}- <Tabs.Content value="actions">- <SessionActionsTable- actions={recordingActions}- startedAt={session.startedAt}- {currentTimeMs}- onSeek={handleSeek}- />- </Tabs.Content>- {/if}- </Tabs.Root>- </Card.Content>- </Card.Root>- {/if}+ {#if hasLogs || hasActions}+ <Card.Root>+ <Card.Header>+ <Card.Title>Session Context</Card.Title>+ <Card.Description>+ Console output and recorded actions across the session. Times are offsets from session+ start.+ </Card.Description>+ </Card.Header>+ <Card.Content>+ <Tabs.Root value={defaultTab}>+ <Tabs.List class="mb-4">+ {#if hasLogs}+ <Tabs.Trigger value="logs">Logs ({recordingLogs.length})</Tabs.Trigger>+ {/if}+ {#if hasActions}+ <Tabs.Trigger value="actions">Actions ({recordingActions.length})</Tabs.Trigger>+ {/if}+ </Tabs.List>+ {#if hasLogs}+ <Tabs.Content value="logs">+ <SessionLogsTable+ logs={recordingLogs}+ startedAt={session.startedAt}+ {currentTimeMs}+ onSeek={handleSeek}+ />+ </Tabs.Content>+ {/if}+ {#if hasActions}+ <Tabs.Content value="actions">+ <SessionActionsTable+ actions={recordingActions}+ startedAt={session.startedAt}+ {currentTimeMs}+ onSeek={handleSeek}+ />+ </Tabs.Content>+ {/if}+ </Tabs.Root>+ </Card.Content>+ </Card.Root>+ {/if}- <Card.Root>- <Card.Header>- <Card.Title>Exceptions in this session</Card.Title>- </Card.Header>- <Card.Content class="p-0">- <Table.Root>- {#if exceptions.length === 0}- <Table.Body>- <TableEmptyState colspan={3} message="No exceptions captured during this session." />- </Table.Body>- {:else}- <Table.Header>- <Table.Row>- <Table.Head>When</Table.Head>- <Table.Head>Stack trace</Table.Head>- <Table.Head class="w-[60px]"></Table.Head>- </Table.Row>- </Table.Header>- <Table.Body>- {#each exceptions as exc}- <Table.Row class="cursor-pointer hover:bg-muted/50" onclick={() => gotoIssue(exc.exceptionHash)}>- <Table.Cell class="text-sm whitespace-nowrap">{formatDateTime(exc.recordedAt, { timezone })}</Table.Cell>- <Table.Cell class="font-mono text-xs truncate max-w-md">- {exc.stackTrace.split('\n')[0]}- </Table.Cell>- <Table.Cell>- <Button variant="ghost" size="icon" aria-label="Open issue">- <ArrowRight class="size-4" />- </Button>- </Table.Cell>- </Table.Row>- {/each}- </Table.Body>- {/if}- </Table.Root>- </Card.Content>- </Card.Root>- {/if}+ <Card.Root>+ <Card.Header>+ <Card.Title>Exceptions in this session</Card.Title>+ </Card.Header>+ <Card.Content>+ <TableContainer>+ <Table.Root>+ {#if exceptions.length === 0}+ <Table.Body>+ <TableEmptyState+ colspan={3}+ message="No exceptions captured during this session."+ />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <Table.Head>When</Table.Head>+ <Table.Head>Stack trace</Table.Head>+ <Table.Head class="w-[60px]"></Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each exceptions as exc, __index (__index)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(`/issues/${exc.exceptionHash}`)}+ >+ <Table.Cell class="text-sm whitespace-nowrap"+ >{formatDateTime(exc.recordedAt, { timezone })}</Table.Cell+ >+ <Table.Cell class="max-w-md truncate font-mono text-xs">+ {exc.stackTrace.split('\n')[0]}+ </Table.Cell>+ <Table.Cell>+ <Button variant="ghost" size="icon" aria-label="Open issue">+ <ArrowRight class="size-4" />+ </Button>+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </TableContainer>+ </Card.Content>+ </Card.Root>+ {/if}</div>diff --git a/frontend/src/routes/settings/+page.svelte b/frontend/src/routes/settings/+page.svelteindex a7a6f6e9..dd1816fb 100644--- a/frontend/src/routes/settings/+page.svelte+++ b/frontend/src/routes/settings/+page.svelte@@ -1,116 +1,108 @@<script lang="ts">- import { goto } from '$app/navigation';- import { authState } from '$lib/state/auth.svelte';- import { projectsState } from '$lib/state/projects.svelte';- import { organizationState } from '$lib/state/organization.svelte';- import * as Select from '$lib/components/ui/select';- import OrganizationTab from './organization-tab.svelte';- import UsersTab from './users-tab.svelte';- import type { Component } from 'svelte';- import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { resolve } from '$app/paths';+ import { goto } from '$app/navigation';+ import { authState } from '$lib/state/auth.svelte';+ import { projectsState } from '$lib/state/projects.svelte';+ import { organizationState } from '$lib/state/organization.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import OrgSwitcher from '$lib/components/traceway/org-switcher.svelte';+ import OrganizationTab from './organization-tab.svelte';+ import UsersTab from './users-tab.svelte';+ import type { Component } from 'svelte';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';- let loading = $state(true);- let error = $state<string | null>(null);- let BillingTab = $state<Component<{ organizationId: number }> | null>(null);+ let loading = $state(true);+ let error = $state<string | null>(null);+ let BillingTab = $state<Component<{ organizationId: number }> | null>(null);- async function loadBillingModule() {- try {- // @ts-ignore - $billing alias only exists when billing extension is available- const module = await import('$billing/billing-tab.svelte');- BillingTab = module.default;- } catch {- // Billing extension not available - this is expected for open source builds- }- }+ async function loadBillingModule() {+ try {+ // @ts-expect-error - $billing alias only exists when billing extension is available+ const module = await import('$billing/billing-tab.svelte');+ BillingTab = module.default;+ } catch {+ // Billing extension not available - this is expected for open source builds+ }+ }- $effect(() => {- loadBillingModule();- });+ $effect(() => {+ loadBillingModule();+ });- const manageableOrgs = $derived(- authState.organizations.filter(o => o.role === 'owner' || o.role === 'admin')- );+ const manageableOrgs = $derived(+ authState.organizations.filter((o) => o.role === 'owner' || o.role === 'admin')+ );- let selectedOrgId = $state<number | null>(null);+ let selectedOrgId = $state<number | null>(null);- const currentOrganizationId = $derived.by(() => {- if (selectedOrgId !== null && manageableOrgs.some(o => o.id === selectedOrgId)) {- return selectedOrgId;- }- const projectOrgId = projectsState.currentProject?.organizationId;- if (projectOrgId && manageableOrgs.some(o => o.id === projectOrgId)) {- return projectOrgId;- }- return manageableOrgs[0]?.id ?? null;- });+ const currentOrganizationId = $derived.by(() => {+ if (selectedOrgId !== null && manageableOrgs.some((o) => o.id === selectedOrgId)) {+ return selectedOrgId;+ }+ const projectOrgId = projectsState.currentProject?.organizationId;+ if (projectOrgId && manageableOrgs.some((o) => o.id === projectOrgId)) {+ return projectOrgId;+ }+ return manageableOrgs[0]?.id ?? null;+ });- const currentOrganizationName = $derived(- manageableOrgs.find(o => o.id === currentOrganizationId)?.name ?? ''- );+ const currentOrganizationName = $derived(+ manageableOrgs.find((o) => o.id === currentOrganizationId)?.name ?? ''+ );- const hasAccess = $derived(currentOrganizationId !== null);+ const hasAccess = $derived(currentOrganizationId !== null);- $effect(() => {- if (!hasAccess) {- goto('/');- }- });+ $effect(() => {+ if (!hasAccess) {+ goto(resolve('/'));+ }+ });- let loadSeq = 0;+ let loadSeq = 0;- $effect(() => {- if (currentOrganizationId && hasAccess) {- const seq = ++loadSeq;- loading = true;- error = null;- organizationState.loadSettings(currentOrganizationId).then(() => {- if (seq !== loadSeq) return;- error = organizationState.error;- loading = false;- });- }- });+ $effect(() => {+ if (currentOrganizationId && hasAccess) {+ const seq = ++loadSeq;+ loading = true;+ error = null;+ organizationState.loadSettings(currentOrganizationId).then(() => {+ if (seq !== loadSeq) return;+ error = organizationState.error;+ loading = false;+ });+ }+ });</script><div class="space-y-4">- <div class="flex items-center justify-between gap-4">- <h1 class="text-3xl font-semibold tracking-tight">Settings</h1>- {#if manageableOrgs.length > 1}- <div class="flex items-center gap-2">- <span class="text-sm text-muted-foreground">Organization</span>- <Select.Root- type="single"- value={currentOrganizationId !== null ? String(currentOrganizationId) : undefined}- onValueChange={(val) => { if (val) selectedOrgId = Number(val); }}- >- <Select.Trigger class="w-[220px]">- {currentOrganizationName || 'Select organization'}- </Select.Trigger>- <Select.Content>- {#each manageableOrgs as org (org.id)}- <Select.Item value={String(org.id)}>{org.name}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- {/if}- </div>+ <PageHeader title="Settings">+ {#snippet actions()}+ {#if manageableOrgs.length > 1}+ <OrgSwitcher+ organizations={manageableOrgs.map((o) => ({ id: o.id, name: o.name }))}+ {currentOrganizationId}+ {currentOrganizationName}+ onChange={(id) => (selectedOrgId = id)}+ />+ {/if}+ {/snippet}+ </PageHeader>- {#if loading}- <div class="flex items-center justify-center py-12">- <LoadingCircle size="xlg" />- </div>- {:else if error}- <div class="text-center py-12 text-destructive">- {error}- </div>- {:else}- <div class="space-y-4">- <OrganizationTab />- <UsersTab organizationId={currentOrganizationId!} />- {#if BillingTab}- <BillingTab organizationId={currentOrganizationId!} />- {/if}- </div>- {/if}+ {#if loading}+ <div class="flex items-center justify-center py-12">+ <LoadingCircle size="xlg" />+ </div>+ {:else if error}+ <div class="py-12 text-center text-destructive">+ {error}+ </div>+ {:else}+ <div class="space-y-4">+ <OrganizationTab />+ <UsersTab organizationId={currentOrganizationId!} />+ {#if BillingTab}+ <BillingTab organizationId={currentOrganizationId!} />+ {/if}+ </div>+ {/if}</div>diff --git a/frontend/src/routes/settings/+page.ts b/frontend/src/routes/settings/+page.tsindex 91ecb20b..1ae6cd16 100644--- a/frontend/src/routes/settings/+page.ts+++ b/frontend/src/routes/settings/+page.ts@@ -5,9 +5,9 @@ import type { PageLoad } from './$types';export const prerender = false;export const load: PageLoad = () => {- const canManage = authState.organizations.some((o) => o.role === 'owner' || o.role === 'admin');- if (!canManage) {- throw redirect(302, '/');- }- return {};+ const canManage = authState.organizations.some((o) => o.role === 'owner' || o.role === 'admin');+ if (!canManage) {+ throw redirect(302, '/');+ }+ return {};};diff --git a/frontend/src/routes/settings/invite-user-dialog.svelte b/frontend/src/routes/settings/invite-user-dialog.svelteindex 393784a9..9fd96f08 100644--- a/frontend/src/routes/settings/invite-user-dialog.svelte+++ b/frontend/src/routes/settings/invite-user-dialog.svelte@@ -1,119 +1,122 @@<script lang="ts">- import * as AlertDialog from "$lib/components/ui/alert-dialog";- import { Button } from "$lib/components/ui/button";- import { Input } from "$lib/components/ui/input";- import { Label } from "$lib/components/ui/label";- import { ErrorAlert } from "$lib/components/ui/error-alert";- import * as Select from "$lib/components/ui/select";- import { Plus } from "@lucide/svelte";- import { toast } from 'svelte-sonner';- import { organizationState } from '$lib/state/organization.svelte';+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import * as Select from '$lib/components/ui/select';+ import FormField from '$lib/components/traceway/form-field.svelte';+ import { Plus } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import { organizationState } from '$lib/state/organization.svelte';- interface Props {- open: boolean;- organizationId: number;- }+ interface Props {+ open: boolean;+ organizationId: number;+ }- let { open = $bindable(), organizationId }: Props = $props();+ let { open = $bindable(), organizationId }: Props = $props();- let email = $state('');- let role = $state('user');- let loading = $state(false);- let error = $state('');+ let email = $state('');+ let role = $state('user');+ let loading = $state(false);+ let error = $state('');- const roleOptions = [- { value: 'admin', label: 'Admin', description: 'Full access to projects and settings' },- { value: 'user', label: 'User', description: 'Can view and modify projects' },- { value: 'readonly', label: 'Read Only', description: 'Can only view projects' }- ];+ const roleOptions = [+ { value: 'admin', label: 'Admin', description: 'Full access to projects and settings' },+ { value: 'user', label: 'User', description: 'Can view and modify projects' },+ { value: 'readonly', label: 'Read Only', description: 'Can only view projects' }+ ];- async function handleSubmit() {- if (!email) {- error = 'Email is required';- return;- }+ async function handleSubmit() {+ if (!email) {+ error = 'Email is required';+ return;+ }- loading = true;- error = '';+ loading = true;+ error = '';- try {- await organizationState.inviteUser(organizationId, email, role);- toast.success('Successfully created the Invitation', { position: 'top-center' });- email = '';- role = 'user';- open = false;- } catch (e: unknown) {- error = e instanceof Error ? e.message : 'Failed to send invitation';- toast.error(error);- } finally {- loading = false;- }- }+ try {+ await organizationState.inviteUser(organizationId, email, role);+ toast.success('Successfully created the Invitation', { position: 'top-center' });+ email = '';+ role = 'user';+ open = false;+ } catch (e: unknown) {+ error = e instanceof Error ? e.message : 'Failed to send invitation';+ toast.error(error);+ } finally {+ loading = false;+ }+ }- function handleOpenChange(isOpen: boolean) {- if (!isOpen) {- email = '';- role = 'user';- error = '';- }- open = isOpen;- }+ function handleOpenChange(isOpen: boolean) {+ if (!isOpen) {+ email = '';+ role = 'user';+ error = '';+ }+ open = isOpen;+ }</script><AlertDialog.Root {open} onOpenChange={handleOpenChange}>- <AlertDialog.Content class="max-w-md">- <AlertDialog.Header>- <AlertDialog.Title>New Invitation</AlertDialog.Title>- <AlertDialog.Description>- Send an invitation to join your organization- </AlertDialog.Description>- </AlertDialog.Header>+ <AlertDialog.Content class="max-w-md">+ <AlertDialog.Header>+ <AlertDialog.Title>New Invitation</AlertDialog.Title>+ <AlertDialog.Description>+ Send an invitation to join your organization+ </AlertDialog.Description>+ </AlertDialog.Header>- <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="space-y-4 py-4">- <ErrorAlert {error} />+ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleSubmit();+ }}+ class="space-y-4"+ >+ <ErrorAlert {error} />- <div class="space-y-2">- <Label for="email">Email Address</Label>- <Input- id="email"- type="email"- bind:value={email}- placeholder="[email protected]"- required- />- </div>+ <FormField label="Email Address" for="email">+ <Input+ id="email"+ type="email"+ bind:value={email}+ placeholder="[email protected]"+ required+ />+ </FormField>- <div class="space-y-2">- <Label for="role">Role</Label>- <Select.Root type="single" bind:value={role}>- <Select.Trigger class="w-full">- {roleOptions.find(r => r.value === role)?.label || 'Select role'}- </Select.Trigger>- <Select.Content>- {#each roleOptions as roleOption}- <Select.Item value={roleOption.value}>- <div class="flex flex-col">- <span>{roleOption.label}</span>- <span class="text-xs text-muted-foreground">{roleOption.description}</span>- </div>- </Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>+ <FormField label="Role" for="role">+ <Select.Root type="single" bind:value={role}>+ <Select.Trigger id="role" class="w-full">+ {roleOptions.find((r) => r.value === role)?.label || 'Select role'}+ </Select.Trigger>+ <Select.Content>+ {#each roleOptions as roleOption, __index (__index)}+ <Select.Item value={roleOption.value}>+ <div class="flex flex-col">+ <span>{roleOption.label}</span>+ <span class="text-xs text-muted-foreground">{roleOption.description}</span>+ </div>+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </FormField>+ </form>- </form>-- <AlertDialog.Footer>- <AlertDialog.Cancel disabled={loading}>Cancel</AlertDialog.Cancel>- <Button variant="success" onclick={handleSubmit} disabled={loading}>- <Plus class="mr-2 h-4 w-4" />- {#if loading}- Creating...- {:else}- New Invitation- {/if}- </Button>- </AlertDialog.Footer>- </AlertDialog.Content>+ <AlertDialog.Footer>+ <AlertDialog.Cancel disabled={loading}>Cancel</AlertDialog.Cancel>+ <Button variant="success" onclick={handleSubmit} disabled={loading}>+ <Plus class="mr-2 h-4 w-4" />+ {#if loading}+ Creating...+ {:else}+ New Invitation+ {/if}+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content></AlertDialog.Root>diff --git a/frontend/src/routes/settings/organization-tab.svelte b/frontend/src/routes/settings/organization-tab.svelteindex f1e8cfad..c9b4c920 100644--- a/frontend/src/routes/settings/organization-tab.svelte+++ b/frontend/src/routes/settings/organization-tab.svelte@@ -1,156 +1,162 @@<script lang="ts">- import { Check } from "@lucide/svelte";- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "$lib/components/ui/card";- import { Label } from "$lib/components/ui/label";- import { Button } from "$lib/components/ui/button";- import * as Select from "$lib/components/ui/select";- import { organizationState } from '$lib/state/organization.svelte';- import { authState } from '$lib/state/auth.svelte';- import { toast } from 'svelte-sonner';+ import { Check } from '@lucide/svelte';+ import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle+ } from '$lib/components/ui/card';+ import { Label } from '$lib/components/ui/label';+ import { Button } from '$lib/components/ui/button';+ import * as Select from '$lib/components/ui/select';+ import { organizationState } from '$lib/state/organization.svelte';+ import { authState } from '$lib/state/auth.svelte';+ import { toast } from 'svelte-sonner';- const organization = $derived(organizationState.currentOrganization);- const canManage = $derived(organizationState.canManage);+ const organization = $derived(organizationState.currentOrganization);+ const canManage = $derived(organizationState.canManage);- let selectedTimezone = $state(organizationState.currentOrganization?.timezone || 'UTC');- let saving = $state(false);+ let selectedTimezone = $state(organizationState.currentOrganization?.timezone || 'UTC');+ let saving = $state(false);- $effect(() => {- if (organization?.timezone) {- selectedTimezone = organization.timezone;- }- });+ $effect(() => {+ if (organization?.timezone) {+ selectedTimezone = organization.timezone;+ }+ });- const hasChanges = $derived(selectedTimezone !== organization?.timezone);+ const hasChanges = $derived(selectedTimezone !== organization?.timezone);- const timezoneGroups = [- {- label: 'Common',- timezones: [- { value: 'UTC', label: 'UTC (Coordinated Universal Time)' },- { value: 'America/New_York', label: 'US Eastern (New York)' },- { value: 'America/Chicago', label: 'US Central (Chicago)' },- { value: 'America/Denver', label: 'US Mountain (Denver)' },- { value: 'America/Los_Angeles', label: 'US Pacific (Los Angeles)' },- ]- },- {- label: 'Europe',- timezones: [- { value: 'Europe/London', label: 'London (GMT/BST)' },- { value: 'Europe/Paris', label: 'Paris (CET/CEST)' },- { value: 'Europe/Berlin', label: 'Berlin (CET/CEST)' },- { value: 'Europe/Belgrade', label: 'Belgrade (CET/CEST)' },- { value: 'Europe/Amsterdam', label: 'Amsterdam (CET/CEST)' },- { value: 'Europe/Stockholm', label: 'Stockholm (CET/CEST)' },- { value: 'Europe/Zurich', label: 'Zurich (CET/CEST)' },- { value: 'Europe/Madrid', label: 'Madrid (CET/CEST)' },- { value: 'Europe/Rome', label: 'Rome (CET/CEST)' },- { value: 'Europe/Athens', label: 'Athens (EET/EEST)' },- { value: 'Europe/Moscow', label: 'Moscow (MSK)' },- ]- },- {- label: 'Asia & Pacific',- timezones: [- { value: 'Asia/Dubai', label: 'Dubai (GST)' },- { value: 'Asia/Kolkata', label: 'India (IST)' },- { value: 'Asia/Singapore', label: 'Singapore (SGT)' },- { value: 'Asia/Hong_Kong', label: 'Hong Kong (HKT)' },- { value: 'Asia/Shanghai', label: 'Shanghai (CST)' },- { value: 'Asia/Tokyo', label: 'Tokyo (JST)' },- { value: 'Asia/Seoul', label: 'Seoul (KST)' },- { value: 'Australia/Sydney', label: 'Sydney (AEST/AEDT)' },- { value: 'Australia/Melbourne', label: 'Melbourne (AEST/AEDT)' },- { value: 'Pacific/Auckland', label: 'Auckland (NZST/NZDT)' },- ]- },- {- label: 'Americas',- timezones: [- { value: 'America/Toronto', label: 'Toronto (EST/EDT)' },- { value: 'America/Vancouver', label: 'Vancouver (PST/PDT)' },- { value: 'America/Mexico_City', label: 'Mexico City (CST/CDT)' },- { value: 'America/Sao_Paulo', label: 'São Paulo (BRT)' },- { value: 'America/Buenos_Aires', label: 'Buenos Aires (ART)' },- ]- }- ];+ const timezoneGroups = [+ {+ label: 'Common',+ timezones: [+ { value: 'UTC', label: 'UTC (Coordinated Universal Time)' },+ { value: 'America/New_York', label: 'US Eastern (New York)' },+ { value: 'America/Chicago', label: 'US Central (Chicago)' },+ { value: 'America/Denver', label: 'US Mountain (Denver)' },+ { value: 'America/Los_Angeles', label: 'US Pacific (Los Angeles)' }+ ]+ },+ {+ label: 'Europe',+ timezones: [+ { value: 'Europe/London', label: 'London (GMT/BST)' },+ { value: 'Europe/Paris', label: 'Paris (CET/CEST)' },+ { value: 'Europe/Berlin', label: 'Berlin (CET/CEST)' },+ { value: 'Europe/Belgrade', label: 'Belgrade (CET/CEST)' },+ { value: 'Europe/Amsterdam', label: 'Amsterdam (CET/CEST)' },+ { value: 'Europe/Stockholm', label: 'Stockholm (CET/CEST)' },+ { value: 'Europe/Zurich', label: 'Zurich (CET/CEST)' },+ { value: 'Europe/Madrid', label: 'Madrid (CET/CEST)' },+ { value: 'Europe/Rome', label: 'Rome (CET/CEST)' },+ { value: 'Europe/Athens', label: 'Athens (EET/EEST)' },+ { value: 'Europe/Moscow', label: 'Moscow (MSK)' }+ ]+ },+ {+ label: 'Asia & Pacific',+ timezones: [+ { value: 'Asia/Dubai', label: 'Dubai (GST)' },+ { value: 'Asia/Kolkata', label: 'India (IST)' },+ { value: 'Asia/Singapore', label: 'Singapore (SGT)' },+ { value: 'Asia/Hong_Kong', label: 'Hong Kong (HKT)' },+ { value: 'Asia/Shanghai', label: 'Shanghai (CST)' },+ { value: 'Asia/Tokyo', label: 'Tokyo (JST)' },+ { value: 'Asia/Seoul', label: 'Seoul (KST)' },+ { value: 'Australia/Sydney', label: 'Sydney (AEST/AEDT)' },+ { value: 'Australia/Melbourne', label: 'Melbourne (AEST/AEDT)' },+ { value: 'Pacific/Auckland', label: 'Auckland (NZST/NZDT)' }+ ]+ },+ {+ label: 'Americas',+ timezones: [+ { value: 'America/Toronto', label: 'Toronto (EST/EDT)' },+ { value: 'America/Vancouver', label: 'Vancouver (PST/PDT)' },+ { value: 'America/Mexico_City', label: 'Mexico City (CST/CDT)' },+ { value: 'America/Sao_Paulo', label: 'São Paulo (BRT)' },+ { value: 'America/Buenos_Aires', label: 'Buenos Aires (ART)' }+ ]+ }+ ];- function getTimezoneLabel(value: string): string {- for (const group of timezoneGroups) {- const tz = group.timezones.find(t => t.value === value);- if (tz) return tz.label;- }- return value;- }+ function getTimezoneLabel(value: string): string {+ for (const group of timezoneGroups) {+ const tz = group.timezones.find((t) => t.value === value);+ if (tz) return tz.label;+ }+ return value;+ }- async function handleSave() {- if (!organization) return;+ async function handleSave() {+ if (!organization) return;- saving = true;- try {- await organizationState.updateTimezone(organization.id, selectedTimezone);- authState.updateOrganizationTimezone(organization.id, selectedTimezone);- toast.success('Successfully updated the Timezone', { position: 'top-center' });- } catch (e: unknown) {- const errorMessage = e instanceof Error ? e.message : 'Failed to update timezone';- toast.error(errorMessage);- } finally {- saving = false;- }- }+ saving = true;+ try {+ await organizationState.updateTimezone(organization.id, selectedTimezone);+ authState.updateOrganizationTimezone(organization.id, selectedTimezone);+ toast.success('Successfully updated the Timezone', { position: 'top-center' });+ } catch (e: unknown) {+ const errorMessage = e instanceof Error ? e.message : 'Failed to update timezone';+ toast.error(errorMessage);+ } finally {+ saving = false;+ }+ }</script><Card>- <CardHeader>- <CardTitle>Organization Details</CardTitle>- <CardDescription>Information about your organization</CardDescription>- </CardHeader>- <CardContent class="space-y-4">- {#if organization}- <div class="grid gap-4">- <div class="grid grid-cols-4 items-center gap-4">- <Label class="text-right text-muted-foreground">Name</Label>- <div class="col-span-3">{organization.name}</div>- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label class="text-right text-muted-foreground">Timezone</Label>- <div class="col-span-3">- {#if canManage}- <div class="flex items-center gap-2">- <Select.Root type="single" bind:value={selectedTimezone}>- <Select.Trigger class="w-[280px]">- {getTimezoneLabel(selectedTimezone)}- </Select.Trigger>- <Select.Content class="max-h-[300px]">- {#each timezoneGroups as group}- <Select.Group>- <Select.GroupHeading>{group.label}</Select.GroupHeading>- {#each group.timezones as tz}- <Select.Item value={tz.value}>{tz.label}</Select.Item>- {/each}- </Select.Group>- {/each}- </Select.Content>- </Select.Root>- {#if hasChanges}- <Button onclick={handleSave} disabled={saving} size="sm">- <Check class="mr-1 h-4 w-4" />- {saving ? 'Updating...' : 'Update Timezone'}- </Button>- {/if}- </div>- <p class="text-xs text-muted-foreground mt-1">- All team members will see timestamps in this timezone- </p>- {:else}- <span>{getTimezoneLabel(organization.timezone)}</span>- {/if}- </div>- </div>- </div>- {:else}- <p class="text-muted-foreground">Organization information not available</p>- {/if}- </CardContent>+ <CardHeader>+ <CardTitle>Organization Details</CardTitle>+ <CardDescription>Information about your organization</CardDescription>+ </CardHeader>+ <CardContent class="space-y-4">+ {#if organization}+ <div class="grid gap-4">+ <div class="grid grid-cols-4 items-center gap-4">+ <Label class="text-right text-muted-foreground">Name</Label>+ <div class="col-span-3">{organization.name}</div>+ </div>+ <div class="grid grid-cols-4 items-center gap-4">+ <Label class="text-right text-muted-foreground">Timezone</Label>+ <div class="col-span-3">+ {#if canManage}+ <div class="flex flex-wrap items-center gap-2">+ <Select.Root type="single" bind:value={selectedTimezone}>+ <Select.Trigger class="w-full sm:w-[280px]">+ {getTimezoneLabel(selectedTimezone)}+ </Select.Trigger>+ <Select.Content class="max-h-[300px]">+ {#each timezoneGroups as group, __index (__index)}+ <Select.Group>+ <Select.GroupHeading>{group.label}</Select.GroupHeading>+ {#each group.timezones as tz, __index (__index)}+ <Select.Item value={tz.value}>{tz.label}</Select.Item>+ {/each}+ </Select.Group>+ {/each}+ </Select.Content>+ </Select.Root>+ {#if hasChanges}+ <Button onclick={handleSave} disabled={saving} size="sm">+ <Check class="mr-2 h-4 w-4" />+ {saving ? 'Updating...' : 'Update Timezone'}+ </Button>+ {/if}+ </div>+ <p class="mt-1 text-xs text-muted-foreground">+ All team members will see timestamps in this timezone+ </p>+ {:else}+ <span>{getTimezoneLabel(organization.timezone)}</span>+ {/if}+ </div>+ </div>+ </div>+ {:else}+ <p class="text-muted-foreground">Organization information not available</p>+ {/if}+ </CardContent></Card>diff --git a/frontend/src/routes/settings/users-tab.svelte b/frontend/src/routes/settings/users-tab.svelteindex 4f234c2c..4c63bd98 100644--- a/frontend/src/routes/settings/users-tab.svelte+++ b/frontend/src/routes/settings/users-tab.svelte@@ -1,375 +1,431 @@<script lang="ts">- import { Button } from "$lib/components/ui/button";- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "$lib/components/ui/card";- import * as Table from "$lib/components/ui/table";- import * as Select from "$lib/components/ui/select";- import * as AlertDialog from "$lib/components/ui/alert-dialog";- import { Badge } from "$lib/components/ui/badge";- import { Plus, Trash2, ChevronRight, ChevronDown } from "@lucide/svelte";- import { toast } from 'svelte-sonner';- import { organizationState, type OrganizationMember, type Invitation, type MemberProjectRole } from '$lib/state/organization.svelte';- import { authState } from '$lib/state/auth.svelte';- import { type Framework } from '$lib/state/projects.svelte';- import FrameworkIcon from '$lib/components/framework-icon.svelte';- import { LoadingCircle } from '$lib/components/ui/loading-circle';- import InviteUserDialog from './invite-user-dialog.svelte';+ import { Button } from '$lib/components/ui/button';+ import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle+ } from '$lib/components/ui/card';+ import * as Table from '$lib/components/ui/table';+ import * as Select from '$lib/components/ui/select';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { Badge } from '$lib/components/ui/badge';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import StatusPill from '$lib/components/traceway/status-pill.svelte';+ import ConfirmDeleteDialog from '$lib/components/traceway/confirm-delete-dialog.svelte';+ import { Plus, Trash2, ChevronRight, ChevronDown } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import {+ organizationState,+ type OrganizationMember,+ type Invitation,+ type MemberProjectRole+ } from '$lib/state/organization.svelte';+ import { type Framework } from '$lib/state/projects.svelte';+ import FrameworkIcon from '$lib/components/framework-icon.svelte';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import InviteUserDialog from './invite-user-dialog.svelte';- interface Props {- organizationId: number;- }+ interface Props {+ organizationId: number;+ }- let { organizationId }: Props = $props();+ let { organizationId }: Props = $props();- let showInviteDialog = $state(false);- let memberToRemove = $state<OrganizationMember | null>(null);- let invitationToRevoke = $state<Invitation | null>(null);- let processingRoleChange = $state<number | null>(null);- let expandedMemberId = $state<number | null>(null);- let expandedProjectRoles = $state<MemberProjectRole[]>([]);- let loadingProjectRoles = $state(false);- let processingProjectRole = $state<string | null>(null);+ let showInviteDialog = $state(false);+ let memberToRemove = $state<OrganizationMember | null>(null);+ let removeDialogOpen = $state(false);+ let removeLoading = $state(false);+ let removeError = $state('');+ let invitationToRevoke = $state<Invitation | null>(null);+ let revokeDialogOpen = $state(false);+ let revokeLoading = $state(false);+ let revokeError = $state('');+ let processingRoleChange = $state<number | null>(null);+ let expandedMemberId = $state<number | null>(null);+ let expandedProjectRoles = $state<MemberProjectRole[]>([]);+ let loadingProjectRoles = $state(false);+ let processingProjectRole = $state<string | null>(null);- const members = $derived(organizationState.members);- const invitations = $derived(organizationState.invitations.filter(i => i.status === 'pending'));- const canInvite = $derived(organizationState.canInvite);- const isOwner = $derived(organizationState.isOwner);+ const members = $derived(organizationState.members);+ const invitations = $derived(organizationState.invitations.filter((i) => i.status === 'pending'));+ const canInvite = $derived(organizationState.canInvite);+ const isOwner = $derived(organizationState.isOwner);- const roleOptions = [- { value: 'admin', label: 'Admin' },- { value: 'user', label: 'User' },- { value: 'readonly', label: 'Read Only' }- ];+ const roleOptions = [+ { value: 'admin', label: 'Admin' },+ { value: 'user', label: 'User' },+ { value: 'readonly', label: 'Read Only' }+ ];- async function handleRoleChange(userId: number, newRole: string) {- processingRoleChange = userId;- try {- await organizationState.updateMemberRole(organizationId, userId, newRole);- toast.success('Successfully updated the Role', { position: 'top-center' });- } catch (e) {- toast.error(e instanceof Error ? e.message : 'Failed to update role', { position: 'top-center' });- } finally {- processingRoleChange = null;- }- }+ async function handleRoleChange(userId: number, newRole: string) {+ processingRoleChange = userId;+ try {+ await organizationState.updateMemberRole(organizationId, userId, newRole);+ toast.success('Successfully updated the Role', { position: 'top-center' });+ } catch (e) {+ toast.error(e instanceof Error ? e.message : 'Failed to update role');+ } finally {+ processingRoleChange = null;+ }+ }- async function handleRemoveMember() {- if (!memberToRemove) return;+ async function handleRemoveMember() {+ if (!memberToRemove) return;- try {- await organizationState.removeMember(organizationId, memberToRemove.id);- toast.success('Successfully removed the Member', { position: 'top-center' });- } catch (e) {- toast.error(e instanceof Error ? e.message : 'Failed to remove member');- } finally {- memberToRemove = null;- }- }+ removeLoading = true;+ removeError = '';+ try {+ await organizationState.removeMember(organizationId, memberToRemove.id);+ toast.success('Successfully removed the Member');+ removeDialogOpen = false;+ memberToRemove = null;+ } catch (e) {+ removeError = e instanceof Error ? e.message : 'Failed to remove member';+ } finally {+ removeLoading = false;+ }+ }- async function handleRevokeInvitation() {- if (!invitationToRevoke) return;+ async function handleRevokeInvitation() {+ if (!invitationToRevoke) return;- try {- await organizationState.revokeInvitation(organizationId, invitationToRevoke.id);- toast.success('Successfully revoked the Invitation', { position: 'top-center' });- } catch (e) {- toast.error(e instanceof Error ? e.message : 'Failed to revoke invitation');- } finally {- invitationToRevoke = null;- }- }+ revokeLoading = true;+ revokeError = '';+ try {+ await organizationState.revokeInvitation(organizationId, invitationToRevoke.id);+ toast.success('Successfully revoked the Invitation');+ revokeDialogOpen = false;+ invitationToRevoke = null;+ } catch (e) {+ revokeError = e instanceof Error ? e.message : 'Failed to revoke invitation';+ } finally {+ revokeLoading = false;+ }+ }- function canChangeRole(member: OrganizationMember): boolean {- if (member.role === 'owner') return false;- return true;- }+ function canChangeRole(member: OrganizationMember): boolean {+ if (member.role === 'owner') return false;+ return true;+ }- function canExpand(member: OrganizationMember): boolean {- return member.role === 'user' || member.role === 'readonly';- }+ function canExpand(member: OrganizationMember): boolean {+ return member.role === 'user' || member.role === 'readonly';+ }- async function toggleExpand(member: OrganizationMember) {- if (expandedMemberId === member.id) {- expandedMemberId = null;- return;- }- expandedMemberId = member.id;- loadingProjectRoles = true;- expandedProjectRoles = [];- try {- const response = await organizationState.getMemberProjectRoles(organizationId, member.id);- if (expandedMemberId !== member.id) return;- expandedProjectRoles = response.projectRoles;- loadingProjectRoles = false;- } catch (e) {- if (expandedMemberId !== member.id) return;- loadingProjectRoles = false;- toast.error(e instanceof Error ? e.message : 'Failed to load project roles', { position: 'top-center' });- expandedMemberId = null;- }- }+ async function toggleExpand(member: OrganizationMember) {+ if (expandedMemberId === member.id) {+ expandedMemberId = null;+ return;+ }+ expandedMemberId = member.id;+ loadingProjectRoles = true;+ expandedProjectRoles = [];+ try {+ const response = await organizationState.getMemberProjectRoles(organizationId, member.id);+ if (expandedMemberId !== member.id) return;+ expandedProjectRoles = response.projectRoles;+ loadingProjectRoles = false;+ } catch (e) {+ if (expandedMemberId !== member.id) return;+ loadingProjectRoles = false;+ toast.error(e instanceof Error ? e.message : 'Failed to load project roles');+ expandedMemberId = null;+ }+ }- function projectRoleLabel(member: OrganizationMember, role: string | null): string {- if (!role || role === 'default') {- return `Default (${member.role === 'readonly' ? 'Read Only' : 'User'})`;- }- return role === 'readonly' ? 'Read Only' : 'User';- }+ function projectRoleLabel(member: OrganizationMember, role: string | null): string {+ if (!role || role === 'default') {+ return `Default (${member.role === 'readonly' ? 'Read Only' : 'User'})`;+ }+ return role === 'readonly' ? 'Read Only' : 'User';+ }- async function handleProjectRoleChange(member: OrganizationMember, projectRole: MemberProjectRole, newRole: string) {- processingProjectRole = projectRole.projectId;- try {- await organizationState.updateMemberProjectRole(organizationId, member.id, projectRole.projectId, newRole);- projectRole.role = newRole === 'default' ? null : newRole;- toast.success('Successfully updated the Project Role', { position: 'top-center' });- } catch (e) {- toast.error(e instanceof Error ? e.message : 'Failed to update project role', { position: 'top-center' });- } finally {- processingProjectRole = null;- }- }+ async function handleProjectRoleChange(+ member: OrganizationMember,+ projectRole: MemberProjectRole,+ newRole: string+ ) {+ processingProjectRole = projectRole.projectId;+ try {+ await organizationState.updateMemberProjectRole(+ organizationId,+ member.id,+ projectRole.projectId,+ newRole+ );+ projectRole.role = newRole === 'default' ? null : newRole;+ toast.success('Successfully updated the Project Role', { position: 'top-center' });+ } catch (e) {+ toast.error(e instanceof Error ? e.message : 'Failed to update project role');+ } finally {+ processingProjectRole = null;+ }+ }- function canRemoveMember(member: OrganizationMember): boolean {- return member.role !== 'owner';- }+ function canRemoveMember(member: OrganizationMember): boolean {+ return member.role !== 'owner';+ }- function getRoleBadgeVariant(role: string): 'default' | 'secondary' | 'destructive' | 'outline' {- switch (role) {- case 'owner': return 'default';- case 'admin': return 'secondary';- case 'readonly': return 'outline';- default: return 'outline';- }- }+ function getRoleBadgeVariant(role: string): 'default' | 'secondary' | 'destructive' | 'outline' {+ switch (role) {+ case 'owner':+ return 'default';+ case 'admin':+ return 'secondary';+ case 'readonly':+ return 'outline';+ default:+ return 'outline';+ }+ }</script><div class="space-y-6">- <Card class="pb-0">- <CardHeader class="flex flex-row items-start justify-between gap-4 space-y-0 pb-4">- <div class="min-w-0 space-y-1.5">- <CardTitle>Team Members</CardTitle>- <CardDescription>Manage your organization's team members</CardDescription>- </div>- <Button variant="success" class="shrink-0" onclick={() => showInviteDialog = true} disabled={!canInvite}>- <Plus class="mr-2 h-4 w-4" />- New Invitation- </Button>- </CardHeader>- <CardContent class="p-0">- <Table.Root>- <Table.Header>- <Table.Row class="hover:bg-transparent">- <Table.Head>Name</Table.Head>- <Table.Head>Email</Table.Head>- <Table.Head>Role</Table.Head>- <Table.Head>Status</Table.Head>- <Table.Head class="w-[100px]"></Table.Head>- </Table.Row>- </Table.Header>- <Table.Body>- {#each members as member (member.id)}- <Table.Row>- <Table.Cell class="font-medium">- <div class="flex items-center gap-1">- {#if canExpand(member)}- <button- type="button"- class="rounded p-0.5 hover:bg-accent"- title="Per-project access"- onclick={() => toggleExpand(member)}- >- {#if expandedMemberId === member.id}- <ChevronDown class="h-4 w-4" />- {:else}- <ChevronRight class="h-4 w-4" />- {/if}- </button>- {:else}- <span class="inline-block w-5"></span>- {/if}- {member.name}- </div>- </Table.Cell>- <Table.Cell>{member.email}</Table.Cell>- <Table.Cell>- {#if canChangeRole(member) && member.role !== 'owner'}- <Select.Root- type="single"- value={member.role}- onValueChange={(val) => val && handleRoleChange(member.id, val)}- disabled={processingRoleChange === member.id || (!isOwner && member.role === 'admin')}- >- <Select.Trigger class="w-[130px]">- {roleOptions.find(r => r.value === member.role)?.label || member.role}- </Select.Trigger>- <Select.Content>- {#each roleOptions as role}- {#if isOwner || role.value !== 'admin'}- <Select.Item value={role.value}>- {role.label}- </Select.Item>- {/if}- {/each}- </Select.Content>- </Select.Root>- {:else}- <Badge variant={getRoleBadgeVariant(member.role)}>- {member.role === 'owner' ? 'Owner' :- member.role === 'admin' ? 'Admin' :- member.role === 'readonly' ? 'Read Only' : 'User'}- </Badge>- {/if}- </Table.Cell>- <Table.Cell>- <Badge variant="outline" class="bg-green-50 text-green-700 border-green-200 dark:bg-green-950 dark:text-green-400 dark:border-green-900">- Active- </Badge>- </Table.Cell>- <Table.Cell>- {#if canRemoveMember(member)}- <Button- variant="ghost"- size="icon"- onclick={() => memberToRemove = member}- >- <Trash2 class="h-4 w-4 text-destructive" />- </Button>- {/if}- </Table.Cell>- </Table.Row>- {#if expandedMemberId === member.id && canExpand(member)}- <Table.Row class="hover:bg-transparent bg-muted/30">- <Table.Cell colspan={5} class="py-2">- {#if loadingProjectRoles}- <div class="flex justify-center py-4">- <LoadingCircle />- </div>- {:else}- <div class="space-y-1 pl-10 pr-2">- {#each expandedProjectRoles as projectRole (projectRole.projectId)}- <div class="flex items-center justify-between gap-4 py-1">- <div class="flex items-center gap-2">- <FrameworkIcon framework={projectRole.framework as Framework} class="size-4" />- <span class="text-sm">{projectRole.name}</span>- </div>- <Select.Root- type="single"- value={projectRole.role ?? 'default'}- onValueChange={(val) => val && handleProjectRoleChange(member, projectRole, val)}- disabled={processingProjectRole === projectRole.projectId}- >- <Select.Trigger class="w-[200px]">- {projectRoleLabel(member, projectRole.role)}- </Select.Trigger>- <Select.Content>- <Select.Item value="default">Default ({member.role === 'readonly' ? 'Read Only' : 'User'})</Select.Item>- <Select.Item value="user">User</Select.Item>- <Select.Item value="readonly">Read Only</Select.Item>- </Select.Content>- </Select.Root>- </div>- {:else}- <div class="py-2 text-sm text-muted-foreground">No projects in this organization yet</div>- {/each}- </div>- {/if}- </Table.Cell>- </Table.Row>- {/if}- {/each}- </Table.Body>- </Table.Root>- </CardContent>- </Card>+ <Card class="overflow-hidden pb-0">+ <CardHeader+ class="flex flex-row flex-wrap items-start justify-between gap-4 space-y-0 gap-y-2 pb-4"+ >+ <div class="min-w-0 space-y-1.5">+ <CardTitle>Team Members</CardTitle>+ <CardDescription>Manage your organization's team members</CardDescription>+ </div>+ <Button+ variant="success"+ class="shrink-0"+ onclick={() => (showInviteDialog = true)}+ disabled={!canInvite}+ >+ <Plus class="mr-2 h-4 w-4" />+ New Invitation+ </Button>+ </CardHeader>+ <CardContent class="p-0">+ <TableContainer class="rounded-none border-0">+ <Table.Root>+ <Table.Header>+ <Table.Row class="hover:bg-transparent">+ <Table.Head>Name</Table.Head>+ <Table.Head>Email</Table.Head>+ <Table.Head>Role</Table.Head>+ <Table.Head>Status</Table.Head>+ <Table.Head class="w-[100px]"></Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each members as member (member.id)}+ <Table.Row>+ <Table.Cell class="font-medium">+ <div class="flex items-center gap-1">+ {#if canExpand(member)}+ <button+ type="button"+ class="rounded p-0.5 hover:bg-accent"+ title="Per-project access"+ onclick={() => toggleExpand(member)}+ >+ {#if expandedMemberId === member.id}+ <ChevronDown class="h-4 w-4" />+ {:else}+ <ChevronRight class="h-4 w-4" />+ {/if}+ </button>+ {:else}+ <span class="inline-block w-5"></span>+ {/if}+ {member.name}+ </div>+ </Table.Cell>+ <Table.Cell>{member.email}</Table.Cell>+ <Table.Cell>+ {#if canChangeRole(member) && member.role !== 'owner'}+ <Select.Root+ type="single"+ value={member.role}+ onValueChange={(val) => val && handleRoleChange(member.id, val)}+ disabled={processingRoleChange === member.id ||+ (!isOwner && member.role === 'admin')}+ >+ <Select.Trigger class="w-[130px]">+ {roleOptions.find((r) => r.value === member.role)?.label || member.role}+ </Select.Trigger>+ <Select.Content>+ {#each roleOptions as role, __index (__index)}+ {#if isOwner || role.value !== 'admin'}+ <Select.Item value={role.value}>+ {role.label}+ </Select.Item>+ {/if}+ {/each}+ </Select.Content>+ </Select.Root>+ {:else}+ <Badge variant={getRoleBadgeVariant(member.role)}>+ {member.role === 'owner'+ ? 'Owner'+ : member.role === 'admin'+ ? 'Admin'+ : member.role === 'readonly'+ ? 'Read Only'+ : 'User'}+ </Badge>+ {/if}+ </Table.Cell>+ <Table.Cell>+ <StatusPill tone="success" label="Active" />+ </Table.Cell>+ <Table.Cell>+ {#if canRemoveMember(member)}+ <Button+ variant="ghost"+ size="icon"+ onclick={() => {+ removeError = '';+ memberToRemove = member;+ removeDialogOpen = true;+ }}+ >+ <Trash2 class="h-4 w-4 text-destructive" />+ </Button>+ {/if}+ </Table.Cell>+ </Table.Row>+ {#if expandedMemberId === member.id && canExpand(member)}+ <Table.Row class="bg-muted/30 hover:bg-transparent">+ <Table.Cell colspan={5} class="py-2">+ {#if loadingProjectRoles}+ <div class="flex justify-center py-4">+ <LoadingCircle />+ </div>+ {:else}+ <div class="space-y-1 pr-2 pl-10">+ {#each expandedProjectRoles as projectRole (projectRole.projectId)}+ <div class="flex items-center justify-between gap-4 py-1">+ <div class="flex items-center gap-2">+ <FrameworkIcon+ framework={projectRole.framework as Framework}+ class="size-4"+ />+ <span class="text-sm">{projectRole.name}</span>+ </div>+ <Select.Root+ type="single"+ value={projectRole.role ?? 'default'}+ onValueChange={(val) =>+ val && handleProjectRoleChange(member, projectRole, val)}+ disabled={processingProjectRole === projectRole.projectId}+ >+ <Select.Trigger class="w-[200px]">+ {projectRoleLabel(member, projectRole.role)}+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="default"+ >Default ({member.role === 'readonly'+ ? 'Read Only'+ : 'User'})</Select.Item+ >+ <Select.Item value="user">User</Select.Item>+ <Select.Item value="readonly">Read Only</Select.Item>+ </Select.Content>+ </Select.Root>+ </div>+ {:else}+ <div class="py-2 text-sm text-muted-foreground">+ No projects in this organization yet+ </div>+ {/each}+ </div>+ {/if}+ </Table.Cell>+ </Table.Row>+ {/if}+ {:else}+ <TableEmptyState colspan={5} message="No members yet." />+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer>+ </CardContent>+ </Card>- {#if invitations.length > 0}- <Card class="pb-0">- <CardHeader>- <CardTitle>Pending Invitations</CardTitle>- <CardDescription>Invitations that have not yet been accepted</CardDescription>- </CardHeader>- <CardContent class="p-0">- <Table.Root>- <Table.Header>- <Table.Row class="hover:bg-transparent">- <Table.Head>Email</Table.Head>- <Table.Head>Role</Table.Head>- <Table.Head>Invited By</Table.Head>- <Table.Head>Status</Table.Head>- <Table.Head class="w-[100px]"></Table.Head>- </Table.Row>- </Table.Header>- <Table.Body>- {#each invitations as invitation}- <Table.Row>- <Table.Cell class="font-medium">{invitation.email}</Table.Cell>- <Table.Cell>- <Badge variant="outline">- {invitation.role === 'admin' ? 'Admin' :- invitation.role === 'readonly' ? 'Read Only' : 'User'}- </Badge>- </Table.Cell>- <Table.Cell>{invitation.inviterName}</Table.Cell>- <Table.Cell>- <Badge variant="outline" class="bg-yellow-50 text-yellow-700 border-yellow-200">- Invited- </Badge>- </Table.Cell>- <Table.Cell>- <Button- variant="ghost"- size="icon"- onclick={() => invitationToRevoke = invitation}- >- <Trash2 class="h-4 w-4 text-destructive" />- </Button>- </Table.Cell>- </Table.Row>- {/each}- </Table.Body>- </Table.Root>- </CardContent>- </Card>- {/if}+ <Card class="overflow-hidden pb-0">+ <CardHeader>+ <CardTitle>Pending Invitations</CardTitle>+ <CardDescription>Invitations that have not yet been accepted</CardDescription>+ </CardHeader>+ <CardContent class="p-0">+ <TableContainer class="rounded-none border-0">+ <Table.Root>+ <Table.Header>+ <Table.Row class="hover:bg-transparent">+ <Table.Head>Email</Table.Head>+ <Table.Head>Role</Table.Head>+ <Table.Head>Invited By</Table.Head>+ <Table.Head>Status</Table.Head>+ <Table.Head class="w-[100px]"></Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each invitations as invitation, __index (__index)}+ <Table.Row>+ <Table.Cell class="font-medium">{invitation.email}</Table.Cell>+ <Table.Cell>+ <Badge variant="outline">+ {invitation.role === 'admin'+ ? 'Admin'+ : invitation.role === 'readonly'+ ? 'Read Only'+ : 'User'}+ </Badge>+ </Table.Cell>+ <Table.Cell>{invitation.inviterName}</Table.Cell>+ <Table.Cell>+ <StatusPill tone="warning" label="Invited" />+ </Table.Cell>+ <Table.Cell>+ <Button+ variant="ghost"+ size="icon"+ onclick={() => {+ revokeError = '';+ invitationToRevoke = invitation;+ revokeDialogOpen = true;+ }}+ >+ <Trash2 class="h-4 w-4 text-destructive" />+ </Button>+ </Table.Cell>+ </Table.Row>+ {:else}+ <TableEmptyState colspan={5} message="No pending invitations." />+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer>+ </CardContent>+ </Card></div>-<InviteUserDialog- bind:open={showInviteDialog}- {organizationId}-/>+<InviteUserDialog bind:open={showInviteDialog} {organizationId} />-<AlertDialog.Root open={memberToRemove !== null} onOpenChange={(open) => { if (!open) memberToRemove = null; }}>- <AlertDialog.Content>- <AlertDialog.Header>- <AlertDialog.Title>Remove Team Member</AlertDialog.Title>- <AlertDialog.Description>- Are you sure you want to remove {memberToRemove?.name} from this organization?- They will lose access to all projects.- </AlertDialog.Description>- </AlertDialog.Header>- <AlertDialog.Footer>- <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>- <AlertDialog.Action variant="destructive" onclick={handleRemoveMember}>- <Trash2 class="mr-2 h-4 w-4" />- Remove Member- </AlertDialog.Action>- </AlertDialog.Footer>- </AlertDialog.Content>-</AlertDialog.Root>+<ConfirmDeleteDialog+ bind:open={removeDialogOpen}+ entity="Member"+ verb="Remove"+ title="Remove Team Member"+ description={`Are you sure you want to remove ${memberToRemove?.name} from this organization? They will lose access to all projects.`}+ error={removeError}+ loading={removeLoading}+ onConfirm={handleRemoveMember}+/>-<AlertDialog.Root open={invitationToRevoke !== null} onOpenChange={(open) => { if (!open) invitationToRevoke = null; }}>- <AlertDialog.Content>- <AlertDialog.Header>- <AlertDialog.Title>Revoke Invitation</AlertDialog.Title>- <AlertDialog.Description>- Are you sure you want to revoke the invitation for {invitationToRevoke?.email}?- </AlertDialog.Description>- </AlertDialog.Header>- <AlertDialog.Footer>- <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>- <AlertDialog.Action variant="destructive" onclick={handleRevokeInvitation}>- <Trash2 class="mr-2 h-4 w-4" />- Revoke Invitation- </AlertDialog.Action>- </AlertDialog.Footer>- </AlertDialog.Content>-</AlertDialog.Root>+<ConfirmDeleteDialog+ bind:open={revokeDialogOpen}+ entity="Invitation"+ verb="Revoke"+ description={`Are you sure you want to revoke the invitation for ${invitationToRevoke?.email}?`}+ error={revokeError}+ loading={revokeLoading}+ onConfirm={handleRevokeInvitation}+/>diff --git a/frontend/src/routes/status/[slug]/+page.svelte b/frontend/src/routes/status/[slug]/+page.svelteindex b1889664..01cec29c 100644--- a/frontend/src/routes/status/[slug]/+page.svelte+++ b/frontend/src/routes/status/[slug]/+page.svelte@@ -1,5 +1,6 @@<script lang="ts">import { onMount, onDestroy } from 'svelte';+ import { SvelteDate, SvelteMap } from 'svelte/reactivity';interface StatusDay {bucket: string;@@ -22,11 +23,25 @@incidents: StatusIncident[];}+ interface PastIncidentUpdate {+ status: string;+ message: string;+ createdAt: string;+ }++ interface PastIncident {+ title: string;+ startedAt: string;+ resolvedAt: string | null;+ updates: PastIncidentUpdate[];+ }+interface StatusView {name: string;description: string;hasLogo: boolean;checks: StatusCheck[];+ pastIncidents: PastIncident[];generatedAt: string;}@@ -75,14 +90,16 @@// A fixed 90-cell grid: days without data render as empty cells instead of// the bar silently shrinking.function buildCells(check: StatusCheck): DayCell[] {- const byDay = new Map<string, StatusDay>();+ const byDay = new SvelteMap<string, StatusDay>();for (const day of check.days) {byDay.set(dayKey(new Date(day.bucket)), day);}const cells: DayCell[] = [];const now = new Date();for (let i = DAYS - 1; i >= 0; i--) {- const date = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));+ const date = new SvelteDate(+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())+ );date.setUTCDate(date.getUTCDate() - i);const day = byDay.get(dayKey(date));const measured = day ? day.total - day.missed : 0;@@ -147,6 +164,63 @@return `${started} — resolved after ${minutes} min`;}+ const INCIDENTS_PER_PAGE = 5;+ let incidentPage = $state(1);++ const totalIncidentPages = $derived(+ Math.ceil((view?.pastIncidents.length ?? 0) / INCIDENTS_PER_PAGE)+ );++ const currentIncidentPage = $derived(+ Math.min(Math.max(incidentPage, 1), Math.max(totalIncidentPages, 1))+ );++ const pagedIncidents = $derived(+ (view?.pastIncidents ?? []).slice(+ (currentIncidentPage - 1) * INCIDENTS_PER_PAGE,+ currentIncidentPage * INCIDENTS_PER_PAGE+ )+ );++ const incidentGroups = $derived.by(() => {+ const groups: { label: string; incidents: PastIncident[] }[] = [];+ for (const incident of pagedIncidents) {+ const label = new Date(incident.startedAt).toLocaleDateString(undefined, {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ timeZone: 'UTC'+ });+ const group = groups[groups.length - 1];+ if (group && group.label === label) {+ group.incidents.push(incident);+ } else {+ groups.push({ label, incidents: [incident] });+ }+ }+ return groups;+ });++ function updateStatusLabel(status: string): string {+ return status.charAt(0).toUpperCase() + status.slice(1);+ }++ function formatUpdateTime(iso: string): string {+ const date = new Date(iso);+ const day = date.toLocaleDateString(undefined, {+ month: 'short',+ day: 'numeric',+ timeZone: 'UTC'+ });+ const time = date.toLocaleTimeString(undefined, {+ hour: '2-digit',+ minute: '2-digit',+ hour12: false,+ timeZone: 'UTC'+ });+ return `${day}, ${time} UTC`;+ }+// The status page is a standalone light design; anonymous visitors default// to the app's dark theme class, which would restyle headings underneath// the scoped styles. Force light here and restore on leave.@@ -209,7 +283,7 @@</div><div class="status-cards">- {#each view.checks as check}+ {#each view.checks as check, __index (__index)}{@const cells = buildCells(check)}{@const chip = checkStatusLabel(check)}<section class="status-card">@@ -228,7 +302,7 @@></div><div class="status-bars">- {#each cells as cell, i}+ {#each cells as cell, i (i)}<spanclass="status-bar {i < 30 ? 'band-oldest' : i < 60 ? 'band-mid' : ''}"style="background: {cellColors[cell.state]}"@@ -249,7 +323,7 @@90 days</summary><ul>- {#each check.incidents as incident}+ {#each check.incidents as incident, __index (__index)}<li>{formatIncident(incident)}</li>{/each}</ul>@@ -259,6 +333,58 @@{/each}</div>+ {#if view.pastIncidents.length > 0}+ <section class="past-incidents">+ <h2>Past Incidents</h2>+ {#each incidentGroups as group, __index (__index)}+ <div class="past-day">+ <h3>{group.label}</h3>+ {#each group.incidents as incident, __index (__index)}+ <article class="past-incident">+ <h4>{incident.title}</h4>+ {#if incident.updates.length > 0}+ {#each incident.updates as update, __index (__index)}+ <div class="past-update">+ <p>+ <b>{updateStatusLabel(update.status)}</b>{update.message+ ? ` - ${update.message}`+ : ''}+ </p>+ <time>{formatUpdateTime(update.createdAt)}</time>+ </div>+ {/each}+ {:else}+ <div class="past-update">+ <p><b>{incident.resolvedAt ? 'Resolved' : 'Investigating'}</b></p>+ <time>{formatUpdateTime(incident.resolvedAt ?? incident.startedAt)}</time>+ </div>+ {/if}+ </article>+ {/each}+ </div>+ {/each}+ {#if totalIncidentPages > 1}+ <nav class="past-pager" aria-label="Past incidents pages">+ <button+ type="button"+ onclick={() => (incidentPage = currentIncidentPage - 1)}+ disabled={currentIncidentPage <= 1}+ >+ Newer+ </button>+ <span>Page {currentIncidentPage} of {totalIncidentPages}</span>+ <button+ type="button"+ onclick={() => (incidentPage = currentIncidentPage + 1)}+ disabled={currentIncidentPage >= totalIncidentPages}+ >+ Older+ </button>+ </nav>+ {/if}+ </section>+ {/if}+<div class="status-legend"><span><i style="background: #22c55e"></i> Operational</span><span><i style="background: #f5a623"></i> Partial outage</span>@@ -518,6 +644,90 @@margin-top: 4px;}+ .past-incidents {+ margin-top: 44px;+ }++ .past-incidents h2 {+ font-size: 22px;+ font-weight: 700;+ letter-spacing: -0.02em;+ margin: 0;+ color: #101828;+ }++ .past-day {+ margin-top: 24px;+ }++ .past-day h3 {+ font-size: 15px;+ font-weight: 600;+ margin: 0;+ padding-bottom: 10px;+ border-bottom: 1px solid #e4e7ec;+ color: #101828;+ }++ .past-incident {+ margin-top: 16px;+ }++ .past-incident h4 {+ font-size: 16px;+ font-weight: 600;+ margin: 0 0 10px;+ color: #d97706;+ }++ .past-update {+ margin-top: 10px;+ }++ .past-update p {+ margin: 0;+ font-size: 14px;+ line-height: 1.5;+ color: #101828;+ }++ .past-update time {+ display: block;+ margin-top: 2px;+ font-size: 12px;+ color: #98a2b3;+ }++ .past-pager {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 14px;+ margin-top: 24px;+ font-size: 13px;+ color: #667085;+ }++ .past-pager button {+ background: #fff;+ border: 1px solid #d0d5dd;+ border-radius: 8px;+ padding: 6px 14px;+ font-size: 13px;+ font-weight: 600;+ color: #344054;+ cursor: pointer;+ }++ .past-pager button:hover:not(:disabled) {+ background: #f7f8fa;+ }++ .past-pager button:disabled {+ opacity: 0.45;+ cursor: default;+ }+.status-legend {display: flex;flex-wrap: wrap;diff --git a/frontend/src/routes/tasks/+page.svelte b/frontend/src/routes/tasks/+page.svelteindex 714fde1c..2a16841d 100644--- a/frontend/src/routes/tasks/+page.svelte+++ b/frontend/src/routes/tasks/+page.svelte@@ -1,365 +1,374 @@<script lang="ts">- import { onMount, onDestroy } from 'svelte';- import { api } from '$lib/api';- import { formatDuration, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';- import { getTimezone } from '$lib/state/timezone.svelte';- import * as Table from "$lib/components/ui/table";- import { LoadingCircle } from "$lib/components/ui/loading-circle";- import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";- import { TableEmptyState } from "$lib/components/ui/table-empty-state";- import { PaginationFooter } from "$lib/components/ui/pagination-footer";- import { TimeRangePicker } from "$lib/components/ui/time-range-picker";- import { SearchBar } from '$lib/components/ui/search-bar';- import { RootFilter } from '$lib/components/ui/root-filter';- import { NonRootChip } from '$lib/components/ui/non-root-chip';- import { CalendarDate } from "@internationalized/date";- import { browser } from '$app/environment';- import { projectsState } from '$lib/state/projects.svelte';- import { createRowClickHandler } from '$lib/utils/navigation';- import { resolve } from '$app/paths';- import PageHeader from '$lib/components/issues/page-header.svelte';- import {- presetMinutes,- getTimeRangeFromPreset,- dateToCalendarDate,- dateToTimeString,- parseTimeRangeFromUrl,- getResolvedTimeRange,- updateUrl- } from '$lib/utils/url-params';- import {- getSortState,- setSortState,- handleSortClick,- type SortDirection- } from '$lib/utils/sort-storage';-- const timezone = $derived(getTimezone());- const initialTimezone = getTimezone();-- type TaskStats = {- taskName: string;- count: number;- p50Duration: number;- p95Duration: number;- avgDuration: number;- lastSeen: string;- hasRoot: boolean;- hasNonRoot: boolean;- };-- type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'last_seen';-- let tasks = $state<TaskStats[]>([]);- let loading = $state(true);- let error = $state('');-- // Pagination State- let page = $state(1);- let pageSize = $state(50);- let total = $state(0);- let totalPages = $state(0);-- // Initialize from URL- const initialUrlParams = parseTimeRangeFromUrl(initialTimezone);- const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);-- function readSearchAndFilterFromUrl() {- if (!browser) return { search: '', rootFilter: 'all' };- const params = new URLSearchParams(window.location.search);- return {- search: params.get('search') || '',- rootFilter: params.get('rootFilter') || 'all'- };- }-- const initialSearchState = readSearchAndFilterFromUrl();- let searchQuery = $state(initialSearchState.search);- let rootFilter = $state(initialSearchState.rootFilter);-- // Date Range State- let selectedPreset = $state<string | null>(initialUrlParams.preset);- let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));- let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));- let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));- let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));-- // Update URL with current time range + search + rootFilter- function updateTimeRangeUrl(pushToHistory = true) {- const params: Record<string, string | undefined> = selectedPreset- ? { preset: selectedPreset }- : { from: getFromDateTimeUTC(), to: getToDateTimeUTC() };- if (searchQuery) params.search = searchQuery;- if (rootFilter && rootFilter !== 'all') params.rootFilter = rootFilter;- updateUrl(params, { pushToHistory });- }-- // Handle browser back/forward navigation- function handlePopState() {- const urlParams = parseTimeRangeFromUrl(timezone);- const range = getResolvedTimeRange(urlParams, timezone);-- selectedPreset = urlParams.preset;- fromDate = dateToCalendarDate(range.from, timezone);- fromTime = dateToTimeString(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- toTime = dateToTimeString(range.to, timezone);-- page = 1;- loadData(false);- }-- // Sorting - persisted to localStorage- const SORT_STORAGE_KEY = 'tasks';- const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'count', direction: 'desc' });- let orderBy = $state<SortField>(initialSort.field as SortField);- let sortDirection = $state<SortDirection>(initialSort.direction);-- // Combine date and time into UTC ISO datetime string- function getFromDateTimeUTC(): string {- const [hour, minute] = (fromTime || '00:00').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute }, timezone);- return toUTCISO(dt);- }-- function getToDateTimeUTC(): string {- const [hour, minute] = (toTime || '23:59').split(':').map(Number);- const dt = calendarDateTimeToLuxon({ year: toDate.year, month: toDate.month, day: toDate.day, hour, minute }, timezone).endOf('minute');- return toUTCISO(dt);- }-- function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) {- fromDate = from.date;- fromTime = from.time;- toDate = to.date;- toTime = to.time;- selectedPreset = preset;- page = 1;- loadData(true);- }-- // Format count with k/m suffixes- function formatCount(count: number): string {- if (count >= 1_000_000) {- return `${(count / 1_000_000).toFixed(1)}m`;- } else if (count >= 1_000) {- return `${(count / 1_000).toFixed(1)}k`;- }- return count.toLocaleString();- }-- async function loadData(pushToHistory = true) {- loading = true;- error = '';-- if (selectedPreset) {- const range = getTimeRangeFromPreset(selectedPreset, timezone);- fromDate = dateToCalendarDate(range.from, timezone);- toDate = dateToCalendarDate(range.to, timezone);- fromTime = dateToTimeString(range.from, timezone);- toTime = dateToTimeString(range.to, timezone);- }-- // Update URL- updateTimeRangeUrl(pushToHistory);-- try {- const requestBody = {- fromDate: getFromDateTimeUTC(),- toDate: getToDateTimeUTC(),- orderBy: orderBy,- sortDirection: sortDirection,- search: searchQuery,- rootFilter: rootFilter === 'all' ? '' : rootFilter,- pagination: {- page: page,- pageSize: pageSize- }- };-- const response = await api.post('/tasks/grouped', requestBody, { projectId: projectsState.currentProjectId ?? undefined });-- tasks = response.data || [];- total = response.pagination.total;- totalPages = response.pagination.totalPages;- } catch (e: any) {- console.error(e);- error = e.message || 'Failed to load data';- } finally {- loading = false;- }- }-- function handlePageChange(newPage: number) {- if (newPage >= 1 && newPage <= totalPages) {- page = newPage;- loadData(false); // Don't push to history for pagination- }- }-- function handlePageSizeChange(newPageSize: number) {- pageSize = newPageSize;- page = 1;- loadData(false); // Don't push to history for pagination- }-- function handleSort(field: SortField) {- const newSort = handleSortClick(field, orderBy, sortDirection);- orderBy = newSort.field as SortField;- sortDirection = newSort.direction;- setSortState(SORT_STORAGE_KEY, newSort);- page = 1;- loadData(false);- }-- function handleSearch() {- page = 1;- loadData(true);- }-- onMount(() => {- // Add popstate listener for back/forward navigation- window.addEventListener('popstate', handlePopState);-- // Initial load with replaceState (don't push to history)- loadData(false);- });-- onDestroy(() => {- if (typeof window !== 'undefined') {- window.removeEventListener('popstate', handlePopState);- }- });+ import { getErrorMessage } from '$lib/utils/errors';+ import { onMount, onDestroy } from 'svelte';+ import { api } from '$lib/api';+ import { formatDuration, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import * as Table from '$lib/components/ui/table';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { TimeRangePicker } from '$lib/components/ui/time-range-picker';+ import { SearchBar } from '$lib/components/ui/search-bar';+ import { RootFilter } from '$lib/components/ui/root-filter';+ import { NonRootChip } from '$lib/components/ui/non-root-chip';+ import { CalendarDate } from '@internationalized/date';+ import { browser } from '$app/environment';+ import { projectsState } from '$lib/state/projects.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { resolve } from '$app/paths';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import {+ getTimeRangeFromPreset,+ dateToCalendarDate,+ dateToTimeString,+ parseTimeRangeFromUrl,+ getResolvedTimeRange,+ updateUrl+ } from '$lib/utils/url-params';+ import {+ getSortState,+ setSortState,+ handleSortClick,+ type SortDirection+ } from '$lib/utils/sort-storage';++ const timezone = $derived(getTimezone());+ const initialTimezone = getTimezone();++ type TaskStats = {+ taskName: string;+ count: number;+ p50Duration: number;+ p95Duration: number;+ avgDuration: number;+ lastSeen: string;+ hasRoot: boolean;+ hasNonRoot: boolean;+ };++ type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'last_seen';++ let tasks = $state<TaskStats[]>([]);+ let loading = $state(true);+ let error = $state('');++ // Pagination State+ let page = $state(1);+ let pageSize = $state(50);+ let total = $state(0);+ let totalPages = $state(0);++ // Initialize from URL+ const initialUrlParams = parseTimeRangeFromUrl(initialTimezone);+ const initialRange = getResolvedTimeRange(initialUrlParams, initialTimezone);++ function readSearchAndFilterFromUrl() {+ if (!browser) return { search: '', rootFilter: 'all' };+ const params = new URLSearchParams(window.location.search);+ return {+ search: params.get('search') || '',+ rootFilter: params.get('rootFilter') || 'all'+ };+ }++ const initialSearchState = readSearchAndFilterFromUrl();+ let searchQuery = $state(initialSearchState.search);+ let rootFilter = $state(initialSearchState.rootFilter);++ // Date Range State+ let selectedPreset = $state<string | null>(initialUrlParams.preset);+ let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from, initialTimezone));+ let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to, initialTimezone));+ let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));+ let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));++ // Update URL with current time range + search + rootFilter+ function updateTimeRangeUrl(pushToHistory = true) {+ const params: Record<string, string | undefined> = selectedPreset+ ? { preset: selectedPreset }+ : { from: getFromDateTimeUTC(), to: getToDateTimeUTC() };+ if (searchQuery) params.search = searchQuery;+ if (rootFilter && rootFilter !== 'all') params.rootFilter = rootFilter;+ updateUrl(params, { pushToHistory });+ }++ // Handle browser back/forward navigation+ function handlePopState() {+ const urlParams = parseTimeRangeFromUrl(timezone);+ const range = getResolvedTimeRange(urlParams, timezone);++ selectedPreset = urlParams.preset;+ fromDate = dateToCalendarDate(range.from, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ toTime = dateToTimeString(range.to, timezone);++ page = 1;+ loadData(false);+ }++ // Sorting - persisted to localStorage+ const SORT_STORAGE_KEY = 'tasks';+ const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'count', direction: 'desc' });+ let orderBy = $state<SortField>(initialSort.field as SortField);+ let sortDirection = $state<SortDirection>(initialSort.direction);++ // Combine date and time into UTC ISO datetime string+ function getFromDateTimeUTC(): string {+ const [hour, minute] = (fromTime || '00:00').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute },+ timezone+ );+ return toUTCISO(dt);+ }++ function getToDateTimeUTC(): string {+ const [hour, minute] = (toTime || '23:59').split(':').map(Number);+ const dt = calendarDateTimeToLuxon(+ { year: toDate.year, month: toDate.month, day: toDate.day, hour, minute },+ timezone+ ).endOf('minute');+ return toUTCISO(dt);+ }++ function handleTimeRangeChange(+ from: { date: CalendarDate; time: string },+ to: { date: CalendarDate; time: string },+ preset: string | null+ ) {+ fromDate = from.date;+ fromTime = from.time;+ toDate = to.date;+ toTime = to.time;+ selectedPreset = preset;+ page = 1;+ loadData(true);+ }++ // Format count with k/m suffixes+ function formatCount(count: number): string {+ if (count >= 1_000_000) {+ return `${(count / 1_000_000).toFixed(1)}m`;+ } else if (count >= 1_000) {+ return `${(count / 1_000).toFixed(1)}k`;+ }+ return count.toLocaleString();+ }++ async function loadData(pushToHistory = true) {+ loading = true;+ error = '';++ if (selectedPreset) {+ const range = getTimeRangeFromPreset(selectedPreset, timezone);+ fromDate = dateToCalendarDate(range.from, timezone);+ toDate = dateToCalendarDate(range.to, timezone);+ fromTime = dateToTimeString(range.from, timezone);+ toTime = dateToTimeString(range.to, timezone);+ }++ // Update URL+ updateTimeRangeUrl(pushToHistory);++ try {+ const requestBody = {+ fromDate: getFromDateTimeUTC(),+ toDate: getToDateTimeUTC(),+ orderBy: orderBy,+ sortDirection: sortDirection,+ search: searchQuery,+ rootFilter: rootFilter === 'all' ? '' : rootFilter,+ pagination: {+ page: page,+ pageSize: pageSize+ }+ };++ const response = await api.post('/tasks/grouped', requestBody, {+ projectId: projectsState.currentProjectId ?? undefined+ });++ tasks = response.data || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e) {+ console.error(e);+ error = getErrorMessage(e) || 'Failed to load data';+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData(false); // Don't push to history for pagination+ }+ }++ function handlePageSizeChange(newPageSize: number) {+ pageSize = newPageSize;+ page = 1;+ loadData(false); // Don't push to history for pagination+ }++ function handleSort(field: SortField) {+ const newSort = handleSortClick(field, orderBy, sortDirection);+ orderBy = newSort.field as SortField;+ sortDirection = newSort.direction;+ setSortState(SORT_STORAGE_KEY, newSort);+ page = 1;+ loadData(false);+ }++ function handleSearch() {+ page = 1;+ loadData(true);+ }++ onMount(() => {+ // Add popstate listener for back/forward navigation+ window.addEventListener('popstate', handlePopState);++ // Initial load with replaceState (don't push to history)+ loadData(false);+ });++ onDestroy(() => {+ if (typeof window !== 'undefined') {+ window.removeEventListener('popstate', handlePopState);+ }+ });</script><div class="space-y-4">- <!-- Header with Title and Time Range Filter -->- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">-- <PageHeader title="Tasks" />-- <div class="flex flex-col">- <TimeRangePicker- bind:fromDate- bind:toDate- bind:fromTime- bind:toTime- bind:preset={selectedPreset}- onApply={handleTimeRangeChange}- />- </div>- </div>-- <!-- Search -->- <SearchBar- placeholder="Search tasks..."- bind:value={searchQuery}- onSearch={handleSearch}- disabled={loading}- >- {#snippet children()}- <RootFilter bind:value={rootFilter} />- {/snippet}- </SearchBar>-- <!-- Tasks Table -->- <div class="rounded-md border overflow-hidden">- <Table.Root>- {#if loading}- <Table.Body>- <Table.Row>- <Table.Cell colspan={4} class="h-48">- <div class="flex justify-center items-center h-full">- <LoadingCircle size="xlg" />- </div>- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if error}- <Table.Body>- <Table.Row>- <Table.Cell colspan={4} class="h-24 text-center text-red-500">- {error}- </Table.Cell>- </Table.Row>- </Table.Body>- {:else if tasks.length === 0}- <Table.Body>- <TableEmptyState colspan={4} message="No task data received yet" />- </Table.Body>- {:else}- <Table.Header>- <Table.Row>- <TracewayTableHeader- label="Task"- tooltip="The background job or task name"- />- <TracewayTableHeader- label="Runs"- tooltip="Total number of task executions"- sortField="count"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Typical"- tooltip="Median duration (P50)"- sortField="p50_duration"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- <TracewayTableHeader- label="Slow"- tooltip="95th percentile - slowest 5% of executions"- sortField="p95_duration"- currentSortField={orderBy}- {sortDirection}- onSort={(field) => handleSort(field as SortField)}- class="w-[100px]"- />- </Table.Row>- </Table.Header>- <Table.Body>- {#each tasks as task}- <Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={createRowClickHandler(resolve(`/tasks/${encodeURIComponent(task.taskName)}`), 'preset', 'from', 'to')}- >- <Table.Cell class="font-mono text-sm">- {task.taskName}- {#if task.hasNonRoot}- <NonRootChip mixed={task.hasRoot && task.hasNonRoot} />- {/if}- </Table.Cell>- <Table.Cell class="tabular-nums">- {formatCount(task.count)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {formatDuration(task.p50Duration)}- </Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- {formatDuration(task.p95Duration)}- </Table.Cell>- </Table.Row>- {/each}- </Table.Body>- {/if}- </Table.Root>- </div>-- <!-- Pagination Footer -->- <PaginationFooter- currentPage={page}- {totalPages}- {pageSize}- totalItems={total}- onPageChange={handlePageChange}- onPageSizeChange={handlePageSizeChange}- {loading}- itemLabel="task"- />+ <PageHeader title="Tasks">+ {#snippet actions()}+ <TimeRangePicker+ bind:fromDate+ bind:toDate+ bind:fromTime+ bind:toTime+ bind:preset={selectedPreset}+ onApply={handleTimeRangeChange}+ />+ {/snippet}+ </PageHeader>++ <!-- Search -->+ <SearchBar+ placeholder="Search tasks..."+ bind:value={searchQuery}+ onSearch={handleSearch}+ disabled={loading}+ >+ <RootFilter bind:value={rootFilter} />+ </SearchBar>++ <!-- Tasks Table -->+ <TableContainer minWidth="640px">+ <Table.Root>+ {#if loading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={4} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if error}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={4} class="h-24 text-center text-red-500">+ {error}+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if tasks.length === 0}+ <Table.Body>+ <TableEmptyState colspan={4} message="No task data received yet" />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader label="Task" tooltip="The background job or task name" />+ <TracewayTableHeader+ label="Runs"+ tooltip="Total number of task executions"+ sortField="count"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Typical"+ tooltip="Median duration (P50)"+ sortField="p50_duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Slow"+ tooltip="95th percentile - slowest 5% of executions"+ sortField="p95_duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each tasks as task, __index (__index)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ resolve(`/tasks/${encodeURIComponent(task.taskName)}`),+ 'preset',+ 'from',+ 'to'+ )}+ >+ <Table.Cell class="font-mono text-sm">+ {task.taskName}+ {#if task.hasNonRoot}+ <NonRootChip mixed={task.hasRoot && task.hasNonRoot} />+ {/if}+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ {formatCount(task.count)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatDuration(task.p50Duration)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatDuration(task.p95Duration)}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </TableContainer>++ <!-- Pagination Footer -->+ <PaginationFooter+ currentPage={page}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={handlePageChange}+ onPageSizeChange={handlePageSizeChange}+ {loading}+ itemLabel="task"+ /></div>diff --git a/frontend/src/routes/tasks/[task]/+page.svelte b/frontend/src/routes/tasks/[task]/+page.svelteindex e2368245..4d9c61f9 100644--- a/frontend/src/routes/tasks/[task]/+page.svelte+++ b/frontend/src/routes/tasks/[task]/+page.svelte@@ -1,4 +1,5 @@<script lang="ts">+ import { getErrorMessage, getErrorStatus } from '$lib/utils/errors';import { onMount } from 'svelte';import { api } from '$lib/api';import {@@ -22,7 +23,10 @@import { createRowClickHandler } from '$lib/utils/navigation';import { createSmartBackHandler } from '$lib/utils/back-navigation';import PaginationFooter from '$lib/components/ui/pagination-footer/pagination-footer.svelte';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import StatRow from '$lib/components/traceway/stat-row.svelte';+ import StatTile from '$lib/components/traceway/stat-tile.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';import { resolve } from '$app/paths';import {presetMinutes,@@ -187,13 +191,13 @@stats = response.stats || null;total = response.pagination.total;totalPages = response.pagination.totalPages;- } catch (e: any) {+ } catch (e) {console.error(e);- errorStatus = e.status || 0;- if (e.status === 404) {+ errorStatus = getErrorStatus(e) || 0;+ if (getErrorStatus(e) === 404) {notFound = true;} else {- error = e.message || 'Failed to load data';+ error = getErrorMessage(e) || 'Failed to load data';}} finally {loading = false;@@ -248,15 +252,12 @@onRetry={() => loadData(false)}/>{:else}- <!-- Header with Title and Time Range Filter -->- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">- <PageHeader- title={decodeURIComponent(data.task)}- subtitle="Task instances"- onBack={createSmartBackHandler({ fallbackPath: resolve('/tasks') })}- />-- <div class="flex flex-col">+ <PageHeader+ title={decodeURIComponent(data.task)}+ subtitle="Task instances"+ onBack={createSmartBackHandler({ fallbackPath: resolve('/tasks') })}+ >+ {#snippet actions()}<TimeRangePickerbind:fromDatebind:toDate@@ -265,35 +266,18 @@bind:preset={selectedPreset}onApply={handleTimeRangeChange}/>- </div>- </div>+ {/snippet}+ </PageHeader><!-- Task Stats -->{#if stats}- <div class="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-5">- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.avgDuration)}</p>- <p class="text-xs text-muted-foreground">Average duration</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">- {formatDurationMs(stats.medianDuration)}- </p>- <p class="text-xs text-muted-foreground">Median duration</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p95Duration)}</p>- <p class="text-xs text-muted-foreground">95th percentile</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p99Duration)}</p>- <p class="text-xs text-muted-foreground">99th percentile</p>- </div>- <div class="space-y-1">- <p class="text-2xl font-semibold tracking-tight">{stats.throughput.toFixed(0)} rpm</p>- <p class="text-xs text-muted-foreground">Average throughput</p>- </div>- </div>+ <StatRow columns={5}>+ <StatTile label="Average duration" value={formatDurationMs(stats.avgDuration)} />+ <StatTile label="Median duration" value={formatDurationMs(stats.medianDuration)} />+ <StatTile label="95th percentile" value={formatDurationMs(stats.p95Duration)} />+ <StatTile label="99th percentile" value={formatDurationMs(stats.p99Duration)} />+ <StatTile label="Average throughput" value={`${stats.throughput.toFixed(0)} rpm`} />+ </StatRow>{:else if loading}<div class="flex items-center justify-center py-8"><LoadingCircle size="lg" />@@ -301,7 +285,7 @@{/if}<!-- Tasks Table -->- <div class="overflow-hidden rounded-md border">+ <TableContainer minWidth="860px"><Table.Root>{#if loading || tasks.length > 0}<Table.Header>@@ -333,17 +317,17 @@{#if loading}<Table.Row><Table.Cell colspan={6} class="h-48">- <div class="flex items-center justify-center">- <LoadingCircle size="lg" />+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" /></div></Table.Cell></Table.Row>{:else if tasks.length === 0}<TableEmptyState colspan={6} message="No tasks found in this time range." />{:else}- {#each tasks as task}+ {#each tasks as task, __index (__index)}<Table.Row- class="cursor-pointer hover:bg-muted/50"+ class="cursor-pointer"onclick={createRowClickHandler(`/tasks/${encodeURIComponent(decodeURIComponent(data.task))}/${task.id}?t=${encodeURIComponent(task.recordedAt)}`,'preset',@@ -374,7 +358,7 @@{/if}</Table.Body></Table.Root>- </div>+ </TableContainer><!-- Pagination Footer --><PaginationFooterdiff --git a/frontend/src/routes/tasks/[task]/[taskId]/+page.svelte b/frontend/src/routes/tasks/[task]/[taskId]/+page.svelteindex 741a3fa1..f526b4a4 100644--- a/frontend/src/routes/tasks/[task]/[taskId]/+page.svelte+++ b/frontend/src/routes/tasks/[task]/[taskId]/+page.svelte@@ -10,17 +10,20 @@import { LoadingCircle } from '$lib/components/ui/loading-circle';import { ErrorDisplay } from '$lib/components/ui/error-display';import { projectsState } from '$lib/state/projects.svelte';- import { ArrowRight, TriangleAlert, ClipboardList } from 'lucide-svelte';+ import { ArrowRight, TriangleAlert, ClipboardList } from '@lucide/svelte';import { LabelValue } from '$lib/components/ui/label-value';import { AttributesGrid } from '$lib/components/ui/attributes-grid/index.js';import SpanWaterfall from '$lib/components/spans/span-waterfall.svelte';import SpanEmptyState from '$lib/components/spans/span-empty-state.svelte';- import PageHeader from '$lib/components/issues/page-header.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';import { createSmartBackHandler } from '$lib/utils/back-navigation';import { resolve } from '$app/paths';import DistributedTraceCard from '$lib/components/distributed-trace/distributed-trace-card.svelte';import TraceLogsPanel from '$lib/components/trace-logs/trace-logs-panel.svelte';import { traceIdUuidToHex } from '$lib/utils/span-id';+ import type { Span } from '$lib/types/spans';type TaskDetailResponse = {task: {@@ -46,7 +49,7 @@recordedAt: string;attributes?: Record<string, string>;}[];- spans: any[];+ spans: Span[];hasSpans: boolean;};@@ -177,7 +180,7 @@<Buttonvariant="outline"size="sm"- onclick={() => goto(`/issues/${response!.exception!.exceptionHash}`)}+ onclick={() => goto(resolve(`/issues/${response!.exception!.exceptionHash}`))}>View Full Exception<ArrowRight class="ml-2 h-4 w-4" />@@ -200,44 +203,49 @@</Card.Description></Card.Header><Card.Content class="px-0 pb-0">- <Table.Root>- <Table.Header>- <Table.Row>- <Table.Head class="pl-6">Message</Table.Head>- <Table.Head class="w-[180px]">Recorded At</Table.Head>- <Table.Head class="w-[100px] pr-6">Attributes</Table.Head>- </Table.Row>- </Table.Header>- <Table.Body>- {#each response.messages as message}- <Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={() => goto(`/issues/${message.exceptionHash}/${message.id}`)}- >- <Table.Cell class="pl-6">- <div class="max-w-md truncate font-mono text-sm">- {message.stackTrace.split('\n')[0]}- </div>- </Table.Cell>- <Table.Cell class="font-mono text-sm text-muted-foreground">- {formatDateTime(message.recordedAt, { timezone })}- </Table.Cell>- <Table.Cell class="pr-6">- {#if message.attributes && Object.keys(message.attributes).length > 0}- <span class="text-xs text-muted-foreground">- {Object.keys(message.attributes).length} key{Object.keys(message.attributes)- .length === 1- ? ''- : 's'}- </span>- {:else}- <span class="text-xs text-muted-foreground">-</span>- {/if}- </Table.Cell>+ <TableContainer class="rounded-none border-0">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <Table.Head class="pl-6">Message</Table.Head>+ <Table.Head class="w-[180px]">Recorded At</Table.Head>+ <Table.Head class="w-[100px] pr-6">Attributes</Table.Head></Table.Row>- {/each}- </Table.Body>- </Table.Root>+ </Table.Header>+ <Table.Body>+ {#each response.messages as message, __index (__index)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ `/issues/${message.exceptionHash}/${message.id}`+ )}+ >+ <Table.Cell class="pl-6">+ <div class="max-w-md truncate font-mono text-sm">+ {message.stackTrace.split('\n')[0]}+ </div>+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {formatDateTime(message.recordedAt, { timezone })}+ </Table.Cell>+ <Table.Cell class="pr-6">+ {#if message.attributes && Object.keys(message.attributes).length > 0}+ <span class="text-xs text-muted-foreground">+ {Object.keys(message.attributes).length} key{Object.keys(+ message.attributes+ ).length === 1+ ? ''+ : 's'}+ </span>+ {:else}+ <span class="text-xs text-muted-foreground">-</span>+ {/if}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer></Card.Content></Card.Root>{/if}@@ -273,10 +281,6 @@traceId={traceIdUuidToHex(response.task.id)}distributedTraceId={response.task.distributedTraceId ?? null}spans={response.spans ?? []}- rootSpan={{- id: response.task.spanId ?? response.task.id,- name: response.task.taskName- }}traceRecordedAt={response.task.recordedAt}/>diff --git a/frontend/src/test/mocks/app-paths.ts b/frontend/src/test/mocks/app-paths.tsnew file mode 100644index 00000000..57529a83--- /dev/null+++ b/frontend/src/test/mocks/app-paths.ts@@ -0,0 +1,6 @@+export const base = '';+export const assets = '';++export function resolve(path: string): string {+ return path;+}diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 95cd27c2..f716d9ab 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -63,10 +63,13 @@ export default defineConfig(({ mode }) => {sourcemap: 'hidden'},resolve: {- dedupe: ['d3-scale', 'd3-array', 'lucide-svelte', 'svelte', 'svelte-sonner']+ dedupe: ['d3-scale', 'd3-array', '@lucide/svelte', 'svelte', 'svelte-sonner']},optimizeDeps: {- include: ['d3-scale', 'd3-array', 'lucide-svelte', 'svelte-sonner']+ // @milkdown/crepe is dynamically imported; pre-bundle it so the first+ // editor open doesn't trigger a mid-session re-optimization page reload+ // that strands the editor on its loading state.+ include: ['d3-scale', 'd3-array', '@lucide/svelte', 'svelte-sonner', '@milkdown/crepe']},server: {proxy: {diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.tsindex 39081f13..850d43fb 100644--- a/frontend/vitest.config.ts+++ b/frontend/vitest.config.ts@@ -7,7 +7,8 @@ export default defineConfig({resolve: {conditions: ['browser'],alias: {- $lib: path.resolve('./src/lib')+ $lib: path.resolve('./src/lib'),+ '$app/paths': path.resolve('./src/test/mocks/app-paths.ts')}},test: {diff --git a/website/app/product/monitors/page.tsx b/website/app/product/monitors/page.tsxindex 222efd8f..92e6fd26 100644--- a/website/app/product/monitors/page.tsx+++ b/website/app/product/monitors/page.tsx@@ -12,7 +12,7 @@ import { AuroraBackground } from "@/components/aurora-background";export const metadata: Metadata = {title: "Monitors · Traceway",description:- "Synthetic uptime monitoring built into your observability stack. HTTP, TCP, and real-browser Playwright checks, flap damping, failure screenshots, public status pages, and paging that resolves itself on recovery.",+ "Synthetic uptime monitoring and full incident management in your observability stack. HTTP, TCP, and real-browser Playwright checks, public status pages with incident timelines, internal post-mortems, and paging that resolves itself on recovery.",};export default function MonitorsPage() {@@ -23,7 +23,7 @@ export default function MonitorsPage() {<div className="wrap relative z-10"><Chip variant="ok"><Radar className="h-3 w-3 inline mr-1" />- Uptime Monitors & Status Pages+ Uptime Monitors, Status Pages & Incident Management</Chip><h1 className="mt-6">Telemetry sees inside. <em>Monitors check from outside.</em>@@ -144,6 +144,51 @@ export default function MonitorsPage() {/></section>+ <section className="wrap">+ <FeatureRow+ eyebrow="Incident management"+ title={+ <>+ Every outage gets <em>a timeline</em>+ </>+ }+ description="Incidents open and resolve themselves from monitor state changes, with an Investigating entry when they open and a Resolved entry when the service comes back. You own the public story: rename an incident to something users understand and post statuspage-style updates while you work. Outages your monitors missed can be recorded by hand, backdated if needed, without ever touching the uptime numbers."+ bullets={[+ "Automatic open and resolve from monitor state transitions",+ "Public titles and Investigating / Identified / Monitoring / Resolved updates",+ "Record incidents by hand for outages the probes missed",+ "Probe errors stay internal, the public page only sees your words",+ ]}+ image={{+ src: "/images/monitors-incidents.png",+ alt: "Managing a status page's incidents in Traceway: renaming, posting public timeline updates, and attaching a post-mortem",+ }}+ />+ </section>++ <section className="wrap">+ <FeatureRow+ reverse+ eyebrow="Post-mortems"+ title={+ <>+ The write-up lives <em>next to the incident</em>+ </>+ }+ description="After the fire, write the post-mortem in the same tool: a WYSIWYG markdown editor with a raw-markdown toggle, tags, and a one-click link to the incident it covers. Post-mortems are internal, searchable across titles, content, and tags, and every edit is recorded in an activity log, so the next time something similar breaks, how it was fixed last time is one search away."+ bullets={[+ "WYSIWYG markdown editor, or flip to raw markdown and paste",+ "Tag and link each write-up to its incident, one per incident",+ "Search titles, content, and tags; filter by tag",+ "Full activity log: who created it, who edited what, and when",+ ]}+ image={{+ src: "/images/monitors-post-mortem.png",+ alt: "Writing an internal post-mortem in Traceway with tags, a linked incident, and an activity log",+ }}+ />+ </section>+<section className="wrap"><FeatureRoweyebrow="Wired into alerting"@@ -173,7 +218,7 @@ export default function MonitorsPage() {Stop paying for <em>a separate uptime tool</em></>}- description="Monitors, status pages, alerting, and on-call in the same tool that holds your traces, logs, and errors. Open source if you self-host."+ description="Monitors, status pages, incident timelines, post-mortems, alerting, and on-call in the same tool that holds your traces, logs, and errors. Open source if you self-host."primary={{label: "Read the Monitors docs",href: "https://docs.tracewayapp.com/learn/monitors",@@ -216,6 +261,10 @@ export default function MonitorsPage() {</>),},+ {+ q: "Does Traceway cover incident management, or just detection?",+ a: "The whole lifecycle. Monitors open and resolve incidents automatically, you give them public titles and post timeline updates (Investigating, Identified, Monitoring, Resolved) while you work, and outages the probes missed can be recorded by hand. Afterwards you write the internal post-mortem in a WYSIWYG markdown editor, tag it, link it to the incident, and find it again later by searching titles, content, and tags. Statuspage, incident tracker, and post-mortem wiki, without three more subscriptions.",+ },{q: "What stops one slow probe from marking my site down?",a: "The failure threshold. A monitor only transitions to down after the configured number of consecutive failures, and only that transition alerts. Recovery works the same way in reverse: the first successful probe flips it back and sends the all-clear.",diff --git a/website/components/site-header.tsx b/website/components/site-header.tsxindex 7abb484d..666bf09b 100644--- a/website/components/site-header.tsx+++ b/website/components/site-header.tsx@@ -67,7 +67,7 @@ const PILLARS: NavItem[] = [},{title: "Monitors",- description: "HTTP, TCP, and browser uptime checks with status pages.",+ description: "Uptime checks, status pages, incidents, and post-mortems.",href: "/product/monitors",icon: Radar,},diff --git a/website/public/images/monitors-incidents.png b/website/public/images/monitors-incidents.pngnew file mode 100644index 00000000..869614c3Binary files /dev/null and b/website/public/images/monitors-incidents.png differdiff --git a/website/public/images/monitors-post-mortem.png b/website/public/images/monitors-post-mortem.pngnew file mode 100644index 00000000..cf301a22Binary files /dev/null and b/website/public/images/monitors-post-mortem.png differ