merge(app): land chat-layout

This commit is contained in:
2026-10-22 15:07:11 +01:00
14 changed files with 931 additions and 95 deletions
@@ -297,43 +297,68 @@ class _ChatThreadViewState extends State<ChatThreadView> {
children: [
Padding(
key: const Key('chat-thread-header'),
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 16, 4),
child: Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
_backButton(cupertino),
if (widget.title.trim().isNotEmpty)
Text(
widget.title.trim(),
style: cupertino
? CupertinoTheme.of(
context,
).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleLarge,
),
if (widget.session != null &&
supportsChatModels(
'${widget.session!['backend'] ?? ''}',
))
ChatModelControl(
key: ValueKey<String>(
'chat-model-${widget.sessionId}',
padding: const EdgeInsetsDirectional.fromSTEB(4, 0, 4, 4),
child: LayoutBuilder(
builder: (context, constraints) {
final title = widget.title.trim();
final session = widget.session;
final hasModel =
session != null &&
supportsChatModels('${session['backend'] ?? ''}');
// One compact row, as on the web: back, the conversation's
// name, its model and the information action. The title
// takes the remaining width and ellipsises; the model keeps
// a bounded share so neither control is pushed off a narrow
// 2x phone and the header never wraps onto a second line.
return Row(
children: [
_backButton(cupertino),
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: 4,
),
child: title.isEmpty
? const SizedBox.shrink()
: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: cupertino
? CupertinoTheme.of(
context,
).textTheme.navTitleTextStyle
: Theme.of(
context,
).textTheme.titleLarge,
),
),
),
gateway: widget.gateway,
sessionId: widget.sessionId,
session: widget.session!,
onChanged: widget.onModelChanged,
),
ChatBarAction(
key: const Key('chat-info'),
label: 'Chat information',
onPressed: _openInfo,
materialIcon: Icons.info_outline,
cupertinoIcon: CupertinoIcons.info,
),
],
if (hasModel)
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: constraints.maxWidth * 0.4,
),
child: ChatModelControl(
key: ValueKey<String>(
'chat-model-${widget.sessionId}',
),
gateway: widget.gateway,
sessionId: widget.sessionId,
session: session,
onChanged: widget.onModelChanged,
),
),
ChatBarAction(
key: const Key('chat-info'),
label: 'Chat information',
onPressed: _openInfo,
materialIcon: Icons.info_outline,
cupertinoIcon: CupertinoIcons.info,
),
],
);
},
),
),
if (initialLoad)
@@ -472,24 +497,31 @@ class _ChatThreadViewState extends State<ChatThreadView> {
return ChatMessageView(row: row, textBuilder: chatMarkdownText);
}
Widget _backButton(bool cupertino) => cupertino
? CupertinoButton(
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 0),
onPressed: widget.onBack,
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(CupertinoIcons.back),
SizedBox(width: 4),
Text('Back'),
],
),
)
: TextButton.icon(
onPressed: widget.onBack,
icon: const Icon(Icons.arrow_back),
label: const Text('Back to chats'),
);
/// The header's compact Back control, matching the web's icon-only control.
/// Its accessible name states the destination; Material keeps a tooltip and
/// Cupertino the same label on the wrapping node.
Widget _backButton(bool cupertino) {
const label = 'Back to chats';
final icon = Icon(cupertino ? CupertinoIcons.back : Icons.arrow_back);
if (!cupertino) {
return IconButton(
key: const Key('chat-back'),
tooltip: label,
onPressed: widget.onBack,
icon: icon,
);
}
return Semantics(
label: label,
button: true,
child: CupertinoButton(
key: const Key('chat-back'),
padding: EdgeInsets.zero,
onPressed: widget.onBack,
child: icon,
),
);
}
}
/// The native dismiss control shared by a local notice and a running
@@ -41,6 +41,19 @@ String chatSessionActivity({required bool running, required bool unseen}) =>
? 'new'
: 'idle';
/// A server timestamp as epoch milliseconds. Accepts an epoch number or an
/// ISO-8601 string and reports `0` for anything unusable, so callers never
/// invent a time for a missing field.
int chatSessionMillis(Object? value) {
if (value is int) return value > 0 ? value : 0;
if (value is num) return value > 0 ? value.toInt() : 0;
final text = '${value ?? ''}'.trim();
if (text.isEmpty) return 0;
final number = int.tryParse(text);
if (number != null) return number > 0 ? number : 0;
return DateTime.tryParse(text)?.millisecondsSinceEpoch ?? 0;
}
/// Native reported values only; missing and invalid values remain unavailable.
JsonMap? chatUsageSnapshot(Object? value) {
if (value is! Map || value is List) return null;
@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';
import '../../../../core/api_gateway.dart';
import '../../../../core/transport/connection_state.dart';
import '../../data/chat_repository.dart';
import '../../domain/chat_sessions.dart';
import 'chat_session_local.dart';
/// Owns the session list, its refresh generation and the shared row actions.
@@ -56,7 +57,7 @@ class ChatSessionsController extends ChangeNotifier {
session['closed'] == true) {
return false;
}
final updatedAt = _millis(session['updated_at']);
final updatedAt = chatSessionMillis(session['updated_at']);
return updatedAt > 0 && updatedAt > _local.watermark(id);
}
@@ -145,7 +146,7 @@ class ChatSessionsController extends ChangeNotifier {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
await _ensureLocal();
final next = _local.read(id, _millis(session['updated_at']));
final next = _local.read(id, chatSessionMillis(session['updated_at']));
if (identical(next, _local)) return;
_local = next;
_notify();
@@ -211,7 +212,7 @@ class ChatSessionsController extends ChangeNotifier {
for (final session in _sessions)
(
id: '${session['id'] ?? ''}',
updatedAt: _millis(session['updated_at']),
updatedAt: chatSessionMillis(session['updated_at']),
),
]);
if (identical(next, _local)) return;
@@ -227,16 +228,6 @@ class ChatSessionsController extends ChangeNotifier {
}
}
static int _millis(Object? value) {
if (value is int) return value > 0 ? value : 0;
if (value is num) return value > 0 ? value.toInt() : 0;
final text = '${value ?? ''}'.trim();
if (text.isEmpty) return 0;
final number = int.tryParse(text);
if (number != null) return number > 0 ? number : 0;
return DateTime.tryParse(text)?.millisecondsSinceEpoch ?? 0;
}
void _notify() {
if (!_disposed) notifyListeners();
}
@@ -5,6 +5,7 @@ import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_content.dart';
import 'session_row_style.dart';
class CupertinoSessionList extends StatelessWidget {
@@ -118,12 +119,37 @@ class _CupertinoSessionRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
final id = '${session['id'] ?? ''}';
final subtitle = sessionSubtitle(session, unseen: unseen);
// Cupertino's grouped list owns the separators and the native tile metrics;
// the row only decides where the title, its muted meta and the recency go.
// The recency sits at the trailing edge of the title line at the tile's
// body size; the meta line keeps the tile's native 12pt subtitle style by
// passing colour only, so `Text` merges with `CupertinoListTile`'s own
// `DefaultTextStyle` instead of overriding it with the title's size.
final theme = CupertinoTheme.of(context);
final secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
final timeStyle = theme.textTheme.textStyle.copyWith(color: secondary);
final time = relativeChatSessionTime(session['updated_at']);
final meta = chatSessionMeta(session);
final status = chatSessionRowStatus(session, unseen: unseen);
final statusStyle = TextStyle(
color: status == 'Closed' ? secondary : theme.primaryColor,
);
return CupertinoListTile(
key: Key('chat-row-$id'),
leading: Icon(sessionCupertinoIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(subtitle),
title: ChatSessionRowTitle(
title: chatSessionTitle(session),
time: time,
timeStyle: timeStyle,
),
subtitle: meta.isEmpty && status == null
? null
: ChatSessionRowMeta(
meta: meta,
status: status,
metaStyle: TextStyle(color: secondary),
statusStyle: statusStyle,
),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
@@ -5,6 +5,7 @@ import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_content.dart';
import 'session_row_style.dart';
class MaterialSessionList extends StatelessWidget {
@@ -71,7 +72,13 @@ class MaterialSessionList extends StatelessWidget {
group.directory.isEmpty ? 'No directory' : group.directory,
),
),
for (final session in group.sessions) ..._row(session),
// Material's native list separator between rows in a group, the
// counterpart of the inset group's hairline on Cupertino. The group
// header still owns the boundary between directories.
for (var i = 0; i < group.sessions.length; i++) ...[
if (i > 0) const Divider(height: 1),
..._row(group.sessions[i]),
],
],
],
);
@@ -126,11 +133,38 @@ class _MaterialSessionRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
final id = '${session['id'] ?? ''}';
// The same content as the Cupertino row: title with trailing recency, then
// a muted `directory · model` line with the unread/closed word trailing.
// `ListTile` does not force one ellipsised line like `CupertinoListTile`,
// so both text widgets state their line limit themselves. The meta line
// passes colour only, so it keeps the tile's native subtitle style.
final theme = Theme.of(context);
final secondary = theme.colorScheme.onSurfaceVariant;
final timeStyle =
theme.textTheme.bodyMedium?.copyWith(color: secondary) ??
TextStyle(color: secondary);
final time = relativeChatSessionTime(session['updated_at']);
final meta = chatSessionMeta(session);
final status = chatSessionRowStatus(session, unseen: unseen);
final statusStyle = TextStyle(
color: status == 'Closed' ? secondary : theme.colorScheme.primary,
);
return ListTile(
key: Key('chat-row-$id'),
leading: Icon(sessionMaterialIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(sessionSubtitle(session, unseen: unseen)),
title: ChatSessionRowTitle(
title: chatSessionTitle(session),
time: time,
timeStyle: timeStyle,
),
subtitle: meta.isEmpty && status == null
? null
: ChatSessionRowMeta(
meta: meta,
status: status,
metaStyle: TextStyle(color: secondary),
statusStyle: statusStyle,
),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
@@ -0,0 +1,106 @@
import 'package:flutter/material.dart';
/// The title line of a chat session row: the session's name, with its relative
/// recency at the trailing edge. Shared by the Material and Cupertino rows so
/// both hosts arrange the same facts the same way.
///
/// The recency takes at most 45% of the text column and ellipsises there, so a
/// long title keeps the larger share and a short row never overflows. The
/// recency is supplementary: at very large text scales it is the part that
/// gives way, while the session's name and state word stay whole.
class ChatSessionRowTitle extends StatelessWidget {
const ChatSessionRowTitle({
super.key,
required this.title,
required this.time,
required this.timeStyle,
});
final String title;
final String time;
final TextStyle timeStyle;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) => Row(
children: [
Expanded(
child: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis),
),
if (time.isNotEmpty) ...[
const SizedBox(width: 8),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: constraints.maxWidth * 0.45,
),
child: Text(
time,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: timeStyle,
),
),
],
],
),
);
}
}
/// The muted second line of a chat session row: the recorded directory and
/// model, with the unread/closed word at the trailing edge.
///
/// The directory/model is the part that ellipsises; the state word is the row's
/// only unread marker, so it keeps its intrinsic width and the metadata shrinks
/// first. If even the whole text column cannot hold the word at the current
/// text scale it is scaled down rather than clipped, so `New`/`Closed` is never
/// replaced by an ellipsis.
class ChatSessionRowMeta extends StatelessWidget {
const ChatSessionRowMeta({
super.key,
required this.meta,
required this.status,
required this.metaStyle,
required this.statusStyle,
});
final String meta;
final String? status;
final TextStyle metaStyle;
final TextStyle statusStyle;
/// The trailing word's intrinsic width is measured against the full text
/// column, minus this gap, so the row can never overflow the line.
static const _statusGap = 8.0;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) => Row(
children: [
Expanded(
child: Text(
meta,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: metaStyle,
),
),
if (status != null)
ConstrainedBox(
constraints: BoxConstraints(maxWidth: constraints.maxWidth),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: _statusGap),
child: FittedBox(
fit: BoxFit.scaleDown,
alignment: AlignmentDirectional.centerEnd,
child: Text(status!, maxLines: 1, style: statusStyle),
),
),
),
],
),
);
}
}
@@ -23,21 +23,62 @@ String sessionActionsLabel(JsonMap session, Set<String> duplicateTitles) {
: 'Chat actions for $title';
}
String sessionSubtitle(JsonMap session, {bool? unseen}) {
final directory = '${session['directory'] ?? ''}';
switch (chatSessionActivity(
running: session['running'] == true,
unseen: unseen ?? session['unseen'] == true,
)) {
case 'streaming':
return '$directory · Streaming';
case 'new':
return '$directory · New';
default:
return directory;
}
/// The web row's relative recency: `just now`, `N min ago`, `N hr ago`,
/// `N days ago`, then a short date (`22 Oct`). A row without a usable
/// `updated_at` reports nothing rather than inventing a time.
String relativeChatSessionTime(Object? updatedAt, {DateTime? now}) {
final millis = chatSessionMillis(updatedAt);
if (millis <= 0) return '';
final then = DateTime.fromMillisecondsSinceEpoch(millis);
var elapsed = (now ?? DateTime.now()).difference(then);
if (elapsed.isNegative) elapsed = Duration.zero;
final seconds = elapsed.inSeconds;
if (seconds < 45) return 'just now';
final minutes = seconds ~/ 60 < 1 ? 1 : seconds ~/ 60;
if (minutes < 60) return '$minutes min ago';
final hours = minutes ~/ 60;
if (hours < 24) return '$hours hr ago';
final days = hours ~/ 24;
if (days < 7) return days == 1 ? '1 day ago' : '$days days ago';
return '${then.day} ${_shortMonths[then.month - 1]}';
}
/// The row's muted second line: the directory the chat runs in, plus the model
/// the server recorded for it. Both come from the row; nothing is inferred.
String chatSessionMeta(JsonMap session) => [
'${session['directory'] ?? ''}'.trim(),
'${session['model'] ?? ''}'.trim(),
].where((part) => part.isNotEmpty).join(' · ');
/// The word on the row's trailing edge while the session has news or a state:
/// `Closed` from the row, otherwise `New`. A streaming session deliberately
/// says nothing, as on the web, where the row's activity logo carries it.
String? chatSessionRowStatus(JsonMap session, {required bool unseen}) {
if (session['closed_at'] != null || session['closed'] == true) {
return 'Closed';
}
// Streaming has no word, as on the web; the row's activity icon carries it.
if (session['running'] == true) return null;
return unseen ? 'New' : null;
}
const _shortMonths = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
// `Intl.DateTimeFormat('en-GB', { month: 'short' })`, which the web row
// uses, abbreviates September as `Sept`, not `Sep`.
'Sept',
'Oct',
'Nov',
'Dec',
];
IconData sessionMaterialIcon(JsonMap session) {
if (session['running'] == true) return Icons.sync;
if (session['starred'] == true) return Icons.star;
@@ -205,7 +205,9 @@ void main() {
await tester.pump();
expect(find.text('A live line arrived.'), findsOneWidget);
await tester.tap(find.text(cupertino ? 'Back' : 'Back to chats'));
// One compact icon-only Back control in the thread header; its
// accessible name is the destination, and both hosts share the key.
await tester.tap(find.byKey(const Key('chat-back')));
await tester.pump();
expect(provider.value.uri.path, '/chat');
expect(find.byType(ChatThreadView), findsNothing);
@@ -89,7 +89,7 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('model-b'), findsOneWidget);
await tester.tap(find.text('Back to chats'));
await tester.tap(find.byKey(const Key('chat-back')));
await tester.pumpAndSettle();
expect(find.text('model-b'), findsNothing);
@@ -0,0 +1,131 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
const _title = 'A conversation title long enough to need an ellipsis at 320px';
const _session = <String, dynamic>{
'id': 's',
'backend': 'opencode',
'model': 'provider/an-extremely-long-recorded-model-id',
'model_provider': 'p1',
};
Widget _host(Widget child, {required bool cupertino}) => cupertino
? CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(child: child),
)
: MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
void _useNarrowText(WidgetTester tester) {
tester.view.physicalSize = const Size(320, 640);
tester.view.devicePixelRatio = 1;
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
}
void main() {
for (final cupertino in [false, true]) {
final host = cupertino ? 'Cupertino' : 'Material';
testWidgets('$host header keeps back, title, model and actions on one row', (
tester,
) async {
_useNarrowText(tester);
final semantics = tester.ensureSemantics();
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
gateway.subscribe = () async => const {};
var backed = 0;
await tester.pumpWidget(
_host(
ChatThreadView(
gateway: gateway,
sessionId: 's',
title: _title,
session: _session,
onBack: () => backed++,
),
cupertino: cupertino,
),
);
await tester.pumpAndSettle();
final title = find.text(_title);
final model = find.byKey(const Key('chat-model'));
final info = find.byKey(const Key('chat-info'));
final back = find.byKey(const Key('chat-back'));
expect(title, findsOneWidget);
expect(model, findsOneWidget);
expect(info, findsOneWidget);
expect(back, findsOneWidget);
expect(tester.takeException(), isNull);
// The icon-only control still states its destination for assistive use.
if (cupertino) {
expect(find.bySemanticsLabel('Back to chats'), findsOneWidget);
} else {
expect(find.byTooltip('Back to chats'), findsOneWidget);
}
// One row, in the web's order: back, title, model, information. A wrapped
// header would put the controls on a different line from the title.
double centerY(Finder finder) => tester.getCenter(finder).dy;
expect((centerY(back) - centerY(title)).abs(), lessThan(16));
expect((centerY(model) - centerY(title)).abs(), lessThan(16));
expect((centerY(info) - centerY(title)).abs(), lessThan(16));
double right(Finder finder) => tester.getTopRight(finder).dx;
expect(right(back), lessThanOrEqualTo(tester.getTopLeft(title).dx));
expect(right(title), lessThanOrEqualTo(tester.getTopLeft(model).dx));
expect(right(model), lessThanOrEqualTo(tester.getTopLeft(info).dx));
await tester.tap(back);
await tester.pump();
expect(backed, 1);
semantics.dispose();
});
}
testWidgets('a conversation without a model keeps the same compact row', (
tester,
) async {
_useNarrowText(tester);
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
gateway.subscribe = () async => const {};
await tester.pumpWidget(
_host(
ChatThreadView(
gateway: gateway,
sessionId: 's',
title: _title,
session: {..._session, 'backend': 'claude'},
onBack: () {},
),
cupertino: false,
),
);
await tester.pumpAndSettle();
expect(find.text(_title), findsOneWidget);
expect(find.byKey(const Key('chat-model')), findsNothing);
expect(
(tester.getCenter(find.byKey(const Key('chat-info'))).dy -
tester.getCenter(find.text(_title)).dy)
.abs(),
lessThan(16),
);
expect(tester.takeException(), isNull);
});
}
@@ -54,18 +54,18 @@ void main() {
],
};
await pumpMaterialChat(tester, gateway);
expect(find.text('/work · New'), findsNothing);
expect(find.text('New'), findsNothing);
updatedAt = 2000;
await tester.tap(find.byKey(const Key('chat-refresh')));
await tester.pumpAndSettle();
expect(find.text('/work · New'), findsOneWidget);
expect(find.text('New'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-row-s1')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-refresh')));
await tester.pumpAndSettle();
expect(find.text('/work · New'), findsNothing);
expect(find.text('New'), findsNothing);
});
testWidgets('a closed row never reports New after newer activity', (
@@ -86,7 +86,7 @@ void main() {
],
};
await pumpMaterialChat(tester, gateway);
expect(find.text('/work · New'), findsNothing);
expect(find.text('New'), findsNothing);
// Another device moved the chat on and closed it after this device read it.
updatedAt = 2000;
@@ -94,8 +94,14 @@ void main() {
await tester.tap(find.byKey(const Key('chat-refresh')));
await tester.pumpAndSettle();
expect(find.text('/work · New'), findsNothing);
expect(find.text('Closed'), findsOneWidget);
expect(find.text('New'), findsNothing);
expect(
find.descendant(
of: find.byKey(const Key('chat-row-s1')),
matching: find.text('Closed'),
),
findsOneWidget,
);
});
testWidgets('Material row refusal is readable at 320px 2x dark', (
@@ -0,0 +1,256 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/ui/sessions/session_list_cupertino.dart';
import 'package:pipelines_app/features/chat/ui/sessions/session_row_style.dart';
/// A grouped Cupertino list, the host the web client runs on macOS/iOS.
Future<void> _pumpRows(
WidgetTester tester,
List<JsonMap> sessions, {
bool Function(JsonMap)? isUnseen,
}) async {
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(
child: CupertinoSessionList(
sections: [(title: 'Chats', sessions: sessions)],
emptyMessage: null,
duplicateTitles: const {},
onOpen: (_) {},
onRename: (_) {},
onClose: (_) {},
onReopen: (_) {},
onStar: (_) {},
onHide: (_) {},
onClearSearch: null,
isUnseen: isUnseen ?? (_) => false,
errorFor: (_) => null,
),
),
),
);
await tester.pumpAndSettle();
}
void _useNarrowText(WidgetTester tester) {
tester.view.physicalSize = const Size(320, 640);
tester.view.devicePixelRatio = 1;
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
}
/// The resolved style a text is painted with, after merging with the host's
/// own `DefaultTextStyle`.
TextStyle _styleOf(WidgetTester tester, String text) =>
tester.renderObject<RenderParagraph>(find.text(text)).text.style!;
void main() {
test('relative recency uses the web wording and never invents a time', () {
final now = DateTime(2026, 10, 22, 12);
final from = now.subtract;
expect(relativeChatSessionTime(null, now: now), '');
expect(relativeChatSessionTime(0, now: now), '');
expect(
relativeChatSessionTime(now.millisecondsSinceEpoch, now: now),
'just now',
);
expect(
relativeChatSessionTime(
from(const Duration(minutes: 5)).millisecondsSinceEpoch,
now: now,
),
'5 min ago',
);
expect(
relativeChatSessionTime(
from(const Duration(hours: 3)).millisecondsSinceEpoch,
now: now,
),
'3 hr ago',
);
expect(
relativeChatSessionTime(
from(const Duration(hours: 25)).millisecondsSinceEpoch,
now: now,
),
'1 day ago',
);
expect(
relativeChatSessionTime(
from(const Duration(days: 3)).millisecondsSinceEpoch,
now: now,
),
'3 days ago',
);
expect(
relativeChatSessionTime(
DateTime(2026, 10, 1, 9).millisecondsSinceEpoch,
now: now,
),
'1 Oct',
);
// The web formats with `Intl.DateTimeFormat('en-GB', …)`, whose short
// September is `Sept`; its own test asserts `12 Sept`.
expect(
relativeChatSessionTime(
DateTime(2026, 9, 12, 9).millisecondsSinceEpoch,
now: now,
),
'12 Sept',
);
});
test('meta and status come only from the row', () {
expect(
chatSessionMeta({'directory': '/work', 'model': 'model-a'}),
'/work · model-a',
);
expect(chatSessionMeta({'directory': '/work'}), '/work');
expect(chatSessionMeta({}), '');
expect(chatSessionRowStatus({}, unseen: false), isNull);
expect(chatSessionRowStatus({}, unseen: true), 'New');
// The web suppresses the streaming word; the row's activity icon carries it.
expect(chatSessionRowStatus({'running': true}, unseen: true), isNull);
expect(chatSessionRowStatus({'running': true}, unseen: false), isNull);
expect(
chatSessionRowStatus({'closed_at': '2026-01-01'}, unseen: true),
'Closed',
);
});
testWidgets('a row reads title, muted meta and trailing recency/unread', (
tester,
) async {
final now = DateTime.now();
final sessions = <JsonMap>[
{
'id': 's1',
'title': 'Starred chat',
'directory': '/work',
'model': 'model-a',
'updated_at': now
.subtract(const Duration(minutes: 5))
.millisecondsSinceEpoch,
},
{
'id': 's2',
'title': 'Open chat',
'directory': '/work',
'updated_at': now
.subtract(const Duration(hours: 2, minutes: 30))
.millisecondsSinceEpoch,
},
];
await _pumpRows(
tester,
sessions,
isUnseen: (session) => session['id'] == 's1',
);
// The unread word trails the muted meta line; the recency trails the title.
expect(find.text('Starred chat'), findsOneWidget);
expect(find.text('/work · model-a'), findsOneWidget);
expect(find.text('5 min ago'), findsOneWidget);
expect(find.text('New'), findsOneWidget);
expect(find.text('/work'), findsOneWidget);
expect(find.text('2 hr ago'), findsOneWidget);
// The meta line keeps `CupertinoListTile`'s native 12pt subtitle style; it
// must not be rendered at the title's body size. The colour-only style the
// row passes merges with the tile's own `DefaultTextStyle`.
final titleStyle = _styleOf(tester, 'Starred chat');
final metaStyle = _styleOf(tester, '/work · model-a');
expect(metaStyle.fontSize, lessThan(titleStyle.fontSize!));
expect(metaStyle.fontSize, 12.0);
expect(_styleOf(tester, 'New').fontSize, metaStyle.fontSize);
// Each session is still its own native tile with its own actions, so the
// inset group draws the separator between them.
expect(find.byType(CupertinoListTile), findsNWidgets(2));
expect(find.byKey(const Key('chat-star-s1')), findsOneWidget);
expect(find.byKey(const Key('chat-actions-s2')), findsOneWidget);
expect(
tester.getTopLeft(find.byKey(const Key('chat-row-s2'))).dy,
greaterThan(
tester.getBottomLeft(find.byKey(const Key('chat-row-s1'))).dy,
),
);
});
testWidgets('at 320px 2x the long title and meta ellipsise, the word does not', (
tester,
) async {
_useNarrowText(tester);
final now = DateTime.now();
await _pumpRows(tester, [
{
'id': 's1',
'title': 'A conversation title long enough to need an ellipsis',
'directory': '/a/very/long/directory/that/must/ellipsise',
'model': 'provider/an-extremely-long-recorded-model-id',
'updated_at': now
.subtract(const Duration(days: 3))
.millisecondsSinceEpoch,
},
{
'id': 'c1',
'title': 'A closed conversation',
'directory': '/work',
'closed_at': '2026-01-01',
},
], isUnseen: (session) => session['id'] == 's1');
expect(tester.takeException(), isNull);
const title = 'A conversation title long enough to need an ellipsis';
const meta =
'/a/very/long/directory/that/must/ellipsise · '
'provider/an-extremely-long-recorded-model-id';
final titleParagraph = tester.renderObject<RenderParagraph>(
find.text(title),
);
expect(titleParagraph.maxLines, 1);
expect(titleParagraph.didExceedMaxLines, isTrue);
final metaParagraph = tester.renderObject<RenderParagraph>(find.text(meta));
expect(metaParagraph.maxLines, 1);
expect(metaParagraph.didExceedMaxLines, isTrue);
// The state word is the row's only unread marker: at the smallest supported
// surface with 2x text it stays whole (it is scaled down only when even the
// full text column cannot hold it) and inside the tile's trailing edge.
for (final row in ['s1', 'c1']) {
final word = row == 's1' ? 'New' : 'Closed';
final paragraph = tester.renderObject<RenderParagraph>(find.text(word));
expect(paragraph.maxLines, 1);
expect(paragraph.didExceedMaxLines, isFalse, reason: '$word is clipped');
final rect = tester.getRect(find.text(word));
expect(rect.width, greaterThan(0));
expect(
rect.right,
lessThanOrEqualTo(
tester.getRect(find.byKey(Key('chat-row-$row'))).right,
),
);
}
// The recency is supplementary, so it is the part that ellipsises here; it
// still keeps its single line at the trailing edge of the title line.
final recency = tester.renderObject<RenderParagraph>(
find.text('3 days ago'),
);
expect(recency.maxLines, 1);
expect(recency.didExceedMaxLines, isTrue);
expect(
(tester.getCenter(find.text(title)).dy -
tester.getCenter(find.text('3 days ago')).dy)
.abs(),
lessThan(20),
);
});
}
@@ -0,0 +1,182 @@
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/ui/sessions/session_list_material.dart';
/// The Android host: a Material grouped list with its native separators.
Future<void> _pumpRows(
WidgetTester tester,
List<JsonMap> sessions, {
bool Function(JsonMap)? isUnseen,
String section = 'Chats',
}) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
platform: TargetPlatform.android,
brightness: Brightness.dark,
),
home: Scaffold(
body: MaterialSessionList(
sections: [(title: section, sessions: sessions)],
emptyMessage: null,
duplicateTitles: const {},
onOpen: (_) {},
onRename: (_) {},
onClose: (_) {},
onReopen: (_) {},
onStar: (_) {},
onHide: (_) {},
onClearSearch: null,
isUnseen: isUnseen ?? (_) => false,
errorFor: (_) => null,
),
),
),
);
await tester.pumpAndSettle();
}
void _useNarrowText(WidgetTester tester) {
tester.view.physicalSize = const Size(320, 640);
tester.view.devicePixelRatio = 1;
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
}
void main() {
testWidgets('a Material row reads title, muted meta and trailing recency', (
tester,
) async {
final now = DateTime.now();
await _pumpRows(tester, [
{
'id': 's1',
'title': 'Starred chat',
'directory': '/work',
'model': 'model-a',
'updated_at': now
.subtract(const Duration(minutes: 5))
.millisecondsSinceEpoch,
},
{
'id': 's2',
'title': 'Open chat',
'directory': '/work',
'updated_at': now
.subtract(const Duration(hours: 2, minutes: 30))
.millisecondsSinceEpoch,
},
], isUnseen: (session) => session['id'] == 's1');
expect(find.text('Starred chat'), findsOneWidget);
expect(find.text('/work · model-a'), findsOneWidget);
expect(find.text('5 min ago'), findsOneWidget);
expect(find.text('New'), findsOneWidget);
expect(find.text('/work'), findsOneWidget);
expect(find.text('2 hr ago'), findsOneWidget);
// The meta line is the theme's muted colour, not the title colour.
final meta = tester.widget<Text>(find.text('/work · model-a'));
final context = tester.element(find.text('/work · model-a'));
expect(meta.style?.color, Theme.of(context).colorScheme.onSurfaceVariant);
// Native Material separators sit between rows, not around the group.
expect(find.byType(Divider), findsOneWidget);
expect(
tester.getTopLeft(find.byKey(const Key('chat-row-s2'))).dy,
greaterThan(
tester.getBottomLeft(find.byKey(const Key('chat-row-s1'))).dy,
),
);
expect(find.byKey(const Key('chat-star-s1')), findsOneWidget);
expect(find.byKey(const Key('chat-actions-s2')), findsOneWidget);
});
testWidgets('a closed Material row carries Closed on the row itself', (
tester,
) async {
await _pumpRows(tester, [
{
'id': 'c1',
'title': 'Closed chat',
'directory': '/work',
'closed_at': '2026-01-01',
},
], section: 'Closed');
// The section header also says Closed; the row's trailing word is its own.
expect(
find.descendant(
of: find.byKey(const Key('chat-row-c1')),
matching: find.text('Closed'),
),
findsOneWidget,
);
expect(find.text('New'), findsNothing);
});
testWidgets('at 320px 2x the Material row ellipsises text, not its word', (
tester,
) async {
_useNarrowText(tester);
final now = DateTime.now();
await _pumpRows(tester, [
{
'id': 's1',
'title': 'A conversation title long enough to need an ellipsis',
'directory': '/a/very/long/directory/that/must/ellipsise',
'model': 'provider/an-extremely-long-recorded-model-id',
'updated_at': now
.subtract(const Duration(days: 3))
.millisecondsSinceEpoch,
},
{
'id': 'c1',
'title': 'A closed conversation',
'directory': '/work',
'closed_at': '2026-01-01',
},
], isUnseen: (session) => session['id'] == 's1');
expect(tester.takeException(), isNull);
const title = 'A conversation title long enough to need an ellipsis';
const meta =
'/a/very/long/directory/that/must/ellipsise · '
'provider/an-extremely-long-recorded-model-id';
final titleParagraph = tester.renderObject<RenderParagraph>(
find.text(title),
);
expect(titleParagraph.maxLines, 1);
expect(titleParagraph.didExceedMaxLines, isTrue);
final metaParagraph = tester.renderObject<RenderParagraph>(find.text(meta));
expect(metaParagraph.maxLines, 1);
expect(metaParagraph.didExceedMaxLines, isTrue);
// `New`/`Closed` is the row's only unread marker; it stays whole at the
// smallest supported surface with 2x text.
for (final row in ['s1', 'c1']) {
final word = row == 's1' ? 'New' : 'Closed';
final paragraph = tester.renderObject<RenderParagraph>(find.text(word));
expect(paragraph.maxLines, 1);
expect(paragraph.didExceedMaxLines, isFalse, reason: '$word is clipped');
final rect = tester.getRect(find.text(word));
expect(rect.width, greaterThan(0));
expect(
rect.right,
lessThanOrEqualTo(
tester.getRect(find.byKey(Key('chat-row-$row'))).right,
),
);
}
// Two lines: the title/recency line, then the muted meta line.
expect(
tester.getCenter(find.text(meta)).dy,
greaterThan(tester.getCenter(find.text(title)).dy),
);
});
}
@@ -15,7 +15,23 @@ void main() {
expect(find.text('Starred'), findsOneWidget);
expect(find.text('Chats'), findsNWidgets(2));
expect(find.text('Closed'), findsOneWidget);
// The Closed section header, and each closed row's trailing word.
expect(
find.byWidgetPredicate(
(widget) =>
widget is ExpansionTile &&
widget.title is Text &&
(widget.title as Text).data == 'Closed',
),
findsOneWidget,
);
expect(
find.descendant(
of: find.byKey(const Key('chat-row-s4')),
matching: find.text('Closed'),
),
findsOneWidget,
);
expect(find.text('Starred chat'), findsOneWidget);
expect(find.text('Starred closed'), findsOneWidget);
expect(find.text('Open chat'), findsOneWidget);