Schedule a message for when the usage limit resets

When the open chat's account has an exhausted quota window, a banner above
the composer reads "Usage limit reached · resets at HH:MM" and offers to
send the last message (or the current draft) a minute after the reset, via
chat_prompt send_at. Queued prompts with a future send_at read
"Scheduled · sends at HH:MM" and keep Remove.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 00:59:33 +00:00
parent f72c46d599
commit 53d8b911a6
13 changed files with 891 additions and 17 deletions
@@ -0,0 +1,267 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/conversation/chat_schedule_time.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
/// A thread gateway that records prompt bodies and answers them as queued,
/// as the server does for one carrying `send_at`.
class _Gateway extends FakeChatGateway {
final promptBodies = <JsonMap>[];
List<JsonMap> messages = [];
_Gateway() {
history = (_) async => chatPage(messages);
}
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (type == 'chat_prompt') {
final body = fields['chat_prompt'] as JsonMap;
promptBodies.add(body);
return {'chat_queued': body['send_at'] != null};
}
return super.call(type, fields);
}
}
JsonMap _text(String text) => {'type': 'text', 'text': text};
JsonMap _limitFrame(DateTime reset, {double percent = 100}) => {
'session_id': 's',
'kind': 'usage',
'usage': {
'account': {
'harness': 'Claude Code',
'plan': 'max',
'windows': [
{
'id': 'five_hour',
'label': '5-hour',
'used_percent': percent,
'resets_at': reset.millisecondsSinceEpoch,
},
{
'id': 'seven_day',
'label': 'Weekly',
'used_percent': 40,
'resets_at': reset
.add(const Duration(days: 2))
.millisecondsSinceEpoch,
},
],
},
},
};
Future<void> _pump(WidgetTester tester) async {
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump();
}
Future<_Gateway> _host(
WidgetTester tester, {
List<JsonMap>? messages,
Future<JsonMap> Function()? subscribe,
}) async {
final gateway = _Gateway()
..messages =
messages ??
[
chatMessage('u1', 'user', parts: [_text('first')]),
chatMessage(
'u2',
'user',
parts: [
_text('Fix the flaky build'),
{'type': 'file', 'name': 'log.txt', 'uri': 'file://log.txt'},
],
),
chatMessage('a1', 'assistant', parts: [_text('On it.')]),
]
..subscribe = subscribe;
addTearDown(gateway.close);
var sequence = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
drafts: MemoryChatDraftStore(),
newOperationId: () => 'op-${++sequence}',
),
),
),
);
await _pump(tester);
return gateway;
}
String _time(WidgetTester tester, DateTime at) =>
chatScheduleTime(tester.element(find.byType(Scaffold)), at);
final _banner = find.byKey(const Key('chat-usage-limit'));
final _button = find.byKey(const Key('chat-usage-limit-schedule'));
void main() {
testWidgets('no banner until a window is exhausted', (tester) async {
final gateway = await _host(tester);
expect(_banner, findsNothing);
final reset = DateTime.now().add(const Duration(hours: 2));
gateway.emitEvent(_limitFrame(reset, percent: 97));
await _pump(tester);
expect(_banner, findsNothing);
});
testWidgets('the button schedules the last message a minute after reset', (
tester,
) async {
final gateway = await _host(tester);
final reset = DateTime.fromMillisecondsSinceEpoch(
DateTime.now().add(const Duration(hours: 2)).millisecondsSinceEpoch,
);
gateway.emitEvent(_limitFrame(reset));
await _pump(tester);
final sendAt = reset.add(const Duration(minutes: 1));
expect(
find.text('Usage limit reached · resets at ${_time(tester, reset)}'),
findsOneWidget,
);
expect(
find.text('Send last message at ${_time(tester, sendAt)}'),
findsOneWidget,
);
// The earlier message's file is not repeated, and the banner says so.
expect(find.text('Its attachments are not sent again.'), findsOneWidget);
await tester.tap(_button);
await _pump(tester);
final body = gateway.promptBodies.single;
expect(body['text'], 'Fix the flaky build');
expect(body['send_at'], sendAt.millisecondsSinceEpoch);
expect(body.containsKey('attachments'), isFalse);
// The new bubble reads as scheduled rather than plain "Queued".
expect(find.byKey(const Key('chat-delivery-scheduled')), findsOneWidget);
expect(
find.text('Scheduled · sends at ${_time(tester, sendAt)}'),
findsOneWidget,
);
// It waits for its time, not the current turn, and is not offered twice.
expect(find.byKey(const Key('chat-composer-queued')), findsNothing);
expect(find.textContaining('1 message scheduled'), findsOneWidget);
expect(_button, findsNothing);
});
testWidgets('with a draft the button schedules the draft and clears it', (
tester,
) async {
final gateway = await _host(tester);
final reset = DateTime.now().add(const Duration(minutes: 40));
gateway.emitEvent(_limitFrame(reset));
await _pump(tester);
final sendAt = DateTime.fromMillisecondsSinceEpoch(
reset.millisecondsSinceEpoch,
).add(const Duration(minutes: 1));
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'Then run the tests',
);
await _pump(tester);
expect(find.text('Send this at ${_time(tester, sendAt)}'), findsOneWidget);
expect(find.text('Its attachments are not sent again.'), findsNothing);
await tester.tap(_button);
await _pump(tester);
final body = gateway.promptBodies.single;
expect(body['text'], 'Then run the tests');
expect(body['send_at'], sendAt.millisecondsSinceEpoch);
final field = tester.widget<TextField>(
find.byKey(const Key('chat-composer-field')),
);
expect(field.controller!.text, isEmpty);
});
testWidgets('nothing to send hides the button', (tester) async {
final gateway = await _host(
tester,
messages: [
chatMessage('a1', 'assistant', parts: [_text('Hello.')]),
],
);
gateway.emitEvent(
_limitFrame(DateTime.now().add(const Duration(hours: 1))),
);
await _pump(tester);
expect(_banner, findsOneWidget);
expect(_button, findsNothing);
});
testWidgets('a passed reset is not a limit', (tester) async {
final gateway = await _host(tester);
gateway.emitEvent(
_limitFrame(DateTime.now().subtract(const Duration(minutes: 1))),
);
await _pump(tester);
expect(_banner, findsNothing);
});
testWidgets('a queued prompt with send_at reads Scheduled with Remove', (
tester,
) async {
final sendAt = DateTime.fromMillisecondsSinceEpoch(
DateTime.now().add(const Duration(hours: 1)).millisecondsSinceEpoch,
);
final gateway = await _host(
tester,
subscribe: () async => {
'chat_queue': {
'session_id': 's',
'prompts': [
{
'operation_id': 'later',
'text': 'continue',
'send_at': sendAt.millisecondsSinceEpoch,
},
{'operation_id': 'next', 'text': 'and then this'},
],
},
},
);
expect(
find.text('Scheduled · sends at ${_time(tester, sendAt)}'),
findsOneWidget,
);
expect(find.text('Queued'), findsOneWidget);
expect(find.byKey(const Key('chat-delivery-remove')), findsNWidgets(2));
// With a message already scheduled the banner offers no second re-send.
gateway.emitEvent(_limitFrame(sendAt.subtract(const Duration(minutes: 1))));
await _pump(tester);
expect(find.textContaining('1 message scheduled'), findsOneWidget);
expect(_button, findsNothing);
});
testWidgets('chatScheduleTime names another day', (tester) async {
await tester.pumpWidget(const MaterialApp(home: Scaffold()));
final context = tester.element(find.byType(Scaffold));
final now = DateTime(2026, 11, 25, 9);
expect(
chatScheduleTime(context, DateTime(2026, 11, 25, 15, 1), now: () => now),
'15:01',
);
expect(
chatScheduleTime(context, DateTime(2026, 11, 28, 7, 5), now: () => now),
'Sat, Nov 28 07:05',
);
});
}
@@ -0,0 +1,160 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/domain/chat_account_usage.dart';
import 'package:pipelines_app/features/chat/domain/chat_usage_limit.dart';
ChatAccountUsage _usage(List<(double, DateTime?)> windows) => ChatAccountUsage(
harness: 'Claude Code',
plan: 'max',
asOf: 0,
unsupported: false,
windows: [
for (final (index, (percent, reset)) in windows.indexed)
ChatQuotaWindow(
id: 'w$index',
label: 'W$index',
usedPercent: percent,
resetsAt: reset?.millisecondsSinceEpoch ?? 0,
),
],
);
void main() {
final now = DateTime(2026, 11, 25, 12);
group('chatUsageLimit', () {
test('an exhausted window with a future reset is a limit', () {
final reset = now.add(const Duration(hours: 3));
final limit = chatUsageLimit(
_usage([(42, now.add(const Duration(days: 2))), (100, reset)]),
now,
)!;
expect(limit.resetsAt, reset);
expect(limit.sendAt, reset.add(const Duration(minutes: 1)));
});
test('below 100% or unknown quota is not a limit', () {
expect(chatUsageLimit(null, now), isNull);
expect(
chatUsageLimit(
_usage([(99.9, now.add(const Duration(hours: 1)))]),
now,
),
isNull,
);
final unsupported = ChatAccountUsage(
harness: 'OpenCode',
plan: '',
asOf: 0,
windows: const [],
unsupported: true,
);
expect(chatUsageLimit(unsupported, now), isNull);
});
test('a reset that has passed, or is unknown, is not a limit', () {
expect(
chatUsageLimit(
_usage([(100, now.subtract(const Duration(minutes: 1)))]),
now,
),
isNull,
);
expect(chatUsageLimit(_usage([(100, null)]), now), isNull);
});
test('several exhausted windows wait for the latest reset', () {
final early = now.add(const Duration(hours: 1));
final late = now.add(const Duration(days: 3));
final limit = chatUsageLimit(
_usage([
(100, early),
(104, late),
(60, now.add(const Duration(days: 9))),
(100, now.subtract(const Duration(hours: 1))),
]),
now,
)!;
expect(limit.resetsAt, late);
});
});
test('Claude Code limit text carries the reset in epoch seconds', () {
final reset = now.add(const Duration(hours: 2));
final seconds = reset.millisecondsSinceEpoch ~/ 1000;
expect(
chatUsageLimitFromText(
'Claude AI usage limit reached|$seconds',
now,
)!.resetsAt,
DateTime.fromMillisecondsSinceEpoch(seconds * 1000),
);
expect(chatUsageLimitFromText('Hello there', now), isNull);
final past = now.subtract(const Duration(hours: 1));
expect(
chatUsageLimitFromText(
'Claude AI usage limit reached|${past.millisecondsSinceEpoch ~/ 1000}',
now,
),
isNull,
);
});
test('the thread limit prefers quota, then the last reply text', () {
final seconds =
now.add(const Duration(hours: 2)).millisecondsSinceEpoch ~/ 1000;
final refused = {
'role': 'assistant',
'parts': [
{'type': 'text', 'text': 'Claude AI usage limit reached|$seconds'},
],
};
expect(chatThreadUsageLimit(null, [refused], now), isNotNull);
expect(
chatThreadUsageLimit(null, [
refused,
{
'role': 'user',
'parts': [
{'type': 'text', 'text': 'continue'},
],
},
], now),
isNull,
);
});
test('the last prompt is the newest user text and notes its files', () {
final last = chatLastPrompt([
{
'role': 'user',
'parts': [
{'type': 'text', 'text': 'first'},
],
},
{
'role': 'user',
'parts': [
{'type': 'text', 'text': ' fix the build '},
{'type': 'file', 'name': 'log.txt'},
],
},
{
'role': 'assistant',
'parts': [
{'type': 'text', 'text': 'ok'},
],
},
])!;
expect(last.text, 'fix the build');
expect(last.hadAttachments, isTrue);
expect(chatLastPrompt(const []), isNull);
});
test('scheduled send_at is a future epoch-ms time only', () {
final later = now.add(const Duration(minutes: 5));
expect(chatScheduledSendAt(later.millisecondsSinceEpoch, now), later);
expect(chatScheduledSendAt(now.millisecondsSinceEpoch - 1, now), isNull);
expect(chatScheduledSendAt(null, now), isNull);
expect(chatScheduledSendAt('x', now), isNull);
});
}