diff --git a/docs/guide.md b/docs/guide.md index dbad77a..4d9be50 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -316,7 +316,7 @@ offload config open interactive settings (terminal only) offload ls [n] list the last n runs (default 10) offload show 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 @@ -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 ``` @@ -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: diff --git a/internal/cli/stats.go b/internal/cli/stats.go index 037cf8d..0b9548d 100644 --- a/internal/cli/stats.go +++ b/internal/cli/stats.go @@ -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) @@ -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 } diff --git a/internal/cli/stats_test.go b/internal/cli/stats_test.go index 3c52945..804a7bb 100644 --- a/internal/cli/stats_test.go +++ b/internal/cli/stats_test.go @@ -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 diff --git a/internal/history/stats.go b/internal/history/stats.go index fed5500..a811c4b 100644 --- a/internal/history/stats.go +++ b/internal/history/stats.go @@ -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 ( @@ -131,19 +133,25 @@ 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: @@ -151,7 +159,7 @@ func PeriodStart(period string, now time.Time) (time.Time, error) { 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) @@ -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: @@ -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: diff --git a/internal/history/stats_test.go b/internal/history/stats_test.go index 94c91a4..4ea754a 100644 --- a/internal/history/stats_test.go +++ b/internal/history/stats_test.go @@ -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"}, } @@ -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 diff --git a/macos/Sources/OffloadMonitor/Pagination.swift b/macos/Sources/OffloadMonitor/Pagination.swift index 90faacc..5e35585 100644 --- a/macos/Sources/OffloadMonitor/Pagination.swift +++ b/macos/Sources/OffloadMonitor/Pagination.swift @@ -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. @@ -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 } diff --git a/macos/Sources/OffloadMonitor/PopoverView.swift b/macos/Sources/OffloadMonitor/PopoverView.swift index bf16167..019322b 100644 --- a/macos/Sources/OffloadMonitor/PopoverView.swift +++ b/macos/Sources/OffloadMonitor/PopoverView.swift @@ -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) } } @@ -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) @@ -156,11 +157,14 @@ struct PanelSegments: View { let values: [Selection] @Binding var selection: Selection let label: (Selection) -> String + let valueHelp: ((Selection) -> String)? - init(_ title: String, values: [Selection], selection: Binding, label: @escaping (Selection) -> String) { + init(_ title: String, values: [Selection], selection: Binding, + help: ((Selection) -> String)? = nil, label: @escaping (Selection) -> String) { self.title = title self.values = values self._selection = selection + self.valueHelp = help self.label = label } @@ -177,6 +181,9 @@ struct PanelSegments: View { .contentShape(Rectangle()) } .buttonStyle(.plain) + .help(valueHelp?(value) ?? label(value)) + .accessibilityLabel(label(value)) + .accessibilityHint(valueHelp?(value) ?? "") .accessibilityAddTraits(selection == value ? .isSelected : []) } } @@ -506,6 +513,7 @@ 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 @@ -513,7 +521,7 @@ struct SnapshotView: View { 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) @@ -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") } @@ -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) @@ -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)) diff --git a/macos/Sources/OffloadMonitor/Preferences.swift b/macos/Sources/OffloadMonitor/Preferences.swift index 7fed530..fe1faa9 100644 --- a/macos/Sources/OffloadMonitor/Preferences.swift +++ b/macos/Sources/OffloadMonitor/Preferences.swift @@ -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. diff --git a/macos/Sources/OffloadMonitor/StatsModels.swift b/macos/Sources/OffloadMonitor/StatsModels.swift index 3c4df94..5d2f61e 100644 --- a/macos/Sources/OffloadMonitor/StatsModels.swift +++ b/macos/Sources/OffloadMonitor/StatsModels.swift @@ -11,16 +11,24 @@ enum AppIdentity { } enum StatsPeriod: String, CaseIterable, Identifiable, Codable { - case today, week, month, all + case today, last7, last30, all var id: String { rawValue } var label: String { switch self { case .today: return "Today" - case .week: return "Week" - case .month: return "Month" + case .last7: return "7 Days" + case .last30: return "30 Days" case .all: return "All" } } + var explanation: String { + switch self { + case .today: return "Today, from local midnight through now." + case .last7: return "The last 7 local calendar days, including today." + case .last30: return "The last 30 local calendar days, including today." + case .all: return "All recorded history." + } + } } struct TokenUsage: Codable, Equatable { diff --git a/macos/Sources/OffloadMonitor/WorkloadView.swift b/macos/Sources/OffloadMonitor/WorkloadView.swift index 2d1af3e..f0f9e7a 100644 --- a/macos/Sources/OffloadMonitor/WorkloadView.swift +++ b/macos/Sources/OffloadMonitor/WorkloadView.swift @@ -4,11 +4,21 @@ import SwiftUI /// this view only formats them. Goals are observability targets, not limits or measured capacity. struct WorkloadPanel: View { let snapshot: StatsSnapshot + var compact = false + @ViewBuilder var body: some View { let w = snapshot.workload let d = snapshot.daily let g = snapshot.goals + if compact { + compactBody(w, d, g) + } else { + fullBody(w, d, g) + } + } + + private func fullBody(_ w: Workload?, _ d: Daily?, _ g: WorkloadGoals) -> some View { Card(tint: .omTeal) { VStack(alignment: .leading, spacing: 3) { HStack(alignment: .top, spacing: 10) { @@ -42,6 +52,95 @@ struct WorkloadPanel: View { } } + private func compactBody(_ w: Workload?, _ d: Daily?, _ g: WorkloadGoals) -> some View { + Card(tint: .omTeal) { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + compactPrimary(title: "Processing now", value: WorkloadPresentation.processingValue(w), goal: g.processing, + detail: processingDetail(w, goal: g.processing), + warn: (w?.stalled ?? 0) > 0 || w?.status == "partial") + compactPrimary(title: "Calls today", value: WorkloadPresentation.callsValue(d), goal: g.dailyCalls, + detail: callsDetail(d, goal: g.dailyCalls), warn: false) + } + HStack(spacing: 8) { + compactSecondary(title: "Peak today", value: WorkloadPresentation.peakValue(d), + detail: peakDetail(d, goal: g.processing), warn: d?.today.peakCoverage == "partial") + compactSecondary(title: "7-day avg", value: WorkloadPresentation.averageValue(d), + detail: averageDetail(d, goal: g.dailyCalls), + warn: d != nil && d?.average.coverage != "complete") + compactSecondary(title: "Queued", value: WorkloadPresentation.number(w?.queued), + detail: queueDetail(w), warn: false) + } + } + } + } + + private func compactPrimary(title: String, value: String, goal: Int, detail: String, warn: Bool) -> some View { + HStack(alignment: .firstTextBaseline, spacing: 2) { + Text(title).font(.system(size: 9.5)).foregroundStyle(Color.secondary).lineLimit(1).minimumScaleFactor(0.8) + .frame(width: 78, alignment: .leading) + if warn { warningIcon } + Text(value).font(.system(size: 16, weight: .semibold).monospacedDigit()).lineLimit(1).minimumScaleFactor(0.55) + .frame(maxWidth: .infinity, alignment: .trailing) + Text("/ \(WorkloadPresentation.exact(goal))").font(.system(size: 9).monospacedDigit()).foregroundStyle(Color.secondary) + .lineLimit(1).fixedSize(horizontal: true, vertical: false) + } + .frame(maxWidth: .infinity, alignment: .leading) + .help(detail) + .accessibilityElement(children: .ignore) + .accessibilityLabel(title) + .accessibilityValue("\(value) of \(WorkloadPresentation.exact(goal))") + .accessibilityHint(detail) + } + + private func compactSecondary(title: String, value: String, detail: String, warn: Bool) -> some View { + HStack(alignment: .firstTextBaseline, spacing: 3) { + Text(title).font(.system(size: 9)).foregroundStyle(Color.secondary).lineLimit(1).minimumScaleFactor(0.75) + Spacer(minLength: 1) + if warn { warningIcon } + Text(value).font(.system(size: 10, weight: .semibold).monospacedDigit()).lineLimit(1).minimumScaleFactor(0.55) + } + .frame(maxWidth: .infinity, alignment: .leading) + .help(detail) + .accessibilityElement(children: .ignore) + .accessibilityLabel(title) + .accessibilityValue(value) + .accessibilityHint(detail) + } + + private var warningIcon: some View { + Image(systemName: "exclamationmark.triangle.fill") + .font(.system(size: 8)).foregroundStyle(Color.orange) + .accessibilityHidden(true) + } + + private func scope(_ w: Workload?) -> String { + guard let scope = w?.scope.trimmingCharacters(in: .whitespacesAndNewlines), !scope.isEmpty else { + return "Counts cover this computer's Offload state directory." + } + return scope + } + + private func processingDetail(_ w: Workload?, goal: Int) -> String { + "\(WorkloadPresentation.processingNote(w)). Goal \(WorkloadPresentation.exact(goal)); goals are targets, not measured capacity. \(scope(w))" + } + + private func callsDetail(_ d: Daily?, goal: Int) -> String { + "\(WorkloadPresentation.callsNote(d, goal: goal)). Goal \(WorkloadPresentation.exact(goal)); goals are targets, not measured capacity. Counts cover this computer." + } + + private func peakDetail(_ d: Daily?, goal: Int) -> String { + "\(WorkloadPresentation.peakNote(d)). Processing goal \(WorkloadPresentation.exact(goal)). Counts cover this computer." + } + + private func averageDetail(_ d: Daily?, goal: Int) -> String { + "\(WorkloadPresentation.averageNote(d)). Daily-calls goal \(WorkloadPresentation.exact(goal)). Counts cover this computer." + } + + private func queueDetail(_ w: Workload?) -> String { + [WorkloadPresentation.queueLine(w), WorkloadPresentation.admissionLine(w), scope(w)].compactMap { $0 }.joined(separator: ". ") + } + private func tile(title: String, value: String, goal: Int, note: String, fill: Double, over: Bool, tint: Color, warn: Bool) -> some View { VStack(alignment: .leading, spacing: 1) { Text(title).font(.system(size: 9.5)).foregroundStyle(.secondary).lineLimit(1) diff --git a/macos/Tests/OffloadMonitorTests/LayoutTests.swift b/macos/Tests/OffloadMonitorTests/LayoutTests.swift index 12d7445..4a1bd34 100644 --- a/macos/Tests/OffloadMonitorTests/LayoutTests.swift +++ b/macos/Tests/OffloadMonitorTests/LayoutTests.swift @@ -34,6 +34,17 @@ final class PaginationTests: XCTestCase { XCTAssertEqual(Pagination.rangeLabel(page: 0, total: 9, size: 4), "1–4 of 9") XCTAssertEqual(Pagination.rangeLabel(page: 2, total: 9, size: 4), "9–9 of 9") XCTAssertEqual(Pagination.rangeLabel(page: 9, total: 9, size: 4), "9–9 of 9") + XCTAssertEqual(Pagination.pageLabel(page: 0, total: 9, size: 4), "Page 1 of 3") + XCTAssertEqual(Pagination.pageLabel(page: 9, total: 9, size: 4), "Page 3 of 3") + } + + func testFourTaskRowsAndFourHistoryRowsFitTheListRegion() { + XCTAssertEqual(Layout.taskPageSize, 4) + XCTAssertEqual(Layout.rowPageSize, 4) + XCTAssertLessThanOrEqual(CGFloat(4) * Layout.taskRow + 3 * 3 + Layout.pager, Layout.list) + XCTAssertLessThanOrEqual(CGFloat(4) * Layout.historyRow + 3 * 3 + Layout.pager, Layout.list) + XCTAssertEqual(Pagination.slice(Array(1...10), page: 2, size: 4), [9, 10]) + XCTAssertEqual(Pagination.clamp(2, total: 3, size: 4), 0, "shrinking data clamps to the remaining page") } } diff --git a/macos/Tests/OffloadMonitorTests/NewTaskFeedbackTests.swift b/macos/Tests/OffloadMonitorTests/NewTaskFeedbackTests.swift index c0796fd..c2d92f5 100644 --- a/macos/Tests/OffloadMonitorTests/NewTaskFeedbackTests.swift +++ b/macos/Tests/OffloadMonitorTests/NewTaskFeedbackTests.swift @@ -215,7 +215,7 @@ final class MonitorPulseTests: XCTestCase { let (m, _) = model() m.ingest(try snapshot(active: [try task(1)]), at: t0) m.period = .all - m.period = .week + m.period = .last7 m.ingest(try snapshot(active: [try task(1)]), at: t0.addingTimeInterval(5)) XCTAssertNil(m.pulse) } diff --git a/macos/Tests/OffloadMonitorTests/PanelRenderTests.swift b/macos/Tests/OffloadMonitorTests/PanelRenderTests.swift index a0cad5b..b2df6f1 100644 --- a/macos/Tests/OffloadMonitorTests/PanelRenderTests.swift +++ b/macos/Tests/OffloadMonitorTests/PanelRenderTests.swift @@ -65,6 +65,9 @@ final class PanelRenderTests: XCTestCase { return [ State(name: "idle", model: MonitorModel(testingSnapshot: try snapshot(active: []))), State(name: "working", model: MonitorModel(testingSnapshot: try snapshot(active: (0..<3).map { task("running", pid: 100 + $0) }))), + State(name: "four-long-tasks", model: MonitorModel(testingSnapshot: try snapshot(active: (0..<4).map { + task("running", pid: 700 + $0, text: String(repeating: "long task text ", count: 20)) + }))), State(name: "queued", model: MonitorModel(testingSnapshot: try snapshot(active: (0..<2).map { task("queued", pid: 200 + $0) }))), State(name: "needs-attention", model: MonitorModel(testingSnapshot: try snapshot(active: [ task("running", pid: 300, stalled: true), task("lost", pid: 301), task("unresolved", pid: 302)]))), @@ -121,7 +124,7 @@ final class PanelRenderTests: XCTestCase { try FileManager.default.createDirectory(at: output!, withIntermediateDirectories: true) } let all = try states() - XCTAssertEqual(all.count, 10) + XCTAssertEqual(all.count, 11) var violations: [String] = [] for s in all { // Natural size: the content is not forced into the fixed height, so overflow shows up as a larger height. diff --git a/macos/Tests/OffloadMonitorTests/StatsDecodeTests.swift b/macos/Tests/OffloadMonitorTests/StatsDecodeTests.swift index c86db64..36e0e52 100644 --- a/macos/Tests/OffloadMonitorTests/StatsDecodeTests.swift +++ b/macos/Tests/OffloadMonitorTests/StatsDecodeTests.swift @@ -155,8 +155,8 @@ final class StatsDecodeTests: XCTestCase { let ok = StatsClient(executable: try script("cat <<'EOF'\n\(Self.empty)\nEOF")) let all = try await ok.fetch(period: .all) XCTAssertEqual(all.period, "all") - do { _ = try await ok.fetch(period: .week); XCTFail() } catch { - XCTAssertEqual(error as? StatsError, .periodMismatch(expected: "week", got: "all")) + do { _ = try await ok.fetch(period: .last7); XCTFail() } catch { + XCTAssertEqual(error as? StatsError, .periodMismatch(expected: "last7", got: "all")) } var slow = StatsClient(executable: try script("sleep 30")) slow.timeout = 0.5 @@ -170,16 +170,31 @@ final class StatsDecodeTests: XCTestCase { let d = UserDefaults(suiteName: suite)! defer { d.removePersistentDomain(forName: suite) } let p = Preferences(defaults: d) - XCTAssertEqual(p.period, .today) + XCTAssertEqual(p.period, .last7) XCTAssertTrue(p.autoCheck) XCTAssertFalse(p.autoInstall) - p.period = .month; p.autoCheck = false; p.autoInstall = true + p.period = .last30; p.autoCheck = false; p.autoInstall = true let q = Preferences(defaults: d) - XCTAssertEqual(q.period, .month) + XCTAssertEqual(q.period, .last30) XCTAssertFalse(q.autoCheck) XCTAssertTrue(q.autoInstall) } + func testPreferencesMigratesLegacyCalendarPeriods() { + let suite = "test-\(UUID().uuidString)" + let d = UserDefaults(suiteName: suite)! + defer { d.removePersistentDomain(forName: suite) } + let p = Preferences(defaults: d) + d.set("week", forKey: "statsPeriod") + XCTAssertEqual(p.period, .last7) + d.set("month", forKey: "statsPeriod") + XCTAssertEqual(p.period, .last30) + d.set("today", forKey: "statsPeriod") + XCTAssertEqual(p.period, .today) + d.set("all", forKey: "statsPeriod") + XCTAssertEqual(p.period, .all) + } + func testDashboardShownOnFirstLaunchOnly() { let suite = "test-\(UUID().uuidString)" let d = UserDefaults(suiteName: suite)! diff --git a/macos/Tests/OffloadMonitorTests/WorkloadTests.swift b/macos/Tests/OffloadMonitorTests/WorkloadTests.swift index 41c8676..c8c4e49 100644 --- a/macos/Tests/OffloadMonitorTests/WorkloadTests.swift +++ b/macos/Tests/OffloadMonitorTests/WorkloadTests.swift @@ -152,4 +152,33 @@ final class WorkloadLayoutTests: XCTestCase { XCTAssertLessThanOrEqual(host.fittingSize.width, Layout.width) XCTAssertLessThan(host.fittingSize.height, 200) } + + func testCompactWorkloadStatesFitAndRenderOffscreen() throws { + let cases: [(String, String, String)] = [ + ("huge", WorkloadDecodeTests.workload(processing: "99999", queued: "88888", stalled: "77"), + WorkloadDecodeTests.daily(todayCalls: "98765432", peak: "99999", avg: "54321000.0")), + ("unknown", WorkloadDecodeTests.workload(processing: "null", queued: "null", status: "unavailable", limit: "null"), + WorkloadDecodeTests.daily(todayCalls: "0", peak: "null", peakCov: "unavailable", avg: "null", cov: "unavailable", covered: 0, met: false)), + ("partial", WorkloadDecodeTests.workload(status: "partial", stalled: "9", limit: "null"), + WorkloadDecodeTests.daily(peak: "12", peakCov: "partial", avg: "4200.4", cov: "partial", covered: 2, met: false)), + ] + let output = ProcessInfo.processInfo.environment["OFFLOAD_PANEL_RENDER_DIR"].map(URL.init(fileURLWithPath:)) + if let output { try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) } + for (name, workload, daily) in cases { + let snapshot = try StatsDecoder.decode(WorkloadDecodeTests.doc(workload: workload, daily: daily)) + let host = NSHostingView(rootView: WorkloadPanel(snapshot: snapshot, compact: true) + .frame(width: Layout.width - 24).background(Color(nsColor: .windowBackgroundColor))) + host.appearance = NSAppearance(named: .aqua) + host.layoutSubtreeIfNeeded() + XCTAssertLessThanOrEqual(host.fittingSize.width, Layout.width - 24, name) + XCTAssertLessThanOrEqual(host.fittingSize.height, 64, "\(name) compact workload needs \(host.fittingSize.height)pt") + host.frame = NSRect(origin: .zero, size: host.fittingSize) + host.layoutSubtreeIfNeeded() + let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds)) + host.cacheDisplay(in: host.bounds, to: bitmap) + let data = try XCTUnwrap(bitmap.representation(using: .png, properties: [:])) + XCTAssertGreaterThan(data.count, 1000, "\(name) compact render looks empty") + if let output { try data.write(to: output.appendingPathComponent("workload-compact-\(name).png")) } + } + } }