diff --git a/app/lib/features/chat/conversation/chat_auto_continue.dart b/app/lib/features/chat/conversation/chat_auto_continue.dart index bac26751..a4f4a645 100644 --- a/app/lib/features/chat/conversation/chat_auto_continue.dart +++ b/app/lib/features/chat/conversation/chat_auto_continue.dart @@ -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? _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 load() => _loading ??= _read(); + + Future _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 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 _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(); + } +} diff --git a/app/lib/features/chat/conversation/chat_usage_limit_banner.dart b/app/lib/features/chat/conversation/chat_usage_limit_banner.dart index aed8e297..efce45db 100644 --- a/app/lib/features/chat/conversation/chat_usage_limit_banner.dart +++ b/app/lib/features/chat/conversation/chat_usage_limit_banner.dart @@ -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 { /// refused request is not repeated on every rebuild. final Set _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 { } } - Future _toggle(bool on, List pending) async { + Future _toggle( + bool on, + List 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 _tryAgain(ChatRefusedTurn refused, List pending) async { @@ -144,6 +199,7 @@ class _ChatUsageLimitBannerState extends State { widget.thread, widget.composer, widget.autoContinue, + _server, ]), builder: (context, _) { final now = widget.now(); @@ -158,9 +214,13 @@ class _ChatUsageLimitBannerState extends State { 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 { 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 { 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 { ); } - Widget _checkbox(BuildContext context, bool enabled, List pending) { - void toggle(bool? on) => unawaited(_toggle(on ?? false, pending)); + Widget _checkbox( + BuildContext context, + bool enabled, + List 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( diff --git a/app/lib/features/chat/domain/chat_usage_limit.dart b/app/lib/features/chat/domain/chat_usage_limit.dart index bc7bf408..96a50ee9 100644 --- a/app/lib/features/chat/domain/chat_usage_limit.dart +++ b/app/lib/features/chat/domain/chat_usage_limit.dart @@ -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 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 _turns(List messages) => [ + for (final m in messages) + if (chatIsTurnMessage(m)) m, +]; + +/// The last turn message (see [chatIsTurnMessage]), or an empty map. +JsonMap _lastTurn(List 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 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 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; diff --git a/app/test/features/chat/conversation/chat_usage_limit_banner_test.dart b/app/test/features/chat/conversation/chat_usage_limit_banner_test.dart index 50b50beb..83a23108 100644 --- a/app/test/features/chat/conversation/chat_usage_limit_banner_test.dart +++ b/app/test/features/chat/conversation/chat_usage_limit_banner_test.dart @@ -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 _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. diff --git a/app/test/features/chat/conversation/chat_usage_limit_server_test.dart b/app/test/features/chat/conversation/chat_usage_limit_server_test.dart new file mode 100644 index 00000000..9540e01a --- /dev/null +++ b/app/test/features/chat/conversation/chat_usage_limit_server_test.dart @@ -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 = []; + final promptBodies = []; + final unqueued = []; + final held = []; + List messages = []; + + _Gateway() { + history = (_) async => chatPage(messages); + } + + void pushQueue() => emitRaw({ + 'type': 'chat_queue', + 'chat_queue': { + 'session_id': 's', + 'prompts': [...held], + }, + }); + + @override + Future 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 _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 _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( + 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(_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); + }); +} diff --git a/app/test/features/chat/domain/chat_usage_limit_test.dart b/app/test/features/chat/domain/chat_usage_limit_test.dart index 17aa80f5..1d68a56a 100644 --- a/app/test/features/chat/domain/chat_usage_limit_test.dart +++ b/app/test/features/chat/domain/chat_usage_limit_test.dart @@ -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( diff --git a/docs/cli.md b/docs/cli.md index 0362a144..0bab3de4 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -584,12 +584,12 @@ queues into the chat, behind the refused turn, a prompt sent as `Pipelines (automatic)` and starting `[Sent automatically by Pipelines]` that names both accounts and asks the agent to check its progress against the request and its plan, and to stop and ask if it is off track, before it -continues. The app's `auto-continue-` prompt for that refusal is -removed from the queue (and refused if it arrives later), and the operator gets +continues. Any `auto-continue-` prompt waiting in the queue is +removed (and one arriving later is refused), and the operator gets a low-priority notification "Switched to and continued". Each refusal switches at most once; a refusal of the new account tries the next -untried account; with none left nothing more happens and auto-continue at the -reset applies. It is on by default and is a per-Claude-home choice kept in +untried account; with none left auto-continue at the reset applies. It is on by +default and is a per-Claude-home choice kept in `/pipelines-accounts/settings.json`: `claude_account_auto_switch` (body `claude_account: {"session_id", "auto_switch": bool}`) sets it, every `claude_accounts` reply reports it as `auto_switch`, and @@ -597,6 +597,27 @@ reset applies. It is on by default and is a per-Claude-home choice kept in not switched: a stage refused for usage fails with the provider-quota error and its run stops. +Auto-continue at the reset: when such a refusal was not continued on another +account (switching off, no account left, or no Claude home of its own), the +server queues a durable prompt into the chat, sent as `Pipelines (automatic)` +with operation id `auto-continue-` and `send_at` one minute +after the reset. The reset is the one the refusal's text names ("resets 7:20pm +(Europe/London)", or the older `usage limit reached|`), else the +rejected `rate_limit_event`'s `resetsAt`; a refusal naming neither is not +continued. The prompt is the refused operator message again when the refused +turn was that message and did no work, else `continue` (also for turns Claude +Code started itself, such as background-task notifications). The refusal is +handled when the server reads it, whether or not a client is attached; one +already scheduled, by the server or by a device, is not scheduled again, and a +prompt still waiting from an earlier refusal is kept rather than joined by a +second. It waits in the queue as a scheduled prompt any client can remove. +The choice ("Auto-continue when limits reset", on by default) is read and set +with `chat_auto_continue` (body and reply `chat_auto_continue: {"session_id", +"auto_continue": bool, "scope"}`; omit `auto_continue` to read it). It is kept +per Claude home as `auto_continue` beside `auto_switch` (scope `claude_home`), +or by the server in its settings table for a chat without one (scope +`server`). + The brokered OpenCode chat exposes the operator's own sessions, separate from the sessions pipeline runs create. The protocol types are: diff --git a/internal/claude/auto_continue.go b/internal/claude/auto_continue.go new file mode 100644 index 00000000..4149cee4 --- /dev/null +++ b/internal/claude/auto_continue.go @@ -0,0 +1,49 @@ +package claude + +import ( + "context" + "strings" + + "git.a-wan.net/alan/pipelines/internal/claudeaccounts" +) + +// The operator's "Auto-continue when limits reset" choice is kept per Claude +// home, beside the automatic-switch choice (claudeaccounts settings.json), so +// every chat on that home and every device share it. A chat whose directory +// selects no Claude home of its own reports ErrNoConfigDir; the server keeps +// the choice for those itself. + +// AutoContinue reports whether chats on the Claude home of sessionID's +// directory ("" uses the open session's) continue automatically once a usage +// limit resets. +func (c *Chat) AutoContinue(ctx context.Context, sessionID, directory string) (bool, error) { + store, err := c.homeStore(ctx, sessionID, directory) + if err != nil { + return false, err + } + return store.AutoContinue(), nil +} + +// SetAutoContinue records the auto-continue choice of that Claude home. +func (c *Chat) SetAutoContinue(ctx context.Context, sessionID, directory string, on bool) error { + store, err := c.homeStore(ctx, sessionID, directory) + if err != nil { + return err + } + return store.SetAutoContinue(on) +} + +func (c *Chat) homeStore(ctx context.Context, sessionID, directory string) (claudeaccounts.Store, error) { + if strings.TrimSpace(directory) == "" { + if s := c.session(sessionID); s != nil { + s.mu.Lock() + directory = s.directory + s.mu.Unlock() + } + } + configDir, err := c.accountConfigDir(ctx, directory) + if err != nil { + return claudeaccounts.Store{}, err + } + return claudeaccounts.Store{ConfigDir: configDir}, nil +} diff --git a/internal/claude/auto_continue_test.go b/internal/claude/auto_continue_test.go new file mode 100644 index 00000000..d616aa67 --- /dev/null +++ b/internal/claude/auto_continue_test.go @@ -0,0 +1,34 @@ +package claude + +import ( + "context" + "errors" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// The auto-continue choice is kept per Claude home beside, and apart from, +// the automatic-switch choice; it is on by default. +func TestAutoContinueIsAClaudeHomeChoice(t *testing.T) { + ctx := context.Background() + chat := directoryChat(t) + directory := accountsHome(t, chat) + if on, err := chat.AutoContinue(ctx, "s", directory); err != nil || !on { + t.Fatalf("default = %v %v", on, err) + } + if err := chat.SetAutoContinue(ctx, "s", directory, false); err != nil { + t.Fatal(err) + } + if on, err := chat.AutoContinue(ctx, "s", directory); err != nil || on { + t.Fatalf("after off = %v %v", on, err) + } + list, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccounts, "") + if err != nil || !list.AutoSwitch { + t.Fatalf("auto-switch changed: %+v %v", list, err) + } + t.Setenv("CLAUDE_CONFIG_DIR", "") + if _, err := chat.AutoContinue(ctx, "s", t.TempDir()); !errors.Is(err, ErrNoConfigDir) { + t.Fatalf("a directory without a Claude home: %v", err) + } +} diff --git a/internal/claude/chat.go b/internal/claude/chat.go index add9c86c..98b81b05 100644 --- a/internal/claude/chat.go +++ b/internal/claude/chat.go @@ -189,6 +189,7 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess s.turnID = turn s.running = true s.beginTurnLocked() + s.turnPrompt = strings.TrimSpace(text) s.steered = 0 s.awaitFollowUp = false s.recordPromptLocked(messageID, text) @@ -254,6 +255,9 @@ func (c *Chat) SteerPrompt(ctx context.Context, id, text, messageID string, file s.mu.Lock() s.steered++ s.lastUsed = time.Now() + // A refused turn that took more than one message continues, rather + // than resending its first. + s.turnPrompt = "" s.recordPromptLocked(messageID, text) s.mu.Unlock() return true, nil diff --git a/internal/claude/claude.go b/internal/claude/claude.go index 91857e20..6ef01238 100644 --- a/internal/claude/claude.go +++ b/internal/claude/claude.go @@ -387,8 +387,18 @@ type session struct { turnEmail string limitMessageID string limitByError bool - prompts []promptRecord - models []protocol.ChatModel + // limitText and limitAt are the refusal's own text and when it was + // written; limitReset is when a rejected rate_limit_event of the turn + // said the limit resets. turnPrompt is the operator's prompt that + // started the running turn ("" for a turn Claude Code started itself) + // and turnWorked is set once the turn produced anything but a refusal. + limitText string + limitAt time.Time + limitReset time.Time + turnPrompt string + turnWorked bool + prompts []promptRecord + models []protocol.ChatModel // commands are the slash commands the live CLI's initialize listed; // terminalCommands are those its init line marks terminal-only (commands.go). commands []protocol.ChatCommand diff --git a/internal/claude/quota.go b/internal/claude/quota.go index a3309532..a7567a25 100644 --- a/internal/claude/quota.go +++ b/internal/claude/quota.go @@ -199,8 +199,14 @@ func (s *session) handleRateLimit(raw json.RawMessage) { s.mu.Unlock() } c := s.chat + until, rejected := rejectedUntil(raw) + if rejected { + s.mu.Lock() + s.noteRejectedResetLocked(until) + s.mu.Unlock() + } c.quotaMu.Lock() - if until, ok := rejectedUntil(raw); ok { + if rejected { c.noteRejectedLocked(account.email, until) } next := mergeRateLimit(c.quotas[key], raw, account.plan, time.Now()) diff --git a/internal/claude/refusal.go b/internal/claude/refusal.go index fbccc99f..caa1684d 100644 --- a/internal/claude/refusal.go +++ b/internal/claude/refusal.go @@ -2,6 +2,7 @@ package claude import ( "regexp" + "strconv" "strings" "time" ) @@ -27,6 +28,15 @@ type UsageRefusal struct { MessageID string // Email is the account the refused turn started on ("" when unknown). Email string + // ResetsAt is when the limit resets: the time the refusal's own text + // names, else the reset of the turn's rejected rate_limit_event; zero + // when neither said. + ResetsAt time.Time + // Prompt is the operator's message the refusal answered when the + // refused turn was started by it and did no work before the refusal; + // "" for a turn that worked, or one Claude Code started itself (a + // background-task notification). + Prompt string } // OnUsageRefused registers the receiver of usage-limit refusals; each is @@ -50,8 +60,19 @@ func (c *Chat) reportUsageRefusal(refusal UsageRefusal) { // refusal of the previous turn. The caller holds s.mu. func (s *session) beginTurnLocked() { s.turnEmail = s.account.email + s.clearRefusalLocked() +} + +// clearRefusalLocked forgets the running turn's refusal record and prompt. +// The caller holds s.mu. +func (s *session) clearRefusalLocked() { s.limitMessageID = "" s.limitByError = false + s.limitText = "" + s.limitAt = time.Time{} + s.limitReset = time.Time{} + s.turnPrompt = "" + s.turnWorked = false } // noteUsageRefusalLocked remembers an assistant message that is a @@ -65,9 +86,23 @@ func (s *session) noteUsageRefusalLocked(envelope lineEnvelope, body messageBody break } } - if byError || byText { - s.limitMessageID = messageID - s.limitByError = s.limitByError || byError + if !byError && !byText { + if messageID != s.limitMessageID { + s.turnWorked = true + } + return + } + s.limitMessageID = messageID + s.limitByError = s.limitByError || byError + s.limitText = "" + for _, block := range blocks { + if block.Type == "text" { + s.limitText += block.Text + "\n" + } + } + s.limitAt = time.Now() + if at, err := time.Parse(time.RFC3339Nano, envelope.Timestamp); err == nil { + s.limitAt = at } } @@ -84,11 +119,97 @@ func (s *session) takeUsageRefusalLocked(envelope lineEnvelope) (UsageRefusal, b if refusal.TurnID == "" { refusal.TurnID = "result-" + strings.TrimSpace(envelope.UUID) } - s.limitMessageID = "" - s.limitByError = false + at := s.limitAt + if at.IsZero() { + at = time.Now() + } + if reset, ok := usageLimitReset(s.limitText+envelope.Result, at); ok { + refusal.ResetsAt = reset + } else if !s.limitReset.IsZero() { + refusal.ResetsAt = s.limitReset + } + if !s.turnWorked { + refusal.Prompt = s.turnPrompt + } + s.clearRefusalLocked() return refusal, refused } +// noteRejectedResetLocked records when a rejected rate_limit_event the +// running turn received says the limit resets. The caller holds s.mu. +func (s *session) noteRejectedResetLocked(until time.Time) { + if until.After(s.limitReset) { + s.limitReset = until + } +} + +var ( + // usageLimitEpoch is the older CLI's "usage limit reached|". + usageLimitEpoch = regexp.MustCompile(`usage limit reached\|(\d{9,11})\b`) + // usageLimitResets is the current CLI's "resets 5:20pm (Europe/London)", + // or with a date for a longer window, "resets Dec 9, 5pm (Europe/London)". + usageLimitResets = regexp.MustCompile(`(?i)\bresets\s+(?:([a-z]{3})[a-z]*\.?\s+(\d{1,2})(?:,|\s+at)?\s+)?(\d{1,2})(?::(\d{2}))?\s*([ap]m)\s*\(([^)\s]+)\)`) +) + +// usageLimitReset is the reset a refusal's text names, the first such time +// after at (when the refusal was written). +func usageLimitReset(text string, at time.Time) (time.Time, bool) { + if match := usageLimitEpoch.FindStringSubmatch(text); match != nil { + seconds, err := strconv.ParseInt(match[1], 10, 64) + if err != nil || seconds <= 0 { + return time.Time{}, false + } + return time.Unix(seconds, 0), true + } + match := usageLimitResets.FindStringSubmatch(text) + if match == nil { + return time.Time{}, false + } + location, err := time.LoadLocation(match[6]) + if err != nil { + return time.Time{}, false + } + hour, _ := strconv.Atoi(match[3]) + minute := 0 + if match[4] != "" { + minute, _ = strconv.Atoi(match[4]) + } + if hour < 1 || hour > 12 || minute > 59 { + return time.Time{}, false + } + hour %= 12 + if strings.EqualFold(match[5], "pm") { + hour += 12 + } + local := at.In(location) + if match[1] != "" { + month, ok := monthOf(match[1]) + day, _ := strconv.Atoi(match[2]) + if !ok || day < 1 || day > 31 { + return time.Time{}, false + } + reset := time.Date(local.Year(), month, day, hour, minute, 0, 0, location) + if reset.Before(at.Add(-time.Minute)) { + reset = time.Date(local.Year()+1, month, day, hour, minute, 0, 0, location) + } + return reset, true + } + reset := time.Date(local.Year(), local.Month(), local.Day(), hour, minute, 0, 0, location) + if reset.Before(at.Add(-time.Minute)) { + reset = time.Date(local.Year(), local.Month(), local.Day()+1, hour, minute, 0, 0, location) + } + return reset, true +} + +func monthOf(name string) (time.Month, bool) { + for month := time.January; month <= time.December; month++ { + if strings.EqualFold(month.String()[:3], name) { + return month, true + } + } + return 0, false +} + // noteRejectedLocked records when a rejected account's limit ends. The // caller holds c.quotaMu. func (c *Chat) noteRejectedLocked(email string, until time.Time) { diff --git a/internal/claude/refusal_test.go b/internal/claude/refusal_test.go new file mode 100644 index 00000000..43af6a4a --- /dev/null +++ b/internal/claude/refusal_test.go @@ -0,0 +1,121 @@ +package claude + +import ( + "context" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestUsageLimitResetIsReadFromTheRefusal(t *testing.T) { + london, err := time.LoadLocation("Europe/London") + if err != nil { + t.Skip("no time zone data:", err) + } + at := time.Date(2026, 12, 2, 17, 21, 0, 0, london) + for _, tc := range []struct { + text string + want time.Time + }{ + {"You've hit your 5-hour limit · resets 7:20pm (Europe/London) · out of usage credits", time.Date(2026, 12, 2, 19, 20, 0, 0, london)}, + {"You've hit your limit · resets 5pm (Europe/London)", time.Date(2026, 12, 3, 17, 0, 0, 0, london)}, + {"You've hit your 5-hour limit · resets 12:30am (Europe/London)", time.Date(2026, 12, 3, 0, 30, 0, 0, london)}, + {"You've hit your weekly limit · resets Dec 9, 5pm (Europe/London)", time.Date(2026, 12, 9, 17, 0, 0, 0, london)}, + {"You've hit your weekly limit · resets Jan 2 at 9am (Europe/London)", time.Date(2027, 1, 2, 9, 0, 0, 0, london)}, + {"Claude AI usage limit reached|1900000000", time.Unix(1900000000, 0)}, + } { + got, ok := usageLimitReset(tc.text, at) + if !ok || !got.Equal(tc.want) { + t.Errorf("%q: %v %v, want %v", tc.text, got, ok, tc.want) + } + } + for _, text := range []string{"You've hit your limit", "resets 7:20pm (Nowhere/Land)", "resets 13pm (Europe/London)"} { + if got, ok := usageLimitReset(text, at); ok { + t.Errorf("%q read as %v", text, got) + } + } +} + +// The refused turn's operator message is sent again only when the turn did +// nothing else; the reset falls back to the rejected rate_limit_event. +func TestUsageRefusalCarriesItsPromptAndReset(t *testing.T) { + limit := []contentBlock{{Type: "text", Text: "You've hit your limit"}} + until := time.Now().Add(time.Hour) + s := &session{id: "s", turnID: "t1"} + s.beginTurnLocked() + s.turnPrompt = "Fix the build" + s.noteRejectedResetLocked(until) + s.noteUsageRefusalLocked(lineEnvelope{Error: "rate_limit"}, messageBody{}, limit, "r1") + refusal, refused := s.takeUsageRefusalLocked(lineEnvelope{IsError: true}) + if !refused || refusal.Prompt != "Fix the build" || !refusal.ResetsAt.Equal(until) { + t.Fatalf("refusal = %+v %v", refusal, refused) + } + + s.turnID = "t2" + s.beginTurnLocked() + s.turnPrompt = "Fix the build" + s.noteUsageRefusalLocked(lineEnvelope{}, messageBody{}, []contentBlock{{Type: "text", Text: "Looking at it"}}, "m2") + s.noteUsageRefusalLocked(lineEnvelope{Error: "rate_limit"}, messageBody{}, limit, "r2") + refusal, refused = s.takeUsageRefusalLocked(lineEnvelope{IsError: true}) + if !refused || refusal.Prompt != "" || !refusal.ResetsAt.IsZero() { + t.Fatalf("worked refusal = %+v %v", refusal, refused) + } +} + +func receiveRefusal(t *testing.T, refusals <-chan UsageRefusal) UsageRefusal { + t.Helper() + select { + case refusal := <-refusals: + return refusal + case <-time.After(5 * time.Second): + t.Fatal("the refusal was not reported") + } + return UsageRefusal{} +} + +// A live refusal of an operator prompt carries the prompt and the reset its +// text names. +func TestLiveUsageRefusalNamesItsResetAndPrompt(t *testing.T) { + london, err := time.LoadLocation("Europe/London") + if err != nil { + t.Skip("no time zone data:", err) + } + chat := testChat(t) + refusals := make(chan UsageRefusal, 4) + chat.OnUsageRefused(func(refusal UsageRefusal) { refusals <- refusal }) + created := newCreatedChat(t, chat) + before := time.Now() + if err := chat.Prompt(context.Background(), created.ID, "usage-limit please"); err != nil { + t.Fatal(err) + } + refusal := receiveRefusal(t, refusals) + local := before.In(london) + want := time.Date(local.Year(), local.Month(), local.Day(), 17, 20, 0, 0, london) + if want.Before(before.Add(-time.Minute)) { + want = time.Date(local.Year(), local.Month(), local.Day()+1, 17, 20, 0, 0, london) + } + if refusal.Prompt != "usage-limit please" || !refusal.ResetsAt.Equal(want) { + t.Fatalf("refusal = %+v, want reset %v", refusal, want) + } +} + +// A turn Claude Code started on its own (a background task's notification) +// that the limit refuses is reported too, with nothing to send again. +func TestRefusalOfATurnClaudeCodeStartedIsReported(t *testing.T) { + chat := testChat(t) + refusals := make(chan UsageRefusal, 4) + chat.OnUsageRefused(func(refusal UsageRefusal) { refusals <- refusal }) + created := newCreatedChat(t, chat) + frames := subscribe(t, chat, created.ID) + if err := chat.Prompt(context.Background(), created.ID, "cli-refusal"); err != nil { + t.Fatal(err) + } + waitFrame(t, frames, "the operator turn's end", func(frame protocol.ChatEventFrame) bool { + return frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded + }) + refusal := receiveRefusal(t, refusals) + if refusal.SessionID != created.ID || refusal.MessageID != "refusal-2" || refusal.Prompt != "" || refusal.ResetsAt.IsZero() { + t.Fatalf("refusal = %+v", refusal) + } +} diff --git a/internal/claude/testdata/fake-claude.py b/internal/claude/testdata/fake-claude.py index e10e97ee..5f04cb95 100644 --- a/internal/claude/testdata/fake-claude.py +++ b/internal/claude/testdata/fake-claude.py @@ -82,6 +82,19 @@ def user_message(text): if "usage-limit" in text: refused(message_id) return + if "cli-refusal" in text: + # The turn works and ends; then a background task's notification + # starts a turn of Claude Code's own, which the limit refuses. + send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test", + "content": [{"type": "text", "text": "Started it"}]}}) + finish(message_id) + state["turn"] += 1 + send({"type": "user", "origin": {"kind": "task-notification"}, + "message": {"role": "user", "content": [{"type": "text", "text": + "b1completed" + "Background command completed"}]}}) + refused("msg_fake_%d" % state["turn"]) + return if "notify" in text: send({"type": "system", "subtype": "task_notification", "task_id": "b1", "tool_use_id": "toolu_bg_fake", "status": "completed", "summary": "Background command completed (exit code 0)"}) diff --git a/internal/claudeaccounts/settings.go b/internal/claudeaccounts/settings.go index 72ea2b1c..87309214 100644 --- a/internal/claudeaccounts/settings.go +++ b/internal/claudeaccounts/settings.go @@ -17,6 +17,8 @@ const settingsFile = "settings.json" type settings struct { // AutoSwitch is nil until the operator chooses; the default is on. AutoSwitch *bool `json:"auto_switch,omitempty"` + // AutoContinue is nil until the operator chooses; the default is on. + AutoContinue *bool `json:"auto_continue,omitempty"` } func (s Store) readSettings() settings { @@ -40,25 +42,43 @@ func (s Store) AutoSwitch() bool { // SetAutoSwitch records the automatic-switch preference and returns the // accounts list, which reports it. func (s Store) SetAutoSwitch(on bool) (protocol.ClaudeAccountList, error) { - if err := s.check(); err != nil { - return protocol.ClaudeAccountList{}, err - } - dir := s.slotsDir() - if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, fs.ErrExist) { - return protocol.ClaudeAccountList{}, err - } - current := s.readSettings() - current.AutoSwitch = &on - data, err := marshal(current) - if err != nil { - return protocol.ClaudeAccountList{}, err - } - path := filepath.Join(dir, settingsFile) - if err := writeAtomic(path, data, 0o600); err != nil { - return protocol.ClaudeAccountList{}, err - } - if err := os.Chmod(path, 0o600); err != nil { + if err := s.updateSettings(func(current *settings) { current.AutoSwitch = &on }); err != nil { return protocol.ClaudeAccountList{}, err } return s.List() } + +// AutoContinue reports whether a chat on this Claude home that a usage limit +// refused is continued automatically once the limit resets (on by default). +func (s Store) AutoContinue() bool { + if on := s.readSettings().AutoContinue; on != nil { + return *on + } + return true +} + +// SetAutoContinue records the auto-continue-at-reset preference. +func (s Store) SetAutoContinue(on bool) error { + return s.updateSettings(func(current *settings) { current.AutoContinue = &on }) +} + +func (s Store) updateSettings(change func(*settings)) error { + if err := s.check(); err != nil { + return err + } + dir := s.slotsDir() + if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, fs.ErrExist) { + return err + } + current := s.readSettings() + change(¤t) + data, err := marshal(current) + if err != nil { + return err + } + path := filepath.Join(dir, settingsFile) + if err := writeAtomic(path, data, 0o600); err != nil { + return err + } + return os.Chmod(path, 0o600) +} diff --git a/internal/pipeline/settings.go b/internal/pipeline/settings.go index cc7a720e..014e3400 100644 --- a/internal/pipeline/settings.go +++ b/internal/pipeline/settings.go @@ -29,6 +29,26 @@ ON CONFLICT(key) DO UPDATE SET value=excluded.value`, openCodeEndpointSetting, u return err } +// ServerSetting reads one server_settings value; found is false when it was +// never recorded. +func (s *Store) ServerSetting(ctx context.Context, key string) (value string, found bool, err error) { + err = s.db.QueryRowContext(ctx, `SELECT value FROM server_settings WHERE key=?`, key).Scan(&value) + if err == sql.ErrNoRows { + return "", false, nil + } + if err != nil { + return "", false, err + } + return value, true, nil +} + +// SetServerSetting records one server_settings value. +func (s *Store) SetServerSetting(ctx context.Context, key, value string) error { + _, err := s.db.ExecContext(ctx, `INSERT INTO server_settings(key,value) VALUES(?,?) +ON CONFLICT(key) DO UPDATE SET value=excluded.value`, key, value) + return err +} + // OpenCodeEndpoint returns the recorded OpenCode endpoint, or an empty string // when none was ever recorded. func (s *Store) OpenCodeEndpoint(ctx context.Context) (string, error) { diff --git a/internal/protocol/claude_accounts.go b/internal/protocol/claude_accounts.go index 774638c2..f7319c17 100644 --- a/internal/protocol/claude_accounts.go +++ b/internal/protocol/claude_accounts.go @@ -65,3 +65,27 @@ type ClaudeAccountList struct { // home to another saved account and continues the chat automatically. AutoSwitch bool `json:"auto_switch"` } + +// ChatAutoContinueType reads (AutoContinue nil) or sets the "Auto-continue +// when limits reset" choice that applies to a chat: when a usage limit +// refuses one of its turns, the server queues a prompt to send a minute after +// the reset. The choice is kept per Claude home (beside auto_switch) for a +// chat whose directory selects one, else by the server for every other chat; +// it is on by default. The reply carries the current choice. +const ChatAutoContinueType = "chat_auto_continue" + +// Scopes of a ChatAutoContinue reply. +const ( + ChatAutoContinueClaudeHome = "claude_home" + ChatAutoContinueServer = "server" +) + +// ChatAutoContinue is the chat_auto_continue body and reply. +type ChatAutoContinue struct { + SessionID string `json:"session_id"` + // AutoContinue is the new choice of a request (nil reads it) and the + // current choice in the reply. + AutoContinue *bool `json:"auto_continue,omitempty"` + // Scope says where the choice is kept: claude_home or server (reply). + Scope string `json:"scope,omitempty"` +} diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 6ab0d983..f856d401 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -256,6 +256,8 @@ type Message struct { // ClaudeAccounts their reply (claude_accounts.go). ClaudeAccount *ClaudeAccountRequest `json:"claude_account,omitempty"` ClaudeAccounts *ClaudeAccountList `json:"claude_accounts,omitempty"` + // ChatAutoContinue is the chat_auto_continue body and reply. + ChatAutoContinue *ChatAutoContinue `json:"chat_auto_continue,omitempty"` // ModelRequest is the chat_model body and echoed selection. ModelRequest *ChatModelRequest `json:"chat_model,omitempty"` // ChatModes is the chat_modes reply: the permission modes the session's diff --git a/internal/server/chat.go b/internal/server/chat.go index 2246896b..eccbcfe8 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -256,6 +256,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker case protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove, protocol.ClaudeAccountAutoSwitch: handleClaudeAccounts(ctx, request, broker, write) return true + case protocol.ChatAutoContinueType: + handleChatAutoContinue(ctx, request, broker, hub, registry, write) + return true case protocol.ChatModelSelect: handleChatModelSwitch(ctx, request, broker, write) return true diff --git a/internal/server/chat_auto_continue.go b/internal/server/chat_auto_continue.go new file mode 100644 index 00000000..1962c8e9 --- /dev/null +++ b/internal/server/chat_auto_continue.go @@ -0,0 +1,215 @@ +package server + +import ( + "context" + "errors" + "log" + "strconv" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/claude" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// When Claude Code refuses an operator chat's turn for a usage limit and the +// server did not continue it on another account (chat_auto_switch.go), the +// server queues a durable prompt into the chat to send a minute after the +// limit resets: the refused operator message again when the turn was that +// message and did no work, else "continue". It is marked as sent +// automatically and waits in the queue as "Scheduled", where the operator can +// remove it. Its operation id, auto-continue-, is the one +// the app used when it scheduled the prompt itself, so a refusal is continued +// once however many devices and servers saw it. It honours the operator's +// "Auto-continue when limits reset" choice (on by default), kept per Claude +// home, or by this server for a chat without one. A refusal that names no +// reset is not continued. + +const ( + // chatAutoContinueMargin is how long after the reset the prompt is sent, + // so it does not race the quota coming back. + chatAutoContinueMargin = time.Minute + // chatAutoContinueText is sent when there is no refused message to send + // again. + chatAutoContinueText = "continue" + // chatAutoContinueSetting is the server_settings key of the choice for + // chats without a Claude home of their own. + chatAutoContinueSetting = "chat.auto_continue" +) + +// chatAutoContinueHome keeps the choice per Claude home (*claude.Chat, and +// chatManager routing to it). It reports claude.ErrNoConfigDir for a chat +// whose directory selects no Claude home. +type chatAutoContinueHome interface { + AutoContinue(ctx context.Context, sessionID, directory string) (bool, error) + SetAutoContinue(ctx context.Context, sessionID, directory string, on bool) error +} + +// chatServerSettings is the server's own settings table; *pipeline.Store +// implements it. +type chatServerSettings interface { + ServerSetting(ctx context.Context, key string) (string, bool, error) + SetServerSetting(ctx context.Context, key, value string) error +} + +// AutoContinue routes the Claude-home choice to the Claude harness. +func (m *chatManager) AutoContinue(ctx context.Context, sessionID, directory string) (bool, error) { + home, err := m.autoContinueHome(ctx, sessionID) + if err != nil { + return false, err + } + return home.AutoContinue(ctx, sessionID, directory) +} + +// SetAutoContinue routes the Claude-home choice to the Claude harness. +func (m *chatManager) SetAutoContinue(ctx context.Context, sessionID, directory string, on bool) error { + home, err := m.autoContinueHome(ctx, sessionID) + if err != nil { + return err + } + return home.SetAutoContinue(ctx, sessionID, directory, on) +} + +func (m *chatManager) autoContinueHome(ctx context.Context, sessionID string) (chatAutoContinueHome, error) { + if m.backendFor(ctx, sessionID) != claude.Backend { + return nil, errNotClaudeChat + } + home, ok := m.attached(claude.Backend).(chatAutoContinueHome) + if !ok { + return nil, errNotClaudeChat + } + return home, nil +} + +// serverSettings is the hub's settings table, or nil. +func (h *chatHub) serverSettings() chatServerSettings { + store, _ := h.settings.(chatServerSettings) + return store +} + +// autoContinue reads the choice that applies to sessionID and where it is +// kept. +func (h *chatHub) autoContinue(ctx context.Context, broker chatBroker, sessionID, directory string) (bool, string, error) { + if home, ok := broker.(chatAutoContinueHome); ok { + on, err := home.AutoContinue(ctx, sessionID, directory) + if err == nil { + return on, protocol.ChatAutoContinueClaudeHome, nil + } + if !errors.Is(err, claude.ErrNoConfigDir) && !errors.Is(err, errNotClaudeChat) { + return false, "", err + } + } + store := h.serverSettings() + if store == nil { + return true, protocol.ChatAutoContinueServer, nil + } + value, found, err := store.ServerSetting(ctx, chatAutoContinueSetting) + if err != nil { + return false, "", err + } + on := true + if found { + on, _ = strconv.ParseBool(value) + } + return on, protocol.ChatAutoContinueServer, nil +} + +// setAutoContinue records the choice where autoContinue reads it. +func (h *chatHub) setAutoContinue(ctx context.Context, broker chatBroker, sessionID, directory string, on bool) (string, error) { + if home, ok := broker.(chatAutoContinueHome); ok { + err := home.SetAutoContinue(ctx, sessionID, directory, on) + if err == nil { + return protocol.ChatAutoContinueClaudeHome, nil + } + if !errors.Is(err, claude.ErrNoConfigDir) && !errors.Is(err, errNotClaudeChat) { + return "", err + } + } + store := h.serverSettings() + if store == nil { + return "", errors.New("auto-continue cannot be changed: this server keeps no settings") + } + return protocol.ChatAutoContinueServer, store.SetServerSetting(ctx, chatAutoContinueSetting, strconv.FormatBool(on)) +} + +// continueAtReset queues refusal's auto-continue prompt (see the file +// comment). The caller already claimed the refusal. +func (h *chatHub) continueAtReset(ctx context.Context, broker chatBroker, refusal claude.UsageRefusal) { + if refusal.ResetsAt.IsZero() { + return + } + on, _, err := h.autoContinue(ctx, broker, refusal.SessionID, refusal.Directory) + if err != nil { + log.Printf("claude auto-continue session=%s: read the setting: %v", refusal.SessionID, err) + return + } + if !on { + return + } + operationID := chatAutoContinuePrefix + refusalKey(refusal) + if h.autoContinueSuperseded(refusal.SessionID, operationID) { + return + } + // A prompt already waiting to continue the chat (an earlier refusal's, + // perhaps resending the operator's message) continues it; were it + // refused again, that refusal schedules the next. + for _, prompt := range h.queueFrame(refusal.SessionID).Prompts { + if strings.HasPrefix(prompt.OperationID, chatAutoContinuePrefix) && prompt.OperationID != operationID { + return + } + } + text := strings.TrimSpace(refusal.Prompt) + if text == "" { + text = chatAutoContinueText + } + sendAt := refusal.ResetsAt.Add(chatAutoContinueMargin) + if err := h.queueServerPrompt(ctx, broker, refusal.SessionID, operationID, text, sendAt); err != nil { + log.Printf("claude auto-continue session=%s: queue the prompt: %v", refusal.SessionID, err) + return + } + log.Printf("claude auto-continue session=%s: scheduled %s for %s", refusal.SessionID, operationID, sendAt.Format(time.RFC3339)) +} + +// holdsQueued reports whether the session's queue (live, else durable) +// holds operationID. +func (h *chatHub) holdsQueued(sessionID, operationID string) bool { + for _, prompt := range h.queueFrame(sessionID).Prompts { + if prompt.OperationID == operationID { + return true + } + } + return false +} + +// handleChatAutoContinue answers chat_auto_continue: it reads, or sets, the +// auto-continue choice that applies to a chat. +func handleChatAutoContinue(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, write func(protocol.Message) error) { + body := request.ChatAutoContinue + if body == nil || !validChatSessionID(body.SessionID) { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"}) + return + } + directory := "" + if registry != nil { + if row, found, err := registry.OperatorSession(ctx, body.SessionID); err == nil && found { + directory = row.Directory + } + } + var ( + on bool + scope string + err error + ) + if body.AutoContinue != nil { + on = *body.AutoContinue + scope, err = hub.setAutoContinue(ctx, broker, body.SessionID, directory, on) + } else { + on, scope, err = hub.autoContinue(ctx, broker, body.SessionID, directory) + } + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + _ = write(protocol.Message{Type: protocol.ChatAutoContinueType, ID: request.ID, + ChatAutoContinue: &protocol.ChatAutoContinue{SessionID: body.SessionID, AutoContinue: &on, Scope: scope}}) +} diff --git a/internal/server/chat_auto_continue_test.go b/internal/server/chat_auto_continue_test.go new file mode 100644 index 00000000..1f8765f4 --- /dev/null +++ b/internal/server/chat_auto_continue_test.go @@ -0,0 +1,163 @@ +package server + +import ( + "context" + "slices" + "strings" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/claude" + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// autoContinueServer is an operator chat whose refusals find no account to +// switch to. +func autoContinueServer(t *testing.T) (*refusingChat, *queueServer, *pipeline.Store) { + t.Helper() + capturePublications(t) + broker, server, store := autoSwitchServer(t, "ses_1") + broker.quiet = true + broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) { + return claude.AutoSwitch{}, claude.ErrNoAccountLeft + } + return broker, server, store +} + +func queuedRows(t *testing.T, store *pipeline.Store) []pipeline.ChatQueuedPrompt { + t.Helper() + rows, err := store.ChatQueuedPrompts(context.Background(), "ses_1") + if err != nil { + t.Fatal(err) + } + return rows +} + +// A refusal the server could not switch away from schedules one automatic +// prompt a minute after the reset: "continue" after a turn that worked, the +// refused message itself after one that did not. Seeing it again (a second +// report, a device scheduling the same refusal) adds nothing. +func TestUsageRefusalSchedulesAutoContinueAtTheReset(t *testing.T) { + for _, tc := range []struct{ name, prompt, want string }{ + {"worked", "", "continue"}, + {"refused prompt", "Fix the build", "Fix the build"}, + } { + t.Run(tc.name, func(t *testing.T) { + broker, server, store := autoContinueServer(t) + reset := time.Now().Add(2 * time.Hour).Truncate(time.Second) + refusal := claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", Email: "a@example.invalid", ResetsAt: reset, Prompt: tc.prompt} + broker.refuse(refusal) + broker.refuse(refusal) + conn := dialChatConn(t, server.ctx, server.srv) + if ack := sendScheduled(t, server.ctx, conn, "p1", "continue", "auto-continue-refusal-1", reset.Add(time.Minute)); !ack.ChatQueued { + t.Fatalf("device's copy ack = %+v", ack) + } + rows := queuedRows(t, store) + if len(rows) != 1 { + t.Fatalf("queued = %+v", rows) + } + row := rows[0] + if row.OperationID != "auto-continue-refusal-1" || row.Text != tc.want || row.Client != chatAutoSwitchClient || + !row.SendAt.Equal(reset.Add(time.Minute)) { + t.Fatalf("row = %+v", row) + } + if n := broker.promptCount(); n != 0 { + t.Fatalf("prompts sent before the reset: %d", n) + } + }) + } +} + +// A refusal without a reset time is not continued, and neither is any +// refusal while the operator turned auto-continue off (a server-kept choice +// for a chat without a Claude home of its own). +func TestUsageRefusalAutoContinueNeedsAResetAndTheSetting(t *testing.T) { + broker, server, store := autoContinueServer(t) + broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1"}) + if ops := queuedOps(t, store); len(ops) != 0 { + t.Fatalf("queued without a reset: %v", ops) + } + + conn := dialChatConn(t, server.ctx, server.srv) + read := func(id string, on *bool) *protocol.ChatAutoContinue { + t.Helper() + writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatAutoContinueType, ID: id, ChatAutoContinue: &protocol.ChatAutoContinue{SessionID: "ses_1", AutoContinue: on}}) + reply := readUntil(t, server.ctx, conn, protocol.ChatAutoContinueType) + if reply.ChatAutoContinue == nil || reply.ChatAutoContinue.AutoContinue == nil { + t.Fatalf("reply = %+v", reply) + } + return reply.ChatAutoContinue + } + if got := read("r1", nil); !*got.AutoContinue || got.Scope != protocol.ChatAutoContinueServer { + t.Fatalf("default = %+v", got) + } + off := false + if got := read("r2", &off); *got.AutoContinue { + t.Fatalf("set off = %+v", got) + } + if got := read("r3", nil); *got.AutoContinue { + t.Fatalf("read back = %+v", got) + } + broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-2", MessageID: "refusal-2", ResetsAt: time.Now().Add(time.Hour)}) + if ops := queuedOps(t, store); len(ops) != 0 { + t.Fatalf("queued with auto-continue off: %v", ops) + } +} + +// When the server continues a refusal on another account, no auto-continue +// is scheduled for it, and one still waiting from an earlier refusal is +// removed. +func TestAutoSwitchReplacesTheAutoContinue(t *testing.T) { + broker, _, store := autoContinueServer(t) + reset := time.Now().Add(time.Hour) + broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: reset}) + if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-1"}) { + t.Fatalf("queued = %v", ops) + } + broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) { + return claude.AutoSwitch{From: "a@example.invalid", To: "b@example.invalid", Switched: true}, nil + } + broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-2", MessageID: "refusal-2", ResetsAt: reset}) + // The idle chat takes the switch's continue prompt at once. + waitFor(t, "the continue prompt", func() bool { return broker.promptCount() == 1 }) + if text := broker.promptTexts()[0]; !strings.HasPrefix(text, "[Sent automatically by Pipelines]") { + t.Fatalf("sent %q", text) + } + if ops := queuedOps(t, store); len(ops) != 0 { + t.Fatalf("queued after the switch = %v", ops) + } +} + +// A later refusal (a background-task turn Claude Code started itself, say) +// leaves the waiting auto-continue as it is: it continues the chat, and +// keeps the operator's refused message. +func TestLaterRefusalKeepsTheWaitingAutoContinue(t *testing.T) { + broker, _, store := autoContinueServer(t) + reset := time.Now().Add(time.Hour) + broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: reset, Prompt: "Fix the build"}) + broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "result-x", MessageID: "refusal-2", ResetsAt: reset}) + rows := queuedRows(t, store) + if len(rows) != 1 || rows[0].OperationID != "auto-continue-refusal-1" || rows[0].Text != "Fix the build" { + t.Fatalf("queued = %+v", rows) + } +} + +// A refusal reported again by a restarted server (its output replayed) finds +// the durable prompt and queues no second one. +func TestRestartedServerDoesNotScheduleTheRefusalTwice(t *testing.T) { + broker, server, store := autoContinueServer(t) + refusal := claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: time.Now().Add(time.Hour)} + broker.refuse(refusal) + server.stop() + + restarted := &refusingChat{channelChat: newChannelChat(), quiet: true} + restarted.switch_ = broker.switch_ + again := startQueueServer(t, restarted, store) + conn := dialChatConn(t, again.ctx, again.srv) + writeChat(t, again.ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}}) + restarted.refuse(refusal) + if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-1"}) { + t.Fatalf("queued after the restart = %v", ops) + } +} diff --git a/internal/server/chat_auto_switch.go b/internal/server/chat_auto_switch.go index f4d268a3..fea5d75a 100644 --- a/internal/server/chat_auto_switch.go +++ b/internal/server/chat_auto_switch.go @@ -19,16 +19,17 @@ import ( // usage left (and the operator left automatic switching on), the server // switches the home to that account and queues a prompt, marked as sent // automatically, that asks the agent to check it is still on track before it -// continues. It works with no client attached. The app's own -// auto-continue-at-reset prompt for that refusal is taken back out. When no -// account has usage left nothing more happens, and auto-continue at the reset -// still applies. +// continues. It works with no client attached. Any auto-continue-at-reset +// prompt for that refusal is taken back out. When no account has usage left +// (or switching is off), the chat continues at the reset instead +// (chat_auto_continue.go). const ( // chatAutoSwitchPrefix starts the operation id of the continue prompt. chatAutoSwitchPrefix = "auto-switch-" - // chatAutoContinuePrefix starts the app's auto-continue-at-reset prompt - // ids ("auto-continue-"). + // chatAutoContinuePrefix starts the auto-continue-at-reset prompt ids + // ("auto-continue-"), the server's and an older + // app's alike. chatAutoContinuePrefix = "auto-continue-" // chatAutoSwitchClient is the sender label of the continue prompt. chatAutoSwitchClient = "Pipelines (automatic)" @@ -129,19 +130,22 @@ func (h *chatHub) continueOnAnotherAccount(broker chatBroker, refusal claude.Usa } switcher, ok := broker.(chatAutoSwitcher) if !ok { + h.continueAtReset(ctx, broker, refusal) return } result, err := switcher.AutoSwitchAccount(ctx, refusal) if err != nil { - if !errors.Is(err, claude.ErrAutoSwitchOff) && !errors.Is(err, claude.ErrNoConfigDir) { + if !errors.Is(err, claude.ErrAutoSwitchOff) && !errors.Is(err, claude.ErrNoConfigDir) && + !errors.Is(err, claude.ErrNoAccountLeft) && !errors.Is(err, errNotClaudeChat) { log.Printf("claude auto-switch session=%s: %v", refusal.SessionID, err) } + h.continueAtReset(ctx, broker, refusal) return } operationID := chatAutoSwitchPrefix + refusalKey(refusal) h.autoSwitch.supersede(refusal, operationID) h.dropAutoContinue(ctx, refusal.SessionID) - if err := h.queueServerPrompt(ctx, broker, refusal.SessionID, operationID, chatAutoSwitchText(result.From, result.To)); err != nil { + if err := h.queueServerPrompt(ctx, broker, refusal.SessionID, operationID, chatAutoSwitchText(result.From, result.To), time.Time{}); err != nil { log.Printf("claude auto-switch session=%s: queue the continue prompt: %v", refusal.SessionID, err) return } @@ -229,10 +233,13 @@ func (h *chatHub) dropAutoContinue(ctx context.Context, sessionID string) { } // queueServerPrompt hands the session a prompt the server composed: it runs -// once the current turn has ended (queued durably behind it), and every -// attached client sees it under the server's own sender label. -func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sessionID, operationID, text string) error { - if duplicate, _, _ := h.duplicateOp(sessionID, operationID); duplicate { +// once the current turn has ended (queued durably behind it), or not before +// sendAt when that is set, and every attached client sees it under the +// server's own sender label (a scheduled one through the queue, as +// "Scheduled", until it is sent). A prompt the session already holds under +// operationID is not queued again. +func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error { + if duplicate, _, _ := h.duplicateOp(sessionID, operationID); duplicate || h.holdsQueued(sessionID, operationID) { return nil } p := &chatQueuedPrompt{ @@ -242,12 +249,18 @@ func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sess client: chatAutoSwitchClient, noSteer: true, } + if sendAt.After(h.clock()) { + p.sendAt = sendAt + } h.rememberOp(sessionID, operationID) admission, err := h.admitPrompt(ctx, sessionID, broker, p) if admission == chatAdmitRefused { h.forgetOp(sessionID, operationID) return err } + if !p.sendAt.IsZero() { + return nil + } h.broadcastUser(protocol.ChatEventFrame{ SessionID: sessionID, MessageID: p.messageID,