Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ offload config open interactive settings (terminal only)
offload ls [n] list the last n runs (default 10)
offload show <session> print every report of a session
offload status what each worker is doing right now
offload stats [--json] [--period today|week|month|all]
offload stats [--json] [--period today|last7|last30|week|month|all]
run, token and cost totals for a period (default today)
offload watch [-t dur] one line per event (started, progress, STALLED, finished) until all workers end;
with -t, stop after dur and exit 124 if workers are still active
Expand Down Expand Up @@ -442,6 +442,8 @@ Native clients can use `offload history list --json` and `offload history show -
offload stats # today, local time
offload stats --period week # since Monday 00:00
offload stats --period month # since the 1st, 00:00
offload stats --period last7 # last 7 local calendar days, including today
offload stats --period last30 # last 30 local calendar days, including today
offload stats --period all # entire history
offload stats --json --period week # one JSON document for tools
```
Expand Down Expand Up @@ -497,7 +499,9 @@ Plain text adds `processing now`, `queued`, `recorded calls today`, `peak proces

**Peak processing** is the highest overlap of processing spans on a local day. A span runs from admission (the run starts processing, after queue wait) until the worker stops (cleanup, finish or cancellation); a salvage step belongs to the same span, and queue wait, cleanup and unresolved leftovers do not. Spans are half-open `[start, end)`, so a run that ends when another starts does not overlap it, and a span crossing midnight counts on both days. Offload writes the span boundaries with nanosecond timestamps to `processing.jsonl` next to `runs.jsonl`, keyed by `run_id`; live files and UI polling are not used, so short tasks between polls and a restarted app are covered. `peak_coverage` is `full`, `partial` (a lower bound: the log starts mid-day, a run has no recorded end because offload was killed, lines are damaged, or admitted runs have no events because they predate the log) or `unavailable` with `peak_processing` `null`. Days before the first event are never reported as a peak of zero. A run with no recorded end also makes every later day's peak a lower bound (`partial`), since it may have kept processing past midnight. `stats` keeps report bodies in memory only for the newest runs that `recent` can list.

The native panel shows processing now / 100, calls today / 10,000, peak today and the 7-day average at the top, with queued work on its own line. Goal bars saturate, but the number next to them keeps the raw value. This is separate from caller aggregation (`caller_run_id`) and release verification, which are unchanged.
The native panel offers Today, 7 Days, 30 Days and All. It defaults to 7 Days; saved Week/Month choices map to 7/30 Days, including today in the local time zone. This changes the viewing window without deleting recorded history. CLI `week` and `month` retain their calendar-period meanings.

Each panel list shows up to four entries per page, with the visible range and page count. Changing the period, caller filter or detail tab returns to the first page. A compact two-line overview shows processing now / 100, calls today / 10,000, peak today, the 7-day average and queued work. Warning icons keep stalled or partial coverage visible; help and accessibility descriptions retain coverage, admission, scope and goal explanations. These workload metrics remain computer-wide when filtering callers or periods.

To build and open the menu bar monitor on macOS:

Expand Down
4 changes: 2 additions & 2 deletions internal/cli/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ type statsOutput struct {
Daily statsDaily `json:"daily"`
}

const statsUsage = "usage: offload stats [--json] [--period today|week|month|all] [--caller ID]"
const statsUsage = "usage: offload stats [--json] [--period today|last7|last30|week|month|all] [--caller ID]"

func cmdStats(args []string, stdout, stderr io.Writer) int {
return runStats(args, time.Now(), stdout, stderr)
Expand All @@ -59,7 +59,7 @@ func runStats(args []string, now time.Time, stdout, stderr io.Writer) int {
var caller callerFlag
fs.Var(&caller, "caller", "filter completed-run metrics by caller ID; workload and daily goals remain computer-wide")
asJSON := fs.Bool("json", false, "print one JSON document")
period := fs.String("period", history.PeriodToday, "today, week (from Monday), month or all")
period := fs.String("period", history.PeriodToday, "today, last7, last30, week (from Monday), month or all")
if err := fs.Parse(args); err != nil {
return 2
}
Expand Down
25 changes: 25 additions & 0 deletions internal/cli/stats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,31 @@ func TestStatsJSONEmptyContract(t *testing.T) {
}
}

func TestStatsRollingPeriodsAndLegacyCalendarPeriods(t *testing.T) {
t.Setenv("XDG_STATE_HOME", t.TempDir())
now := time.Date(2026, 10, 29, 12, 0, 0, 0, time.FixedZone("X", 3600))
for period, wantLabel := range map[string]string{
"last7": "Last 7 days", "last30": "Last 30 days", "week": "This week", "month": "This month",
} {
code, out, errOut := statsRun(t, now, "--json", "--period", period)
if code != 0 {
t.Fatalf("%s: code=%d stderr=%q", period, code, errOut)
}
var got struct {
Period string `json:"period"`
Trend struct {
Label string `json:"label"`
} `json:"trend"`
}
if err := json.Unmarshal([]byte(out), &got); err != nil {
t.Fatal(err)
}
if got.Period != period || got.Trend.Label != wantLabel {
t.Errorf("%s: %+v", period, got)
}
}
}

func TestStatsJSONRecordsAndActive(t *testing.T) {
t.Setenv("XDG_STATE_HOME", t.TempDir())
// A fixed instant keeps the record inside the period and the idle times deterministic. The
Expand Down
34 changes: 25 additions & 9 deletions internal/history/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import (

// Stats periods accepted by Aggregate.
const (
PeriodToday = "today"
PeriodWeek = "week"
PeriodMonth = "month"
PeriodAll = "all"
PeriodToday = "today"
PeriodLast7 = "last7"
PeriodLast30 = "last30"
PeriodWeek = "week"
PeriodMonth = "month"
PeriodAll = "all"
)

const (
Expand Down Expand Up @@ -131,27 +133,33 @@ type Stats struct {
// ValidPeriod reports whether p is a period Aggregate accepts.
func ValidPeriod(p string) bool {
switch p {
case PeriodToday, PeriodWeek, PeriodMonth, PeriodAll:
case PeriodToday, PeriodLast7, PeriodLast30, PeriodWeek, PeriodMonth, PeriodAll:
return true
}
return false
}

// PeriodStart is the first instant of the period in now's location: the calendar day, the week
// starting Monday, or the calendar month. For "all" it is the zero time.
// PeriodStart is the first instant of the period in now's location: the calendar day, the last
// 7 or 30 calendar days including today, the week starting Monday, or the calendar month. For
// "all" it is the zero time.
func PeriodStart(period string, now time.Time) (time.Time, error) {
y, m, d := now.Date()
today := time.Date(y, m, d, 0, 0, 0, 0, now.Location())
switch period {
case PeriodToday:
return time.Date(y, m, d, 0, 0, 0, 0, now.Location()), nil
return today, nil
case PeriodLast7:
return today.AddDate(0, 0, -6), nil
case PeriodLast30:
return today.AddDate(0, 0, -29), nil
case PeriodWeek:
return time.Date(y, m, d-(int(now.Weekday())+6)%7, 0, 0, 0, 0, now.Location()), nil
case PeriodMonth:
return time.Date(y, m, 1, 0, 0, 0, 0, now.Location()), nil
case PeriodAll:
return time.Time{}, nil
}
return time.Time{}, fmt.Errorf("unknown period %q; use today, week, month or all", period)
return time.Time{}, fmt.Errorf("unknown period %q; use today, last7, last30, week, month or all", period)
}

// ParseTS reads a record timestamp: the local "2006-01-02 15:04:05" layout (interpreted in loc)
Expand Down Expand Up @@ -294,6 +302,10 @@ func trendStarts(period string, now time.Time) (interval, label string, starts [
starts = append(starts, t)
}
return
case PeriodLast7:
label = "Last 7 days"
case PeriodLast30:
label = "Last 30 days"
case PeriodWeek:
label = "This week"
case PeriodMonth:
Expand All @@ -303,6 +315,10 @@ func trendStarts(period string, now time.Time) (interval, label string, starts [
}
first := today
switch period {
case PeriodLast7:
first = today.AddDate(0, 0, -6)
case PeriodLast30:
first = today.AddDate(0, 0, -29)
case PeriodWeek:
first = today.AddDate(0, 0, -((int(now.Weekday()) + 6) % 7))
case PeriodMonth:
Expand Down
59 changes: 59 additions & 0 deletions internal/history/stats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,8 @@ func TestPeriodBoundariesAndTimezone(t *testing.T) {
now := time.Date(2026, 10, 29, 12, 0, 0, 0, loc) // Thursday
cases := []struct{ period, start string }{
{PeriodToday, "2026-10-29 00:00:00"},
{PeriodLast7, "2026-10-23 00:00:00"},
{PeriodLast30, "2026-09-30 00:00:00"},
{PeriodWeek, "2026-10-26 00:00:00"}, // Monday
{PeriodMonth, "2026-10-01 00:00:00"},
}
Expand Down Expand Up @@ -224,6 +226,63 @@ func TestPeriodBoundariesAndTimezone(t *testing.T) {
}
}

func TestRollingPeriodBoundsDSTMonthYearAndAggregation(t *testing.T) {
loc, err := time.LoadLocation("America/New_York")
if err != nil {
t.Skip("no tz database: ", err)
}
now := time.Date(2026, 3, 10, 12, 0, 0, 0, loc)
start7, err := PeriodStart(PeriodLast7, now)
if err != nil || start7.Format(time.RFC3339) != "2026-03-04T00:00:00-05:00" {
t.Fatalf("last7 start: %s %v", start7.Format(time.RFC3339), err)
}
start30, err := PeriodStart(PeriodLast30, now)
if err != nil || start30.Format(time.RFC3339) != "2026-02-09T00:00:00-05:00" {
t.Fatalf("last30 start: %s %v", start30.Format(time.RFC3339), err)
}
yearNow := time.Date(2027, 1, 3, 9, 0, 0, 0, loc)
if start, _ := PeriodStart(PeriodLast30, yearNow); start.Format(time.RFC3339) != "2026-12-05T00:00:00-05:00" {
t.Fatalf("cross-year last30 start: %s", start.Format(time.RFC3339))
}

rs := []Record{
{TS: start30.Add(-time.Second).Format(time.RFC3339), Status: "ok", Session: "before30"},
{TS: start30.Format(time.RFC3339), Status: "ok", Session: "first30"},
{TS: start7.Add(-time.Second).Format(time.RFC3339), Status: "ok", Session: "before"},
{TS: start7.Format(time.RFC3339), Status: "ok", Session: "first"},
{TS: now.Format(time.RFC3339), Status: "ok", Session: "now"},
{TS: now.Add(time.Second).Format(time.RFC3339), Status: "ok", Session: "future"},
}
st, err := Aggregate(rs, PeriodLast7, now)
if err != nil {
t.Fatal(err)
}
if st.Totals.Runs != 2 || st.Totals.Sessions != 2 || len(st.Trend.Points) != 7 || st.Trend.Label != "Last 7 days" {
t.Fatalf("last7 aggregate: totals=%+v trend=%+v", st.Totals, st.Trend)
}
if st.Trend.Points[0].Start != "2026-03-04T00:00:00-05:00" || st.Trend.Points[4].Start != "2026-03-08T00:00:00-05:00" || st.Trend.Points[5].Start != "2026-03-09T00:00:00-04:00" {
t.Fatalf("last7 DST buckets: %+v", st.Trend.Points)
}
var trendRuns int
for _, p := range st.Trend.Points {
trendRuns += p.Totals.Runs
}
if trendRuns != st.Totals.Runs {
t.Fatalf("trend runs %d != total runs %d", trendRuns, st.Totals.Runs)
}
last30, err := Aggregate(rs, PeriodLast30, now)
if err != nil || len(last30.Trend.Points) != 30 || last30.Trend.Label != "Last 30 days" || last30.Totals.Runs != 4 {
t.Fatalf("last30 trend: %d %q total=%d %v", len(last30.Trend.Points), last30.Trend.Label, last30.Totals.Runs, err)
}
trendRuns = 0
for _, p := range last30.Trend.Points {
trendRuns += p.Totals.Runs
}
if trendRuns != last30.Totals.Runs {
t.Fatalf("last30 trend runs %d != total runs %d", trendRuns, last30.Totals.Runs)
}
}

func TestRecentOrderLimitAndTruncation(t *testing.T) {
now := time.Date(2026, 10, 29, 23, 0, 0, 0, time.UTC)
var rs []Record
Expand Down
13 changes: 9 additions & 4 deletions macos/Sources/OffloadMonitor/Pagination.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ enum Pagination {
let p = clamp(page, total: total, size: size)
return "\(p * size + 1)–\(min(total, p * size + size)) of \(total)"
}

static func pageLabel(page: Int, total: Int, size: Int) -> String {
let pages = pageCount(total: total, size: size)
return "Page \(clamp(page, total: total, size: size) + 1) of \(pages)"
}
}

/// Fixed panel geometry. The main panel never scrolls, so every region has a set height.
Expand All @@ -33,11 +38,11 @@ enum Layout {
static let height: CGFloat = 720
static let notice: CGFloat = 36
static let chart: CGFloat = 48
static let list: CGFloat = 132
static let list: CGFloat = 206
static let pager: CGFloat = 20
static let taskPageSize = 2
static let rowPageSize = 3
static let taskRow: CGFloat = 52
static let taskPageSize = 4
static let rowPageSize = 4
static let taskRow: CGFloat = 44
static let historyRow: CGFloat = 36
static let groupRow: CGFloat = 30
}
33 changes: 24 additions & 9 deletions macos/Sources/OffloadMonitor/PopoverView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ struct PopoverView: View {
PanelAction(symbol: "gearshape", title: "Settings (⌘,)") { AppState.shared.showSettings() }
}
HStack(spacing: 12) {
PanelSegments("Period", values: StatsPeriod.allCases, selection: $model.period) { $0.label }
PanelSegments("Period", values: StatsPeriod.allCases, selection: $model.period,
help: { $0.explanation }) { $0.label }
ProfileMenu(profiles: profiles)
}
}
Expand All @@ -80,7 +81,7 @@ struct PopoverView: View {

@ViewBuilder private var content: some View {
if let s = model.snapshot {
SnapshotView(snapshot: s, callerFilter: $model.callerFilter, callerGroups: model.callerGroups)
SnapshotView(snapshot: s, period: model.period, callerFilter: $model.callerFilter, callerGroups: model.callerGroups)
} else if model.lastError == nil {
HStack { ProgressView().controlSize(.small); Text("Loading…").font(.caption).foregroundStyle(.secondary) }
.frame(maxWidth: .infinity, minHeight: 120)
Expand Down Expand Up @@ -156,11 +157,14 @@ struct PanelSegments<Selection: Hashable>: View {
let values: [Selection]
@Binding var selection: Selection
let label: (Selection) -> String
let valueHelp: ((Selection) -> String)?

init(_ title: String, values: [Selection], selection: Binding<Selection>, label: @escaping (Selection) -> String) {
init(_ title: String, values: [Selection], selection: Binding<Selection>,
help: ((Selection) -> String)? = nil, label: @escaping (Selection) -> String) {
self.title = title
self.values = values
self._selection = selection
self.valueHelp = help
self.label = label
}

Expand All @@ -177,6 +181,9 @@ struct PanelSegments<Selection: Hashable>: View {
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.help(valueHelp?(value) ?? label(value))
.accessibilityLabel(label(value))
.accessibilityHint(valueHelp?(value) ?? "")
.accessibilityAddTraits(selection == value ? .isSelected : [])
}
}
Expand Down Expand Up @@ -506,14 +513,15 @@ enum DetailTab: String, CaseIterable, Identifiable {

struct SnapshotView: View {
let snapshot: StatsSnapshot
let period: StatsPeriod
@Binding var callerFilter: String?
var callerGroups: [StatsGroup]
@State private var tab: DetailTab = .tasks
@State private var page = 0

var body: some View {
VStack(alignment: .leading, spacing: 6) {
WorkloadPanel(snapshot: snapshot)
WorkloadPanel(snapshot: snapshot, compact: true)
HStack {
Text(callerFilter == nil ? "All callers" : "Caller: \(callerFilter!)").font(.system(size: 10, weight: .medium)).lineLimit(1)
Spacer(minLength: 4)
Expand All @@ -531,6 +539,8 @@ struct SnapshotView: View {
t == .tasks && !snapshot.active.isEmpty ? "Tasks (\(snapshot.active.count))" : t.rawValue
}
.onChange(of: tab) { _ in page = 0 }
.onChange(of: period) { _ in page = 0 }
.onChange(of: callerFilter) { _ in page = 0 }
list
HStack(spacing: 12) {
Button { AppState.shared.showDetails() } label: { Label("Token and cost detail", systemImage: "chart.bar.doc.horizontal") }
Expand Down Expand Up @@ -591,14 +601,19 @@ struct SnapshotView: View {
Spacer(minLength: 0)
HStack(spacing: 6) {
Text(Pagination.rangeLabel(page: p, total: items.count, size: size)).font(.system(size: 9)).foregroundStyle(.secondary)
Text(Pagination.pageLabel(page: p, total: items.count, size: size)).font(.system(size: 9)).foregroundStyle(.secondary)
Spacer()
if tab == .history {
Button("Browse all") { AppState.shared.browseHistory() }
.help("Search and open every conversation")
}
if pages > 1 {
Button { page = p - 1 } label: { Image(systemName: "chevron.left") }.disabled(p == 0).help("Previous page")
Button { page = p + 1 } label: { Image(systemName: "chevron.right") }.disabled(p >= pages - 1).help("Next page")
Button { page = p - 1 } label: { Image(systemName: "chevron.left") }
.disabled(p == 0).help("Previous page").accessibilityLabel("Previous page")
.accessibilityHint("Shows page \(max(1, p)) of \(pages)")
Button { page = p + 1 } label: { Image(systemName: "chevron.right") }
.disabled(p >= pages - 1).help("Next page").accessibilityLabel("Next page")
.accessibilityHint("Shows page \(min(p + 2, pages)) of \(pages)")
}
}
.buttonStyle(.borderless)
Expand Down Expand Up @@ -745,14 +760,14 @@ struct ActiveRow: View {

@ViewBuilder private var row: some View {
let t = task
HStack(spacing: 9) {
HStack(spacing: 7) {
Image(systemName: stateSymbol)
.font(.system(size: 15, weight: .medium)).symbolRenderingMode(.hierarchical)
.foregroundStyle(stateTint)
.frame(width: 28, height: 28)
.frame(width: 24, height: 24)
.background(stateTint.opacity(0.10), in: RoundedRectangle(cornerRadius: 8))
.help(task.stalled ? "No recent progress reported" : "Task state: \(task.phase)")
VStack(alignment: .leading, spacing: 2) {
VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 4) {
Text("Caller: \(t.callerName)")
.font(.system(size: 9, weight: .semibold))
Expand Down
10 changes: 9 additions & 1 deletion macos/Sources/OffloadMonitor/Preferences.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,15 @@ struct Preferences {
init(defaults: UserDefaults = .standard) { self.defaults = defaults }

var period: StatsPeriod {
get { defaults.string(forKey: Key.period).flatMap(StatsPeriod.init(rawValue:)) ?? .today }
get {
switch defaults.string(forKey: Key.period) {
case "today": return .today
case "last30", "month": return .last30
case "all": return .all
case "last7", "week", nil: return .last7
default: return .last7
}
}
nonmutating set { defaults.set(newValue.rawValue, forKey: Key.period) }
}
/// Default on.
Expand Down
Loading
Loading