Files
pipelines/app/tool/chat_composer_probe_entry.dart
T
alan 20bf6202b3 Rebuild only the live chat turn while replies stream
Reuse unchanged transcript rows, the composer bar and the header across
streamed deltas, and share parsed markdown by text so rows scrolled back
into view are not parsed again. Adds a rebuild/parse harness and a
release-web frame-timing probe with a long-transcript fixture.
2026-11-01 23:59:40 +00:00

302 lines
9.7 KiB
Dart

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_perf_fixture.dart';
/// A live-looking fixture conversation with a deterministic composer.
///
/// A successful prompt starts a running turn (so the primary control becomes
/// Stop); text containing `queued` additionally returns the queued flag. Text
/// containing `refuse` is rejected so the browser can see the restored draft
/// and the polite error line. Stop ends the turn through a live step frame.
class _ProbeGateway implements ApiGateway {
final _frames = StreamController<JsonMap>.broadcast();
var _sequence = 0;
static const _session = 'probe-composer';
@override
Stream<JsonMap> get frames => _frames.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
switch (type) {
case 'chat_subscribe':
return <String, dynamic>{};
case 'chat_shells':
// `?tasks=2` reports that many running background tasks.
return {
'chat_shells': [
for (var i = 0; i < _probeTasks; i++)
{
'id': 'probe-shell-$i',
'status': 'running',
'command': 'go test ./... #$i',
},
],
};
case 'chat_messages':
return {
'chat_history': {
'messages': [
// `?perf=<n>`: a long transcript for tool/chat_perf_probe.mjs.
...chatPerfTranscript(chatPerfMessages),
// A long history scrolls behind the floating header.
if (_probeLong || _query['long'] == '1')
for (var i = 0; i < 12; i++)
{
'id': 'probe-history-$i',
'role': i.isEven ? 'user' : 'assistant',
'parts': [
{
'type': 'text',
'text':
'Earlier message ${i + 1}: a line of history so '
'the transcript is taller than the window.',
},
],
},
// `?paras=1`: a long reply that arrived in chunks — several
// text parts and a second folded message, each with markdown
// paragraphs.
if (_query['paras'] == '1') ..._chunkedReply,
if (chatPerfMessages == 0) ...[
{
'id': 'probe-user',
'role': 'user',
'parts': [
{
'type': 'text',
'text':
'Show me the composer as an operator would use it.',
},
],
},
{
'id': 'probe-assistant',
'role': 'assistant',
'parts': [
{
'type': 'text',
'text':
'The composer sits below the conversation with a '
'multiline field and one primary control.',
},
],
},
],
],
'next_cursor': '',
'has_more': false,
},
};
case 'chat_prompt':
final body = fields['chat_prompt'] as JsonMap? ?? const {};
final text = '${body['text'] ?? ''}';
if (text.toLowerCase().contains('refuse')) {
throw StateError('The fixture refused this prompt.');
}
// `hold`: the reply never arrives, so the message stays Sending….
if (text.toLowerCase().contains('hold')) {
return Completer<JsonMap>().future;
}
final queued = text.toLowerCase().contains('queued');
Timer(const Duration(milliseconds: 150), _running);
await Future<void>.delayed(const Duration(milliseconds: 450));
return queued ? {'chat_queued': true} : <String, dynamic>{};
case 'chat_interrupt':
Timer(const Duration(milliseconds: 200), _ended);
return <String, dynamic>{};
}
return <String, dynamic>{};
}
void _running() => _emit({
'kind': 'step',
'step': {
'status': 'running',
'turn_id': 'probe-turn',
'intermediate': false,
},
});
void _ended() => _emit({
'kind': 'step',
'step': {'status': 'ended', 'turn_id': 'probe-turn', 'intermediate': false},
});
void emit(JsonMap body) => _emit(body);
void _emit(JsonMap body) => _frames.add({
'type': 'chat_event',
'chat_event': {'session_id': _session, ...body},
});
String nextOperation() => 'probe-op-${++_sequence}';
}
const _chunkedReply = <JsonMap>[
{
'id': 'probe-chunked-user',
'role': 'user',
'parts': [
{'type': 'text', 'text': 'Walk me through the deploy plan.'},
],
},
{
'id': 'probe-chunked-1',
'role': 'assistant',
'parts': [
{
'type': 'text',
'text':
'First I checked the build. Every target compiles and the '
'focused tests pass on this branch.\n\n'
'The integration suite is slower, so I ran it in the background '
'while reading the release notes.',
},
{
'type': 'text',
'text':
'Next, the migration. It only adds a column, so it is safe to '
'apply before the new server starts.',
},
],
},
{
'id': 'probe-chunked-2',
'role': 'assistant',
'parts': [
{
'type': 'text',
'text':
'Finally, the rollout order:\n\n'
'1. Apply the migration.\n'
'2. Restart the server.\n'
'3. Publish the client.\n\n'
'Each step can be rolled back on its own.',
},
],
},
];
const _probeLong = bool.fromEnvironment('CHAT_COMPOSER_PROBE_LONG');
const _probeModel = String.fromEnvironment(
'CHAT_COMPOSER_PROBE_MODEL',
defaultValue: 'claude-opus-5-5',
);
/// A phone-width frame inside a wider browser window (headless Chrome crops
/// windows narrower than about 500px); zero uses the whole window.
const _probeWidth = int.fromEnvironment('CHAT_COMPOSER_PROBE_WIDTH');
Widget _framed(Widget child) => _probeWidth == 0
? child
: Center(
child: SizedBox(width: _probeWidth.toDouble(), child: child),
);
const _probeStyle = String.fromEnvironment(
'CHAT_COMPOSER_PROBE_STYLE',
defaultValue: 'material',
);
/// Browser overrides: `?platform=cupertino|material`, `?theme=dark|light`,
/// `?long=1`, `?paras=1` (a chunked multi-paragraph reply), `?tasks=<n>`, `?mode=0` (no permission mode recorded) and
/// `?model=0` (a backend without models). `?perf=<n>` and `?stream=<n>` are
/// the long-transcript performance fixture (see chat_perf_fixture.dart).
///
/// Delivery states: `?send=<text>` types and sends that text once the thread
/// has loaded (`hold` never replies, `queued` queues, `refuse` is refused), and
/// `?unsent=1` opens with a message a previous visit sent but never saw
/// accepted, as after a page reload mid-request.
Map<String, String> get _query => Uri.base.queryParameters;
int get _probeTasks => int.tryParse(_query['tasks'] ?? '') ?? 0;
void main() {
final gateway = _ProbeGateway();
final cupertino = (_query['platform'] ?? _probeStyle) == 'cupertino';
final dark = _query['theme'] == null ? cupertino : _query['theme'] == 'dark';
final thread = ChatThreadView(
gateway: gateway,
sessionId: 'probe-composer',
title: 'Composer fixture',
session: {
'id': 'probe-composer',
'backend': _query['model'] == '0' ? 'pi' : 'opencode',
'model': _probeModel,
'directory': '/Users/ada/repos/tank',
if (_query['mode'] != '0') ...{
'mode': 'default',
'mode_name': 'Ask for permission',
},
},
onBack: () {},
drafts: MemoryChatDraftStore(
drafts: {'probe-composer': ?_query['send']},
unsent: {
if (_query['unsent'] == '1')
'probe-composer': [
{
'session_id': 'probe-composer',
'text': 'Did this one reach the server before the reload?',
'operation_id': 'probe-op-reloaded',
'native_message_id': 'msg_probeopreloaded',
},
],
},
),
newOperationId: gateway.nextOperation,
);
startChatPerf(gateway.emit);
if (_query['send'] != null) {
Timer(
const Duration(milliseconds: 1200),
() => _press('chat-composer-primary'),
);
}
if (cupertino) {
runApp(
CupertinoApp(
theme: CupertinoThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
home: CupertinoPageScaffold(child: _framed(SafeArea(child: thread))),
),
);
return;
}
runApp(
MaterialApp(
theme: ThemeData(
platform: TargetPlatform.android,
brightness: dark ? Brightness.dark : Brightness.light,
),
home: Scaffold(body: _framed(SafeArea(child: thread))),
),
);
}
/// Presses the native button carrying [key], as a tap would; the probe has no
/// pointer in a headless screenshot.
void _press(String key) {
void visit(Element element) {
final widget = element.widget;
if (widget.key == Key(key)) {
if (widget is CupertinoButton) widget.onPressed?.call();
if (widget is ButtonStyleButton) widget.onPressed?.call();
if (widget is IconButton) widget.onPressed?.call();
return;
}
element.visitChildren(visit);
}
WidgetsBinding.instance.rootElement?.visitChildren(visit);
}