Files
ccp/README.md
T
adamfandClaude Opus 5.5 1dad3583b1
Test and publish / test (push) Successful in 19s
Test and publish / publish (push) Successful in 31s
CI: roll out into /home/adamf/deploy/stpweb
The site's deploy directory moved from web_server to stpweb with the repo
rename, so the publish job's roll-out step failed after pushing the image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 15:19:17 +00:00

15 KiB

Activity Tracker

A self-hosted service that records where your time goes: desktop apps, browser tabs, time at home and away, and desk/bed presence. Each device runs a small collector that uploads timestamped intervals to a Go API backed by PostgreSQL. A daily summary checks your totals against goals such as "≤ 1h of YouTube" or "≥ 1h outside".

[hypr-agent] [browser ext] [webcam agent] [iOS Shortcuts]
      └────────── HTTPS + Bearer API key (batched JSON) ─────────┘
                               │
                    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 stores point metrics such as step counts. Collectors generate an id for each event, so re-uploading a batch never creates duplicates.

Status

Collector Status
Hyprland (cmd/hypr-agent) ✅ built
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
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

make up                 # builds the image and starts tracker + a dev Postgres on :8080 / :5432 (AUTH_MODE=dev: no login)
curl localhost:8080/readyz

In production, run only the image and point it at your own database:

docker build -f deploy/Dockerfile -t activity-tracker .
docker run -d -p 8080:8080 \
  -e DATABASE_URL='postgres://user:pass@db-host:5432/tracker' \
  -e TRACKER_TZ='Europe/London' \
  activity-tracker
Env var Default
DATABASE_URL (required) PostgreSQL connection string
LISTEN_ADDR :8080
AUTO_MIGRATE true Apply migrations on startup. Set it to false to run tracker migrate yourself
TRACKER_TZ UTC Timezone that defines "a day" in summaries
AUTH_MODE forward forward gates the dashboard on the main site's admin login (see Dashboard and auth). dev admits everyone and requires DEV_MODE=true
AUTH_VALIDATE_URL http://backend:8080/auth/validate-admin The site backend's admin check

Put the service behind your reverse proxy (Caddy, Traefik and so on) for TLS, because API keys are sent as bearer tokens.

Deploying to stpvm

Pushing to main on Gitea (adamf/ccp) runs .gitea/workflows/ci.yaml on stpvm's runner. The workflow runs the tests, pushes adam-french.co.uk/adamf/activity-tracker:<sha> and :latest to Gitea's container registry, and recreates the activity-tracker service in the stpweb stack. The service is served at https://www.adam-french.co.uk/tracker/, so set collectors to TRACKER_URL=https://www.adam-french.co.uk/tracker. Use the www host because the apex redirect would turn uploaded POSTs into GETs. To hold a version, set ACTIVITY_TRACKER_IMAGE_TAG to a sha in stpweb's .env.

The repo needs the REGISTRY_USER and REGISTRY_TOKEN Actions secrets, the same ones job-tracker uses. Create its database role once on the host:

docker exec db psql -U "$POSTGRES_USER" -d postgres \
  -c "CREATE ROLE tracker LOGIN PASSWORD '…'" -c "CREATE DATABASE tracker OWNER tracker"

Then run the admin commands with docker exec activity-tracker tracker apikey create ….

Admin commands

The admin commands are built into the same binary. Inside the container, run them with docker exec <container> tracker ….

tracker apikey create --name laptop-hypr --kind hyprland   # prints the key once
tracker apikey list
tracker apikey revoke --name laptop-hypr

tracker goal add --kind tab_focus --label youtube.com --op '<=' --target 1h
tracker goal add --kind walk --op '>=' --target 30m       # empty label = any walk
tracker goal list
tracker goal rm --id 2

Dashboard and auth

The dashboard (/) and the setup page (/setup) are one Vue app (web/), built into the Go binary. They have no login of their own. As in job-tracker, the tracker borrows the main site's session. It forwards the browser's cookies to the site backend's GET /auth/validate-admin and treats a 2xx as admin (internal/auth). A visitor who isn't signed in is sent to the site's /admin/login?redirect=/tracker/, which returns them afterwards. A "yes" is cached for 30 seconds per cookie, so signing out takes up to 30 seconds to reach the tracker. If the backend refreshes an expired token, its new cookies are passed back to the browser.

Signed in, the dashboard shows every device's data without asking for a key. The setup page has step-by-step instructions for each collector, with your server URL filled in. It also lists devices and creates and revokes their API keys, so you don't need docker exec for keys. Each collector's section has a Generate key button that names the device (for example firefox, or hyprland-2 if that's taken), copies the key to the clipboard and fills it into that collector's steps.

Collectors never use the site login. Each one sends its own bearer key.

API

Auth Meaning
key Authorization: Bearer <key> from tracker apikey create or the setup page
admin the main site's admin session cookies
Method Path Auth Accepted kinds
POST /api/v1/desktop/events key app_focus, idle, locked
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)
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/notifications/goals/check admin evaluate today's goals and send ntfy alerts for unmet goals behind pace
GET /api/v1/health/collectors admin collector last-seen age/status and activity/sample ingestion counts
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

The event batch format is shared by all */events endpoints. A batch holds at most 1000 events.

{"events": [
  {"id": "3f2a…", "kind": "app_focus", "label": "kitty",
   "started_at": "2026-10-14T09:00:00Z", "ended_at": "2026-10-14T09:42:10Z",
   "attrs": {"title": "nvim"}}
]}

The response is {"received": 1, "inserted": 1}. If inserted is lower than received, the missing events were duplicates.

Hyprland agent

