Merge main into run token usage branch

This commit is contained in:
2026-11-03 22:21:38 +00:00
118 changed files with 4294 additions and 1483 deletions
@@ -244,7 +244,7 @@ void main() {
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text('Download'), findsOneWidget);
expect(find.text('Share'), findsOneWidget);
expect(find.text('Open'), findsOneWidget);
expect(find.text('Open in browser'), findsOneWidget);
expect(find.text('Copy link'), findsOneWidget);
await tester.tap(find.text('Download'));
@@ -0,0 +1,42 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_html_links.dart';
void main() {
const inDocument = ArtifactHtmlLinkAction.inDocument;
const external = ArtifactHtmlLinkAction.external;
const blocked = ArtifactHtmlLinkAction.blocked;
final cases = <String, ArtifactHtmlLinkAction>{
'#section-2': inDocument,
' #top ': inDocument,
'about:blank': inDocument,
'about:blank#section-2': inDocument,
'about:srcdoc#top': inDocument,
'https://example.com/report': external,
'HTTP://Example.com': external,
'http://127.0.0.1:8080/x': external,
'mailto:ops@example.com': external,
'javascript:alert(1)': blocked,
' JavaScript:alert(1)': blocked,
'file:///etc/passwd': blocked,
'data:text/html,<b>x</b>': blocked,
'about:config': blocked,
'intent://scan#Intent;end': blocked,
'tel:+15551234': blocked,
'report.html': blocked,
'../7/2/other.html': blocked,
'/api/runs': blocked,
'//example.com/x': blocked,
'http:no-host': blocked,
'': blocked,
};
for (final entry in cases.entries) {
test(
'${entry.key.isEmpty ? '(empty)' : entry.key} -> ${entry.value.name}',
() {
expect(artifactHtmlLinkAction(entry.key), entry.value);
},
);
}
}
@@ -0,0 +1,180 @@
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:pipelines_app/features/artifacts/domain/artifact_groups.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_fullscreen.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_body.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart';
import 'artifact_visit_list_fixture.dart';
const _endpoint = 'ws://127.0.0.1:8081/connect';
const _shellBar = Key('shell-tab-bar');
final ArtifactRecord _report = recordedArtifact(
'report.html',
url: '/artifacts/1/1/report.html',
contentType: 'text/html',
);
final ArtifactRecord _log = recordedArtifact(
'build.log',
url: '/artifacts/1/1/build.log',
contentType: 'text/plain',
);
final ArtifactGroup _group = visitGroup(artifacts: [_report, _log]);
/// Each rendered HTML document, with whether it rendered in full screen.
typedef _Rendered = List<(String, bool)>;
Future<({_Rendered rendered, List<Uri> opened})> _pump(
WidgetTester tester, {
bool cupertino = false,
}) async {
final rendered = <(String, bool)>[];
final opened = <Uri>[];
final page = ArtifactViewerPage(
groups: [_group],
selectedIdentity: artifactVisitIdentity(_group, _report),
configuredEndpoint: _endpoint,
fetch: (uri) async => ArtifactFetchResult(
status: 200,
bytes: utf8.encode(uri.path.endsWith('.html') ? '<h1>Hi</h1>' : 'ok'),
),
openExternal: (uri) async {
opened.add(uri);
return true;
},
htmlBuilder: (context, html) {
rendered.add((html, ArtifactFullscreenScope.maybeOf(context) != null));
return Text('html:$html');
},
);
// A stand-in for the shell: a nested navigator holding the viewer above a
// tab bar the full-screen view must cover.
final shell = Column(
children: [
Expanded(
child: Navigator(
onGenerateRoute: (_) => cupertino
? CupertinoPageRoute<void>(builder: (_) => page)
: MaterialPageRoute<void>(builder: (_) => page),
),
),
const SizedBox(key: _shellBar, height: 56, child: Text('Tabs')),
],
);
await tester.pumpWidget(
cupertino ? CupertinoApp(home: shell) : MaterialApp(home: shell),
);
await tester.pumpAndSettle();
return (rendered: rendered, opened: opened);
}
Future<void> _enter(WidgetTester tester) async {
await tester.tap(find.byKey(artifactFullscreenKey));
await tester.pumpAndSettle();
}
/// A bar control by its accessible name: the Material button's tooltip, the
/// Cupertino button's semantics label.
Finder _named(bool cupertino, String name) =>
cupertino ? find.bySemanticsLabel(name) : find.byTooltip(name);
void main() {
for (final cupertino in [false, true]) {
final host = cupertino ? 'Cupertino' : 'Material';
testWidgets('$host: the bottom actions offer Full screen', (tester) async {
final result = await _pump(tester, cupertino: cupertino);
final bar = find.byKey(const Key('artifact-viewer-actions'));
expect(
find.descendant(of: bar, matching: find.byKey(artifactFullscreenKey)),
findsOneWidget,
);
expect(_named(cupertino, 'Full screen'), findsOneWidget);
expect(result.rendered.single, ('<h1>Hi</h1>', false));
});
testWidgets('$host: full screen covers the shell, keeps the actions and '
'renders the fetched document in the app', (tester) async {
final result = await _pump(tester, cupertino: cupertino);
await _enter(tester);
expect(find.byKey(_shellBar), findsNothing);
// The same document, fetched once with the app's session, now in the
// full-screen scope; nothing was handed to the system browser.
expect(result.rendered.last, ('<h1>Hi</h1>', true));
expect(result.opened, isEmpty);
final bar = find.byKey(const Key('artifact-viewer-actions'));
expect(bar, findsOneWidget);
for (final key in const [
Key('artifact-open'),
Key('artifact-copy-link'),
artifactPreviousKey,
artifactNextKey,
]) {
expect(find.descendant(of: bar, matching: find.byKey(key)), findsOne);
}
expect(_named(cupertino, 'Exit full screen'), findsOneWidget);
expect(_named(cupertino, 'Open in browser'), findsOneWidget);
});
testWidgets('$host: Exit full screen returns to the viewer', (
tester,
) async {
await _pump(tester, cupertino: cupertino);
await _enter(tester);
await tester.tap(find.byKey(artifactFullscreenKey));
await tester.pumpAndSettle();
expect(find.byKey(_shellBar), findsOneWidget);
expect(_named(cupertino, 'Full screen'), findsOneWidget);
});
}
testWidgets('Escape and the system back leave full screen', (tester) async {
await _pump(tester);
await _enter(tester);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(find.byKey(_shellBar), findsOneWidget);
expect(find.text('html:<h1>Hi</h1>'), findsOneWidget);
await _enter(tester);
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.byKey(_shellBar), findsOneWidget);
// Back left full screen only, not the viewer as well.
expect(find.text('html:<h1>Hi</h1>'), findsOneWidget);
});
testWidgets('paging in full screen follows the viewer, any kind', (
tester,
) async {
await _pump(tester);
await _enter(tester);
await tester.tap(find.byKey(artifactNextKey));
await tester.pumpAndSettle();
expect(find.text('build.log'), findsOneWidget);
expect(find.byKey(const Key('artifact-text-preview')), findsOneWidget);
expect(find.byKey(_shellBar), findsNothing);
await tester.tap(find.byKey(artifactFullscreenKey));
await tester.pumpAndSettle();
expect(find.text('build.log'), findsOneWidget);
expect(find.byKey(_shellBar), findsOneWidget);
});
test('zoom steps walk the list and hold at both ends', () {
expect(artifactHtmlZoomStep(1, 1), 1.1);
expect(artifactHtmlZoomStep(1, -1), 0.9);
expect(artifactHtmlZoomStep(4, 1), 4);
expect(artifactHtmlZoomStep(0.5, -1), 0.5);
expect(artifactHtmlZoomStep(1.3, -1), 1.25);
});
}
@@ -188,7 +188,7 @@ void main() {
expect(find.byType(ArtifactViewerPage), findsNothing);
expect(_dialog(platform, 'session.html'), findsOneWidget);
expect(_dialog(platform, 'text/plain · 512\u00a0B'), findsOneWidget);
await tester.tap(_dialog(platform, 'Open'));
await tester.tap(_dialog(platform, 'Open in browser'));
await tester.pumpAndSettle();
expect(find.byType(ArtifactViewerPage), findsNothing);
expect(opened, [
@@ -214,7 +214,7 @@ void main() {
);
await tester.tap(find.text('result.zip'));
await tester.pumpAndSettle();
await tester.tap(_inDialog(_Platform.material, 'Open'));
await tester.tap(_inDialog(_Platform.material, 'Open in browser'));
await tester.pumpAndSettle();
expect(opened, [
@@ -243,7 +243,7 @@ void main() {
),
findsOneWidget,
);
expect(_inDialog(_Platform.material, 'Open'), findsNothing);
expect(_inDialog(_Platform.material, 'Open in browser'), findsNothing);
expect(_inDialog(_Platform.material, 'Copy link'), findsNothing);
});
@@ -270,7 +270,7 @@ void main() {
_inDialog(_Platform.material, 'No artifact URL recorded.'),
findsOneWidget,
);
expect(_inDialog(_Platform.material, 'Open'), findsNothing);
expect(_inDialog(_Platform.material, 'Open in browser'), findsNothing);
});
testWidgets('Copy link copies the resolved url, separate from Open', (
@@ -504,7 +504,7 @@ void main() {
}
expect(orderOf('Close'), lessThan(orderOf('Copy link')));
expect(orderOf('Copy link'), lessThan(orderOf('Open')));
expect(orderOf('Copy link'), lessThan(orderOf('Open in browser')));
},
);
}
@@ -488,7 +488,9 @@ void main() {
});
held.complete(const {});
await tester.pumpAndSettle();
expect(find.text(chatQuestionAnswered), findsOneWidget);
// The answered question leaves the card list (chat_question_group_test).
expect(find.text(chatQuestionWaiting), findsNothing);
expect(find.text('Colour · Red · +1 more'), findsOneWidget);
});
testWidgets('a refused question keeps the card open with the server reason', (
@@ -0,0 +1,301 @@
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_question_card_model.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_group.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
JsonMap _turn(String id) => {
'kind': 'assistant',
'key': id,
'messageIds': [id],
'parts': const [],
};
JsonMap _card(
String id, {
String? raisedIn,
bool resolved = false,
bool cancelled = false,
String? error,
}) => {
'kind': 'question',
'key': 'chat-question-$id',
'form': {
'id': id,
'resolved': resolved,
'cancelled': cancelled,
chatQuestionRaisedIn: ?raisedIn,
},
'error': error,
};
JsonMap _form({String id = 'form-1'}) => {
'id': id,
'session_id': 's',
'kind': 'question',
'title': 'Database',
'fields': [
{
'key': 'q0',
'title': 'Which database?',
'type': 'string',
'required': true,
'options': [
{'value': 'pg', 'label': 'Postgres'},
{'value': 'lite', 'label': 'SQLite'},
],
},
],
};
const _chip = 'Which database? · Postgres';
/// A chat whose agent turn `a1` is the one the question arrives during.
Future<FakeChatGateway> _open(
WidgetTester tester,
Size size, {
bool cupertino = false,
}) async {
await tester.binding.setSurfaceSize(size);
addTearDown(() => tester.binding.setSurfaceSize(null));
final gateway = FakeChatGateway()
..history = (_) async => chatPage([
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': 'Ship the release.'},
],
),
chatMessage(
'a1',
'assistant',
parts: [
{'type': 'text', 'text': 'Which database first?'},
],
),
]);
addTearDown(gateway.close);
final view = ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {});
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: view))
: MaterialApp(home: Scaffold(body: view)),
);
await tester.pumpAndSettle();
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': _form()});
await tester.pumpAndSettle();
expect(find.text(chatQuestionWaiting), findsOneWidget);
return gateway;
}
Future<void> _answerPostgres(WidgetTester tester) async {
await tester.tap(find.text('Postgres'));
await tester.pump();
await tester.tap(find.text(chatQuestionSubmit));
await tester.pumpAndSettle();
}
void _expectCollapsed() {
expect(find.text(chatQuestionWaiting), findsNothing);
expect(find.text(chatQuestionSubmit), findsNothing);
expect(find.text(chatQuestionAnswered), findsNothing);
expect(find.text(_chip), findsOneWidget);
// The chip sits in its turn's footer, under the turn that asked.
expect(
find.descendant(
of: find.byKey(const Key('chat-message-footer')),
matching: find.text(_chip),
),
findsOneWidget,
);
}
void main() {
test('settled questions join the turn they were raised during', () {
final rows = groupSettledQuestions([
_turn('m1'),
_turn('m2'),
_card('a', raisedIn: 'm1', resolved: true),
_card('b', raisedIn: 'm2', cancelled: true),
]);
expect(rows.map((r) => r['kind']), ['assistant', 'assistant']);
expect(chatRowQuestions(rows[0]).map((f) => f['id']), ['a']);
expect(chatRowQuestions(rows[1]).map((f) => f['id']), ['b']);
});
test('questions naming no turn share one row; open ones stay cards', () {
final rows = groupSettledQuestions([
_turn('m1'),
_card('loose-1', resolved: true),
_card('pending', raisedIn: 'm1'),
_card('refused', raisedIn: 'm1', error: 'no longer awaiting'),
_card('loose-2', raisedIn: 'paged-out', resolved: true),
]);
expect(rows.map((r) => r['kind']), [
'assistant',
'questions',
'question',
'question',
]);
expect(rows[0].containsKey('questions'), isFalse);
expect(chatRowQuestions(rows[1]).map((f) => f['id']), [
'loose-1',
'loose-2',
]);
});
test('the summary names the question and its outcome', () {
final form = _form();
expect(
chatQuestionSummary({
...form,
'resolved': true,
'answers': {'q0': 'pg'},
}),
_chip,
);
expect(
chatQuestionSummary({
...form,
'resolved': true,
'answers': {'q0': 'pg', 'extra': 'x'},
}),
'$_chip · +1 more',
);
expect(
chatQuestionSummary({...form, 'cancelled': true}),
'Which database? · Expired',
);
expect(
chatQuestionSummary({...form, 'resolved': true}),
'Which database? · Closed',
);
});
for (final (name, size) in [
('narrow', const Size(390, 844)),
('wide', const Size(1280, 900)),
]) {
testWidgets('$name: an acknowledged answer collapses into its turn at once '
'(Claude Code: the ack is the only signal)', (tester) async {
final gateway = await _open(tester, size);
final held = Completer<JsonMap>();
gateway.answer = (_) => held.future;
await tester.tap(find.text('Postgres'));
await tester.pump();
await tester.tap(find.text(chatQuestionSubmit));
await tester.pump();
// Still the card while the reply is in flight.
expect(find.text(chatQuestionWaiting), findsOneWidget);
held.complete(const {'type': 'chat_answer'});
await tester.pumpAndSettle();
_expectCollapsed();
// A late replay of the pending frame cannot reopen it.
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': _form()});
await tester.pumpAndSettle();
_expectCollapsed();
await tester.tap(find.text(_chip));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-question-sheet')), findsOneWidget);
expect(find.text('Which database?'), findsOneWidget);
expect(find.text('Postgres'), findsOneWidget);
expect(find.text(chatQuestionAnswered), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('$name: a refused answer keeps the full card with the reason', (
tester,
) async {
final gateway = await _open(tester, size);
gateway.answer = (_) async =>
throw StateError('the question is no longer awaiting an answer');
await _answerPostgres(tester);
expect(find.textContaining('no longer awaiting'), findsOneWidget);
expect(find.text(chatQuestionWaiting), findsOneWidget);
expect(find.text(chatQuestionSubmit), findsOneWidget);
expect(find.text(_chip), findsNothing);
});
}
testWidgets('OpenCode/Codex: the server resolution collapses a question '
'answered elsewhere', (tester) async {
final gateway = await _open(tester, const Size(390, 844));
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': {'id': 'form-1', 'session_id': 's', 'resolved': true},
});
await tester.pumpAndSettle();
expect(find.text(chatQuestionWaiting), findsNothing);
expect(find.text('Which database? · Closed'), findsOneWidget);
});
testWidgets('a cancelled question collapses as expired', (tester) async {
final gateway = await _open(tester, const Size(390, 844));
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': {'id': 'form-1', 'session_id': 's', 'cancelled': true},
});
await tester.pumpAndSettle();
expect(find.text(chatQuestionWaiting), findsNothing);
expect(find.text('Which database? · Expired'), findsOneWidget);
});
testWidgets('OpenCode: ack then form.replied leaves one collapsed row', (
tester,
) async {
final gateway = await _open(tester, const Size(390, 844));
gateway.answer = (_) async {
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': {'id': 'form-1', 'session_id': 's', 'resolved': true},
});
return const {'type': 'chat_answer'};
};
await _answerPostgres(tester);
_expectCollapsed();
});
testWidgets('Cupertino: the answered question collapses to the native chip', (
tester,
) async {
final gateway = await _open(tester, const Size(390, 844), cupertino: true);
gateway.answer = (_) async => const {'type': 'chat_answer'};
await _answerPostgres(tester);
_expectCollapsed();
expect(tester.takeException(), isNull);
});
testWidgets('after a reload the answered question stays gone', (
tester,
) async {
final gateway = await _open(tester, const Size(390, 844));
gateway.answer = (_) async => const {'type': 'chat_answer'};
await _answerPostgres(tester);
_expectCollapsed();
// A fresh view over the same server: the subscribe replays only pending
// forms, and this one is no longer pending.
await tester.pumpWidget(const SizedBox());
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
),
);
await tester.pumpAndSettle();
expect(find.text('Which database first?'), findsOneWidget);
expect(find.text(chatQuestionWaiting), findsNothing);
});
}
@@ -0,0 +1,264 @@
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/data/chat_repository.dart';
import 'package:pipelines_app/features/chat/domain/chat_list_activity.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 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
/// The list shows every chat's live activity from the server: a spinner while
/// a turn runs, a quieter badge while only background tasks run, nothing when
/// idle. `chat_activity` pushes reach chats this device never opened, and an
/// older server (no `activity`) leaves the list as before.
JsonMap _row(String id, {JsonMap? activity}) => {
'id': id,
'title': 'Chat $id',
'directory': '/w',
'updated_at': 1000,
'activity': ?activity,
};
JsonMap _activity({bool turn = false, int tasks = 0, int seq = 1}) => {
if (turn) 'turn_running': true,
if (tasks > 0) 'background_tasks': tasks,
'seq': seq,
};
JsonMap _push(
String id, {
bool turn = false,
int tasks = 0,
required int seq,
}) => {
'type': 'chat_activity',
'chat_activity': {
'session_id': id,
..._activity(turn: turn, tasks: tasks, seq: seq),
},
};
/// The row merges its semantics, so the badge's label is part of the row's.
Finder _label(int tasks) => find.bySemanticsLabel(
RegExp(RegExp.escape('Background tasks running ($tasks)')),
);
Finder _badge(String id) => find.descendant(
of: find.byKey(Key('chat-row-$id')),
matching: find.byKey(const Key('chat-row-background')),
);
Finder _spinner(String id) => find.descendant(
of: find.byKey(Key('chat-row-$id')),
matching: find.byKey(const Key('chat-row-working')),
);
Future<void> _pump(
WidgetTester tester,
FakeChatGateway fake, {
bool cupertino = false,
}) async {
final screen = ChatSessionsScreen(
gateway: fake,
onOpen: (_) {},
localStore: MemoryChatSessionLocalStore(),
);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: screen)
: MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: screen,
),
);
// A spinner never settles, so pump a few frames instead.
for (var i = 0; i < 5; i++) {
await tester.pump(const Duration(milliseconds: 50));
}
}
Future<void> _frames(WidgetTester tester) async {
await tester.pump();
await tester.pump();
}
void main() {
testWidgets(
'listed activity draws a spinner, a background badge or nothing',
(tester) async {
final fake = FakeChatGateway()
..sessionsReply = {
'chat_sessions': [
_row('run', activity: _activity(turn: true, tasks: 1)),
_row('bg', activity: _activity(tasks: 2)),
_row('idle', activity: _activity()),
],
};
await _pump(tester, fake);
expect(_spinner('run'), findsOneWidget);
expect(_badge('run'), findsNothing, reason: 'the turn spinner wins');
expect(_spinner('bg'), findsNothing);
expect(_badge('bg'), findsOneWidget);
expect(_spinner('idle'), findsNothing);
expect(_badge('idle'), findsNothing);
expect(_label(2), findsOneWidget);
final tooltip = tester.widget<Tooltip>(_badge('bg'));
expect(tooltip.message, 'Background tasks running (2)');
expect(tooltip.triggerMode, TooltipTriggerMode.manual);
expect(
find.descendant(of: _badge('bg'), matching: find.byIcon(Icons.pending)),
findsOneWidget,
);
expect(
find.descendant(
of: _badge('bg'),
matching: find.byType(CircularProgressIndicator),
),
findsNothing,
reason: 'the background badge is not a second spinner',
);
},
);
testWidgets('pushes move a chat this device never opened', (tester) async {
final fake = FakeChatGateway()
..sessionsReply = {
'chat_sessions': [_row('s1', activity: _activity(seq: 10))],
};
await _pump(tester, fake);
expect(_spinner('s1'), findsNothing);
fake.pushed.add(_push('s1', turn: true, seq: 11));
await _frames(tester);
expect(_spinner('s1'), findsOneWidget);
fake.pushed.add(_push('s1', tasks: 3, seq: 13));
await _frames(tester);
expect(_spinner('s1'), findsNothing);
expect(_label(3), findsOneWidget);
// A push older than the snapshot already applied is ignored.
fake.pushed.add(_push('s1', turn: true, seq: 12));
await _frames(tester);
expect(_spinner('s1'), findsNothing);
expect(_badge('s1'), findsOneWidget);
fake.pushed.add(_push('s1', seq: 14));
await _frames(tester);
expect(_badge('s1'), findsNothing);
expect(_spinner('s1'), findsNothing);
expect(fake.count('chat_sessions'), 1);
});
testWidgets('an older server without activity keeps the old spinner', (
tester,
) async {
final fake = FakeChatGateway()
..sessionsReply = {
'chat_sessions': [_row('s1')],
};
await _pump(tester, fake);
expect(_badge('s1'), findsNothing);
expect(_spinner('s1'), findsNothing);
fake.pushed.add({
'type': 'chat_event',
'chat_event': {
'session_id': 's1',
'kind': 'step',
'step': {'status': 'started'},
},
});
await _frames(tester);
expect(_spinner('s1'), findsOneWidget);
expect(_badge('s1'), findsNothing);
});
testWidgets('the Cupertino host draws its own glyph', (tester) async {
final fake = FakeChatGateway()
..sessionsReply = {
'chat_sessions': [_row('bg', activity: _activity(tasks: 1))],
};
await _pump(tester, fake, cupertino: true);
expect(
find.descendant(
of: _badge('bg'),
matching: find.byIcon(CupertinoIcons.ellipsis_circle_fill),
),
findsOneWidget,
);
expect(_label(1), findsOneWidget);
});
group('controller', () {
late FakeChatGateway fake;
late ChatSessionsController controller;
late List<JsonMap> rows;
setUp(() {
fake = FakeChatGateway();
fake.sessionsHandler = () async => {'chat_sessions': rows};
controller = ChatSessionsController(
ChatRepository(fake),
localStore: MemoryChatSessionLocalStore(),
);
});
tearDown(() => controller.dispose());
JsonMap row() => controller.sessions.single;
test('a list read older than an applied push keeps the push', () async {
rows = [_row('s1', activity: _activity(seq: 5))];
await controller.refresh();
fake.pushed.add(_push('s1', tasks: 2, seq: 7));
await Future<void>.delayed(Duration.zero);
expect(chatSessionBackgroundTasks(row()), 2);
rows = [_row('s1', activity: _activity(seq: 6))];
await controller.refresh();
expect(chatSessionBackgroundTasks(row()), 2);
expect(row()['running'], false);
});
test('a newer list read (a reconnect) replaces the pushed state', () async {
rows = [_row('s1', activity: _activity(seq: 5))];
await controller.refresh();
fake.pushed.add(_push('s1', turn: true, tasks: 2, seq: 7));
await Future<void>.delayed(Duration.zero);
expect(row()['running'], true);
rows = [_row('s1', activity: _activity(seq: 90))];
await controller.refresh();
expect(row()['running'], false);
expect(chatSessionBackgroundTasks(row()), 0);
});
});
test('chatListActivityOf reads rows and pushes and refuses malformed', () {
expect(
chatListActivityOf({
'turn_running': true,
'background_tasks': 2,
'seq': 9,
}, sessionId: 's1'),
(sessionId: 's1', turnRunning: true, backgroundTasks: 2, seq: 9),
);
expect(chatListActivityOf({'session_id': 's2'}), (
sessionId: 's2',
turnRunning: false,
backgroundTasks: 0,
seq: 0,
));
expect(chatListActivityOf({'background_tasks': 1}), isNull);
expect(chatListActivityOf('nope', sessionId: 's1'), isNull);
expect(
chatListActivityOf({
'background_tasks': -4,
}, sessionId: 's1')?.backgroundTasks,
0,
);
});
}
@@ -67,6 +67,25 @@ JsonMap _event(String id, {String kind = 'text', String? delta}) => {
},
};
JsonMap _tool(String id, String status) => {
'type': 'chat_event',
'chat_event': {
'session_id': id,
'kind': 'tool',
'part': {
'type': 'tool',
'state': {
'status': status,
if (status == 'completed')
'content': [
{'type': 'text', 'text': 'command output'},
],
if (status == 'error') 'error': 'exit status 1',
},
},
},
};
void main() {
setUp(() => _store = MemoryChatSessionLocalStore());
@@ -176,46 +195,79 @@ void main() {
expect(find.byType(CircularProgressIndicator), findsNothing);
});
testWidgets('tool starts are loading; returned tool results are unread', (
testWidgets('tool calls and their results are loading, never New', (
tester,
) async {
final fake = gateway();
await _pump(tester, fake);
fake.pushed.add({
'type': 'chat_event',
'chat_event': {
'session_id': 's1',
'kind': 'tool',
'part': {
'type': 'tool',
'state': {'status': 'running'},
},
},
});
fake.pushed.add(_tool('s1', 'running'));
await tester.pump();
await tester.pump();
expect(find.byKey(const Key('chat-row-unread')), findsNothing);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
fake.pushed.add(_tool('s1', 'completed'));
fake.pushed.add(_tool('s1', 'error'));
// Harness notices, agent reports, a prompt from another device and
// whitespace-only deltas around a tool call are not a reply either.
fake.pushed.add({
'type': 'chat_event',
'chat_event': {
'session_id': 's1',
'kind': 'tool',
'part': {
'type': 'tool',
'state': {
'status': 'completed',
'content': [
{'type': 'text', 'text': 'command output'},
],
},
},
'kind': 'text',
'delta': 'Background task finished',
'message_kind': 'notice',
},
});
fake.pushed.add({
'type': 'chat_event',
'chat_event': {
'session_id': 's1',
'kind': 'text',
'delta': 'Subagent report',
'message_kind': 'agent_report',
},
});
fake.pushed.add({
'type': 'chat_event',
'chat_event': {'session_id': 's1', 'kind': 'user', 'delta': 'hi'},
});
fake.pushed.add(_event('s1', delta: '\n\n'));
// The turn is still working, so its spinner never settles.
await tester.pump();
await tester.pump();
expect(find.byKey(const Key('chat-row-unread')), findsNothing);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
// The assistant's reply after the tool call is what is unread.
fake.pushed.add(_event('s1', delta: 'Done: tests pass.'));
await tester.pump();
await tester.pump();
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')), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
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);
});
testWidgets('only unresolved permission requests mark New', (tester) async {
@@ -37,4 +37,44 @@ void main() {
});
expect(intermediate!.running, isNull);
});
test('only visible assistant reply text is unread', () {
bool attention(Map<String, Object?> event) =>
chatSessionFrameEffect({
'type': 'chat_event',
'chat_event': {'session_id': 's', ...event},
})!.attention;
for (final status in ['running', 'completed', 'error']) {
expect(
attention({
'kind': 'tool',
'part': {
'type': 'tool',
'state': {
'status': status,
'content': [
{'type': 'text', 'text': 'out'},
],
'error': status == 'error' ? 'failed' : null,
},
},
}),
isFalse,
reason: 'tool $status',
);
}
expect(attention({'kind': 'user', 'delta': 'prompt'}), isFalse);
expect(attention({'kind': 'text', 'delta': ' \n'}), isFalse);
for (final messageKind in ['notice', 'agent_report']) {
expect(
attention({
'kind': 'text',
'delta': 'x',
'message_kind': messageKind,
}),
isFalse,
);
}
expect(attention({'kind': 'text', 'delta': 'answer'}), isTrue);
});
}
@@ -0,0 +1,113 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_link_launcher.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart';
import 'chat_markdown_test_support.dart';
// A mouse click on a link opens it even when the pointer moves a few pixels
// between press and release: the selection area used to claim that press as a
// selection drag after 2 px, so ordinary clicks in the browser opened nothing.
void main() {
late List<Uri> opened;
Future<RenderParagraph> pump(WidgetTester tester) async {
await phoneViewport(tester);
opened = [];
await tester.pumpWidget(
ChatLinkScope(
launcher: (uri) async {
opened.add(uri);
return true;
},
child: markdownHost(
const ChatMarkdownView(text: 'go [here](https://x.com/c) now'),
),
),
);
await tester.pumpAndSettle();
return tester.renderObject<RenderParagraph>(find.byType(RichText).first);
}
Offset centreOf(RenderParagraph paragraph, String text) {
final start = paragraph.text.toPlainText().indexOf(text);
final box = paragraph.getBoxesForSelection(
TextSelection(baseOffset: start, extentOffset: start + text.length),
);
return paragraph.localToGlobal(box.first.toRect().center);
}
Future<void> mouseDrag(WidgetTester tester, Offset from, double dx) async {
final mouse = await tester.startGesture(
from,
kind: PointerDeviceKind.mouse,
);
await tester.pump();
// Three moves, as a hand drifts during a click or drags.
for (var i = 1; i <= 3; i++) {
await mouse.moveTo(from + Offset(dx * i / 3, 0));
await tester.pump();
}
await mouse.up();
await tester.pumpAndSettle();
await mouse.removePointer();
}
for (final dx in [0.0, 3.0, 8.0]) {
testWidgets(
'a mouse click moving ${dx}px opens the link',
(tester) async {
final paragraph = await pump(tester);
await mouseDrag(tester, centreOf(paragraph, 'here'), dx);
expect(opened.map((uri) => '$uri'), ['https://x.com/c']);
},
variant: TargetPlatformVariant.desktop(),
);
}
testWidgets(
'dragging off a link opens nothing',
(tester) async {
final paragraph = await pump(tester);
await mouseDrag(tester, centreOf(paragraph, 'here'), 40);
expect(opened, isEmpty);
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets(
'a mouse drag from plain text still selects across the link',
(tester) async {
final paragraph = await pump(tester);
final from = centreOf(paragraph, 'go');
await mouseDrag(tester, from, centreOf(paragraph, 'now').dx - from.dx);
expect(opened, isEmpty);
String? copied;
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
copied = (call.arguments as Map)['text'] as String?;
}
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
await tester.sendKeyDownEvent(LogicalKeyboardKey.meta);
await tester.sendKeyEvent(LogicalKeyboardKey.keyC);
await tester.sendKeyUpEvent(LogicalKeyboardKey.meta);
await tester.pump();
// The link claims only presses on itself; this drag selects across it.
expect(copied, contains('o here n'));
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
}