From 9a6363b80e1ffa21c2d7d91766bde2003eaa409b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 15:40:34 +0000 Subject: [PATCH] Chat: draw agent follow-ups and automatic continues apart from the operator The server now names a user turn's origin (followup, auto_continue, auto_switch, scheduled) on chat messages, user frames and queued prompts, from the prompt's operation id while it holds the prompt and from its own text prefixes in history read later. Origin is a new field, so older clients keep treating these as ordinary user turns. The app draws an agent follow-up, auto-continue and account-switch prompt as a quiet outlined card on the agent's side with an icon, label and the schedule facts from the preamble; the operator's own scheduled message keeps its bubble with a small Scheduled mark. Find searches the drawn text. Co-Authored-By: Claude Opus 5.5 --- .../chat/conversation/chat_server_queue.dart | 3 +- .../chat/conversation/chat_thread_view.dart | 3 + app/lib/features/chat/domain/chat_find.dart | 6 +- .../chat/domain/chat_prompt_origin.dart | 130 +++++++++++++ .../features/chat/domain/chat_transcript.dart | 1 + .../ui/transcript/chat_automated_prompt.dart | 149 ++++++++++++++ .../chat/ui/transcript/chat_message_view.dart | 73 +++++-- .../chat/domain/chat_prompt_origin_test.dart | 109 +++++++++++ .../chat_automated_prompt_test.dart | 183 ++++++++++++++++++ app/tool/perf/chat_followup_fixture.dart | 82 ++++++++ app/tool/perf/chat_scroll_fixture.dart | 4 + internal/protocol/chat.go | 29 ++- internal/server/chat_auto_switch.go | 3 +- internal/server/chat_commands.go | 2 +- internal/server/chat_hub.go | 15 +- internal/server/chat_prompt_origin.go | 76 ++++++++ internal/server/chat_prompt_origin_test.go | 86 ++++++++ internal/server/chat_queue.go | 1 + internal/server/chat_room.go | 3 +- internal/server/chat_stream.go | 1 + internal/server/chat_tools_followup.go | 5 +- internal/server/chat_tools_followup_test.go | 8 +- 22 files changed, 946 insertions(+), 26 deletions(-) create mode 100644 app/lib/features/chat/domain/chat_prompt_origin.dart create mode 100644 app/lib/features/chat/ui/transcript/chat_automated_prompt.dart create mode 100644 app/test/features/chat/domain/chat_prompt_origin_test.dart create mode 100644 app/test/features/chat/ui/transcript/chat_automated_prompt_test.dart create mode 100644 app/tool/perf/chat_followup_fixture.dart create mode 100644 internal/server/chat_prompt_origin.go create mode 100644 internal/server/chat_prompt_origin_test.go diff --git a/app/lib/features/chat/conversation/chat_server_queue.dart b/app/lib/features/chat/conversation/chat_server_queue.dart index 9e38318d..abcd9434 100644 --- a/app/lib/features/chat/conversation/chat_server_queue.dart +++ b/app/lib/features/chat/conversation/chat_server_queue.dart @@ -11,7 +11,7 @@ class ChatServerQueue { List _prompts = const []; /// The queued prompts, each `{operation_id, message_id, native_message_id, - /// text, client, attachments}` as the server sent it. + /// text, client, attachments, send_at, origin}` as the server sent it. List get prompts => _prompts; bool get isEmpty => _prompts.isEmpty; @@ -45,6 +45,7 @@ class ChatServerQueue { 'operation_id': operation, 'native_message_id': prompt['native_message_id'] ?? '', 'client': prompt['client'], + 'origin': ?prompt['origin'], 'parts': [ {'type': 'text', 'text': '${prompt['text'] ?? ''}'}, for (final attachment in prompt['attachments'] as List? ?? const []) diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 67c75627..248eac05 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -1919,6 +1919,7 @@ class _ChatThreadViewState extends State with ChatFindHost { () => ChatMessageView( row: row, speechScope: widget.sessionId, + scheduleShown: sendAt != null, // The same reader id as the reply's Read aloud button, so the spoken // word is highlighted in this reply's text. textBuilder: (context, text) => ChatMarkdownView( @@ -1983,6 +1984,7 @@ class _ChatThreadViewState extends State with ChatFindHost { row: {'kind': 'user', 'key': message['id'], 'message': message}, textBuilder: chatMarkdownText, images: _images, + scheduleShown: true, footer: [ ChatDeliveryIndicator( state: ChatDelivery.queued, @@ -2005,6 +2007,7 @@ class _ChatThreadViewState extends State with ChatFindHost { }, textBuilder: chatMarkdownText, images: _images, + scheduleShown: true, footer: [ ChatDeliveryIndicator( state: ChatDelivery.failed, diff --git a/app/lib/features/chat/domain/chat_find.dart b/app/lib/features/chat/domain/chat_find.dart index e9054d67..68df3cb0 100644 --- a/app/lib/features/chat/domain/chat_find.dart +++ b/app/lib/features/chat/domain/chat_find.dart @@ -1,4 +1,5 @@ import '../../../core/api_gateway.dart'; +import 'chat_prompt_origin.dart'; /// One piece of transcript text find searches, as the transcript shows it: /// a user turn's text (its text parts joined by line breaks, as its bubble @@ -75,7 +76,10 @@ List chatFindUnits(List rows, List keys) { final kind = row['kind']; if (kind == 'user') { final message = row['message'] is Map ? row['message'] as Map : row; - final text = _textParts(message).join('\n'); + final text = chatPromptDisplayText( + message, + _textParts(message).join('\n'), + ); if (text.trim().isEmpty) continue; final id = '${row['key'] ?? message['id'] ?? ''}'; units.add(ChatFindUnit(index, keys[index], text, [id])); diff --git a/app/lib/features/chat/domain/chat_prompt_origin.dart b/app/lib/features/chat/domain/chat_prompt_origin.dart new file mode 100644 index 00000000..92b38a45 --- /dev/null +++ b/app/lib/features/chat/domain/chat_prompt_origin.dart @@ -0,0 +1,130 @@ +/// Who put a user turn into the chat when the operator did not type it just +/// now. The server names it in `origin` (on a message, a user frame and a +/// queued prompt); an older server's operation ids and the server's own text +/// prefixes say the same. +enum ChatPromptOrigin { + /// The operator's own message, sent now. + operator, + + /// The operator's own message they scheduled to send later. + scheduled, + + /// A follow-up the agent scheduled for itself (schedule_followup). + followup, + + /// The server resending the chat after its usage limit reset. + autoContinue, + + /// The server continuing the chat on another Claude account. + autoSwitch; + + /// Whether the agent or the server, not the operator, sent it. + bool get automated => + this == followup || this == autoContinue || this == autoSwitch; +} + +const _followupTextPrefix = '[Follow-up you scheduled at '; +const _autoSwitchTextPrefix = '[Sent automatically by Pipelines]'; + +/// The origin of a user [message] (a transcript message or a queued prompt). +ChatPromptOrigin chatPromptOrigin(Map message) { + switch ('${message['origin'] ?? ''}') { + case 'followup': + return ChatPromptOrigin.followup; + case 'auto_continue': + return ChatPromptOrigin.autoContinue; + case 'auto_switch': + return ChatPromptOrigin.autoSwitch; + case 'scheduled': + return ChatPromptOrigin.scheduled; + } + final operation = '${message['operation_id'] ?? ''}'; + if (operation.startsWith('followup-')) return ChatPromptOrigin.followup; + if (operation.startsWith('auto-continue-')) { + return ChatPromptOrigin.autoContinue; + } + if (operation.startsWith('auto-switch-')) return ChatPromptOrigin.autoSwitch; + final text = _firstText(message).trimLeft(); + if (text.startsWith(_followupTextPrefix)) return ChatPromptOrigin.followup; + if (text.startsWith(_autoSwitchTextPrefix)) { + return ChatPromptOrigin.autoSwitch; + } + final sendAt = message['send_at']; + if (sendAt is num && sendAt > 0) return ChatPromptOrigin.scheduled; + return ChatPromptOrigin.operator; +} + +/// An automated prompt as the transcript shows it: the server's bracketed +/// preamble becomes the header's facts and [body] is the message itself. +class ChatAutomatedPrompt { + const ChatAutomatedPrompt({ + required this.origin, + required this.body, + this.scheduledAt, + this.condition, + }); + + final ChatPromptOrigin origin; + + /// The prompt's text less the server's preamble. + final String body; + + /// When the agent scheduled a follow-up, from its preamble. + final DateTime? scheduledAt; + + /// What a run-triggered follow-up waits for: "run 42 finishes". + final String? condition; +} + +final RegExp _followupPreamble = RegExp( + r'^\s*\[Follow-up you scheduled at (\S+) with schedule_followup' + r'(?:, for when (run \d+ [^;\]]+?))?' + r'(?:; delivered at \S+ at the latest)?\]\s*', +); + +/// [text] of a prompt from [origin], split into its preamble's facts and body. +ChatAutomatedPrompt chatAutomatedPrompt(ChatPromptOrigin origin, String text) { + if (origin == ChatPromptOrigin.followup) { + final match = _followupPreamble.firstMatch(text); + if (match != null) { + return ChatAutomatedPrompt( + origin: origin, + body: text.substring(match.end), + scheduledAt: DateTime.tryParse(match.group(1)!)?.toLocal(), + condition: match.group(2), + ); + } + } + if (origin == ChatPromptOrigin.autoSwitch) { + final trimmed = text.trimLeft(); + if (trimmed.startsWith(_autoSwitchTextPrefix)) { + return ChatAutomatedPrompt( + origin: origin, + body: trimmed.substring(_autoSwitchTextPrefix.length).trimLeft(), + ); + } + } + return ChatAutomatedPrompt(origin: origin, body: text); +} + +/// The text a user turn's row draws for its joined text parts [text]: an +/// automated prompt's body without the server's preamble, else [text]. +/// Find searches this same string, so its matches line up with the drawing. +String chatPromptDisplayText(Map message, String text) { + final origin = chatPromptOrigin(message); + if (!origin.automated) return text; + return chatAutomatedPrompt(origin, text).body; +} + +String _firstText(Map message) { + final parts = message['parts']; + if (parts is! List) return ''; + for (final part in parts) { + if (part is Map && + (part['type'] == null || part['type'] == 'text') && + part['text'] is String) { + return part['text'] as String; + } + } + return ''; +} diff --git a/app/lib/features/chat/domain/chat_transcript.dart b/app/lib/features/chat/domain/chat_transcript.dart index 83bc75bc..22c5994a 100644 --- a/app/lib/features/chat/domain/chat_transcript.dart +++ b/app/lib/features/chat/domain/chat_transcript.dart @@ -212,6 +212,7 @@ JsonMap applyChatEvent(JsonMap thread, JsonMap frame, {int Function()? now}) { 'created_at': arrived(), 'client': frame['client'], 'operation_id': frame['operation_id'], + 'origin': ?frame['origin'], 'parts': [ {'type': 'text', 'text': text}, ...(frame['attachments'] is List diff --git a/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart b/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart new file mode 100644 index 00000000..0be88512 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart @@ -0,0 +1,149 @@ +import 'package:flutter/material.dart'; + +import '../../conversation/chat_schedule_time.dart'; +import '../../domain/chat_prompt_origin.dart'; +import 'chat_copy_button.dart'; +import 'chat_hover_actions.dart'; + +/// The header words of an automated prompt. +String chatAutomatedPromptLabel(ChatPromptOrigin origin) => switch (origin) { + ChatPromptOrigin.followup => 'Follow-up from agent', + ChatPromptOrigin.autoContinue => 'Auto-continue after limit reset', + ChatPromptOrigin.autoSwitch => 'Continued on another account', + _ => '', +}; + +IconData _icon(ChatPromptOrigin origin) => switch (origin) { + ChatPromptOrigin.followup => Icons.update, + ChatPromptOrigin.autoContinue => Icons.autorenew, + _ => Icons.swap_horiz, +}; + +/// A prompt the agent or the server sent on the operator's behalf. It is not +/// the operator's filled bubble: a quiet outlined card on the agent's side, +/// headed by what sent it (and, for a follow-up, when the agent scheduled it +/// or what run it waited for), with the prompt's [body] beneath. [footer] +/// (its delivery line) and the time sit under the card with its Copy. +class ChatAutomatedPromptCard extends StatelessWidget { + const ChatAutomatedPromptCard({ + super.key, + required this.prompt, + required this.body, + this.footer = const [], + this.timestamp, + }); + + final ChatAutomatedPrompt prompt; + final Widget body; + final List footer; + final Widget? timestamp; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final label = chatAutomatedPromptLabel(prompt.origin); + final detail = switch (prompt) { + ChatAutomatedPrompt(:final condition?) => 'when $condition', + ChatAutomatedPrompt(:final scheduledAt?) => + 'scheduled ${chatScheduleTime(context, scheduledAt)}', + _ => null, + }; + final muted = theme.textTheme.labelMedium?.copyWith( + color: scheme.onSurfaceVariant, + ); + final header = SelectionContainer.disabled( + child: Wrap( + key: const Key('chat-automated-prompt-header'), + spacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Icon(_icon(prompt.origin), size: 16, color: scheme.tertiary), + Text(label, style: muted?.copyWith(fontWeight: FontWeight.w600)), + if (detail != null) Text('· $detail', style: muted), + ], + ), + ); + final card = Material( + key: const Key('chat-automated-prompt'), + color: scheme.surfaceContainerLow, + clipBehavior: Clip.antiAlias, + shape: RoundedRectangleBorder( + borderRadius: const BorderRadius.all(Radius.circular(16)), + side: BorderSide(color: scheme.outlineVariant), + ), + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 8, 14, 10), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + header, + if (prompt.body.trim().isNotEmpty) ...[ + const SizedBox(height: 4), + DefaultTextStyle.merge( + style: theme.textTheme.bodyMedium, + child: body, + ), + ], + ], + ), + ), + ); + final copy = prompt.body.trim().isEmpty + ? null + : ChatHoverReveal(child: ChatCopyButton(text: prompt.body.trim())); + return ChatHoverRegion( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + card, + if (footer.isNotEmpty || timestamp != null || copy != null) + Padding( + padding: const EdgeInsetsDirectional.only(start: 14, top: 2), + child: Wrap( + key: const Key('chat-message-footer'), + spacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [...footer, ?timestamp, ?copy], + ), + ), + ], + ), + ); + } +} + +/// The small "Scheduled" mark under the operator's own message they had +/// scheduled to send later, once it is no longer waiting. +class ChatScheduledMark extends StatelessWidget { + const ChatScheduledMark({super.key}); + + @override + Widget build(BuildContext context) { + final style = Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ); + return SelectionContainer.disabled( + child: Semantics( + container: true, + label: 'Scheduled message', + excludeSemantics: true, + child: Row( + key: const Key('chat-scheduled-mark'), + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.schedule_send, + size: (style?.fontSize ?? 12) + 2, + color: style?.color, + ), + const SizedBox(width: 4), + Text('Scheduled', style: style), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/chat/ui/transcript/chat_message_view.dart b/app/lib/features/chat/ui/transcript/chat_message_view.dart index f821e7a3..464f9298 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -5,6 +5,8 @@ import 'package:flutter/material.dart'; import '../../../../core/api_gateway.dart'; import '../../data/chat_attachment_images.dart'; import 'chat_attachment_gallery.dart'; +import 'chat_automated_prompt.dart'; +import '../../domain/chat_prompt_origin.dart'; import '../../domain/chat_tool_calls.dart'; import '../../domain/chat_transcript.dart'; import 'chat_copy_button.dart'; @@ -31,8 +33,14 @@ class ChatMessageView extends StatelessWidget { this.footer = const [], this.images, this.speechScope = 'chat', + this.scheduleShown = false, }); + /// Whether [footer] already says the message is scheduled (its delivery + /// line reads "Scheduled · sends at …"), so the operator's own scheduled + /// message needs no second mark. + final bool scheduleShown; + final JsonMap row; /// Names the conversation in the reader's message ids, so leaving it can @@ -53,7 +61,17 @@ class ChatMessageView extends StatelessWidget { @override Widget build(BuildContext context) { final user = row['kind'] == 'user'; - final role = user ? 'User' : 'Assistant'; + final origin = user + ? chatPromptOrigin(_userMessage) + : ChatPromptOrigin.operator; + // A prompt the agent or the server sent reads as neither side's turn: a + // quiet card on the agent's side, headed by what sent it. + final automated = origin.automated; + final role = automated + ? chatAutomatedPromptLabel(origin) + : user + ? 'User' + : 'Assistant'; final content = user ? _userParts(context) : _agentParts(context); // A wide window draws an answer's Copy in the gutter left of the reading // column; without room it trails the time in the answer's footer. @@ -78,7 +96,7 @@ class ChatMessageView extends StatelessWidget { padding: const EdgeInsets.symmetric(vertical: 6), child: LayoutBuilder( builder: (context, constraints) => Align( - alignment: user + alignment: user && !automated ? AlignmentDirectional.centerEnd : AlignmentDirectional.centerStart, child: ConstrainedBox( @@ -90,8 +108,10 @@ class ChatMessageView extends StatelessWidget { ? (constraints.maxWidth * 0.85).clamp(0, 560).toDouble() : 720 + gutter, ), - child: user - ? _userTurn(content, body) + child: automated + ? _automatedTurn(origin, content) + : user + ? _userTurn(content, body, origin) : _agentRow( context, content, @@ -115,7 +135,7 @@ class ChatMessageView extends StatelessWidget { /// Attached images sit above the operator's bubble, as their own thumbnails; /// an images-only turn draws no empty bubble. The footer (the delivery line) /// sits under the bubble's trailing corner. - Widget _userTurn(List content, Widget body) { + Widget _userTurn(List content, Widget body, ChatPromptOrigin origin) { final thumbnails = [ for (final part in _partsOf(_userMessage)) if (_isFile(part) && chatPartIsThumbnail(part)) part, @@ -124,7 +144,8 @@ class ChatMessageView extends StatelessWidget { createdAt: chatMessageCreatedAt(_userMessage), ); final hasTimestamp = chatMessageCreatedAt(_userMessage) != null; - if (thumbnails.isEmpty && footer.isEmpty && !hasTimestamp) { + final marked = origin == ChatPromptOrigin.scheduled && !scheduleShown; + if (thumbnails.isEmpty && footer.isEmpty && !hasTimestamp && !marked) { return ChatUserBubble(child: body); } return Column( @@ -141,27 +162,53 @@ class ChatMessageView extends StatelessWidget { if (content.isNotEmpty || thumbnails.isEmpty) ChatUserBubble(child: body), // The delivery line and the time share one line under the bubble. - if (footer.isNotEmpty || hasTimestamp) ...[ + if (footer.isNotEmpty || hasTimestamp || marked) ...[ const SizedBox(height: 2), Wrap( key: const Key('chat-message-footer'), spacing: 8, alignment: WrapAlignment.end, crossAxisAlignment: WrapCrossAlignment.center, - children: [...footer, if (hasTimestamp) timestamp], + children: [ + ...footer, + if (marked) const ChatScheduledMark(), + if (hasTimestamp) timestamp, + ], ), ], ], ); } + /// A prompt the agent or the server sent: its card, with the delivery line + /// and time beneath. + Widget _automatedTurn(ChatPromptOrigin origin, List content) { + final created = chatMessageCreatedAt(_userMessage); + return ChatAutomatedPromptCard( + prompt: chatAutomatedPrompt(origin, _userText(_userMessage)), + body: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: content, + ), + footer: footer, + timestamp: created == null + ? null + : ChatMessageTimestamp(createdAt: created), + ); + } + + /// The user turn's text parts joined as its row draws them. + static String _userText(JsonMap message) => _partsOf(message) + .where((part) => part['type'] == null || part['type'] == 'text') + .map((part) => '${part['text'] ?? ''}') + .join('\n'); + List _userParts(BuildContext context) { final message = _userMessage; final parts = _partsOf(message); - final text = parts - .where((part) => part['type'] == null || part['type'] == 'text') - .map((part) => '${part['text'] ?? ''}') - .join('\n'); + final automated = chatPromptOrigin(message).automated; + final text = chatPromptDisplayText(message, _userText(message)); final widgets = [ if (text.trim().isNotEmpty) ChatLinkText(text), for (final part in parts.where(_isFile)) @@ -173,7 +220,7 @@ class ChatMessageView extends StatelessWidget { _unrecognised(part), ]; final client = '${message['client'] ?? ''}'.trim(); - if (client.isNotEmpty) { + if (client.isNotEmpty && !automated) { widgets.insert(0, Text(client, style: _clientStyle(context))); } return widgets; diff --git a/app/test/features/chat/domain/chat_prompt_origin_test.dart b/app/test/features/chat/domain/chat_prompt_origin_test.dart new file mode 100644 index 00000000..6e0f37d5 --- /dev/null +++ b/app/test/features/chat/domain/chat_prompt_origin_test.dart @@ -0,0 +1,109 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_find.dart'; +import 'package:pipelines_app/features/chat/domain/chat_prompt_origin.dart'; + +Map _user( + String text, [ + Map extra = const {}, +]) => { + 'id': 'u1', + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': text}, + ], + ...extra, +}; + +const _followup = + '[Follow-up you scheduled at 2026-12-03T10:00:00Z with schedule_followup] ' + 'Check the deploy.'; + +void main() { + test('the server origin names who sent a user turn', () { + expect( + chatPromptOrigin(_user('x', {'origin': 'followup'})), + ChatPromptOrigin.followup, + ); + expect( + chatPromptOrigin(_user('continue', {'origin': 'auto_continue'})), + ChatPromptOrigin.autoContinue, + ); + expect( + chatPromptOrigin(_user('x', {'origin': 'auto_switch'})), + ChatPromptOrigin.autoSwitch, + ); + expect( + chatPromptOrigin(_user('x', {'origin': 'scheduled'})), + ChatPromptOrigin.scheduled, + ); + expect(chatPromptOrigin(_user('hello')), ChatPromptOrigin.operator); + }); + + test('an older server is read from operation ids and its own text', () { + expect( + chatPromptOrigin(_user('x', {'operation_id': 'followup-ab12'})), + ChatPromptOrigin.followup, + ); + expect( + chatPromptOrigin(_user('again', {'operation_id': 'auto-continue-m1'})), + ChatPromptOrigin.autoContinue, + ); + expect( + chatPromptOrigin(_user('x', {'operation_id': 'auto-switch-m1'})), + ChatPromptOrigin.autoSwitch, + ); + expect(chatPromptOrigin(_user(_followup)), ChatPromptOrigin.followup); + expect( + chatPromptOrigin( + _user('[Sent automatically by Pipelines] Usage ran out'), + ), + ChatPromptOrigin.autoSwitch, + ); + expect( + chatPromptOrigin(_user('later', {'send_at': 1764756000000})), + ChatPromptOrigin.scheduled, + ); + expect( + chatPromptOrigin(_user('see [Follow-up you scheduled at noon]')), + ChatPromptOrigin.operator, + ); + }); + + test('a follow-up preamble becomes the header facts', () { + final plain = chatAutomatedPrompt(ChatPromptOrigin.followup, _followup); + expect(plain.body, 'Check the deploy.'); + expect(plain.scheduledAt, DateTime.utc(2026, 12, 3, 10).toLocal()); + expect(plain.condition, isNull); + + final run = chatAutomatedPrompt( + ChatPromptOrigin.followup, + '[Follow-up you scheduled at 2026-12-03T10:00:00Z with schedule_followup, ' + 'for when run 42 needs the operator or finishes; delivered at ' + '2026-12-04T10:00:00Z at the latest] Review it.\n\n' + '[Pipelines: run 42 is now succeeded; read it with pipelines inspect 42.]', + ); + expect(run.condition, 'run 42 needs the operator or finishes'); + expect(run.body, startsWith('Review it.\n\n[Pipelines: run 42')); + + final unknown = chatAutomatedPrompt(ChatPromptOrigin.followup, 'raw'); + expect(unknown.body, 'raw'); + expect( + chatAutomatedPrompt( + ChatPromptOrigin.autoSwitch, + '[Sent automatically by Pipelines] Usage ran out.', + ).body, + 'Usage ran out.', + ); + }); + + test('find searches the text a follow-up draws', () { + final units = chatFindUnits( + [ + {'kind': 'user', 'key': 'u1', 'message': _user(_followup)}, + {'kind': 'user', 'key': 'u2', 'message': _user('mine')}, + ], + ['u1', 'u2'], + ); + expect(units.map((unit) => unit.text), ['Check the deploy.', 'mine']); + }); +} diff --git a/app/test/features/chat/ui/transcript/chat_automated_prompt_test.dart b/app/test/features/chat/ui/transcript/chat_automated_prompt_test.dart new file mode 100644 index 00000000..df3677be --- /dev/null +++ b/app/test/features/chat/ui/transcript/chat_automated_prompt_test.dart @@ -0,0 +1,183 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_bubble.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart'; + +JsonMap _row(Map message) => { + 'kind': 'user', + 'key': message['id'], + 'message': message, +}; + +JsonMap _message(String text, [Map extra = const {}]) => { + 'id': 'u1', + 'role': 'user', + 'created_at': DateTime.utc(2026, 12, 3, 11).millisecondsSinceEpoch, + 'client': 'Agent follow-up', + 'parts': [ + {'type': 'text', 'text': text}, + ], + ...extra, +}; + +const _followup = + '[Follow-up you scheduled at 2026-12-03T10:00:00Z with schedule_followup] ' + 'Check the deploy finished.'; + +Widget _host( + JsonMap row, { + Brightness brightness = Brightness.light, + bool scheduleShown = false, +}) => MaterialApp( + theme: ThemeData(brightness: brightness), + home: Scaffold( + body: ListView( + children: [ChatMessageView(row: row, scheduleShown: scheduleShown)], + ), + ), +); + +void _wide(WidgetTester tester) { + tester.view.physicalSize = const Size(1000, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); +} + +void main() { + for (final brightness in Brightness.values) { + testWidgets('an agent follow-up is a quiet card on the agent side ' + '(${brightness.name})', (tester) async { + _wide(tester); + await tester.pumpWidget( + _host( + _row(_message(_followup, {'origin': 'followup'})), + brightness: brightness, + ), + ); + expect(find.byType(ChatUserBubble), findsNothing); + final card = find.byKey(const Key('chat-automated-prompt')); + expect(card, findsOneWidget); + expect(find.text('Follow-up from agent'), findsOneWidget); + expect(find.textContaining('· scheduled '), findsOneWidget); + expect(find.byIcon(Icons.update), findsOneWidget); + // The preamble is header facts, not body text; the sender label is not + // repeated inside the card. + expect(find.text('Check the deploy finished.'), findsOneWidget); + expect(find.textContaining('[Follow-up'), findsNothing); + expect(find.text('Agent follow-up'), findsNothing); + // Start-aligned, not on the operator's trailing side. + expect(tester.getTopLeft(card).dx, lessThan(40)); + final material = tester.widget(card); + final scheme = Theme.of(tester.element(card)).colorScheme; + expect(material.color, scheme.surfaceContainerLow); + expect( + (material.shape! as RoundedRectangleBorder).side.color, + scheme.outlineVariant, + ); + expect( + find.bySemanticsLabel('Follow-up from agent message'), + findsOneWidget, + ); + }); + } + + testWidgets('the follow-up body stays selectable and copies without the ' + 'preamble', (tester) async { + _wide(tester); + String? copied; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied = (call.arguments as Map)['text'] as String?; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + await tester.pumpWidget( + _host(_row(_message(_followup, {'operation_id': 'followup-ab'}))), + ); + expect( + find.widgetWithText(SelectableText, 'Check the deploy finished.'), + findsOneWidget, + ); + await tester.tap(find.byKey(const Key('chat-message-copy'))); + await tester.pump(); + expect(copied, 'Check the deploy finished.'); + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('auto-continue and auto-switch name the server', (tester) async { + _wide(tester); + await tester.pumpWidget( + _host(_row(_message('continue', {'origin': 'auto_continue'}))), + ); + expect(find.text('Auto-continue after limit reset'), findsOneWidget); + expect(find.text('continue'), findsOneWidget); + await tester.pumpWidget( + _host( + _row( + _message('[Sent automatically by Pipelines] Usage ran out on a.', { + 'operation_id': 'auto-switch-m1', + }), + ), + ), + ); + expect(find.text('Continued on another account'), findsOneWidget); + expect(find.text('Usage ran out on a.'), findsOneWidget); + }); + + testWidgets('a run follow-up says what it waited for', (tester) async { + _wide(tester); + await tester.pumpWidget( + _host( + _row( + _message( + '[Follow-up you scheduled at 2026-12-03T10:00:00Z with ' + 'schedule_followup, for when run 42 finishes; delivered at ' + '2026-12-04T10:00:00Z at the latest] Review it.', + ), + ), + ), + ); + expect(find.text('· when run 42 finishes'), findsOneWidget); + expect(find.text('Review it.'), findsOneWidget); + }); + + testWidgets("the operator's scheduled message keeps its bubble with a mark", ( + tester, + ) async { + _wide(tester); + final row = _row( + _message('send this later', {'origin': 'scheduled', 'client': 'Laptop'}), + ); + await tester.pumpWidget(_host(row)); + expect(find.byType(ChatUserBubble), findsOneWidget); + expect(find.byKey(const Key('chat-automated-prompt')), findsNothing); + expect(find.byKey(const Key('chat-scheduled-mark')), findsOneWidget); + expect(find.text('Laptop'), findsOneWidget); + // While the delivery line already reads "Scheduled · sends at", no mark. + await tester.pumpWidget(_host(row, scheduleShown: true)); + expect(find.byKey(const Key('chat-scheduled-mark')), findsNothing); + }); + + testWidgets('an ordinary message is unchanged', (tester) async { + _wide(tester); + await tester.pumpWidget( + _host(_row(_message('hello', {'client': 'Phone'}))), + ); + expect(find.byType(ChatUserBubble), findsOneWidget); + expect(find.byKey(const Key('chat-scheduled-mark')), findsNothing); + expect(find.byKey(const Key('chat-automated-prompt')), findsNothing); + expect(find.bySemanticsLabel('User message'), findsOneWidget); + }); +} diff --git a/app/tool/perf/chat_followup_fixture.dart b/app/tool/perf/chat_followup_fixture.dart new file mode 100644 index 00000000..812bb7ee --- /dev/null +++ b/app/tool/perf/chat_followup_fixture.dart @@ -0,0 +1,82 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// `?followups=1`: the prompts the operator did not type just now, between +/// ordinary turns: an agent's follow-up (timed and run-triggered), the +/// server's auto-continue and account switch, and the operator's own +/// scheduled message. +List chatFollowupMessages(String chat) { + var minute = 0; + int at() => DateTime.utc(2026, 12, 3, 9, minute += 7).millisecondsSinceEpoch; + JsonMap user(String id, String text, [JsonMap extra = const {}]) => { + 'id': '$chat-fu-$id', + 'role': 'user', + 'created_at': at(), + 'parts': [ + {'type': 'text', 'text': text}, + ], + ...extra, + }; + JsonMap reply(String id, String text) => { + 'id': '$chat-fu-$id', + 'role': 'assistant', + 'created_at': at(), + 'parts': [ + {'type': 'text', 'text': text}, + ], + }; + return [ + user('q', 'Deploy the release and keep an eye on it.', { + 'client': 'Laptop', + }), + reply( + 'a1', + 'Started run 42. I scheduled a follow-up to check it in 30 minutes.', + ), + user( + 'f1', + '[Follow-up you scheduled at 2026-12-03T09:14:00Z with ' + 'schedule_followup] Check whether run 42 finished and report the ' + 'deploy status.', + { + 'client': 'Agent follow-up', + 'operation_id': 'followup-1a2b', + 'origin': 'followup', + }, + ), + reply('a2', 'Run 42 finished; the deploy is healthy.'), + user( + 'f2', + '[Follow-up you scheduled at 2026-12-03T09:28:00Z with ' + 'schedule_followup, for when run 43 finishes; delivered at ' + '2026-12-04T09:28:00Z at the latest] Review the canary results.' + '\n\n[Pipelines: run 43 is now succeeded; read it with pipelines ' + 'inspect 43.]', + {'client': 'Agent follow-up', 'origin': 'followup'}, + ), + reply('a3', 'You\'ve hit your 5-hour limit · resets 2pm'), + user('c1', 'Review the canary results.', { + 'client': 'Pipelines (automatic)', + 'operation_id': 'auto-continue-a3', + 'origin': 'auto_continue', + }), + reply('a4', 'The canary results look good.'), + user( + 's1', + '[Sent automatically by Pipelines] Usage ran out on ada@example.com, ' + 'so Pipelines switched this chat to bob@example.com. Before ' + 'continuing: briefly check your progress against my original ' + 'request and your plan.', + { + 'client': 'Pipelines (automatic)', + 'operation_id': 'auto-switch-a4', + 'origin': 'auto_switch', + }, + ), + reply('a5', 'Still on track; continuing.'), + user('l1', 'Summarise the release for the team channel.', { + 'client': 'Laptop', + 'origin': 'scheduled', + }), + reply('a6', 'Here is the summary for the team channel.'), + ]; +} diff --git a/app/tool/perf/chat_scroll_fixture.dart b/app/tool/perf/chat_scroll_fixture.dart index 1df0ea92..feae82c7 100644 --- a/app/tool/perf/chat_scroll_fixture.dart +++ b/app/tool/perf/chat_scroll_fixture.dart @@ -20,9 +20,12 @@ // `?tables=1` answers carry a wrapping table, one with a long token and // one too wide for a phone (it scrolls sideways); // `?timestamps=1` messages carry recorded times over two calendar days. +// `?followups=1` appends agent follow-ups, auto-continue/switch prompts and +// a scheduled operator message (chat_followup_fixture.dart). import 'dart:async'; import 'package:pipelines_app/core/api_gateway.dart'; +import 'chat_followup_fixture.dart'; Map _params = const {}; @@ -275,6 +278,7 @@ JsonMap chatScrollHistory(String sessionId, int index, String cursor) { for (var i = 0; i < messages.length; i++) _timed(messages[i], i, messages.length), if (_bgwork) ..._backgroundWork(sessionId), + if (_params['followups'] == '1') ...chatFollowupMessages(sessionId), ], 'next_cursor': _older ? 'older' : '', 'has_more': _older, diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index 9f43b1e7..8e718b6d 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -271,6 +271,24 @@ const ( ChatMessageKindNotice = "notice" ) +// ChatMessage.Origin (and ChatEventFrame.Origin, ChatQueuedPrompt.Origin) +// values: who put a user turn into the chat when it was not the operator +// typing it now. Empty is the operator's own message. Origin is separate from +// Kind, so a client that ignores it still treats the turn as an ordinary user +// turn. +// +// ChatOriginFollowup is a follow-up the agent scheduled for itself +// (schedule_followup). ChatOriginAutoContinue is the server resending a chat +// after its usage limit reset; ChatOriginAutoSwitch is the server continuing +// a chat on another Claude account. ChatOriginScheduled is the operator's own +// message they scheduled to send later. +const ( + ChatOriginFollowup = "followup" + ChatOriginAutoContinue = "auto_continue" + ChatOriginAutoSwitch = "auto_switch" + ChatOriginScheduled = "scheduled" +) + // ChatCommand is one slash command or skill the chat's harness session offers. // Name is the word after the slash; the operator sends "/ " as an // ordinary prompt and the harness expands it. ArgumentHint is the harness's @@ -594,6 +612,8 @@ type ChatQueuedPrompt struct { // SendAt (epoch milliseconds) is set on a scheduled prompt: the earliest // time the server will deliver it. SendAt int64 `json:"send_at,omitempty"` + // Origin is the ChatMessage.Origin the prompt is delivered with. + Origin string `json:"origin,omitempty"` } // ChatQueueFrame is a session's current server-side prompt queue, in delivery @@ -659,8 +679,11 @@ type ChatMessage struct { OperationID string `json:"operation_id,omitempty"` // Kind is empty for an ordinary user or assistant turn, or one of the // ChatMessageKind values for content the harness injected. - Kind string `json:"kind,omitempty"` - Parts []ChatPart `json:"parts"` + Kind string `json:"kind,omitempty"` + // Origin is one of the ChatOrigin values on a user turn the operator did + // not type just now; empty otherwise, or when the server no longer knows. + Origin string `json:"origin,omitempty"` + Parts []ChatPart `json:"parts"` } // ChatDeltaPartID is the stable part id an incremental text or reasoning delta @@ -764,6 +787,8 @@ type ChatEventFrame struct { // MessageKind is the ChatMessage.Kind of the message a text frame starts, // so a live agent report or notice is never drawn as an answer or a prompt. MessageKind string `json:"message_kind,omitempty"` + // Origin is the ChatMessage.Origin of a user frame's message. + Origin string `json:"origin,omitempty"` // Seq numbers a text or reasoning delta within its session, increasing; // see ChatHistoryPage.LiveSeq. Zero when the harness does not number them. Seq int64 `json:"seq,omitempty"` diff --git a/internal/server/chat_auto_switch.go b/internal/server/chat_auto_switch.go index c9ec7048..ba2d3329 100644 --- a/internal/server/chat_auto_switch.go +++ b/internal/server/chat_auto_switch.go @@ -100,7 +100,7 @@ func chatAutoSwitchText(from, to string) string { if from == "" { from = "the previous account" } - return "[Sent automatically by Pipelines] Usage ran out on " + from + ", so Pipelines switched this chat to " + to + ". " + + return chatAutoSwitchTextPrefix + " Usage ran out on " + from + ", so Pipelines switched this chat to " + to + ". " + "Before continuing: you already used up a full usage window on this task. Briefly check your progress against my original request and your plan, " + "and make sure you are on track, not going in circles or off the rails. If something looks wrong, stop and ask me; otherwise continue where you left off." } @@ -274,6 +274,7 @@ func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sess Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text}, Client: chatAutoSwitchClient, OperationID: operationID, + Origin: chatPromptOrigin(operationID, false), }, "") return nil } diff --git a/internal/server/chat_commands.go b/internal/server/chat_commands.go index 64c3c033..510ba1b1 100644 --- a/internal/server/chat_commands.go +++ b/internal/server/chat_commands.go @@ -34,7 +34,7 @@ func addChatHistory(ctx context.Context, response *protocol.Message, broker chat if err != nil { return err } - page.Messages = hub.reconcileHistory(query.SessionID, page.Messages) + page.Messages = markChatOrigins(hub.reconcileHistory(query.SessionID, page.Messages)) response.ChatMessages = page.Messages // legacy peers keep working. response.ChatHistory = &page // The session's recorded per-turn changes ride with its history, so the diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index a87cf318..b5dca27c 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -124,9 +124,11 @@ type chatMessage struct { operationID string // kind is the ChatMessage.Kind of harness-injected content (an agent // report or a notice); empty for an ordinary turn. - kind string - order []string - parts map[string]*chatPart + kind string + // origin is the ChatMessage.Origin of a user turn. + origin string + order []string + parts map[string]*chatPart } type chatTurn struct { @@ -302,6 +304,9 @@ func (h *chatHub) applyLocked(frame protocol.ChatEventFrame) { if message.operationID == "" && frame.Kind == protocol.ChatEventUser { message.operationID = frame.OperationID } + if message.origin == "" && frame.Kind == protocol.ChatEventUser { + message.origin = frame.Origin + } if message.kind == "" && frame.MessageKind != "" && frame.Kind != protocol.ChatEventUser { message.kind = frame.MessageKind } @@ -635,6 +640,7 @@ func (h *chatHub) snapshot(sessionID string) []protocol.ChatMessage { out.Client = message.client out.OperationID = message.operationID out.Kind = message.kind + out.Origin = message.origin for _, partID := range message.order { if part, ok := message.parts[partID]; ok { piece := part.part @@ -674,6 +680,9 @@ func (h *chatHub) reconcileHistory(sessionID string, messages []protocol.ChatMes if out[i].Client == "" { out[i].Client = live.client } + if out[i].Origin == "" { + out[i].Origin = live.origin + } } } return out diff --git a/internal/server/chat_prompt_origin.go b/internal/server/chat_prompt_origin.go new file mode 100644 index 00000000..6beab1ca --- /dev/null +++ b/internal/server/chat_prompt_origin.go @@ -0,0 +1,76 @@ +package server + +import ( + "strings" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// A user turn the operator did not type just now carries an origin +// (protocol.ChatOrigin*), so clients can draw an agent's follow-up or the +// server's automatic continue apart from the operator's own messages. While +// the server holds the prompt (queued, or retained after delivery) the origin +// comes from its operation id; a history page read later, after the server +// forgot the prompt, recognises the server-written text prefixes instead. + +const ( + // chatFollowupTextPrefix starts the text of an agent's follow-up. + chatFollowupTextPrefix = "[Follow-up you scheduled at " + // chatAutoSwitchTextPrefix starts the text of the auto-switch continue. + chatAutoSwitchTextPrefix = "[Sent automatically by Pipelines]" +) + +// chatPromptOrigin is the origin of a prompt sent under operationID; +// scheduled says it waits for a send_at (the operator's "send later"). +func chatPromptOrigin(operationID string, scheduled bool) string { + switch { + case strings.HasPrefix(operationID, chatFollowupPrefix): + return protocol.ChatOriginFollowup + case strings.HasPrefix(operationID, chatAutoContinuePrefix): + return protocol.ChatOriginAutoContinue + case strings.HasPrefix(operationID, chatAutoSwitchPrefix): + return protocol.ChatOriginAutoSwitch + case scheduled: + return protocol.ChatOriginScheduled + } + return "" +} + +// chatTextOrigin is the origin a user turn's text shows on its own: only the +// server's own prefixes are recognised, so an operator's message never is. +func chatTextOrigin(message protocol.ChatMessage) string { + for _, part := range message.Parts { + if part.Type != protocol.ChatPartText && part.Type != "" { + continue + } + switch text := strings.TrimSpace(part.Text); { + case strings.HasPrefix(text, chatFollowupTextPrefix): + return protocol.ChatOriginFollowup + case strings.HasPrefix(text, chatAutoSwitchTextPrefix): + return protocol.ChatOriginAutoSwitch + } + return "" + } + return "" +} + +// markChatOrigins gives each user turn of a history page that has no origin +// the one its text shows. The page is copied before a change, since a +// harness may keep the slice it returned. +func markChatOrigins(messages []protocol.ChatMessage) []protocol.ChatMessage { + out := messages + for i := range messages { + if messages[i].Role != protocol.ChatRoleUser || messages[i].Origin != "" { + continue + } + origin := chatTextOrigin(messages[i]) + if origin == "" { + continue + } + if &out[0] == &messages[0] { + out = append([]protocol.ChatMessage(nil), messages...) + } + out[i].Origin = origin + } + return out +} diff --git a/internal/server/chat_prompt_origin_test.go b/internal/server/chat_prompt_origin_test.go new file mode 100644 index 00000000..3c1ff5e2 --- /dev/null +++ b/internal/server/chat_prompt_origin_test.go @@ -0,0 +1,86 @@ +package server + +import ( + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestChatPromptOriginFromOperationID(t *testing.T) { + for _, tc := range []struct { + operationID string + scheduled bool + want string + }{ + {chatFollowupPrefix + "abc", true, protocol.ChatOriginFollowup}, + {chatRunFollowupPrefix + "7-finished-abc", true, protocol.ChatOriginFollowup}, + {chatAutoContinuePrefix + "msg_1", true, protocol.ChatOriginAutoContinue}, + {chatAutoSwitchPrefix + "msg_1", false, protocol.ChatOriginAutoSwitch}, + {"op-1", true, protocol.ChatOriginScheduled}, + {"op-1", false, ""}, + } { + if got := chatPromptOrigin(tc.operationID, tc.scheduled); got != tc.want { + t.Errorf("chatPromptOrigin(%q, %v) = %q, want %q", tc.operationID, tc.scheduled, got, tc.want) + } + } +} + +// A history page read after the server forgot the prompt still marks the +// server's own prompts by their text, and never the operator's or an +// assistant's message; the harness's slice is not changed. +func TestMarkChatOriginsRecognisesServerText(t *testing.T) { + text := func(role, s string) protocol.ChatMessage { + return protocol.ChatMessage{Role: role, Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: s}}} + } + page := []protocol.ChatMessage{ + text(protocol.ChatRoleUser, "[Follow-up you scheduled at 2026-12-03T10:00:00Z with schedule_followup] check the run"), + text(protocol.ChatRoleUser, chatAutoSwitchText("a@example.com", "b@example.com")), + text(protocol.ChatRoleUser, "please look at [Follow-up you scheduled at noon]"), + text(protocol.ChatRoleAssistant, "[Follow-up you scheduled at 2026-12-03T10:00:00Z with schedule_followup] echo"), + {Role: protocol.ChatRoleUser, Origin: protocol.ChatOriginScheduled, Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: chatAutoSwitchTextPrefix}}}, + } + got := markChatOrigins(page) + want := []string{protocol.ChatOriginFollowup, protocol.ChatOriginAutoSwitch, "", "", protocol.ChatOriginScheduled} + for i, origin := range want { + if got[i].Origin != origin { + t.Errorf("message %d origin = %q, want %q", i, got[i].Origin, origin) + } + } + if page[0].Origin != "" { + t.Fatalf("the harness's page was changed in place") + } +} + +// The hub keeps a live user turn's origin, so a resume snapshot and a history +// page mapped to that turn carry it. +func TestChatHubKeepsUserOrigin(t *testing.T) { + hub := newChatHub() + hub.apply(protocol.ChatEventFrame{ + SessionID: "ses_1", MessageID: "msg_f", Kind: protocol.ChatEventUser, + Client: chatFollowupClient, OperationID: chatFollowupPrefix + "abc", Origin: protocol.ChatOriginFollowup, + Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: "later"}, + }) + snapshot := hub.snapshot("ses_1") + if len(snapshot) != 1 || snapshot[0].Origin != protocol.ChatOriginFollowup { + t.Fatalf("snapshot = %+v", snapshot) + } + got := hub.reconcileHistory("ses_1", []protocol.ChatMessage{{ID: "msg_f", Role: protocol.ChatRoleUser}}) + if got[0].Origin != protocol.ChatOriginFollowup { + t.Fatalf("history origin = %+v", got[0]) + } +} + +// A queued prompt tells clients its origin. +func TestQueuedPromptWireOrigin(t *testing.T) { + later := time.Now().Add(time.Hour) + if got := (&chatQueuedPrompt{operationID: chatFollowupPrefix + "x", sendAt: later}).wire().Origin; got != protocol.ChatOriginFollowup { + t.Fatalf("follow-up origin = %q", got) + } + if got := (&chatQueuedPrompt{operationID: "op-1", sendAt: later}).wire().Origin; got != protocol.ChatOriginScheduled { + t.Fatalf("send-later origin = %q", got) + } + if got := (&chatQueuedPrompt{operationID: "op-1"}).wire().Origin; got != "" { + t.Fatalf("queued operator prompt origin = %q", got) + } +} diff --git a/internal/server/chat_queue.go b/internal/server/chat_queue.go index f750bed2..700724b5 100644 --- a/internal/server/chat_queue.go +++ b/internal/server/chat_queue.go @@ -332,6 +332,7 @@ func (p *chatQueuedPrompt) wire() protocol.ChatQueuedPrompt { Text: p.text, Client: p.client, Attachments: p.parts, + Origin: chatPromptOrigin(p.operationID, !p.sendAt.IsZero()), } if !p.queuedAt.IsZero() { out.QueuedAt = p.queuedAt.UnixMilli() diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 6a514a94..11353806 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -236,7 +236,7 @@ func joinChatDeltas(last, next protocol.Message) (protocol.Message, bool) { func plainChatDelta(f *protocol.ChatEventFrame) bool { return (f.Kind == protocol.ChatEventText || f.Kind == protocol.ChatEventReasoning) && f.Delta != "" && f.Part != nil && f.Part.Text == "" && f.Step == nil && f.Usage == nil && f.Shell == nil && f.Form == nil && f.Compaction == nil && - len(f.Attachments) == 0 && f.Client == "" && f.OperationID == "" + len(f.Attachments) == 0 && f.Client == "" && f.OperationID == "" && f.Origin == "" } // utf16Len is the length of s in UTF-16 code units, the unit a Dart client @@ -1227,6 +1227,7 @@ func (h *chatHub) publishDelivery(room *chatRoom, p *chatQueuedPrompt) { Attachments: p.parts, Client: p.client, OperationID: p.operationID, + Origin: chatPromptOrigin(p.operationID, !p.sendAt.IsZero()), } h.mu.Lock() turn := h.turnLocked(room.sessionID) diff --git a/internal/server/chat_stream.go b/internal/server/chat_stream.go index 90629a9a..6122cd8e 100644 --- a/internal/server/chat_stream.go +++ b/internal/server/chat_stream.go @@ -139,6 +139,7 @@ func admitChatPrompt(ctx context.Context, request protocol.Message, broker chatB queuedPrompt.sendAt = at } } + userFrame.Origin = chatPromptOrigin(operationID, !queuedPrompt.sendAt.IsZero()) // Claim the operation before admission so a concurrent retry of the same // prompt is acknowledged rather than delivered twice. hub.rememberOp(sessionID, operationID) diff --git a/internal/server/chat_tools_followup.go b/internal/server/chat_tools_followup.go index 39a40f1f..d79ee8bf 100644 --- a/internal/server/chat_tools_followup.go +++ b/internal/server/chat_tools_followup.go @@ -123,10 +123,10 @@ func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, me var token [8]byte _, _ = rand.Read(token[:]) operationID := chatFollowupPrefix + hex.EncodeToString(token[:]) - text := fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup] %s", now.UTC().Format(time.RFC3339), message) + text := fmt.Sprintf(chatFollowupTextPrefix+"%s with schedule_followup] %s", now.UTC().Format(time.RFC3339), message) if run != nil { operationID = fmt.Sprintf("%s%d-%s-%s", chatRunFollowupPrefix, run.ID, on, hex.EncodeToString(token[:])) - text = fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup, for when run %d %s; delivered at %s at the latest] %s", + text = fmt.Sprintf(chatFollowupTextPrefix+"%s with schedule_followup, for when run %d %s; delivered at %s at the latest] %s", now.UTC().Format(time.RFC3339), run.ID, runFollowupCondition(on), sendAt.UTC().Format(time.RFC3339), message) } if err := s.hub.queueFollowup(ctx, s.broker, sessionID, operationID, text, sendAt); err != nil { @@ -417,6 +417,7 @@ func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionI Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text}, Client: chatFollowupClient, OperationID: operationID, + Origin: protocol.ChatOriginFollowup, }, "") return nil } diff --git a/internal/server/chat_tools_followup_test.go b/internal/server/chat_tools_followup_test.go index b578d0cd..0a9069b3 100644 --- a/internal/server/chat_tools_followup_test.go +++ b/internal/server/chat_tools_followup_test.go @@ -58,9 +58,15 @@ func TestScheduleFollowupQueuesWithoutBlockingTheOperator(t *testing.T) { t.Fatalf("a fourth pending follow-up must be refused: %v", result) } writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatUnqueue, ID: "rm", ChatUnqueue: &protocol.ChatUnqueueRequest{SessionID: "ses_1", OperationID: rows[0].OperationID}}) - if removed := readUntil(t, server.ctx, conn, protocol.ChatUnqueue); removed.ChatQueue == nil || removed.ChatQueue.Removed != rows[0].OperationID || len(removed.ChatQueue.Prompts) != 2 { + removed := readUntil(t, server.ctx, conn, protocol.ChatUnqueue) + if removed.ChatQueue == nil || removed.ChatQueue.Removed != rows[0].OperationID || len(removed.ChatQueue.Prompts) != 2 { t.Fatalf("the operator removes a follow-up: %+v", removed.ChatQueue) } + for _, prompt := range removed.ChatQueue.Prompts { + if prompt.Origin != protocol.ChatOriginFollowup { + t.Fatalf("a queued follow-up is marked as the agent's: %+v", prompt) + } + } if n := broker.promptCount(); n != 1 { t.Fatalf("no follow-up is delivered before its time: %v", broker.promptTexts()) }