Fix drift sync: per-window verdicts, forgiving class match, event-driven status bar
Three independent defects made the focus state feel flaky and let the OS
status bar disagree with the web UI:
- Status file lagged the web by up to a minute: it rendered only on a 60s
ticker with no hook into state changes. notify() now fans out to multiple
listeners (AddOnChange) and the writer has a coalesced Wake() so drift
reaches the bar as promptly as the browser.
- A brief off-task visit could latch drift for the whole session. Sibling
windows of one app (a browser's reading tab vs its chat tab) share a window
class, but the judge verdict was cached by class alone, so one tab's verdict
poisoned the rest and never re-judged. Cache is now keyed by class + scrubbed
title (judgedWindows) so siblings are judged independently.
- Allowed-class matching was exact equality, so a short token ("brave") never
matched the real WM_CLASS ("Brave-browser") and every window was routed to
the LLM. Matching is now substring-based, and planning surfaces the live
window class with a click-to-add chip so users pick a token that matches.
Also fix the planning checkbox alignment: the global full-width input rule was
stretching the "Enforce focus" checkbox; scope it out for checkboxes.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+23
-10
@@ -76,15 +76,15 @@ func (c *Controller) resetDriftLocked() {
|
||||
c.driftGen++
|
||||
c.nudgeEpoch++
|
||||
c.lastJudgedAt = time.Time{}
|
||||
c.judgedClasses = map[string]ai.Verdict{}
|
||||
c.judgedWindows = map[string]ai.Verdict{}
|
||||
c.recentTitles = nil
|
||||
c.nudgeMessage = ""
|
||||
c.lastNudgedAt = time.Time{}
|
||||
}
|
||||
|
||||
// OnTask appends the current window class to the session allowed-context, clears
|
||||
// drift, drops any cached verdict for that class, and persists. The class now
|
||||
// matches locally and is never re-judged.
|
||||
// drift, drops the cached verdict for the current window, and persists. The
|
||||
// class now matches locally and is never re-judged.
|
||||
func (c *Controller) OnTask() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
@@ -100,7 +100,7 @@ func (c *Controller) OnTask() error {
|
||||
if !evidence.MatchesAllowed(ac, class, "") {
|
||||
c.allowedClasses = append(c.allowedClasses, strings.TrimSpace(class))
|
||||
}
|
||||
delete(c.judgedClasses, class)
|
||||
delete(c.judgedWindows, verdictKey(class, c.stats.Current.Title))
|
||||
}
|
||||
c.driftStatus = driftOnTask
|
||||
c.driftReason = ""
|
||||
@@ -108,7 +108,7 @@ func (c *Controller) OnTask() error {
|
||||
}
|
||||
|
||||
// Refocus clears the current drift verdict without changing allowed-context, and
|
||||
// drops the cached verdict for the current class so it may be judged again later.
|
||||
// drops the cached verdict for the current window so it may be judged again later.
|
||||
func (c *Controller) Refocus() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
@@ -116,7 +116,7 @@ func (c *Controller) Refocus() error {
|
||||
return ErrNotActive
|
||||
}
|
||||
if c.stats != nil {
|
||||
delete(c.judgedClasses, c.stats.Current.Class)
|
||||
delete(c.judgedWindows, verdictKey(c.stats.Current.Class, c.stats.Current.Title))
|
||||
}
|
||||
c.driftStatus = driftIdle
|
||||
c.driftReason = ""
|
||||
@@ -193,8 +193,12 @@ func (c *Controller) evaluateDriftLocked(now time.Time, snap evidence.WindowSnap
|
||||
c.nudgeMessage = ""
|
||||
c.nudgeEpoch++
|
||||
|
||||
// 2. Per-class cache.
|
||||
if v, ok := c.judgedClasses[class]; ok {
|
||||
// 2. Per-window cache, keyed by class+title. A verdict for one window of an
|
||||
// app must not leak to a sibling window of the same class — a browser hosts
|
||||
// both an on-task reading page and an off-task chat under one window class, so
|
||||
// keying by class alone latched one tab's verdict onto every other tab.
|
||||
key := verdictKey(class, title)
|
||||
if v, ok := c.judgedWindows[key]; ok {
|
||||
c.applyVerdictLocked(v)
|
||||
return nil
|
||||
}
|
||||
@@ -241,9 +245,9 @@ func (c *Controller) evaluateDriftLocked(now time.Time, snap evidence.WindowSnap
|
||||
c.notify()
|
||||
return
|
||||
}
|
||||
c.judgedClasses[class] = v
|
||||
c.judgedWindows[key] = v
|
||||
var enforceAct func()
|
||||
if c.stats != nil && c.stats.Current.Class == class {
|
||||
if c.stats != nil && verdictKey(c.stats.Current.Class, c.stats.Current.Title) == key {
|
||||
c.applyVerdictLocked(v)
|
||||
enforceAct = c.enforceActionLocked()
|
||||
}
|
||||
@@ -314,6 +318,15 @@ func (c *Controller) recordTitleLocked(title string) {
|
||||
}
|
||||
}
|
||||
|
||||
// verdictKey identifies the judged window for the per-window verdict cache. It
|
||||
// combines the window class with the scrubbed, casefolded title so sibling
|
||||
// windows of one app (a browser's reading tab vs its chat tab) are judged
|
||||
// independently, while transient title noise (clocks, counts) does not split a
|
||||
// window into ever-changing keys that defeat the cache.
|
||||
func verdictKey(class, title string) string {
|
||||
return strings.ToLower(strings.TrimSpace(class)) + "\x00" + strings.ToLower(evidence.ScrubTitle(title))
|
||||
}
|
||||
|
||||
// applyVerdictLocked maps a verdict onto drift state. Caller holds mu.
|
||||
func (c *Controller) applyVerdictLocked(v ai.Verdict) {
|
||||
if v.OnTask {
|
||||
|
||||
@@ -43,7 +43,7 @@ type Controller struct {
|
||||
auditPath string
|
||||
sessionsDir string
|
||||
clock func() time.Time
|
||||
onChange func()
|
||||
onChanges []func()
|
||||
latestWindow evidence.WindowSnapshot
|
||||
stats *EvidenceStats
|
||||
outcomePending string
|
||||
@@ -80,7 +80,7 @@ type Controller struct {
|
||||
driftGen int
|
||||
nudgeEpoch int // identifies the current on-task stretch; nudge staleness guard
|
||||
lastJudgedAt time.Time
|
||||
judgedClasses map[string]ai.Verdict
|
||||
judgedWindows map[string]ai.Verdict
|
||||
|
||||
nudge ai.Nudger
|
||||
recentTitles []string // in-memory ring of recent distinct titles this session
|
||||
@@ -119,7 +119,7 @@ func New(snapshotPath string) (*Controller, error) {
|
||||
c.allowedClasses = s.AllowedWindowClasses
|
||||
c.enforcementLevel = s.EnforcementLevel
|
||||
// Drift state is not persisted: recompute fresh after restart to avoid
|
||||
// stale interrupts. This also initializes judgedClasses (the pipeline
|
||||
// stale interrupts. This also initializes judgedWindows (the pipeline
|
||||
// writes to it) so a restored Active session never panics on a nil map.
|
||||
c.resetDriftLocked()
|
||||
c.replayStats(s.SessionID)
|
||||
@@ -135,20 +135,32 @@ func (c *Controller) SetClock(f func() time.Time) {
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetOnChange registers a callback fired after an evidence-driven state change
|
||||
// (focus updates). It is invoked with the mutex released.
|
||||
// SetOnChange registers the sole change listener, replacing any already set. A
|
||||
// listener is fired after a state change (focus updates, role results) with the
|
||||
// mutex released. Use AddOnChange to register additional listeners.
|
||||
func (c *Controller) SetOnChange(f func()) {
|
||||
c.mu.Lock()
|
||||
c.onChange = f
|
||||
c.onChanges = []func(){f}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// AddOnChange registers an additional change listener alongside any already set,
|
||||
// so several consumers (the web broadcaster, the status-file writer) all react
|
||||
// to the same notification rather than only the last one wired.
|
||||
func (c *Controller) AddOnChange(f func()) {
|
||||
c.mu.Lock()
|
||||
c.onChanges = append(c.onChanges, f)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *Controller) notify() {
|
||||
c.mu.Lock()
|
||||
f := c.onChange
|
||||
fs := append([]func(){}, c.onChanges...)
|
||||
c.mu.Unlock()
|
||||
if f != nil {
|
||||
f()
|
||||
for _, f := range fs {
|
||||
if f != nil {
|
||||
f()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -386,6 +386,29 @@ func TestStartCommitmentPersistsAllowedClasses(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanningStateExposesCurrentWindowClass(t *testing.T) {
|
||||
c, _ := newTestController(t)
|
||||
c.RecordWindow(obs("Brave-browser", "Consume - Brave"))
|
||||
if err := c.EnterPlanning(); err != nil {
|
||||
t.Fatalf("planning: %v", err)
|
||||
}
|
||||
st := c.State()
|
||||
if st.Evidence == nil || st.Evidence.Current.Class != "Brave-browser" {
|
||||
t.Fatalf("planning should expose the live window class so the user can pick a matching token, got %+v", st.Evidence)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddOnChangeFansOutToAllListeners(t *testing.T) {
|
||||
c, _ := newTestController(t)
|
||||
var a, b int
|
||||
c.SetOnChange(func() { a++ })
|
||||
c.AddOnChange(func() { b++ })
|
||||
c.notify()
|
||||
if a != 1 || b != 1 {
|
||||
t.Fatalf("every registered listener should fire: a=%d b=%d", a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnTaskAppendsCurrentClass(t *testing.T) {
|
||||
c, _ := newTestController(t)
|
||||
_ = c.EnterPlanning()
|
||||
@@ -478,7 +501,54 @@ func TestUnmatchedWindowIsJudgedDrifting(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerClassCacheAvoidsSecondJudge(t *testing.T) {
|
||||
// titleJudge returns a verdict chosen by which substring the title contains,
|
||||
// so a test can model an app (e.g. a browser) hosting both on- and off-task
|
||||
// windows under one window class.
|
||||
type titleJudge struct {
|
||||
byTitle map[string]ai.Verdict
|
||||
calls int32
|
||||
}
|
||||
|
||||
func (j *titleJudge) JudgeDrift(ctx context.Context, commitment, class, title string) (ai.Verdict, error) {
|
||||
atomic.AddInt32(&j.calls, 1)
|
||||
for sub, v := range j.byTitle {
|
||||
if strings.Contains(title, sub) {
|
||||
return v, nil
|
||||
}
|
||||
}
|
||||
return ai.Verdict{OnTask: true}, nil
|
||||
}
|
||||
|
||||
// A brief off-task window must not poison every later same-class window. Teams
|
||||
// and a Consume reading page are both class "Brave-browser"; caching the judge
|
||||
// verdict by class alone made the on-task page inherit Teams's drift verdict
|
||||
// (and never re-judge), latching drift for the rest of the session.
|
||||
func TestVerdictCacheKeysOnTitleNotClassAlone(t *testing.T) {
|
||||
c, _ := newTestController(t)
|
||||
now := time.Now()
|
||||
c.SetClock(func() time.Time { return now })
|
||||
fj := &titleJudge{byTitle: map[string]ai.Verdict{
|
||||
"Teams": {OnTask: false, Reason: "Teams is off-task"},
|
||||
"Consume": {OnTask: true},
|
||||
}}
|
||||
c.SetDriftJudge(fj)
|
||||
startActive(t, c, []string{"code"}) // Brave-browser never matches locally
|
||||
|
||||
c.RecordWindow(obs("Brave-browser", "Microsoft Teams - Brave"))
|
||||
waitDriftStatus(t, c, "drifting")
|
||||
|
||||
now = now.Add(2 * driftDebounce) // clear debounce so a re-judge is allowed
|
||||
c.RecordWindow(obs("Brave-browser", "Consume - Brave"))
|
||||
st := waitDriftStatus(t, c, "ontask")
|
||||
if st.Drift.Reason != "" {
|
||||
t.Fatalf("on-task window must not carry the Teams reason: %+v", st.Drift)
|
||||
}
|
||||
if got := atomic.LoadInt32(&fj.calls); got != 2 {
|
||||
t.Fatalf("different title under same class should re-judge, calls=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerWindowCacheAvoidsSecondJudge(t *testing.T) {
|
||||
c, _ := newTestController(t)
|
||||
now := time.Now()
|
||||
c.SetClock(func() time.Time { return now })
|
||||
@@ -488,12 +558,13 @@ func TestPerClassCacheAvoidsSecondJudge(t *testing.T) {
|
||||
c.RecordWindow(obs("firefox", "YouTube"))
|
||||
waitDriftStatus(t, c, "drifting")
|
||||
// Advance past the debounce window so a second judge call would be allowed:
|
||||
// this isolates the per-class cache as the only reason the judge is skipped.
|
||||
// this isolates the per-window cache as the only reason the judge is skipped.
|
||||
now = now.Add(2 * driftDebounce)
|
||||
c.RecordWindow(obs("firefox", "Reddit")) // same class, should hit cache
|
||||
c.RecordWindow(obs("Code", "main.go")) // switch away (local on-task match)
|
||||
c.RecordWindow(obs("firefox", "YouTube")) // same window, should hit cache
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := atomic.LoadInt32(&fj.calls); got != 1 {
|
||||
t.Fatalf("cached class should not re-judge, calls=%d", got)
|
||||
t.Fatalf("cached window should not re-judge, calls=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,7 +625,7 @@ func TestRestoredActiveSessionCanBeJudged(t *testing.T) {
|
||||
t.Fatalf("reload: %v", err)
|
||||
}
|
||||
second.SetDriftJudge(&fakeJudge{verdict: ai.Verdict{OnTask: false, Reason: "off-task"}})
|
||||
second.RecordWindow(obs("firefox", "YouTube")) // must not panic on nil judgedClasses map
|
||||
second.RecordWindow(obs("firefox", "YouTube")) // must not panic on nil judgedWindows map
|
||||
waitDriftStatus(t, second, "drifting")
|
||||
}
|
||||
|
||||
@@ -714,8 +785,8 @@ func TestNudgeDoesNotRunOnDriftPath(t *testing.T) {
|
||||
c.SetDriftJudge(&fakeJudge{verdict: ai.Verdict{OnTask: false, Reason: "off-task"}})
|
||||
startActive(t, c, []string{"code"})
|
||||
c.RecordWindow(obs("firefox", "YouTube"))
|
||||
c.RecordWindow(obs("firefox", "Reddit"))
|
||||
waitDriftStatus(t, c, "drifting")
|
||||
c.RecordWindow(obs("firefox", "Reddit")) // second off-task title builds nudge history
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := atomic.LoadInt32(&fn.calls); got != 0 {
|
||||
t.Fatalf("nudge must not run on the drift path, calls=%d", got)
|
||||
@@ -1484,7 +1555,8 @@ func TestRecordWindowCreditsSplitFaithfully(t *testing.T) {
|
||||
waitDriftStatus(t, c, "drifting") // wait for the async verdict before crediting the firefox segment
|
||||
|
||||
clk.advance(8 * time.Minute)
|
||||
c.RecordWindow(snap("firefox", "Reddit")) // credits 8m to firefox/YouTube while drifting -> off-task; cache keeps drifting
|
||||
c.RecordWindow(snap("firefox", "Reddit")) // credits 8m to firefox/YouTube while drifting -> off-task
|
||||
waitDriftStatus(t, c, "drifting") // Reddit is a distinct window: re-judged off-task before its segment is credited
|
||||
clk.advance(4 * time.Minute)
|
||||
if err := c.Complete(); err != nil { // flush: credits 4m to firefox/Reddit while drifting -> off-task
|
||||
t.Fatalf("complete: %v", err)
|
||||
|
||||
@@ -125,6 +125,14 @@ func (c *Controller) stateLocked() State {
|
||||
}
|
||||
}
|
||||
if c.runtimeState == domain.RuntimePlanning {
|
||||
// Surface the live window so planning can show the real class to copy into
|
||||
// the allowed-apps field — exact class names are otherwise invisible, and a
|
||||
// non-matching token silently disables the local on-task fast path.
|
||||
st.Evidence = &EvidenceView{
|
||||
Available: c.latestWindow.Health.Available,
|
||||
Reason: c.latestWindow.Health.Reason,
|
||||
Current: WindowView{Class: c.latestWindow.Class, Title: c.latestWindow.Title},
|
||||
}
|
||||
status := c.coachStatus
|
||||
if status == "" {
|
||||
status = coachIdle
|
||||
|
||||
Reference in New Issue
Block a user