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
+120
View File
@@ -0,0 +1,120 @@
package hypr
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"ccp/internal/ingest"
)
// Buffer holds events that haven't been uploaded yet, persisted as JSONL so
// they survive restarts and server outages.
type Buffer struct {
mu sync.Mutex
path string
pending []ingest.Event
}
// OpenBuffer loads any events left over from a previous run. Corrupt lines
// (e.g. from a crash mid-write) are skipped.
func OpenBuffer(path string) (*Buffer, error) {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return nil, err
}
b := &Buffer{path: path}
f, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
return b, nil
}
if err != nil {
return nil, err
}
defer f.Close()
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 64*1024), 1024*1024)
for sc.Scan() {
var e ingest.Event
if json.Unmarshal(sc.Bytes(), &e) == nil && e.ID != "" {
b.pending = append(b.pending, e)
}
}
return b, sc.Err()
}
// Add appends an event to the buffer and its file.
func (b *Buffer) Add(e ingest.Event) error {
line, err := json.Marshal(e)
if err != nil {
return err
}
b.mu.Lock()
defer b.mu.Unlock()
f, err := os.OpenFile(b.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return err
}
defer f.Close()
if _, err := f.Write(append(line, '\n')); err != nil {
return err
}
b.pending = append(b.pending, e)
return nil
}
// Peek returns up to max of the oldest pending events.
func (b *Buffer) Peek(max int) []ingest.Event {
b.mu.Lock()
defer b.mu.Unlock()
n := min(max, len(b.pending))
return append([]ingest.Event(nil), b.pending[:n]...)
}
// Ack drops the n oldest events and rewrites the file.
func (b *Buffer) Ack(n int) error {
b.mu.Lock()
defer b.mu.Unlock()
if n > len(b.pending) {
return fmt.Errorf("ack %d of %d pending events", n, len(b.pending))
}
b.pending = b.pending[n:]
return b.rewrite()
}
func (b *Buffer) Len() int {
b.mu.Lock()
defer b.mu.Unlock()
return len(b.pending)
}
// rewrite atomically replaces the file with the pending events.
func (b *Buffer) rewrite() error {
tmp := b.path + ".tmp"
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err != nil {
return err
}
w := bufio.NewWriter(f)
enc := json.NewEncoder(w)
for _, e := range b.pending {
if err := enc.Encode(e); err != nil {
f.Close()
return err
}
}
if err := w.Flush(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(tmp, b.path)
}
+90
View File
@@ -0,0 +1,90 @@
package hypr
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"time"
)
// Control commands sent by hypridle hooks via `hypr-agent <command>`.
var Commands = map[string]bool{"idle": true, "resume": true, "lock": true, "unlock": true}
// ControlEvent is a control command stamped with when it was received.
type ControlEvent struct {
Command string
At time.Time
}
// ControlSocketPath is where the running agent listens for control commands.
func ControlSocketPath() string {
dir := os.Getenv("XDG_RUNTIME_DIR")
if dir == "" {
dir = os.TempDir()
}
return filepath.Join(dir, "hypr-agent.sock")
}
// ServeControl accepts one-line commands on the control socket until ctx is
// cancelled.
func ServeControl(ctx context.Context, out chan<- ControlEvent) error {
path := ControlSocketPath()
os.Remove(path) // stale socket from a previous run
ln, err := net.Listen("unix", path)
if err != nil {
return err
}
go func() {
<-ctx.Done()
ln.Close()
}()
for {
conn, err := ln.Accept()
if err != nil {
if ctx.Err() != nil {
return nil
}
return err
}
go func() {
defer conn.Close()
conn.SetDeadline(time.Now().Add(2 * time.Second))
line, _ := bufio.NewReader(conn).ReadString('\n')
cmd := strings.TrimSpace(line)
if !Commands[cmd] {
fmt.Fprintf(conn, "unknown command %q\n", cmd)
return
}
out <- ControlEvent{Command: cmd, At: time.Now()}
fmt.Fprintln(conn, "ok")
}()
}
}
// SendControl sends a command to the running agent.
func SendControl(cmd string) error {
conn, err := net.DialTimeout("unix", ControlSocketPath(), 2*time.Second)
if err != nil {
return fmt.Errorf("is hypr-agent running? %w", err)
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(2 * time.Second))
if _, err := fmt.Fprintln(conn, cmd); err != nil {
return err
}
reply, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
return err
}
if reply = strings.TrimSpace(reply); reply != "ok" {
return errors.New(reply)
}
return nil
}
+95
View File
@@ -0,0 +1,95 @@
package hypr
import (
"path/filepath"
"testing"
"time"
"ccp/internal/ingest"
)
func TestParseActiveWindow(t *testing.T) {
event, data, ok := ParseLine("activewindow>>firefox,Inbox, 3 unread - Mozilla Firefox")
if !ok || event != "activewindow" {
t.Fatalf("ParseLine: got %q %v", event, ok)
}
got := ParseActiveWindow(data)
want := Focus{Class: "firefox", Title: "Inbox, 3 unread - Mozilla Firefox"}
if got != want {
t.Fatalf("got %+v, want %+v", got, want)
}
if got := ParseActiveWindow(","); got != (Focus{}) {
t.Fatalf("empty focus: got %+v", got)
}
}
func TestSessionizer(t *testing.T) {
t0 := time.Date(2026, 10, 14, 9, 0, 0, 0, time.UTC)
at := func(sec int) time.Time { return t0.Add(time.Duration(sec) * time.Second) }
var got []ingest.Event
s := &Sessionizer{MinDuration: 2 * time.Second, Emit: func(e ingest.Event) { got = append(got, e) }}
kitty := Focus{Class: "kitty", Title: "nvim"}
ff := Focus{Class: "firefox", Title: "docs"}
s.Focus(at(0), kitty)
s.Focus(at(0), kitty) // duplicate event: no new interval
s.Focus(at(60), ff)
s.Focus(at(61), kitty) // firefox for 1s: dropped as flicker
s.Pause(at(120), "idle")
s.Focus(at(130), ff) // focus change while idle is remembered, not recorded
s.Pause(at(300), "locked")
s.Resume(at(600))
s.Close(at(660))
want := []struct {
kind, label string
start, end int
}{
{"app_focus", "kitty", 0, 60},
{"app_focus", "kitty", 61, 120},
{"idle", "idle", 120, 300},
{"locked", "locked", 300, 600},
{"app_focus", "firefox", 600, 660},
}
if len(got) != len(want) {
t.Fatalf("got %d events, want %d: %+v", len(got), len(want), got)
}
for i, w := range want {
g := got[i]
if g.Kind != w.kind || g.Label != w.label || !g.StartedAt.Equal(at(w.start)) || !g.EndedAt.Equal(at(w.end)) {
t.Errorf("event %d: got %s/%s %v-%v, want %+v", i, g.Kind, g.Label, g.StartedAt, g.EndedAt, w)
}
if g.ID == "" {
t.Errorf("event %d has no ID", i)
}
}
if got[0].Attrs["title"] != "nvim" {
t.Errorf("title not recorded: %+v", got[0].Attrs)
}
}
func TestBufferPersists(t *testing.T) {
path := filepath.Join(t.TempDir(), "buf.jsonl")
b, err := OpenBuffer(path)
if err != nil {
t.Fatal(err)
}
for _, id := range []string{"a", "b", "c"} {
if err := b.Add(ingest.Event{ID: id, Kind: "app_focus"}); err != nil {
t.Fatal(err)
}
}
if err := b.Ack(2); err != nil {
t.Fatal(err)
}
reopened, err := OpenBuffer(path)
if err != nil {
t.Fatal(err)
}
if ev := reopened.Peek(10); len(ev) != 1 || ev[0].ID != "c" {
t.Fatalf("after reopen got %+v, want only c", ev)
}
}
+142
View File
@@ -0,0 +1,142 @@
// Package hypr implements the Hyprland desktop collector: it follows window
// focus over Hyprland's IPC sockets, turns it into intervals, buffers them on
// disk and uploads them to the tracker server.
package hypr
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"os"
"path/filepath"
"strings"
"time"
)
// Focus is the currently focused window. An empty Class means nothing is
// focused (e.g. an empty workspace).
type Focus struct {
Class string
Title string
}
// FocusEvent is a focus change stamped with the time it was observed.
type FocusEvent struct {
Focus
At time.Time
}
func socketDir() (string, error) {
sig := os.Getenv("HYPRLAND_INSTANCE_SIGNATURE")
if sig == "" {
return "", errors.New("HYPRLAND_INSTANCE_SIGNATURE not set; is Hyprland running?")
}
return filepath.Join(os.Getenv("XDG_RUNTIME_DIR"), "hypr", sig), nil
}
// ParseLine splits a socket2 line of the form "event>>data".
func ParseLine(line string) (event, data string, ok bool) {
return strings.Cut(line, ">>")
}
// ParseActiveWindow parses the data of an "activewindow" event, "class,title".
// Titles may contain commas, so only the first one is a separator.
func ParseActiveWindow(data string) Focus {
class, title, _ := strings.Cut(data, ",")
return Focus{Class: class, Title: title}
}
// ActiveWindow asks Hyprland (via the request socket) for the focused window.
func ActiveWindow() (Focus, error) {
dir, err := socketDir()
if err != nil {
return Focus{}, err
}
conn, err := net.DialTimeout("unix", filepath.Join(dir, ".socket.sock"), 2*time.Second)
if err != nil {
return Focus{}, err
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(2 * time.Second))
if _, err := conn.Write([]byte("j/activewindow")); err != nil {
return Focus{}, err
}
body, err := io.ReadAll(conn)
if err != nil {
return Focus{}, err
}
var w struct {
Class string `json:"class"`
Title string `json:"title"`
}
if err := json.Unmarshal(body, &w); err != nil {
return Focus{}, fmt.Errorf("decode activewindow: %w", err)
}
return Focus{Class: w.Class, Title: w.Title}, nil
}
// Listen streams focus changes to out until ctx is cancelled, reconnecting to
// the event socket if the connection drops.
func Listen(ctx context.Context, out chan<- FocusEvent, log *slog.Logger) error {
dir, err := socketDir()
if err != nil {
return err
}
path := filepath.Join(dir, ".socket2.sock")
for {
err := listenOnce(ctx, path, out)
if ctx.Err() != nil {
return nil
}
log.Warn("hyprland event socket disconnected; retrying", "err", err)
select {
case <-ctx.Done():
return nil
case <-time.After(2 * time.Second):
}
}
}
func listenOnce(ctx context.Context, path string, out chan<- FocusEvent) error {
var d net.Dialer
conn, err := d.DialContext(ctx, "unix", path)
if err != nil {
return err
}
defer conn.Close()
go func() {
<-ctx.Done()
conn.Close()
}()
send := func(f Focus) {
select {
case out <- FocusEvent{Focus: f, At: time.Now()}:
case <-ctx.Done():
}
}
// Seed with the current window so time before the first switch is counted.
if f, err := ActiveWindow(); err == nil {
send(f)
}
sc := bufio.NewScanner(conn)
sc.Buffer(make([]byte, 64*1024), 1024*1024)
for sc.Scan() {
event, data, ok := ParseLine(sc.Text())
if ok && event == "activewindow" {
send(ParseActiveWindow(data))
}
}
if err := sc.Err(); err != nil {
return err
}
return io.EOF
}
+115
View File
@@ -0,0 +1,115 @@
package hypr
import (
"crypto/rand"
"encoding/hex"
"time"
"ccp/internal/ingest"
)
// Sessionizer turns a stream of focus changes and idle/lock signals into
// closed intervals. It is not safe for concurrent use.
type Sessionizer struct {
// Intervals shorter than this are dropped (alt-tab flicker).
MinDuration time.Duration
// Emit receives every completed interval.
Emit func(ingest.Event)
last Focus // most recent focus, remembered while paused
cur *span // open focus interval
pause *span // open idle/locked interval
}
type span struct {
kind string
focus Focus
start time.Time
}
// Focus records that f gained focus at now.
func (s *Sessionizer) Focus(now time.Time, f Focus) {
s.last = f
if s.pause != nil {
return // resumes with this window once the pause ends
}
if s.cur != nil && s.cur.focus == f {
return
}
s.closeFocus(now)
s.openFocus(now)
}
// Pause starts an idle or locked period ("idle" or "locked"). A different
// pause kind while already paused ends the previous one.
func (s *Sessionizer) Pause(now time.Time, kind string) {
if s.pause != nil {
if s.pause.kind == kind {
return
}
s.closePause(now)
}
s.closeFocus(now)
s.pause = &span{kind: kind, start: now}
}
// Resume ends any pause and reopens the last focused window.
func (s *Sessionizer) Resume(now time.Time) {
if s.pause == nil {
return
}
s.closePause(now)
s.openFocus(now)
}
// Close ends every open interval, e.g. on shutdown.
func (s *Sessionizer) Close(now time.Time) {
s.closeFocus(now)
s.closePause(now)
}
func (s *Sessionizer) openFocus(now time.Time) {
if s.last.Class != "" {
s.cur = &span{kind: "app_focus", focus: s.last, start: now}
}
}
func (s *Sessionizer) closeFocus(now time.Time) {
if s.cur == nil {
return
}
var attrs map[string]any
if s.cur.focus.Title != "" {
attrs = map[string]any{"title": s.cur.focus.Title}
}
s.emit(s.cur, s.cur.focus.Class, now, attrs)
s.cur = nil
}
func (s *Sessionizer) closePause(now time.Time) {
if s.pause == nil {
return
}
s.emit(s.pause, s.pause.kind, now, nil)
s.pause = nil
}
func (s *Sessionizer) emit(sp *span, label string, end time.Time, attrs map[string]any) {
if end.Sub(sp.start) < s.MinDuration {
return
}
s.Emit(ingest.Event{
ID: newID(),
Kind: sp.kind,
Label: label,
StartedAt: sp.start.UTC(),
EndedAt: end.UTC(),
Attrs: attrs,
})
}
func newID() string {
b := make([]byte, 16)
rand.Read(b)
return hex.EncodeToString(b)
}
+94
View File
@@ -0,0 +1,94 @@
package hypr
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"strings"
"time"
"ccp/internal/ingest"
)
const uploadBatch = 500
// Uploader sends buffered events to the tracker server.
type Uploader struct {
URL string // server base URL, e.g. https://tracker.example.com
Key string
Buf *Buffer
Client *http.Client
Log *slog.Logger
}
// Flush uploads everything in the buffer, oldest first.
func (u *Uploader) Flush(ctx context.Context) error {
for {
batch := u.Buf.Peek(uploadBatch)
if len(batch) == 0 {
return nil
}
status, err := u.post(ctx, batch)
switch {
case err != nil:
return err
case status == http.StatusBadRequest || status == http.StatusUnprocessableEntity:
// The server will never accept this batch; drop it so it
// doesn't block everything behind it.
u.Log.Error("server rejected batch; dropping it", "status", status, "events", len(batch))
case status != http.StatusOK:
return fmt.Errorf("upload: server returned %d", status)
}
if err := u.Buf.Ack(len(batch)); err != nil {
return err
}
}
}
func (u *Uploader) post(ctx context.Context, events []ingest.Event) (int, error) {
body, err := json.Marshal(ingest.Batch{Events: events})
if err != nil {
return 0, err
}
url := strings.TrimRight(u.URL, "/") + "/api/v1/desktop/events"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return 0, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+u.Key)
resp, err := u.Client.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
u.Log.Warn("upload failed", "status", resp.StatusCode, "body", strings.TrimSpace(string(msg)))
}
return resp.StatusCode, nil
}
// Run flushes every interval until ctx is cancelled, backing off up to
// 10 minutes while the server is unreachable.
func (u *Uploader) Run(ctx context.Context, interval time.Duration) {
wait := interval
for {
select {
case <-ctx.Done():
return
case <-time.After(wait):
}
if err := u.Flush(ctx); err != nil {
wait = min(wait*2, 10*time.Minute)
u.Log.Warn("upload failed; will retry", "err", err, "pending", u.Buf.Len(), "retry_in", wait)
continue
}
wait = interval
}
}