Merge branch 'worktree-agent-a04a38e74fe1aef60'

This commit is contained in:
2026-12-02 19:56:31 +00:00
23 changed files with 1380 additions and 71 deletions
@@ -3,6 +3,8 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../core/api_gateway.dart';
const chatAutoContinuePreferenceKey = 'pipelines.chatAutoContinue.v1';
/// The usage-limit banner's "Auto-continue when limits reset" choice: one
@@ -68,3 +70,85 @@ class ChatAutoContinue extends ChangeNotifier {
}
}
}
/// The "Auto-continue when limits reset" choice the server keeps for one
/// chat (`chat_auto_continue`): per Claude home, or the server's own for a
/// chat without one. A server that keeps it also schedules the continue
/// prompt itself, so the app only shows it. An older server does not answer
/// with a choice; then [unsupported] is set and the per-device
/// [ChatAutoContinue] preference, and the app's own scheduling, apply as
/// before.
class ChatServerAutoContinue extends ChangeNotifier {
ChatServerAutoContinue({required this.gateway, required this.sessionId});
final ApiGateway gateway;
final String sessionId;
bool? _enabled;
bool _unsupported = false;
bool _disposed = false;
Future<void>? _loading;
/// Whether the server answered with its choice.
bool get supported => _enabled != null && !_unsupported;
/// Whether the server does not keep the choice (an older server).
bool get unsupported => _unsupported;
/// Whether the server's answer (or refusal) arrived.
bool get loaded => supported || _unsupported;
/// The server's choice; on until it says otherwise.
bool get enabled => _enabled ?? true;
/// Reads the server's choice once.
Future<void> load() => _loading ??= _read();
Future<void> _read() async {
try {
_enabled = _choice(await _call(null));
_unsupported = _enabled == null;
} on Object {
// An older server does not know the request.
_unsupported = true;
}
_notify();
}
/// Records the operator's choice on the server; the shown choice goes
/// back when the server does not record it.
Future<void> set(bool on) async {
final previous = _enabled;
_enabled = on;
_notify();
try {
final recorded = _choice(await _call(on));
if (recorded == null) throw StateError('no auto_continue in the reply');
_enabled = recorded;
} on Object catch (error) {
debugPrint('Auto-continue: the server did not record it: $error');
_enabled = previous;
}
_notify();
}
Future<JsonMap> _call(bool? on) => gateway.call('chat_auto_continue', {
'chat_auto_continue': {'session_id': sessionId, 'auto_continue': ?on},
});
static bool? _choice(JsonMap reply) {
final body = reply['chat_auto_continue'];
final value = body is Map ? body['auto_continue'] : null;
return value is bool ? value : null;
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
@@ -18,12 +18,16 @@ import 'chat_thread_controller.dart';
/// "Auto-resuming at 15:41", an
/// "Auto-continue when limits reset" checkbox and Try again.
///
/// With auto-continue on (a preference shared by every chat, on by default,
/// [ChatAutoContinue]) and the transcript ending on the limit's refusal, the
/// banner hands the server a prompt to send a minute after the reset: the
/// refused operator message again, or "continue" when the refused turn had
/// already worked on it. The server holds it durably, so it is sent with the
/// app closed or the server restarted. Unchecking takes it back out of the
/// The chat counts as refused while its latest turn is the limit's refusal,
/// whatever notices or agent reports arrived after it. With auto-continue on,
/// the server queues a prompt to send a minute after the reset (the refused
/// operator message again, or "continue" when the refused turn had already
/// worked on it), with no app involved; the choice is the server's
/// ([ChatServerAutoContinue], per Claude home, on by default), and the
/// banner shows the prompt it scheduled. An older server that keeps no such
/// choice falls back to the per-device [ChatAutoContinue] preference, and the
/// banner hands that server the prompt itself, under the same operation id
/// so a server copy is never doubled. Unchecking takes it back out of the
/// server's queue; Try again takes it out and sends now. The banner hides
/// once the reset passes, or once the account is switched (by the operator
/// or by the server's automatic switch, whose queued continue prompt also
@@ -35,6 +39,7 @@ class ChatUsageLimitBanner extends StatefulWidget {
required this.composer,
this.accounts,
ChatAutoContinue? autoContinue,
this.serverAutoContinue,
this.now = DateTime.now,
}) : autoContinue = autoContinue ?? ChatAutoContinue.shared;
@@ -45,6 +50,10 @@ class ChatUsageLimitBanner extends StatefulWidget {
/// null for a chat that is not Claude Code's.
final ChatClaudeAccountsController? accounts;
final ChatAutoContinue autoContinue;
/// The server's choice for this chat; null builds one on [thread]'s
/// gateway.
final ChatServerAutoContinue? serverAutoContinue;
final DateTime Function() now;
@override
@@ -59,18 +68,48 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
/// refused request is not repeated on every rebuild.
final Set<String> _requested = {};
late ChatServerAutoContinue _server;
bool _ownsServer = false;
@override
void initState() {
super.initState();
unawaited(widget.autoContinue.load());
_server = _serverFor(widget);
}
ChatServerAutoContinue _serverFor(ChatUsageLimitBanner widget) {
_ownsServer = widget.serverAutoContinue == null;
return widget.serverAutoContinue ??
ChatServerAutoContinue(
gateway: widget.thread.gateway,
sessionId: widget.thread.sessionId,
);
}
@override
void didUpdateWidget(ChatUsageLimitBanner old) {
super.didUpdateWidget(old);
if (widget.serverAutoContinue != old.serverAutoContinue ||
widget.thread.sessionId != old.thread.sessionId) {
if (_ownsServer) _server.dispose();
_server = _serverFor(widget);
_requested.clear();
}
}
@override
void dispose() {
_reset?.cancel();
if (_ownsServer) _server.dispose();
super.dispose();
}
/// Whether auto-continue is on: the server's choice, or this device's for
/// an older server.
bool get _enabled =>
_server.supported ? _server.enabled : widget.autoContinue.enabled;
/// Rebuilds when the reset passes, so the banner leaves on time.
void _watchReset(DateTime? at, DateTime now) {
if (at == _resetFor) return;
@@ -124,11 +163,27 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
}
}
Future<void> _toggle(bool on, List<JsonMap> pending) async {
Future<void> _toggle(
bool on,
List<JsonMap> pending,
ChatRefusedTurn? refused,
ChatUsageLimit limit,
) async {
// Rechecking may schedule the same refusal again.
_requested.clear();
await widget.autoContinue.set(on);
if (!on) await _cancel(pending);
if (!_server.supported) {
await widget.autoContinue.set(on);
if (!on) await _cancel(pending);
return;
}
await _server.set(on);
if (!on) {
await _cancel(pending);
} else if (refused != null && pending.isEmpty && mounted) {
// The server considered this refusal while it was off; ask for its
// prompt now, under the id the server would have used.
_arm(refused, limit);
}
}
Future<void> _tryAgain(ChatRefusedTurn refused, List<JsonMap> pending) async {
@@ -144,6 +199,7 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
widget.thread,
widget.composer,
widget.autoContinue,
_server,
]),
builder: (context, _) {
final now = widget.now();
@@ -158,9 +214,13 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
final refused = chatRefusedTurn(thread.messages, thread.accountUsage);
final pending = _pending(now);
final auto = widget.autoContinue;
unawaited(_server.load());
// The server already switched accounts and is continuing the chat.
final switching = chatAutoSwitchPending(thread.queuedPrompts);
if (auto.loaded &&
// A server that keeps the choice schedules the prompt itself; only
// for an older one does this device ask for it.
if (_server.unsupported &&
auto.loaded &&
auto.enabled &&
refused != null &&
pending.isEmpty &&
@@ -183,7 +243,7 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final text = theme.textTheme;
final enabled = widget.autoContinue.enabled;
final enabled = _enabled;
String time(DateTime at) => chatScheduleTime(context, at, now: () => now);
final resumesAt = pending.isEmpty
? limit.sendAt
@@ -253,7 +313,7 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
spacing: 8,
runSpacing: 4,
children: [
_checkbox(context, enabled, pending),
_checkbox(context, enabled, pending, refused, limit),
Wrap(
spacing: 8,
runSpacing: 4,
@@ -283,8 +343,15 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
);
}
Widget _checkbox(BuildContext context, bool enabled, List<JsonMap> pending) {
void toggle(bool? on) => unawaited(_toggle(on ?? false, pending));
Widget _checkbox(
BuildContext context,
bool enabled,
List<JsonMap> pending,
ChatRefusedTurn? refused,
ChatUsageLimit limit,
) {
void toggle(bool? on) =>
unawaited(_toggle(on ?? false, pending, refused, limit));
// A labelled checkbox: the label toggles it too, as one control.
return MergeSemantics(
child: InkWell(
@@ -78,14 +78,42 @@ final RegExp _limitText = RegExp(r'usage limit reached\|(\d{9,11})\b');
/// session limit"); the first clause is the limit's own wording.
final RegExp _hitText = RegExp(r"^\s*You['’]ve hit your [^·\n]*limit");
/// The last transcript message that is part of the conversation (a message
/// scheduled since is not yet), or an empty map.
JsonMap _lastSent(List<JsonMap> messages) =>
messages.lastWhere((m) => m['send_at'] == null, orElse: () => const {});
/// Whether [message] is a turn of the conversation: the operator's message
/// or the agent's reply. Not one: a message scheduled to send later, content
/// the harness injected after the turn (an agent's report, a notice such as
/// a background task ending), and a row with no text or tool of its own (an
/// activity record).
bool chatIsTurnMessage(JsonMap message) {
if (message['send_at'] != null) return false;
if ('${message['kind'] ?? ''}'.isNotEmpty) return false;
final role = message['role'];
if (role == 'user') return true;
if (role != 'assistant') return false;
final parts = message['parts'];
if (parts is! List) return '${message['text'] ?? ''}'.isNotEmpty;
return parts.any(
(part) =>
part is Map &&
(part['type'] == 'text' ||
part['type'] == 'tool' ||
part['type'] == 'reasoning'),
);
}
/// The conversation's turn messages, in order.
List<JsonMap> _turns(List<JsonMap> messages) => [
for (final m in messages)
if (chatIsTurnMessage(m)) m,
];
/// The last turn message (see [chatIsTurnMessage]), or an empty map.
JsonMap _lastTurn(List<JsonMap> messages) =>
messages.lastWhere(chatIsTurnMessage, orElse: () => const {});
/// The limit for the open chat: the reported quota first, then the
/// transcript's last message when it is the harness's limit refusal (a
/// message scheduled since then is not part of the conversation yet).
/// transcript's last turn when it is the harness's limit refusal (notices
/// and reports that arrived after it, and a message scheduled since, are
/// not turns).
ChatUsageLimit? chatThreadUsageLimit(
ChatAccountUsage? usage,
List<JsonMap> messages,
@@ -93,7 +121,7 @@ ChatUsageLimit? chatThreadUsageLimit(
) {
final quota = chatUsageLimit(usage, now);
if (quota != null) return quota;
final last = _lastSent(messages);
final last = _lastTurn(messages);
if (last.isEmpty || last['role'] == 'user') return null;
if (_beforeSwitch(usage, last)) return null;
return chatUsageLimitFromText(_text(last), now);
@@ -108,8 +136,10 @@ bool _beforeSwitch(ChatAccountUsage? usage, JsonMap message) {
return created is! num || created <= switchedAt;
}
/// The turn the limit refused: the transcript ends on the harness's limit
/// refusal. Auto-continue and Try again send [text]: the operator's message
/// The turn the limit refused: the transcript's latest turn is the harness's
/// limit refusal (whatever notices, agent reports or background-task rows
/// followed it), until a later turn starts. Auto-continue and Try again send
/// [text]: the operator's message
/// the refusal answered, or "continue" when the refusal ended a turn that
/// had already worked on it.
class ChatRefusedTurn {
@@ -143,16 +173,14 @@ class ChatRefusedTurn {
String get autoContinueId => '$chatAutoContinuePrefix$refusalId';
}
/// The refused turn [messages] end on, or null when the last message is not
/// a limit refusal (or came before an account switch in [usage]).
/// The refused turn [messages] end on, or null when their last turn (see
/// [chatIsTurnMessage]) is not a limit refusal (or came before an account
/// switch in [usage]).
ChatRefusedTurn? chatRefusedTurn(
List<JsonMap> messages,
ChatAccountUsage? usage,
) {
final sent = [
for (final m in messages)
if (m['send_at'] == null) m,
];
final sent = _turns(messages);
if (sent.isEmpty) return null;
final last = sent.last;
if (last['role'] == 'user' || _beforeSwitch(usage, last)) return null;
@@ -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(