The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(mobile): a reset time past what a DateTime holds no longer drops a machine's usage
dee31482a8b8cf3
diff --git a/mobile/lib/usage/usage_window.dart b/mobile/lib/usage/usage_window.dartindex 4f508bf02..18513b9f1 100644--- a/mobile/lib/usage/usage_window.dart+++ b/mobile/lib/usage/usage_window.dart@@ -165,10 +165,17 @@ class ProviderUsage {/// 1e10 is the discriminator: it sits above any plausible seconds epoch (year/// 2286) and below any plausible milliseconds one (year 2001), so the unit can/// be told from the magnitude without the vendor having to label it.+///+/// ⚠️ A count past what a [DateTime] can hold (±8.64e15 ms — a vendor that+/// switched to nanoseconds, say) is no reset time, not a throw:+/// `fromMillisecondsSinceEpoch` raises a RangeError there, and this runs inside+/// `parseUsageReadResult`, whose caller drops the machine's whole answer — every+/// provider on it — when anything escapes.DateTime? parseResetTimestamp(Object? value) {if (value is num) {if (!value.isFinite) return null;final ms = value > 10000000000 ? value : value * 1000;+ if (ms.abs() > _maxEpochMilliseconds) return null;return DateTime.fromMillisecondsSinceEpoch(ms.round());}if (value is! String || value.trim().isEmpty) return null;@@ -177,6 +184,9 @@ DateTime? parseResetTimestamp(Object? value) {return DateTime.tryParse(value);}+/// The furthest a [DateTime] reaches either side of the epoch.+const int _maxEpochMilliseconds = 8640000000000000;+/// Reads a vendor's utilization figure, clamped to the 0–100 the UI draws.////// The vendors disagree on the field name, so the caller passes each candidatediff --git a/mobile/test/usage/usage_answers_test.dart b/mobile/test/usage/usage_answers_test.dartnew file mode 100644index 000000000..363a1fd12--- /dev/null+++ b/mobile/test/usage/usage_answers_test.dart@@ -0,0 +1,324 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/usage/claude_usage_source.dart';+import 'package:harness_mobile/usage/codex_usage_source.dart';+import 'package:harness_mobile/usage/remote_usage.dart';+import 'package:harness_mobile/usage/usage_source.dart';+import 'package:harness_mobile/usage/usage_window.dart';++/// What a machine's `usage_read_result` turns into on the phone.+///+/// Every figure the Usage page and the model sheet draw came in through here:+/// a phone has no Claude or Codex login of its own, so a linked machine asks+/// with ITS tokens and hands back the vendors' replies verbatim. Each way that+/// reply can be partial, refused or malformed has to land as a state the page+/// can say a sentence about — never as a missing machine or a thrown error.+void main() {+ group('a finished request, as the state it leaves', () {+ test('no status at all: the vendor was not reached', () {+ final failure = usageFailureFor(UsageProvider.codex, null)!;+ expect(failure.status, UsageStatus.failed);+ expect(failure.message, 'Could not reach Codex');+ });++ test('401 and 403 are a missing session, not a failure to retry', () {+ for (final code in [401, 403]) {+ final failure = usageFailureFor(UsageProvider.claude, code)!;+ expect(failure.status, UsageStatus.signedOut, reason: '$code');+ expect(failure.message, 'Sign in to Claude to see usage');+ }+ });++ test('any other 4xx or 5xx names the status it answered with', () {+ final failure = usageFailureFor(UsageProvider.claude, 429)!;+ expect(failure.status, UsageStatus.failed);+ expect(failure.message, 'Claude answered 429');+ expect(+ usageFailureFor(UsageProvider.codex, 503)!.message,+ contains('503'),+ );+ });++ test('a success is no failure — the body decides', () {+ expect(usageFailureFor(UsageProvider.claude, 200), isNull);+ });++ test('signed out, in the sentence the page prints', () {+ final reading = signedOut(UsageProvider.codex);+ expect(reading.status, UsageStatus.signedOut);+ expect(reading.message, 'Sign in to Codex to see usage');+ });+ });++ group('Claude', () {+ test('reads its three windows, in the order they bite', () {+ final reading = claudeUsageFromAnswer(+ statusCode: 200,+ account: 'acct',+ body: {+ 'five_hour': {'utilization': 12, 'resets_at': '2026-09-27T15:00:00Z'},+ 'seven_day': {'used_percentage': '41.5'},+ 'fable_weekly': {'utilization': 3},+ },+ );+ expect(reading.status, UsageStatus.ok);+ expect(reading.account, 'acct');+ expect(reading.fetchedAt, isNotNull);+ expect(+ [for (final w in reading.windows) w.label],+ ['Session', kWeeklyWindowLabel, 'Fable'],+ );+ expect(reading.windows[1].usedPercent, 41.5);+ expect(reading.windows.first.resetsAt, isNotNull);+ });++ test('finds Fable under either of its older spellings', () {+ for (final key in ['fable_seven_day', 'seven_day_fable']) {+ final reading = claudeUsageFromAnswer(+ statusCode: 200,+ body: {+ key: {'utilization': 9},+ },+ );+ expect(reading.windows.single.label, 'Fable', reason: key);+ }+ });++ test('a window with no figure is dropped, not drawn as zero', () {+ final reading = claudeUsageFromAnswer(+ statusCode: 200,+ body: {+ 'five_hour': {'utilization': null},+ 'seven_day': {'utilization': 50},+ 'seven_day_opus': null,+ },+ );+ expect(reading.windows.single.label, kWeeklyWindowLabel);+ });++ test('an answer with no window at all is a failure that says so', () {+ final reading = claudeUsageFromAnswer(statusCode: 200, body: const {});+ expect(reading.status, UsageStatus.failed);+ expect(reading.message, 'Claude reported no limits');+ });++ test('a body that is not an object is a shape this build cannot read', () {+ final reading = claudeUsageFromAnswer(statusCode: 200, body: 'oops');+ expect(reading.status, UsageStatus.failed);+ expect(reading.message, contains('cannot read'));+ });++ test('a refused request never reaches the body', () {+ expect(+ claudeUsageFromAnswer(statusCode: 401, body: const {}).status,+ UsageStatus.signedOut,+ );+ });+ });++ group('Codex', () {+ Map<String, Object?> window(Object? seconds, {Object? used = 30}) => {+ 'used_percent': used,+ 'limit_window_seconds': seconds,+ 'reset_at': 1790000000,+ };++ ProviderUsage answer(Map<String, Object?> primary) => codexUsageFromAnswer(+ statusCode: 200,+ body: {+ 'rate_limit': {'primary_window': primary},+ },+ );++ test('names each window by how long it really is', () {+ expect(answer(window(18000)).windows.single.label, '5h');+ expect(answer(window(1800)).windows.single.label, '30m');+ expect(answer(window(604800)).windows.single.label, kWeeklyWindowLabel);+ expect(answer(window(86400 * 30)).windows.single.label, '30d');+ });++ test('a window whose length was not sent is a neutral "Limit"', () {+ for (final seconds in <Object?>[null, 0, -60, 'soon', double.nan]) {+ expect(+ answer(window(seconds)).windows.single.label,+ 'Limit',+ reason: '$seconds',+ );+ }+ });++ test('reads its primary and secondary windows, and the account', () {+ final reading = codexUsageFromAnswer(+ statusCode: 200,+ account: 'acct',+ body: {+ 'rate_limit': {+ 'primary_window': window(18000),+ 'secondary_window': window(604800, used: 64),+ },+ },+ );+ expect(reading.status, UsageStatus.ok);+ expect(reading.account, 'acct');+ expect(reading.windows, hasLength(2));+ expect(reading.railWindow!.usedPercent, 64);+ expect(reading.windows.first.resetsAt, isNotNull);+ });++ test('no readable window is a failure that says so', () {+ for (final body in <Object?>[+ const {},+ const {'rate_limit': 'x'},+ {+ 'rate_limit': {+ 'primary_window': window(18000, used: null),+ 'secondary_window': 'x',+ },+ },+ ]) {+ final reading = codexUsageFromAnswer(statusCode: 200, body: body);+ expect(reading.status, UsageStatus.failed, reason: '$body');+ expect(reading.message, 'Codex reported no limits');+ }+ });++ test('a body that is not an object, or a refusal', () {+ expect(+ codexUsageFromAnswer(statusCode: 200, body: null).message,+ contains('cannot read'),+ );+ expect(+ codexUsageFromAnswer(statusCode: 500, body: null).message,+ 'Codex answered 500',+ );+ });+ });++ group('parseUsageReadResult', () {+ test('an answer with no provider list has nothing to add', () {+ expect(parseUsageReadResult(const {}), isEmpty);+ expect(parseUsageReadResult(const {'providers': 'x'}), isEmpty);+ });++ test('each provider read by the same mapper this phone would use', () {+ final readings = parseUsageReadResult({+ 'providers': [+ {+ 'provider': 'claude',+ 'outcome': 'answered',+ 'httpStatus': 200,+ 'account': 'a1',+ 'body': {+ 'seven_day': {'utilization': 20},+ },+ },+ {+ 'provider': 'codex',+ 'outcome': 'answered',+ 'httpStatus': 200,+ 'account': '',+ 'body': {+ 'rate_limit': {+ 'primary_window': {+ 'used_percent': 5,+ 'limit_window_seconds': 18000,+ },+ },+ },+ },+ ],+ });+ expect(readings, hasLength(2));+ expect(readings[0].provider, UsageProvider.claude);+ expect(readings[0].account, 'a1');+ expect(readings[1].provider, UsageProvider.codex);+ // An empty key is no key: it must never merge two accounts.+ expect(readings[1].account, isNull);+ });++ test('a provider or entry this build has never heard of is dropped', () {+ final readings = parseUsageReadResult({+ 'providers': [+ 'not a map',+ {'provider': 'grok', 'outcome': 'answered'},+ {'provider': 'codex', 'outcome': 'signedOut'},+ ],+ });+ expect(readings.single.provider, UsageProvider.codex);+ });++ test('signed out there: the machine\'s own sentence when it sent one', () {+ final readings = parseUsageReadResult({+ 'providers': [+ {+ 'provider': 'claude',+ 'outcome': 'signedOut',+ 'message': 'Claude session expired on Studio',+ },+ {'provider': 'codex', 'outcome': 'signedOut', 'message': ''},+ ],+ });+ expect(readings[0].status, UsageStatus.signedOut);+ expect(readings[0].message, 'Claude session expired on Studio');+ expect(readings[1].message, 'Sign in to Codex to see usage');+ });++ test('unreachable, or an outcome from a newer CLI, is a failure', () {+ final readings = parseUsageReadResult({+ 'providers': [+ {'provider': 'claude', 'outcome': 'unreachable'},+ {'provider': 'codex', 'outcome': 'rate_limited_somewhere_new'},+ ],+ });+ expect(readings.map((r) => r.status), [+ UsageStatus.failed,+ UsageStatus.failed,+ ]);+ expect(readings.first.message, 'Could not reach Claude');+ });++ test('an answered entry with no status reads as unreached', () {+ final reading = parseUsageReadResult({+ 'providers': [+ {'provider': 'claude', 'outcome': 'answered', 'httpStatus': '200'},+ ],+ }).single;+ expect(reading.status, UsageStatus.failed);+ });++ test('one odd timestamp costs its window, not the machine\'s answer', () {+ // The regression behind the RangeError guard in `parseResetTimestamp`:+ // the caller (`AppNotifier.readRemoteUsage`) catches anything thrown+ // here by dropping the MACHINE, so a Claude reset time in the wrong unit+ // used to take the machine's Codex figure down with it.+ final readings = parseUsageReadResult({+ 'providers': [+ {+ 'provider': 'claude',+ 'outcome': 'answered',+ 'httpStatus': 200,+ 'body': {+ 'seven_day': {+ 'utilization': 20,+ 'resets_at': 1790000000000000000,+ },+ },+ },+ {+ 'provider': 'codex',+ 'outcome': 'answered',+ 'httpStatus': 200,+ 'body': {+ 'rate_limit': {+ 'primary_window': {'used_percent': 5},+ },+ },+ },+ ],+ });+ expect(readings, hasLength(2));+ expect(readings.first.hasFigures, isTrue);+ expect(readings.first.windows.single.resetsAt, isNull);+ expect(readings.last.hasFigures, isTrue);+ });+ });+}diff --git a/mobile/test/usage/usage_window_test.dart b/mobile/test/usage/usage_window_test.dartnew file mode 100644index 000000000..c6c7eb8fc--- /dev/null+++ b/mobile/test/usage/usage_window_test.dart@@ -0,0 +1,228 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/usage/usage_pressure.dart';+import 'package:harness_mobile/usage/usage_window.dart';++/// The one model both vendors are read into, and the two parsers every figure+/// on the Usage page passes through. A figure here is only ever as right as+/// these are, so the edges are pinned rather than trusted.+void main() {+ final now = DateTime(2026, 9, 27, 12);++ group('UsageProvider', () {+ test(+ 'names itself, and is found by the engine id its agents run under',+ () {+ expect(UsageProvider.claude.label, 'Claude');+ expect(UsageProvider.codex.label, 'Codex');+ // `EngineMark` finds the logo by this id; a second spelling would draw+ // an account without its mark.+ expect(UsageProvider.claude.engineId, 'claude');+ expect(UsageProvider.codex.engineId, 'codex');+ },+ );+ });++ group('resetsInLabel', () {+ UsageWindow resetting(Duration? after) => UsageWindow(+ label: 'Session',+ usedPercent: 10,+ resetsAt: after == null ? null : now.add(after),+ );++ test('says nothing when the vendor gave no reset time', () {+ // Null is not zero: "resets in 0m" for an answer never given would be a+ // measurement invented out of a silence.+ expect(resetting(null).resetsInLabel(now: now), isNull);+ });++ test(+ 'says nothing once the reset has passed, or is under a minute off',+ () {+ expect(+ resetting(const Duration(minutes: -5)).resetsInLabel(now: now),+ isNull,+ );+ expect(+ resetting(const Duration(seconds: 59)).resetsInLabel(now: now),+ isNull,+ );+ },+ );++ test('minutes under an hour, hours and minutes under a day, then days', () {+ expect(+ resetting(const Duration(minutes: 43)).resetsInLabel(now: now),+ '43m',+ );+ expect(+ resetting(const Duration(hours: 4, minutes: 34))+ .resetsInLabel(now: now),+ '4h 34m',+ );+ expect(+ resetting(const Duration(days: 5, hours: 11)).resetsInLabel(now: now),+ '5d 11h',+ );+ });++ test('reads the wall clock when no time is passed in', () {+ final window = UsageWindow(+ label: 'Weekly',+ usedPercent: 1,+ resetsAt: DateTime.now().add(const Duration(hours: 2, minutes: 30)),+ );+ expect(window.resetsInLabel(), anyOf('2h 29m', '2h 30m'));+ });+ });++ group('ProviderUsage', () {+ const session = UsageWindow(label: 'Session', usedPercent: 71);+ const weekly = UsageWindow(label: kWeeklyWindowLabel, usedPercent: 40);+ const fable = UsageWindow(label: 'Fable', usedPercent: 12);++ test('before its first answer it is loading, with nothing to draw', () {+ const loading = ProviderUsage.loading(UsageProvider.codex);+ expect(loading.status, UsageStatus.loading);+ expect(loading.windows, isEmpty);+ expect(loading.message, isNull);+ expect(loading.fetchedAt, isNull);+ expect(loading.account, isNull);+ expect(loading.hasFigures, isFalse);+ expect(loading.tightest, isNull);+ expect(loading.railWindow, isNull);+ });++ test('has figures only when it answered AND reported a window', () {+ expect(+ const ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.ok,+ ).hasFigures,+ isFalse,+ );+ expect(+ const ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.failed,+ windows: [session],+ ).hasFigures,+ isFalse,+ );+ });++ test('the tightest window is the one closest to being spent', () {+ const reading = ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.ok,+ windows: [weekly, session, fable],+ );+ expect(reading.tightest, same(session));+ });++ test('the rail prints the weekly window, even when another is tighter', () {+ const reading = ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.ok,+ windows: [session, weekly, fable],+ );+ expect(reading.railWindow, same(weekly));+ });++ test('with no weekly window the rail falls back to the tightest', () {+ const reading = ProviderUsage(+ provider: UsageProvider.codex,+ status: UsageStatus.ok,+ windows: [fable, session],+ );+ expect(reading.railWindow, same(session));+ });+ });++ group('parseResetTimestamp', () {+ test('reads epoch seconds and epoch milliseconds by their size', () {+ final at = DateTime.utc(2026, 9, 27, 12);+ final seconds = at.millisecondsSinceEpoch ~/ 1000;+ expect(parseResetTimestamp(seconds)!.isAtSameMomentAs(at), isTrue);+ expect(+ parseResetTimestamp(at.millisecondsSinceEpoch)!.isAtSameMomentAs(at),+ isTrue,+ );+ // Fractional seconds are a number like any other.+ expect(+ parseResetTimestamp(seconds + 0.5)!.millisecondsSinceEpoch,+ at.millisecondsSinceEpoch + 500,+ );+ });++ test('reads a number sent as a string, and an ISO timestamp', () {+ final at = DateTime.utc(2026, 9, 27, 12);+ expect(+ parseResetTimestamp(' ${at.millisecondsSinceEpoch ~/ 1000} ')!+ .isAtSameMomentAs(at),+ isTrue,+ );+ expect(+ parseResetTimestamp('2026-09-27T12:00:00Z')!.isAtSameMomentAs(at),+ isTrue,+ );+ });++ test('anything else is no reset time rather than a guess', () {+ for (final value in <Object?>[+ null,+ '',+ ' ',+ 'soon',+ true,+ double.nan,+ double.infinity,+ const {'at': 1},+ ]) {+ expect(parseResetTimestamp(value), isNull, reason: '$value');+ }+ });++ test('a timestamp past the calendar is dropped, not thrown', () {+ // Nanoseconds, or any unit this build does not expect, reads as a+ // millisecond count past what a DateTime can hold. It used to throw a+ // RangeError out of here — through `parseUsageReadResult`, which+ // promises never to throw — and the caller then dropped the machine's+ // WHOLE answer, every provider on it, over one odd field.+ expect(parseResetTimestamp(1790000000000000000), isNull);+ expect(parseResetTimestamp(-1790000000000000000), isNull);+ expect(parseResetTimestamp('1790000000000000000'), isNull);+ });+ });++ group('parseUsedPercent', () {+ test('the first candidate that is really a number wins', () {+ expect(parseUsedPercent([null, 'n/a', 42]), 42);+ expect(parseUsedPercent(['17.5', 3]), 17.5);+ });++ test('is clamped to the 0-100 the page draws', () {+ expect(parseUsedPercent([-4]), 0);+ expect(parseUsedPercent([140]), 100);+ });++ test('a non-finite figure is no figure', () {+ // `double.tryParse('NaN')` succeeds, and NaN clamps to a number — so the+ // finiteness check is what keeps a hand-edited answer off the page.+ expect(parseUsedPercent(['NaN', double.infinity]), isNull);+ expect(parseUsedPercent(const []), isNull);+ });+ });++ group('usage pressure', () {+ test('calm below 80, amber from 80, red from 90', () {+ expect(usagePressureOf(79.9), UsagePressure.calm);+ expect(usagePressureOf(kUsageWarnPercent), UsagePressure.warn);+ expect(usagePressureOf(89.9), UsagePressure.warn);+ expect(usagePressureOf(kUsageCriticalPercent), UsagePressure.critical);+ expect(+ const UsageWindow(label: 'Weekly', usedPercent: 95).pressure,+ UsagePressure.critical,+ );+ });+ });+}