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) }