Files
pipelines/app/test/application/chat_registration_test.dart
T
alan 96de9f5bea Remove Cupertino chat conversation branches
Keep the Material-only conversation implementation while preserving public Cupertino parameters for callers. Narrow affected tests to Material hosts so the dead platform paths are no longer exercised.
2026-11-11 13:11:05 +00:00

767 lines
26 KiB
Dart

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/application/server_endpoint.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart';
import 'package:pipelines_app/features/chat/workspace/chat_mobile_peek_divider.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
import '../native_back.dart';
import 'package:pipelines_app/ui/adaptive/segmented_bar.dart';
ServerEndpoint webServer() => ServerEndpoint.resolve(
base: Uri.parse('http://127.0.0.1:8096/'),
web: true,
);
Map<String, dynamic>? requestOf(
FakeChannel channel,
String type, {
int index = 0,
}) => channel.outgoing
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
.where((frame) => frame['type'] == type)
.skip(index)
.firstOrNull;
final _fixtureAutomationReplies = Expando<Set<String>>();
Future<Map<String, dynamic>> waitForRequest(
WidgetTester tester,
FakeChannel channel,
String type, {
int index = 0,
}) async {
final replied = _fixtureAutomationReplies[channel] ??= <String>{};
for (var attempt = 0; attempt < 80; attempt++) {
// Automation metadata is independently requested before history. This
// fixture has no provider schedules; answer unavailable rather than leave
// the correlated transport blocked behind an unanswered request.
if (type != 'chat_automations') {
for (final raw in channel.outgoing.toList()) {
final metadata = jsonDecode(raw as String) as Map<String, dynamic>;
if (metadata['type'] == 'chat_automations' &&
replied.add('${metadata['id']}')) {
channel.incoming.add(
jsonEncode({
'id': metadata['id'],
'type': 'chat_automations',
'chat_automations': {
'session_id': metadata['chat_query']['session_id'],
'provider': 'fixture',
'status': 'unavailable',
},
}),
);
}
}
}
final request = requestOf(channel, type, index: index);
if (request != null) return request;
await tester.pump(const Duration(milliseconds: 5));
}
fail('Timed out waiting for $type #$index');
}
Future<void> replySessions(
WidgetTester tester,
FakeChannel channel, {
int index = 0,
}) async {
final request = await waitForRequest(
tester,
channel,
'chat_sessions',
index: index,
);
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'chat_sessions',
'chat_sessions': [
{'id': 's1', 'title': 'Wire chat', 'directory': '/workspace/demo'},
],
}),
);
await tester.pump();
}
Future<void> replySubscribe(
WidgetTester tester,
FakeChannel channel, {
int index = 0,
}) async {
final request = await waitForRequest(
tester,
channel,
'chat_subscribe',
index: index,
);
channel.incoming.add(
jsonEncode({'id': request['id'], 'type': 'chat_subscribe'}),
);
await tester.pump();
await tester.pump();
}
/// The mounted thread also reads the session's running background tasks. The
/// client serializes requests, so this snapshot is answered (no running task)
/// before the history page behind it can leave the queue.
Future<void> replyShells(
WidgetTester tester,
FakeChannel channel, {
int index = 0,
}) async {
final request = await waitForRequest(
tester,
channel,
'chat_shells',
index: index,
);
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'chat_shells',
'chat_shells': const [],
}),
);
await tester.pump();
}
Future<void> replyHistory(
WidgetTester tester,
FakeChannel channel, {
int index = 0,
String text = 'The stored reply stays readable.',
bool shells = true,
}) async {
if (shells) await replyShells(tester, channel, index: index);
final request = await waitForRequest(
tester,
channel,
'chat_messages',
index: index,
);
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'chat_history',
'chat_history': {
'messages': [
{
'id': 'u1',
'role': 'user',
'parts': [
{'type': 'text', 'text': 'Open this chat from its route.'},
],
},
{
'id': 'a1',
'role': 'assistant',
'parts': [
{'type': 'text', 'text': text},
{'type': 'reasoning', 'text': 'Kept behind a native disclosure.'},
{'type': 'tool', 'name': 'shell'},
],
},
],
'next_cursor': '',
'has_more': false,
},
}),
);
await tester.pump();
await tester.pump();
}
Future<void> replyChatSessions(
WidgetTester tester,
FakeChannel channel,
List<String> ids, {
int index = 0,
}) async {
final request = await waitForRequest(
tester,
channel,
'chat_sessions',
index: index,
);
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'chat_sessions',
'chat_sessions': [
for (final id in ids) {'id': id, 'title': 'Chat $id'},
],
}),
);
await tester.pump();
}
Future<void> replyChatHistory(
WidgetTester tester,
FakeChannel channel, {
required int subscribeIndex,
required int historyIndex,
String? text,
}) async {
await replySubscribe(tester, channel, index: subscribeIndex);
await replyHistory(
tester,
channel,
index: historyIndex,
text: text ?? 'History for chat ${subscribeIndex + 1}',
);
}
void main() {
testWidgets(
'a wide /chat/s1 deep link shows that thread beside the list and route Back returns to /chat',
(tester) async {
tester.view.physicalSize = const Size(900, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')),
);
addTearDown(provider.dispose);
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: false,
routeInformationProvider: provider,
),
);
await tester.pump();
await replySessions(tester, channel);
await replySubscribe(tester, channel);
await replyHistory(tester, channel);
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat/s1');
expect(find.byType(ChatThreadView), findsOneWidget);
// The exact route names the session; the request carries the same id.
expect(requestOf(channel, 'chat_subscribe')!['chat_subscribe'], {
'session_id': 's1',
});
expect(requestOf(channel, 'chat_messages')!['chat_query'], {
'session_id': 's1',
'limit': 200,
'cursor': '',
});
expect(find.text('The stored reply stays readable.'), findsOneWidget);
expect(find.text('Ran 1 command'), findsOneWidget);
expect(find.byKey(const Key('chat-turn-activity')), findsOneWidget);
expect(find.text('Kept behind a native disclosure.'), findsNothing);
// The shell bar stays over the list and tabs; the open chat draws its
// own floating bar in its pane, with no Back: the list beside it is the
// way out.
expect(find.byType(ChatSessionsScreen), findsOneWidget);
expect(find.byType(NavigationRail), findsNothing);
expect(find.byType(FloatingDestinationBar), findsOneWidget);
// The shell's bar and the conversation's own header.
expect(find.byType(SegmentedBar), findsNWidgets(2));
expect(find.byType(AppBar), findsNothing);
expect(find.byType(CupertinoNavigationBar), findsNothing);
expect(find.byKey(const Key('chat-thread-header')), findsOneWidget);
expect(findNativeBack(), findsNothing);
// A live frame updates the held thread.
channel.incoming.add(
jsonEncode({
'type': 'chat_event',
'chat_event': {
'session_id': 's1',
'message_id': 'a1',
'kind': 'text',
'part': {'id': 'p2', 'type': 'text'},
'delta': 'A live line arrived.',
},
}),
);
await tester.pump();
await tester.pump();
expect(find.text('A live line arrived.'), findsOneWidget);
// The thread's own bar carries its controls once: no second bar.
expect(find.byKey(const Key('chat-thread-header')), findsOneWidget);
// Browser Back to /chat clears the open pane and keeps the list.
await provider.didPushRouteInformation(
RouteInformation(uri: Uri.parse('/chat')),
);
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat');
expect(find.byType(ChatThreadView), findsNothing);
expect(find.byType(ChatSessionsScreen), findsOneWidget);
expect(find.text('Wire chat'), findsOneWidget);
expect(find.text('Select a chat to open it here.'), findsOneWidget);
// Browser Forward re-opens the same session through its route.
await provider.didPushRouteInformation(
RouteInformation(uri: Uri.parse('/chat/s1')),
);
await tester.pump();
expect(provider.value.uri.path, '/chat/s1');
await replySubscribe(tester, channel, index: 1);
await replyHistory(
tester,
channel,
index: 1,
text: 'Reopened from the route.',
);
expect(find.text('Reopened from the route.'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
},
);
testWidgets(
'mobile Chats retap reopens the retained multi-pane workspace after tabs',
(tester) async {
// A restored empty layout chooses the retained inline mobile path from
// the first selection, rather than the initial pushed detail route.
SharedPreferences.setMockInitialValues({
chatWorkspacePreferenceKey: jsonEncode({
'version': 1,
'root': null,
'active_pane': null,
'sidebar_mode': 'expanded',
}),
});
tester.platformDispatcher.accessibilityFeaturesTestValue =
const FakeAccessibilityFeatures(disableAnimations: false);
addTearDown(
tester.platformDispatcher.clearAccessibilityFeaturesTestValue,
);
tester.view.physicalSize = const Size(560, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')),
);
addTearDown(provider.dispose);
addTearDown(client.dispose);
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: false,
routeInformationProvider: provider,
),
);
await tester.pump();
await replyChatSessions(tester, channel, ['a', 'b']);
await tester.pumpAndSettle();
await tester.tap(find.text('Chat a').first);
await tester.pump();
expect(provider.value.uri.path, '/chat/a');
expect(find.byType(ChatThreadView), findsOneWidget);
await replyChatSessions(tester, channel, ['a', 'b'], index: 1);
await replyChatHistory(
tester,
channel,
subscribeIndex: 0,
historyIndex: 0,
);
await tester.pumpAndSettle();
await tester.enterText(
find.descendant(
of: find.byKey(const ValueKey('chat-composer-a')),
matching: find.byType(EditableText),
),
'Draft retained in pane a',
);
final addPane = find.byTooltip('Add chat pane').hitTestable();
if (addPane.evaluate().isEmpty) {
await tester.tap(find.byTooltip('More actions').hitTestable().first);
await tester.pumpAndSettle();
await tester.tap(find.text('Add chat pane'));
} else {
await tester.tap(addPane);
}
await tester.pumpAndSettle();
await tester.tap(find.text('Chat b').last);
await tester.pump();
await replyChatHistory(
tester,
channel,
subscribeIndex: 1,
historyIndex: 1,
text: List.generate(80, (i) => 'History line $i').join('\n\n'),
);
await tester.pumpAndSettle();
await tester.enterText(
find.descendant(
of: find.byKey(const ValueKey('chat-composer-b')),
matching: find.byType(EditableText),
),
'Draft retained in pane b',
);
expect(
tester
.widget<EditableText>(
find.descendant(
of: find.byKey(const ValueKey('chat-composer-b')),
matching: find.byType(EditableText),
),
)
.controller
.text,
'Draft retained in pane b',
);
final workspace = tester.widget<ChatWorkspace>(
find.byType(ChatWorkspace),
);
expect(workspace.controller.paneCount, 2);
expect(workspace.controller.activePane?.sessionId, 'b');
expect(provider.value.uri.path, '/chat/b');
final workspaceState = tester.state(find.byType(ChatWorkspace));
final activeThreadState = tester.state(
find.byKey(const ValueKey('chat-session-b')),
);
final restingTop = tester.getTopLeft(find.byType(ChatWorkspace)).dy;
final paneOrder = workspace.controller.panes
.map((p) => p.sessionId)
.toList();
await tester.drag(
find.byType(ChatMobilePeekDivider),
const Offset(0, 60),
);
await tester.pumpAndSettle();
final peekFraction = workspace.controller.mobilePeekFraction;
expect(peekFraction, lessThan(.2));
await tester.tap(find.bySemanticsLabel('Expand Chat a'));
await tester.pumpAndSettle();
expect(workspace.controller.activePane?.sessionId, 'a');
expect(workspace.controller.panes.map((p) => p.sessionId), paneOrder);
await tester.tap(find.bySemanticsLabel('Expand Chat b'));
await tester.pumpAndSettle();
expect(workspace.controller.activePane?.sessionId, 'b');
final transcript = find.byKey(const ValueKey('chat-thread-b'));
ScrollPosition historyPosition() => tester
.state<ScrollableState>(
find
.descendant(of: transcript, matching: find.byType(Scrollable))
.first,
)
.position;
final atEnd = historyPosition().pixels;
await tester.drag(transcript, const Offset(0, 250));
await tester.pumpAndSettle();
final historyOffset = historyPosition().pixels;
expect(historyOffset, isNot(closeTo(atEnd, 1)));
await tester.tap(find.byTooltip('Back').hitTestable());
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat');
expect(find.byType(ChatThreadView), findsNothing);
await tester.tap(find.byKey(const ValueKey('shell.destination.runs')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('shell.destination.chat')));
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat');
expect(find.byType(ChatThreadView), findsNothing);
// The selected Chats destination is already showing its list: the
// second tap reuses the mounted workspace instead of opening a new one.
await tester.tap(find.byKey(const ValueKey('shell.destination.chat')));
await tester.pump();
final enteringTop = tester.getTopLeft(find.byType(ChatWorkspace)).dy;
expect(enteringTop, greaterThan(restingTop + 1));
await tester.pump(const Duration(milliseconds: 80));
final midwayTop = tester.getTopLeft(find.byType(ChatWorkspace)).dy;
expect(midwayTop, greaterThan(restingTop + 1));
expect(midwayTop, lessThan(enteringTop));
await tester.pumpAndSettle();
expect(tester.getTopLeft(find.byType(ChatWorkspace)).dy, restingTop);
expect(tester.state(find.byType(ChatWorkspace)), same(workspaceState));
expect(
tester.state(find.byKey(const ValueKey('chat-session-b'))),
same(activeThreadState),
);
expect(provider.value.uri.path, '/chat/b');
final restored = tester.widget<ChatWorkspace>(find.byType(ChatWorkspace));
expect(restored.controller, same(workspace.controller));
expect(restored.controller.paneCount, 2);
expect(restored.controller.activePane?.sessionId, 'b');
expect(restored.controller.panes.map((p) => p.sessionId), paneOrder);
expect(restored.controller.mobilePeekFraction, peekFraction);
expect(historyPosition().pixels, closeTo(historyOffset, 1));
expect(find.byType(ChatThreadView), findsNWidgets(2));
expect(
tester
.widget<EditableText>(
find.descendant(
of: find.byKey(const ValueKey('chat-composer-b')),
matching: find.byType(EditableText),
),
)
.controller
.text,
'Draft retained in pane b',
);
expect(
find.descendant(
of: find.byKey(
const ValueKey('chat-composer-a'),
skipOffstage: false,
),
matching: find.byType(EditableText, skipOffstage: false),
skipOffstage: false,
),
findsOneWidget,
);
expect(
tester
.widget<EditableText>(
find.descendant(
of: find.byKey(
const ValueKey('chat-composer-a'),
skipOffstage: false,
),
matching: find.byType(EditableText, skipOffstage: false),
skipOffstage: false,
),
)
.controller
.text,
'Draft retained in pane a',
);
expect(tester.takeException(), isNull);
},
);
testWidgets(
'a folded workspace rejects paste while retained behind the list',
(tester) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(1000, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')),
);
addTearDown(provider.dispose);
addTearDown(client.dispose);
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: false,
routeInformationProvider: provider,
),
);
await tester.pump();
await replyChatSessions(tester, channel, ['a']);
await tester.pumpAndSettle();
await tester.tap(find.text('Chat a').first);
await tester.pump();
await replyChatHistory(
tester,
channel,
subscribeIndex: 0,
historyIndex: 0,
);
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'original draft',
);
tester.view.physicalSize = const Size(560, 1000);
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Back').hitTestable());
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat');
final retained = tester.widgetList<ChatComposerBar>(
find.byType(ChatComposerBar, skipOffstage: false),
);
expect(retained, hasLength(1));
expect(retained.single.pasteTarget, isFalse);
var clipboardReads = 0;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.getData') {
clipboardReads++;
return {'text': 'must not enter hidden chat'};
}
return null;
});
addTearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null);
});
FocusManager.instance.primaryFocus?.unfocus();
await tester.pump();
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyV);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pumpAndSettle();
expect(clipboardReads, 0);
await tester.tap(find.byKey(const ValueKey('shell.destination.chat')));
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat/a');
expect(find.text('original draft'), findsOneWidget);
expect(find.textContaining('must not enter hidden chat'), findsNothing);
expect(
tester
.widget<ChatComposerBar>(find.byType(ChatComposerBar))
.pasteTarget,
isTrue,
);
},
);
testWidgets(
'mobile Chats retap stays on list with no history or a removed chat',
(tester) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(560, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')),
);
addTearDown(provider.dispose);
addTearDown(client.dispose);
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: false,
routeInformationProvider: provider,
),
);
await tester.pump();
await replyChatSessions(tester, channel, ['a']);
await tester.pumpAndSettle();
final chatTab = find.byKey(const ValueKey('shell.destination.chat'));
await tester.tap(chatTab);
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat');
expect(find.byType(ChatThreadView), findsNothing);
await tester.tap(find.text('Chat a').first);
await tester.pump();
await replyChatHistory(
tester,
channel,
subscribeIndex: 0,
historyIndex: 0,
);
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Back').hitTestable());
await tester.pumpAndSettle();
await tester.tap(chatTab);
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat/a');
expect(find.byType(ChatThreadView), findsOneWidget);
// The cached transcript renders immediately, but answer the restored
// thread's network read before refreshing the serialized session list.
await replyChatHistory(
tester,
channel,
subscribeIndex: 1,
historyIndex: 1,
);
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Back').hitTestable());
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-refresh')).hitTestable());
await tester.pump();
await replyChatSessions(tester, channel, [], index: 1);
await tester.pumpAndSettle();
for (var attempt = 0; attempt < 2; attempt++) {
await tester.tap(chatTab);
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat');
expect(find.byType(ChatThreadView), findsNothing);
}
expect(tester.takeException(), isNull);
},
);
testWidgets('Chats retap restores a boot deep link after folding and Back', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(1000, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/a')),
);
addTearDown(provider.dispose);
addTearDown(client.dispose);
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: false,
routeInformationProvider: provider,
),
);
await tester.pump();
await replyChatSessions(tester, channel, ['a']);
await replyChatHistory(tester, channel, subscribeIndex: 0, historyIndex: 0);
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'deep link draft',
);
tester.view.physicalSize = const Size(560, 1000);
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Back').hitTestable());
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat');
await tester.tap(find.byKey(const ValueKey('shell.destination.chat')));
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat/a');
expect(find.byType(ChatThreadView), findsOneWidget);
expect(
tester
.widget<TextField>(find.byKey(const Key('chat-composer-field')))
.controller!
.text,
'deep link draft',
);
expect(tester.takeException(), isNull);
});
}