merge(app): land native chat composer after retained-run recovery

This commit is contained in:
2026-10-21 23:49:08 +01:00
8 changed files with 1386 additions and 84 deletions
@@ -0,0 +1,120 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
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_draft_store.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
/// A gateway for one open fixture conversation with a composer. History pages
/// are tests' own; prompt/interrupt replies are controlled per test.
class ComposerBarGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
final _frames = StreamController<JsonMap>.broadcast();
JsonMap page = chatPage(const []);
Future<JsonMap> Function(String text, String operationId)? prompt;
Future<JsonMap> Function()? interrupt;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type: type, fields: fields));
switch (type) {
case 'chat_subscribe':
return <String, dynamic>{};
case 'chat_messages':
return page;
case 'chat_prompt':
final body = fields['chat_prompt'] as JsonMap? ?? const {};
return prompt == null
? <String, dynamic>{}
: prompt!('${body['text'] ?? ''}', '${body['operation_id'] ?? ''}');
case 'chat_interrupt':
return interrupt == null ? <String, dynamic>{} : interrupt!();
}
return <String, dynamic>{};
}
@override
Stream<JsonMap> get frames => _frames.stream;
List<JsonMap> get promptBodies => calls
.where((call) => call.type == 'chat_prompt')
.map((call) => call.fields['chat_prompt'] as JsonMap)
.toList();
List<JsonMap> get interruptBodies => calls
.where((call) => call.type == 'chat_interrupt')
.map((call) => call.fields['chat_query'] as JsonMap)
.toList();
void emitEvent(JsonMap body) =>
_frames.add({'type': 'chat_event', 'chat_event': body});
void close() => _frames.close();
}
Widget materialHost(Widget child) => MaterialApp(
theme: ThemeData(
platform: TargetPlatform.android,
brightness: Brightness.light,
),
home: Scaffold(body: child),
);
Widget cupertinoHost(Widget child) => CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(child: child),
);
Widget composerThread(
ComposerBarGateway gateway, {
bool cupertino = false,
int syncToken = 0,
ChatDraftStore? drafts,
String Function()? newOperationId,
VoidCallback? onBack,
}) {
final thread = ChatThreadView(
gateway: gateway,
sessionId: 's',
syncToken: syncToken,
onBack: onBack ?? () {},
drafts: drafts ?? MemoryChatDraftStore(),
newOperationId: newOperationId,
);
return cupertino ? cupertinoHost(thread) : materialHost(thread);
}
/// The common fixture turn, so a rebuild has real transcript content to move.
JsonMap fixtureTurn({
String user = 'Stored question',
String answer = 'Stored answer',
}) => chatPage([
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': user},
],
),
chatMessage(
'a1',
'assistant',
parts: [
{'type': 'text', 'text': answer},
],
),
]);
String fieldText(WidgetTester tester) => tester
.widget<EditableText>(
find.descendant(
of: find.byKey(const Key('chat-composer-field')),
matching: find.byType(EditableText),
),
)
.controller
.text;
@@ -0,0 +1,148 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart';
import 'chat_composer_bar_fixtures.dart';
import 'chat_thread_fixtures.dart';
void main() {
late ComposerBarGateway gateway;
late int sequence;
String nextOperation() => 'op/${++sequence}';
setUp(() {
gateway = ComposerBarGateway()..page = fixtureTurn();
sequence = 0;
});
tearDown(() => gateway.close());
testWidgets('Stop replaces Send while running and interrupts this session', (
tester,
) async {
await tester.pumpWidget(
composerThread(gateway, newOperationId: nextOperation),
);
await tester.pumpAndSettle();
expect(find.text(chatSendLabel), findsOneWidget);
gateway.emitEvent(chatStepFrame('running'));
await tester.pump();
await tester.pump();
expect(find.text(chatSendLabel), findsNothing);
expect(find.text(chatStopLabel), findsOneWidget);
final button = tester.widget<FilledButton>(
find.byKey(const Key('chat-composer-primary')),
);
final scheme = Theme.of(
tester.element(find.byKey(const Key('chat-composer-primary'))),
).colorScheme;
expect(button.style?.backgroundColor?.resolve({}), scheme.error);
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pumpAndSettle();
expect(gateway.interruptBodies.single, {'session_id': 's'});
expect(gateway.promptBodies, isEmpty);
});
testWidgets('the queued notice is a polite line and clears on a frame', (
tester,
) async {
gateway.prompt = (_, _) async => {'chat_queued': true};
final semantics = tester.ensureSemantics();
await tester.pumpWidget(
composerThread(gateway, newOperationId: nextOperation),
);
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'wait behind',
);
await tester.pump();
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pumpAndSettle();
expect(find.text(chatQueuedNotice), findsOneWidget);
expect(
tester.getSemantics(find.byKey(const Key('chat-composer-queued'))),
isSemantics(isLiveRegion: true),
);
gateway.emitEvent(chatStepFrame('running'));
await tester.pump();
await tester.pump();
expect(find.byKey(const Key('chat-composer-queued')), findsNothing);
semantics.dispose();
});
testWidgets('a live rebuild keeps the field focus, text and caret', (
tester,
) async {
await tester.pumpWidget(
composerThread(gateway, newOperationId: nextOperation),
);
await tester.pumpAndSettle();
final field = find.byKey(const Key('chat-composer-field'));
await tester.enterText(field, 'caret draft');
await tester.pump();
final before = tester.widget<EditableText>(
find.descendant(of: field, matching: find.byType(EditableText)),
);
before.controller.selection = const TextSelection.collapsed(offset: 5);
await tester.pump();
gateway.emitEvent(chatStepFrame('running'));
await tester.pump();
final after = tester.widget<EditableText>(
find.descendant(of: field, matching: find.byType(EditableText)),
);
expect(after.focusNode, same(before.focusNode));
expect(after.focusNode.hasFocus, isTrue);
expect(after.controller.text, 'caret draft');
expect(after.controller.selection.baseOffset, 5);
});
for (final cupertino in [false, true]) {
testWidgets('the composer wraps at 320 logical px with 2x text '
'(${cupertino ? 'cupertino' : 'material'})', (tester) async {
tester.view.physicalSize = const Size(640, 1200);
tester.view.devicePixelRatio = 2;
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
gateway.page = fixtureTurn(
user:
'A stored question long enough to wrap onto several lines at a '
'narrow phone width without clipping any of its words.',
answer:
'A stored answer that also wraps so the transcript has real '
'content above the composer.',
);
await tester.pumpWidget(
composerThread(
gateway,
cupertino: cupertino,
newOperationId: nextOperation,
),
);
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'A draft with enough words to wrap inside the composer field on a '
'narrow screen while the host text is scaled up.',
);
await tester.pump();
expect(tester.takeException(), isNull);
expect(find.byKey(const Key('chat-composer')), findsOneWidget);
expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget);
});
}
}
@@ -0,0 +1,234 @@
import 'dart:async';
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 'chat_composer_bar_fixtures.dart';
import 'chat_thread_fixtures.dart';
void main() {
late ComposerBarGateway gateway;
late int sequence;
String nextOperation() => 'op/${++sequence}';
setUp(() {
gateway = ComposerBarGateway()..page = fixtureTurn();
sequence = 0;
});
tearDown(() => gateway.close());
testWidgets(
'Send posts the exact trimmed prompt identity and shows it once',
(tester) async {
await tester.pumpWidget(
composerThread(gateway, newOperationId: nextOperation),
);
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
' hello ',
);
await tester.pump();
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pumpAndSettle();
expect(gateway.promptBodies.single, {
'session_id': 's',
'text': 'hello',
'operation_id': 'op/1',
'native_message_id': 'msg_op1',
});
expect(fieldText(tester), '');
expect(find.text('hello'), findsOneWidget);
// The live user frame carries the same intent; the local row disappears
// instead of drawing the operator's turn twice.
gateway.emitEvent({
'session_id': 's',
'message_id': 'msg_op1',
'kind': 'user',
'operation_id': 'op/1',
'part': {'type': 'text', 'text': 'hello'},
});
await tester.pump();
expect(find.text('hello'), findsOneWidget);
// A history resync that includes the stored prompt keeps exactly one row.
gateway.page = chatPage([
{
'id': 'u1',
'role': 'user',
'parts': [
{'type': 'text', 'text': 'Stored question'},
],
},
{
'id': 'a1',
'role': 'assistant',
'parts': [
{'type': 'text', 'text': 'Stored answer'},
],
},
{
'id': 'msg_op1',
'role': 'user',
'operation_id': 'op/1',
'parts': [
{'type': 'text', 'text': 'hello'},
],
},
]);
await tester.pumpWidget(
composerThread(gateway, syncToken: 1, newOperationId: nextOperation),
);
await tester.pumpAndSettle();
expect(find.text('hello'), findsOneWidget);
},
);
testWidgets('Enter inserts a newline; Ctrl+Enter sends', (tester) async {
await tester.pumpWidget(
composerThread(gateway, newOperationId: nextOperation),
);
await tester.pumpAndSettle();
final field = find.byKey(const Key('chat-composer-field'));
await tester.enterText(field, 'line one');
await tester.pump();
// A hardware Enter is left to the IME and never submits; the engine then
// inserts the newline as an editing value.
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(gateway.promptBodies, isEmpty);
tester.testTextInput.updateEditingValue(
const TextEditingValue(
text: 'line one\n',
selection: TextSelection.collapsed(offset: 9),
),
);
await tester.pump();
expect(fieldText(tester), 'line one\n');
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pumpAndSettle();
expect(gateway.promptBodies.single['text'], 'line one');
});
testWidgets('Cmd+Enter sends on the Cupertino host', (tester) async {
await tester.pumpWidget(
composerThread(gateway, cupertino: true, newOperationId: nextOperation),
);
await tester.pumpAndSettle();
final field = find.byKey(const Key('chat-composer-field'));
await tester.enterText(field, 'mac line');
await tester.pump();
await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
await tester.pumpAndSettle();
expect(gateway.promptBodies.single['text'], 'mac line');
});
testWidgets('Send is disabled for a blank draft and while sending', (
tester,
) async {
final reply = Completer<JsonMap>();
gateway.prompt = (_, _) => reply.future;
await tester.pumpWidget(
composerThread(gateway, newOperationId: nextOperation),
);
await tester.pumpAndSettle();
FilledButton primary() => tester.widget<FilledButton>(
find.byKey(const Key('chat-composer-primary')),
);
expect(primary().onPressed, isNull);
await tester.enterText(find.byKey(const Key('chat-composer-field')), ' ');
await tester.pump();
expect(primary().onPressed, isNull);
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'ready',
);
await tester.pump();
expect(primary().onPressed, isNotNull);
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pump();
expect(gateway.promptBodies, hasLength(1));
// Newer text cannot start a second prompt while the first awaits its reply.
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'second',
);
await tester.pump();
expect(primary().onPressed, isNull);
reply.complete(const {});
await tester.pumpAndSettle();
expect(primary().onPressed, isNotNull);
expect(gateway.promptBodies, hasLength(1));
});
testWidgets('a refusal restores the draft visibly and reuses its intent', (
tester,
) async {
var attempts = 0;
gateway.prompt = (_, _) async {
if (++attempts == 1) throw StateError('response lost');
return const {};
};
await tester.pumpWidget(
composerThread(gateway, newOperationId: nextOperation),
);
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
' keep me ',
);
await tester.pump();
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pumpAndSettle();
expect(fieldText(tester), ' keep me ');
expect(find.byKey(const Key('chat-composer-error')), findsOneWidget);
expect(find.textContaining('response lost'), findsOneWidget);
expect(gateway.promptBodies.single['operation_id'], 'op/1');
// The refused optimistic turn is withdrawn, not left as a fake message.
expect(find.text('keep me'), findsNothing);
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pumpAndSettle();
expect(gateway.promptBodies.map((body) => body['operation_id']), [
'op/1',
'op/1',
]);
expect(fieldText(tester), '');
expect(find.byKey(const Key('chat-composer-error')), findsNothing);
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'different',
);
await tester.pump();
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pumpAndSettle();
expect(gateway.promptBodies.last['operation_id'], 'op/2');
});
}