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;