Files
pipelines/app/tool/perf/chat_scroll_fixture.dart
T
alan 9a6363b80e 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 <noreply@anthropic.com>
2026-12-03 15:40:34 +00:00

356 lines
12 KiB
Dart

// Transcript variety for chat scroll captures over the full-app fixture's
// `?chats=N` sessions (tool/perf/perf_fixture.dart). Every option defaults to
// off, so the bench's short markdown transcripts are unchanged.
//
// `?msgs=60,3` messages per chat, by chat index (the last count repeats);
// `?rich=1` answers carry a wide code line and a wide table, operator
// turns an image, and every fifth turn an agent report and a
// harness notice;
// `?older=1` the first page reports more history; Load older adds 20
// earlier messages;
// `?live=N` 3 s after a chat subscribes, N text deltas stream into a
// new reply, one every 60 ms;
// `?tasks=N` the history ends with N consecutive background-task notices
// in the server's wording (every third one failed);
// `?bgwork=1` the history ends with an agent's background work between two
// answers: tool-only turns ("Used 9 tools", "Ran 1 command",
// one with a failed command) split by background-task notices;
// `?links=1` answers and operator turns carry a markdown link, an
// autolink, a bare URL and URLs inside code (linked too);
// `?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<String, String> _params = const {};
void configureChatScrollFixture(Map<String, String> params) => _params = params;
bool get _rich => _params['rich'] == '1';
/// `?turnactivity=1`: replies carry thinking and a tool call, so the turn
/// activity row ("Thought … · 1 tool call") is shown.
bool get _activity => _params['turnactivity'] == '1';
bool get _links => _params['links'] == '1';
bool get _older => _params['older'] == '1';
int get _live => int.tryParse(_params['live'] ?? '') ?? 0;
int get _tasks => int.tryParse(_params['tasks'] ?? '') ?? 0;
bool get _bgwork => _params['bgwork'] == '1';
/// `?bgwork=1`: a reply, then tool-only turns split by task notices, then a
/// closing reply, the shape a long background session records.
List<JsonMap> _backgroundWork(String chat) {
var minute = 0;
int at() => DateTime.utc(2026, 11, 5, 10, minute++).millisecondsSinceEpoch;
JsonMap tool(String id, String name, {bool failed = false}) => {
'type': 'tool',
'id': id,
'name': name,
'state': {'status': failed ? 'error' : 'completed', 'title': name},
};
JsonMap turn(String id, List<JsonMap> parts) => {
'id': '$chat-bg-$id',
'role': 'assistant',
'created_at': at(),
'parts': parts,
};
JsonMap notice(String id, String summary) => {
..._taskNotice(chat, 0),
'id': '$chat-bg-task-$id',
'created_at': at(),
'parts': [
{'type': 'text', 'text': 'Background task finished: $summary'},
],
};
return [
{
'id': '$chat-bg-q',
'role': 'user',
'created_at': at(),
'parts': [
{'type': 'text', 'text': 'Run the checks in the background.'},
],
},
turn('a0', [
{'type': 'text', 'text': 'Starting the checks in the background.'},
]),
notice('1', 'Background command "Unit tests" completed (exit code 0)'),
turn('t1', [for (var i = 0; i < 9; i++) tool('t1-$i', 'read')]),
notice('2', 'Agent "Review part 1" finished'),
notice('3', 'Agent "Review part 2" finished'),
turn('t2', [tool('t2-0', 'bash')]),
notice('4', 'Background command "Lint" completed (exit code 0)'),
turn('t3', [tool('t3-0', 'bash')]),
notice('5', 'Background command "Build" completed (exit code 0)'),
notice('6', 'Background command "Docs" completed (exit code 0)'),
turn('t4', [
for (var i = 0; i < 4; i++) tool('t4-$i', 'bash', failed: i == 2),
]),
notice('7', 'Background command "Format" completed (exit code 0)'),
turn('t5', [tool('t5-0', 'bash')]),
notice('8', 'Background command "Smoke test" completed (exit code 0)'),
turn('a1', [
{'type': 'text', 'text': 'All the background checks are done.'},
]),
];
}
bool get _timestamps => _params['timestamps'] == '1';
/// Background task [i]'s notice, as the server records a Claude Code task
/// notification.
JsonMap _taskNotice(String chat, int i) {
final failed = i % 3 == 2;
final summary = i.isEven
? 'Background command "Build step $i" '
'${failed ? 'failed (exit code 1)' : 'completed (exit code 0)'}'
: 'Agent "Review part $i" ${failed ? 'failed' : 'finished'}';
return {
'id': '$chat-task-$i',
'role': 'assistant',
'kind': 'notice',
'parts': [
{
'type': 'text',
'text': 'Background task ${failed ? 'failed' : 'finished'}: $summary',
},
],
};
}
/// The message count for chat [index] (`perf-chat-<index>`).
int chatScrollMessageCount(int index) {
final counts = [
for (final value in (_params['msgs'] ?? '').split(','))
?int.tryParse(value.trim()),
];
if (counts.isEmpty) return 20;
return counts[index < counts.length ? index : counts.length - 1];
}
/// A 96x64 PNG, so an operator turn draws an image thumbnail.
const _png =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABACAIAAABqVuVZAAAAeklE'
'QVR4nO3QMQ0AIADAMOQgEYnIwgEPBzuaTMDSMdfWpfH9IB4gQIAAAQoHCBAgQIDCAQIECBCg'
'cIAAAQIEKBwgQIAAAQoHCBAgQIDCAQIECBCgcIAAAQIEKBwgQIAAAQoHCBAgQIDCAQIECBCg'
'cIAAAQIEKBwgQG8du9DB8GFqxbUAAAAASUVORK5CYII=';
String _answer(int i) {
final wide = _rich
? '\n```sh\n${List.filled(14, 'go test ./internal/server/... -run Test$i').join(' && ')}\n```\n\n'
'| ${[for (var c = 0; c < 14; c++) 'Column $c'].join(' | ')} |\n'
'| ${List.filled(14, '---').join(' | ')} |\n'
'| ${[for (var c = 0; c < 14; c++) 'value $i.$c'].join(' | ')} |\n\n'
: '';
return '## Answer $i\n\nSome **bold** text with `code`.\n\n'
'```dart\n${List.generate(8, (l) => 'final v$l = $i * $l;').join('\n')}'
'\n```\n$wide${_tables ? _answerTables : ''}\n- one\n- two\n'
'${_links ? _answerLinks : ''}';
}
bool get _tables => _params['tables'] == '1';
/// `?tables=1`: a table whose prose wraps to fit, one with a long unbroken
/// token, and one whose words cannot fit a phone side by side.
const _answerTables =
'\n| Column | Description | Status |\n| --- | --- | --- |\n'
'| Parser | Reads the markdown source and keeps each table cell as '
'written, so wrapping happens only between words | Done |\n'
'| Renderer | Lays the cells out at the transcript width | Review |\n\n'
'| Commit | Link |\n| --- | --- |\n'
'| 4f1c2a9 | https://example.com/pipelines/commit/'
'4f1c2a9e0b7d3c6f5a8e1d2c3b4a5f6e7d8c9b0a |\n\n'
'| Component | Ownership | Lifecycle | Dependencies | Deployment | '
'Monitoring |\n| --- | --- | --- | --- | --- | --- |\n'
'| scheduler | platform | long-lived | database | kubernetes | '
'prometheus |\n\n';
const _answerLinks =
'\nRead [the release notes](https://example.com/releases/v2) or '
'<https://example.com/auto>; the bare https://example.com/bare/path. '
'and www.example.org work too. Not `https://example.com/inline`:\n\n'
'```sh\ncurl https://example.com/fenced\n```\n';
const _questionLinks =
' See https://example.com/question?id=1, [md](https://example.com/md) '
'and `https://example.com/code`.';
JsonMap _message(String chat, int i) {
final id = '$chat-m$i';
if (_rich && i % 10 == 5) {
return {
'id': id,
'role': 'user',
'kind': 'agent_report',
'parts': [
{
'type': 'text',
'name': 'reviewer',
'text':
'## Review of change $i\n\nAll checks passed.\n\n${_answer(i)}',
},
],
};
}
if (_rich && i % 10 == 7) {
return {
'id': id,
'role': 'user',
'kind': 'notice',
'parts': [
{'type': 'text', 'text': 'Background task $i finished.'},
],
};
}
if (i.isEven) {
return {
'id': id,
'role': 'user',
'parts': [
if (_rich && i % 4 == 0)
{
'type': 'file',
'mime': 'image/png',
'name': 'shot$i.png',
'uri': _png,
},
{'type': 'text', 'text': 'Question $i${_links ? _questionLinks : ''}'},
],
};
}
return {
'id': id,
'role': 'assistant',
'parts': [
if (_activity) ...[
{'type': 'reasoning', 'text': 'Checking the files for step $i.'},
{
'type': 'tool',
'id': 'tool-$i',
'name': 'read',
'state': 'completed',
'input': {'path': 'lib/main.dart'},
},
],
{'type': 'text', 'text': _answer(i)},
],
};
}
/// With `?timestamps=1`, message [i] of [count] carries a recorded time: the
/// first half on 24 November 2026 and the rest on the 25th (local time), a
/// few minutes apart, so the transcript shows two day dividers.
JsonMap _timed(JsonMap message, int i, int count) {
if (!_timestamps) return message;
final secondDay = i >= count ~/ 2;
final at = DateTime(
2026,
11,
secondDay ? 25 : 24,
10,
0,
).add(Duration(minutes: 3 * i));
return {...message, 'created_at': at.millisecondsSinceEpoch};
}
/// One history page for chat [index]: the newest messages, or with `?older=1`
/// and a cursor, the 20 messages before them.
JsonMap chatScrollHistory(String sessionId, int index, String cursor) {
final count = chatScrollMessageCount(index);
if (_older && cursor == 'older') {
return {
'messages': [for (var i = -20; i < 0; i++) _message(sessionId, i)],
'next_cursor': '',
'has_more': false,
};
}
final messages = [
for (var i = 0; i < count; i++) _message(sessionId, i),
for (var i = 0; i < _tasks; i++) _taskNotice(sessionId, i),
];
return {
'messages': [
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,
};
}
/// Streams the `?live=N` reply into [sessionId] through [emit].
void chatScrollStream(String sessionId, void Function(JsonMap frame) emit) {
final deltas = _live;
if (deltas == 0) return;
JsonMap event(JsonMap body) => {
'type': 'chat_event',
'chat_event': {'session_id': sessionId, ...body},
};
Timer(const Duration(seconds: 3), () {
emit(
event({
'kind': 'step',
'step': {'status': 'running', 'turn_id': 'live', 'intermediate': false},
}),
);
var sent = 0;
Timer.periodic(const Duration(milliseconds: 60), (timer) {
emit(
event({
'message_id': '$sessionId-live',
'kind': 'text',
'part': {'id': '$sessionId-live-text', 'type': 'text'},
'delta': sent % 12 == 11 ? 'word$sent\n\n' : 'word$sent ',
}),
);
if (++sent >= deltas) timer.cancel();
});
});
}
/// A scoped find-in-chat search (`scope: chat:<id>`) the way
/// `internal/server/search_chat_scoped.go` answers it: every occurrence in
/// the text parts of the history before [cursor] ("0|older" for the page
/// `?older=1` holds back), newest message first.
List<JsonMap> chatScrollScopedHits(
String sessionId,
String cursor,
String query,
bool caseSensitive,
) {
if (!_older || !cursor.endsWith('|older') || query.trim().isEmpty) {
return const [];
}
final pattern = RegExp(RegExp.escape(query), caseSensitive: caseSensitive);
final hits = <JsonMap>[];
for (var i = -1; i >= -20; i--) {
final message = _message(sessionId, i);
final parts = message['parts'] as List;
for (var part = 0; part < parts.length; part++) {
final body = parts[part] as Map;
if (body['type'] != 'text') continue;
for (final match in pattern.allMatches('${body['text']}')) {
hits.add({
'kind': 'chat',
'target': 'chat:$sessionId',
'chat': {
'session_id': sessionId,
'message_id': message['id'],
'part': part,
'offset': match.start,
'length': match.end - match.start,
},
});
}
}
}
return hits;
}