Merge branch 'worktree-agent-a04a38e74fe1aef60'
This commit is contained in:
@@ -3,6 +3,8 @@ import 'dart:async';
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
import '../../../core/api_gateway.dart';
|
||||||
|
|
||||||
const chatAutoContinuePreferenceKey = 'pipelines.chatAutoContinue.v1';
|
const chatAutoContinuePreferenceKey = 'pipelines.chatAutoContinue.v1';
|
||||||
|
|
||||||
/// The usage-limit banner's "Auto-continue when limits reset" choice: one
|
/// 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-resuming at 15:41", an
|
||||||
/// "Auto-continue when limits reset" checkbox and Try again.
|
/// "Auto-continue when limits reset" checkbox and Try again.
|
||||||
///
|
///
|
||||||
/// With auto-continue on (a preference shared by every chat, on by default,
|
/// The chat counts as refused while its latest turn is the limit's refusal,
|
||||||
/// [ChatAutoContinue]) and the transcript ending on the limit's refusal, the
|
/// whatever notices or agent reports arrived after it. With auto-continue on,
|
||||||
/// banner hands the server a prompt to send a minute after the reset: the
|
/// the server queues a prompt to send a minute after the reset (the refused
|
||||||
/// refused operator message again, or "continue" when the refused turn had
|
/// operator message again, or "continue" when the refused turn had already
|
||||||
/// already worked on it. The server holds it durably, so it is sent with the
|
/// worked on it), with no app involved; the choice is the server's
|
||||||
/// app closed or the server restarted. Unchecking takes it back out of the
|
/// ([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
|
/// 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
|
/// 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
|
/// or by the server's automatic switch, whose queued continue prompt also
|
||||||
@@ -35,6 +39,7 @@ class ChatUsageLimitBanner extends StatefulWidget {
|
|||||||
required this.composer,
|
required this.composer,
|
||||||
this.accounts,
|
this.accounts,
|
||||||
ChatAutoContinue? autoContinue,
|
ChatAutoContinue? autoContinue,
|
||||||
|
this.serverAutoContinue,
|
||||||
this.now = DateTime.now,
|
this.now = DateTime.now,
|
||||||
}) : autoContinue = autoContinue ?? ChatAutoContinue.shared;
|
}) : autoContinue = autoContinue ?? ChatAutoContinue.shared;
|
||||||
|
|
||||||
@@ -45,6 +50,10 @@ class ChatUsageLimitBanner extends StatefulWidget {
|
|||||||
/// null for a chat that is not Claude Code's.
|
/// null for a chat that is not Claude Code's.
|
||||||
final ChatClaudeAccountsController? accounts;
|
final ChatClaudeAccountsController? accounts;
|
||||||
final ChatAutoContinue autoContinue;
|
final ChatAutoContinue autoContinue;
|
||||||
|
|
||||||
|
/// The server's choice for this chat; null builds one on [thread]'s
|
||||||
|
/// gateway.
|
||||||
|
final ChatServerAutoContinue? serverAutoContinue;
|
||||||
final DateTime Function() now;
|
final DateTime Function() now;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -59,18 +68,48 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
|||||||
/// refused request is not repeated on every rebuild.
|
/// refused request is not repeated on every rebuild.
|
||||||
final Set<String> _requested = {};
|
final Set<String> _requested = {};
|
||||||
|
|
||||||
|
late ChatServerAutoContinue _server;
|
||||||
|
bool _ownsServer = false;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
unawaited(widget.autoContinue.load());
|
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
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_reset?.cancel();
|
_reset?.cancel();
|
||||||
|
if (_ownsServer) _server.dispose();
|
||||||
super.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.
|
/// Rebuilds when the reset passes, so the banner leaves on time.
|
||||||
void _watchReset(DateTime? at, DateTime now) {
|
void _watchReset(DateTime? at, DateTime now) {
|
||||||
if (at == _resetFor) return;
|
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.
|
// Rechecking may schedule the same refusal again.
|
||||||
_requested.clear();
|
_requested.clear();
|
||||||
await widget.autoContinue.set(on);
|
if (!_server.supported) {
|
||||||
if (!on) await _cancel(pending);
|
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 {
|
Future<void> _tryAgain(ChatRefusedTurn refused, List<JsonMap> pending) async {
|
||||||
@@ -144,6 +199,7 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
|||||||
widget.thread,
|
widget.thread,
|
||||||
widget.composer,
|
widget.composer,
|
||||||
widget.autoContinue,
|
widget.autoContinue,
|
||||||
|
_server,
|
||||||
]),
|
]),
|
||||||
builder: (context, _) {
|
builder: (context, _) {
|
||||||
final now = widget.now();
|
final now = widget.now();
|
||||||
@@ -158,9 +214,13 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
|||||||
final refused = chatRefusedTurn(thread.messages, thread.accountUsage);
|
final refused = chatRefusedTurn(thread.messages, thread.accountUsage);
|
||||||
final pending = _pending(now);
|
final pending = _pending(now);
|
||||||
final auto = widget.autoContinue;
|
final auto = widget.autoContinue;
|
||||||
|
unawaited(_server.load());
|
||||||
// The server already switched accounts and is continuing the chat.
|
// The server already switched accounts and is continuing the chat.
|
||||||
final switching = chatAutoSwitchPending(thread.queuedPrompts);
|
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 &&
|
auto.enabled &&
|
||||||
refused != null &&
|
refused != null &&
|
||||||
pending.isEmpty &&
|
pending.isEmpty &&
|
||||||
@@ -183,7 +243,7 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
|||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final scheme = theme.colorScheme;
|
final scheme = theme.colorScheme;
|
||||||
final text = theme.textTheme;
|
final text = theme.textTheme;
|
||||||
final enabled = widget.autoContinue.enabled;
|
final enabled = _enabled;
|
||||||
String time(DateTime at) => chatScheduleTime(context, at, now: () => now);
|
String time(DateTime at) => chatScheduleTime(context, at, now: () => now);
|
||||||
final resumesAt = pending.isEmpty
|
final resumesAt = pending.isEmpty
|
||||||
? limit.sendAt
|
? limit.sendAt
|
||||||
@@ -253,7 +313,7 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
|||||||
spacing: 8,
|
spacing: 8,
|
||||||
runSpacing: 4,
|
runSpacing: 4,
|
||||||
children: [
|
children: [
|
||||||
_checkbox(context, enabled, pending),
|
_checkbox(context, enabled, pending, refused, limit),
|
||||||
Wrap(
|
Wrap(
|
||||||
spacing: 8,
|
spacing: 8,
|
||||||
runSpacing: 4,
|
runSpacing: 4,
|
||||||
@@ -283,8 +343,15 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _checkbox(BuildContext context, bool enabled, List<JsonMap> pending) {
|
Widget _checkbox(
|
||||||
void toggle(bool? on) => unawaited(_toggle(on ?? false, pending));
|
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.
|
// A labelled checkbox: the label toggles it too, as one control.
|
||||||
return MergeSemantics(
|
return MergeSemantics(
|
||||||
child: InkWell(
|
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.
|
/// session limit"); the first clause is the limit's own wording.
|
||||||
final RegExp _hitText = RegExp(r"^\s*You['’]ve hit your [^·\n]*limit");
|
final RegExp _hitText = RegExp(r"^\s*You['’]ve hit your [^·\n]*limit");
|
||||||
|
|
||||||
/// The last transcript message that is part of the conversation (a message
|
/// Whether [message] is a turn of the conversation: the operator's message
|
||||||
/// scheduled since is not yet), or an empty map.
|
/// or the agent's reply. Not one: a message scheduled to send later, content
|
||||||
JsonMap _lastSent(List<JsonMap> messages) =>
|
/// the harness injected after the turn (an agent's report, a notice such as
|
||||||
messages.lastWhere((m) => m['send_at'] == null, orElse: () => const {});
|
/// 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
|
/// 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
|
/// transcript's last turn when it is the harness's limit refusal (notices
|
||||||
/// message scheduled since then is not part of the conversation yet).
|
/// and reports that arrived after it, and a message scheduled since, are
|
||||||
|
/// not turns).
|
||||||
ChatUsageLimit? chatThreadUsageLimit(
|
ChatUsageLimit? chatThreadUsageLimit(
|
||||||
ChatAccountUsage? usage,
|
ChatAccountUsage? usage,
|
||||||
List<JsonMap> messages,
|
List<JsonMap> messages,
|
||||||
@@ -93,7 +121,7 @@ ChatUsageLimit? chatThreadUsageLimit(
|
|||||||
) {
|
) {
|
||||||
final quota = chatUsageLimit(usage, now);
|
final quota = chatUsageLimit(usage, now);
|
||||||
if (quota != null) return quota;
|
if (quota != null) return quota;
|
||||||
final last = _lastSent(messages);
|
final last = _lastTurn(messages);
|
||||||
if (last.isEmpty || last['role'] == 'user') return null;
|
if (last.isEmpty || last['role'] == 'user') return null;
|
||||||
if (_beforeSwitch(usage, last)) return null;
|
if (_beforeSwitch(usage, last)) return null;
|
||||||
return chatUsageLimitFromText(_text(last), now);
|
return chatUsageLimitFromText(_text(last), now);
|
||||||
@@ -108,8 +136,10 @@ bool _beforeSwitch(ChatAccountUsage? usage, JsonMap message) {
|
|||||||
return created is! num || created <= switchedAt;
|
return created is! num || created <= switchedAt;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The turn the limit refused: the transcript ends on the harness's limit
|
/// The turn the limit refused: the transcript's latest turn is the harness's
|
||||||
/// refusal. Auto-continue and Try again send [text]: the operator's message
|
/// 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
|
/// the refusal answered, or "continue" when the refusal ended a turn that
|
||||||
/// had already worked on it.
|
/// had already worked on it.
|
||||||
class ChatRefusedTurn {
|
class ChatRefusedTurn {
|
||||||
@@ -143,16 +173,14 @@ class ChatRefusedTurn {
|
|||||||
String get autoContinueId => '$chatAutoContinuePrefix$refusalId';
|
String get autoContinueId => '$chatAutoContinuePrefix$refusalId';
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The refused turn [messages] end on, or null when the last message is not
|
/// The refused turn [messages] end on, or null when their last turn (see
|
||||||
/// a limit refusal (or came before an account switch in [usage]).
|
/// [chatIsTurnMessage]) is not a limit refusal (or came before an account
|
||||||
|
/// switch in [usage]).
|
||||||
ChatRefusedTurn? chatRefusedTurn(
|
ChatRefusedTurn? chatRefusedTurn(
|
||||||
List<JsonMap> messages,
|
List<JsonMap> messages,
|
||||||
ChatAccountUsage? usage,
|
ChatAccountUsage? usage,
|
||||||
) {
|
) {
|
||||||
final sent = [
|
final sent = _turns(messages);
|
||||||
for (final m in messages)
|
|
||||||
if (m['send_at'] == null) m,
|
|
||||||
];
|
|
||||||
if (sent.isEmpty) return null;
|
if (sent.isEmpty) return null;
|
||||||
final last = sent.last;
|
final last = sent.last;
|
||||||
if (last['role'] == 'user' || _beforeSwitch(usage, last)) return null;
|
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 {
|
Future<void> _pump(WidgetTester tester) async {
|
||||||
await tester.pump();
|
await tester.pump();
|
||||||
await tester.pump(const Duration(milliseconds: 100));
|
await tester.pump(const Duration(milliseconds: 100));
|
||||||
await tester.pump();
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A refused operator message: the refusal answers it directly.
|
/// 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', () {
|
test('a refusal from before an account switch no longer counts', () {
|
||||||
final refusal = {...message('r1', 'assistant', hit), 'created_at': 10};
|
final refusal = {...message('r1', 'assistant', hit), 'created_at': 10};
|
||||||
final switched = ChatAccountUsage(
|
final switched = ChatAccountUsage(
|
||||||
|
|||||||
+25
-4
@@ -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
|
`Pipelines (automatic)` and starting `[Sent automatically by Pipelines]` that
|
||||||
names both accounts and asks the agent to check its progress against the
|
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
|
request and its plan, and to stop and ask if it is off track, before it
|
||||||
continues. The app's `auto-continue-<refusal id>` prompt for that refusal is
|
continues. Any `auto-continue-<refusal id>` prompt waiting in the queue is
|
||||||
removed from the queue (and refused if it arrives later), and the operator gets
|
removed (and one arriving later is refused), and the operator gets
|
||||||
a low-priority notification "Switched <chat> to <email> and continued". Each
|
a low-priority notification "Switched <chat> to <email> and continued". Each
|
||||||
refusal switches at most once; a refusal of the new account tries the next
|
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
|
untried account; with none left auto-continue at the reset applies. It is on by
|
||||||
reset applies. It is on by default and is a per-Claude-home choice kept in
|
default and is a per-Claude-home choice kept in
|
||||||
`<config dir>/pipelines-accounts/settings.json`: `claude_account_auto_switch`
|
`<config dir>/pipelines-accounts/settings.json`: `claude_account_auto_switch`
|
||||||
(body `claude_account: {"session_id", "auto_switch": bool}`) sets it, every
|
(body `claude_account: {"session_id", "auto_switch": bool}`) sets it, every
|
||||||
`claude_accounts` reply reports it as `auto_switch`, and
|
`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
|
not switched: a stage refused for usage fails with the provider-quota error and
|
||||||
its run stops.
|
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-<refusal message id>` 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|<epoch>`), 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
|
The brokered OpenCode chat exposes the operator's own sessions, separate from the
|
||||||
sessions pipeline runs create. The protocol types are:
|
sessions pipeline runs create. The protocol types are:
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -189,6 +189,7 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
|
|||||||
s.turnID = turn
|
s.turnID = turn
|
||||||
s.running = true
|
s.running = true
|
||||||
s.beginTurnLocked()
|
s.beginTurnLocked()
|
||||||
|
s.turnPrompt = strings.TrimSpace(text)
|
||||||
s.steered = 0
|
s.steered = 0
|
||||||
s.awaitFollowUp = false
|
s.awaitFollowUp = false
|
||||||
s.recordPromptLocked(messageID, text)
|
s.recordPromptLocked(messageID, text)
|
||||||
@@ -254,6 +255,9 @@ func (c *Chat) SteerPrompt(ctx context.Context, id, text, messageID string, file
|
|||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
s.steered++
|
s.steered++
|
||||||
s.lastUsed = time.Now()
|
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.recordPromptLocked(messageID, text)
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
return true, nil
|
return true, nil
|
||||||
|
|||||||
@@ -387,8 +387,18 @@ type session struct {
|
|||||||
turnEmail string
|
turnEmail string
|
||||||
limitMessageID string
|
limitMessageID string
|
||||||
limitByError bool
|
limitByError bool
|
||||||
prompts []promptRecord
|
// limitText and limitAt are the refusal's own text and when it was
|
||||||
models []protocol.ChatModel
|
// 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;
|
// commands are the slash commands the live CLI's initialize listed;
|
||||||
// terminalCommands are those its init line marks terminal-only (commands.go).
|
// terminalCommands are those its init line marks terminal-only (commands.go).
|
||||||
commands []protocol.ChatCommand
|
commands []protocol.ChatCommand
|
||||||
|
|||||||
@@ -199,8 +199,14 @@ func (s *session) handleRateLimit(raw json.RawMessage) {
|
|||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
}
|
}
|
||||||
c := s.chat
|
c := s.chat
|
||||||
|
until, rejected := rejectedUntil(raw)
|
||||||
|
if rejected {
|
||||||
|
s.mu.Lock()
|
||||||
|
s.noteRejectedResetLocked(until)
|
||||||
|
s.mu.Unlock()
|
||||||
|
}
|
||||||
c.quotaMu.Lock()
|
c.quotaMu.Lock()
|
||||||
if until, ok := rejectedUntil(raw); ok {
|
if rejected {
|
||||||
c.noteRejectedLocked(account.email, until)
|
c.noteRejectedLocked(account.email, until)
|
||||||
}
|
}
|
||||||
next := mergeRateLimit(c.quotas[key], raw, account.plan, time.Now())
|
next := mergeRateLimit(c.quotas[key], raw, account.plan, time.Now())
|
||||||
|
|||||||
+126
-5
@@ -2,6 +2,7 @@ package claude
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -27,6 +28,15 @@ type UsageRefusal struct {
|
|||||||
MessageID string
|
MessageID string
|
||||||
// Email is the account the refused turn started on ("" when unknown).
|
// Email is the account the refused turn started on ("" when unknown).
|
||||||
Email string
|
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
|
// 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.
|
// refusal of the previous turn. The caller holds s.mu.
|
||||||
func (s *session) beginTurnLocked() {
|
func (s *session) beginTurnLocked() {
|
||||||
s.turnEmail = s.account.email
|
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.limitMessageID = ""
|
||||||
s.limitByError = false
|
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
|
// noteUsageRefusalLocked remembers an assistant message that is a
|
||||||
@@ -65,9 +86,23 @@ func (s *session) noteUsageRefusalLocked(envelope lineEnvelope, body messageBody
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if byError || byText {
|
if !byError && !byText {
|
||||||
s.limitMessageID = messageID
|
if messageID != s.limitMessageID {
|
||||||
s.limitByError = s.limitByError || byError
|
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 == "" {
|
if refusal.TurnID == "" {
|
||||||
refusal.TurnID = "result-" + strings.TrimSpace(envelope.UUID)
|
refusal.TurnID = "result-" + strings.TrimSpace(envelope.UUID)
|
||||||
}
|
}
|
||||||
s.limitMessageID = ""
|
at := s.limitAt
|
||||||
s.limitByError = false
|
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
|
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|<epoch>".
|
||||||
|
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
|
// noteRejectedLocked records when a rejected account's limit ends. The
|
||||||
// caller holds c.quotaMu.
|
// caller holds c.quotaMu.
|
||||||
func (c *Chat) noteRejectedLocked(email string, until time.Time) {
|
func (c *Chat) noteRejectedLocked(email string, until time.Time) {
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
@@ -82,6 +82,19 @@ def user_message(text):
|
|||||||
if "usage-limit" in text:
|
if "usage-limit" in text:
|
||||||
refused(message_id)
|
refused(message_id)
|
||||||
return
|
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":
|
||||||
|
"<task-notification><task-id>b1</task-id><status>completed</status>"
|
||||||
|
"<summary>Background command completed</summary></task-notification>"}]}})
|
||||||
|
refused("msg_fake_%d" % state["turn"])
|
||||||
|
return
|
||||||
if "notify" in text:
|
if "notify" in text:
|
||||||
send({"type": "system", "subtype": "task_notification", "task_id": "b1",
|
send({"type": "system", "subtype": "task_notification", "task_id": "b1",
|
||||||
"tool_use_id": "toolu_bg_fake", "status": "completed", "summary": "Background command completed (exit code 0)"})
|
"tool_use_id": "toolu_bg_fake", "status": "completed", "summary": "Background command completed (exit code 0)"})
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ const settingsFile = "settings.json"
|
|||||||
type settings struct {
|
type settings struct {
|
||||||
// AutoSwitch is nil until the operator chooses; the default is on.
|
// AutoSwitch is nil until the operator chooses; the default is on.
|
||||||
AutoSwitch *bool `json:"auto_switch,omitempty"`
|
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 {
|
func (s Store) readSettings() settings {
|
||||||
@@ -40,25 +42,43 @@ func (s Store) AutoSwitch() bool {
|
|||||||
// SetAutoSwitch records the automatic-switch preference and returns the
|
// SetAutoSwitch records the automatic-switch preference and returns the
|
||||||
// accounts list, which reports it.
|
// accounts list, which reports it.
|
||||||
func (s Store) SetAutoSwitch(on bool) (protocol.ClaudeAccountList, error) {
|
func (s Store) SetAutoSwitch(on bool) (protocol.ClaudeAccountList, error) {
|
||||||
if err := s.check(); err != nil {
|
if err := s.updateSettings(func(current *settings) { current.AutoSwitch = &on }); 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 {
|
|
||||||
return protocol.ClaudeAccountList{}, err
|
return protocol.ClaudeAccountList{}, err
|
||||||
}
|
}
|
||||||
return s.List()
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,6 +29,26 @@ ON CONFLICT(key) DO UPDATE SET value=excluded.value`, openCodeEndpointSetting, u
|
|||||||
return err
|
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
|
// OpenCodeEndpoint returns the recorded OpenCode endpoint, or an empty string
|
||||||
// when none was ever recorded.
|
// when none was ever recorded.
|
||||||
func (s *Store) OpenCodeEndpoint(ctx context.Context) (string, error) {
|
func (s *Store) OpenCodeEndpoint(ctx context.Context) (string, error) {
|
||||||
|
|||||||
@@ -65,3 +65,27 @@ type ClaudeAccountList struct {
|
|||||||
// home to another saved account and continues the chat automatically.
|
// home to another saved account and continues the chat automatically.
|
||||||
AutoSwitch bool `json:"auto_switch"`
|
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"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -256,6 +256,8 @@ type Message struct {
|
|||||||
// ClaudeAccounts their reply (claude_accounts.go).
|
// ClaudeAccounts their reply (claude_accounts.go).
|
||||||
ClaudeAccount *ClaudeAccountRequest `json:"claude_account,omitempty"`
|
ClaudeAccount *ClaudeAccountRequest `json:"claude_account,omitempty"`
|
||||||
ClaudeAccounts *ClaudeAccountList `json:"claude_accounts,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 is the chat_model body and echoed selection.
|
||||||
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
|
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
|
||||||
// ChatModes is the chat_modes reply: the permission modes the session's
|
// ChatModes is the chat_modes reply: the permission modes the session's
|
||||||
|
|||||||
@@ -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:
|
case protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove, protocol.ClaudeAccountAutoSwitch:
|
||||||
handleClaudeAccounts(ctx, request, broker, write)
|
handleClaudeAccounts(ctx, request, broker, write)
|
||||||
return true
|
return true
|
||||||
|
case protocol.ChatAutoContinueType:
|
||||||
|
handleChatAutoContinue(ctx, request, broker, hub, registry, write)
|
||||||
|
return true
|
||||||
case protocol.ChatModelSelect:
|
case protocol.ChatModelSelect:
|
||||||
handleChatModelSwitch(ctx, request, broker, write)
|
handleChatModelSwitch(ctx, request, broker, write)
|
||||||
return true
|
return true
|
||||||
|
|||||||
@@ -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-<refusal message id>, 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}})
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,16 +19,17 @@ import (
|
|||||||
// usage left (and the operator left automatic switching on), the server
|
// usage left (and the operator left automatic switching on), the server
|
||||||
// switches the home to that account and queues a prompt, marked as sent
|
// 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
|
// 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
|
// continues. It works with no client attached. Any auto-continue-at-reset
|
||||||
// auto-continue-at-reset prompt for that refusal is taken back out. When no
|
// prompt for that refusal is taken back out. When no account has usage left
|
||||||
// account has usage left nothing more happens, and auto-continue at the reset
|
// (or switching is off), the chat continues at the reset instead
|
||||||
// still applies.
|
// (chat_auto_continue.go).
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// chatAutoSwitchPrefix starts the operation id of the continue prompt.
|
// chatAutoSwitchPrefix starts the operation id of the continue prompt.
|
||||||
chatAutoSwitchPrefix = "auto-switch-"
|
chatAutoSwitchPrefix = "auto-switch-"
|
||||||
// chatAutoContinuePrefix starts the app's auto-continue-at-reset prompt
|
// chatAutoContinuePrefix starts the auto-continue-at-reset prompt ids
|
||||||
// ids ("auto-continue-<refusal message id>").
|
// ("auto-continue-<refusal message id>"), the server's and an older
|
||||||
|
// app's alike.
|
||||||
chatAutoContinuePrefix = "auto-continue-"
|
chatAutoContinuePrefix = "auto-continue-"
|
||||||
// chatAutoSwitchClient is the sender label of the continue prompt.
|
// chatAutoSwitchClient is the sender label of the continue prompt.
|
||||||
chatAutoSwitchClient = "Pipelines (automatic)"
|
chatAutoSwitchClient = "Pipelines (automatic)"
|
||||||
@@ -129,19 +130,22 @@ func (h *chatHub) continueOnAnotherAccount(broker chatBroker, refusal claude.Usa
|
|||||||
}
|
}
|
||||||
switcher, ok := broker.(chatAutoSwitcher)
|
switcher, ok := broker.(chatAutoSwitcher)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
h.continueAtReset(ctx, broker, refusal)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
result, err := switcher.AutoSwitchAccount(ctx, refusal)
|
result, err := switcher.AutoSwitchAccount(ctx, refusal)
|
||||||
if err != nil {
|
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)
|
log.Printf("claude auto-switch session=%s: %v", refusal.SessionID, err)
|
||||||
}
|
}
|
||||||
|
h.continueAtReset(ctx, broker, refusal)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
operationID := chatAutoSwitchPrefix + refusalKey(refusal)
|
operationID := chatAutoSwitchPrefix + refusalKey(refusal)
|
||||||
h.autoSwitch.supersede(refusal, operationID)
|
h.autoSwitch.supersede(refusal, operationID)
|
||||||
h.dropAutoContinue(ctx, refusal.SessionID)
|
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)
|
log.Printf("claude auto-switch session=%s: queue the continue prompt: %v", refusal.SessionID, err)
|
||||||
return
|
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
|
// queueServerPrompt hands the session a prompt the server composed: it runs
|
||||||
// once the current turn has ended (queued durably behind it), and every
|
// once the current turn has ended (queued durably behind it), or not before
|
||||||
// attached client sees it under the server's own sender label.
|
// sendAt when that is set, and every attached client sees it under the
|
||||||
func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sessionID, operationID, text string) error {
|
// server's own sender label (a scheduled one through the queue, as
|
||||||
if duplicate, _, _ := h.duplicateOp(sessionID, operationID); duplicate {
|
// "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
|
return nil
|
||||||
}
|
}
|
||||||
p := &chatQueuedPrompt{
|
p := &chatQueuedPrompt{
|
||||||
@@ -242,12 +249,18 @@ func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sess
|
|||||||
client: chatAutoSwitchClient,
|
client: chatAutoSwitchClient,
|
||||||
noSteer: true,
|
noSteer: true,
|
||||||
}
|
}
|
||||||
|
if sendAt.After(h.clock()) {
|
||||||
|
p.sendAt = sendAt
|
||||||
|
}
|
||||||
h.rememberOp(sessionID, operationID)
|
h.rememberOp(sessionID, operationID)
|
||||||
admission, err := h.admitPrompt(ctx, sessionID, broker, p)
|
admission, err := h.admitPrompt(ctx, sessionID, broker, p)
|
||||||
if admission == chatAdmitRefused {
|
if admission == chatAdmitRefused {
|
||||||
h.forgetOp(sessionID, operationID)
|
h.forgetOp(sessionID, operationID)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if !p.sendAt.IsZero() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
h.broadcastUser(protocol.ChatEventFrame{
|
h.broadcastUser(protocol.ChatEventFrame{
|
||||||
SessionID: sessionID,
|
SessionID: sessionID,
|
||||||
MessageID: p.messageID,
|
MessageID: p.messageID,
|
||||||
|
|||||||
Reference in New Issue
Block a user