Expand tracker analytics and dashboard UX
Test and publish / publish (push) Successful in 4m27s
Test and publish / test (push) Successful in 9m45s

This commit is contained in:
2026-10-23 20:16:50 +01:00
parent e0f8399ff7
commit 667091efb0
17 changed files with 1140 additions and 81 deletions
+16 -5
View File
@@ -9,7 +9,7 @@ A self-hosted service that records where your time goes: desktop apps, browser t
tracker (Go, container) ── PostgreSQL
```
Every source is stored as an interval in a single `activities` table, with columns `source, kind, label, started_at, ended_at, attrs`. The `samples` table for point metrics (step counts and so on) has no collector at the moment. Collectors generate an `id` for each event, so re-uploading a batch never creates duplicates.
Every source is stored as an interval in a single `activities` table, with columns `source, kind, label, started_at, ended_at, attrs`. The `samples` table stores point metrics such as step counts. Collectors generate an `id` for each event, so re-uploading a batch never creates duplicates.
## Status
@@ -19,7 +19,9 @@ Every source is stored as an interval in a single `activities` table, with colum
| iPhone location (Shortcuts → `/location/{arrive,leave}`) | ✅ built; configure the automations |
| Browser (Violentmonkey userscript, `/tracker.user.js`) | ✅ built |
| Webcam presence (`/presence/events`) | endpoint ready, agent not yet written |
| AI analysis (`reports` table) | planned |
| Samples API and range summaries | ✅ available |
| AI analysis (`reports` table) | ✅ storage API; job remains external |
| ntfy goal notification configuration | ✅ configuration/status API |
## Running the server
@@ -98,11 +100,20 @@ Collectors never use the site login. Each one sends its own bearer key.
| POST | `/api/v1/browser/events` | key | `tab_focus`, `idle` |
| POST | `/api/v1/presence/events` | key | `at_desk`, `in_bed`, `away` |
| POST | `/api/v1/manual/events` | key | any |
| POST | `/api/v1/samples` | key | point metrics in `{"samples":[{"id","source","metric","ts","value","unit"}]}` |
| GET | `/api/v1/samples?from=&to=&source=&metric=&limit=&cursor=` | key or admin | point samples, defaults to the last 24h |
| POST | `/api/v1/location/{arrive,leave}[/{place}]` | key | place from the path, `?place=`, or optional `{"place","at"}`; defaults to `home` and now. Builds `place` intervals (see [iPhone location](#iphone-location)) |
| GET | `/api/v1/activities?from=&to=&source=&kind=&limit=` | key or admin | RFC3339 times; defaults to the last 24h |
| GET | `/api/v1/activities?from=&to=&source=&kind=&limit=&cursor=` | key or admin | RFC3339 times; defaults to the last 24h; returns clipped intervals and `next_cursor` when more rows exist |
| GET | `/api/v1/activities/export?from=&to=&source=&kind=&format=csv` | admin | Downloads the filtered activity data as CSV, or JSON with `format=json` |
| GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | key or admin | totals per label and kind, plus goal results |
| GET | `/api/v1/summary/range?from=&to=` | key or admin | interval totals and metric min/max/average/count for a range |
| GET, POST, PUT, DELETE | `/api/v1/goals[/{id}]` | admin | List, create, update, or delete daily goals |
| GET, POST | `/api/v1/devices` | admin | list devices; create one with `{"name","kind"}`, which returns its key once |
| DELETE | `/api/v1/devices/{name}` | admin | revoke a device's key |
| GET, POST | `/api/v1/reports` | admin | list or store nightly/weekly report output (`period_start`, `period_end`, `model`, `prompt_hash`, `body`) |
| GET | `/api/v1/notifications/status` | admin | ntfy configuration and whether nudges are configured |
| PUT | `/api/v1/notifications/config` | admin | set ntfy server/topic, enabled flag, and optional retention days |
| POST | `/api/v1/privacy/purge?before=RFC3339` | admin | permanently delete old activities, samples, and reports |
| GET | `/`, `/setup` | admin | the dashboard app |
| GET | `/tracker.user.js`, `/assets/*`, `/healthz`, `/readyz` | none | the userscript and the app's scripts hold no secrets |
@@ -203,5 +214,5 @@ Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,a
## Roadmap
1. Webcam presence agent. Detection will run on the device and only intervals will be uploaded; frames never leave the machine.
2. Nudges: push notifications through ntfy when a goal is at risk during the day.
3. AI analysis: a nightly or weekly job will send the daily summaries (not raw rows) to the Claude API and store the result in `reports`.
2. Nudges: send goal-risk notifications through the configured ntfy topic.
3. AI analysis: a nightly or weekly job will send the daily summaries (not raw rows) to the Claude API and store the result through `POST /api/v1/reports`.
+377 -1
View File
@@ -3,10 +3,13 @@ package api
import (
"context"
"encoding/base64"
"encoding/csv"
"encoding/json"
"errors"
"io"
"log/slog"
"math"
"net/http"
"strconv"
"strings"
@@ -53,13 +56,27 @@ func New(s *store.Store, admin auth.Checker, loc *time.Location, log *slog.Logge
api.Handle("POST /browser/events", srv.device(srv.ingestEvents(ingest.Browser)))
api.Handle("POST /presence/events", srv.device(srv.ingestEvents(ingest.Presence)))
api.Handle("POST /manual/events", srv.device(srv.ingestEvents(ingest.Manual)))
api.Handle("POST /samples", srv.device(http.HandlerFunc(srv.ingestSamples)))
api.Handle("POST /samples/events", srv.device(http.HandlerFunc(srv.ingestSamples)))
api.Handle("GET /samples", srv.deviceOrAdmin(http.HandlerFunc(srv.samples)))
api.Handle("POST /location/{event}", srv.device(http.HandlerFunc(srv.ingestLocation)))
api.Handle("POST /location/{event}/{place}", srv.device(http.HandlerFunc(srv.ingestLocation)))
api.Handle("GET /activities", srv.deviceOrAdmin(http.HandlerFunc(srv.activities)))
api.Handle("GET /activities/export", srv.adminAPI(http.HandlerFunc(srv.exportActivities)))
api.Handle("GET /summary/daily", srv.deviceOrAdmin(http.HandlerFunc(srv.dailySummary)))
api.Handle("GET /summary/range", srv.deviceOrAdmin(http.HandlerFunc(srv.rangeSummary)))
api.Handle("GET /goals", srv.adminAPI(http.HandlerFunc(srv.listGoals)))
api.Handle("POST /goals", srv.adminAPI(http.HandlerFunc(srv.createGoal)))
api.Handle("PUT /goals/{id}", srv.adminAPI(http.HandlerFunc(srv.updateGoal)))
api.Handle("DELETE /goals/{id}", srv.adminAPI(http.HandlerFunc(srv.deleteGoal)))
api.Handle("GET /devices", srv.adminAPI(http.HandlerFunc(srv.listDevices)))
api.Handle("POST /devices", srv.adminAPI(http.HandlerFunc(srv.createDevice)))
api.Handle("DELETE /devices/{name}", srv.adminAPI(http.HandlerFunc(srv.revokeDevice)))
api.Handle("GET /reports", srv.adminAPI(http.HandlerFunc(srv.listReports)))
api.Handle("POST /reports", srv.adminAPI(http.HandlerFunc(srv.createReport)))
api.Handle("GET /notifications/status", srv.adminAPI(http.HandlerFunc(srv.notificationStatus)))
api.Handle("PUT /notifications/config", srv.adminAPI(http.HandlerFunc(srv.updateNotificationConfig)))
api.Handle("POST /privacy/purge", srv.adminAPI(http.HandlerFunc(srv.purgePrivacyData)))
mux.Handle("/api/v1/", http.StripPrefix("/api/v1", api))
return srv.logRequests(mux)
@@ -193,6 +210,93 @@ func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc {
}
}
type sampleRequest struct {
ID string `json:"id"`
Source string `json:"source"`
Metric string `json:"metric"`
TS time.Time `json:"ts"`
Value float64 `json:"value"`
Unit string `json:"unit"`
}
func (s *Server) ingestSamples(w http.ResponseWriter, r *http.Request) {
var req struct {
Samples []sampleRequest `json:"samples"`
}
if !s.decode(w, r, maxEventBody, &req) {
return
}
if len(req.Samples) == 0 || len(req.Samples) > ingest.MaxBatch {
writeError(w, http.StatusBadRequest, "samples must contain 1-1000 items")
return
}
samples := make([]store.Sample, 0, len(req.Samples))
for i, in := range req.Samples {
in.ID, in.Source, in.Metric, in.Unit = strings.TrimSpace(in.ID), strings.TrimSpace(in.Source), strings.TrimSpace(in.Metric), strings.TrimSpace(in.Unit)
if in.ID == "" || in.Source == "" || in.Metric == "" || in.TS.IsZero() || !isFinite(in.Value) {
writeError(w, http.StatusUnprocessableEntity, "sample "+strconv.Itoa(i)+" has invalid id, source, metric, ts, or value")
return
}
if in.TS.After(s.now().Add(5 * time.Minute)) {
writeError(w, http.StatusUnprocessableEntity, "sample timestamp is in the future")
return
}
samples = append(samples, store.Sample{ExternalID: in.ID, Source: in.Source, Metric: in.Metric, TS: in.TS.UTC(), Value: in.Value, Unit: in.Unit})
}
n, err := s.store.InsertSamples(r.Context(), deviceFrom(r.Context()).ID, samples)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"received": len(samples), "inserted": n})
}
func isFinite(v float64) bool { return !math.IsNaN(v) && !math.IsInf(v, 0) }
func (s *Server) samples(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
now := s.now()
f := store.SampleFilter{From: now.Add(-24 * time.Hour), To: now, Source: q.Get("source"), Metric: q.Get("metric"), Limit: 1000}
var err error
if v := q.Get("from"); v != "" {
if f.From, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "from must be RFC3339")
return
}
}
if v := q.Get("to"); v != "" {
if f.To, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "to must be RFC3339")
return
}
}
if v := q.Get("limit"); v != "" {
if f.Limit, err = strconv.Atoi(v); err != nil || f.Limit < 1 || f.Limit > 10000 {
writeError(w, http.StatusBadRequest, "limit must be 1-10000")
return
}
}
if v := q.Get("cursor"); v != "" {
var c activityCursor
b, decodeErr := base64.RawURLEncoding.DecodeString(v)
if decodeErr != nil || json.Unmarshal(b, &c) != nil || c.ID < 1 || c.StartedAt.IsZero() {
writeError(w, http.StatusBadRequest, "cursor is invalid")
return
}
f.After = &store.SampleCursor{TS: c.StartedAt, ID: c.ID}
}
items, next, err := s.store.SamplesPage(r.Context(), f)
if err != nil {
s.internalError(w, r, err)
return
}
out := map[string]any{"samples": items}
if next != nil {
out["next_cursor"] = encodeActivityCursor(activityCursor{StartedAt: next.TS, ID: next.ID})
}
writeJSON(w, http.StatusOK, out)
}
// ingestLocation takes an arrive or leave from a phone geofence automation.
// The place comes from the path (/arrive/gym), ?place=, the body's "place",
// or defaults to home. ingest.Destination decides where the device ends up.
@@ -259,13 +363,84 @@ func (s *Server) activities(w http.ResponseWriter, r *http.Request) {
return
}
}
var cursor *store.ActivityCursor
if v := q.Get("cursor"); v != "" {
var payload activityCursor
decoded, decodeErr := base64.RawURLEncoding.DecodeString(v)
if decodeErr != nil || json.Unmarshal(decoded, &payload) != nil || payload.ID < 1 || payload.StartedAt.IsZero() {
writeError(w, http.StatusBadRequest, "cursor is invalid")
return
}
cursor = &store.ActivityCursor{StartedAt: payload.StartedAt, ID: payload.ID}
f.After = cursor
}
acts, err := s.store.Activities(r.Context(), f)
acts, next, err := s.store.ActivitiesPage(r.Context(), f)
if err != nil {
s.internalError(w, r, err)
return
}
out := map[string]any{"activities": acts}
if next != nil {
out["next_cursor"] = encodeActivityCursor(activityCursor{StartedAt: next.StartedAt, ID: next.ID})
}
writeJSON(w, http.StatusOK, out)
}
type activityCursor struct {
StartedAt time.Time `json:"started_at"`
ID int64 `json:"id"`
}
func encodeActivityCursor(c activityCursor) string {
b, _ := json.Marshal(c)
return base64.RawURLEncoding.EncodeToString(b)
}
func (s *Server) exportActivities(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
now := s.now()
f := store.ActivityFilter{From: now.Add(-24 * time.Hour), To: now, Source: q.Get("source"), Kind: q.Get("kind"), Limit: 10000}
var err error
if v := q.Get("from"); v != "" {
if f.From, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "from must be RFC3339")
return
}
}
if v := q.Get("to"); v != "" {
if f.To, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "to must be RFC3339")
return
}
}
var acts []store.StoredActivity
for {
page, next, pageErr := s.store.ActivitiesPage(r.Context(), f)
if pageErr != nil {
s.internalError(w, r, pageErr)
return
}
acts = append(acts, page...)
if next == nil {
break
}
f.After = next
}
if q.Get("format") == "json" {
w.Header().Set("Content-Disposition", "attachment; filename=activities.json")
writeJSON(w, http.StatusOK, map[string]any{"activities": acts})
return
}
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Header().Set("Content-Disposition", "attachment; filename=activities.csv")
cw := csv.NewWriter(w)
_ = cw.Write([]string{"id", "device", "source", "kind", "label", "started_at", "ended_at", "duration_s", "attrs"})
for _, a := range acts {
attrs, _ := json.Marshal(a.Attrs)
_ = cw.Write([]string{strconv.FormatInt(a.ID, 10), a.Device, a.Source, a.Kind, a.Label, a.StartedAt.Format(time.RFC3339Nano), a.EndedAt.Format(time.RFC3339Nano), strconv.Itoa(a.DurationS), string(attrs)})
}
cw.Flush()
}
func (s *Server) dailySummary(w http.ResponseWriter, r *http.Request) {
@@ -292,6 +467,207 @@ func (s *Server) dailySummary(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, summary.Build(from.Format(time.DateOnly), from, to, totals, goals))
}
func (s *Server) rangeSummary(w http.ResponseWriter, r *http.Request) {
from, to, ok := s.parseRange(w, r)
if !ok {
return
}
totals, err := s.store.Totals(r.Context(), from, to)
if err != nil {
s.internalError(w, r, err)
return
}
samples, err := s.store.SampleSummary(r.Context(), from, to)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"from": from, "to": to, "totals": totals, "samples": samples})
}
func (s *Server) parseRange(w http.ResponseWriter, r *http.Request) (time.Time, time.Time, bool) {
now := s.now()
from, to := now.Add(-24*time.Hour), now
var err error
if v := r.URL.Query().Get("from"); v != "" {
from, err = time.Parse(time.RFC3339, v)
if err != nil {
writeError(w, http.StatusBadRequest, "from must be RFC3339")
return time.Time{}, time.Time{}, false
}
}
if v := r.URL.Query().Get("to"); v != "" {
to, err = time.Parse(time.RFC3339, v)
if err != nil {
writeError(w, http.StatusBadRequest, "to must be RFC3339")
return time.Time{}, time.Time{}, false
}
}
if !from.Before(to) {
writeError(w, http.StatusBadRequest, "from must be before to")
return time.Time{}, time.Time{}, false
}
return from, to, true
}
func (s *Server) listReports(w http.ResponseWriter, r *http.Request) {
reports, err := s.store.Reports(r.Context())
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"reports": reports})
}
func (s *Server) createReport(w http.ResponseWriter, r *http.Request) {
var report store.Report
if !s.decode(w, r, 1<<20, &report) {
return
}
if report.PeriodStart.IsZero() || report.PeriodEnd.IsZero() || !report.PeriodStart.Before(report.PeriodEnd) || strings.TrimSpace(report.Model) == "" || report.Body == "" {
writeError(w, http.StatusBadRequest, "period_start, period_end, model, and body are required")
return
}
report.Model, report.PromptHash = strings.TrimSpace(report.Model), strings.TrimSpace(report.PromptHash)
created, err := s.store.CreateReport(r.Context(), report)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusCreated, created)
}
func (s *Server) notificationStatus(w http.ResponseWriter, r *http.Request) {
settings, err := s.store.NotificationSettings(r.Context())
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"configured": settings.Enabled && settings.NtfyTopic != "", "settings": settings})
}
func (s *Server) updateNotificationConfig(w http.ResponseWriter, r *http.Request) {
var settings store.NotificationSettings
if !s.decode(w, r, 16<<10, &settings) {
return
}
settings.NtfyServer, settings.NtfyTopic = strings.TrimRight(strings.TrimSpace(settings.NtfyServer), "/"), strings.TrimSpace(settings.NtfyTopic)
if settings.NtfyServer == "" {
settings.NtfyServer = "https://ntfy.sh"
}
if settings.RetentionDays < 0 || (settings.Enabled && settings.NtfyTopic == "") {
writeError(w, http.StatusBadRequest, "retention_days must be non-negative and enabled requires ntfy_topic")
return
}
updated, err := s.store.UpdateNotificationSettings(r.Context(), settings)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, updated)
}
func (s *Server) purgePrivacyData(w http.ResponseWriter, r *http.Request) {
cutoff := r.URL.Query().Get("before")
if cutoff == "" {
writeError(w, http.StatusBadRequest, "before must be RFC3339")
return
}
before, err := time.Parse(time.RFC3339, cutoff)
if err != nil {
writeError(w, http.StatusBadRequest, "before must be RFC3339")
return
}
n, err := s.store.PurgeBefore(r.Context(), before)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"deleted": n, "before": before})
}
func (s *Server) listGoals(w http.ResponseWriter, r *http.Request) {
goals, err := s.store.Goals(r.Context())
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"goals": goals})
}
type goalRequest struct {
Kind string `json:"kind"`
Label string `json:"label"`
Op string `json:"op"`
TargetS int64 `json:"target_s"`
Period string `json:"period"`
}
func (s *Server) decodeGoal(w http.ResponseWriter, r *http.Request) (store.Goal, bool) {
var req goalRequest
if !s.decode(w, r, 4<<10, &req) {
return store.Goal{}, false
}
req.Kind, req.Label, req.Op, req.Period = strings.TrimSpace(req.Kind), strings.TrimSpace(req.Label), strings.TrimSpace(req.Op), strings.TrimSpace(req.Period)
if req.Kind == "" || (req.Op != ">=" && req.Op != "<=") || req.TargetS < 0 || (req.Period != "" && req.Period != "day") {
writeError(w, http.StatusBadRequest, "kind, op (>= or <=), target_s >= 0, and period=day are required")
return store.Goal{}, false
}
return store.Goal{Kind: req.Kind, Label: req.Label, Op: req.Op, TargetS: req.TargetS}, true
}
func (s *Server) createGoal(w http.ResponseWriter, r *http.Request) {
goal, ok := s.decodeGoal(w, r)
if !ok {
return
}
goal, err := s.store.CreateGoal(r.Context(), goal)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusCreated, goal)
}
func (s *Server) updateGoal(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id < 1 {
writeError(w, http.StatusBadRequest, "id must be a positive integer")
return
}
goal, ok := s.decodeGoal(w, r)
if !ok {
return
}
goal.ID = id
goal, err = s.store.UpdateGoal(r.Context(), goal)
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "goal not found")
return
}
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, goal)
}
func (s *Server) deleteGoal(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id < 1 {
writeError(w, http.StatusBadRequest, "id must be a positive integer")
return
}
if err := s.store.DeleteGoal(r.Context(), id); errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "goal not found")
return
} else if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
}
func (s *Server) listDevices(w http.ResponseWriter, r *http.Request) {
devs, err := s.store.ListDevices(r.Context())
if err != nil {
+26
View File
@@ -154,3 +154,29 @@ func TestLocation(t *testing.T) {
t.Errorf("unknown event: %d", code)
}
}
func TestSamplesReportsAndSettings(t *testing.T) {
srv, key := setup(t)
ts := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)
body := `{"samples":[{"id":"s1","source":"watch","metric":"steps","ts":"` + ts.Format(time.RFC3339) + `","value":12,"unit":"count"}]}`
code, out := do(t, "POST", srv.URL+"/api/v1/samples", key, body)
if code != http.StatusOK || out["inserted"] != 1.0 {
t.Fatalf("sample ingest: %d %v", code, out)
}
code, out = do(t, "POST", srv.URL+"/api/v1/samples", key, body)
if code != http.StatusOK || out["inserted"] != 0.0 {
t.Fatalf("sample idempotency: %d %v", code, out)
}
code, out = do(t, "GET", srv.URL+"/api/v1/summary/range?from="+ts.Add(-time.Minute).Format(time.RFC3339)+"&to="+ts.Add(time.Minute).Format(time.RFC3339), key, "")
if code != http.StatusOK || len(out["samples"].([]any)) != 1 {
t.Fatalf("range summary: %d %v", code, out)
}
code, out = do(t, "PUT", srv.URL+"/api/v1/notifications/config", "", `{"enabled":true,"ntfy_topic":"goals","retention_days":30}`)
if code != http.StatusOK || out["ntfy_topic"] != "goals" {
t.Fatalf("notification config: %d %v", code, out)
}
code, out = do(t, "POST", srv.URL+"/api/v1/reports", "", `{"period_start":"`+ts.Format(time.RFC3339)+`","period_end":"`+ts.Add(time.Hour).Format(time.RFC3339)+`","model":"test","body":"summary"}`)
if code != http.StatusCreated || out["id"] == nil {
t.Fatalf("report create: %d %v", code, out)
}
}
@@ -0,0 +1,20 @@
-- +goose Up
-- The same collector event ID is only idempotent within its device.
DELETE FROM activities a
USING activities duplicate
WHERE a.source = duplicate.source
AND a.external_id = duplicate.external_id
AND a.id > duplicate.id;
ALTER TABLE activities DROP CONSTRAINT activities_source_external_id_key;
ALTER TABLE activities ADD CONSTRAINT activities_device_source_external_id_key
UNIQUE (device_id, source, external_id);
-- +goose Down
DELETE FROM activities a
USING activities duplicate
WHERE a.source = duplicate.source
AND a.external_id = duplicate.external_id
AND a.id > duplicate.id;
ALTER TABLE activities DROP CONSTRAINT activities_device_source_external_id_key;
ALTER TABLE activities ADD CONSTRAINT activities_source_external_id_key
UNIQUE (source, external_id);
@@ -0,0 +1,24 @@
-- +goose Up
CREATE TABLE notification_settings (
id boolean PRIMARY KEY DEFAULT true CHECK (id),
ntfy_server text NOT NULL DEFAULT 'https://ntfy.sh',
ntfy_topic text NOT NULL DEFAULT '',
enabled boolean NOT NULL DEFAULT false,
retention_days integer NOT NULL DEFAULT 0 CHECK (retention_days >= 0),
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO notification_settings DEFAULT VALUES;
DELETE FROM samples s USING samples duplicate
WHERE s.source = duplicate.source AND s.external_id = duplicate.external_id AND s.id > duplicate.id;
ALTER TABLE samples DROP CONSTRAINT samples_source_external_id_key;
ALTER TABLE samples ADD CONSTRAINT samples_device_source_external_id_key UNIQUE (device_id, source, external_id);
CREATE INDEX reports_period_idx ON reports (period_start DESC, period_end DESC);
CREATE INDEX samples_device_metric_ts_idx ON samples (device_id, metric, ts);
-- +goose Down
DROP INDEX samples_device_metric_ts_idx;
DROP INDEX reports_period_idx;
DROP TABLE notification_settings;
ALTER TABLE samples DROP CONSTRAINT samples_device_source_external_id_key;
ALTER TABLE samples ADD CONSTRAINT samples_source_external_id_key UNIQUE (source, external_id);
+252 -12
View File
@@ -9,6 +9,7 @@ import (
"encoding/hex"
"errors"
"fmt"
"strconv"
"time"
"github.com/jackc/pgx/v5"
@@ -105,19 +106,120 @@ func (s *Store) DeviceByKey(ctx context.Context, key string) (Device, error) {
// ---- ingest ----
// InsertActivities stores activities, skipping ones already stored with the
// same (source, external_id). It returns how many rows were new.
// same (device_id, source, external_id). It returns how many rows were new.
func (s *Store) InsertActivities(ctx context.Context, deviceID int64, acts []ingest.Activity) (int64, error) {
b := &pgx.Batch{}
for _, a := range acts {
attrs := a.Attrs
if attrs == nil {
attrs = map[string]any{}
}
b.Queue(`INSERT INTO activities
(device_id, source, kind, label, started_at, ended_at, attrs, external_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (source, external_id) DO NOTHING`,
deviceID, a.Source, a.Kind, a.Label, a.StartedAt, a.EndedAt, a.Attrs, a.ExternalID)
ON CONFLICT (device_id, source, external_id) DO NOTHING`,
deviceID, a.Source, a.Kind, a.Label, a.StartedAt, a.EndedAt, attrs, a.ExternalID)
}
return s.sendBatch(ctx, b)
}
// Sample is a point-in-time metric uploaded by a collector.
type Sample struct {
ID int64 `json:"id"`
Device string `json:"device,omitempty"`
Source string `json:"source"`
Metric string `json:"metric"`
TS time.Time `json:"ts"`
Value float64 `json:"value"`
Unit string `json:"unit"`
ExternalID string `json:"external_id"`
}
func (s *Store) InsertSamples(ctx context.Context, deviceID int64, samples []Sample) (int64, error) {
b := &pgx.Batch{}
for _, sample := range samples {
b.Queue(`INSERT INTO samples (device_id, source, metric, ts, value, unit, external_id)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (device_id, source, external_id) DO NOTHING`,
deviceID, sample.Source, sample.Metric, sample.TS, sample.Value, sample.Unit, sample.ExternalID)
}
return s.sendBatch(ctx, b)
}
type SampleFilter struct {
From, To time.Time
Source, Metric string
Limit int
After *SampleCursor
}
type SampleCursor struct {
TS time.Time
ID int64
}
func (s *Store) SamplesPage(ctx context.Context, f SampleFilter) ([]Sample, *SampleCursor, error) {
limit := f.Limit
if limit < 1 {
limit = 1000
}
args := []any{f.From, f.To, f.Source, f.Metric}
clause := ""
if f.After != nil {
clause = " AND (s.ts, s.id) > ($5, $6)"
args = append(args, f.After.TS, f.After.ID)
}
args = append(args, limit+1)
rows, err := s.pool.Query(ctx, `SELECT s.id, d.name, s.source, s.metric, s.ts, s.value, s.unit, s.external_id
FROM samples s JOIN devices d ON d.id = s.device_id
WHERE s.ts >= $1 AND s.ts < $2 AND ($3 = '' OR s.source = $3) AND ($4 = '' OR s.metric = $4)`+clause+`
ORDER BY s.ts, s.id LIMIT $`+strconv.Itoa(len(args)), args...)
if err != nil {
return nil, nil, err
}
rowsOut, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Sample, error) {
var sample Sample
err := r.Scan(&sample.ID, &sample.Device, &sample.Source, &sample.Metric, &sample.TS, &sample.Value, &sample.Unit, &sample.ExternalID)
return sample, err
})
if err != nil {
return nil, nil, err
}
more := len(rowsOut) > limit
if more {
rowsOut = rowsOut[:limit]
}
var next *SampleCursor
if more {
last := rowsOut[len(rowsOut)-1]
next = &SampleCursor{TS: last.TS, ID: last.ID}
}
return rowsOut, next, nil
}
// SampleRangeSummary returns min/max/average/count grouped by metric.
type SampleSummary struct {
Metric string `json:"metric"`
Unit string `json:"unit"`
Count int64 `json:"count"`
Min float64 `json:"min"`
Max float64 `json:"max"`
Average float64 `json:"average"`
}
func (s *Store) SampleSummary(ctx context.Context, from, to time.Time) ([]SampleSummary, error) {
rows, err := s.pool.Query(ctx, `SELECT metric, min(unit), count(*), min(value), max(value), avg(value)
FROM samples WHERE ts >= $1 AND ts < $2 GROUP BY metric ORDER BY metric`, from, to)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(r pgx.CollectableRow) (SampleSummary, error) {
var out SampleSummary
err := r.Scan(&out.Metric, &out.Unit, &out.Count, &out.Min, &out.Max, &out.Average)
return out, err
})
}
// MoveTo records a location transition for a device: it closes the device's
// open place interval at `at` and opens one labelled dest(current place).
// dest is called under the device's lock, so concurrent events see each
@@ -232,6 +334,12 @@ type ActivityFilter struct {
From, To time.Time
Source, Kind string // empty matches all
Limit int
After *ActivityCursor
}
type ActivityCursor struct {
StartedAt time.Time
ID int64
}
// effectiveEnd is an activity's end, reading open location intervals (stored
@@ -240,25 +348,70 @@ const effectiveEnd = `(CASE WHEN attrs ? 'open' THEN greatest(ended_at, now()) E
// Activities returns activities overlapping [From, To), oldest first.
func (s *Store) Activities(ctx context.Context, f ActivityFilter) ([]StoredActivity, error) {
acts, _, err := s.activitiesPage(ctx, f)
return acts, err
}
// ActivitiesPage returns one page of activities and a cursor for the next
// page, if one exists. Results are clipped to the requested [From, To) range.
func (s *Store) ActivitiesPage(ctx context.Context, f ActivityFilter) ([]StoredActivity, *ActivityCursor, error) {
return s.activitiesPage(ctx, f)
}
func (s *Store) activitiesPage(ctx context.Context, f ActivityFilter) ([]StoredActivity, *ActivityCursor, error) {
limit := f.Limit
if limit < 1 {
limit = 1000
}
args := []any{f.From, f.To, f.Source, f.Kind}
cursorClause := ""
if f.After != nil {
cursorClause = " AND (a.started_at, a.id) > ($5, $6)"
args = append(args, f.After.StartedAt, f.After.ID)
}
limitArg := len(args) + 1
args = append(args, limit+1)
rows, err := s.pool.Query(ctx,
`SELECT a.id, d.name, a.source, a.kind, a.label, a.started_at, a.end_at,
extract(epoch FROM a.end_at - a.started_at)::integer, a.attrs
`SELECT a.id, a.started_at, d.name, a.source, a.kind, a.label,
greatest(a.started_at, $1), least(a.end_at, $2),
extract(epoch FROM least(a.end_at, $2) - greatest(a.started_at, $1))::integer, a.attrs
FROM (SELECT *, `+effectiveEnd+` AS end_at FROM activities) a
JOIN devices d ON d.id = a.device_id
WHERE a.started_at < $2 AND a.end_at > $1
AND ($3 = '' OR a.source = $3)
AND ($4 = '' OR a.kind = $4)
ORDER BY a.started_at
LIMIT $5`,
f.From, f.To, f.Source, f.Kind, f.Limit)
`+cursorClause+`
ORDER BY a.started_at, a.id
LIMIT $`+strconv.Itoa(limitArg), args...)
if err != nil {
return nil, err
return nil, nil, err
}
return pgx.CollectRows(rows, func(r pgx.CollectableRow) (StoredActivity, error) {
type activityRow struct {
activity StoredActivity
started time.Time
}
rowsOut, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (activityRow, error) {
var a StoredActivity
err := r.Scan(&a.ID, &a.Device, &a.Source, &a.Kind, &a.Label, &a.StartedAt, &a.EndedAt, &a.DurationS, &a.Attrs)
return a, err
var started time.Time
err := r.Scan(&a.ID, &started, &a.Device, &a.Source, &a.Kind, &a.Label, &a.StartedAt, &a.EndedAt, &a.DurationS, &a.Attrs)
return activityRow{activity: a, started: started}, err
})
if err != nil {
return nil, nil, err
}
more := len(rowsOut) > limit
if more {
rowsOut = rowsOut[:limit]
}
acts := make([]StoredActivity, len(rowsOut))
for i, row := range rowsOut {
acts[i] = row.activity
}
var next *ActivityCursor
if more {
next = &ActivityCursor{StartedAt: rowsOut[len(rowsOut)-1].started, ID: rowsOut[len(rowsOut)-1].activity.ID}
}
return acts, next, nil
}
type Total struct {
@@ -317,6 +470,22 @@ func (s *Store) CreateGoal(ctx context.Context, g Goal) (Goal, error) {
return g, nil
}
func (s *Store) UpdateGoal(ctx context.Context, g Goal) (Goal, error) {
err := s.pool.QueryRow(ctx,
`UPDATE goals SET kind = $2, label = $3, op = $4, target_s = $5
WHERE id = $1
RETURNING id, kind, label, op, target_s, period`,
g.ID, g.Kind, g.Label, g.Op, g.TargetS,
).Scan(&g.ID, &g.Kind, &g.Label, &g.Op, &g.TargetS, &g.Period)
if errors.Is(err, pgx.ErrNoRows) {
return g, ErrNotFound
}
if err != nil {
return g, fmt.Errorf("update goal: %w", err)
}
return g, nil
}
func (s *Store) DeleteGoal(ctx context.Context, id int64) error {
tag, err := s.pool.Exec(ctx, `DELETE FROM goals WHERE id = $1`, id)
if err != nil {
@@ -327,3 +496,74 @@ func (s *Store) DeleteGoal(ctx context.Context, id int64) error {
}
return nil
}
type Report struct {
ID int64 `json:"id"`
PeriodStart time.Time `json:"period_start"`
PeriodEnd time.Time `json:"period_end"`
Model string `json:"model"`
PromptHash string `json:"prompt_hash"`
Body string `json:"body"`
CreatedAt time.Time `json:"created_at"`
}
func (s *Store) Reports(ctx context.Context) ([]Report, error) {
rows, err := s.pool.Query(ctx, `SELECT id, period_start, period_end, model, prompt_hash, body, created_at
FROM reports ORDER BY period_start DESC, id DESC`)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, pgx.RowToStructByPos[Report])
}
func (s *Store) CreateReport(ctx context.Context, report Report) (Report, error) {
err := s.pool.QueryRow(ctx, `INSERT INTO reports (period_start, period_end, model, prompt_hash, body)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, created_at`, report.PeriodStart, report.PeriodEnd, report.Model, report.PromptHash, report.Body).
Scan(&report.ID, &report.CreatedAt)
return report, err
}
type NotificationSettings struct {
NtfyServer string `json:"ntfy_server"`
NtfyTopic string `json:"ntfy_topic"`
Enabled bool `json:"enabled"`
RetentionDays int `json:"retention_days"`
UpdatedAt time.Time `json:"updated_at"`
}
func (s *Store) NotificationSettings(ctx context.Context) (NotificationSettings, error) {
var settings NotificationSettings
err := s.pool.QueryRow(ctx, `SELECT ntfy_server, ntfy_topic, enabled, retention_days, updated_at
FROM notification_settings WHERE id`).Scan(&settings.NtfyServer, &settings.NtfyTopic, &settings.Enabled,
&settings.RetentionDays, &settings.UpdatedAt)
return settings, err
}
func (s *Store) UpdateNotificationSettings(ctx context.Context, settings NotificationSettings) (NotificationSettings, error) {
err := s.pool.QueryRow(ctx, `UPDATE notification_settings SET ntfy_server = $1, ntfy_topic = $2,
enabled = $3, retention_days = $4, updated_at = now() WHERE id
RETURNING ntfy_server, ntfy_topic, enabled, retention_days, updated_at`, settings.NtfyServer,
settings.NtfyTopic, settings.Enabled, settings.RetentionDays).Scan(&settings.NtfyServer, &settings.NtfyTopic,
&settings.Enabled, &settings.RetentionDays, &settings.UpdatedAt)
return settings, err
}
// PurgeBefore applies the privacy retention policy to all user data tables.
func (s *Store) PurgeBefore(ctx context.Context, before time.Time) (int64, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return 0, err
}
defer tx.Rollback(ctx)
var deleted int64
for _, table := range []string{"activities", "samples", "reports"} {
column := map[string]string{"activities": "started_at", "samples": "ts", "reports": "period_start"}[table]
tag, err := tx.Exec(ctx, `DELETE FROM `+table+` WHERE `+column+` < $1`, before)
if err != nil {
return 0, err
}
deleted += tag.RowsAffected()
}
return deleted, tx.Commit(ctx)
}
+80
View File
@@ -84,3 +84,83 @@ func TestMoveToConcurrent(t *testing.T) {
t.Errorf("places = %v, want to end at gym", got)
}
}
func TestActivityIdempotencyIsPerDevice(t *testing.T) {
s, dev := setup(t)
other, _, err := s.CreateDevice(context.Background(), "other", "desktop")
if err != nil {
t.Fatal(err)
}
a := ingest.Activity{Source: "test", Kind: "focus", StartedAt: time.Now().Add(-time.Hour), EndedAt: time.Now(), ExternalID: "same"}
if n, err := s.InsertActivities(context.Background(), dev, []ingest.Activity{a}); err != nil || n != 1 {
t.Fatalf("first insert: n=%d err=%v", n, err)
}
if n, err := s.InsertActivities(context.Background(), dev, []ingest.Activity{a}); err != nil || n != 0 {
t.Fatalf("duplicate insert: n=%d err=%v", n, err)
}
if n, err := s.InsertActivities(context.Background(), other.ID, []ingest.Activity{a}); err != nil || n != 1 {
t.Fatalf("other device insert: n=%d err=%v", n, err)
}
}
func TestActivitiesClipToRange(t *testing.T) {
s, dev := setup(t)
from := time.Now().UTC().Add(-2 * time.Hour).Truncate(time.Second)
to := from.Add(time.Hour)
a := ingest.Activity{Source: "test", Kind: "focus", StartedAt: from.Add(-time.Hour), EndedAt: to.Add(time.Hour), ExternalID: "clip"}
b := ingest.Activity{Source: "test", Kind: "focus", StartedAt: from.Add(10 * time.Minute), EndedAt: from.Add(20 * time.Minute), ExternalID: "page"}
if _, err := s.InsertActivities(context.Background(), dev, []ingest.Activity{a, b}); err != nil {
t.Fatal(err)
}
acts, err := s.Activities(context.Background(), ActivityFilter{From: from, To: to, Limit: 10})
if err != nil {
t.Fatal(err)
}
if len(acts) != 2 || !acts[0].StartedAt.Equal(from) || !acts[0].EndedAt.Equal(to) || acts[0].DurationS != 3600 {
t.Fatalf("clipped activities = %+v", acts)
}
page, next, err := s.ActivitiesPage(context.Background(), ActivityFilter{From: from, To: to, Limit: 1})
if err != nil || len(page) != 1 || next == nil {
t.Fatalf("first page: page=%+v next=%+v err=%v", page, next, err)
}
page, next, err = s.ActivitiesPage(context.Background(), ActivityFilter{From: from, To: to, Limit: 1, After: next})
if err != nil || len(page) != 1 || next != nil || !page[0].StartedAt.Equal(from.Add(10*time.Minute)) {
t.Fatalf("second page: page=%+v next=%+v err=%v", page, next, err)
}
}
func TestSamplesReportsAndPrivacyPurge(t *testing.T) {
s, dev := setup(t)
ctx := context.Background()
ts := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)
samples := []Sample{{Source: "watch", Metric: "steps", TS: ts, Value: 10, Unit: "count", ExternalID: "s1"}, {Source: "watch", Metric: "steps", TS: ts.Add(time.Minute), Value: 20, Unit: "count", ExternalID: "s2"}}
if n, err := s.InsertSamples(ctx, dev, samples); err != nil || n != 2 {
t.Fatalf("insert samples: n=%d err=%v", n, err)
}
if n, err := s.InsertSamples(ctx, dev, samples[:1]); err != nil || n != 0 {
t.Fatalf("duplicate samples: n=%d err=%v", n, err)
}
got, next, err := s.SamplesPage(ctx, SampleFilter{From: ts.Add(-time.Minute), To: ts.Add(time.Hour), Limit: 1})
if err != nil || len(got) != 1 || next == nil {
t.Fatalf("sample page: got=%+v next=%+v err=%v", got, next, err)
}
summary, err := s.SampleSummary(ctx, ts.Add(-time.Minute), ts.Add(time.Hour))
if err != nil || len(summary) != 1 || summary[0].Count != 2 || summary[0].Average != 15 {
t.Fatalf("sample summary: %+v err=%v", summary, err)
}
report, err := s.CreateReport(ctx, Report{PeriodStart: ts, PeriodEnd: ts.Add(time.Hour), Model: "test", Body: "ok"})
if err != nil || report.ID == 0 {
t.Fatalf("create report: %+v err=%v", report, err)
}
settings, err := s.NotificationSettings(ctx)
if err != nil || settings.NtfyServer == "" {
t.Fatalf("settings: %+v err=%v", settings, err)
}
if _, err := s.PurgeBefore(ctx, ts.Add(time.Minute)); err != nil {
t.Fatal(err)
}
reports, err := s.Reports(ctx)
if err != nil || len(reports) != 0 {
t.Fatalf("purged reports: %+v err=%v", reports, err)
}
}
+3 -2
View File
@@ -1,12 +1,13 @@
<template>
<main>
<a class="skip-link" href="#main-content">Skip to content</a>
<nav class="topbar">
<span class="brand">Activity Tracker</span>
<div class="tabs">
<div class="tabs" aria-label="Primary navigation">
<RouterLink to="/">Dashboard</RouterLink>
<RouterLink to="/setup">Setup</RouterLink>
</div>
</nav>
<RouterView />
<div id="main-content" tabindex="-1"><RouterView /></div>
</main>
</template>
+18 -1
View File
@@ -1,9 +1,10 @@
// Calls /api/v1 with the main site's session cookies, which the browser sends.
export async function api<T>(method: string, path: string, body?: unknown): Promise<T> {
export async function api<T>(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
const r = await fetch("api/v1/" + path, {
method,
headers: body ? { "Content-Type": "application/json" } : {},
body: body ? JSON.stringify(body) : undefined,
signal,
});
const out = await r.json().catch(() => ({}));
// The server serves the login redirect instead of the app, so a reload signs in again.
@@ -22,6 +23,7 @@ export interface Summary {
totals: Total[]; by_kind: Record<string, number>; goals: Goal[];
}
export interface Activity {
id: number; device: string; source: string;
kind: string; label: string;
started_at: string; ended_at: string; duration_s: number;
attrs?: Record<string, unknown>;
@@ -31,6 +33,21 @@ export interface Device {
last_seen_at?: string | null; revoked_at?: string | null;
}
export interface AdminGoal {
id: number; kind: string; label: string; op: string;
target_s: number; period?: string;
}
export interface Report {
id: number; period_start: string; period_end: string;
model: string; prompt_hash: string; body: string; created_at: string;
}
export interface NotificationSettings {
ntfy_server: string; ntfy_topic: string; enabled: boolean;
retention_days: number; updated_at?: string;
}
export function dur(s: number): string {
s = Math.round(s);
const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60);
+6 -1
View File
@@ -5,11 +5,16 @@ import { copy } from "../copy";
// A command block with a Copy button, which copies the text as rendered.
const pre = ref<HTMLPreElement>();
const label = ref("Copy");
const feedback = ref("");
function copyCode() {
copy(pre.value?.innerText || "", s => { label.value = s; feedback.value = s === "Copied" ? "Code copied to clipboard." : "Could not copy code."; });
}
</script>
<template>
<div class="codeblock">
<pre ref="pre"><slot /></pre>
<button class="small copy" type="button" @click="copy(pre!.innerText, s => label = s)">{{ label }}</button>
<button class="small copy" type="button" @click="copyCode">{{ label }}</button>
<span class="sr-only" role="status" aria-live="polite">{{ feedback }}</span>
</div>
</template>
+15 -5
View File
@@ -1,11 +1,12 @@
<script setup lang="ts">
import { computed } from "vue";
import { computed, ref } from "vue";
import { IDLE, dur, kindName, seriesKey, slotColor, type Activity } from "../api";
import { useTip } from "../tip";
import Tooltip from "./Tooltip.vue";
const props = defineProps<{ activities: Activity[]; from: string; to: string; slots: Map<string, number> }>();
const { tip, show, hide } = useTip();
const selected = ref<Activity | null>(null);
// Lanes in a fixed order so they don't jump between days; unknown kinds go last.
const ORDER = ["place", "app_focus", "tab_focus", "at_desk", "in_bed", "away", "idle", "locked"];
@@ -59,24 +60,28 @@ const legend = computed(() => {
return items;
});
function enter(e: MouseEvent, s: { a: Activity; color: string }) {
function enter(e: MouseEvent | FocusEvent, s: { a: Activity; color: string }) {
show(e, [
{ text: dur(s.a.duration_s) },
{ text: `${s.a.label || kindName(s.a.kind)} · ${kindName(s.a.kind)}`, color: s.color },
{ text: `${time(s.a.started_at)}–${time(s.a.ended_at)}` },
]);
}
function select(a: Activity) { selected.value = selected.value === a ? null : a; }
const details = (a: Activity) => `${a.label || kindName(a.kind)}, ${time(a.started_at)} to ${time(a.ended_at)}, ${dur(a.duration_s)}`;
</script>
<template>
<div class="timeline" @mouseleave="hide">
<div class="timeline" role="region" aria-label="Activity timeline" @mouseleave="hide">
<div v-for="l in lanes" :key="l.kind" class="lane">
<div class="lane-name">{{ kindName(l.kind) }}</div>
<div class="track">
<div v-for="t in ticks" :key="t.left" class="grid" :style="{ left: t.left + '%' }"></div>
<div v-for="(s, i) in l.segs" :key="i" class="seg"
<button v-for="s in l.segs" :key="s.a.id" type="button" class="seg"
:aria-label="details(s.a)" :aria-pressed="selected === s.a"
:style="{ left: s.left + '%', width: `max(1px, calc(${s.width}% - 1px))`, background: s.color }"
@mousemove="enter($event, s)" @mouseleave="hide"></div>
@mousemove="enter($event, s)" @mouseleave="hide" @focus="enter($event, s)" @blur="hide"
@click="select(s.a)"></button>
<div v-if="now !== null" class="now" :style="{ left: now + '%' }"></div>
</div>
</div>
@@ -94,6 +99,11 @@ function enter(e: MouseEvent, s: { a: Activity; color: string }) {
<span v-if="it.kind" class="muted small-text">{{ it.kind }}</span>
</span>
</div>
<div v-if="selected" class="timeline-detail" role="status" aria-live="polite">
<strong>{{ selected.label || kindName(selected.kind) }}</strong>
<span class="muted">{{ time(selected.started_at) }}–{{ time(selected.ended_at) }} · {{ dur(selected.duration_s) }}</span>
<div v-if="selected.attrs?.title" class="muted small-text">{{ selected.attrs.title }}</div>
</div>
<Tooltip :tip="tip" />
</div>
</template>
+2 -2
View File
@@ -30,8 +30,8 @@ function enter(e: MouseEvent | FocusEvent, date: string, g?: Goal) {
</script>
<template>
<div class="history" @mouseleave="hide">
<div v-for="r in rows" :key="r.k" class="hrow">
<div class="history" role="table" aria-label="Goal history" @mouseleave="hide">
<div v-for="r in rows" :key="r.k" class="hrow" role="row">
<div class="name">{{ r.name }}</div>
<div class="cells">
<button v-for="c in r.cells" :key="c.date" class="cell"
+7 -2
View File
@@ -6,7 +6,11 @@ import { copy } from "../copy";
// A freshly created key, copied to the clipboard as soon as it's shown.
const props = defineProps<{ device: Device; apiKey: string }>();
const label = ref("Copy");
onMounted(() => copy(props.apiKey, s => label.value = s));
const feedback = ref("");
function copyKey() {
copy(props.apiKey, s => { label.value = s; feedback.value = s === "Copied" ? "API key copied to clipboard." : "Could not copy API key."; });
}
onMounted(copyKey);
</script>
<template>
@@ -14,7 +18,8 @@ onMounted(() => copy(props.apiKey, s => label.value = s));
<div>Key for <b>{{ device.name }}</b> <span class="badge">{{ device.kind }}</span>. Copy it now; it won't be shown again.</div>
<div class="codeblock">
<pre>{{ apiKey }}</pre>
<button class="small copy" type="button" @click="copy(apiKey, s => label = s)">{{ label }}</button>
<button class="small copy" type="button" @click="copyKey">{{ label }}</button>
</div>
<span class="sr-only" role="status" aria-live="polite">{{ feedback }}</span>
</div>
</template>
+4 -3
View File
@@ -44,12 +44,13 @@ function enter(e: MouseEvent | FocusEvent, c: (typeof cols.value)[number]) {
<template>
<div class="trend">
<div class="row spread">
<h2>Last {{ days.length }} days</h2>
<h2>Last {{ days.length }} days <span class="muted chart-subtitle">Daily {{ kindName(kind) }} time</span></h2>
<select v-model="kind" aria-label="Measure">
<option v-for="k in kinds" :key="k" :value="k">{{ kindName(k) }}</option>
</select>
</div>
<div class="plot">
<p v-if="!kinds.length" class="empty-chart" role="status">No activity data is available for this period.</p>
<div v-else class="plot" role="region" :aria-label="`Daily ${kindName(kind)} time for the last ${days.length} days`">
<div class="yaxis">
<span v-for="l in scale.lines" :key="l" :style="{ bottom: h(l) }">{{ tick(l) }}</span>
</div>
@@ -63,7 +64,7 @@ function enter(e: MouseEvent | FocusEvent, c: (typeof cols.value)[number]) {
</button>
</div>
</div>
<div class="xaxis">
<div v-if="kinds.length" class="xaxis" aria-hidden="true">
<span v-for="c in cols" :key="c.date" :class="{ sel: c.date === selected }">{{ c.day }}</span>
</div>
<Tooltip :tip="tip" />
+48 -1
View File
@@ -23,6 +23,8 @@ a { color:var(--accent); }
/* ---- top bar ---- */
.topbar { display:flex; align-items:center; gap:20px; padding:16px 0; margin-bottom:8px; border-bottom:1px solid var(--line); }
.skip-link { position:absolute; left:-999px; top:8px; z-index:20; padding:8px 12px; background:var(--card); border:1px solid var(--accent); border-radius:6px; }
.skip-link:focus { left:8px; }
.brand { font-weight:650; font-size:17px; }
.tabs { display:flex; gap:4px; }
.tabs a { color:var(--muted); text-decoration:none; padding:5px 10px; border-radius:6px; }
@@ -44,10 +46,13 @@ button:disabled { opacity:.6; cursor:default; }
.spread { justify-content:space-between; }
.card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:16px; margin-top:16px; }
.card > h2:first-child, .card > .row:first-child h2 { margin-top:0; }
.section-head { margin-bottom:10px; }
.filter { display:flex; align-items:center; gap:6px; color:var(--muted); font-size:13px; }
h1 { font-size:20px; margin:16px 0 0; }
h2 { font-size:15px; margin:0 0 10px; }
h3 { font-size:14px; margin:16px 0 6px; }
.muted { color:var(--muted); }
.sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
.small-text { font-size:13px; }
.ok { color:var(--ok); } .bad, .err { color:var(--bad); }
.badge { display:inline-block; font-size:12px; padding:1px 7px; border-radius:999px; background:var(--accent-soft); color:var(--accent); white-space:nowrap; }
@@ -79,6 +84,32 @@ li { margin:6px 0; }
/* ---- setup ---- */
.keybox { margin-top:12px; padding:12px; border:1px solid var(--ok); border-radius:8px; }
.status-dot { display:inline-block; width:8px; height:8px; margin-right:5px; border-radius:50%; background:var(--muted); }
.status-dot.good { background:var(--ok); }
.status-dot.warn { background:var(--s4); }
.status-dot.bad { background:var(--bad); }
.confirm { margin-top:12px; padding:12px; border:1px solid var(--bad); border-radius:8px; background:var(--bad-soft); }
.danger { color:var(--bad); border-color:var(--bad); }
.button-like { display:inline-block; padding:5px 10px; border:1px solid var(--line); border-radius:6px; color:var(--fg); text-decoration:none; background:var(--card); }
.button-like:hover { border-color:var(--muted); }
.setup-progress { display:grid; gap:7px; margin-bottom:0; }
.setup-progress li { margin:0; }
.setup-progress li.ok b { color:var(--ok); }
.goal-form { display:grid; grid-template-columns:1fr 1fr auto auto; gap:8px; align-items:end; }
.goal-form label { display:grid; gap:3px; font-size:13px; color:var(--muted); }
.settings-form { display:grid; grid-template-columns:1fr 1fr; gap:8px; align-items:end; margin-top:12px; }
.settings-form label, .privacy-tools label { display:grid; gap:3px; font-size:13px; color:var(--muted); }
.settings-form .check { display:flex; align-items:center; gap:6px; }
.settings-form .check input { width:auto; }
.data-actions { margin:10px 0 14px; }
.privacy-tools { border-top:1px solid var(--line); margin-top:16px; padding-top:12px; }
.privacy-tools h3 { margin-top:0; }
.report-list { border-top:1px solid var(--line); margin-top:16px; padding-top:12px; }
.report { border-bottom:1px solid var(--line); padding:8px 0; }
.report:last-child { border-bottom:0; }
.report p { margin:4px 0 0; white-space:pre-wrap; }
@media (max-width:620px) { .goal-form { grid-template-columns:1fr 1fr; } .goal-form button { grid-column:span 2; } }
@media (max-width:620px) { .settings-form { grid-template-columns:1fr; } }
.keybox pre { margin:8px 0; }
details.collector { background:var(--card); border:1px solid var(--line); border-radius:10px; margin-top:12px; }
details.collector > summary { cursor:pointer; padding:14px 16px; list-style:none; display:flex; gap:10px; align-items:baseline; }
@@ -104,8 +135,10 @@ details.collector > .body { padding:0 16px 16px; }
.timeline .track { position:relative; flex:1; height:18px; min-width:0; }
.timeline .axis .track { height:16px; }
.timeline .grid { position:absolute; top:-3px; bottom:-3px; width:1px; background:var(--grid); }
.timeline .seg { position:absolute; top:0; bottom:0; border-radius:3px; }
.timeline .seg { position:absolute; top:0; bottom:0; border:0; border-radius:3px; padding:0; }
.timeline .seg:hover { filter:brightness(1.15); }
.timeline .seg[aria-pressed="true"] { outline:2px solid var(--fg); outline-offset:1px; z-index:1; }
.timeline-detail { margin:12px 0 0 72px; padding:9px 10px; border-left:3px solid var(--accent); background:var(--accent-soft); display:grid; gap:2px; }
.timeline .now { position:absolute; top:-4px; bottom:-4px; width:2px; margin-left:-1px; background:var(--fg); border-radius:1px; }
.timeline .tick { position:absolute; transform:translateX(-50%); font-size:12px; color:var(--muted); font-variant-numeric:tabular-nums; white-space:nowrap; }
.timeline .tick.first { transform:none; }
@@ -132,6 +165,8 @@ details.collector > .body { padding:0 16px 16px; }
.trend .xaxis { display:flex; margin-left:40px; margin-top:4px; }
.trend .xaxis span { flex:1; text-align:center; font-size:12px; color:var(--muted); font-variant-numeric:tabular-nums; }
.trend .xaxis span.sel { color:var(--fg); font-weight:650; }
.chart-subtitle { font-size:13px; font-weight:400; }
.empty-chart { min-height:140px; display:grid; place-items:center; margin:22px 0 0; border:1px dashed var(--line); color:var(--muted); }
.history .hrow { display:grid; grid-template-columns:minmax(0, 1fr) auto 76px; gap:6px 12px; align-items:center;
padding:7px 0; border-bottom:1px solid var(--line); }
@@ -140,9 +175,21 @@ details.collector > .body { padding:0 16px 16px; }
.history .cells { display:flex; gap:2px; }
.history .streak { text-align:right; white-space:nowrap; }
@media (max-width:620px) {
.dashboard-head { align-items:flex-start; }
.dashboard-head > .row { width:100%; justify-content:space-between; }
.dashboard-head input[type="date"] { flex:1; min-width:0; }
.section-head { align-items:flex-start; }
.section-head .filter { width:100%; }
.section-head select { flex:1; }
.history .hrow { grid-template-columns:1fr auto; }
.history .cells { grid-row:2; grid-column:1 / -1; }
}
@media (max-width:420px) {
main { padding-left:10px; padding-right:10px; }
.card { padding:12px; }
.tile .v { font-size:19px; }
th, td { padding-right:5px; }
}
.history .cell { width:22px; height:22px; padding:0; border:0; border-radius:4px; font-size:12px; line-height:22px; text-align:center; flex:none; }
@media (max-width:420px) { .history .cell { width:auto; flex:1; } }
.history .cell.met { background:var(--ok-soft); color:var(--ok); }
+37 -27
View File
@@ -15,6 +15,7 @@ const sum = ref<Summary | null>(null);
const activities = ref<Activity[]>([]);
const loading = ref(false);
const error = ref("");
const activityKind = ref("all");
// Summaries for the trend charts, kept across day changes. The selected day's
// is always refetched since today's is still growing.
const history = reactive<Record<string, Summary>>({});
@@ -25,31 +26,48 @@ const title = computed(() => daysAgo.value === 0 ? "Today" : daysAgo.value === 1
// Ignore a response for a day that's no longer selected.
let seq = 0;
let controller: AbortController | null = null;
async function request<T>(path: string, signal: AbortSignal): Promise<T> {
return api<T>("GET", path, undefined, signal);
}
async function load() {
const n = ++seq;
controller?.abort();
controller = new AbortController();
const signal = controller.signal;
loading.value = true;
error.value = "";
try {
const s = await api<Summary>("GET", "summary/daily?date=" + date.value);
const s = await request<Summary>("summary/daily?date=" + date.value, signal);
const q = new URLSearchParams({ from: s.from, to: s.to, limit: String(LIMIT) });
const { activities: acts } = await api<{ activities: Activity[] }>("GET", "activities?" + q);
const [{ activities: acts }, ...trend] = await Promise.all([
request<{ activities: Activity[] }>("activities?" + q, signal),
...trendDates(date.value).map(d => request<Summary>("summary/daily?date=" + d, signal)
.then(x => [d, x] as const).catch(() => null)),
]);
if (n !== seq) return;
sum.value = s;
activities.value = acts;
history[s.date] = s;
for (const item of trend) if (item) history[item[0]] = item[1];
} catch (e) {
if (n === seq) error.value = (e as Error).message;
if (n === seq && (e as Error).name !== "AbortError") error.value = (e as Error).message;
} finally {
if (n === seq) loading.value = false;
}
}
watch(date, load, { immediate: true });
const addDays = (d: string, n: number) => {
const x = noon(d);
x.setDate(x.getDate() + n);
return x.toLocaleDateString("en-CA");
};
const trendDates = (selected: string) => {
let end = selected;
for (let i = 0; i < TREND_DAYS / 2 && end < today(); i++) end = addDays(end, 1);
return Array.from({ length: TREND_DAYS }, (_, i) => addDays(end, i - TREND_DAYS + 1))
.filter(d => d !== selected && d <= today());
};
const trendDays = computed(() => {
// Runs up to a week past the selected day, but never past today.
let end = date.value;
@@ -57,16 +75,7 @@ const trendDays = computed(() => {
return Array.from({ length: TREND_DAYS }, (_, i) => addDays(end, i - TREND_DAYS + 1))
.map(d => ({ date: d, sum: history[d] ?? null }));
});
const pending = new Set<string>();
watch(() => trendDays.value.map(d => d.date), days => {
for (const d of days) {
if (d in history || d === date.value || pending.has(d)) continue;
pending.add(d);
api<Summary>("GET", "summary/daily?date=" + d)
.then(s => { history[d] = s; }, () => {})
.finally(() => pending.delete(d));
}
}, { immediate: true });
watch(date, load, { immediate: true });
const shift = (days: number) => { date.value = addDays(date.value, days); };
const slots = computed(() => seriesSlots(sum.value?.totals ?? []));
@@ -81,7 +90,9 @@ const goalsMet = computed(() => {
const kinds = computed(() => Object.entries(sum.value?.by_kind ?? {}).sort((a, b) => b[1] - a[1]));
const labels = computed(() => [...sum.value?.totals ?? []].sort((a, b) => b.seconds - a.seconds).slice(0, 15));
const timeline = computed(() => activities.value.filter(a => a.duration_s >= 60)
.filter(a => activityKind.value === "all" || a.kind === activityKind.value)
.sort((a, b) => +new Date(b.started_at) - +new Date(a.started_at)));
const activityKinds = computed(() => [...new Set(activities.value.map(a => a.kind))].sort());
const time = (t: string) => new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const pct = (v: number, max: number) => `${v / (max || 1) * 100}%`;
@@ -93,7 +104,7 @@ const meter = (g: Summary["goals"][number]) => {
</script>
<template>
<div class="row spread">
<div class="row spread dashboard-head">
<h1>{{ title }}</h1>
<div class="row">
<button aria-label="Previous day" @click="shift(-1)">‹</button>
@@ -103,8 +114,8 @@ const meter = (g: Summary["goals"][number]) => {
</div>
</div>
<p class="muted">
<span v-if="error" class="err">{{ error }}</span>
<p class="muted status" role="status" aria-live="polite" aria-atomic="true">
<span v-if="error" class="err" role="alert">{{ error }}</span>
<template v-else-if="loading">Loading…</template>
<template v-else-if="activities.length >= LIMIT">Timeline shows the first {{ LIMIT }} activities.</template>
</p>
@@ -118,7 +129,7 @@ const meter = (g: Summary["goals"][number]) => {
</div>
<section class="card"><h2>Goals</h2><div class="tablewrap"><table>
<tr v-for="(g, i) in sum.goals" :key="i">
<caption class="sr-only">Goals for {{ title }}</caption><thead><tr><th scope="col">Goal</th><th scope="col">Actual</th><th scope="col">Status</th></tr></thead><tbody><tr v-for="(g, i) in sum.goals" :key="i">
<td class="label">{{ kindName(g.kind) }}{{ g.label ? " · " + g.label : "" }}
<span class="muted">{{ g.op }} {{ dur(g.target_s) }}</span>
<div class="meter" :class="g.met ? 'ok' : 'bad'">
@@ -127,8 +138,7 @@ const meter = (g: Summary["goals"][number]) => {
</div></td>
<td class="num">{{ dur(g.actual_s) }}</td>
<td class="num" :class="g.met ? 'ok' : 'bad'">{{ g.met ? "✓ met" : "✗ missed" }}</td>
</tr>
<tr v-if="!sum.goals.length"><td class="muted">No goals yet. See <RouterLink to="/setup#goals">Setup</RouterLink>.</td></tr>
</tr><tr v-if="!sum.goals.length"><td colspan="3" class="muted">No goals yet. See <RouterLink to="/setup#goals">Setup</RouterLink>.</td></tr></tbody>
</table></div></section>
<section class="card"><h2>Day at a glance</h2>
@@ -143,31 +153,31 @@ const meter = (g: Summary["goals"][number]) => {
<GoalHistory :days="trendDays" :selected="date" @select="date = $event" />
</section>
<section class="card"><h2>By kind</h2><div class="tablewrap"><table>
<section class="card"><h2>By kind</h2><div class="tablewrap"><table><caption class="sr-only">Time by activity kind</caption><thead><tr><th scope="col">Kind</th><th scope="col">Time</th></tr></thead><tbody>
<tr v-for="[k, s] in kinds" :key="k">
<td class="label">{{ kindName(k) }}<div class="bar" :style="{ width: pct(s, kinds[0][1]) }"></div></td>
<td class="num">{{ dur(s) }}</td>
</tr>
<tr v-if="!kinds.length"><td class="muted">Nothing recorded.</td></tr>
<tr v-if="!kinds.length"><td colspan="2" class="muted">Nothing recorded.</td></tr></tbody>
</table></div></section>
<section class="card"><h2>Top labels</h2><div class="tablewrap"><table>
<section class="card"><h2>Top labels</h2><div class="tablewrap"><table><caption class="sr-only">Top labels by time</caption><thead><tr><th scope="col">Label</th><th scope="col">Time</th></tr></thead><tbody>
<tr v-for="t in labels" :key="t.kind + '\0' + t.label">
<td class="label">{{ t.label || "—" }} <span class="badge">{{ kindName(t.kind) }}</span>
<div class="bar" :style="{ width: pct(t.seconds, labels[0].seconds), background: slotColor(slots.get(seriesKey(t.kind, t.label))) }"></div></td>
<td class="num">{{ dur(t.seconds) }}</td>
</tr>
<tr v-if="!labels.length"><td class="muted">Nothing recorded.</td></tr>
<tr v-if="!labels.length"><td colspan="2" class="muted">Nothing recorded.</td></tr></tbody>
</table></div></section>
<section class="card"><h2>Timeline</h2><div class="tablewrap"><table>
<tr v-for="(a, i) in timeline" :key="i">
<section class="card"><div class="row spread section-head"><h2>Activity details</h2><label class="filter">Filter <select v-model="activityKind" aria-label="Filter activity details"><option value="all">All activity</option><option v-for="k in activityKinds" :key="k" :value="k">{{ kindName(k) }}</option></select></label></div><div class="tablewrap"><table><caption class="sr-only">Activities lasting at least one minute</caption><thead><tr><th scope="col">Time</th><th scope="col">Activity</th><th scope="col">Duration</th></tr></thead><tbody>
<tr v-for="a in timeline" :key="a.id">
<td class="time">{{ time(a.started_at) }}–{{ time(a.ended_at) }}</td>
<td class="label">{{ a.label || a.kind }} <span class="badge">{{ kindName(a.kind) }}</span>
<div v-if="a.attrs?.title" class="muted small-text">{{ a.attrs.title }}</div></td>
<td class="num">{{ dur(a.duration_s) }}</td>
</tr>
<tr v-if="!timeline.length"><td class="muted">No activities of a minute or longer.</td></tr>
<tr v-if="!timeline.length"><td colspan="3" class="muted">No matching activities of a minute or longer.</td></tr></tbody>
</table></div></section>
</div>
</template>
+201 -15
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { api, type Device } from "../api";
import { api, type AdminGoal, type Device, type NotificationSettings, type Report } from "../api";
import CodeBlock from "../components/CodeBlock.vue";
import Collector from "../components/Collector.vue";
import KeyBox from "../components/KeyBox.vue";
@@ -14,6 +14,17 @@ const loaded = ref(false);
const status = ref<{ msg: string; cls?: string }>({ msg: "" });
const active = computed(() => devices.value.filter(d => !d.revoked_at));
const revoked = computed(() => devices.value.filter(d => d.revoked_at));
const goals = ref<AdminGoal[]>([]);
const goalLoaded = ref(false);
const goalForm = reactive({ kind: "tab_focus", label: "", op: ">=", target: "30m" });
const editingGoal = ref<number | null>(null);
const goalBusy = ref(false);
const pendingRevoke = ref<Device | null>(null);
const revokeCancel = ref<HTMLButtonElement>();
const reports = ref<Report[]>([]);
const notifications = reactive<NotificationSettings>({ ntfy_server: "https://ntfy.sh", ntfy_topic: "", enabled: false, retention_days: 0 });
const purgeBefore = ref(new Date(Date.now() - 90 * 86400000).toISOString().slice(0, 10));
const privacyBusy = ref(false);
// Which collector sections are open: the browser's by default, and the one a
// #section in the URL names.
@@ -45,6 +56,24 @@ function ago(t?: string | null) {
return new Date(t).toLocaleDateString([], { day: "numeric", month: "short", year: "numeric" });
}
function deviceStatus(d: Device) {
if (d.revoked_at) return { label: "Revoked", cls: "bad" };
if (!d.last_seen_at) return { label: "Never seen", cls: "warn" };
const age = Date.now() - +new Date(d.last_seen_at);
return age < 2 * 86400000 ? { label: "Healthy", cls: "good" } : { label: "Stale", cls: "warn" };
}
function parseDuration(value: string) {
const m = value.trim().match(/^(?:(\d+(?:\.\d+)?)h)?\s*(?:(\d+(?:\.\d+)?)m)?\s*(?:(\d+(?:\.\d+)?)s)?$/i);
if (!m || !m[1] && !m[2] && !m[3]) return 0;
return Math.round((Number(m[1] || 0) * 3600) + (Number(m[2] || 0) * 60) + Number(m[3] || 0));
}
function formatDuration(s: number) {
const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60), sec = s % 60;
return h ? `${h}h${m ? ` ${m}m` : ""}` : m ? `${m}m${sec ? ` ${sec}s` : ""}` : `${sec}s`;
}
async function loadDevices() {
try {
({ devices: devices.value } = await api<{ devices: Device[] }>("GET", "devices"));
@@ -53,7 +82,26 @@ async function loadDevices() {
status.value = { msg: (e as Error).message, cls: "err" };
}
}
onMounted(loadDevices);
async function loadGoals() {
try {
const out = await api<{ goals: AdminGoal[] }>("GET", "goals");
goals.value = out.goals;
goalLoaded.value = true;
} catch (e) {
status.value = { msg: (e as Error).message, cls: "err" };
}
}
async function loadAdminData() {
try {
const [notification, reportList] = await Promise.all([
api<{ settings: NotificationSettings }>("GET", "notifications/status"),
api<{ reports: Report[] }>("GET", "reports"),
]);
Object.assign(notifications, notification.settings);
reports.value = reportList.reports;
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
}
onMounted(() => { loadDevices(); loadGoals(); loadAdminData(); });
// A readable name that isn't taken yet (names stay taken after revoking).
function suggestName(kind: string) {
@@ -93,36 +141,124 @@ async function create() {
}
async function revoke(name: string) {
if (!confirm(`Revoke ${name}? Its collector will stop being able to upload.`)) return;
pendingRevoke.value = devices.value.find(d => d.name === name) || null;
}
watch(pendingRevoke, value => { if (value) nextTick(() => revokeCancel.value?.focus()); });
async function confirmRevoke() {
const device = pendingRevoke.value;
if (!device) return;
try {
await api("DELETE", "devices/" + encodeURIComponent(name));
status.value = { msg: `Revoked ${name}.`, cls: "ok" };
await api("DELETE", "devices/" + encodeURIComponent(device.name));
status.value = { msg: `Revoked ${device.name}.`, cls: "ok" };
pendingRevoke.value = null;
loadDevices();
} catch (e) {
status.value = { msg: (e as Error).message, cls: "err" };
}
}
async function addGoal() {
const target_s = parseDuration(goalForm.target);
if (!goalForm.kind.trim() || target_s <= 0) { status.value = { msg: "Enter a kind and a duration such as 30m or 1h.", cls: "err" }; return; }
goalBusy.value = true;
try {
const body = { kind: goalForm.kind.trim(), label: goalForm.label.trim(), op: goalForm.op, target_s };
if (editingGoal.value === null) {
const out = await api<AdminGoal>("POST", "goals", body);
goals.value.push(out);
status.value = { msg: "Goal added.", cls: "ok" };
} else {
const out = await api<AdminGoal>("PUT", "goals/" + encodeURIComponent(String(editingGoal.value)), body);
goals.value = goals.value.map(g => g.id === editingGoal.value ? out : g);
status.value = { msg: "Goal updated.", cls: "ok" };
}
resetGoalForm();
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
finally { goalBusy.value = false; }
}
function editGoal(goal: AdminGoal) {
editingGoal.value = goal.id;
goalForm.kind = goal.kind;
goalForm.label = goal.label;
goalForm.op = goal.op;
goalForm.target = formatDuration(goal.target_s).replace(" ", "");
}
function resetGoalForm() {
editingGoal.value = null;
goalForm.kind = "tab_focus";
goalForm.label = "";
goalForm.op = ">=";
goalForm.target = "30m";
}
async function removeGoal(goal: AdminGoal) {
try {
await api("DELETE", "goals/" + encodeURIComponent(String(goal.id)));
goals.value = goals.value.filter(g => g.id !== goal.id);
status.value = { msg: "Goal removed.", cls: "ok" };
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
}
async function saveNotifications() {
privacyBusy.value = true;
try {
Object.assign(notifications, await api<NotificationSettings>("PUT", "notifications/config", notifications));
status.value = { msg: "Notification and retention settings saved.", cls: "ok" };
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
finally { privacyBusy.value = false; }
}
async function purgeData() {
if (!purgeBefore.value) return;
privacyBusy.value = true;
try {
const before = new Date(purgeBefore.value + "T00:00:00").toISOString();
const out = await api<{ deleted: number }>("POST", "privacy/purge?before=" + encodeURIComponent(before));
status.value = { msg: `Deleted ${out.deleted} records before ${purgeBefore.value}.`, cls: "ok" };
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
finally { privacyBusy.value = false; }
}
const setupProgress = computed(() => {
const done = [active.value.length > 0, goals.value.length > 0, active.value.some(d => d.last_seen_at)].filter(Boolean).length;
return { done, total: 3 };
});
</script>
<template>
<h1>Setup</h1>
<p class="muted">Each collector uploads to <code>{{ base }}</code> with its own API key. Open a collector below and click <b>Generate key</b>; the key is filled into its steps. A key is shown only once.</p>
<section class="card" aria-labelledby="progress-title">
<div class="row spread"><h2 id="progress-title">Getting started</h2><span class="badge">{{ setupProgress.done }}/{{ setupProgress.total }} complete</span></div>
<ol class="setup-progress">
<li :class="{ ok: active.length }"><b>{{ active.length ? "Device created" : "Create a device key" }}</b><span class="muted"> Generate a key below, then follow that collector's instructions.</span></li>
<li :class="{ ok: goals.length }"><b>{{ goals.length ? "Goals configured" : "Add a daily goal" }}</b><span class="muted"> Optional targets are managed here and appear on the dashboard.</span></li>
<li :class="{ ok: active.some(d => d.last_seen_at) }"><b>{{ active.some(d => d.last_seen_at) ? "First upload received" : "Check device health" }}</b><span class="muted"> A healthy device has uploaded in the last two days.</span></li>
</ol>
</section>
<section class="card">
<div class="row spread"><h2>Devices</h2></div>
<div class="tablewrap"><table>
<tr v-if="!loaded"><td class="muted">Loading…</td></tr>
<template v-else>
<tr><th>Name</th><th>Kind</th><th>Last upload</th><th></th></tr>
<caption class="sr-only">Collector devices and upload health</caption>
<thead><tr><th scope="col">Name</th><th scope="col">Kind</th><th scope="col">Health</th><th scope="col">Last upload</th><th scope="col"><span class="sr-only">Actions</span></th></tr></thead>
<tbody v-if="!loaded"><tr><td colspan="5" class="muted">Loading…</td></tr></tbody>
<tbody v-else>
<tr v-for="d in active" :key="d.name">
<td class="label">{{ d.name }}</td>
<td><span class="badge">{{ d.kind }}</span></td>
<td><span class="status-dot" :class="deviceStatus(d).cls"></span>{{ deviceStatus(d).label }}</td>
<td class="time">{{ ago(d.last_seen_at) }}</td>
<td class="num"><button class="small" @click="revoke(d.name)">Revoke</button></td>
</tr>
<tr v-if="!active.length"><td colspan="4" class="muted">No devices yet.</td></tr>
<tr v-if="revoked.length"><td colspan="4" class="muted small-text">{{ revoked.length }} revoked: {{ revoked.map(d => d.name).join(", ") }}</td></tr>
</template>
<tr v-if="!active.length"><td colspan="5" class="muted">No devices yet.</td></tr>
<tr v-if="revoked.length"><td colspan="5" class="muted small-text">{{ revoked.length }} revoked: {{ revoked.map(d => d.name).join(", ") }}</td></tr>
</tbody>
</table></div>
<form class="row" style="margin-top:12px" @submit.prevent="create">
<select v-model="kindSel" aria-label="Kind">
@@ -137,6 +273,11 @@ async function revoke(name: string) {
</form>
<KeyBox v-if="issued?.slot === 'create'" :key="issued.key" :device="issued.device" :api-key="issued.key" />
<p class="small-text" :class="status.cls">{{ status.msg }}</p>
<div v-if="pendingRevoke" class="confirm" role="alertdialog" aria-modal="true" aria-labelledby="revoke-title" aria-describedby="revoke-copy" @keydown.esc="pendingRevoke = null">
<h3 id="revoke-title">Revoke {{ pendingRevoke.name }}?</h3>
<p id="revoke-copy">This stops the collector from uploading. Existing data is not deleted, but the key cannot be used again.</p>
<div class="row"><button ref="revokeCancel" class="small" @click="pendingRevoke = null">Keep device</button><button class="small danger" @click="confirmRevoke">Revoke device</button></div>
</div>
</section>
<Collector id="browser" title="Browser" hint="Violentmonkey userscript · time per site" v-model:open="open.browser">
@@ -144,7 +285,7 @@ async function revoke(name: string) {
<button class="primary" :disabled="busy === 'browser'" @click="generate('browser', '', 'browser')">Generate key for this browser</button>
<KeyBox v-if="issued?.slot === 'browser'" :key="issued.key" :device="issued.device" :api-key="issued.key" />
<ol>
<li>Install Violentmonkey: <a href="https://addons.mozilla.org/firefox/addon/violentmonkey/" target="_blank" rel="noopener">Firefox</a> · <a href="https://chromewebstore.google.com/detail/violentmonkey/jinjaccalgkegednnccohejagnlnfdag" target="_blank" rel="noopener">Chrome / Chromium</a></li>
<li>Install Violentmonkey: <a href="https://addons.mozilla.org/firefox/addon/violentmonkey/" target="_blank" rel="noopener">Firefox <span class="sr-only">(opens in a new tab)</span></a> · <a href="https://chromewebstore.google.com/detail/violentmonkey/jinjaccalgkegednnccohejagnlnfdag" target="_blank" rel="noopener">Chrome / Chromium <span class="sr-only">(opens in a new tab)</span></a></li>
<li>Open <a :href="base + '/tracker.user.js'">{{ base }}/tracker.user.js</a> and click <b>Install</b>. Violentmonkey checks this URL for updates.</li>
<li>Click the Violentmonkey toolbar icon, then <b>Activity Tracker → Set server and API key</b>. Enter the server and key:
<CodeBlock>{{ base }}</CodeBlock>
@@ -223,10 +364,55 @@ listener {
</Collector>
<Collector id="goals" title="Goals" hint="daily targets on the dashboard" v-model:open="open.goals">
<p>Managed on the server. An empty label matches every label of that kind.</p>
<p>Daily targets are managed here. An empty label matches every label of that kind. Durations accept values such as <code>30m</code>, <code>1h</code>, or <code>1h 30m</code>.</p>
<form class="goal-form" @submit.prevent="addGoal">
<label>Kind<input v-model="goalForm.kind" required placeholder="tab_focus"></label>
<label>Label <span class="muted">(optional)</span><input v-model="goalForm.label" placeholder="youtube.com"></label>
<label>Rule<select v-model="goalForm.op"><option value=">=">At least</option><option value="<=">At most</option></select></label>
<label>Target per day<input v-model="goalForm.target" required placeholder="30m"></label>
<div class="row"><button class="primary" :disabled="goalBusy">{{ goalBusy ? "Saving…" : editingGoal === null ? "Add goal" : "Save goal" }}</button><button v-if="editingGoal !== null" type="button" class="small" @click="resetGoalForm">Cancel</button></div>
</form>
<div class="tablewrap" v-if="goalLoaded || goals.length">
<table>
<caption class="sr-only">Configured daily goals</caption>
<thead><tr><th scope="col">Kind</th><th scope="col">Label</th><th scope="col">Rule</th><th scope="col">Target</th><th scope="col"><span class="sr-only">Actions</span></th></tr></thead>
<tbody><tr v-for="goal in goals" :key="goal.id"><td>{{ goal.kind }}</td><td>{{ goal.label || "Any label" }}</td><td>{{ goal.op === ">=" ? "At least" : "At most" }}</td><td>{{ formatDuration(goal.target_s) }}</td><td class="num"><button class="small" @click="editGoal(goal)">Edit</button> <button class="small" @click="removeGoal(goal)">Remove</button></td></tr><tr v-if="!goals.length"><td colspan="5" class="muted">No goals configured.</td></tr></tbody>
</table>
</div>
<CodeBlock>docker exec activity-tracker tracker goal add --kind tab_focus --label youtube.com --op '&lt;=' --target 1h
docker exec activity-tracker tracker goal add --kind walk --op '&gt;=' --target 30m
docker exec activity-tracker tracker goal list
docker exec activity-tracker tracker goal rm --id 2</CodeBlock>
docker exec activity-tracker tracker goal rm --id 2</CodeBlock>
</Collector>
<section class="card" aria-labelledby="data-title">
<div class="row spread"><h2 id="data-title">Data and notifications</h2><span class="badge">Admin only</span></div>
<p class="muted small-text">Export your activity data, configure optional goal nudges, and control how long records are retained.</p>
<div class="row data-actions">
<a class="button-like" :href="base + '/api/v1/activities/export?format=csv'" download>Export activity CSV</a>
<a class="button-like" :href="base + '/api/v1/activities/export?format=json'" download>Export activity JSON</a>
</div>
<form class="settings-form" @submit.prevent="saveNotifications">
<label>ntfy server<input v-model="notifications.ntfy_server" placeholder="https://ntfy.sh"></label>
<label>Topic<input v-model="notifications.ntfy_topic" placeholder="private-topic"></label>
<label class="check"><input v-model="notifications.enabled" type="checkbox"> Enable goal nudges</label>
<label>Retention days <span class="muted">(0 = keep forever)</span><input v-model.number="notifications.retention_days" type="number" min="0"></label>
<button class="primary" :disabled="privacyBusy">Save settings</button>
</form>
<div class="privacy-tools">
<h3>Delete old records</h3>
<p class="muted small-text">This permanently deletes activities, samples, and reports before the selected date.</p>
<form class="row" @submit.prevent="purgeData">
<label>Delete before <input v-model="purgeBefore" type="date" required></label>
<button class="danger" :disabled="privacyBusy">Delete records</button>
</form>
</div>
<div v-if="reports.length" class="report-list">
<h3>Saved insights</h3>
<article v-for="report in reports.slice(0, 5)" :key="report.id" class="report">
<div class="row spread"><b>{{ report.model }}</b><span class="muted small-text">{{ new Date(report.period_start).toLocaleDateString() }}–{{ new Date(report.period_end).toLocaleDateString() }}</span></div>
<p>{{ report.body }}</p>
</article>
</div>
</section>
</template>