merge(app): land live Chat destination after retained-deadline recovery
This commit is contained in:
@@ -10,7 +10,7 @@ enum AppRouteKind { pipelines, runs, chat, settings }
|
||||
/// malformed path resolves to the default Pipelines list instead of throwing.
|
||||
/// The serialiser is its inverse for every route the app can produce.
|
||||
class AppRoute {
|
||||
const AppRoute(this.kind, {this.runId});
|
||||
const AppRoute(this.kind, {this.runId, this.chatSessionId});
|
||||
|
||||
static const pipelines = AppRoute(AppRouteKind.pipelines);
|
||||
static const runs = AppRoute(AppRouteKind.runs);
|
||||
@@ -19,16 +19,27 @@ class AppRoute {
|
||||
|
||||
static const run = _RunRouteFactory();
|
||||
|
||||
/// One chat session, or the chat list when [id] is not a session id.
|
||||
static AppRoute chatSession(String id) => isChatSessionId(id)
|
||||
? AppRoute(AppRouteKind.chat, chatSessionId: id)
|
||||
: chat;
|
||||
|
||||
final AppRouteKind kind;
|
||||
|
||||
/// The run shown by the Runs destination, or null for the list.
|
||||
final int? runId;
|
||||
|
||||
/// The chat session shown by the Chat destination, or null for the list.
|
||||
final String? chatSessionId;
|
||||
|
||||
/// The path the app writes into history for this route.
|
||||
String get path => switch (kind) {
|
||||
AppRouteKind.pipelines => '/pipelines',
|
||||
AppRouteKind.runs => runId == null ? '/runs' : '/runs/$runId',
|
||||
AppRouteKind.chat => '/chat',
|
||||
AppRouteKind.chat =>
|
||||
chatSessionId == null || !isChatSessionId(chatSessionId!)
|
||||
? '/chat'
|
||||
: '/chat/${Uri.encodeComponent(chatSessionId!)}',
|
||||
AppRouteKind.settings => '/settings',
|
||||
};
|
||||
|
||||
@@ -65,6 +76,7 @@ class AppRoute {
|
||||
'runs' when segments.length == 1 => runs,
|
||||
'runs' when segments.length == 2 => _runRoute(segments[1]),
|
||||
'chat' when segments.length == 1 => chat,
|
||||
'chat' when segments.length == 2 => _chatRoute(segments[1]),
|
||||
'settings' when segments.length == 1 => settings,
|
||||
_ => pipelines,
|
||||
};
|
||||
@@ -77,12 +89,26 @@ class AppRoute {
|
||||
return AppRoute(AppRouteKind.runs, runId: id);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is AppRoute && other.kind == kind && other.runId == runId;
|
||||
/// A chat session id is nonempty, bounded and URL-safe, matching the web
|
||||
/// parser. Anything else is malformed rather than a stale session the
|
||||
/// destination has to guess about.
|
||||
static bool isChatSessionId(String value) =>
|
||||
value.isNotEmpty &&
|
||||
value.length <= 200 &&
|
||||
RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(value);
|
||||
|
||||
static AppRoute _chatRoute(String value) =>
|
||||
isChatSessionId(value) ? chatSession(value) : pipelines;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(kind, runId);
|
||||
bool operator ==(Object other) =>
|
||||
other is AppRoute &&
|
||||
other.kind == kind &&
|
||||
other.runId == runId &&
|
||||
other.chatSessionId == chatSessionId;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(kind, runId, chatSessionId);
|
||||
|
||||
@override
|
||||
String toString() => path;
|
||||
|
||||
@@ -27,6 +27,7 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
|
||||
AppRouterDelegate({
|
||||
required this.builder,
|
||||
required this.onPopToRuns,
|
||||
required this.onPopToChat,
|
||||
required this.cupertino,
|
||||
AppRoute initial = AppRoute.pipelines,
|
||||
}) : _route = initial;
|
||||
@@ -36,6 +37,9 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
|
||||
/// Called when a system Back belongs to the Runs detail, not the app stack.
|
||||
final VoidCallback onPopToRuns;
|
||||
|
||||
/// Called when a system Back belongs to one chat session.
|
||||
final VoidCallback onPopToChat;
|
||||
|
||||
final bool cupertino;
|
||||
|
||||
final _navigatorKey = GlobalKey<NavigatorState>();
|
||||
@@ -81,9 +85,15 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
|
||||
|
||||
@override
|
||||
Future<bool> popRoute() async {
|
||||
if (_route.runId == null) return false;
|
||||
onPopToRuns();
|
||||
return true;
|
||||
if (_route.runId != null) {
|
||||
onPopToRuns();
|
||||
return true;
|
||||
}
|
||||
if (_route.chatSessionId != null) {
|
||||
onPopToChat();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Records a user move; the Router turns the new configuration into a
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../features/chat/screen.dart';
|
||||
import '../ui/adaptive/host.dart';
|
||||
import 'app_session.dart';
|
||||
import 'connection_status.dart';
|
||||
import 'server_endpoint.dart';
|
||||
|
||||
/// The Chat destination: the shared session list and one read-only thread.
|
||||
///
|
||||
/// Before the shared socket accepts its first connection nothing is requested,
|
||||
/// so an offline launch cannot look like an empty chat list. After that the
|
||||
/// screen stays mounted through drops; a reconnect advances [syncToken] so the
|
||||
/// open conversation re-subscribes and re-reads without losing its selection.
|
||||
class ChatDestination extends StatelessWidget {
|
||||
const ChatDestination({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.server,
|
||||
this.initialSessionId,
|
||||
this.onSessionSelected,
|
||||
this.onBack,
|
||||
});
|
||||
|
||||
final AppSession session;
|
||||
final ServerEndpoint server;
|
||||
final String? initialSessionId;
|
||||
final ValueChanged<String>? onSessionSelected;
|
||||
final VoidCallback? onBack;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AnimatedBuilder(
|
||||
animation: session,
|
||||
builder: (context, _) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
if ((server.requiresConfiguration || server.error != null) &&
|
||||
session.endpoint == null) {
|
||||
return ConnectionGate(
|
||||
session: session,
|
||||
server: server,
|
||||
cupertino: cupertino,
|
||||
);
|
||||
}
|
||||
if (!session.everConnected) {
|
||||
if (session.connected) return _chatScreen();
|
||||
return ConnectionGate(
|
||||
session: session,
|
||||
server: server,
|
||||
cupertino: cupertino,
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
children: [
|
||||
if (!session.connected)
|
||||
ConnectionBanner(session: session, cupertino: cupertino),
|
||||
Expanded(child: _chatScreen()),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Widget _chatScreen() => ChatScreen(
|
||||
gateway: session.gateway,
|
||||
initialSessionId: initialSessionId,
|
||||
syncToken: session.connectionEpoch,
|
||||
onSessionSelected: onSessionSelected,
|
||||
onBack: onBack,
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import 'app.dart';
|
||||
import 'app_route.dart';
|
||||
import 'app_router.dart';
|
||||
import 'app_session.dart';
|
||||
import 'chat_destination.dart';
|
||||
import 'pipelines_destination.dart';
|
||||
import 'runs_destination.dart';
|
||||
import 'server_endpoint.dart';
|
||||
@@ -71,6 +72,7 @@ class _PipelinesAppState extends State<PipelinesApp> {
|
||||
initial: initial,
|
||||
cupertino: _cupertino,
|
||||
onPopToRuns: () => _delegate.goTo(AppRoute.runs),
|
||||
onPopToChat: () => _delegate.goTo(AppRoute.chat),
|
||||
builder: _buildShell,
|
||||
);
|
||||
_config = RouterConfig<AppRoute>(
|
||||
@@ -110,6 +112,13 @@ class _PipelinesAppState extends State<PipelinesApp> {
|
||||
onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)),
|
||||
onBack: () => _delegate.goTo(AppRoute.runs),
|
||||
),
|
||||
AppDestination.chat: (_) => ChatDestination(
|
||||
session: _session,
|
||||
server: widget.server,
|
||||
initialSessionId: route.chatSessionId,
|
||||
onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)),
|
||||
onBack: () => _delegate.goTo(AppRoute.chat),
|
||||
),
|
||||
AppDestination.settings: (_) => SettingsScreen(
|
||||
client: _session.client,
|
||||
initialEndpoint: _session.endpoint,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Stable widget-key strings for transcript rows while history grows at both
|
||||
/// ends.
|
||||
///
|
||||
/// A folded assistant turn has no stable message boundary: `Load older` can
|
||||
/// prepend messages into the turn (changing its first id) and a live frame can
|
||||
/// append a message (changing its last id). Deriving the row key from either
|
||||
/// boundary remounts the row and resets every native disclosure in it, which
|
||||
/// moved an open reasoning block to another answer or closed it.
|
||||
///
|
||||
/// So the first sighting of a turn assigns a synthetic key, and later calls
|
||||
/// carry that key forward while the turn still contains any message it held
|
||||
/// before. Rows without a message id fall back to their position: they have no
|
||||
/// identity that survives a prepend.
|
||||
class ChatRowKeys {
|
||||
final Map<String, String> _byMessageId = {};
|
||||
int _serial = 0;
|
||||
|
||||
/// One key per row, in row order. Call once per build.
|
||||
List<String> forRows(List<JsonMap> rows) {
|
||||
final nextByMessageId = <String, String>{};
|
||||
final used = <String>{};
|
||||
final keys = <String>[];
|
||||
for (var index = 0; index < rows.length; index++) {
|
||||
final row = rows[index];
|
||||
final kind = '${row['kind'] ?? ''}';
|
||||
final ids = _messageIds(row);
|
||||
String? key;
|
||||
for (final id in ids) {
|
||||
final held = _byMessageId[id];
|
||||
if (held != null) {
|
||||
key = held;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (key == null) {
|
||||
// A row with no id has no identity that survives a prepend, so it
|
||||
// follows its position, as a plain indexed list would. Every other new
|
||||
// row gets a key no older row can generate.
|
||||
key = ids.isEmpty
|
||||
? 'chat-row-$kind-index-$index'
|
||||
: 'chat-row-$kind-${_serial++}';
|
||||
used.add(key);
|
||||
} else if (!used.add(key)) {
|
||||
// Defensive: a held key is only reused once even if input unexpectedly
|
||||
// splits one turn into two rows; duplicate widget keys would throw.
|
||||
key = 'chat-row-$kind-${_serial++}';
|
||||
used.add(key);
|
||||
}
|
||||
keys.add(key);
|
||||
for (final id in ids) {
|
||||
nextByMessageId[id] = key;
|
||||
}
|
||||
}
|
||||
_byMessageId
|
||||
..clear()
|
||||
..addAll(nextByMessageId);
|
||||
return keys;
|
||||
}
|
||||
|
||||
static List<String> _messageIds(JsonMap row) {
|
||||
final listed = row['messageIds'];
|
||||
if (listed is List) {
|
||||
return listed
|
||||
.map((id) => '$id'.trim())
|
||||
.where((id) => id.isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
final key = '${row['key'] ?? ''}'.trim();
|
||||
return key.isEmpty ? const [] : [key];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/chat_transcript.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import '../ui/transcript/chat_message_view.dart';
|
||||
import 'chat_row_keys.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
|
||||
/// One read-only conversation: the controller's transcript in the order the
|
||||
/// server reports it, rendered by the existing [ChatMessageView].
|
||||
///
|
||||
/// History and live-subscription failures are separate notices: readable stored
|
||||
/// history must never hide a refused live watch. The shell owns the navigation
|
||||
/// bar, so this view adds only its own Back control and content.
|
||||
class ChatThreadView extends StatefulWidget {
|
||||
const ChatThreadView({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
required this.sessionId,
|
||||
required this.onBack,
|
||||
this.title = '',
|
||||
this.syncToken = 0,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
final String sessionId;
|
||||
final VoidCallback onBack;
|
||||
|
||||
/// The list row's title when this visit knows it; a deep link may not.
|
||||
final String title;
|
||||
|
||||
/// Advances when the shared socket is replaced, keeping this selection.
|
||||
final int syncToken;
|
||||
|
||||
@override
|
||||
State<ChatThreadView> createState() => _ChatThreadViewState();
|
||||
}
|
||||
|
||||
class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
late ChatThreadController _controller = _attach();
|
||||
late ChatRowKeys _rowKeys = ChatRowKeys();
|
||||
|
||||
ChatThreadController _attach() =>
|
||||
ChatThreadController(widget.gateway, widget.sessionId)..load();
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatThreadView oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.gateway != widget.gateway ||
|
||||
oldWidget.sessionId != widget.sessionId) {
|
||||
_controller.dispose();
|
||||
_controller = _attach();
|
||||
_rowKeys = ChatRowKeys();
|
||||
} else if (oldWidget.syncToken != widget.syncToken) {
|
||||
unawaited(_controller.resync());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AnimatedBuilder(
|
||||
animation: _controller,
|
||||
builder: (context, _) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final rows = transcriptRows(_controller.messages);
|
||||
// Older pages prepend messages and a live frame can append one, so a
|
||||
// folded assistant turn's first message id is not a stable identity.
|
||||
// ChatRowKeys carries a turn's key forward while it still holds any of
|
||||
// its previous messages, keeping the element (and its open disclosures)
|
||||
// across paging and streaming.
|
||||
final keys = _rowKeys.forRows(rows);
|
||||
final initialLoad = !_controller.loaded && _controller.loading;
|
||||
return ListView(
|
||||
key: ValueKey<String>('chat-thread-${widget.sessionId}'),
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
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 (initialLoad)
|
||||
Padding(
|
||||
key: const Key('chat-thread-loading'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Center(
|
||||
child: cupertino
|
||||
? const CupertinoActivityIndicator()
|
||||
: const CircularProgressIndicator(),
|
||||
),
|
||||
),
|
||||
if (_controller.hasMore)
|
||||
Padding(
|
||||
key: const Key('chat-load-older'),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: cupertino
|
||||
? CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: _controller.loading
|
||||
? null
|
||||
: _controller.loadOlder,
|
||||
child: const Text('Load older'),
|
||||
)
|
||||
: TextButton(
|
||||
onPressed: _controller.loading
|
||||
? null
|
||||
: _controller.loadOlder,
|
||||
child: const Text('Load older'),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_controller.error != null)
|
||||
ChatErrorNotice(
|
||||
key: const Key('chat-history-error'),
|
||||
message: 'Chat history unavailable\n${_controller.error}',
|
||||
onRetry: _controller.load,
|
||||
),
|
||||
if (_controller.subscriptionError != null)
|
||||
ChatErrorNotice(
|
||||
key: const Key('chat-live-error'),
|
||||
message:
|
||||
'Live updates unavailable\n${_controller.subscriptionError}',
|
||||
onRetry: _controller.resync,
|
||||
),
|
||||
if (_controller.loaded && rows.isEmpty && _controller.error == null)
|
||||
const Padding(
|
||||
key: Key('chat-thread-empty'),
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text('No messages in this chat yet.'),
|
||||
),
|
||||
for (var index = 0; index < rows.length; index++)
|
||||
Padding(
|
||||
key: ValueKey<String>(keys[index]),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: ChatMessageView(row: rows[index]),
|
||||
),
|
||||
if (_controller.running)
|
||||
Padding(
|
||||
key: const Key('chat-running'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: const Text('Assistant is responding…'),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
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'),
|
||||
);
|
||||
}
|
||||
@@ -34,25 +34,36 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) {
|
||||
|
||||
/// Consecutive assistant messages form one answer turn. All part fields (also
|
||||
/// future/unknown protocol types) are preserved in original order.
|
||||
///
|
||||
/// `key` is the turn's first assistant message id, which is only a display
|
||||
/// anchor: paging an older assistant message into the turn changes it, so widget
|
||||
/// identity uses `messageIds`. That list carries every message the folded turn
|
||||
/// currently holds so the view can keep the same row element while the turn
|
||||
/// grows at either end.
|
||||
List<JsonMap> transcriptRows(List<JsonMap> messages) {
|
||||
final rows = <JsonMap>[];
|
||||
String? key;
|
||||
final ids = <String>[];
|
||||
final parts = <JsonMap>[];
|
||||
void flush() {
|
||||
if (key != null && parts.isNotEmpty) {
|
||||
rows.add({
|
||||
'kind': 'assistant',
|
||||
'key': key,
|
||||
'messageIds': List<String>.of(ids),
|
||||
'parts': List<JsonMap>.of(parts),
|
||||
});
|
||||
}
|
||||
key = null;
|
||||
ids.clear();
|
||||
parts.clear();
|
||||
}
|
||||
|
||||
for (final message in messages) {
|
||||
if (message['role'] == 'assistant') {
|
||||
key ??= '${message['id'] ?? ''}';
|
||||
final id = '${message['id'] ?? ''}'.trim();
|
||||
key ??= id;
|
||||
if (id.isNotEmpty) ids.add(id);
|
||||
for (final part in (message['parts'] as List? ?? const [])) {
|
||||
if (part is Map) parts.add(Map<String, dynamic>.from(part));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'conversation/chat_thread_view.dart';
|
||||
import 'ui/sessions/chat_sessions_screen.dart';
|
||||
|
||||
/// The Chat destination's list/detail switch.
|
||||
///
|
||||
/// The route names the open session, so a row tap, a deep link and Back all
|
||||
/// navigate through the same value. The session list stays mounted (offstage)
|
||||
/// while a conversation is open, so returning to it keeps its rows and query.
|
||||
/// The shell owns the app bar; this screen adds no second one.
|
||||
class ChatScreen extends StatefulWidget {
|
||||
const ChatScreen({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
this.initialSessionId,
|
||||
this.syncToken = 0,
|
||||
this.onSessionSelected,
|
||||
this.onBack,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
|
||||
/// The chat session the current route names, or null for the list.
|
||||
final String? initialSessionId;
|
||||
|
||||
/// Advances when the shared socket is replaced. The open conversation
|
||||
/// re-subscribes and re-reads in place, so its selection survives.
|
||||
final int syncToken;
|
||||
|
||||
final ValueChanged<String>? onSessionSelected;
|
||||
final VoidCallback? onBack;
|
||||
|
||||
@override
|
||||
State<ChatScreen> createState() => _ChatScreenState();
|
||||
}
|
||||
|
||||
class _ChatScreenState extends State<ChatScreen> {
|
||||
/// Rows opened in this visit, used only for the native title. A deep link has
|
||||
/// no title until the list loads, and this screen waits for no list request.
|
||||
final Map<String, String> _titles = {};
|
||||
String? _standaloneSelection;
|
||||
|
||||
String? get _selected {
|
||||
final routed = widget.initialSessionId;
|
||||
if (routed != null && routed.isNotEmpty) return routed;
|
||||
return _standaloneSelection;
|
||||
}
|
||||
|
||||
void _open(JsonMap session) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
if (id.isEmpty) return;
|
||||
final title = '${session['title'] ?? ''}'.trim();
|
||||
if (title.isNotEmpty) _titles[id] = title;
|
||||
final select = widget.onSessionSelected;
|
||||
if (select != null) {
|
||||
select(id);
|
||||
} else {
|
||||
setState(() => _standaloneSelection = id);
|
||||
}
|
||||
}
|
||||
|
||||
void _back() {
|
||||
final back = widget.onBack;
|
||||
if (back != null) {
|
||||
back();
|
||||
} else {
|
||||
setState(() => _standaloneSelection = null);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final selected = _selected;
|
||||
return Stack(
|
||||
children: [
|
||||
Offstage(
|
||||
offstage: selected != null,
|
||||
child: ChatSessionsScreen(
|
||||
gateway: widget.gateway,
|
||||
embedded: true,
|
||||
syncToken: widget.syncToken,
|
||||
onOpen: _open,
|
||||
),
|
||||
),
|
||||
if (selected != null)
|
||||
ChatThreadView(
|
||||
key: ValueKey<String>('chat-session-$selected'),
|
||||
gateway: widget.gateway,
|
||||
sessionId: selected,
|
||||
title: _titles[selected] ?? '',
|
||||
syncToken: widget.syncToken,
|
||||
onBack: _back,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@@ -16,10 +18,19 @@ class ChatSessionsScreen extends StatefulWidget {
|
||||
super.key,
|
||||
required this.gateway,
|
||||
required this.onOpen,
|
||||
this.embedded = false,
|
||||
this.syncToken = 0,
|
||||
});
|
||||
final ApiGateway gateway;
|
||||
final void Function(JsonMap session) onOpen;
|
||||
|
||||
/// True under the application shell, which owns the single navigation bar.
|
||||
final bool embedded;
|
||||
|
||||
/// Advances when the shared socket is replaced; sessions created, renamed or
|
||||
/// closed elsewhere during the gap must not stay invisible until Refresh.
|
||||
final int syncToken;
|
||||
|
||||
@override
|
||||
State<ChatSessionsScreen> createState() => _ChatSessionsScreenState();
|
||||
}
|
||||
@@ -35,6 +46,8 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.gateway != widget.gateway) {
|
||||
_controller.replaceRepository(ChatRepository(widget.gateway));
|
||||
} else if (oldWidget.syncToken != widget.syncToken) {
|
||||
unawaited(_controller.refresh());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,53 +128,38 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
],
|
||||
);
|
||||
|
||||
if (widget.embedded) {
|
||||
return Column(
|
||||
children: [
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerEnd,
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 8),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: _actions(),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(child: body),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: CupertinoNavigationBar(
|
||||
middle: const Text('Chats'),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ChatBarAction(
|
||||
key: const Key('chat-new-chat'),
|
||||
label: 'New chat',
|
||||
onPressed: _newChat,
|
||||
materialIcon: Icons.add,
|
||||
cupertinoIcon: CupertinoIcons.add,
|
||||
),
|
||||
ChatBarAction(
|
||||
key: const Key('chat-refresh'),
|
||||
label: 'Refresh',
|
||||
onPressed: _controller.refresh,
|
||||
materialIcon: Icons.refresh,
|
||||
cupertinoIcon: CupertinoIcons.refresh,
|
||||
),
|
||||
],
|
||||
children: _actions(),
|
||||
),
|
||||
),
|
||||
child: SafeArea(child: body),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Chats'),
|
||||
actions: [
|
||||
ChatBarAction(
|
||||
key: const Key('chat-new-chat'),
|
||||
label: 'New chat',
|
||||
onPressed: _newChat,
|
||||
materialIcon: Icons.add,
|
||||
cupertinoIcon: CupertinoIcons.add,
|
||||
),
|
||||
ChatBarAction(
|
||||
key: const Key('chat-refresh'),
|
||||
label: 'Refresh',
|
||||
onPressed: _controller.refresh,
|
||||
materialIcon: Icons.refresh,
|
||||
cupertinoIcon: CupertinoIcons.refresh,
|
||||
),
|
||||
],
|
||||
),
|
||||
appBar: AppBar(title: const Text('Chats'), actions: _actions()),
|
||||
body: body,
|
||||
floatingActionButton: FloatingActionButton.extended(
|
||||
key: const Key('chat-new-chat-fab'),
|
||||
@@ -173,4 +171,21 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _actions() => [
|
||||
ChatBarAction(
|
||||
key: const Key('chat-new-chat'),
|
||||
label: 'New chat',
|
||||
onPressed: _newChat,
|
||||
materialIcon: Icons.add,
|
||||
cupertinoIcon: CupertinoIcons.add,
|
||||
),
|
||||
ChatBarAction(
|
||||
key: const Key('chat-refresh'),
|
||||
label: 'Refresh',
|
||||
onPressed: _controller.refresh,
|
||||
materialIcon: Icons.refresh,
|
||||
cupertinoIcon: CupertinoIcons.refresh,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -92,13 +92,34 @@ class ChatMessageView extends StatelessWidget {
|
||||
|
||||
List<Widget> _agentParts(BuildContext context) {
|
||||
final widgets = <Widget>[];
|
||||
for (final part in _partsOf(row)) {
|
||||
final parts = _partsOf(row);
|
||||
final seen = <String, int>{};
|
||||
for (var index = 0; index < parts.length; index++) {
|
||||
final part = parts[index];
|
||||
final widget = _agentPart(context, part);
|
||||
if (widget != null) widgets.add(widget);
|
||||
if (widget == null) continue;
|
||||
// Part identity, not position, so an older assistant message that folds
|
||||
// into the same turn can prepend its parts without moving an open
|
||||
// disclosure. The enclosing row's identity is carried by ChatRowKeys; a
|
||||
// part with no server id still falls back to its position.
|
||||
widgets.add(
|
||||
KeyedSubtree(key: _partKey(part, index, seen), child: widget),
|
||||
);
|
||||
}
|
||||
return widgets;
|
||||
}
|
||||
|
||||
/// The server's part id when there is one, else this part's position. A
|
||||
/// repeated identity gets an ordinal so two sibling keys never collide.
|
||||
Key _partKey(JsonMap part, int index, Map<String, int> seen) {
|
||||
final type = '${part['type'] ?? ''}';
|
||||
final id = '${part['id'] ?? ''}'.trim();
|
||||
final base = id.isEmpty ? 'index-$index' : '$type:$id';
|
||||
final ordinal = (seen[base] ?? 0) + 1;
|
||||
seen[base] = ordinal;
|
||||
return ValueKey<String>('chat-part-$base-$ordinal');
|
||||
}
|
||||
|
||||
/// One agent part, or null when a known part has nothing to draw. The web's
|
||||
/// `partRendering` hides blank text/reasoning too, so a blank known part must
|
||||
/// not fall through to the unknown-part disclosure.
|
||||
|
||||
Reference in New Issue
Block a user