Chat: the server continues a usage-refused Claude chat at the reset

When Claude Code refuses an operator chat's turn for a usage limit and the
server does not continue it on another account, the server now queues a
durable prompt (auto-continue-<refusal id>, sent as Pipelines (automatic))
for a minute after the reset: the refused operator message when the turn
did no work, else "continue". The reset comes from the refusal's text,
else the rejected rate_limit_event. Refusals of turns Claude Code started
itself are handled too, with no client attached; a restarted server or a
device scheduling the same refusal adds nothing. The choice is kept per
Claude home beside auto-switch (or by the server for chats without one),
read and set with chat_auto_continue, on by default.

The app's limit banner now finds the refusal as the latest turn, ignoring
notices, agent reports and activity rows after it, reads and writes the
server's choice, and only schedules its own prompt for older servers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 19:52:03 +00:00
parent c441400f36
commit 633b5953bb
23 changed files with 1380 additions and 71 deletions
@@ -82,10 +82,13 @@ JsonMap _limitFrame(DateTime reset, {double percent = 100, JsonMap? extra}) => {
},
};
/// Frames enough for the banner to learn this (older) server keeps no
/// auto-continue choice, schedule the prompt and see it queued.
Future<void> _pump(WidgetTester tester) async {
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump();
await tester.pump();
}
/// A refused operator message: the refusal answers it directly.
@@ -0,0 +1,239 @@
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_auto_continue.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 'package:shared_preferences/shared_preferences.dart';
import 'chat_thread_fixtures.dart';
/// A server that keeps the auto-continue choice (`chat_auto_continue`) and
/// schedules the continue prompt itself.
class _Gateway extends FakeChatGateway {
bool autoContinue = true;
final settings = <JsonMap>[];
final promptBodies = <JsonMap>[];
final unqueued = <String>[];
final held = <JsonMap>[];
List<JsonMap> messages = [];
_Gateway() {
history = (_) async => chatPage(messages);
}
void pushQueue() => emitRaw({
'type': 'chat_queue',
'chat_queue': {
'session_id': 's',
'prompts': [...held],
},
});
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
switch (type) {
case 'chat_auto_continue':
final body = fields['chat_auto_continue'] as JsonMap;
settings.add(body);
if (body['auto_continue'] case final bool on) autoContinue = on;
return {
'chat_auto_continue': {
'session_id': 's',
'auto_continue': autoContinue,
'scope': 'claude_home',
},
};
case 'chat_prompt':
final body = fields['chat_prompt'] as JsonMap;
promptBodies.add(body);
if (!held.any((p) => p['operation_id'] == body['operation_id'])) {
held.add({
'operation_id': body['operation_id'],
'text': body['text'],
'send_at': body['send_at'],
});
pushQueue();
}
return {'chat_queued': true};
case 'chat_unqueue':
final id = (fields['chat_unqueue'] as JsonMap)['operation_id'];
unqueued.add('$id');
held.removeWhere((p) => p['operation_id'] == id);
return {
'chat_queue': {
'session_id': 's',
'prompts': [...held],
'removed': id,
},
};
}
return super.call(type, fields);
}
}
JsonMap _text(String text) => {'type': 'text', 'text': text};
const _hit =
"You've hit your 5-hour limit · resets 7:20pm (Europe/London) · out of "
'usage credits';
JsonMap _notice(String id) => {
...chatMessage(id, 'assistant', parts: [_text('Background task finished')]),
'kind': 'notice',
};
/// A refused operator message, then background-task notices that arrived
/// after the refusal.
List<JsonMap> _refusedThenNotices() => [
chatMessage('u1', 'user', parts: [_text('Fix the flaky build')]),
chatMessage('r1', 'assistant', parts: [_text(_hit)]),
_notice('n1'),
_notice('n2'),
_notice('n3'),
];
JsonMap _limitFrame(DateTime reset) => {
'session_id': 's',
'kind': 'usage',
'usage': {
'account': {
'harness': 'Claude Code',
'plan': 'max',
'windows': [
{
'id': 'five_hour',
'label': '5-hour',
'used_percent': 100,
'resets_at': reset.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) async {
final gateway = _Gateway()..messages = _refusedThenNotices();
addTearDown(gateway.close);
var sequence = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
drafts: MemoryChatDraftStore(),
newOperationId: () => 'op-${++sequence}',
autoContinue: ChatAutoContinue(
preferences: SharedPreferences.getInstance,
),
),
),
),
);
await _pump(tester);
return gateway;
}
DateTime _resetIn(Duration offset) => DateTime.fromMillisecondsSinceEpoch(
DateTime.now().add(offset).millisecondsSinceEpoch,
);
String _time(WidgetTester tester, DateTime at) =>
chatScheduleTime(tester.element(find.byType(Scaffold)), at);
final _banner = find.byKey(const Key('chat-usage-limit'));
final _status = find.byKey(const Key('chat-usage-limit-status'));
final _checkbox = find.byKey(const Key('chat-usage-limit-auto-continue'));
bool _checked(WidgetTester tester) => tester
.widget<Checkbox>(
find.descendant(of: _checkbox, matching: find.byType(Checkbox)),
)
.value!;
void main() {
setUp(() => SharedPreferences.setMockInitialValues({}));
testWidgets('a refusal followed by notices shows the server\'s scheduled '
'prompt and schedules nothing of its own', (tester) async {
final gateway = await _host(tester);
final reset = _resetIn(const Duration(hours: 2));
final sendAt = reset.add(const Duration(minutes: 1));
// The server scheduled the continue prompt when the refusal happened.
gateway.held.add({
'operation_id': 'auto-continue-r1',
'text': 'Fix the flaky build',
'client': 'Pipelines (automatic)',
'send_at': sendAt.millisecondsSinceEpoch,
});
gateway.pushQueue();
gateway.emitEvent(_limitFrame(reset));
await _pump(tester);
expect(_banner, findsOneWidget);
expect(find.text("You've hit your 5-hour limit"), findsOneWidget);
expect(
tester.widget<Text>(_status).data,
'Auto-resuming at ${_time(tester, sendAt)}',
);
expect(find.byKey(const Key('chat-usage-limit-try-again')), findsOneWidget);
expect(_checked(tester), isTrue);
expect(gateway.settings.first, {'session_id': 's'});
expect(gateway.promptBodies, isEmpty);
expect(
find.text('Scheduled · sends at ${_time(tester, sendAt)}'),
findsOneWidget,
);
});
testWidgets('the checkbox writes the server\'s choice, not the device\'s', (
tester,
) async {
final gateway = await _host(tester);
final reset = _resetIn(const Duration(hours: 2));
gateway.held.add({
'operation_id': 'auto-continue-r1',
'text': 'Fix the flaky build',
'send_at': reset.add(const Duration(minutes: 1)).millisecondsSinceEpoch,
});
gateway.pushQueue();
gateway.emitEvent(_limitFrame(reset));
await _pump(tester);
await tester.tap(_checkbox);
await _pump(tester);
expect(_checked(tester), isFalse);
expect(gateway.settings.last, {'session_id': 's', 'auto_continue': false});
expect(gateway.unqueued, ['auto-continue-r1']);
final preferences = await SharedPreferences.getInstance();
expect(preferences.getBool(chatAutoContinuePreferenceKey), isNull);
expect(gateway.promptBodies, isEmpty);
// Checked again, the refusal the server passed over while it was off
// is scheduled under the server's own id.
await tester.tap(_checkbox);
await _pump(tester);
expect(_checked(tester), isTrue);
expect(gateway.settings.last, {'session_id': 's', 'auto_continue': true});
expect(gateway.promptBodies.single['operation_id'], 'auto-continue-r1');
expect(gateway.promptBodies.single['text'], 'Fix the flaky build');
});
testWidgets('with the server keeping the choice, a refusal it has not '
'scheduled is not scheduled by the app', (tester) async {
final gateway = await _host(tester);
gateway.emitEvent(_limitFrame(_resetIn(const Duration(hours: 1))));
await _pump(tester);
expect(_banner, findsOneWidget);
expect(gateway.promptBodies, isEmpty);
});
}
@@ -185,6 +185,55 @@ void main() {
);
});
test('notices, reports and activity rows after the refusal do not hide '
'it; a later turn does', () {
final refused = [
message('u1', 'user', 'fix the build'),
message('r1', 'assistant', hit),
for (final id in ['n1', 'n2', 'n3'])
{
...message(id, 'assistant', 'Background task finished: tests'),
'kind': 'notice',
},
{
...message('rep1', 'assistant', 'Subagent report'),
'kind': 'agent_report',
},
{
'id': 'act1',
'role': 'assistant',
'parts': [
{'type': 'compaction', 'status': 'completed'},
],
},
];
final turn = chatRefusedTurn(refused, null)!;
expect(turn.refusalId, 'r1');
expect(turn.text, 'fix the build');
expect(
chatThreadUsageLimit(null, [
message(
'r1',
'assistant',
'Claude AI usage limit reached|1900000000',
),
{...message('n1', 'assistant', 'Background task'), 'kind': 'notice'},
], now),
isNotNull,
);
expect(
chatRefusedTurn([
...refused,
message('a2', 'assistant', 'Picked it back up.'),
], null),
isNull,
);
expect(
chatRefusedTurn([...refused, message('u2', 'user', 'continue')], null),
isNull,
);
});
test('a refusal from before an account switch no longer counts', () {
final refusal = {...message('r1', 'assistant', hit), 'created_at': 10};
final switched = ChatAccountUsage(