Merge commit 'a1c0d10593881af1b59b2ce61b10fd3dbf790ad3' into pipelines/run-20261112-0233-phone-bottom-tab-bar-2b54

This commit is contained in:
2026-11-12 03:36:04 +00:00
57 changed files with 4333 additions and 469 deletions
@@ -0,0 +1,205 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/server_scope.dart';
import 'package:pipelines_app/features/chat/screen.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/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'conversation/chat_thread_fixtures.dart';
/// A chat server that keeps the open-chat set with the real revision rules:
/// a seed applies only to a never-stored set, a write from a stale base is
/// refused with the current set.
class _Server extends FakeChatGateway {
_Server({this.revision = 0, List<String> open = const []})
: open = List.of(open);
int revision;
List<String> open;
final writes = <List<String>>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_sessions') {
return Future.value({
'chat_sessions': [
for (final id in ['a', 'b', 'c', 'd'])
{'id': id, 'title': 'Chat $id'},
],
});
}
if (type == 'chat_shells') return Future.value({'chat_shells': []});
if (type == 'chat_open_workspace') return Future.value(_workspace(fields));
return super.call(type, fields);
}
JsonMap _workspace(JsonMap fields) {
final request = fields['chat_open_workspace_request'] as Map?;
var rejected = false;
if (request != null) {
final ids = [
for (final entry in request['entries'] as List)
'${entry['session_id']}',
];
writes.add(ids);
if (request['seed'] == true) {
if (revision == 0) {
open = ids;
revision = 1;
}
} else if (request['base_revision'] != revision) {
rejected = true;
} else {
open = ids;
revision++;
}
}
return {
'type': 'chat_open_workspace',
'chat_open_workspace': _body(rejected),
};
}
JsonMap _body([bool rejected = false]) => {
'revision': revision,
'entries': [
for (final id in open) {'session_id': id},
],
if (rejected) 'rejected': true,
};
/// Another device (or the server) changed the set.
void change(List<String> ids) {
open = List.of(ids);
revision++;
emitRaw({
'type': 'chat_open_workspace_changed',
'chat_open_workspace': _body(),
});
}
}
ChatWorkspaceController _workspace(WidgetTester tester) =>
tester.widget<ChatWorkspace>(find.byType(ChatWorkspace)).controller;
List<String> _open(WidgetTester tester) =>
_workspace(tester).panes.map((pane) => pane.sessionId).toList();
Future<void> _mount(WidgetTester tester, _Server server) async {
await tester.pumpWidget(
MaterialApp(
home: AdaptiveShell(
destination: AppDestination.chat,
destinationBodies: {
AppDestination.chat: (_) =>
ChatScreen(gateway: server, persistWorkspace: true),
},
),
),
);
await tester.pumpAndSettle();
}
_Server _server(
String identity, {
int revision = 0,
List<String> open = const [],
}) {
final server = _Server(revision: revision, open: open)
..history = (_) async => chatPage([]);
bindServerIdentity(server, identity);
addTearDown(server.close);
return server;
}
void _saveLocal(String identity, List<String> ids) {
final saved = ChatWorkspaceController()..open(ids.first);
for (final id in ids.skip(1)) {
saved.splitActive(id, ChatSplitAxis.horizontal);
}
SharedPreferences.setMockInitialValues({
scopedServerKey(chatWorkspacePreferenceKey, identity): saved
.snapshot()!
.encode(),
});
}
void main() {
testWidgets(
'the local layout seeds a new server and remote removal drops its pane',
(tester) async {
tester.view.physicalSize = const Size(1800, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
_saveLocal('server-a', ['a', 'b']);
final server = _server('server-a');
await _mount(tester, server);
expect(server.revision, 1);
expect(server.open, ['a', 'b']);
expect(_open(tester), ['a', 'b']);
server.change(['b']);
await tester.pumpAndSettle();
expect(_open(tester), ['b']);
// Applying the server's change is not written back.
expect(server.writes, hasLength(1));
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpAndSettle();
},
);
testWidgets('an existing server set wins over an old local snapshot', (
tester,
) async {
tester.view.physicalSize = const Size(1800, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
_saveLocal('server-a', ['a']);
final server = _server('server-a', revision: 3, open: ['b', 'c']);
await _mount(tester, server);
expect(_open(tester), ['b', 'c']);
expect(server.open, ['b', 'c']);
expect(server.revision, 3);
// A local change is sent from the server's revision and accepted.
_workspace(tester).close(_workspace(tester).panes.first.id);
await tester.pumpAndSettle();
expect(server.open, ['c']);
expect(server.revision, 4);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpAndSettle();
});
testWidgets('rebinding to another server disposes the old sync', (
tester,
) async {
tester.view.physicalSize = const Size(1800, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
SharedPreferences.setMockInitialValues({});
final first = _server('server-a', revision: 1, open: ['a']);
final second = _server('server-b', revision: 1, open: ['c']);
await _mount(tester, first);
expect(_open(tester), ['a']);
await _mount(tester, second);
expect(_open(tester), ['c']);
// The old server's pushes no longer reach this screen.
first.change(['a', 'b', 'd']);
await tester.pumpAndSettle();
expect(_open(tester), ['c']);
// The new server's do, and local changes go only to it.
second.change(['c', 'd']);
await tester.pumpAndSettle();
expect(_open(tester), ['c', 'd']);
final firstWrites = first.writes.length;
_workspace(tester).close(_workspace(tester).panes.last.id);
await tester.pumpAndSettle();
expect(second.open, ['c']);
expect(first.writes, hasLength(firstWrites));
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpAndSettle();
});
}
@@ -22,7 +22,7 @@ void main() {
tearDown(() => gateway.close());
testWidgets(
'Stop stays beside Send while running and interrupts this session',
'a running turn shows no stop button; Send stays and nothing interrupts',
(tester) async {
await tester.pumpWidget(
composerThread(gateway, newOperationId: nextOperation),
@@ -35,18 +35,9 @@ void main() {
await tester.pump();
expect(find.byTooltip(chatSendLabel), findsOneWidget);
expect(find.byTooltip(chatStopLabel), findsOneWidget);
final button = tester.widget<IconButton>(
find.byKey(const Key('chat-composer-stop')),
);
final scheme = Theme.of(
tester.element(find.byKey(const Key('chat-composer-stop'))),
).colorScheme;
expect(button.style?.backgroundColor?.resolve({}), scheme.error);
await tester.tap(find.byKey(const Key('chat-composer-stop')));
await tester.pumpAndSettle();
expect(gateway.interruptBodies.single, {'session_id': 's'});
expect(find.byKey(const Key('chat-composer-stop')), findsNothing);
expect(find.byTooltip(chatStopLabel), findsNothing);
expect(gateway.interruptBodies, isEmpty);
expect(gateway.promptBodies, isEmpty);
},
);
@@ -190,7 +181,7 @@ void main() {
reply.complete({'chat_queued': true});
await tester.pumpAndSettle();
expect(fieldText(tester), 'Newer draft');
expect(find.byKey(const Key('chat-composer-stop')), findsOneWidget);
expect(find.byKey(const Key('chat-composer-stop')), findsNothing);
expect(gateway.interruptBodies, isEmpty);
},
);
@@ -213,7 +204,7 @@ void main() {
text,
);
await tester.pump();
expect(find.byKey(const Key('chat-composer-stop')), findsOneWidget);
expect(find.byKey(const Key('chat-composer-stop')), findsNothing);
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pumpAndSettle();
expect(fieldText(tester), '');
@@ -228,7 +219,7 @@ void main() {
'op/2',
]);
expect(gateway.interruptBodies, isEmpty);
expect(find.byKey(const Key('chat-composer-stop')), findsOneWidget);
expect(find.byKey(const Key('chat-composer-stop')), findsNothing);
});
testWidgets('the composer wraps at 320 logical px with 2x text', (
@@ -267,6 +258,6 @@ void main() {
expect(tester.takeException(), isNull);
expect(find.byKey(const Key('chat-composer')), findsOneWidget);
expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget);
expect(find.byKey(const Key('chat-composer-stop')), findsOneWidget);
expect(find.byKey(const Key('chat-composer-stop')), findsNothing);
});
}
@@ -0,0 +1,161 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_command_palette.dart';
import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart';
import 'package:pipelines_app/features/chat/conversation/chat_escape_stop.dart';
import 'chat_composer_bar_fixtures.dart';
import 'chat_thread_fixtures.dart';
Finder get _border => find.byKey(const Key('chat-composer-running-border'));
Future<ComposerBarGateway> _pumpThread(WidgetTester tester) async {
final gateway = ComposerBarGateway()..page = fixtureTurn();
addTearDown(gateway.close);
await tester.pumpWidget(
composerThread(gateway, newOperationId: () => 'op/1'),
);
await tester.pumpAndSettle();
return gateway;
}
/// Starts a turn. The border repeats for as long as it runs, so the test
/// settles by pumping a frame, never by waiting for the tree to go quiet.
Future<void> _startTurn(WidgetTester tester, ComposerBarGateway gateway) async {
gateway.emitEvent(chatStepFrame('running'));
await tester.pump();
await tester.pump();
}
Future<void> _endTurn(WidgetTester tester, ComposerBarGateway gateway) async {
gateway.emitEvent(chatStepFrame('ended'));
await tester.pump();
await tester.pump();
}
void _reducedMotion(bool reduced) =>
TestWidgetsFlutterBinding.ensureInitialized()
.platformDispatcher
.accessibilityFeaturesTestValue = FakeAccessibilityFeatures(
disableAnimations: reduced,
);
void main() {
tearDown(() => _reducedMotion(false));
testWidgets('the border travels while a turn runs and is gone after it', (
tester,
) async {
_reducedMotion(false);
final gateway = await _pumpThread(tester);
expect(_border, findsNothing);
await _startTurn(tester, gateway);
expect(_border, findsOneWidget);
expect(tester.binding.transientCallbackCount, greaterThan(0));
await _endTurn(tester, gateway);
expect(_border, findsNothing);
expect(tester.binding.transientCallbackCount, 0);
});
testWidgets('reduced motion draws the static border and never ticks', (
tester,
) async {
_reducedMotion(true);
final gateway = await _pumpThread(tester);
await _startTurn(tester, gateway);
expect(_border, findsOneWidget);
expect(tester.binding.transientCallbackCount, 0);
await tester.pump(const Duration(seconds: 2));
expect(tester.binding.transientCallbackCount, 0);
});
testWidgets('no stop button appears while a turn runs', (tester) async {
final gateway = await _pumpThread(tester);
await _startTurn(tester, gateway);
expect(find.byKey(const Key('chat-composer-stop')), findsNothing);
expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget);
});
testWidgets('/stop sent in the composer stops the running turn', (
tester,
) async {
final gateway = await _pumpThread(tester);
await _startTurn(tester, gateway);
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'/stop',
);
await tester.pump();
// A draft that already names /stop runs on the first send.
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pump();
await tester.pump();
expect(gateway.interruptBodies, [
{'session_id': 's'},
]);
expect(gateway.promptBodies, isEmpty);
expect(find.text(chatStopCommandNotice), findsOneWidget);
});
testWidgets('two Escapes from the composer stop the turn', (tester) async {
final gateway = await _pumpThread(tester);
await _startTurn(tester, gateway);
await tester.tap(find.byKey(const Key('chat-composer-field')));
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(gateway.interruptBodies, isEmpty);
expect(find.text(chatEscapeStopHint), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
await tester.pump();
expect(gateway.interruptBodies, [
{'session_id': 's'},
]);
});
testWidgets('a single Escape does not stop the turn', (tester) async {
final gateway = await _pumpThread(tester);
await _startTurn(tester, gateway);
await tester.tap(find.byKey(const Key('chat-composer-field')));
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
await tester.pump(const Duration(seconds: 2));
expect(gateway.interruptBodies, isEmpty);
});
testWidgets('Escape closes the command palette first and does not count', (
tester,
) async {
final gateway = await _pumpThread(tester);
await _startTurn(tester, gateway);
await tester.enterText(find.byKey(const Key('chat-composer-field')), '/');
await tester.pump();
expect(find.byType(ChatCommandPalette), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.byType(ChatCommandPalette), findsNothing);
expect(gateway.interruptBodies, isEmpty);
// The palette's Escape was not the first of a pair; this one is.
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(gateway.interruptBodies, isEmpty);
});
testWidgets('Escape does nothing while no turn runs', (tester) async {
final gateway = await _pumpThread(tester);
await tester.tap(find.byKey(const Key('chat-composer-field')));
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(gateway.interruptBodies, isEmpty);
expect(find.text(chatEscapeStopHint), findsNothing);
});
}
@@ -0,0 +1,169 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_escape_stop.dart';
void main() {
group('ChatEscapeStopTracker', () {
test('a second press inside the window completes a pair', () {
final tracker = ChatEscapeStopTracker();
final start = DateTime(2026, 11, 12, 10);
expect(tracker.press(start), isFalse);
expect(
tracker.press(start.add(const Duration(milliseconds: 900))),
isTrue,
);
});
test('a press after the window starts a new pair', () {
final tracker = ChatEscapeStopTracker();
final start = DateTime(2026, 11, 12, 10);
expect(tracker.press(start), isFalse);
expect(tracker.press(start.add(const Duration(seconds: 2))), isFalse);
expect(
tracker.press(start.add(const Duration(seconds: 2, milliseconds: 500))),
isTrue,
);
});
test('reset forgets a pending first press', () {
final tracker = ChatEscapeStopTracker();
final start = DateTime(2026, 11, 12, 10);
tracker.press(start);
tracker.reset();
expect(
tracker.press(start.add(const Duration(milliseconds: 100))),
isFalse,
);
});
});
group('ChatEscapeStop', () {
late DateTime now;
late int stops;
setUp(() {
now = DateTime(2026, 11, 12, 10);
stops = 0;
});
Widget host({required bool running, Widget? child}) => MaterialApp(
home: Scaffold(
body: ChatEscapeStop(
running: running,
onStop: () => stops++,
clock: () => now,
child: child ?? const TextField(key: Key('field')),
),
),
);
testWidgets('a single Escape shows the hint and does not stop', (
tester,
) async {
await tester.pumpWidget(host(running: true));
await tester.tap(find.byKey(const Key('field')));
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(stops, 0);
expect(find.text(chatEscapeStopHint), findsOneWidget);
});
testWidgets('two Escapes within a second stop the turn once', (
tester,
) async {
await tester.pumpWidget(host(running: true));
await tester.tap(find.byKey(const Key('field')));
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
now = now.add(const Duration(milliseconds: 400));
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(stops, 1);
expect(find.text(chatEscapeStopHint), findsNothing);
});
testWidgets('two Escapes more than a second apart do not stop', (
tester,
) async {
await tester.pumpWidget(host(running: true));
await tester.tap(find.byKey(const Key('field')));
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
now = now.add(const Duration(milliseconds: 1500));
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(stops, 0);
});
testWidgets('an idle chat ignores Escape', (tester) async {
await tester.pumpWidget(host(running: false));
await tester.tap(find.byKey(const Key('field')));
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(stops, 0);
expect(find.text(chatEscapeStopHint), findsNothing);
});
testWidgets('focus on the transcript counts the same as the composer', (
tester,
) async {
await tester.pumpWidget(
host(
running: true,
child: const Focus(
autofocus: true,
child: SizedBox(width: 10, height: 10),
),
),
);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(stops, 1);
});
testWidgets('an Escape a descendant already handled never counts', (
tester,
) async {
await tester.pumpWidget(
host(
running: true,
child: Focus(
autofocus: true,
onKeyEvent: (_, event) =>
event.logicalKey == LogicalKeyboardKey.escape
? KeyEventResult.handled
: KeyEventResult.ignored,
child: const SizedBox(width: 10, height: 10),
),
),
);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(stops, 0);
expect(find.text(chatEscapeStopHint), findsNothing);
});
testWidgets('a held Escape is one press, not a pair', (tester) async {
await tester.pumpWidget(
host(
running: true,
child: const Focus(
autofocus: true,
child: SizedBox(width: 10, height: 10),
),
),
);
await tester.pump();
await tester.sendKeyDownEvent(LogicalKeyboardKey.escape);
await tester.sendKeyRepeatEvent(LogicalKeyboardKey.escape);
await tester.sendKeyRepeatEvent(LogicalKeyboardKey.escape);
await tester.sendKeyUpEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(stops, 0);
});
});
}
@@ -38,6 +38,15 @@ JsonMap permission({
if (decision.isNotEmpty) 'decision': decision,
};
Future<void> expectStopInMoreMenu(WidgetTester tester) async {
await tester.tap(find.byTooltip('More actions').hitTestable().first);
await tester.pumpAndSettle();
expect(find.text('Stop'), findsOneWidget);
await tester.tapAt(const Offset(1, 1));
await tester.pumpAndSettle();
expect(find.text('Stop'), findsNothing);
}
void main() {
test('recorded action, risk and options survive the card model', () {
final card = chatPermissionCard(permission(), '')!;
@@ -331,7 +340,8 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('Approve bash'), findsOneWidget);
expect(find.byTooltip('Stop'), findsOneWidget);
expect(find.byKey(const Key('chat-composer-stop')), findsNothing);
await expectStopInMoreMenu(tester);
gateway.emitRaw({
'type': 'chat_permission',
@@ -339,9 +349,10 @@ void main() {
});
await tester.pumpAndSettle();
// No filler line while the turn runs; Stop is the running signal.
// No filler line while the turn runs; the More menu keeps Stop reachable.
expect(find.byKey(const Key('chat-running')), findsNothing);
expect(find.byTooltip('Stop'), findsOneWidget);
expect(find.byKey(const Key('chat-composer-stop')), findsNothing);
await expectStopInMoreMenu(tester);
});
testWidgets('consecutive Material cards stay separate surfaces', (
@@ -0,0 +1,220 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
import 'package:pipelines_app/core/servers/server_context.dart';
import 'package:pipelines_app/features/chat/conversation/chat_seen_interaction.dart';
import 'package:pipelines_app/features/settings/server_connections.dart';
/// One open chat's pane: a field and a long transcript, both inside the region.
Widget _pane({
required VoidCallback onInteract,
ScrollController? scroll,
FocusNode? focus,
}) => MaterialApp(
home: Scaffold(
body: ChatSeenInteraction(
sessionId: 'ses_a',
onInteract: onInteract,
child: Column(
children: [
TextField(focusNode: focus),
Expanded(
child: ListView.builder(
controller: scroll,
itemCount: 200,
itemBuilder: (context, index) =>
SizedBox(height: 40, child: Text('row $index')),
),
),
],
),
),
),
);
void main() {
testWidgets('showing the pane reports nothing', (tester) async {
var count = 0;
await tester.pumpWidget(_pane(onInteract: () => count++));
await tester.pump();
await tester.pump(const Duration(seconds: 2));
expect(count, 0);
});
testWidgets('a programmatic scroll reports nothing', (tester) async {
var count = 0;
final scroll = ScrollController();
addTearDown(scroll.dispose);
await tester.pumpWidget(_pane(onInteract: () => count++, scroll: scroll));
scroll.jumpTo(600);
await tester.pump();
expect(count, 0);
});
testWidgets('a click or tap in the pane reports once per press', (
tester,
) async {
var count = 0;
await tester.pumpWidget(_pane(onInteract: () => count++));
await tester.tap(find.text('row 3'));
await tester.pump();
expect(count, greaterThanOrEqualTo(1));
});
testWidgets('a user drag of the transcript reports', (tester) async {
var count = 0;
await tester.pumpWidget(_pane(onInteract: () => count++));
await tester.drag(find.text('row 0'), const Offset(0, -300));
await tester.pumpAndSettle();
expect(count, greaterThanOrEqualTo(1));
});
testWidgets('a mouse-wheel scroll of the transcript reports', (tester) async {
var count = 0;
final scroll = ScrollController();
addTearDown(scroll.dispose);
await tester.pumpWidget(_pane(onInteract: () => count++, scroll: scroll));
final pointer = TestPointer(1, PointerDeviceKind.mouse);
await tester.sendEventToBinding(
pointer.hover(tester.getCenter(find.text('row 0'))),
);
await tester.sendEventToBinding(pointer.scroll(const Offset(0, 200)));
await tester.pumpAndSettle();
expect(scroll.offset, greaterThan(0));
expect(count, greaterThanOrEqualTo(1));
});
testWidgets('a key press while focus is in the pane reports, with no click', (
tester,
) async {
var count = 0;
final focus = FocusNode();
addTearDown(focus.dispose);
await tester.pumpWidget(_pane(onInteract: () => count++, focus: focus));
await tester.sendKeyEvent(LogicalKeyboardKey.keyA);
await tester.pump();
expect(count, 0, reason: 'a key with no focus in the pane is not its input');
focus.requestFocus();
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyA);
await tester.pump();
expect(count, 1);
});
testWidgets('code-driven focus into the pane reports nothing', (tester) async {
var count = 0;
final focus = FocusNode();
addTearDown(focus.dispose);
await tester.pumpWidget(_pane(onInteract: () => count++, focus: focus));
focus.requestFocus();
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(focus.hasFocus, isTrue);
expect(count, 0, reason: 'focus moved in code, with no key press, is passive');
});
testWidgets('Tab from outside the pane into it reports once', (tester) async {
var count = 0;
final outside = FocusNode();
final focus = FocusNode();
addTearDown(outside.dispose);
addTearDown(focus.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: [
TextField(focusNode: outside),
Expanded(
child: ChatSeenInteraction(
sessionId: 'ses_a',
onInteract: () => count++,
child: Column(
children: [
TextField(focusNode: focus),
const Expanded(child: SizedBox()),
],
),
),
),
],
),
),
),
);
outside.requestFocus();
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(focus.hasFocus, isTrue, reason: 'Tab moved focus into the pane');
expect(count, 1);
});
testWidgets('a notification tap that opened this chat reports once', (
tester,
) async {
var count = 0;
final connections = ServerConnections(
store: MemoryServerCatalogStore(
catalog: ServerCatalog(
servers: [
SavedServer.validated(
id: 'mac',
name: 'Mac',
endpoints: const ['ws://mac.test/connect'],
),
],
selectedId: 'mac',
),
),
onSelected: (_) async {},
);
addTearDown(connections.dispose);
await connections.load();
await tester.pumpWidget(
ServerContext(
connections: connections,
serverId: 'mac',
child: _pane(onInteract: () => count++),
),
);
await tester.pump();
expect(count, 0);
// Another chat's notification is not this pane's open.
connections.requestChatOpen('ses_other');
await tester.pump();
await tester.pump();
expect(count, 0);
connections.requestChatOpen('ses_a');
await tester.pump();
await tester.pump();
expect(count, 1);
// The tap is consumed: a later rebuild does not report it again.
connections.requestChatOpen('ses_other');
await tester.pump();
await tester.pump();
expect(count, 1);
});
}
@@ -1,174 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_stop_icon.dart';
import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart';
import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/ui/motion/motion.dart';
import 'chat_composer_bar_fixtures.dart';
class _CountPaint extends CustomPainter {
_CountPaint(this.onPaint);
final VoidCallback onPaint;
@override
void paint(Canvas canvas, Size size) => onPaint();
@override
bool shouldRepaint(_CountPaint oldDelegate) => false;
}
void main() {
setUp(() {
TestWidgetsFlutterBinding.ensureInitialized()
.platformDispatcher
.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures(
disableAnimations: false,
);
});
tearDown(() {
TestWidgetsFlutterBinding.ensureInitialized()
.platformDispatcher
.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures(
disableAnimations: true,
);
});
testWidgets('rotation repaints only the icon, not the surrounding chat', (
tester,
) async {
var paints = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: CustomPaint(
painter: _CountPaint(() => paints++),
child: const ChatStopIcon(child: Icon(Icons.stop)),
),
),
),
);
final before = paints;
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(paints, before);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets(
'Stop rotates linearly and continuously once every eight seconds',
(tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: ChatStopIcon(child: Icon(Icons.stop))),
),
);
RotationTransition rotation() =>
tester.widget(find.byKey(const Key('chat-stop-rotation')));
await tester.pump(const Duration(seconds: 2));
expect(rotation().turns.value, closeTo(0.25, 0.001));
await tester.pump(const Duration(seconds: 2));
expect(rotation().turns.value, closeTo(0.5, 0.001));
await tester.pump(const Duration(seconds: 8));
expect(rotation().turns.value, closeTo(0.5, 0.001));
await tester.pumpWidget(const SizedBox.shrink());
expect(tester.binding.transientCallbackCount, 0);
},
);
testWidgets('reduced motion stops/reset rotation and resumes when enabled', (
tester,
) async {
final reduce = ValueNotifier<bool>(true);
addTearDown(reduce.dispose);
await tester.pumpWidget(
MaterialApp(
home: ValueListenableBuilder<bool>(
valueListenable: reduce,
builder: (context, value, _) => MediaQuery(
data: MediaQuery.of(context).copyWith(disableAnimations: value),
child: const ChatStopIcon(child: Icon(Icons.stop)),
),
),
),
);
RotationTransition rotation() =>
tester.widget(find.byKey(const Key('chat-stop-rotation')));
await tester.pumpAndSettle();
expect(rotation().turns.value, 0);
expect(tester.binding.transientCallbackCount, 0);
reduce.value = false;
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(rotation().turns.value, closeTo(0.125, 0.001));
reduce.value = true;
await tester.pumpAndSettle();
expect(rotation().turns.value, 0);
expect(tester.binding.transientCallbackCount, 0);
});
testWidgets('TickerMode silences hidden Stop animation', (tester) async {
await tester.pumpWidget(
const MaterialApp(
home: TickerMode(
enabled: false,
child: ChatStopIcon(child: Icon(Icons.stop)),
),
),
);
await tester.pumpAndSettle();
expect(tester.binding.transientCallbackCount, 0);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets(
'rotating Stop keeps its target and interrupt action; Send stays available',
(tester) async {
final gateway = ComposerBarGateway();
addTearDown(gateway.close);
final composer = ChatComposerController(
gateway,
's',
drafts: MemoryChatDraftStore(),
);
addTearDown(composer.dispose);
final running = ValueNotifier<bool>(true);
addTearDown(running.dispose);
final bar = ValueListenableBuilder<bool>(
valueListenable: running,
builder: (_, value, _) =>
ChatComposerBar(composer: composer, running: value),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body: Center(child: bar)),
),
);
// The composer pops in first; Stop's target is measured once it has.
await tester.pump(Motion.tabEntranceDuration);
final stop = find.byKey(const Key('chat-composer-stop'));
final target = tester.getRect(stop);
await tester.pump(const Duration(seconds: 3));
expect(tester.getRect(stop), target);
expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget);
expect(
tester
.widget<RotationTransition>(
find.byKey(const Key('chat-stop-rotation')),
)
.turns
.value,
greaterThan(0),
);
await tester.tap(stop);
await tester.pump();
await tester.pump();
expect(gateway.interruptBodies, [
{'session_id': 's'},
]);
running.value = false;
await tester.pumpAndSettle();
expect(find.byType(ChatStopIcon), findsNothing);
expect(tester.binding.transientCallbackCount, 0);
},
);
}
@@ -0,0 +1,122 @@
import 'dart:async';
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_background_tasks.dart';
import 'package:pipelines_app/features/chat/conversation/chat_task_spinner.dart';
RotationTransition _rotation(WidgetTester tester) =>
tester.widget<RotationTransition>(
find.byKey(const Key('chat-background-tasks-spinner')),
);
Widget _spinner(bool spinning) => MaterialApp(
home: Scaffold(
body: ChatTaskSpinner(
spinning: spinning,
child: const Icon(Icons.layers_outlined, size: 16),
),
),
);
void _reducedMotion(bool reduced) =>
TestWidgetsFlutterBinding.ensureInitialized()
.platformDispatcher
.accessibilityFeaturesTestValue = FakeAccessibilityFeatures(
disableAnimations: reduced,
);
class _TasksGateway implements ApiGateway {
final _frames = StreamController<JsonMap>.broadcast();
List<JsonMap> running = const [];
@override
Stream<JsonMap> get frames => _frames.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (type == 'chat_shells') return {'chat_shells': running};
if (type == 'chat_automations') {
return {
'chat_automations': {'status': 'unavailable'},
};
}
return <String, dynamic>{};
}
void close() => _frames.close();
}
void main() {
tearDown(() => _reducedMotion(false));
testWidgets('turns once every period while spinning', (tester) async {
_reducedMotion(false);
await tester.pumpWidget(_spinner(true));
expect(_rotation(tester).turns.value, 0);
await tester.pump(ChatTaskSpinner.period ~/ 4);
expect(_rotation(tester).turns.value, closeTo(0.25, 0.01));
// Past one full lap the turn starts again from the top.
await tester.pump(
ChatTaskSpinner.period ~/ 4 * 3 + const Duration(milliseconds: 100),
);
expect(_rotation(tester).turns.value, closeTo(0.04, 0.01));
await tester.pumpWidget(const SizedBox.shrink());
expect(tester.binding.transientCallbackCount, 0);
});
testWidgets('stays still when not spinning, and stops when it stops', (
tester,
) async {
_reducedMotion(false);
await tester.pumpWidget(_spinner(false));
await tester.pump(const Duration(seconds: 2));
expect(_rotation(tester).turns.value, 0);
expect(tester.binding.transientCallbackCount, 0);
await tester.pumpWidget(_spinner(true));
await tester.pump(const Duration(milliseconds: 625));
expect(_rotation(tester).turns.value, greaterThan(0));
await tester.pumpWidget(_spinner(false));
await tester.pump();
expect(_rotation(tester).turns.value, 0);
await tester.pump(const Duration(seconds: 2));
expect(_rotation(tester).turns.value, 0);
expect(tester.binding.transientCallbackCount, 0);
});
testWidgets('reduced motion keeps the icon static even while spinning', (
tester,
) async {
_reducedMotion(true);
await tester.pumpWidget(_spinner(true));
await tester.pump(const Duration(seconds: 1));
expect(_rotation(tester).turns.value, 0);
expect(tester.binding.transientCallbackCount, 0);
});
testWidgets('the tasks icon rotates only while a task runs', (tester) async {
_reducedMotion(false);
final gateway = _TasksGateway();
addTearDown(gateway.close);
gateway.running = const [
{'id': 'sh1', 'status': 'running', 'command': 'go test ./...'},
];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatBackgroundTasks(gateway: gateway, sessionId: 's'),
),
),
);
// The spinning icon repeats forever, so settle by pumping, never by waiting.
await tester.pump();
await tester.pump();
expect(find.text('1 task'), findsOneWidget);
final before = _rotation(tester).turns.value;
await tester.pump(const Duration(milliseconds: 300));
expect(_rotation(tester).turns.value, greaterThan(before));
});
}
@@ -0,0 +1,46 @@
import 'package:flutter_test/flutter_test.dart';
import 'chat_composer_bar_fixtures.dart';
import 'chat_thread_fixtures.dart';
void main() {
Future<ComposerBarGateway> pumpThread(WidgetTester tester) async {
final gateway = ComposerBarGateway()..page = fixtureTurn();
addTearDown(gateway.close);
await tester.pumpWidget(
composerThread(gateway, newOperationId: () => 'op/1'),
);
await tester.pumpAndSettle();
return gateway;
}
testWidgets('the More menu offers Stop while a turn runs, for touch use', (
tester,
) async {
final gateway = await pumpThread(tester);
gateway.emitEvent(chatStepFrame('running'));
await tester.pump();
await tester.pump();
await tester.tap(find.byTooltip('More actions').hitTestable().first);
await tester.pumpAndSettle();
await tester.tap(find.text('Stop'));
await tester.pump();
await tester.pump();
expect(gateway.interruptBodies, [
{'session_id': 's'},
]);
expect(gateway.promptBodies, isEmpty);
});
testWidgets('the More menu has no Stop once the turn has ended', (
tester,
) async {
final gateway = await pumpThread(tester);
await tester.tap(find.byTooltip('More actions').hitTestable().first);
await tester.pumpAndSettle();
expect(find.text('Stop'), findsNothing);
expect(gateway.interruptBodies, isEmpty);
});
}
@@ -0,0 +1,376 @@
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/attention/runtime/attention_ack_queue.dart';
import 'package:pipelines_app/features/attention/runtime/attention_ack_sync.dart';
import 'package:pipelines_app/features/chat/data/chat_repository.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_seen_focus.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
import '../../../attention/runtime/fake_ack_server.dart';
import 'chat_test_harness.dart';
/// A chat reply in [id], as the server pushes it while the chat is live.
JsonMap _reply(String id) => {
'type': 'chat_event',
'chat_event': {'session_id': id, 'kind': 'text', 'delta': 'hello'},
};
/// One device's chat list, its shared acknowledgements and its window focus.
class _Device {
_Device(this.server, {required this.clock, bool focused = true})
: client = server.connect(),
local = MemoryChatSessionLocalStore(),
focus = ChatSeenFocus(focused: focused) {
sync = AttentionAckSync(gateway: client, queue: MemoryAttentionAckQueue());
bindAttentionAckSync(client, sync);
list = ChatSessionsController(
ChatRepository(client),
localStore: local,
nowMillis: () => clock(),
seenFocus: focus,
// Short enough to test quiet periods, long enough to settle under load.
activeAckDelay: const Duration(milliseconds: 60),
);
}
final FakeAckServer server;
final FakeAckClient client;
final MemoryChatSessionLocalStore local;
final ChatSeenFocus focus;
final int Function() clock;
late final AttentionAckSync sync;
late final ChatSessionsController list;
Future<void> start() async {
await sync.connected();
await list.refresh();
await settle();
}
JsonMap row(String id) => list.sessions.firstWhere((row) => row['id'] == id);
/// Whether [id] shows a New badge in the list (an open chat never does).
bool isNew(String id) => list.isUnseen(row(id));
/// Whether this device holds [id] as unread, whether or not it is open.
bool holdsUnread(String id) => local.state?.isUnseen(id) ?? false;
void dispose() {
list.dispose();
sync.dispose();
focus.dispose();
}
}
/// Lets a pending quiet-period acknowledgement fire (60 ms here) and settle.
Future<void> quietPeriod() async {
await Future<void>.delayed(const Duration(milliseconds: 200));
await settle();
}
void main() {
late FakeAckServer server;
var now = 5000;
setUp(() {
now = 5000;
server = FakeAckServer()
..chatSessions = [
{'id': 'ses_a', 'title': 'A', 'directory': '/w', 'updated_at': 1000},
{'id': 'ses_b', 'title': 'B', 'directory': '/w', 'updated_at': 1000},
];
});
void pushToAll(JsonMap frame) {
for (final client in server.clients) {
client.pushed.add(frame);
}
}
group('passive states never mark a chat seen', () {
test('a reply in an unfocused window stays New', () async {
final device = _Device(server, clock: () => now, focused: false);
addTearDown(device.dispose);
await device.start();
// Restored as the open chat, then the window is in the background.
device.list.activeSessionId = 'ses_a';
pushToAll(_reply('ses_a'));
await quietPeriod();
expect(server.state.chatSeen, isEmpty);
expect(device.holdsUnread('ses_a'), isTrue);
device.list.activeSessionId = null;
expect(device.isNew('ses_a'), isTrue);
});
test('a restored open chat with no interaction stays New', () async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
// A layout restored on start sets the open chat without any open.
device.list.activeSessionId = 'ses_a';
await settle();
pushToAll(_reply('ses_a'));
await quietPeriod();
expect(server.state.chatSeen, isEmpty);
expect(device.holdsUnread('ses_a'), isTrue);
});
testWidgets(
'a layout restored with a chat open, then a reply, leaves it New',
(tester) async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await tester.runAsync(device.start);
// The list screen is shown with the restored chat as its open conversation.
await tester.pumpWidget(
MaterialApp(
home: ChatSessionsScreen(
gateway: device.client,
onOpen: (_) {},
controller: device.list,
activeSessionId: 'ses_a',
localStore: device.local,
),
),
);
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
);
await tester.pump();
await tester.runAsync(() async {
pushToAll(_reply('ses_a'));
await quietPeriod();
});
await tester.pump();
expect(server.state.chatSeen, isEmpty);
expect(device.holdsUnread('ses_a'), isTrue);
},
);
test('an open chat left idle long after a reply stays New', () async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
await settle();
pushToAll(_reply('ses_a'));
now += 600000; // Ten minutes later, nothing touched it.
await quietPeriod();
expect(server.state.chatSeen, isEmpty);
expect(device.holdsUnread('ses_a'), isTrue);
});
test('a reply after backgrounding an engaged chat stays New, even '
'once the window is focused again without interaction', () async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
device.list.reportInteraction('ses_a');
await settle();
expect(server.state.chatSeen['ses_a'], 5000);
device.focus.focused = false;
now = 6000;
pushToAll(_reply('ses_a'));
await quietPeriod();
expect(server.state.chatSeen['ses_a'], 5000);
device.focus.focused = true;
now = 7000;
pushToAll(_reply('ses_a'));
await quietPeriod();
expect(server.state.chatSeen['ses_a'], 5000);
expect(device.holdsUnread('ses_a'), isTrue);
});
test('a reply in another chat while this one is open stays New', () async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
device.list.reportInteraction('ses_a');
await settle();
now = 6000;
pushToAll(_reply('ses_b'));
await quietPeriod();
expect(server.state.chatSeen.containsKey('ses_b'), isFalse);
expect(device.isNew('ses_b'), isTrue);
});
test('a reply after leaving an engaged chat stays New', () async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
device.list.reportInteraction('ses_a');
await settle();
device.list.activeSessionId = 'ses_b';
now = 6000;
pushToAll(_reply('ses_a'));
await quietPeriod();
expect(server.state.chatSeen['ses_a'], 5000);
expect(device.isNew('ses_a'), isTrue);
});
test('a reply still in its quiet period when the window loses focus '
'stays New, not seen', () async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
device.list.reportInteraction('ses_a');
await settle();
expect(server.state.chatSeen['ses_a'], 5000);
now = 6000;
pushToAll(_reply('ses_a'));
await settle(); // The reply is held in its quiet period, not yet acked.
device.focus.focused = false;
await quietPeriod();
expect(server.state.chatSeen['ses_a'], 5000);
expect(device.holdsUnread('ses_a'), isTrue);
});
test('a reply still in its quiet period when the user opens another '
'chat stays New, not seen', () async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
device.list.reportInteraction('ses_a');
await settle();
now = 6000;
pushToAll(_reply('ses_a'));
await settle();
device.list.activeSessionId = 'ses_b';
await quietPeriod();
expect(server.state.chatSeen['ses_a'], 5000);
expect(device.isNew('ses_a'), isTrue);
});
test('an interaction while the window is unfocused is ignored', () async {
final device = _Device(server, clock: () => now, focused: false);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
device.list.reportInteraction('ses_a');
await quietPeriod();
expect(server.state.chatSeen, isEmpty);
});
});
group('user interactions mark the chat seen', () {
test(
'an interaction in an unread open chat marks it seen up to now',
() async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
pushToAll(_reply('ses_a'));
await settle();
expect(device.holdsUnread('ses_a'), isTrue);
now = 6000;
device.list.reportInteraction('ses_a');
await settle();
expect(server.state.chatSeen['ses_a'], 6000);
expect(device.holdsUnread('ses_a'), isFalse);
expect(device.sync.pending.chatSeen, isEmpty);
},
);
test('opening a chat from the list marks it seen', () async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
pushToAll(_reply('ses_a'));
await settle();
now = 6000;
await device.list.markOpened(device.row('ses_a'));
await settle();
expect(server.state.chatSeen['ses_a'], 6000);
expect(device.holdsUnread('ses_a'), isFalse);
});
test(
'a reply after an interaction is marked seen once the chat is quiet',
() async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
device.list.reportInteraction('ses_a');
await settle();
now = 6000;
pushToAll(_reply('ses_a'));
await quietPeriod();
expect(server.state.chatSeen['ses_a'], 6000);
expect(device.holdsUnread('ses_a'), isFalse);
},
);
test(
'repeated interactions in an engaged, read chat send nothing more',
() async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
device.list.reportInteraction('ses_a');
await settle();
final sent = device.client.count('ack_attention');
// Scroll ticks and clicks after the first engagement.
for (var i = 0; i < 5; i++) {
device.list.reportInteraction('ses_a');
}
await settle();
expect(device.client.count('ack_attention'), sent);
},
);
test('an interaction in a visible chat that is not the open one marks it '
'seen', () async {
final device = _Device(server, clock: () => now);
addTearDown(device.dispose);
await device.start();
device.list.activeSessionId = 'ses_a';
pushToAll(_reply('ses_b'));
await settle();
expect(device.holdsUnread('ses_b'), isTrue);
now = 6000;
device.list.reportInteraction('ses_b');
await settle();
expect(server.state.chatSeen['ses_b'], 6000);
expect(device.holdsUnread('ses_b'), isFalse);
});
});
}
@@ -229,29 +229,32 @@ void main() {
expect(find.byKey(const Key('chat-row-unread')), findsOneWidget);
});
testWidgets('a tool call and reply in the open chat stay read on leaving', (
tester,
) async {
final fake = gateway();
await _pump(tester, fake, active: 's1');
fake.pushed.add(_tool('s1', 'running'));
fake.pushed.add(_tool('s1', 'completed'));
fake.pushed.add(_event('s1', delta: 'Here is the answer.'));
fake.pushed.add({
'type': 'chat_event',
'chat_event': {
'session_id': 's1',
'kind': 'step',
'step': {'status': 'ended'},
},
});
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-row-unread')), findsNothing);
testWidgets(
'a tool call and reply in the open chat stay New on leaving without interaction',
(tester) async {
final fake = gateway();
await _pump(tester, fake, active: 's1');
fake.pushed.add(_tool('s1', 'running'));
fake.pushed.add(_tool('s1', 'completed'));
fake.pushed.add(_event('s1', delta: 'Here is the answer.'));
fake.pushed.add({
'type': 'chat_event',
'chat_event': {
'session_id': 's1',
'kind': 'step',
'step': {'status': 'ended'},
},
});
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-row-unread')), findsNothing);
await _pump(tester, fake);
expect(find.byKey(const Key('chat-row-unread')), findsNothing);
expect(_store.state?.isUnseen('s1') ?? false, isFalse);
});
// The chat was open but the user never interacted with it, so the
// reply is not seen: it stays New after the chat is left.
await _pump(tester, fake);
expect(find.byKey(const Key('chat-row-unread')), findsOneWidget);
expect(_store.state?.isUnseen('s1') ?? false, isTrue);
},
);
testWidgets('only unresolved permission requests mark New', (tester) async {
final fake = gateway();
@@ -0,0 +1,211 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_controller.dart';
import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_gateway.dart';
/// Answers each chat_open_workspace call only when the test completes it.
class _Gateway implements ApiGateway {
final requests = <({JsonMap fields, Completer<JsonMap> reply})>[];
final _frames = StreamController<JsonMap>.broadcast();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
final reply = Completer<JsonMap>();
requests.add((fields: fields, reply: reply));
return reply.future;
}
@override
Stream<JsonMap> get frames => _frames.stream;
void push(int revision, List<String> ids) => _frames.add({
'type': 'chat_open_workspace_changed',
'chat_open_workspace': _snapshot(revision, ids),
});
void answer(
int index,
int revision,
List<String> ids, {
bool rejected = false,
}) => requests[index].reply.complete({
'type': 'chat_open_workspace',
'chat_open_workspace': _snapshot(revision, ids, rejected: rejected),
});
List<String> sentIds(int index) => [
for (final entry
in (requests[index].fields['chat_open_workspace_request']
as Map)['entries']
as List)
'${entry['session_id']}',
];
int base(int index) =>
(requests[index].fields['chat_open_workspace_request']
as Map)['base_revision'];
}
JsonMap _snapshot(int revision, List<String> ids, {bool rejected = false}) => {
'revision': revision,
'entries': [
for (final id in ids) {'session_id': id},
],
if (rejected) 'rejected': true,
};
List<ChatOpenWorkspaceEntry> _entries(List<String> ids) => [
for (final id in ids) ChatOpenWorkspaceEntry(id),
];
Future<(ChatOpenWorkspaceController, _Gateway, List<List<String>>)> _started({
int revision = 1,
List<String> ids = const ['a'],
}) async {
final gateway = _Gateway();
final applied = <List<String>>[];
final controller = ChatOpenWorkspaceController(gateway: gateway)
..onChanged = (snapshot) =>
applied.add(snapshot.entries.map((e) => e.sessionId).toList());
final started = controller.start(local: _entries(ids));
await pumpEventQueue();
expect(gateway.requests.single.fields['chat_open_workspace_request'], {
'entries': [
for (final id in ids) {'session_id': id},
],
'base_revision': 0,
'seed': true,
});
gateway.answer(0, revision, ids);
await started;
return (controller, gateway, applied);
}
void main() {
test('reads instead of seeding when the device has no chats', () async {
final gateway = _Gateway();
final controller = ChatOpenWorkspaceController(gateway: gateway);
final started = controller.start();
await pumpEventQueue();
expect(gateway.requests.single.fields, isEmpty);
gateway.answer(0, 4, ['x']);
await started;
expect(controller.revision, 4);
expect(controller.ready, isTrue);
});
test(
'serializes writes and sends the latest from the replied revision',
() async {
final (controller, gateway, _) = await _started();
controller.replace(_entries(['a', 'b']));
controller.replace(_entries(['a', 'b', 'c']));
controller.replace(_entries(['c', 'a', 'b']));
await pumpEventQueue();
// One write in flight; the two later ones coalesced behind it.
expect(gateway.requests, hasLength(2));
expect(gateway.sentIds(1), ['a', 'b']);
expect(gateway.base(1), 1);
gateway.answer(1, 2, ['a', 'b']);
await pumpEventQueue();
expect(gateway.requests, hasLength(3));
expect(gateway.sentIds(2), ['c', 'a', 'b']);
expect(gateway.base(2), 2);
gateway.answer(2, 3, ['c', 'a', 'b']);
await pumpEventQueue();
expect(controller.revision, 3);
// An unchanged set is not sent again.
controller.replace(_entries(['c', 'a', 'b']));
await pumpEventQueue();
expect(gateway.requests, hasLength(3));
},
);
test('a late reply never overwrites a newer pushed revision', () async {
final (controller, gateway, applied) = await _started();
controller.replace(_entries(['a', 'b']));
await pumpEventQueue();
// Another device's change (revision 3) is pushed before this write's
// reply (revision 2) arrives.
gateway.push(3, ['z']);
await pumpEventQueue();
gateway.answer(1, 2, ['a', 'b']);
await pumpEventQueue();
expect(controller.revision, 3);
expect(applied.last, ['z']);
// Older and repeated pushes are ignored.
gateway.push(2, ['a', 'b']);
gateway.push(3, ['z']);
await pumpEventQueue();
expect(applied, [
['a'],
['z'],
]);
});
test(
'a refused stale write applies the server state and drops queued ones',
() async {
final (controller, gateway, applied) = await _started();
controller.replace(_entries(['a', 'b']));
await pumpEventQueue();
controller.replace(_entries(['a', 'b', 'c']));
gateway.answer(1, 5, ['q'], rejected: true);
await pumpEventQueue();
expect(applied.last, ['q']);
expect(controller.revision, 5);
expect(gateway.requests, hasLength(2));
// The next change is derived from the server's state.
controller.replace(_entries(['q', 'r']));
await pumpEventQueue();
expect(gateway.base(2), 5);
},
);
test('a push applied while writing replaces the queued write', () async {
final (controller, gateway, applied) = await _started();
controller.replace(_entries(['a', 'b']));
await pumpEventQueue();
controller.replace(_entries(['a', 'b', 'c']));
gateway.push(4, ['b']);
await pumpEventQueue();
expect(applied.last, ['b']);
gateway.answer(1, 4, ['b'], rejected: true);
await pumpEventQueue();
expect(gateway.requests, hasLength(2));
});
test('dispose stops pushes and writes', () async {
final (controller, gateway, applied) = await _started();
controller.dispose();
gateway.push(9, ['late']);
controller.replace(_entries(['x']));
await pumpEventQueue();
expect(applied, [
['a'],
]);
expect(gateway.requests, hasLength(1));
});
test(
'stays local-only when the server does not answer the request',
() async {
final gateway = _Gateway();
final controller = ChatOpenWorkspaceController(gateway: gateway);
final started = controller.start(local: _entries(['a']));
await pumpEventQueue();
gateway.requests.single.reply.completeError(StateError('unknown type'));
await started;
expect(controller.ready, isFalse);
controller.replace(_entries(['a', 'b']));
await pumpEventQueue();
expect(gateway.requests, hasLength(1));
// A server push (a reconnect) brings it up to date and enables writes.
gateway.push(2, ['a']);
await pumpEventQueue();
expect(controller.ready, isTrue);
},
);
}
@@ -0,0 +1,38 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_gateway.dart';
void main() {
test('decodes bounded ordered membership and floating state', () {
final snapshot = ChatOpenWorkspaceSnapshot.fromJson({
'revision': 7,
'entries': [
{'session_id': 'ses_a', 'floating': true},
{'session_id': 'ses_b'},
],
});
expect(snapshot?.revision, 7);
expect(snapshot?.entries.map((entry) => entry.sessionId), [
'ses_a',
'ses_b',
]);
expect(snapshot?.entries.first.floating, isTrue);
});
test('rejects duplicate and oversized snapshots', () {
expect(
ChatOpenWorkspaceSnapshot.fromJson({
'entries': [
{'session_id': 'ses_a'},
{'session_id': 'ses_a'},
],
}),
isNull,
);
expect(
ChatOpenWorkspaceSnapshot.fromJson({
'entries': List.generate(65, (index) => {'session_id': 'ses_$index'}),
}),
isNull,
);
});
}
@@ -0,0 +1,56 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart';
List<String> _sessions(ChatWorkspaceController c) =>
c.panes.map((pane) => pane.sessionId).toList();
ChatWorkspaceController _three() {
final c = ChatWorkspaceController()..open('a');
c.splitActive('b', ChatSplitAxis.vertical);
c.splitActive('c', ChatSplitAxis.horizontal);
c.resize(c.root!.id, .3);
return c;
}
void main() {
test('a remote removal drops only that pane and keeps the geometry', () {
final c = _three();
final paneA = c.panes.first.id;
final paneC = c.panes.last.id;
c.reconcileSessions(['a', 'c']);
expect(_sessions(c), ['a', 'c']);
expect(c.panes.map((pane) => pane.id), [paneA, paneC]);
expect((c.root as ChatWorkspaceSplit).ratio, .3);
});
test('a reorder moves panes with their ids and keeps the splits', () {
final c = _three();
final ids = {for (final pane in c.panes) pane.sessionId: pane.id};
final splitId = c.root!.id;
c.reconcileSessions(['c', 'a', 'b']);
expect(_sessions(c), ['c', 'a', 'b']);
expect(c.panes.map((pane) => pane.id), [ids['c'], ids['a'], ids['b']]);
expect(c.root!.id, splitId);
expect((c.root as ChatWorkspaceSplit).ratio, .3);
});
test('new chats split off and an unchanged set notifies nothing', () {
final c = ChatWorkspaceController()..open('a');
c.reconcileSessions(['a', 'b']);
expect(_sessions(c), ['a', 'b']);
var notified = 0;
c.addListener(() => notified++);
c.reconcileSessions(['a', 'b']);
expect(notified, 0);
c.reconcileSessions(const []);
expect(c.panes, isEmpty);
expect(c.activePane, isNull);
});
test('the active pane moves on when its chat is removed', () {
final c = _three();
expect(c.activePane?.sessionId, 'c');
c.reconcileSessions(['b']);
expect(c.activePane?.sessionId, 'b');
});
}