Move the dashboard and setup pages to a Vue SPA
Test and publish / test (push) Successful in 1m28s
Test and publish / publish (push) Successful in 3m30s

The pages are now a Vue 3 + Vite + TypeScript app in web/, built into
internal/web/dist/app and embedded in the binary. Go still serves
index.html for / and /setup behind the admin gate, plus the hashed
/assets/* (public, cached forever). The router takes its base from the
current URL, so it works under nginx's /tracker/ prefix unchanged.

Only dist/.gitkeep is committed, so go build and go test need no Node;
an unbuilt binary shows a "run make web" page at /. The Dockerfile gains
a Node stage, CI typechecks and builds the app, and make build/run build
it first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 22:06:41 +01:00
co-authored by Claude Opus 5.5
parent 67638cdef0
commit 0be97384fa
26 changed files with 2326 additions and 461 deletions
+2
View File
@@ -1,2 +1,4 @@
.git .git
bin bin
internal/web/dist/app
web/node_modules
+14 -1
View File
@@ -9,7 +9,8 @@
# #
# TWO JOBS # TWO JOBS
# test go vet + go test, as `make test`. The API tests skip themselves # test go vet + go test, as `make test`. The API tests skip themselves
# here: they need TEST_DATABASE_URL, and CI has no Postgres. # here: they need TEST_DATABASE_URL, and CI has no Postgres. Then
# the Vue app's typecheck and build, in a node container.
# publish main only, after test: builds deploy/Dockerfile, pushes it to # publish main only, after test: builds deploy/Dockerfile, pushes it to
# this Gitea's container registry as :<sha> and :latest, then # this Gitea's container registry as :<sha> and :latest, then
# pulls it into the web_server stack (its `activity-tracker` # pulls it into the web_server stack (its `activity-tracker`
@@ -63,6 +64,18 @@ jobs:
golang:1.27 \ golang:1.27 \
sh -c 'go vet ./... && go test ./...' sh -c 'go vet ./... && go test ./...'
# Copies web/ out of the read-only source so node_modules and the
# build output stay in the container.
- name: Web - typecheck and build
shell: bash
run: |
set -eu
docker run --rm \
-v "$SRC":/src:ro \
-v activity_tracker_ci_npm:/root/.npm \
node:24-alpine \
sh -c 'cp -r /src/web /web && cd /web && npm ci && npm run typecheck && npx vite build --outDir /tmp/dist'
- name: Remove the scratch directory - name: Remove the scratch directory
if: always() if: always()
shell: bash shell: bash
+2
View File
@@ -1,2 +1,4 @@
bin/ bin/
*.test *.test
internal/web/dist/app/
web/node_modules/
+11 -3
View File
@@ -1,9 +1,17 @@
COMPOSE := docker compose -f deploy/docker-compose.yml COMPOSE := docker compose -f deploy/docker-compose.yml
DEV_DB := postgres://tracker:tracker@localhost:5432/tracker?sslmode=disable DEV_DB := postgres://tracker:tracker@localhost:5432/tracker?sslmode=disable
.PHONY: build test test-integration run up down docker migrate install-agent .PHONY: web web-dev build test test-integration run up down docker migrate install-agent
build: # Builds the Vue app into internal/web/dist/app, which the binary embeds.
web:
cd web && { [ -d node_modules ] || npm ci; } && npm run build
# Vite dev server with hot reload; it proxies /api to `make run` on :8080.
web-dev:
cd web && npm run dev
build: web
go build -o bin/ ./cmd/... go build -o bin/ ./cmd/...
test: test:
@@ -13,7 +21,7 @@ test:
test-integration: test-integration:
TEST_DATABASE_URL='$(DEV_DB)' go test -count=1 ./... TEST_DATABASE_URL='$(DEV_DB)' go test -count=1 ./...
run: run: web
AUTH_MODE=dev DEV_MODE=true DATABASE_URL='$(DEV_DB)' go run ./cmd/tracker serve AUTH_MODE=dev DEV_MODE=true DATABASE_URL='$(DEV_DB)' go run ./cmd/tracker serve
up: up:
+8 -5
View File
@@ -79,7 +79,7 @@ tracker goal rm --id 2
## Dashboard and auth ## Dashboard and auth
The dashboard (`/`) and the setup page (`/setup`) 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. 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. 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.
@@ -103,8 +103,8 @@ Collectors never use the site login. Each one sends its own bearer key.
| GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | key or admin | totals per label and kind, plus goal results | | GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | key or admin | totals per label and kind, plus goal results |
| GET, POST | `/api/v1/devices` | admin | list devices; create one with `{"name","kind"}`, which returns its key once | | 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 | | DELETE | `/api/v1/devices/{name}` | admin | revoke a device's key |
| GET | `/`, `/setup` | admin | dashboard and setup pages | | GET | `/`, `/setup` | admin | the dashboard app |
| GET | `/tracker.user.js`, `/style.css`, `/healthz`, `/readyz` | none | the browser userscript holds no secrets | | 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. The event batch format is shared by all `*/events` endpoints. A batch holds at most 1000 events.
@@ -183,10 +183,13 @@ To track time outside: `tracker goal add --kind place --label away --op '>=' --t
```sh ```sh
make test # unit tests make test # unit tests
make up && make test-integration # also runs the API tests against the compose Postgres (truncates its tables!) 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 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
``` ```
Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,auth,ingest,store,summary,migrations,config,web}` (`web/tracker.user.js` is the browser collector), `internal/agent/hypr`, `deploy/`. 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.
Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,auth,ingest,store,summary,migrations,config,web}` (`internal/web/tracker.user.js` is the browser collector), `web/` (dashboard app), `internal/agent/hypr`, `deploy/`.
## Roadmap ## Roadmap
+10 -1
View File
@@ -1,13 +1,22 @@
# Build from the repo root: docker build -f deploy/Dockerfile -t activity-tracker . # Build from the repo root: docker build -f deploy/Dockerfile -t activity-tracker .
# #
# Multi-arch by construction: both base images are published for arm64, and # Multi-arch by construction: all the base images are published for arm64, and
# the Pi's CI (.gitea/workflows/ci.yaml) builds natively there. No # the Pi's CI (.gitea/workflows/ci.yaml) builds natively there. No
# `RUN --mount` cache lines, so it also builds on the Pi's legacy builder. # `RUN --mount` cache lines, so it also builds on the Pi's legacy builder.
FROM node:24-alpine AS web
WORKDIR /src/web
COPY web/package.json web/package-lock.json ./
RUN npm ci
COPY web/ ./
# Writes ../internal/web/dist/app, which the Go build embeds.
RUN npm run build
FROM golang:1.27 AS build FROM golang:1.27 AS build
WORKDIR /src WORKDIR /src
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
COPY . . COPY . .
COPY --from=web /src/internal/web/dist/app internal/web/dist/app
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/tracker ./cmd/tracker RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/tracker ./cmd/tracker
FROM gcr.io/distroless/static-debian12:nonroot FROM gcr.io/distroless/static-debian12:nonroot
+4 -3
View File
@@ -43,9 +43,10 @@ func New(s *store.Store, admin auth.Checker, loc *time.Location, log *slog.Logge
}) })
mux.HandleFunc("GET /readyz", srv.ready) mux.HandleFunc("GET /readyz", srv.ready)
mux.HandleFunc("GET /tracker.user.js", web.UserScript) mux.HandleFunc("GET /tracker.user.js", web.UserScript)
mux.HandleFunc("GET /style.css", web.Style) mux.Handle("GET /assets/", web.Assets())
mux.Handle("GET /{$}", srv.adminPage(web.Page(web.Index))) // The Vue app's routes; it sends visitors between them itself.
mux.Handle("GET /setup", srv.adminPage(web.Page(web.Setup))) mux.Handle("GET /{$}", srv.adminPage(http.HandlerFunc(web.App)))
mux.Handle("GET /setup", srv.adminPage(http.HandlerFunc(web.App)))
api := http.NewServeMux() api := http.NewServeMux()
api.Handle("POST /desktop/events", srv.device(srv.ingestEvents(ingest.Desktop))) api.Handle("POST /desktop/events", srv.device(srv.ingestEvents(ingest.Desktop)))
View File
-146
View File
@@ -1,146 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Activity Tracker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<nav class="topbar">
<span class="brand">Activity Tracker</span>
<div class="tabs">
<a href="./" aria-current="page">Dashboard</a>
<a href="setup">Setup</a>
</div>
</nav>
<div class="row spread">
<h1 id="title">Today</h1>
<div class="row">
<button id="prev" aria-label="Previous day">‹</button>
<input type="date" id="date" aria-label="Day">
<button id="next" aria-label="Next day">›</button>
<button id="today">Today</button>
</div>
</div>
<p id="status" class="muted"></p>
<div id="content" hidden>
<div class="tiles">
<div class="tile"><div class="k">Desktop time</div><div class="v" id="t-desktop">–</div></div>
<div class="tile"><div class="k">Browser time</div><div class="v" id="t-browser">–</div></div>
<div class="tile"><div class="k">Top site or app</div><div class="v" id="t-top">–</div></div>
<div class="tile"><div class="k">Goals met</div><div class="v" id="t-goals">–</div></div>
</div>
<section class="card"><h2>Goals</h2><div class="tablewrap"><table id="goals"></table></div></section>
<section class="card"><h2>By kind</h2><div class="tablewrap"><table id="kinds"></table></div></section>
<section class="card"><h2>Top labels</h2><div class="tablewrap"><table id="labels"></table></div></section>
<section class="card"><h2>Timeline</h2><div class="tablewrap"><table id="timeline"></table></div></section>
</div>
</main>
<script>
const $ = id => document.getElementById(id);
function dur(s) {
s = Math.round(s);
const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60);
if (h) return `${h}h ${String(m).padStart(2, "0")}m`;
return m ? `${m}m` : `${s}s`;
}
const time = t => new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;" }[c]));
// Friendlier names for the kinds collectors send; anything else shows as is.
const KINDS = { app_focus: "desktop", tab_focus: "browser", at_desk: "at desk", in_bed: "in bed" };
const kind = k => esc(KINDS[k] || k);
const today = () => new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD in local time
async function api(path) {
// Authenticated by the main site's session cookies, which the browser sends.
const r = await fetch("api/v1/" + path);
const body = await r.json().catch(() => ({}));
if (r.status === 401) { location.reload(); throw new Error("session expired"); } // reload goes to the login page
if (!r.ok) throw new Error(body.error || r.statusText);
return body;
}
function rows(el, items, render, empty) {
el.innerHTML = items.length ? items.map(render).join("") : `<tr><td class="muted">${empty}</td></tr>`;
}
function setTitle(date) {
const d = new Date(date + "T12:00:00");
const diff = Math.round((new Date(today() + "T12:00:00") - d) / 864e5);
$("title").textContent = diff === 0 ? "Today" : diff === 1 ? "Yesterday"
: d.toLocaleDateString([], { weekday: "long", day: "numeric", month: "long" });
$("today").disabled = diff === 0;
}
async function load() {
const date = $("date").value;
setTitle(date);
$("status").textContent = "Loading…";
try {
const sum = await api("summary/daily?date=" + date);
const q = new URLSearchParams({ from: sum.from, to: sum.to, limit: "500" });
const { activities } = await api("activities?" + q);
$("t-desktop").textContent = dur(sum.by_kind.app_focus || 0);
$("t-browser").textContent = dur(sum.by_kind.tab_focus || 0);
const focus = sum.totals.filter(t => t.kind === "app_focus" || t.kind === "tab_focus")
.sort((a, b) => b.seconds - a.seconds)[0];
$("t-top").textContent = focus ? focus.label || "—" : "–";
$("t-goals").textContent = sum.goals.length ? `${sum.goals.filter(g => g.met).length} / ${sum.goals.length}` : "–";
rows($("goals"), sum.goals, g => `<tr>
<td class="label">${kind(g.kind)}${g.label ? " · " + esc(g.label) : ""}
<span class="muted">${esc(g.op)} ${dur(g.target_s)}</span></td>
<td class="num">${dur(g.actual_s)}</td>
<td class="num ${g.met ? "ok" : "bad"}">${g.met ? "✓ met" : "✗ missed"}</td></tr>`,
`No goals yet. See <a href="setup#goals">Setup</a>.`);
const kinds = Object.entries(sum.by_kind).sort((a, b) => b[1] - a[1]);
const maxK = kinds[0]?.[1] || 1;
rows($("kinds"), kinds, ([k, s]) => `<tr>
<td class="label">${kind(k)}<div class="bar" style="width:${s / maxK * 100}%"></div></td>
<td class="num">${dur(s)}</td></tr>`, "Nothing recorded.");
const labels = [...sum.totals].sort((a, b) => b.seconds - a.seconds).slice(0, 15);
const maxL = labels[0]?.seconds || 1;
rows($("labels"), labels, t => `<tr>
<td class="label">${esc(t.label || "—")} <span class="badge">${kind(t.kind)}</span>
<div class="bar" style="width:${t.seconds / maxL * 100}%"></div></td>
<td class="num">${dur(t.seconds)}</td></tr>`, "Nothing recorded.");
const acts = activities.filter(a => a.duration_s >= 60)
.sort((a, b) => new Date(b.started_at) - new Date(a.started_at));
rows($("timeline"), acts, a => `<tr>
<td class="time">${time(a.started_at)}–${time(a.ended_at)}</td>
<td class="label">${esc(a.label || a.kind)} <span class="badge">${kind(a.kind)}</span>
${a.attrs?.title ? `<div class="muted small-text">${esc(a.attrs.title)}</div>` : ""}</td>
<td class="num">${dur(a.duration_s)}</td></tr>`, "No activities of a minute or longer.");
$("content").hidden = false;
$("status").textContent = activities.length >= 500 ? "Timeline shows the first 500 activities." : "";
} catch (e) {
$("status").innerHTML = `<span class="err">${esc(e.message)}</span>`;
}
}
function shift(days) {
const d = new Date($("date").value + "T12:00:00");
d.setDate(d.getDate() + days);
$("date").value = d.toLocaleDateString("en-CA");
load();
}
$("prev").onclick = () => shift(-1);
$("next").onclick = () => shift(1);
$("today").onclick = () => { $("date").value = today(); load(); };
$("date").onchange = load;
$("date").value = today();
load();
</script>
</body>
</html>
-278
View File
@@ -1,278 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Activity Tracker Setup</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<nav class="topbar">
<span class="brand">Activity Tracker</span>
<div class="tabs">
<a href="./">Dashboard</a>
<a href="setup" aria-current="page">Setup</a>
</div>
</nav>
<h1>Setup</h1>
<p class="muted">Each collector uploads to <code class="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">
<div class="row spread"><h2>Devices</h2></div>
<div class="tablewrap"><table id="devices"><tr><td class="muted">Loading…</td></tr></table></div>
<form class="row" id="create" style="margin-top:12px">
<select id="kind" aria-label="Kind">
<option value="browser">Browser</option>
<option value="hyprland">Hyprland</option>
<option value="health">Apple Health</option>
<option value="manual">Script / manual</option>
<option value="presence">Presence</option>
</select>
<input id="name" placeholder="Name (optional)" aria-label="Name" style="flex:1; min-width:140px">
<button class="primary">Generate key</button>
</form>
<div class="keyslot"></div>
<p id="status" class="small-text"></p>
</section>
<details class="collector" id="browser" open>
<summary><b>Browser</b><span class="muted">Violentmonkey userscript · time per site</span></summary>
<div class="body">
<p>Records <code>tab_focus</code> intervals labelled by hostname. A tab counts only while it's the selected tab of the focused window, and stops after 5 minutes without input unless video or audio is playing.</p>
<button class="primary" data-kind="browser">Generate key for this browser</button>
<div class="keyslot"></div>
<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>Open <a class="script" href="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:
<pre class="base"></pre>
<pre class="key">trk_… (generate a key above)</pre></li>
<li>Check it with <b>Status / upload now</b> in the same menu. Uploads happen every minute.</li>
</ol>
<p class="muted small-text">The menu also turns full URLs and page titles on or off (both off by default), sets hosts to ignore, and changes the idle timeout. It runs on every web page and on local <code>file://</code> pages (labelled <code>file</code>; in Chrome, turn on <b>Allow access to file URLs</b> in Violentmonkey's extension details). Browsers block all extensions on <code>about:</code> pages, the new tab page, extension stores and the PDF viewer, so those aren't recorded; Hyprland still counts them as browser time.</p>
</div>
</details>
<details class="collector" id="hyprland">
<summary><b>Hyprland desktop</b><span class="muted">focused window, idle and locked time</span></summary>
<div class="body">
<p>Records <code>app_focus</code> intervals labelled by window class, with the title.</p>
<button class="primary" data-kind="hyprland">Generate key for this machine</button>
<div class="keyslot"></div>
<h3>1. Install the agent</h3>
<pre>git clone ssh://[email protected]:2222/adamf/ccp.git && cd ccp
make install-agent # ~/.local/bin/hypr-agent and the systemd user unit</pre>
<h3>2. Configure and start it</h3>
<pre>mkdir -p ~/.config/hypr-agent
cat > ~/.config/hypr-agent/env &lt;&lt;EOF
TRACKER_URL=<span class="base"></span>
TRACKER_API_KEY=<span class="key">trk_…</span>
# 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</pre>
<h3>3. Idle and lock (optional)</h3>
<p>Add to <code>~/.config/hypr/hypridle.conf</code>:</p>
<pre>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
}</pre>
<p class="muted small-text">Check it with <code>journalctl --user -u hypr-agent -f</code>. Events upload every minute and wait in <code>~/.local/state/hypr-agent/buffer.jsonl</code> while the server can't be reached.</p>
</div>
</details>
<details class="collector" id="health">
<summary><b>Apple Health</b><span class="muted">walks, workouts, steps, sleep</span></summary>
<div class="body">
<p>Workouts become activities (<code>walk</code>, <code>run</code>, <code>workout</code>); step counts, sleep and other metrics become samples.</p>
<button class="primary" data-kind="health">Generate key for Health Auto Export</button>
<div class="keyslot"></div>
<p>In the Health Auto Export iOS app, create a <b>REST API</b> automation:</p>
<ul>
<li>URL: <code><span class="base"></span>/api/v1/health/hae</code></li>
<li>Header: <code>Authorization</code> = <code>Bearer <span class="key">trk_…</span></code></li>
<li>Format: JSON · Sync cadence: hourly</li>
<li>Data: Workouts, plus metrics such as Step Count and Sleep Analysis</li>
</ul>
</div>
</details>
<details class="collector" id="manual">
<summary><b>Scripts</b><span class="muted">post any interval with curl</span></summary>
<div class="body">
<button class="primary" data-kind="manual">Generate key for scripts</button>
<div class="keyslot"></div>
<pre>curl -X POST <span class="base"></span>/api/v1/manual/events \
-H 'Authorization: Bearer <span class="key">trk_…</span>' -H 'Content-Type: application/json' \
-d '{"events":[{"id":"reading-2026-10-14","kind":"reading","label":"book",
"started_at":"2026-10-14T20:00:00Z","ended_at":"2026-10-14T20:45:00Z"}]}'</pre>
<p class="muted small-text">The <code>id</code> makes re-sending safe: a duplicate is ignored. Webcam presence (<code>/api/v1/presence/events</code>) has an endpoint but no agent yet.</p>
</div>
</details>
<details class="collector" id="goals">
<summary><b>Goals</b><span class="muted">daily targets on the dashboard</span></summary>
<div class="body">
<p>Managed on the Pi. An empty label matches every label of that kind.</p>
<pre>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</pre>
</div>
</details>
</main>
<script>
const $ = id => document.getElementById(id);
const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;" }[c]));
function ago(t) {
if (!t) return "never";
const s = (Date.now() - new Date(t)) / 1000;
if (s < 90) return "just now";
if (s < 3600) return Math.round(s / 60) + " min ago";
if (s < 86400) return Math.round(s / 3600) + " h ago";
return new Date(t).toLocaleDateString([], { day: "numeric", month: "short", year: "numeric" });
}
// The tracker's public URL, e.g. https://www.adam-french.co.uk/tracker
const base = new URL(".", location.href).href.replace(/\/$/, "");
document.querySelectorAll(".base").forEach(el => el.textContent = base);
document.querySelectorAll("a.script").forEach(el => el.textContent = base + "/tracker.user.js");
async function api(method, path, body) {
const r = await fetch("api/v1/" + path, {
method, headers: body ? { "Content-Type": "application/json" } : {},
body: body ? JSON.stringify(body) : undefined,
});
const out = await r.json().catch(() => ({}));
if (r.status === 401) { location.reload(); throw new Error("session expired"); }
if (!r.ok) throw new Error(out.error || r.statusText);
return out;
}
function status(msg, cls) {
$("status").className = "small-text " + (cls || "");
$("status").textContent = msg;
}
async function copy(text, btn) {
try { await navigator.clipboard.writeText(text); btn.textContent = "Copied"; }
catch { btn.textContent = "Copy failed"; }
setTimeout(() => btn.textContent = "Copy", 1500);
}
// A Copy button on every command block.
document.querySelectorAll("pre").forEach(pre => {
const wrap = document.createElement("div");
wrap.className = "codeblock";
pre.replaceWith(wrap);
wrap.append(pre);
const btn = document.createElement("button");
btn.className = "small copy"; btn.type = "button"; btn.textContent = "Copy";
btn.onclick = () => copy(pre.innerText, btn);
wrap.append(btn);
});
// ---- devices and keys ----
let devices = [];
async function loadDevices() {
try {
({ devices } = await api("GET", "devices"));
const active = devices.filter(d => !d.revoked_at);
const revoked = devices.filter(d => d.revoked_at);
$("devices").innerHTML = `<tr><th>Name</th><th>Kind</th><th>Last upload</th><th></th></tr>` +
(active.length ? active.map(d => `<tr>
<td class="label">${esc(d.name)}</td>
<td><span class="badge">${esc(d.kind)}</span></td>
<td class="time">${ago(d.last_seen_at)}</td>
<td class="num"><button class="small" data-revoke="${esc(d.name)}">Revoke</button></td></tr>`).join("")
: `<tr><td colspan="4" class="muted">No devices yet.</td></tr>`) +
(revoked.length ? `<tr><td colspan="4" class="muted small-text">${revoked.length} revoked: ${revoked.map(d => esc(d.name)).join(", ")}</td></tr>` : "");
} catch (e) {
status(e.message, "err");
}
}
// A readable name that isn't taken yet (names stay taken after revoking).
function suggestName(kind) {
let stem = { health: "iphone-health", manual: "script" }[kind] || kind;
if (kind === "browser") {
const ua = navigator.userAgent;
stem = /Firefox\//.test(ua) ? "firefox" : /Edg\//.test(ua) ? "edge" : /Chrome\//.test(ua) ? "chrome" : "browser";
}
const taken = new Set(devices.map(d => d.name));
let name = stem;
for (let i = 2; taken.has(name); i++) name = `${stem}-${i}`;
return name;
}
function showKey(slot, device, key) {
document.querySelectorAll(".keyslot").forEach(s => s.innerHTML = "");
slot.innerHTML = `<div class="keybox">
<div>Key for <b>${esc(device.name)}</b> <span class="badge">${esc(device.kind)}</span>. Copy it now; it won't be shown again.</div>
<div class="codeblock"><pre>${esc(key)}</pre><button class="small copy" type="button">Copy</button></div>
</div>`;
const btn = slot.querySelector("button");
btn.onclick = () => copy(key, btn);
copy(key, btn);
}
async function generate(kind, name, slot, button) {
button.disabled = true;
try {
if (!devices.length) await loadDevices();
const { device, key } = await api("POST", "devices", { kind, name: name || suggestName(kind) });
showKey(slot, device, key);
// Fill the key into this collector's steps so they can be copied as-is.
const section = $(kind);
if (section) {
section.open = true;
section.querySelectorAll(".key").forEach(el => el.textContent = key);
}
status("");
loadDevices();
return true;
} catch (e) {
status(e.message, "err");
return false;
} finally {
button.disabled = false;
}
}
$("create").onsubmit = e => {
e.preventDefault();
const btn = e.submitter || $("create").querySelector("button");
generate($("kind").value, $("name").value.trim(), $("create").nextElementSibling, btn)
.then(ok => { if (ok) $("name").value = ""; });
};
document.querySelectorAll("button[data-kind]").forEach(btn => {
btn.onclick = () => generate(btn.dataset.kind, "", btn.nextElementSibling, btn);
});
$("devices").onclick = async e => {
const name = e.target.dataset?.revoke;
if (!name || !confirm(`Revoke ${name}? Its collector will stop being able to upload.`)) return;
try {
await api("DELETE", "devices/" + encodeURIComponent(name));
status(`Revoked ${name}.`, "ok");
loadDevices();
} catch (err) { status(err.message, "err"); }
};
if (location.hash && $(location.hash.slice(1))?.tagName === "DETAILS") $(location.hash.slice(1)).open = true;
loadDevices();
</script>
</body>
</html>
+33 -20
View File
@@ -1,42 +1,55 @@
// Package web holds the dashboard pages, which read /api/v1 with the main // Package web serves the dashboard, a Vue app in /web that reads /api/v1 with
// site's session cookies, and the browser userscript. // the main site's session cookies, and the browser userscript.
package web package web
import ( import (
_ "embed" "embed"
"io/fs"
"net/http" "net/http"
"strings"
) )
var ( var (
//go:embed index.html // dist holds the Vue build in dist/app (`make web`). Only dist/.gitkeep is
Index []byte // committed, so the Go code builds and tests without Node.
// LoginRedirect is served instead of a page when the visitor isn't the //go:embed all:dist
dist embed.FS
// LoginRedirect is served instead of the app when the visitor isn't the
// site's admin. // site's admin.
//go:embed login.html //go:embed login.html
LoginRedirect []byte LoginRedirect []byte
//go:embed setup.html
Setup []byte
//go:embed tracker.user.js //go:embed tracker.user.js
userScript []byte userScript []byte
//go:embed style.css
style []byte
) )
// Style serves the stylesheet the pages share. It's public: the login var app, _ = fs.Sub(dist, "dist/app")
// redirect doesn't use it, but there's nothing private in it either.
func Style(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/css; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
w.Write(style)
}
// Page serves a static HTML page. // notBuilt stands in for the app in a binary built without `make web`.
func Page(page []byte) http.HandlerFunc { var notBuilt = []byte(`<!doctype html><meta charset="utf-8"><title>Activity Tracker</title>
return func(w http.ResponseWriter, r *http.Request) { <p>The dashboard wasn't built into this binary. Run <code>make web</code> and rebuild.</p>`)
// App serves the app's index.html, for every route the app handles.
func App(w http.ResponseWriter, r *http.Request) {
page, err := fs.ReadFile(app, "index.html")
if err != nil {
page = notBuilt
}
w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store") w.Header().Set("Cache-Control", "no-store")
w.Write(page) w.Write(page)
}
// Assets serves the app's scripts and styles. Their names carry a content
// hash, so they can be cached forever, and they hold no secrets, so they are
// public.
func Assets() http.Handler {
files := http.FileServerFS(app)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := fs.Stat(app, strings.TrimPrefix(r.URL.Path, "/")); err == nil {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
} }
files.ServeHTTP(w, r)
})
} }
// UserScript serves the browser collector. Opening a *.user.js URL in a // UserScript serves the browser collector. Opening a *.user.js URL in a
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Activity Tracker</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1687
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "activity-tracker-web",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"typecheck": "vue-tsc --noEmit"
},
"dependencies": {
"vue": "^3.5.44",
"vue-router": "^5.4.0"
},
"devDependencies": {
"@types/node": "^26.6.5",
"@vitejs/plugin-vue": "^6.0.10",
"@vue/tsconfig": "^0.9.1",
"typescript": "^6.0.3",
"vite": "^8.3.4",
"vue-tsc": "^3.3.13"
}
}
+12
View File
@@ -0,0 +1,12 @@
<template>
<main>
<nav class="topbar">
<span class="brand">Activity Tracker</span>
<div class="tabs">
<RouterLink to="/">Dashboard</RouterLink>
<RouterLink to="/setup">Setup</RouterLink>
</div>
</nav>
<RouterView />
</main>
</template>
+43
View File
@@ -0,0 +1,43 @@
// 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> {
const r = await fetch("api/v1/" + path, {
method,
headers: body ? { "Content-Type": "application/json" } : {},
body: body ? JSON.stringify(body) : undefined,
});
const out = await r.json().catch(() => ({}));
// The server serves the login redirect instead of the app, so a reload signs in again.
if (r.status === 401) { location.reload(); throw new Error("session expired"); }
if (!r.ok) throw new Error(out.error || r.statusText);
return out as T;
}
export interface Goal {
kind: string; label: string; op: string;
target_s: number; actual_s: number; met: boolean;
}
export interface Total { kind: string; label: string; seconds: number }
export interface Summary {
date: string; from: string; to: string;
totals: Total[]; by_kind: Record<string, number>; goals: Goal[];
}
export interface Activity {
kind: string; label: string;
started_at: string; ended_at: string; duration_s: number;
attrs?: Record<string, unknown>;
}
export interface Device {
name: string; kind: string;
last_seen_at?: string | null; revoked_at?: string | null;
}
export function dur(s: number): string {
s = Math.round(s);
const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60);
if (h) return `${h}h ${String(m).padStart(2, "0")}m`;
return m ? `${m}m` : `${s}s`;
}
// Friendlier names for the kinds collectors send; anything else shows as is.
const KINDS: Record<string, string> = { app_focus: "desktop", tab_focus: "browser", at_desk: "at desk", in_bed: "in bed" };
export const kindName = (k: string) => KINDS[k] || k;
+15
View File
@@ -0,0 +1,15 @@
<script setup lang="ts">
import { ref } from "vue";
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");
</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>
</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
<script setup lang="ts">
// One collector's collapsible section on the setup page.
defineProps<{ id: string; title: string; hint: string }>();
const open = defineModel<boolean>("open", { default: false });
</script>
<template>
<details class="collector" :id="id" :open="open" @toggle="open = ($event.target as HTMLDetailsElement).open">
<summary><b>{{ title }}</b><span class="muted">{{ hint }}</span></summary>
<div class="body"><slot /></div>
</details>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import type { Device } from "../api";
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));
</script>
<template>
<div class="keybox">
<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>
</div>
</div>
</template>
+6
View File
@@ -0,0 +1,6 @@
// Copies text to the clipboard and reports the result through a button label.
export async function copy(text: string, setLabel: (s: string) => void) {
try { await navigator.clipboard.writeText(text); setLabel("Copied"); }
catch { setLabel("Copy failed"); }
setTimeout(() => setLabel("Copy"), 1500);
}
+22
View File
@@ -0,0 +1,22 @@
import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import Dashboard from "./views/Dashboard.vue";
import Setup from "./views/Setup.vue";
import "./style.css";
const router = createRouter({
// The tracker is served under a prefix only the browser knows (nginx strips
// /tracker/), and every route is one segment deep, so the directory of the
// current URL is the app's base.
history: createWebHistory(new URL(".", location.href).pathname),
routes: [
{ path: "/", component: Dashboard, meta: { title: "Activity Tracker" } },
{ path: "/setup", component: Setup, meta: { title: "Activity Tracker Setup" } },
{ path: "/:rest(.*)", redirect: "/" },
],
scrollBehavior: to => (to.hash ? { el: to.hash } : { top: 0 }),
});
router.afterEach(to => { document.title = String(to.meta.title); });
createApp(App).use(router).mount("#app");
+1 -1
View File
@@ -1,4 +1,4 @@
/* Shared by the dashboard and setup pages. */ /* Shared by every view. */
:root { :root {
--bg:#f6f6f4; --card:#ffffff; --fg:#1b1b1b; --muted:#6b6b6b; --line:#e4e4e0; --bg:#f6f6f4; --card:#ffffff; --fg:#1b1b1b; --muted:#6b6b6b; --line:#e4e4e0;
--accent:#3d6fc4; --accent-soft:#e8eefa; --ok:#2e8b57; --bad:#c0392b; --code:#f2f2ef; --accent:#3d6fc4; --accent-soft:#e8eefa; --ok:#2e8b57; --bad:#c0392b; --code:#f2f2ef;
+124
View File
@@ -0,0 +1,124 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { api, dur, kindName, type Activity, type Summary } from "../api";
const LIMIT = 500;
const today = () => new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD in local time
const noon = (d: string) => new Date(d + "T12:00:00");
const date = ref(today());
const sum = ref<Summary | null>(null);
const activities = ref<Activity[]>([]);
const loading = ref(false);
const error = ref("");
const daysAgo = computed(() => Math.round((+noon(today()) - +noon(date.value)) / 864e5));
const title = computed(() => daysAgo.value === 0 ? "Today" : daysAgo.value === 1 ? "Yesterday"
: noon(date.value).toLocaleDateString([], { weekday: "long", day: "numeric", month: "long" }));
// Ignore a response for a day that's no longer selected.
let seq = 0;
async function load() {
const n = ++seq;
loading.value = true;
error.value = "";
try {
const s = await api<Summary>("GET", "summary/daily?date=" + date.value);
const q = new URLSearchParams({ from: s.from, to: s.to, limit: String(LIMIT) });
const { activities: acts } = await api<{ activities: Activity[] }>("GET", "activities?" + q);
if (n !== seq) return;
sum.value = s;
activities.value = acts;
} catch (e) {
if (n === seq) error.value = (e as Error).message;
} finally {
if (n === seq) loading.value = false;
}
}
watch(date, load, { immediate: true });
function shift(days: number) {
const d = noon(date.value);
d.setDate(d.getDate() + days);
date.value = d.toLocaleDateString("en-CA");
}
const top = computed(() => sum.value?.totals
.filter(t => t.kind === "app_focus" || t.kind === "tab_focus")
.sort((a, b) => b.seconds - a.seconds)[0]);
const goalsMet = computed(() => {
const g = sum.value?.goals ?? [];
return g.length ? `${g.filter(x => x.met).length} / ${g.length}` : "–";
});
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)
.sort((a, b) => +new Date(b.started_at) - +new Date(a.started_at)));
const time = (t: string) => new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const pct = (v: number, max: number) => `${v / (max || 1) * 100}%`;
</script>
<template>
<div class="row spread">
<h1>{{ title }}</h1>
<div class="row">
<button aria-label="Previous day" @click="shift(-1)">‹</button>
<input type="date" v-model="date" aria-label="Day">
<button aria-label="Next day" @click="shift(1)">›</button>
<button :disabled="daysAgo === 0" @click="date = today()">Today</button>
</div>
</div>
<p class="muted">
<span v-if="error" class="err">{{ error }}</span>
<template v-else-if="loading">Loading…</template>
<template v-else-if="activities.length >= LIMIT">Timeline shows the first {{ LIMIT }} activities.</template>
</p>
<div v-if="sum">
<div class="tiles">
<div class="tile"><div class="k">Desktop time</div><div class="v">{{ dur(sum.by_kind.app_focus || 0) }}</div></div>
<div class="tile"><div class="k">Browser time</div><div class="v">{{ dur(sum.by_kind.tab_focus || 0) }}</div></div>
<div class="tile"><div class="k">Top site or app</div><div class="v">{{ top ? top.label || "—" : "–" }}</div></div>
<div class="tile"><div class="k">Goals met</div><div class="v">{{ goalsMet }}</div></div>
</div>
<section class="card"><h2>Goals</h2><div class="tablewrap"><table>
<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></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>
</table></div></section>
<section class="card"><h2>By kind</h2><div class="tablewrap"><table>
<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>
</table></div></section>
<section class="card"><h2>Top labels</h2><div class="tablewrap"><table>
<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) }"></div></td>
<td class="num">{{ dur(t.seconds) }}</td>
</tr>
<tr v-if="!labels.length"><td class="muted">Nothing recorded.</td></tr>
</table></div></section>
<section class="card"><h2>Timeline</h2><div class="tablewrap"><table>
<tr v-for="(a, i) in timeline" :key="i">
<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>
</table></div></section>
</div>
</template>
+232
View File
@@ -0,0 +1,232 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import { api, type Device } from "../api";
import CodeBlock from "../components/CodeBlock.vue";
import Collector from "../components/Collector.vue";
import KeyBox from "../components/KeyBox.vue";
// The tracker's public URL, e.g. https://www.adam-french.co.uk/tracker
const base = new URL(".", location.href).href.replace(/\/$/, "");
const devices = ref<Device[]>([]);
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));
// Which collector sections are open: the browser's by default, and the one a
// #section in the URL names.
const open = reactive<Record<string, boolean>>({ browser: true });
const route = useRoute();
if (route.hash) open[route.hash.slice(1)] = true;
// The last key generated, shown under the button that made it ("create" is
// the form), and the keys filled into each collector's steps.
const issued = ref<{ slot: string; device: Device; key: string } | null>(null);
const keys = reactive<Record<string, string>>({});
const keyFor = (kind: string) => keys[kind] || "trk_…";
const busy = ref("");
// The place a pair of Shortcuts automations reports. It ends up in a URL
// path, so spaces become hyphens rather than relying on Shortcuts to encode.
const place = ref("home");
const placeName = computed(() => place.value.trim().toLowerCase().replace(/[\s/?#]+/g, "-") || "home");
const kindSel = ref("browser");
const nameIn = ref("");
function ago(t?: string | null) {
if (!t) return "never";
const s = (Date.now() - +new Date(t)) / 1000;
if (s < 90) return "just now";
if (s < 3600) return Math.round(s / 60) + " min ago";
if (s < 86400) return Math.round(s / 3600) + " h ago";
return new Date(t).toLocaleDateString([], { day: "numeric", month: "short", year: "numeric" });
}
async function loadDevices() {
try {
({ devices: devices.value } = await api<{ devices: Device[] }>("GET", "devices"));
loaded.value = true;
} catch (e) {
status.value = { msg: (e as Error).message, cls: "err" };
}
}
onMounted(loadDevices);
// A readable name that isn't taken yet (names stay taken after revoking).
function suggestName(kind: string) {
let stem = ({ location: "iphone", manual: "script" } as Record<string, string>)[kind] || kind;
if (kind === "browser") {
const ua = navigator.userAgent;
stem = /Firefox\//.test(ua) ? "firefox" : /Edg\//.test(ua) ? "edge" : /Chrome\//.test(ua) ? "chrome" : "browser";
}
const taken = new Set(devices.value.map(d => d.name));
let name = stem;
for (let i = 2; taken.has(name); i++) name = `${stem}-${i}`;
return name;
}
async function generate(kind: string, name: string, slot: string) {
busy.value = slot;
try {
if (!loaded.value) await loadDevices();
const { device, key } = await api<{ device: Device; key: string }>("POST", "devices", { kind, name: name || suggestName(kind) });
issued.value = { slot, device, key };
// Fill the key into this collector's steps so they can be copied as-is.
keys[kind] = key;
open[kind] = true;
status.value = { msg: "" };
loadDevices();
return true;
} catch (e) {
status.value = { msg: (e as Error).message, cls: "err" };
return false;
} finally {
busy.value = "";
}
}
async function create() {
if (await generate(kindSel.value, nameIn.value.trim(), "create")) nameIn.value = "";
}
async function revoke(name: string) {
if (!confirm(`Revoke ${name}? Its collector will stop being able to upload.`)) return;
try {
await api("DELETE", "devices/" + encodeURIComponent(name));
status.value = { msg: `Revoked ${name}.`, cls: "ok" };
loadDevices();
} catch (e) {
status.value = { msg: (e as Error).message, cls: "err" };
}
}
</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">
<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>
<tr v-for="d in active" :key="d.name">
<td class="label">{{ d.name }}</td>
<td><span class="badge">{{ d.kind }}</span></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>
</table></div>
<form class="row" style="margin-top:12px" @submit.prevent="create">
<select v-model="kindSel" aria-label="Kind">
<option value="browser">Browser</option>
<option value="hyprland">Hyprland</option>
<option value="location">iPhone location</option>
<option value="manual">Script / manual</option>
<option value="presence">Presence</option>
</select>
<input v-model="nameIn" placeholder="Name (optional)" aria-label="Name" style="flex:1; min-width:140px">
<button class="primary" :disabled="busy === 'create'">Generate key</button>
</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>
</section>
<Collector id="browser" title="Browser" hint="Violentmonkey userscript · time per site" v-model:open="open.browser">
<p>Records <code>tab_focus</code> intervals labelled by hostname. A tab counts only while it's the selected tab of the focused window, and stops after 5 minutes without input unless video or audio is playing.</p>
<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>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>
<CodeBlock>{{ keys.browser || "trk_… (generate a key above)" }}</CodeBlock></li>
<li>Check it with <b>Status / upload now</b> in the same menu. Uploads happen every minute.</li>
</ol>
<p class="muted small-text">The menu also turns full URLs and page titles on or off (both off by default), sets hosts to ignore, and changes the idle timeout. It runs on every web page and on local <code>file://</code> pages (labelled <code>file</code>; in Chrome, turn on <b>Allow access to file URLs</b> in Violentmonkey's extension details). Browsers block all extensions on <code>about:</code> pages, the new tab page, extension stores and the PDF viewer, so those aren't recorded; Hyprland still counts them as browser time.</p>
</Collector>
<Collector id="hyprland" title="Hyprland desktop" hint="focused window, idle and locked time" v-model:open="open.hyprland">
<p>Records <code>app_focus</code> intervals labelled by window class, with the title.</p>
<button class="primary" :disabled="busy === 'hyprland'" @click="generate('hyprland', '', 'hyprland')">Generate key for this machine</button>
<KeyBox v-if="issued?.slot === 'hyprland'" :key="issued.key" :device="issued.device" :api-key="issued.key" />
<h3>1. Install the agent</h3>
<CodeBlock>git clone ssh://[email protected]:2222/adamf/ccp.git && cd ccp
make install-agent # ~/.local/bin/hypr-agent and the systemd user unit</CodeBlock>
<h3>2. Configure and start it</h3>
<CodeBlock>mkdir -p ~/.config/hypr-agent
cat > ~/.config/hypr-agent/env &lt;&lt;EOF
TRACKER_URL={{ base }}
TRACKER_API_KEY={{ keyFor("hyprland") }}
# 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</CodeBlock>
<h3>3. Idle and lock (optional)</h3>
<p>Add to <code>~/.config/hypr/hypridle.conf</code>:</p>
<CodeBlock>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
}</CodeBlock>
<p class="muted small-text">Check it with <code>journalctl --user -u hypr-agent -f</code>. Events upload every minute and wait in <code>~/.local/state/hypr-agent/buffer.jsonl</code> while the server can't be reached.</p>
</Collector>
<Collector id="location" title="iPhone location" hint="Shortcuts automations · time at home and away" v-model:open="open.location">
<p>Records <code>place</code> intervals labelled by place (<code>home</code>, <code>gym</code>, …) and <code>away</code> in between. Each arrive or leave closes the current interval and opens the next; the current one counts up to now.</p>
<button class="primary" :disabled="busy === 'location'" @click="generate('location', '', 'location')">Generate key for this phone</button>
<KeyBox v-if="issued?.slot === 'location'" :key="issued.key" :device="issued.device" :api-key="issued.key" />
<h3>1. Make the Tracker shortcut (once)</h3>
<ol>
<li>In the Shortcuts app, on the <b>Shortcuts</b> tab, tap <b>+</b> and name the shortcut <code>Tracker</code>.</li>
<li>Add the action <b>Get Contents of URL</b>. In the URL, type the text below, then insert the <b>Shortcut Input</b> variable right after the last slash:
<CodeBlock>{{ base }}/api/v1/location/</CodeBlock></li>
<li>Tap <b>Show More</b>. Set Method to <code>POST</code> and add a header <code>Authorization</code> = <code>Bearer {{ keyFor("location") }}</code></li>
</ol>
<p class="muted small-text">The shortcut holds your key, so don't share it.</p>
<h3>2. Add two automations per place</h3>
<p>Type the place's name to fill in the steps:</p>
<div class="row"><input v-model="place" placeholder="home" aria-label="Place name" style="flex:1; min-width:140px"></div>
<ol>
<li>On the <b>Automation</b> tab, tap <b>+</b>, choose <b>Arrive</b>, set Location to your {{ placeName }}'s address and pick <b>Run Immediately</b> (turn off <b>Notify When Run</b> if you like). Then tap <b>New Blank Automation</b>.</li>
<li>Add a <b>Text</b> action containing:
<CodeBlock>arrive/{{ placeName }}</CodeBlock>
then a <b>Run Shortcut</b> action set to <b>Tracker</b>. The Text becomes its input.</li>
<li>Repeat with <b>Leave</b> for the same address, with the Text:
<CodeBlock>leave/{{ placeName }}</CodeBlock></li>
</ol>
<p class="muted small-text">Any name works except <code>away</code>. Names are lower-cased, and spaces become hyphens. Repeated triggers are ignored, and a late "leave home" after "arrive gym" doesn't undo the arrival. Goal examples: <code>--kind place --label away --op '&gt;=' --target 1h</code>, <code>--kind place --label gym --op '&gt;=' --target 45m</code>.</p>
</Collector>
<Collector id="manual" title="Scripts" hint="post any interval with curl" v-model:open="open.manual">
<button class="primary" :disabled="busy === 'manual'" @click="generate('manual', '', 'manual')">Generate key for scripts</button>
<KeyBox v-if="issued?.slot === 'manual'" :key="issued.key" :device="issued.device" :api-key="issued.key" />
<CodeBlock>curl -X POST {{ base }}/api/v1/manual/events \
-H 'Authorization: Bearer {{ keyFor("manual") }}' -H 'Content-Type: application/json' \
-d '{"events":[{"id":"reading-2026-10-14","kind":"reading","label":"book",
"started_at":"2026-10-14T20:00:00Z","ended_at":"2026-10-14T20:45:00Z"}]}'</CodeBlock>
<p class="muted small-text">The <code>id</code> makes re-sending safe: a duplicate is ignored. Webcam presence (<code>/api/v1/presence/events</code>) has an endpoint but no agent yet.</p>
</Collector>
<Collector id="goals" title="Goals" hint="daily targets on the dashboard" v-model:open="open.goals">
<p>Managed on the Pi. An empty label matches every label of that kind.</p>
<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>
</Collector>
</template>
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"compilerOptions": {
"types": ["vite/client"],
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts"]
}
+22
View File
@@ -0,0 +1,22 @@
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
// The build is embedded in the Go binary (internal/web/dist/app) and served under
// whatever prefix the proxy gives it (/tracker/ in production), so every asset
// URL is relative.
export default defineConfig({
plugins: [vue()],
base: "./",
build: {
outDir: fileURLToPath(new URL("../internal/web/dist/app", import.meta.url)),
emptyOutDir: true,
},
server: {
// `make run` serves the API on :8080 with AUTH_MODE=dev.
proxy: {
"/api": "http://localhost:8080",
"/tracker.user.js": "http://localhost:8080",
},
},
});