Files
antidrift/internal/statusfile/statusfile.go
T
felixm 13633ffabf 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>
2026-06-04 09:25:30 -04:00

136 lines
3.9 KiB
Go

// Package statusfile mirrors the controller's runtime status into a single-line
// file (~/.antidrift_status) so an external consumer — a window-manager status
// bar — can display it with a plain file read.
package statusfile
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"time"
"antidrift/internal/domain"
"antidrift/internal/session"
)
// statusFileName is the file written under the user's home directory.
const statusFileName = ".antidrift_status"
// interval is how often the writer re-renders. Minute granularity is enough for
// a status bar, so a coarse tick keeps the write rate (and disk churn) low.
const interval = time.Minute
// DefaultPath resolves ~/.antidrift_status.
func DefaultPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, statusFileName), nil
}
// Render produces the single status line for the given state. It is empty for
// Locked/idle so a bar module can hide itself. Drift status strings ("drifting")
// match the JSON contract the web UI already consumes.
func Render(st session.State, now time.Time) string {
switch st.RuntimeState {
case domain.RuntimeActive:
timer := remaining(st, now)
switch {
case st.Drift != nil && st.Drift.Status == "drifting":
return "⚠ DRIFT " + timer
case st.Drift != nil && st.Drift.Nudge != "":
return "● " + timer + " ·?"
default:
return "● " + timer
}
case domain.RuntimePlanning:
return "◔ planning"
case domain.RuntimeReview:
return "✓ review"
default:
return ""
}
}
// remaining formats the minutes left until the commitment deadline, rounded up
// so a partial minute still reads as a minute and the count hits 0m only at the
// end. It returns 0m when no deadline is known.
func remaining(st session.State, now time.Time) string {
if st.Commitment == nil || st.Commitment.DeadlineUnixSecs == 0 {
return "0m"
}
left := time.Unix(st.Commitment.DeadlineUnixSecs, 0).Sub(now)
if left < 0 {
left = 0
}
mins := int((left + time.Minute - 1) / time.Minute) // ceil
return fmt.Sprintf("%dm", mins)
}
// Writer periodically renders the controller state and writes it to a file,
// rewriting only when the line changes.
type Writer struct {
path string
state func() session.State
now func() time.Time
wake chan struct{}
last string
wrote bool
}
// NewWriter builds a Writer for path, reading state via the given accessor.
func NewWriter(path string, state func() session.State) *Writer {
return &Writer{path: path, state: state, now: time.Now, wake: make(chan struct{}, 1)}
}
// Wake asks the writer to re-render now rather than at the next tick. It is the
// hook the controller's change notifications fire through, so drift transitions
// reach the status bar promptly instead of lagging the web UI by up to a tick.
// The signal is coalesced (buffered, size 1): a burst of changes collapses into
// a single re-render, and the actual write still happens on the Run goroutine,
// so concurrent callers never race on the file.
func (w *Writer) Wake() {
select {
case w.wake <- struct{}{}:
default: // a re-render is already pending
}
}
// Run writes the status file immediately, then re-renders on each wake or tick
// when the rendered line has changed. The tick still advances the minute
// countdown when nothing else changes. It removes the file on ctx cancellation
// so a stale status does not linger after shutdown.
func (w *Writer) Run(ctx context.Context) {
t := time.NewTicker(interval)
defer t.Stop()
w.write()
for {
select {
case <-ctx.Done():
_ = os.Remove(w.path)
return
case <-w.wake:
w.write()
case <-t.C:
w.write()
}
}
}
func (w *Writer) write() {
line := Render(w.state(), w.now())
if w.wrote && line == w.last {
return
}
if err := os.WriteFile(w.path, []byte(line), 0o644); err != nil {
log.Printf("statusfile: write %s: %v", w.path, err)
return
}
w.last = line
w.wrote = true
}