Add activity tracker server, Hyprland agent and Gitea image publishing
Test and publish / test (push) Successful in 2m38s
Test and publish / publish (push) Failing after 2m30s

The Go API on PostgreSQL ingests desktop, browser, presence, manual and
Health Auto Export events and serves activities and daily goal summaries.
The Hyprland agent records window focus, idle and lock intervals.

The CI workflow publishes adam-french.co.uk/adamf/activity-tracker to the
Gitea registry and rolls the web_server stack onto it. The image probes
itself through a new `tracker healthcheck` command, because distroless
has no wget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 20:38:12 +01:00
co-authored by Claude Opus 5.5
parent 0cbbb76dee
commit f4ce04875c
29 changed files with 2810 additions and 0 deletions
+165
View File
@@ -0,0 +1,165 @@
# Activity Tracker
A self-hosted service that records where your time goes: desktop apps, browser tabs, walks and workouts, 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] [Health Auto Export]
└────────── 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`. Point metrics such as step counts go in `samples`. Collectors generate an `id` for each event, so re-uploading a batch never creates duplicates.
## Status
| Collector | Status |
|---|---|
| Hyprland (`cmd/hypr-agent`) | ✅ built |
| Apple Health (Health Auto Export → `/health/hae`) | ✅ endpoint built; configure the app |
| Browser extension (`/browser/events`) | endpoint ready, extension not yet written |
| Webcam presence (`/presence/events`) | endpoint ready, agent not yet written |
| AI analysis (`reports` table) | planned |
## Running the server
```sh
make up # builds the image and starts tracker + a dev Postgres on :8080 / :5432
curl localhost:8080/readyz
```
In production, run only the image and point it at your own database:
```sh
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 |
Put the service behind your reverse proxy (Caddy, Traefik and so on) for TLS, because API keys are sent as bearer tokens.
### Deploying to stppi
Pushing to `main` on Gitea (`adamf/ccp`) runs `.gitea/workflows/ci.yaml` on the Pi'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 web_server 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 web_server'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 Pi:
```sh
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 …`.
```sh
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
```
## API
All `/api/v1` routes require `Authorization: Bearer <key>`.
| Method | Path | Accepted kinds |
|---|---|---|
| POST | `/api/v1/desktop/events` | `app_focus`, `idle`, `locked` |
| POST | `/api/v1/browser/events` | `tab_focus`, `idle` |
| POST | `/api/v1/presence/events` | `at_desk`, `in_bed`, `away` |
| POST | `/api/v1/manual/events` | any |
| POST | `/api/v1/health/hae` | Health Auto Export JSON. Workouts and sleep become activities; other metrics become samples |
| GET | `/api/v1/activities?from=&to=&source=&kind=&limit=` | RFC3339 times; defaults to the last 24h |
| GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | totals per label and kind, plus goal results |
| GET | `/healthz`, `/readyz` | no auth |
The event batch format is shared by all `*/events` endpoints. A batch holds at most 1000 events.
```json
{"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.
```sh
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`:
```ini
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
}
```
## Apple Health
In the Health Auto Export iOS app, create a **REST API** automation with these settings:
- URL: `https://tracker.example.com/api/v1/health/hae`
- Header: `Authorization: Bearer <key>`. Create the key with `--kind health`.
- Format: JSON
- Data: Workouts, plus metrics such as Step Count and Sleep Analysis
- Sync cadence: hourly
Walking and hiking workouts are stored with the kind `walk`, running workouts as `run`, and any other workout as `workout`.
## Development
```sh
make test # unit tests
make up && make test-integration # also runs the API tests against the compose Postgres (truncates its tables!)
make run # run the server locally against the compose Postgres
```
Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,ingest,store,summary,migrations,config}`, `internal/agent/hypr`, `deploy/`.
## Roadmap
1. Browser extension (MV3, Firefox and Chromium). It will send hostnames by default and full URLs only if you opt in.
2. Webcam presence agent. Detection will run on the device and only intervals will be uploaded; frames never leave the machine.
3. Nudges: push notifications through ntfy when a goal is at risk during the day.
4. Location: an OwnTracks or Home Assistant geofence will provide reliable "time outside" intervals.
5. 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`.