The agent follows activewindow events on Hyprland's event socket and records one interval for each window class and title. Focus that lasts under 2s is dropped. hypridle hooks mark idle and locked time. Pending events are kept in $XDG_STATE_HOME/hypr-agent/buffer.jsonl and uploaded every minute, so nothing is lost while the server is unreachable.

tracker apikey create --name laptop-hypr --kind hyprland    # on the server
make install-agent                                          # builds into ~/.local/bin and installs the user unit
mkdir -p ~/.config/hypr-agent
cat > ~/.config/hypr-agent/env <<EOF
TRACKER_URL=https://tracker.example.com
TRACKER_API_KEY=trk_...
# HYPR_AGENT_TITLES=false            # don't send window titles at all
# HYPR_AGENT_REDACT=(?i)bank|private  # replace matching titles with [redacted]
EOF
chmod 600 ~/.config/hypr-agent/env
systemctl --user enable --now hypr-agent

To record idle and locked time, add these to ~/.config/hypr/hypridle.conf:

general {
    lock_cmd = hypr-agent lock; pidof hyprlock || hyprlock
    unlock_cmd = hypr-agent unlock
}

listener {
    timeout = 300
    on-timeout = hypr-agent idle
    on-resume = hypr-agent resume
}

Browser

The browser collector is a Violentmonkey userscript served by the tracker itself. It runs in every tab and records a tab_focus interval, labelled with the hostname (www. stripped, so goals use youtube.com), only while that tab is the selected tab of the focused browser window. Focus that lasts under 2s is dropped. The interval ends after 5 minutes without mouse or keyboard input, unless a video or audio element is playing. Time spent asleep or suspended is never counted.

The setup page has these steps with your URL filled in.

  1. Create a key with kind browser on the setup page, or with tracker apikey create --name laptop-firefox --kind browser. Use one key per browser.
  2. Install Violentmonkey and open https://www.adam-french.co.uk/tracker/tracker.user.js. Violentmonkey offers to install the script and later checks that URL for updates.
  3. From the Violentmonkey toolbar menu, choose Set server and API key. Enter https://www.adam-french.co.uk/tracker and the key.
  4. Other menu commands toggle full URLs (attrs.url, which also splits intervals per page) and page titles (attrs.title), set a regexp of hosts to ignore, change the idle timeout, and show the queue and last upload result.

Closed intervals are queued in the script's storage and uploaded every minute by one tab at a time. If a tab is closed or crashes mid-interval, another tab recovers its last checkpoint (at most 5s lost). It runs on every http/https page and on local file:// pages, which are labelled file (in Chrome, enable Allow access to file URLs for Violentmonkey). It can't see browser pages such as about:, chrome:// or the new tab page, extension stores, or the built-in PDF viewer, so time there isn't recorded. The Hyprland agent still counts it as browser app_focus.

iPhone location

The free Shortcuts app reports when you arrive at and leave each place. Apple doesn't let you import automations, so you set them up on the phone. One shared shortcut holds the URL and key, so each automation is only two actions. The setup page shows the same steps with your key and place names filled in.

  1. Create a key with kind location on the setup page.
  2. Once: make a shortcut named Tracker with one Get Contents of URL action. The URL is https://www.adam-french.co.uk/tracker/api/v1/location/ followed by the Shortcut Input variable, the Method is POST, and the Header is Authorization: Bearer <key>.
  3. For each place, make two personal automations (iOS 17 or later, Run Immediately). The first is Arrive at the address, with a Text action arrive/<place> followed by Run Shortcut → Tracker. The second is the same for Leave, with leave/<place>.

The endpoint is POST /api/v1/location/{arrive,leave}/{place}. ?place= and a {"place"} body also work, and with no place given it means home.

Each device has one open place interval at a time, labelled with the place (lower-cased; home if none is given) or away between places. An arrive or leave closes the open interval and starts the next one. The open interval is stored with ended_at = started_at (marked attrs.open), and queries and summaries count it as running until now. Arriving where you already are does nothing, and a leave for a place you aren't in is ignored, so duplicate or late geofence triggers can't corrupt the timeline. A missed trigger stretches the previous interval until the next one arrives.

To track time outside: tracker goal add --kind place --label away --op '>=' --target 1h.

Development

make check              # everything CI runs: gofmt, vet, staticcheck, all tests (-race), web typecheck. Needs `make up`
make test               # unit tests only; database tests skip themselves
make run                # build the app, then run the server locally against the compose Postgres
make web-dev            # with `make run` going: Vite on :5173 with hot reload, proxying /api to :8080

The dashboard is a Vue 3 + Vite app in web/. make web (and make build, make run, the Docker build) builds it into internal/web/dist/app, which the binary embeds. That directory isn't committed, so a plain go build serves a "not built" page at / but everything else works, and go test needs no Node.

Database tests call testdb.New(t), which creates a fresh, migrated database for that test on the server in TEST_DATABASE_URL and drops it afterwards. Tests never touch your data and can run in parallel. CI starts a throwaway Postgres for them.

To add a collector that uploads intervals:

  1. Add a Spec (source and accepted kinds) in internal/ingest/ingest.go.
  2. Route POST /<name>/events to it in internal/api/api.go.
  3. Add it to the API table above, and to the kind picker and a <Collector> section in web/src/views/Setup.vue.
  4. If the kind needs a friendlier name or a fixed timeline lane, add it to KINDS in web/src/api.ts and ORDER in web/src/components/DayTimeline.vue.

Layout: cmd/tracker (server and admin CLI), cmd/hypr-agent, internal/{api,auth,ingest,store,summary,migrations,config,web,testdb} (internal/web/tracker.user.js is the browser collector), web/ (dashboard app), internal/agent/hypr, deploy/.

Roadmap

  1. Webcam presence agent. Detection will run on the device and only intervals will be uploaded; frames never leave the machine.
  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.