merge(app): land reviewed native chat sessions
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
const webChatClient = 'Web';
|
||||
|
||||
String nativeChatMessageId(String operationId) {
|
||||
final compact = operationId.replaceAll(RegExp('[^A-Za-z0-9]'), '');
|
||||
final capped = compact.length > 120 ? compact.substring(0, 120) : compact;
|
||||
return capped.isEmpty ? '' : 'msg_$capped';
|
||||
}
|
||||
|
||||
/// Chat wire adapter. ApiGateway supplies request ids and returns full envelopes.
|
||||
class ChatRepository {
|
||||
ChatRepository(this.gateway);
|
||||
final ApiGateway gateway;
|
||||
|
||||
Future<List<JsonMap>> sessions() async =>
|
||||
_maps((await gateway.call('chat_sessions'))['chat_sessions']);
|
||||
Future<JsonMap> models(String sessionId) async {
|
||||
final reply = await gateway.call('chat_models', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
});
|
||||
final catalog = reply['chat_models'];
|
||||
return catalog is Map ? Map<String, dynamic>.from(catalog) : {};
|
||||
}
|
||||
|
||||
Future<JsonMap> selectModel(
|
||||
String sessionId,
|
||||
String provider,
|
||||
String model,
|
||||
) => gateway.call('chat_model', {
|
||||
'chat_model': {
|
||||
'session_id': sessionId,
|
||||
'provider': provider,
|
||||
'model': model,
|
||||
},
|
||||
});
|
||||
Future<List<JsonMap>> shells(String sessionId) async => _maps(
|
||||
(await gateway.call('chat_shells', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
}))['chat_shells'],
|
||||
);
|
||||
Future<List<String>> directories() async {
|
||||
final value = (await gateway.call('chat_directories'))['chat_directories'];
|
||||
if (value is! List) {
|
||||
throw StateError('Server did not return chat directories.');
|
||||
}
|
||||
return value
|
||||
.whereType<String>()
|
||||
.where((entry) => entry.trim().isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<List<String>> backends() async {
|
||||
final value = (await gateway.call('chat_backends'))['chat_backends'];
|
||||
if (value is! List) {
|
||||
throw StateError('Server did not return chat backends.');
|
||||
}
|
||||
final result = value
|
||||
.whereType<String>()
|
||||
.where((entry) => entry.trim().isNotEmpty)
|
||||
.toList();
|
||||
if (result.isEmpty) throw StateError('Server returned no chat backends.');
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<JsonMap> shellOutput(
|
||||
String sessionId,
|
||||
String shellId, {
|
||||
int cursor = 0,
|
||||
int limit = 65536,
|
||||
}) => gateway.call('chat_shell_output', {
|
||||
'chat_shell_output_query': {
|
||||
'session_id': sessionId,
|
||||
'shell_id': shellId,
|
||||
'cursor': cursor,
|
||||
'limit': limit,
|
||||
},
|
||||
});
|
||||
|
||||
Future<JsonMap> history(
|
||||
String sessionId, {
|
||||
int limit = 200,
|
||||
String cursor = '',
|
||||
}) async {
|
||||
final reply = await gateway.call('chat_messages', {
|
||||
'chat_query': {'session_id': sessionId, 'limit': limit, 'cursor': cursor},
|
||||
});
|
||||
final page = reply['chat_history'];
|
||||
if (page is Map) {
|
||||
return {
|
||||
'messages': _maps(page['messages']),
|
||||
'nextCursor': '${page['next_cursor'] ?? ''}',
|
||||
'hasMore': page['has_more'] == true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
'messages': _maps(reply['chat_messages']),
|
||||
'nextCursor': '',
|
||||
'hasMore': false,
|
||||
};
|
||||
}
|
||||
|
||||
Future<JsonMap> subscribe(String sessionId) =>
|
||||
gateway.call('chat_subscribe', {
|
||||
'chat_subscribe': {'session_id': sessionId},
|
||||
});
|
||||
Future<JsonMap> create({
|
||||
required String title,
|
||||
required String directory,
|
||||
required String operationId,
|
||||
String backend = 'opencode',
|
||||
String instructions = '',
|
||||
}) {
|
||||
if (title.trim().isEmpty || directory.trim().isEmpty) {
|
||||
throw ArgumentError('Enter a chat name and choose a directory.');
|
||||
}
|
||||
return gateway.call('chat_create', {
|
||||
'chat_create': {
|
||||
'title': title.trim(),
|
||||
'directory': directory.trim(),
|
||||
'operation_id': operationId,
|
||||
if (backend.isNotEmpty && backend != 'opencode') 'backend': backend,
|
||||
if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
Future<JsonMap> rename(String sessionId, String title) =>
|
||||
gateway.call('chat_rename', {
|
||||
'chat_rename': {'session_id': sessionId, 'title': title.trim()},
|
||||
});
|
||||
Future<JsonMap> star(String sessionId, bool starred) =>
|
||||
gateway.call('chat_star', {
|
||||
'chat_query': {'session_id': sessionId, 'starred': starred},
|
||||
});
|
||||
Future<JsonMap> close(String sessionId) => gateway.call('chat_close', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
});
|
||||
Future<JsonMap> reopen(String sessionId) => gateway.call('chat_reopen', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
});
|
||||
|
||||
Future<JsonMap> prompt(
|
||||
String sessionId,
|
||||
String text, {
|
||||
required String operationId,
|
||||
List<String> files = const [],
|
||||
List<JsonMap> attachments = const [],
|
||||
}) {
|
||||
if (sessionId.trim().isEmpty) {
|
||||
throw ArgumentError('Select a chat session first.');
|
||||
}
|
||||
if (text.trim().isEmpty) {
|
||||
throw ArgumentError('Enter a message before sending.');
|
||||
}
|
||||
final body = <String, dynamic>{
|
||||
'session_id': sessionId,
|
||||
'text': text.trim(),
|
||||
'operation_id': operationId,
|
||||
'native_message_id': nativeChatMessageId(operationId),
|
||||
};
|
||||
if (files.isNotEmpty) body['files'] = files;
|
||||
if (attachments.isNotEmpty) body['attachments'] = attachments;
|
||||
return gateway.call('chat_prompt', {'chat_prompt': body});
|
||||
}
|
||||
|
||||
Future<JsonMap> interrupt(String sessionId) =>
|
||||
gateway.call('chat_interrupt', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
});
|
||||
Future<JsonMap> answerForm(
|
||||
String sessionId,
|
||||
String formId,
|
||||
JsonMap answers, {
|
||||
String action = '',
|
||||
}) => gateway.call('chat_answer', {
|
||||
'chat_answer': {
|
||||
'session_id': sessionId,
|
||||
'form_id': formId,
|
||||
'answers': answers,
|
||||
if (action.isNotEmpty) 'action': action,
|
||||
},
|
||||
});
|
||||
Future<JsonMap> replyPermission(
|
||||
String sessionId,
|
||||
String requestId,
|
||||
String decision, {
|
||||
String client = webChatClient,
|
||||
String message = '',
|
||||
}) {
|
||||
if (sessionId.trim().isEmpty) {
|
||||
throw ArgumentError('Select a chat session first.');
|
||||
}
|
||||
if (requestId.trim().isEmpty) {
|
||||
throw ArgumentError('This approval request is no longer available.');
|
||||
}
|
||||
if (!const ['once', 'always', 'reject'].contains(decision.trim())) {
|
||||
throw ArgumentError('Choose once, always or reject.');
|
||||
}
|
||||
return gateway.call('chat_reply', {
|
||||
'chat_reply': {
|
||||
'session_id': sessionId,
|
||||
'request_id': requestId,
|
||||
'decision': decision,
|
||||
'client': client,
|
||||
if (message.trim().isNotEmpty) 'message': message.trim(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static List<JsonMap> _maps(Object? value) => (value as List? ?? const [])
|
||||
.whereType<Map>()
|
||||
.map((item) => Map<String, dynamic>.from(item))
|
||||
.toList();
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Pure session-list operations. Unknown server fields remain on each row.
|
||||
String chatSessionTitle(JsonMap session) {
|
||||
final title = '${session['title'] ?? ''}';
|
||||
if (title.trim().isNotEmpty) return title;
|
||||
final id = '${session['id'] ?? ''}';
|
||||
return id.isEmpty ? 'Untitled chat' : id.substring(0, id.length.clamp(0, 18));
|
||||
}
|
||||
|
||||
List<JsonMap> filterChatSessions(List<JsonMap> sessions, String query) {
|
||||
final needle = query.trim().toLowerCase();
|
||||
if (needle.isEmpty) return sessions;
|
||||
return sessions
|
||||
.where(
|
||||
(session) =>
|
||||
'${chatSessionTitle(session)}\u0000${session['directory'] ?? ''}'
|
||||
.toLowerCase()
|
||||
.contains(needle),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Directory groups retain server recency order, both within and between groups.
|
||||
List<({String directory, List<JsonMap> sessions})> groupChatSessions(
|
||||
List<JsonMap> sessions,
|
||||
) {
|
||||
final groups = <String, List<JsonMap>>{};
|
||||
for (final session in sessions) {
|
||||
groups.putIfAbsent('${session['directory'] ?? ''}', () => []).add(session);
|
||||
}
|
||||
return groups.entries
|
||||
.map((entry) => (directory: entry.key, sessions: entry.value))
|
||||
.toList();
|
||||
}
|
||||
|
||||
String chatSessionActivity({required bool running, required bool unseen}) =>
|
||||
running
|
||||
? 'streaming'
|
||||
: unseen
|
||||
? 'new'
|
||||
: 'idle';
|
||||
|
||||
/// Native reported values only; missing and invalid values remain unavailable.
|
||||
JsonMap? chatUsageSnapshot(Object? value) {
|
||||
if (value is! Map || value is List) return null;
|
||||
final usage = Map<String, dynamic>.from(value);
|
||||
final result = <String, dynamic>{};
|
||||
for (final key in ['total_tokens', 'context_tokens', 'context_window']) {
|
||||
final n = usage[key];
|
||||
result[key] = n is int && n >= 0 ? n : null;
|
||||
}
|
||||
for (final key in ['cost_usd', 'output_tokens_per_second']) {
|
||||
final n = usage[key];
|
||||
result[key] = n is num && n.isFinite && n >= 0 ? n : null;
|
||||
}
|
||||
result['scope'] = ['session', 'turn'].contains(usage['scope'])
|
||||
? usage['scope']
|
||||
: '';
|
||||
result['rate_basis'] = ['generation', 'turn'].contains(usage['rate_basis'])
|
||||
? usage['rate_basis']
|
||||
: '';
|
||||
return result.values.any((v) => v != null && v != '') ? result : null;
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Merge chronological history pages by message id. Incoming authoritative
|
||||
/// copies replace held copies without changing their order; cursor is opaque.
|
||||
JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) {
|
||||
final held = (previous['messages'] as List? ?? const [])
|
||||
.whereType<Map>()
|
||||
.map((m) => Map<String, dynamic>.from(m))
|
||||
.toList();
|
||||
final incoming = (page['messages'] as List? ?? const [])
|
||||
.whereType<Map>()
|
||||
.map((m) => Map<String, dynamic>.from(m))
|
||||
.toList();
|
||||
final latest = <Object, JsonMap>{};
|
||||
for (final message in incoming) {
|
||||
if (message['id'] != null) latest[message['id']] = message;
|
||||
}
|
||||
final combined = older ? [...incoming, ...held] : [...held, ...incoming];
|
||||
final seen = <Object>{};
|
||||
final messages = <JsonMap>[];
|
||||
for (final message in combined) {
|
||||
final id = message['id'];
|
||||
if (id != null && !seen.add(id)) continue;
|
||||
messages.add(id == null ? message : latest[id] ?? message);
|
||||
}
|
||||
return {
|
||||
'messages': messages,
|
||||
'nextCursor': '${page['nextCursor'] ?? ''}',
|
||||
'hasMore': page['hasMore'] == true,
|
||||
'loaded': true,
|
||||
'loading': false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Consecutive assistant messages form one answer turn. All part fields (also
|
||||
/// future/unknown protocol types) are preserved in original order.
|
||||
List<JsonMap> transcriptRows(List<JsonMap> messages) {
|
||||
final rows = <JsonMap>[];
|
||||
String? key;
|
||||
final parts = <JsonMap>[];
|
||||
void flush() {
|
||||
if (key != null && parts.isNotEmpty) {
|
||||
rows.add({
|
||||
'kind': 'assistant',
|
||||
'key': key,
|
||||
'parts': List<JsonMap>.of(parts),
|
||||
});
|
||||
}
|
||||
key = null;
|
||||
parts.clear();
|
||||
}
|
||||
|
||||
for (final message in messages) {
|
||||
if (message['role'] == 'assistant') {
|
||||
key ??= '${message['id'] ?? ''}';
|
||||
for (final part in (message['parts'] as List? ?? const [])) {
|
||||
if (part is Map) parts.add(Map<String, dynamic>.from(part));
|
||||
}
|
||||
} else {
|
||||
flush();
|
||||
rows.add({'kind': 'user', 'key': message['id'], 'message': message});
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// Replace a local optimistic user row when its server echo identifies the
|
||||
/// same operation/native message; otherwise append once by authoritative id.
|
||||
List<JsonMap> reconcileChatUser(List<JsonMap> messages, JsonMap remote) {
|
||||
final operation = remote['operation_id'];
|
||||
final nativeId = remote['native_message_id'];
|
||||
final id = remote['id'];
|
||||
final index = messages.indexWhere(
|
||||
(message) =>
|
||||
(operation != null && message['operation_id'] == operation) ||
|
||||
(nativeId != null && message['native_message_id'] == nativeId) ||
|
||||
(id != null && message['id'] == id),
|
||||
);
|
||||
if (index < 0) return [...messages, remote];
|
||||
final result = List<JsonMap>.of(messages);
|
||||
result[index] = remote;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Fold a live chat frame into an immutable thread snapshot. Text and reasoning
|
||||
/// deltas append by part id, tool snapshots merge without dropping prior fields,
|
||||
/// and step frames update turn activity. Frames for another session are ignored.
|
||||
JsonMap applyChatEvent(JsonMap thread, JsonMap frame) {
|
||||
final session = thread['sessionId'];
|
||||
if (session != null &&
|
||||
frame['session_id'] != null &&
|
||||
session != frame['session_id']) {
|
||||
return thread;
|
||||
}
|
||||
final messages = (thread['messages'] as List? ?? const [])
|
||||
.whereType<Map>()
|
||||
.map((m) => Map<String, dynamic>.from(m))
|
||||
.toList();
|
||||
final kind = frame['kind'];
|
||||
if (kind == 'user') {
|
||||
final part = frame['part'];
|
||||
final text = part is Map ? part['text'] : null;
|
||||
final id = frame['message_id'];
|
||||
if (text is! String ||
|
||||
text.isEmpty ||
|
||||
id == null ||
|
||||
messages.any(
|
||||
(m) =>
|
||||
m['id'] == id ||
|
||||
(frame['operation_id'] != null &&
|
||||
m['operation_id'] == frame['operation_id']),
|
||||
)) {
|
||||
return thread;
|
||||
}
|
||||
messages.add({
|
||||
'id': id,
|
||||
'session_id': frame['session_id'],
|
||||
'role': 'user',
|
||||
'client': frame['client'],
|
||||
'operation_id': frame['operation_id'],
|
||||
'parts': [
|
||||
{'type': 'text', 'text': text},
|
||||
...(frame['attachments'] is List
|
||||
? frame['attachments'] as List
|
||||
: const []),
|
||||
],
|
||||
});
|
||||
return {...thread, 'messages': messages};
|
||||
}
|
||||
if (kind == 'text' || kind == 'reasoning' || kind == 'tool') {
|
||||
final incoming = frame['part'];
|
||||
if (incoming is! Map || incoming['id'] == null) return thread;
|
||||
final messageId = frame['message_id'];
|
||||
var index = messages.indexWhere(
|
||||
(m) => m['id'] == messageId && m['role'] == 'assistant',
|
||||
);
|
||||
if (index < 0) {
|
||||
messages.add({
|
||||
'id': messageId,
|
||||
'session_id': frame['session_id'],
|
||||
'role': 'assistant',
|
||||
'parts': <JsonMap>[],
|
||||
});
|
||||
index = messages.length - 1;
|
||||
}
|
||||
final message = messages[index];
|
||||
final parts = (message['parts'] as List? ?? const [])
|
||||
.whereType<Map>()
|
||||
.map((p) => Map<String, dynamic>.from(p))
|
||||
.toList();
|
||||
final partIndex = parts.indexWhere(
|
||||
(p) => p['id'] == incoming['id'] && p['type'] == kind,
|
||||
);
|
||||
if (kind == 'text' || kind == 'reasoning') {
|
||||
final delta = frame['delta'];
|
||||
if (delta is! String || delta.isEmpty) return thread;
|
||||
if (partIndex < 0) {
|
||||
parts.add({'type': kind, 'id': incoming['id'], 'text': delta});
|
||||
} else {
|
||||
parts[partIndex] = {
|
||||
...parts[partIndex],
|
||||
'text': '${parts[partIndex]['text'] ?? ''}$delta',
|
||||
};
|
||||
}
|
||||
} else if (partIndex < 0) {
|
||||
parts.add(Map<String, dynamic>.from(incoming));
|
||||
} else {
|
||||
final merged = {
|
||||
...parts[partIndex],
|
||||
...Map<String, dynamic>.from(incoming),
|
||||
};
|
||||
if (parts[partIndex]['state'] is Map && incoming['state'] is Map) {
|
||||
merged['state'] = {
|
||||
...Map<String, dynamic>.from(parts[partIndex]['state'] as Map),
|
||||
...Map<String, dynamic>.from(incoming['state'] as Map),
|
||||
};
|
||||
}
|
||||
parts[partIndex] = merged;
|
||||
}
|
||||
messages[index] = {...message, 'parts': parts};
|
||||
return {...thread, 'messages': messages, 'running': true};
|
||||
}
|
||||
if (kind == 'step' && frame['step'] is Map) {
|
||||
final step = frame['step'] as Map;
|
||||
if (step['intermediate'] == true) return thread;
|
||||
return {
|
||||
...thread,
|
||||
'running': step['status'] != 'ended',
|
||||
'nativeTurnId': step['status'] == 'ended'
|
||||
? ''
|
||||
: (step['turn_id'] ?? thread['nativeTurnId'] ?? ''),
|
||||
};
|
||||
}
|
||||
return thread;
|
||||
}
|
||||
|
||||
/// Queue serialized sends per session; operation ids survive retries/replays.
|
||||
class QueuedChatSend {
|
||||
QueuedChatSend({
|
||||
required this.operationId,
|
||||
required this.text,
|
||||
this.files = const [],
|
||||
});
|
||||
final String operationId;
|
||||
final String text;
|
||||
final List<String> files;
|
||||
|
||||
/// Retry the same immutable intent with the same idempotency key.
|
||||
QueuedChatSend retry() => QueuedChatSend(
|
||||
operationId: operationId,
|
||||
text: text,
|
||||
files: List.unmodifiable(files),
|
||||
);
|
||||
}
|
||||
|
||||
class ChatSendQueue {
|
||||
final Map<String, List<QueuedChatSend>> _sessions = {};
|
||||
List<QueuedChatSend> forSession(String sessionId) =>
|
||||
List.unmodifiable(_sessions[sessionId] ?? const []);
|
||||
bool enqueue(String sessionId, QueuedChatSend send) {
|
||||
final queue = _sessions.putIfAbsent(sessionId, () => []);
|
||||
if (queue.any((item) => item.operationId == send.operationId)) return false;
|
||||
queue.add(send);
|
||||
return true;
|
||||
}
|
||||
|
||||
QueuedChatSend? takeNext(String sessionId) {
|
||||
final queue = _sessions[sessionId];
|
||||
if (queue == null || queue.isEmpty) return null;
|
||||
final result = queue.removeAt(0);
|
||||
if (queue.isEmpty) _sessions.remove(sessionId);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export 'ui/sessions/chat_sessions_screen.dart';
|
||||
@@ -0,0 +1,200 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Which standard control family this screen renders.
|
||||
enum ChatControlsStyle { material, cupertino }
|
||||
|
||||
/// Cupertino under a Cupertino app or an iOS/macOS Material theme, Material
|
||||
/// everywhere else. The shell decides the app class, so a bare Cupertino app
|
||||
/// never has to grow a Material ancestor just for this screen.
|
||||
ChatControlsStyle chatControlsStyleOf(BuildContext context) {
|
||||
if (context.findAncestorWidgetOfExactType<MaterialApp>() == null) {
|
||||
return ChatControlsStyle.cupertino;
|
||||
}
|
||||
final platform = Theme.of(context).platform;
|
||||
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS
|
||||
? ChatControlsStyle.cupertino
|
||||
: ChatControlsStyle.material;
|
||||
}
|
||||
|
||||
class ChatBarAction extends StatelessWidget {
|
||||
const ChatBarAction({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.onPressed,
|
||||
required this.materialIcon,
|
||||
required this.cupertinoIcon,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final VoidCallback onPressed;
|
||||
final IconData materialIcon;
|
||||
final IconData cupertinoIcon;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return Semantics(
|
||||
label: label,
|
||||
button: true,
|
||||
child: CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onPressed,
|
||||
child: Icon(cupertinoIcon),
|
||||
),
|
||||
);
|
||||
}
|
||||
return IconButton(
|
||||
tooltip: label,
|
||||
onPressed: onPressed,
|
||||
icon: Icon(materialIcon),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ChatSearchField extends StatelessWidget {
|
||||
const ChatSearchField({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final TextEditingController controller;
|
||||
final ValueChanged<String> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: CupertinoSearchTextField(
|
||||
controller: controller,
|
||||
placeholder: 'Search chats',
|
||||
onChanged: onChanged,
|
||||
),
|
||||
);
|
||||
}
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: TextField(
|
||||
controller: controller,
|
||||
onChanged: onChanged,
|
||||
decoration: const InputDecoration(
|
||||
prefixIcon: Icon(Icons.search),
|
||||
labelText: 'Search chats',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A grouped Cupertino card for a message that may wrap onto several lines.
|
||||
///
|
||||
/// [CupertinoListTile] forces its title to one ellipsised line, which cut long
|
||||
/// no-match queries and server reasons. This layout keeps the native card but
|
||||
/// lets the message wrap, with its action on a separate button below.
|
||||
class ChatCupertinoMessage extends StatelessWidget {
|
||||
const ChatCupertinoMessage({
|
||||
super.key,
|
||||
required this.message,
|
||||
this.icon,
|
||||
this.actionLabel,
|
||||
this.onAction,
|
||||
});
|
||||
|
||||
final String message;
|
||||
final IconData? icon;
|
||||
final String? actionLabel;
|
||||
final VoidCallback? onAction;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Semantics(
|
||||
container: true,
|
||||
explicitChildNodes: true,
|
||||
child: CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (icon != null) ...[
|
||||
Icon(
|
||||
icon,
|
||||
color: CupertinoColors.secondaryLabel.resolveFrom(context),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
],
|
||||
Expanded(
|
||||
// Cupertino widgets normally supply their own text style.
|
||||
// This card is also mounted under a bare MaterialApp (the
|
||||
// iOS/macOS theme path), where Text would otherwise inherit
|
||||
// MaterialApp's "missing Material" fallback style.
|
||||
child: DefaultTextStyle.merge(
|
||||
style: CupertinoTheme.of(context).textTheme.textStyle,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(message),
|
||||
if (actionLabel != null && onAction != null)
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: CupertinoButton(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
onPressed: onAction,
|
||||
child: Text(actionLabel!),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ChatErrorNotice extends StatelessWidget {
|
||||
const ChatErrorNotice({
|
||||
super.key,
|
||||
required this.message,
|
||||
required this.onRetry,
|
||||
});
|
||||
|
||||
final String message;
|
||||
final VoidCallback onRetry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return ChatCupertinoMessage(
|
||||
message: message,
|
||||
icon: CupertinoIcons.exclamationmark_circle,
|
||||
actionLabel: 'Retry',
|
||||
onAction: onRetry,
|
||||
);
|
||||
}
|
||||
return MaterialBanner(
|
||||
content: Text(message),
|
||||
actions: [TextButton(onPressed: onRetry, child: const Text('Retry'))],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ChatLoadingIndicator extends StatelessWidget {
|
||||
const ChatLoadingIndicator({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? const CupertinoActivityIndicator()
|
||||
: const CircularProgressIndicator(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'chat_adaptive.dart';
|
||||
|
||||
/// The create dialog's server catalog area: loading, error with retry, the
|
||||
/// empty-catalog message, or the two server-backed selectors.
|
||||
class ChatCatalogFields extends StatelessWidget {
|
||||
const ChatCatalogFields({
|
||||
super.key,
|
||||
required this.loading,
|
||||
required this.error,
|
||||
required this.directories,
|
||||
required this.backends,
|
||||
required this.directory,
|
||||
required this.backend,
|
||||
required this.onDirectory,
|
||||
required this.onBackend,
|
||||
required this.onRetry,
|
||||
});
|
||||
|
||||
final bool loading;
|
||||
final String? error;
|
||||
final List<String> directories;
|
||||
final List<String> backends;
|
||||
final String? directory;
|
||||
final String? backend;
|
||||
final ValueChanged<String> onDirectory;
|
||||
final ValueChanged<String> onBackend;
|
||||
final VoidCallback onRetry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
if (loading) return const Text('Loading directories…');
|
||||
if (error != null) {
|
||||
return _message(cupertino, 'Unable to load chat options: $error');
|
||||
}
|
||||
if (directories.isEmpty || backends.isEmpty) {
|
||||
return _message(
|
||||
cupertino,
|
||||
'The server has no chat directories or backends available.',
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (cupertino)
|
||||
CupertinoPickerField(
|
||||
label: 'Server directory',
|
||||
value: directory,
|
||||
values: directories,
|
||||
onSelected: onDirectory,
|
||||
)
|
||||
else
|
||||
MaterialPickerField(
|
||||
label: 'Server directory',
|
||||
value: directory,
|
||||
values: directories,
|
||||
onSelected: onDirectory,
|
||||
),
|
||||
if (cupertino)
|
||||
CupertinoPickerField(
|
||||
label: 'Backend',
|
||||
value: backend,
|
||||
values: backends,
|
||||
onSelected: onBackend,
|
||||
)
|
||||
else
|
||||
MaterialPickerField(
|
||||
label: 'Backend',
|
||||
value: backend,
|
||||
values: backends,
|
||||
onSelected: onBackend,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _message(bool cupertino, String text) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(text),
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: cupertino
|
||||
? CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onRetry,
|
||||
child: const Text('Retry'),
|
||||
)
|
||||
: TextButton(onPressed: onRetry, child: const Text('Retry')),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MaterialPickerField extends StatelessWidget {
|
||||
const MaterialPickerField({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.values,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final String? value;
|
||||
final List<String> values;
|
||||
final ValueChanged<String> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DropdownButtonFormField<String>(
|
||||
key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'),
|
||||
initialValue: value,
|
||||
decoration: InputDecoration(labelText: label),
|
||||
items: [
|
||||
for (final item in values)
|
||||
DropdownMenuItem(value: item, child: Text(item)),
|
||||
],
|
||||
onChanged: (item) {
|
||||
if (item != null) onSelected(item);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CupertinoPickerField extends StatelessWidget {
|
||||
const CupertinoPickerField({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.values,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final String? value;
|
||||
final List<String> values;
|
||||
final ValueChanged<String> onSelected;
|
||||
|
||||
Future<void> _choose(BuildContext context) async {
|
||||
final choice = await showCupertinoModalPopup<String>(
|
||||
context: context,
|
||||
builder: (sheetContext) => CupertinoActionSheet(
|
||||
title: Text(label),
|
||||
actions: [
|
||||
for (final item in values)
|
||||
CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(sheetContext, item),
|
||||
child: Text(item),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(sheetContext),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (choice != null) onSelected(choice);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Semantics(
|
||||
label: '$label: ${value ?? ''}',
|
||||
button: true,
|
||||
child: CupertinoButton(
|
||||
key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'),
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
onPressed: () => _choose(context),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Text('$label: ${value ?? ''}')),
|
||||
const Icon(CupertinoIcons.chevron_down),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
import 'chat_adaptive.dart';
|
||||
import 'session_list_cupertino.dart';
|
||||
import 'session_list_material.dart';
|
||||
import 'session_row_style.dart';
|
||||
|
||||
typedef ChatSessionSection = ({String title, List<JsonMap> sessions});
|
||||
|
||||
/// Groups the visible sessions the way the server reports them.
|
||||
class ChatSessionsBody extends StatelessWidget {
|
||||
const ChatSessionsBody({
|
||||
super.key,
|
||||
required this.sessions,
|
||||
required this.query,
|
||||
required this.loading,
|
||||
required this.error,
|
||||
required this.onOpen,
|
||||
required this.onRename,
|
||||
required this.onClose,
|
||||
required this.onReopen,
|
||||
required this.onStar,
|
||||
required this.onClearSearch,
|
||||
});
|
||||
|
||||
final List<JsonMap> sessions;
|
||||
final String query;
|
||||
final bool loading;
|
||||
final String? error;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> onStar;
|
||||
final VoidCallback onClearSearch;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final visible = filterChatSessions(sessions, query);
|
||||
final sections = <ChatSessionSection>[
|
||||
if (visible.any((s) => s['starred'] == true && s['closed_at'] == null))
|
||||
(
|
||||
title: 'Starred',
|
||||
sessions: visible
|
||||
.where((s) => s['starred'] == true && s['closed_at'] == null)
|
||||
.toList(),
|
||||
),
|
||||
if (visible.any((s) => s['starred'] != true && s['closed_at'] == null))
|
||||
(
|
||||
title: 'Chats',
|
||||
sessions: visible
|
||||
.where((s) => s['starred'] != true && s['closed_at'] == null)
|
||||
.toList(),
|
||||
),
|
||||
if (visible.any((s) => s['closed_at'] != null))
|
||||
(
|
||||
title: 'Closed',
|
||||
sessions: visible.where((s) => s['closed_at'] != null).toList(),
|
||||
),
|
||||
];
|
||||
final emptyMessage = sessions.isEmpty
|
||||
? error == null
|
||||
? 'No chat sessions on this server yet.'
|
||||
: null
|
||||
: 'No chats match "${query.trim()}".';
|
||||
|
||||
if (loading && sessions.isEmpty) return const ChatLoadingIndicator();
|
||||
final clearSearch = query.trim().isEmpty ? null : onClearSearch;
|
||||
final duplicateTitles = duplicateChatTitles(visible);
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return CupertinoSessionList(
|
||||
sections: sections,
|
||||
emptyMessage: visible.isEmpty ? emptyMessage : null,
|
||||
duplicateTitles: duplicateTitles,
|
||||
onOpen: onOpen,
|
||||
onRename: onRename,
|
||||
onClose: onClose,
|
||||
onReopen: onReopen,
|
||||
onStar: onStar,
|
||||
onClearSearch: clearSearch,
|
||||
);
|
||||
}
|
||||
return MaterialSessionList(
|
||||
sections: sections,
|
||||
emptyMessage: visible.isEmpty ? emptyMessage : null,
|
||||
duplicateTitles: duplicateTitles,
|
||||
onOpen: onOpen,
|
||||
onRename: onRename,
|
||||
onClose: onClose,
|
||||
onReopen: onReopen,
|
||||
onStar: onStar,
|
||||
onClearSearch: clearSearch,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../data/chat_repository.dart';
|
||||
|
||||
/// Owns the session list, its refresh generation and the row actions.
|
||||
///
|
||||
/// A refresh that finishes after a newer one (or after the screen is gone) is
|
||||
/// discarded, so a slow reply can never replace fresher state.
|
||||
class ChatSessionsController extends ChangeNotifier {
|
||||
ChatSessionsController(this.repository);
|
||||
|
||||
ChatRepository repository;
|
||||
List<JsonMap> _sessions = const [];
|
||||
String? _error;
|
||||
bool _loading = true;
|
||||
bool _disposed = false;
|
||||
int _generation = 0;
|
||||
|
||||
List<JsonMap> get sessions => _sessions;
|
||||
String? get error => _error;
|
||||
bool get loading => _loading;
|
||||
|
||||
void replaceRepository(ChatRepository next) {
|
||||
if (identical(next.gateway, repository.gateway)) return;
|
||||
repository = next;
|
||||
refresh();
|
||||
}
|
||||
|
||||
Future<void> refresh() async {
|
||||
if (_disposed) return;
|
||||
final generation = ++_generation;
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_notify();
|
||||
try {
|
||||
final sessions = await repository.sessions();
|
||||
if (generation != _generation) return;
|
||||
_sessions = sessions;
|
||||
_loading = false;
|
||||
_notify();
|
||||
} catch (error) {
|
||||
if (generation != _generation) return;
|
||||
_error = '$error';
|
||||
_loading = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> star(String sessionId, bool starred) =>
|
||||
_mutate(() => repository.star(sessionId, starred));
|
||||
|
||||
Future<void> close(String sessionId) =>
|
||||
_mutate(() => repository.close(sessionId));
|
||||
|
||||
Future<void> reopen(String sessionId) =>
|
||||
_mutate(() => repository.reopen(sessionId));
|
||||
|
||||
Future<void> rename(String sessionId, String title) =>
|
||||
_mutate(() => repository.rename(sessionId, title));
|
||||
|
||||
Future<JsonMap?> create({
|
||||
required String title,
|
||||
required String directory,
|
||||
required String backend,
|
||||
required String instructions,
|
||||
required String operationId,
|
||||
}) async {
|
||||
try {
|
||||
final reply = await repository.create(
|
||||
title: title,
|
||||
directory: directory,
|
||||
backend: backend,
|
||||
operationId: operationId,
|
||||
instructions: instructions,
|
||||
);
|
||||
// Opening the created chat must not wait for the list refresh: the dialog
|
||||
// has already closed, so a slow listing would look like a failed create.
|
||||
unawaited(refresh());
|
||||
final session = reply['chat_session'];
|
||||
return session is Map ? Map<String, dynamic>.from(session) : null;
|
||||
} catch (error) {
|
||||
_error = '$error';
|
||||
_notify();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _mutate(Future<JsonMap> Function() action) async {
|
||||
try {
|
||||
await action();
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
_error = '$error';
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_generation++;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../data/chat_repository.dart';
|
||||
import 'chat_adaptive.dart';
|
||||
import 'chat_sessions_body.dart';
|
||||
import 'chat_sessions_controller.dart';
|
||||
import 'create_chat_dialog.dart';
|
||||
import 'rename_chat_dialog.dart';
|
||||
import 'session_actions.dart';
|
||||
|
||||
/// Browses server-owned sessions. Opening a row is read-only at this layer.
|
||||
class ChatSessionsScreen extends StatefulWidget {
|
||||
const ChatSessionsScreen({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
required this.onOpen,
|
||||
});
|
||||
final ApiGateway gateway;
|
||||
final void Function(JsonMap session) onOpen;
|
||||
|
||||
@override
|
||||
State<ChatSessionsScreen> createState() => _ChatSessionsScreenState();
|
||||
}
|
||||
|
||||
class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
late final ChatSessionsController _controller = ChatSessionsController(
|
||||
ChatRepository(widget.gateway),
|
||||
)..refresh();
|
||||
final _search = TextEditingController();
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.gateway != widget.gateway) {
|
||||
_controller.replaceRepository(ChatRepository(widget.gateway));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
_search.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String _sessionId(JsonMap session) => '${session['id'] ?? ''}';
|
||||
|
||||
Future<void> _rename(JsonMap session) async {
|
||||
final title = await showRenameChatDialog(context, session);
|
||||
if (title == null || !mounted) return;
|
||||
await _controller.rename(_sessionId(session), title);
|
||||
}
|
||||
|
||||
Future<void> _close(JsonMap session) async {
|
||||
if (!await confirmCloseChat(context, session)) return;
|
||||
if (!mounted) return;
|
||||
await _controller.close(_sessionId(session));
|
||||
}
|
||||
|
||||
Future<void> _newChat() async {
|
||||
final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}';
|
||||
final draft = await showChatCreateDialog(
|
||||
context,
|
||||
repository: _controller.repository,
|
||||
);
|
||||
if (draft == null || !mounted) return;
|
||||
final session = await _controller.create(
|
||||
title: draft.title,
|
||||
directory: draft.directory,
|
||||
backend: draft.backend,
|
||||
instructions: draft.instructions,
|
||||
operationId: operationId,
|
||||
);
|
||||
if (session != null && mounted) widget.onOpen(session);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: _controller,
|
||||
builder: (context, _) {
|
||||
final body = Column(
|
||||
children: [
|
||||
ChatSearchField(
|
||||
controller: _search,
|
||||
onChanged: (_) => setState(() {}),
|
||||
),
|
||||
if (_controller.error != null)
|
||||
ChatErrorNotice(
|
||||
message: _controller.error!,
|
||||
onRetry: _controller.refresh,
|
||||
),
|
||||
Expanded(
|
||||
child: ChatSessionsBody(
|
||||
sessions: _controller.sessions,
|
||||
query: _search.text,
|
||||
loading: _controller.loading,
|
||||
error: _controller.error,
|
||||
onOpen: widget.onOpen,
|
||||
onRename: _rename,
|
||||
onClose: _close,
|
||||
onReopen: (session) => _controller.reopen(_sessionId(session)),
|
||||
onStar: (session) => _controller.star(
|
||||
_sessionId(session),
|
||||
session['starred'] != true,
|
||||
),
|
||||
onClearSearch: () {
|
||||
_search.clear();
|
||||
setState(() {});
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
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,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
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,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: body,
|
||||
floatingActionButton: FloatingActionButton.extended(
|
||||
key: const Key('chat-new-chat-fab'),
|
||||
onPressed: _newChat,
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('New chat'),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../data/chat_repository.dart';
|
||||
import 'chat_adaptive.dart';
|
||||
import 'chat_create_fields.dart';
|
||||
|
||||
class ChatDraft {
|
||||
const ChatDraft({
|
||||
required this.title,
|
||||
required this.directory,
|
||||
required this.backend,
|
||||
required this.instructions,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String directory;
|
||||
final String backend;
|
||||
final String instructions;
|
||||
}
|
||||
|
||||
Future<ChatDraft?> showChatCreateDialog(
|
||||
BuildContext context, {
|
||||
required ChatRepository repository,
|
||||
}) {
|
||||
final dialog = CreateChatDialog(repository: repository);
|
||||
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? showCupertinoDialog<ChatDraft>(context: context, builder: (_) => dialog)
|
||||
: showDialog<ChatDraft>(context: context, builder: (_) => dialog);
|
||||
}
|
||||
|
||||
class CreateChatDialog extends StatefulWidget {
|
||||
const CreateChatDialog({super.key, required this.repository});
|
||||
|
||||
final ChatRepository repository;
|
||||
|
||||
@override
|
||||
State<CreateChatDialog> createState() => _CreateChatDialogState();
|
||||
}
|
||||
|
||||
class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
final _name = TextEditingController(text: 'New chat');
|
||||
final _instructions = TextEditingController();
|
||||
List<String> _directories = const [];
|
||||
List<String> _backends = const [];
|
||||
String? _directory;
|
||||
String? _backend;
|
||||
String? _catalogError;
|
||||
String? _formError;
|
||||
bool _loading = true;
|
||||
int _attempt = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadCatalog();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_attempt++;
|
||||
_name.dispose();
|
||||
_instructions.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadCatalog() async {
|
||||
final attempt = ++_attempt;
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_catalogError = null;
|
||||
});
|
||||
try {
|
||||
final values = await Future.wait([
|
||||
widget.repository.directories(),
|
||||
widget.repository.backends(),
|
||||
]);
|
||||
if (!mounted || attempt != _attempt) return;
|
||||
setState(() {
|
||||
_directories = values[0];
|
||||
_backends = values[1];
|
||||
_directory = _directories.contains(_directory)
|
||||
? _directory
|
||||
: _directories.isEmpty
|
||||
? null
|
||||
: _directories.first;
|
||||
_backend = _backends.contains(_backend)
|
||||
? _backend
|
||||
: _backends.isEmpty
|
||||
? null
|
||||
: _backends.first;
|
||||
_loading = false;
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted || attempt != _attempt) return;
|
||||
setState(() {
|
||||
_catalogError = '$error';
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
bool get _catalogReady =>
|
||||
!_loading &&
|
||||
_catalogError == null &&
|
||||
_directories.isNotEmpty &&
|
||||
_backends.isNotEmpty;
|
||||
|
||||
void _submit() {
|
||||
if (!_catalogReady) return;
|
||||
final title = _name.text.trim();
|
||||
final directory = _directory ?? '';
|
||||
if (title.isEmpty || directory.isEmpty) {
|
||||
setState(() => _formError = 'Enter a name and server directory.');
|
||||
return;
|
||||
}
|
||||
Navigator.pop(
|
||||
context,
|
||||
ChatDraft(
|
||||
title: title,
|
||||
directory: directory,
|
||||
backend: _backend ?? '',
|
||||
instructions: _instructions.text,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final content = SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (cupertino)
|
||||
CupertinoTextField(
|
||||
key: const Key('chat-create-name'),
|
||||
controller: _name,
|
||||
placeholder: 'Name',
|
||||
)
|
||||
else
|
||||
TextField(
|
||||
key: const Key('chat-create-name'),
|
||||
controller: _name,
|
||||
decoration: const InputDecoration(labelText: 'Name'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ChatCatalogFields(
|
||||
loading: _loading,
|
||||
error: _catalogError,
|
||||
directories: _directories,
|
||||
backends: _backends,
|
||||
directory: _directory,
|
||||
backend: _backend,
|
||||
onDirectory: (value) => setState(() => _directory = value),
|
||||
onBackend: (value) => setState(() => _backend = value),
|
||||
onRetry: _loadCatalog,
|
||||
),
|
||||
if (_catalogReady) ...[
|
||||
const SizedBox(height: 8),
|
||||
const Text('New chats use the server default model.'),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
if (cupertino)
|
||||
CupertinoTextField(
|
||||
key: const Key('chat-create-instructions'),
|
||||
controller: _instructions,
|
||||
placeholder: 'Instructions',
|
||||
minLines: 1,
|
||||
maxLines: 3,
|
||||
)
|
||||
else
|
||||
TextField(
|
||||
key: const Key('chat-create-instructions'),
|
||||
controller: _instructions,
|
||||
decoration: const InputDecoration(labelText: 'Instructions'),
|
||||
minLines: 1,
|
||||
maxLines: 3,
|
||||
),
|
||||
if (_formError != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(_formError!),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (cupertino) {
|
||||
return CupertinoAlertDialog(
|
||||
title: const Text('New chat'),
|
||||
content: content,
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
isDefaultAction: true,
|
||||
onPressed: _catalogReady ? _submit : null,
|
||||
child: const Text('Create'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return AlertDialog(
|
||||
title: const Text('New chat'),
|
||||
content: content,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _catalogReady ? _submit : null,
|
||||
child: const Text('Create'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
import 'chat_adaptive.dart';
|
||||
|
||||
/// Renames one session. Save is disabled while the trimmed name is blank,
|
||||
/// matching the web dialog.
|
||||
Future<String?> showRenameChatDialog(BuildContext context, JsonMap session) {
|
||||
final dialog = _RenameChatDialog(initialTitle: chatSessionTitle(session));
|
||||
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? showCupertinoDialog<String>(context: context, builder: (_) => dialog)
|
||||
: showDialog<String>(context: context, builder: (_) => dialog);
|
||||
}
|
||||
|
||||
class _RenameChatDialog extends StatefulWidget {
|
||||
const _RenameChatDialog({required this.initialTitle});
|
||||
|
||||
final String initialTitle;
|
||||
|
||||
@override
|
||||
State<_RenameChatDialog> createState() => _RenameChatDialogState();
|
||||
}
|
||||
|
||||
class _RenameChatDialogState extends State<_RenameChatDialog> {
|
||||
late final TextEditingController _title =
|
||||
TextEditingController(text: widget.initialTitle)
|
||||
..selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: widget.initialTitle.length,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_title.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _save() {
|
||||
final title = _title.text.trim();
|
||||
if (title.isEmpty) return;
|
||||
Navigator.pop(context, title);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ValueListenableBuilder<TextEditingValue>(
|
||||
valueListenable: _title,
|
||||
builder: (context, value, _) {
|
||||
final canSave = value.text.trim().isNotEmpty;
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return CupertinoAlertDialog(
|
||||
title: const Text('Rename chat'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CupertinoTextField(
|
||||
key: const Key('chat-rename-field'),
|
||||
controller: _title,
|
||||
autofocus: true,
|
||||
placeholder: 'Name',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text('This name is shared with every device.'),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
isDefaultAction: true,
|
||||
onPressed: canSave ? _save : null,
|
||||
child: const Text('Save'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return AlertDialog(
|
||||
title: const Text('Rename chat'),
|
||||
content: TextField(
|
||||
key: const Key('chat-rename-field'),
|
||||
controller: _title,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Name',
|
||||
helperText: 'This name is shared with every device.',
|
||||
helperMaxLines: 2,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: canSave ? _save : null,
|
||||
child: const Text('Save'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
import 'chat_adaptive.dart';
|
||||
import 'session_row_style.dart';
|
||||
|
||||
enum SessionAction { rename, close, reopen }
|
||||
|
||||
/// The close confirmation's body, matching the web client's explanation.
|
||||
String closeChatConfirmation(String title) =>
|
||||
'Closes "$title" and marks it closed on every device. '
|
||||
'A turn that is running is stopped first. '
|
||||
'Nothing is deleted — the chat and its history are kept, '
|
||||
'and you can reopen it from the list.';
|
||||
|
||||
class SessionStarButton extends StatelessWidget {
|
||||
const SessionStarButton({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
final JsonMap session;
|
||||
final VoidCallback onPressed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final starred = session['starred'] == true;
|
||||
final label = starred ? 'Unstar chat' : 'Star chat';
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return Semantics(
|
||||
label: label,
|
||||
button: true,
|
||||
child: CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onPressed,
|
||||
child: Icon(starred ? CupertinoIcons.star_fill : CupertinoIcons.star),
|
||||
),
|
||||
);
|
||||
}
|
||||
return IconButton(
|
||||
tooltip: label,
|
||||
onPressed: onPressed,
|
||||
icon: Icon(starred ? Icons.star : Icons.star_border),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SessionActionsButton extends StatelessWidget {
|
||||
const SessionActionsButton({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.onSelected,
|
||||
this.duplicateTitles = const {},
|
||||
});
|
||||
|
||||
final JsonMap session;
|
||||
final ValueChanged<SessionAction> onSelected;
|
||||
final Set<String> duplicateTitles;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final label = sessionActionsLabel(session, duplicateTitles);
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return Semantics(
|
||||
label: label,
|
||||
button: true,
|
||||
child: CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: () => _showSheet(context),
|
||||
child: const Icon(CupertinoIcons.ellipsis),
|
||||
),
|
||||
);
|
||||
}
|
||||
return PopupMenuButton<SessionAction>(
|
||||
tooltip: label,
|
||||
onSelected: onSelected,
|
||||
itemBuilder: (context) => _menuItems(session),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showSheet(BuildContext context) async {
|
||||
final action = await showCupertinoModalPopup<SessionAction>(
|
||||
context: context,
|
||||
builder: (sheetContext) => CupertinoActionSheet(
|
||||
title: Text(chatSessionTitle(session)),
|
||||
actions: [
|
||||
for (final item in _items(session))
|
||||
CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(sheetContext, item.action),
|
||||
child: Text(item.label),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(sheetContext),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (action != null && context.mounted) onSelected(action);
|
||||
}
|
||||
}
|
||||
|
||||
List<PopupMenuEntry<SessionAction>> _menuItems(JsonMap session) => [
|
||||
for (final item in _items(session))
|
||||
PopupMenuItem(value: item.action, child: Text(item.label)),
|
||||
];
|
||||
|
||||
List<({SessionAction action, String label})> _items(JsonMap session) {
|
||||
final isClosed = session['closed_at'] != null;
|
||||
return [
|
||||
(action: SessionAction.rename, label: 'Rename…'),
|
||||
isClosed
|
||||
? (action: SessionAction.reopen, label: 'Reopen')
|
||||
: (action: SessionAction.close, label: 'Close chat…'),
|
||||
];
|
||||
}
|
||||
|
||||
Future<bool> confirmCloseChat(BuildContext context, JsonMap session) async {
|
||||
final title = chatSessionTitle(session);
|
||||
final body = closeChatConfirmation(title);
|
||||
final confirmed = chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? await showCupertinoDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => CupertinoAlertDialog(
|
||||
title: const Text('Close chat?'),
|
||||
content: Text(body),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
isDestructiveAction: true,
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('Close chat'),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Close chat?'),
|
||||
content: Text(body),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('Close chat'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
return confirmed == true;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
import 'chat_adaptive.dart';
|
||||
import 'chat_sessions_body.dart';
|
||||
import 'session_actions.dart';
|
||||
import 'session_row_style.dart';
|
||||
|
||||
class CupertinoSessionList extends StatelessWidget {
|
||||
const CupertinoSessionList({
|
||||
super.key,
|
||||
required this.sections,
|
||||
required this.emptyMessage,
|
||||
required this.duplicateTitles,
|
||||
required this.onOpen,
|
||||
required this.onRename,
|
||||
required this.onClose,
|
||||
required this.onReopen,
|
||||
required this.onStar,
|
||||
required this.onClearSearch,
|
||||
});
|
||||
|
||||
final List<ChatSessionSection> sections;
|
||||
final String? emptyMessage;
|
||||
final Set<String> duplicateTitles;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> onStar;
|
||||
final VoidCallback? onClearSearch;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.only(bottom: 24),
|
||||
children: [
|
||||
for (final section in sections) ..._section(section),
|
||||
if (emptyMessage != null)
|
||||
ChatCupertinoMessage(
|
||||
message: emptyMessage!,
|
||||
actionLabel: onClearSearch == null ? null : 'Clear search',
|
||||
onAction: onClearSearch,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
List<CupertinoListSection> _section(ChatSessionSection section) {
|
||||
final groups = groupChatSessions(section.sessions);
|
||||
return [
|
||||
for (final group in groups)
|
||||
CupertinoListSection.insetGrouped(
|
||||
header: Text(
|
||||
groups.length > 1
|
||||
? '${section.title} · ${group.directory.isEmpty ? 'No directory' : group.directory}'
|
||||
: section.title,
|
||||
),
|
||||
children: [
|
||||
for (final session in group.sessions)
|
||||
_CupertinoSessionRow(
|
||||
session: session,
|
||||
duplicateTitles: duplicateTitles,
|
||||
onOpen: onOpen,
|
||||
onRename: onRename,
|
||||
onClose: onClose,
|
||||
onReopen: onReopen,
|
||||
onStar: onStar,
|
||||
),
|
||||
],
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
class _CupertinoSessionRow extends StatelessWidget {
|
||||
const _CupertinoSessionRow({
|
||||
required this.session,
|
||||
required this.duplicateTitles,
|
||||
required this.onOpen,
|
||||
required this.onRename,
|
||||
required this.onClose,
|
||||
required this.onReopen,
|
||||
required this.onStar,
|
||||
});
|
||||
|
||||
final JsonMap session;
|
||||
final Set<String> duplicateTitles;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> onStar;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
return CupertinoListTile(
|
||||
key: Key('chat-row-$id'),
|
||||
leading: Icon(sessionCupertinoIcon(session)),
|
||||
title: Text(chatSessionTitle(session)),
|
||||
subtitle: Text(sessionSubtitle(session)),
|
||||
onTap: () => onOpen(session),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SessionStarButton(
|
||||
key: Key('chat-star-$id'),
|
||||
session: session,
|
||||
onPressed: () => onStar(session),
|
||||
),
|
||||
SessionActionsButton(
|
||||
key: Key('chat-actions-$id'),
|
||||
session: session,
|
||||
duplicateTitles: duplicateTitles,
|
||||
onSelected: _select,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _select(SessionAction action) {
|
||||
switch (action) {
|
||||
case SessionAction.rename:
|
||||
onRename(session);
|
||||
case SessionAction.close:
|
||||
onClose(session);
|
||||
case SessionAction.reopen:
|
||||
onReopen(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
import 'chat_sessions_body.dart';
|
||||
import 'session_actions.dart';
|
||||
import 'session_row_style.dart';
|
||||
|
||||
class MaterialSessionList extends StatelessWidget {
|
||||
const MaterialSessionList({
|
||||
super.key,
|
||||
required this.sections,
|
||||
required this.emptyMessage,
|
||||
required this.duplicateTitles,
|
||||
required this.onOpen,
|
||||
required this.onRename,
|
||||
required this.onClose,
|
||||
required this.onReopen,
|
||||
required this.onStar,
|
||||
required this.onClearSearch,
|
||||
});
|
||||
|
||||
final List<ChatSessionSection> sections;
|
||||
final String? emptyMessage;
|
||||
final Set<String> duplicateTitles;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> onStar;
|
||||
final VoidCallback? onClearSearch;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
children: [
|
||||
for (final section in sections) _section(section),
|
||||
if (emptyMessage != null)
|
||||
ListTile(
|
||||
title: Text(emptyMessage!),
|
||||
trailing: onClearSearch == null
|
||||
? null
|
||||
: TextButton(
|
||||
onPressed: onClearSearch,
|
||||
child: const Text('Clear search'),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _section(ChatSessionSection section) {
|
||||
final groups = groupChatSessions(section.sessions);
|
||||
return ExpansionTile(
|
||||
title: Text(section.title),
|
||||
initiallyExpanded: true,
|
||||
children: [
|
||||
for (final group in groups) ...[
|
||||
if (groups.length > 1)
|
||||
ListTile(
|
||||
dense: true,
|
||||
leading: const Icon(Icons.folder_outlined),
|
||||
title: Text(
|
||||
group.directory.isEmpty ? 'No directory' : group.directory,
|
||||
),
|
||||
),
|
||||
for (final session in group.sessions)
|
||||
_MaterialSessionRow(
|
||||
session: session,
|
||||
duplicateTitles: duplicateTitles,
|
||||
onOpen: onOpen,
|
||||
onRename: onRename,
|
||||
onClose: onClose,
|
||||
onReopen: onReopen,
|
||||
onStar: onStar,
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MaterialSessionRow extends StatelessWidget {
|
||||
const _MaterialSessionRow({
|
||||
required this.session,
|
||||
required this.duplicateTitles,
|
||||
required this.onOpen,
|
||||
required this.onRename,
|
||||
required this.onClose,
|
||||
required this.onReopen,
|
||||
required this.onStar,
|
||||
});
|
||||
|
||||
final JsonMap session;
|
||||
final Set<String> duplicateTitles;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> onStar;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
return ListTile(
|
||||
key: Key('chat-row-$id'),
|
||||
leading: Icon(sessionMaterialIcon(session)),
|
||||
title: Text(chatSessionTitle(session)),
|
||||
subtitle: Text(sessionSubtitle(session)),
|
||||
onTap: () => onOpen(session),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SessionStarButton(
|
||||
key: Key('chat-star-$id'),
|
||||
session: session,
|
||||
onPressed: () => onStar(session),
|
||||
),
|
||||
SessionActionsButton(
|
||||
key: Key('chat-actions-$id'),
|
||||
session: session,
|
||||
duplicateTitles: duplicateTitles,
|
||||
onSelected: (action) => _select(action),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _select(SessionAction action) {
|
||||
switch (action) {
|
||||
case SessionAction.rename:
|
||||
onRename(session);
|
||||
case SessionAction.close:
|
||||
onClose(session);
|
||||
case SessionAction.reopen:
|
||||
onReopen(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
|
||||
/// Titles shared by more than one visible session, so row action labels can
|
||||
/// add the session id the way the web client does.
|
||||
Set<String> duplicateChatTitles(Iterable<JsonMap> sessions) {
|
||||
final seen = <String>{};
|
||||
final duplicates = <String>{};
|
||||
for (final session in sessions) {
|
||||
final title = chatSessionTitle(session);
|
||||
if (!seen.add(title)) duplicates.add(title);
|
||||
}
|
||||
return duplicates;
|
||||
}
|
||||
|
||||
String sessionActionsLabel(JsonMap session, Set<String> duplicateTitles) {
|
||||
final title = chatSessionTitle(session);
|
||||
return duplicateTitles.contains(title)
|
||||
? 'Chat actions for $title (${session['id'] ?? ''})'
|
||||
: 'Chat actions for $title';
|
||||
}
|
||||
|
||||
String sessionSubtitle(JsonMap session) {
|
||||
final directory = '${session['directory'] ?? ''}';
|
||||
switch (chatSessionActivity(
|
||||
running: session['running'] == true,
|
||||
unseen: session['unseen'] == true,
|
||||
)) {
|
||||
case 'streaming':
|
||||
return '$directory · Streaming';
|
||||
case 'new':
|
||||
return '$directory · New';
|
||||
default:
|
||||
return directory;
|
||||
}
|
||||
}
|
||||
|
||||
IconData sessionMaterialIcon(JsonMap session) {
|
||||
if (session['running'] == true) return Icons.sync;
|
||||
if (session['starred'] == true) return Icons.star;
|
||||
return Icons.chat_bubble_outline;
|
||||
}
|
||||
|
||||
IconData sessionCupertinoIcon(JsonMap session) {
|
||||
if (session['running'] == true) return CupertinoIcons.arrow_2_circlepath;
|
||||
if (session['starred'] == true) return CupertinoIcons.star_fill;
|
||||
return CupertinoIcons.chat_bubble;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# C1 — Chat sessions and repository adapter
|
||||
|
||||
The sessions browser now requests server directory and backend catalogs before showing the create dialog, exposes both selectors and model-default guidance, and reports unavailable catalog capabilities instead of silently substituting values. Catalog envelope regressions are covered. Closed starred rows no longer appear twice; directory headings appear only when grouping multiple directories; empty and search-no-match states are distinct.
|
||||
|
||||
Verification: focused chat tests, `flutter analyze`, fixture `flutter build web -t tool/chat_sessions_probe_entry.dart`, `git diff --check`, and an isolated Chrome DevTools probe passed. Captures: `/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/chat-sessions-capture/chat-sessions-phone.png` and `chat-sessions-create-dialog.png` (plus desktop). The probe enabled semantics, matched the exact “New chat” label, and verified the rendered body changed to show server catalog controls. Cupertino-specific controls, controller/row/dialog decomposition under 250 lines, and wider out-of-order reply UI regression coverage remain incomplete; this is not a parity-complete delivery. Mobile builds were not performed. The fixture entry point is `tool/chat_sessions_probe_entry.dart`.
|
||||
@@ -0,0 +1,163 @@
|
||||
# C1b — Chat session browser completion
|
||||
|
||||
The 406-line sessions screen is split into a controller, adaptive primitives,
|
||||
session groups/rows, action dialogs, a rename dialog and a create dialog. The
|
||||
server directory and backend catalogs, the instructions field, the closed/star
|
||||
grouping and the distinct empty/no-match states are retained. No repository,
|
||||
domain, shell or pubspec file changed.
|
||||
|
||||
The UI review's must-fix is addressed: Cupertino no-match, empty and error
|
||||
messages are no longer forced through `CupertinoListTile`'s one-line title. They
|
||||
use a wrapping grouped card with `Clear search`/`Retry` as separate buttons. The
|
||||
same turn also fixed the related behavioural findings: a failed initial load no
|
||||
longer also shows the empty-server message, creating a chat opens it without
|
||||
waiting for the list refresh, blank rename disables Save, and row action labels
|
||||
name their session (adding the id when titles repeat).
|
||||
|
||||
The second UI review's must-fixes are also addressed:
|
||||
|
||||
- `ChatCupertinoMessage` now sets `DefaultTextStyle.merge` from
|
||||
`CupertinoTheme.of(context).textTheme.textStyle`. Mounted under a bare
|
||||
`MaterialApp` (the screen's iOS/macOS path, no `Material` ancestor), its text
|
||||
previously inherited MaterialApp's intentional "missing Material" fallback
|
||||
style (48px red monospace with a double yellow underline). The card now
|
||||
renders as ordinary Cupertino body text in that configuration.
|
||||
- The Material rename dialog sets `helperMaxLines: 2`, so "This name is shared
|
||||
with every device." wraps instead of being ellipsised at 2.0x text scale.
|
||||
|
||||
## Source layout
|
||||
|
||||
All paths under `lib/features/chat/ui/sessions/` (1,584 lines total):
|
||||
|
||||
| File | Lines | Responsibility |
|
||||
| --- | ---: | --- |
|
||||
| `chat_sessions_screen.dart` | 176 | Screen composition, toolbar/FAB, controller wiring |
|
||||
| `chat_sessions_controller.dart` | 111 | List state, generation-guarded refresh, row actions, create |
|
||||
| `chat_sessions_body.dart` | 97 | Filtering, starred/open/closed sections, duplicate titles |
|
||||
| `session_list_material.dart` | 140 | Material list sections and rows |
|
||||
| `session_list_cupertino.dart` | 134 | Cupertino list sections and rows |
|
||||
| `session_row_style.dart` | 51 | Shared subtitle, icons and action labels |
|
||||
| `session_actions.dart` | 161 | Star control, actions menu/sheet, close confirmation |
|
||||
| `rename_chat_dialog.dart` | 107 | Rename dialog and its blank-name guard |
|
||||
| `create_chat_dialog.dart` | 222 | Create state, draft fields, submit |
|
||||
| `chat_create_fields.dart` | 185 | Catalog loading/error/retry and directory/backend pickers |
|
||||
| `chat_adaptive.dart` | 200 | Style detection, bar actions, search, wrapping message card, loading |
|
||||
|
||||
`chatControlsStyleOf` chooses Cupertino for a Cupertino app (no `MaterialApp`
|
||||
ancestor) and for iOS/macOS Material themes; Material otherwise. The Cupertino
|
||||
branch uses only Cupertino controls (`CupertinoPageScaffold`,
|
||||
`CupertinoNavigationBar`, `CupertinoSearchTextField`, `CupertinoListSection`/
|
||||
`CupertinoListTile`, `CupertinoAlertDialog`, `CupertinoActionSheet`,
|
||||
`CupertinoTextField`, `CupertinoActivityIndicator`). It therefore has no
|
||||
Material ancestor dependency. The `SafeArea` in that branch keeps the search
|
||||
field below the translucent navigation bar (the first browser capture caught
|
||||
this overlap).
|
||||
|
||||
Behavior:
|
||||
|
||||
- `chat_sessions`, `chat_directories`, `chat_backends` and `chat_create` use the
|
||||
existing repository envelopes; no fallback directory or backend is invented.
|
||||
- A catalog failure keeps the dialog open, shows the server reason with Retry,
|
||||
and retains the typed name and instructions.
|
||||
- Closed starred rows appear once, only under Closed.
|
||||
- Directory headings appear only when a section has more than one directory.
|
||||
- Empty and search-no-match states stay distinct; "Clear search" restores the
|
||||
list. In the Cupertino branch the message and its action are a wrapping
|
||||
`ChatCupertinoMessage` card, and a failed load uses the same card for the
|
||||
server reason with Retry. The failed initial load no longer also renders the
|
||||
empty-server message. The card supplies a Cupertino text style, so it renders
|
||||
normally when the Cupertino branch is mounted under the app's bare
|
||||
`MaterialApp` root instead of a `Material`/`CupertinoApp`.
|
||||
- Creating a chat opens it as soon as `chat_create` replies; the list refresh
|
||||
continues in the background, so a slow listing cannot look like a failed
|
||||
create.
|
||||
- Star, rename, close (with the web's confirmation wording), reopen and row
|
||||
opening keep their existing request shapes. Save is disabled while the
|
||||
rename name is blank, matching the web dialog.
|
||||
- Row action labels are `Chat actions for {title}`, adding `({id})` when two
|
||||
visible sessions share a title, matching the web's accessible label.
|
||||
|
||||
## Checks (actual)
|
||||
|
||||
- `flutter test test/features/chat/ui/sessions`: 24 widget tests, all passed.
|
||||
They cover Material and Cupertino list branches, both create branches, the
|
||||
delayed catalog failure with draft retention and Retry, rename/close/reopen/
|
||||
star, blank-name Save disabling in both branches, the close confirmation,
|
||||
catalog-empty state, stale refresh ordering, dispose while a reply is
|
||||
pending, opening a created chat before the refresh completes, Cupertino
|
||||
no-match/error wrapping (including 2x text scale), separate Clear search
|
||||
semantics, duplicate-title action labels, the Cupertino message card under a
|
||||
bare `MaterialApp` iOS theme (empty, no-match, long error style), and the
|
||||
Material rename helper at 2x text scale. The three MaterialApp-hosted tests
|
||||
fail when the `DefaultTextStyle` merge is removed (verified).
|
||||
- `flutter test`: 46 tests passed.
|
||||
- `flutter analyze`: no issues.
|
||||
- `flutter build web`: built `lib/main.dart` successfully.
|
||||
- Fixture probe built for both variants and run in real headless Chrome through
|
||||
the local loopback server in `tool/chat_sessions_probe.mjs`. Each run loaded
|
||||
the list, opened the create dialog, confirmed the rendered catalog controls,
|
||||
opened a row action menu/sheet, and captured PNGs. The probe now clicks the
|
||||
per-session action label and requires `Rename…` in the action labels instead
|
||||
of accepting the dismiss barrier. Material and Cupertino PNGs were inspected.
|
||||
|
||||
Captures from this turn's fix (shared with later stages under
|
||||
`public/c1b-fix/`):
|
||||
|
||||
- `/Users/alan/.local/share/pipelines/data/artifacts/42/public/c1b-fix/cupertino-fix-search-no-match.png` — light, 390x844, long query wraps in full with Clear search on its own line.
|
||||
- `.../cupertino-fix-search-no-match-dark.png` — same state in dark appearance.
|
||||
- `.../cupertino-fix-load-error.png` — long server reason wraps; Retry is separate and the empty-server message is absent.
|
||||
- `.../cupertino-fix-list-phone.png` and `.../material-fix-actions.png` — probe list and actions after the label change.
|
||||
|
||||
Probe commands (run from `app/`):
|
||||
|
||||
```sh
|
||||
flutter build web -t tool/chat_sessions_probe_entry.dart \
|
||||
--dart-define=CHAT_PROBE_STYLE=material --output build/probe-material-fix
|
||||
PROBE_WEB_ROOT="$PWD/build/probe-material-fix" PROBE_VARIANT=material \
|
||||
OPENCODE_ARTIFACT_DIR=/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/chat-sessions-capture \
|
||||
node tool/chat_sessions_probe.mjs
|
||||
# repeat with CHAT_PROBE_STYLE=cupertino and build/probe-cupertino-fix
|
||||
```
|
||||
|
||||
Captures for the second review's fixes (same `public/c1b-fix/` folder, real
|
||||
headless Chrome at 390x844 through a temporary fixture entry that was deleted
|
||||
afterwards; the shipped probe entry was not changed):
|
||||
|
||||
- `platform-default-empty-phone.png` — `MaterialApp` default theme (macOS →
|
||||
Cupertino branch), empty server. The message is ordinary body text.
|
||||
- `platform-default-search-no-match-phone.png` — long query; message wraps and
|
||||
`Clear search` is a separate control.
|
||||
- `platform-default-error-phone.png` — long server reason wraps; `Retry` is
|
||||
separate and no empty-server message appears.
|
||||
- `material-scale2-rename-phone.png` — Material rename dialog at 2.0x text
|
||||
scale; the helper sentence wraps onto two lines in full.
|
||||
|
||||
## Not changed in this turn
|
||||
|
||||
These review notes remain advisory and were left alone because they predate
|
||||
C1b or are native behaviour:
|
||||
|
||||
- The Material FAB can still cover the last row's star/actions when the list
|
||||
exactly fills a phone viewport. Same as the base screen.
|
||||
- Raw exception text (`Bad state: …`, `Exception: …`) is still shown to the
|
||||
operator; wording belongs to a separate error-presentation change.
|
||||
- Cupertino row titles/subtitles still truncate to one line (standard
|
||||
`CupertinoListTile` behaviour). The no-match/error messages no longer do.
|
||||
- The Cupertino-under-MaterialApp probe still takes its accent from the ambient
|
||||
`ThemeData`. No theme override was added.
|
||||
|
||||
## Remaining gaps
|
||||
|
||||
- Mobile is unverified: no Android/iOS builds, devices or installs were run.
|
||||
Source is portable but only web was exercised.
|
||||
- Browser evidence uses the fixture gateway, not an authenticated live server.
|
||||
No real chat was created, renamed, closed or starred in the browser; those
|
||||
request paths are covered by widget tests.
|
||||
- The Cupertino list/actions probes use the local Chrome dark appearance; the
|
||||
no-match fix was captured in both light and dark. The long-error capture came
|
||||
from a temporary private fixture entry that was deleted afterwards.
|
||||
- The create dialog still omits the web's default instruction text and its
|
||||
backend segmented control; it preserves the existing name/directory/backend/
|
||||
instructions request fields.
|
||||
- This stage did not commit. The changes remain an uncommitted working-tree
|
||||
candidate for the next stage.
|
||||
@@ -0,0 +1,17 @@
|
||||
# F4 chat foundation
|
||||
|
||||
Non-visual chat foundations for the UI lane, using the shared `ApiGateway` and no socket ownership.
|
||||
|
||||
## Imports and API
|
||||
|
||||
- `package:pipelines_app/features/chat/domain/chat_sessions.dart`: `chatSessionTitle`, `filterChatSessions`, `groupChatSessions`, `chatSessionActivity`, and `chatUsageSnapshot`.
|
||||
- `package:pipelines_app/features/chat/domain/chat_transcript.dart`: `mergeChatHistory`, `transcriptRows`, `reconcileChatUser`, `applyChatEvent`, `QueuedChatSend`, and `ChatSendQueue`.
|
||||
- `package:pipelines_app/features/chat/data/chat_repository.dart`: `ChatRepository(gateway)`; exposes sessions, directories, history, subscribe, create/rename/star/close/reopen, prompt/interrupt, form answer, permission reply, models/shells and model selection. `gateway.frames` remains the UI/controller's unsolicited event source.
|
||||
|
||||
History uses `chat_history.next_cursor` verbatim, falls back to legacy `chat_messages`, and replaces duplicate authoritative messages while preserving order. `transcriptRows` preserves unknown part maps. Live fold supports user echoes, text/reasoning deltas, tool state snapshots, and step activity; UI should retain its richer thread/timing state as needed. Queue operation IDs are stable across retry objects and deduplicated within each session. Usage values remain unavailable unless reported and valid.
|
||||
|
||||
Wire envelopes are asserted in `test/features/chat/chat_foundation_test.dart`. Current backend has no `chat_forms` or `chat_permissions` list command; forms and permissions arrive as live events and are answered through `chat_answer` / `chat_reply`.
|
||||
|
||||
## Verification
|
||||
|
||||
`/Users/alan/development/flutter/bin/flutter test test/features/chat` passed. Nonvisual foundation: UI/browser review and captures are not applicable at this stage. Web is the only permitted target; Android/iOS remain unverified.
|
||||
@@ -0,0 +1,316 @@
|
||||
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_sessions.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_transcript.dart';
|
||||
|
||||
class RecordingGateway implements ApiGateway {
|
||||
final calls = <({String type, JsonMap fields})>[];
|
||||
JsonMap reply = {};
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
calls.add((type: type, fields: fields));
|
||||
return reply;
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('chat domain', () {
|
||||
test(
|
||||
'filters/groups in server order and keeps server usage unknowns unavailable',
|
||||
() {
|
||||
final sessions = [
|
||||
{'id': 'a', 'directory': '/work', 'title': 'First'},
|
||||
{'id': 'b', 'directory': '/else', 'title': 'Second'},
|
||||
{'id': 'c', 'directory': '/work', 'title': 'Third'},
|
||||
];
|
||||
expect(filterChatSessions(sessions, 'ELSE').single['id'], 'b');
|
||||
expect(groupChatSessions(sessions).map((g) => g.directory), [
|
||||
'/work',
|
||||
'/else',
|
||||
]);
|
||||
expect(chatSessionActivity(running: true, unseen: true), 'streaming');
|
||||
expect(
|
||||
chatUsageSnapshot({
|
||||
'total_tokens': 3,
|
||||
'context_window': 'unknown',
|
||||
})!['context_window'],
|
||||
isNull,
|
||||
);
|
||||
expect(chatUsageSnapshot({'legacy_tokens': 9}), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'merges pages by id, retains idless events, replaces authority, and folds parts',
|
||||
() {
|
||||
final first = mergeChatHistory({}, {
|
||||
'messages': [
|
||||
{
|
||||
'id': 'a',
|
||||
'role': 'assistant',
|
||||
'parts': [
|
||||
{'type': 'reasoning', 'text': 'think'},
|
||||
],
|
||||
},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'parts': [
|
||||
{'type': 'future_part', 'payload': 4},
|
||||
],
|
||||
},
|
||||
{'id': 'u', 'role': 'user', 'text': 'hello', 'operation_id': 'op'},
|
||||
],
|
||||
'nextCursor': 'opaque/1',
|
||||
'hasMore': true,
|
||||
});
|
||||
final older = mergeChatHistory(first, {
|
||||
'messages': [
|
||||
{
|
||||
'id': 'a',
|
||||
'role': 'assistant',
|
||||
'parts': [
|
||||
{'type': 'text', 'text': 'final'},
|
||||
],
|
||||
},
|
||||
],
|
||||
'nextCursor': '',
|
||||
'hasMore': false,
|
||||
}, older: true);
|
||||
expect(older['nextCursor'], '');
|
||||
final msgs = older['messages'] as List<JsonMap>;
|
||||
expect(msgs.map((m) => m['id']), ['a', null, 'u']);
|
||||
expect(
|
||||
(transcriptRows(msgs).first['parts'] as List).map((p) => p['type']),
|
||||
['text', 'future_part'],
|
||||
);
|
||||
expect(
|
||||
reconcileChatUser(msgs, {
|
||||
'id': 'remote',
|
||||
'role': 'user',
|
||||
'operation_id': 'op',
|
||||
}).where((m) => m['operation_id'] == 'op').length,
|
||||
1,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'send queue is session-scoped and operation IDs deduplicate retries',
|
||||
() {
|
||||
final queue = ChatSendQueue();
|
||||
final send = QueuedChatSend(
|
||||
operationId: 'stable',
|
||||
text: ' prompt ',
|
||||
files: ['/tmp/a'],
|
||||
);
|
||||
expect(queue.enqueue('s1', send), isTrue);
|
||||
expect(queue.enqueue('s1', send.retry()), isFalse);
|
||||
expect(queue.enqueue('s2', send.retry()), isTrue);
|
||||
expect(queue.takeNext('s1')!.operationId, 'stable');
|
||||
expect(queue.takeNext('s1'), isNull);
|
||||
expect(queue.forSession('s2').single.files, ['/tmp/a']);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'live text/reasoning append, tool snapshots merge, and steps settle only activity',
|
||||
() {
|
||||
var thread = <String, dynamic>{
|
||||
'sessionId': 's',
|
||||
'messages': <JsonMap>[],
|
||||
};
|
||||
thread = applyChatEvent(thread, {
|
||||
'kind': 'text',
|
||||
'session_id': 's',
|
||||
'message_id': 'a',
|
||||
'part': {'id': 'p'},
|
||||
'delta': 'one',
|
||||
});
|
||||
thread = applyChatEvent(thread, {
|
||||
'kind': 'text',
|
||||
'session_id': 's',
|
||||
'message_id': 'a',
|
||||
'part': {'id': 'p'},
|
||||
'delta': ' two',
|
||||
});
|
||||
thread = applyChatEvent(thread, {
|
||||
'kind': 'reasoning',
|
||||
'session_id': 's',
|
||||
'message_id': 'a',
|
||||
'part': {'id': 'r'},
|
||||
'delta': 'hidden',
|
||||
});
|
||||
thread = applyChatEvent(thread, {
|
||||
'kind': 'tool',
|
||||
'session_id': 's',
|
||||
'message_id': 'a',
|
||||
'part': {
|
||||
'id': 't',
|
||||
'type': 'tool',
|
||||
'state': {'input': 'x'},
|
||||
},
|
||||
});
|
||||
thread = applyChatEvent(thread, {
|
||||
'kind': 'tool',
|
||||
'session_id': 's',
|
||||
'message_id': 'a',
|
||||
'part': {
|
||||
'id': 't',
|
||||
'type': 'tool',
|
||||
'state': {'status': 'completed'},
|
||||
},
|
||||
});
|
||||
final parts =
|
||||
((thread['messages'] as List).single as JsonMap)['parts']
|
||||
as List<JsonMap>;
|
||||
expect(parts[0]['text'], 'one two');
|
||||
expect(parts[1]['text'], 'hidden');
|
||||
expect(parts[2]['state'], {'input': 'x', 'status': 'completed'});
|
||||
expect(thread['running'], true);
|
||||
thread = applyChatEvent(thread, {
|
||||
'kind': 'step',
|
||||
'session_id': 's',
|
||||
'step': {'status': 'ended', 'turn_id': 'turn'},
|
||||
});
|
||||
expect(thread['running'], false);
|
||||
expect(
|
||||
applyChatEvent(thread, {'kind': 'text', 'session_id': 'other'}),
|
||||
same(thread),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('chat wire adapter', () {
|
||||
late RecordingGateway gateway;
|
||||
late ChatRepository repo;
|
||||
setUp(() {
|
||||
gateway = RecordingGateway();
|
||||
repo = ChatRepository(gateway);
|
||||
});
|
||||
test('uses web envelopes and opaque history cursor', () async {
|
||||
gateway.reply = {
|
||||
'chat_history': {
|
||||
'messages': [
|
||||
{'id': 'm', 'role': 'user'},
|
||||
],
|
||||
'next_cursor': 'opaque',
|
||||
'has_more': true,
|
||||
},
|
||||
};
|
||||
final page = await repo.history('s', cursor: 'before', limit: 17);
|
||||
expect(page['nextCursor'], 'opaque');
|
||||
expect(gateway.calls.last.type, 'chat_messages');
|
||||
expect(gateway.calls.last.fields, {
|
||||
'chat_query': {'session_id': 's', 'cursor': 'before', 'limit': 17},
|
||||
});
|
||||
await repo.subscribe('s');
|
||||
expect(gateway.calls.last.fields, {
|
||||
'chat_subscribe': {'session_id': 's'},
|
||||
});
|
||||
});
|
||||
test(
|
||||
'sends stable operation id, omits empty files, and builds action envelopes',
|
||||
() async {
|
||||
await repo.prompt('s', ' hi ', operationId: 'same');
|
||||
expect(gateway.calls.last.fields, {
|
||||
'chat_prompt': {
|
||||
'session_id': 's',
|
||||
'text': 'hi',
|
||||
'operation_id': 'same',
|
||||
'native_message_id': 'msg_same',
|
||||
},
|
||||
});
|
||||
await repo.answerForm('s', 'f', {'choice': 'yes'}, action: 'submit');
|
||||
expect(gateway.calls.last.fields, {
|
||||
'chat_answer': {
|
||||
'session_id': 's',
|
||||
'form_id': 'f',
|
||||
'answers': {'choice': 'yes'},
|
||||
'action': 'submit',
|
||||
},
|
||||
});
|
||||
await repo.replyPermission('s', 'r', 'once', message: ' approved ');
|
||||
expect(gateway.calls.last.fields, {
|
||||
'chat_reply': {
|
||||
'session_id': 's',
|
||||
'request_id': 'r',
|
||||
'decision': 'once',
|
||||
'client': 'Web',
|
||||
'message': 'approved',
|
||||
},
|
||||
});
|
||||
await repo.create(title: 'New', directory: '~', operationId: 'create');
|
||||
expect(gateway.calls.last.fields, {
|
||||
'chat_create': {
|
||||
'title': 'New',
|
||||
'directory': '~',
|
||||
'operation_id': 'create',
|
||||
},
|
||||
});
|
||||
await repo.selectModel('s', 'provider', 'model');
|
||||
expect(gateway.calls.last.type, 'chat_model');
|
||||
},
|
||||
);
|
||||
test('rejects invalid permissions and prompts before sending', () async {
|
||||
expect(
|
||||
() => repo.prompt(' ', 'hello', operationId: 'x'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(
|
||||
() => repo.prompt('s', ' ', operationId: 'x'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(
|
||||
() => repo.replyPermission('s', 'r', 'approve'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(gateway.calls, isEmpty);
|
||||
});
|
||||
test(
|
||||
'uses the server model catalog object and default history limit',
|
||||
() async {
|
||||
gateway.reply = {
|
||||
'chat_models': {
|
||||
'providers': {
|
||||
'p': ['m'],
|
||||
},
|
||||
},
|
||||
};
|
||||
expect((await repo.models('s'))['providers'], {
|
||||
'p': ['m'],
|
||||
});
|
||||
expect(gateway.calls.single.fields, {
|
||||
'chat_query': {'session_id': 's'},
|
||||
});
|
||||
gateway.calls.clear();
|
||||
await repo.history('s');
|
||||
expect(gateway.calls.single.fields['chat_query']['limit'], 200);
|
||||
},
|
||||
);
|
||||
test(
|
||||
'reads exact directory/backend catalog envelopes without inventing fallback',
|
||||
() async {
|
||||
gateway.reply = {
|
||||
'chat_directories': ['~', '/work'],
|
||||
};
|
||||
expect(await repo.directories(), ['~', '/work']);
|
||||
expect(gateway.calls.last.type, 'chat_directories');
|
||||
expect(gateway.calls.last.fields, isEmpty);
|
||||
gateway.reply = {
|
||||
'chat_backends': ['opencode', 'claude'],
|
||||
};
|
||||
expect(await repo.backends(), ['opencode', 'claude']);
|
||||
expect(gateway.calls.last.type, 'chat_backends');
|
||||
expect(gateway.calls.last.fields, isEmpty);
|
||||
gateway.reply = {};
|
||||
await expectLater(repo.directories(), throwsStateError);
|
||||
await expectLater(repo.backends(), throwsStateError);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
|
||||
import 'chat_test_harness.dart';
|
||||
import 'fake_chat_gateway.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'material create dialog retains the draft through a delayed catalog failure and retry',
|
||||
(tester) async {
|
||||
final gateway = FakeChatGateway();
|
||||
final directories = Completer<JsonMap>();
|
||||
gateway.directoriesHandler = () => directories.future;
|
||||
JsonMap? opened;
|
||||
await pumpMaterialChat(
|
||||
tester,
|
||||
gateway,
|
||||
onOpen: (session) => opened = session,
|
||||
);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 400));
|
||||
expect(find.text('Loading directories…'), findsOneWidget);
|
||||
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-create-name')),
|
||||
'Draft chat',
|
||||
);
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-create-instructions')),
|
||||
'Keep me',
|
||||
);
|
||||
|
||||
directories.completeError(
|
||||
StateError('Server did not return chat directories.'),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(
|
||||
find.textContaining('Unable to load chat options'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('Draft chat'), findsOneWidget);
|
||||
expect(find.text('Keep me'), findsOneWidget);
|
||||
|
||||
gateway.directoriesHandler = () async => {
|
||||
'chat_directories': ['/work'],
|
||||
};
|
||||
await tester.tap(find.text('Retry'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('Unable to load chat options'), findsNothing);
|
||||
expect(
|
||||
find.byKey(const Key('chat-create-server-directory')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.text('New chats use the server default model.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
|
||||
await tester.enterText(find.byKey(const Key('chat-create-name')), '');
|
||||
await tester.tap(find.text('Create'));
|
||||
await tester.pump();
|
||||
expect(find.text('Enter a name and server directory.'), findsOneWidget);
|
||||
expect(gateway.count('chat_create'), 0);
|
||||
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-create-name')),
|
||||
'Draft chat',
|
||||
);
|
||||
await tester.tap(find.text('Create'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final fields =
|
||||
gateway.lastFields('chat_create')!['chat_create']! as JsonMap;
|
||||
expect(fields['title'], 'Draft chat');
|
||||
expect(fields['directory'], '/work');
|
||||
expect(fields.containsKey('backend'), isFalse);
|
||||
expect(fields['instructions'], 'Keep me');
|
||||
expect(fields.containsKey('operation_id'), isTrue);
|
||||
expect(opened?['id'], 'created');
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('Cupertino create dialog keeps the draft when catalogs fail', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
gateway.directoriesHandler = () =>
|
||||
Future.error(StateError('Server did not return chat directories.'));
|
||||
await pumpCupertinoChat(tester, gateway);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-new-chat')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('Unable to load chat options'), findsOneWidget);
|
||||
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-create-name')),
|
||||
'Cupertino draft',
|
||||
);
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-create-instructions')),
|
||||
'Keep me too',
|
||||
);
|
||||
expect(find.text('Cupertino draft'), findsOneWidget);
|
||||
expect(find.text('Keep me too'), findsOneWidget);
|
||||
|
||||
gateway.directoriesHandler = () async => {
|
||||
'chat_directories': ['/work'],
|
||||
};
|
||||
await tester.tap(find.text('Retry'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('Unable to load chat options'), findsNothing);
|
||||
expect(find.text('Cupertino draft'), findsOneWidget);
|
||||
expect(find.text('Keep me too'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('material create dialog reports an empty catalog', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
gateway.directoriesHandler = () async => {'chat_directories': []};
|
||||
await pumpMaterialChat(tester, gateway);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.text('The server has no chat directories or backends available.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Cupertino create dialog uses native selectors and fields', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
JsonMap? opened;
|
||||
await pumpCupertinoChat(
|
||||
tester,
|
||||
gateway,
|
||||
onOpen: (session) => opened = session,
|
||||
);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-new-chat')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
|
||||
expect(find.text('Server directory: /work'), findsOneWidget);
|
||||
expect(find.text('Backend: opencode'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-create-backend')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('codex'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Backend: codex'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-create-server-directory')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('/archive'), findsOneWidget);
|
||||
await tester.tap(find.text('/archive'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Server directory: /archive'), findsOneWidget);
|
||||
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-create-name')),
|
||||
'Cupertino draft',
|
||||
);
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-create-instructions')),
|
||||
'Be careful',
|
||||
);
|
||||
await tester.tap(find.text('Create'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final fields =
|
||||
gateway.lastFields('chat_create')!['chat_create']! as JsonMap;
|
||||
expect(fields['title'], 'Cupertino draft');
|
||||
expect(fields['directory'], '/archive');
|
||||
expect(fields['backend'], 'codex');
|
||||
expect(fields['instructions'], 'Be careful');
|
||||
expect(opened?['id'], 'created');
|
||||
});
|
||||
|
||||
testWidgets('a created chat opens before the list refresh completes', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
JsonMap? opened;
|
||||
await pumpMaterialChat(
|
||||
tester,
|
||||
gateway,
|
||||
onOpen: (session) => opened = session,
|
||||
);
|
||||
|
||||
final refresh = Completer<JsonMap>();
|
||||
gateway.pendingSessions.add(refresh);
|
||||
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Create'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 300));
|
||||
|
||||
expect(gateway.count('chat_create'), 1);
|
||||
expect(gateway.count('chat_sessions'), 2);
|
||||
expect(
|
||||
opened?['id'],
|
||||
'created',
|
||||
reason: 'a slow listing must not hold up opening the new chat',
|
||||
);
|
||||
|
||||
refresh.complete({'chat_sessions': []});
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'chat_test_harness.dart';
|
||||
import 'fake_chat_gateway.dart';
|
||||
|
||||
/// The message card is also mounted under a bare `MaterialApp` (the screen's
|
||||
/// iOS/macOS path). Without its own style, `Text` inherits MaterialApp's
|
||||
/// "missing Material" fallback: 48px, red, monospace with a double underline.
|
||||
void main() {
|
||||
testWidgets('Cupertino empty message under MaterialApp uses normal text', (
|
||||
tester,
|
||||
) async {
|
||||
usePhoneSurface(tester);
|
||||
await pumpIosMaterialChat(tester, FakeChatGateway());
|
||||
|
||||
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
|
||||
expect(find.byType(Scaffold), findsNothing);
|
||||
|
||||
const message = 'No chat sessions on this server yet.';
|
||||
expect(find.text(message), findsOneWidget);
|
||||
expectNormalTextStyle(tester, message);
|
||||
});
|
||||
|
||||
testWidgets('Cupertino no-match message under MaterialApp wraps normally', (
|
||||
tester,
|
||||
) async {
|
||||
usePhoneSurface(tester);
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpIosMaterialChat(tester, gateway);
|
||||
|
||||
await tester.enterText(
|
||||
find.byType(CupertinoSearchTextField),
|
||||
'zzz-no-match-with-a-long-query',
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
const message = 'No chats match "zzz-no-match-with-a-long-query".';
|
||||
expect(find.text(message), findsOneWidget);
|
||||
expectNormalTextStyle(tester, message);
|
||||
expect(
|
||||
tester.renderObject<RenderBox>(find.text(message)).size.height,
|
||||
greaterThan(30),
|
||||
reason: 'the query message must wrap instead of being cut to one line',
|
||||
);
|
||||
expect(
|
||||
find.widgetWithText(CupertinoButton, 'Clear search'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Cupertino load error under MaterialApp uses normal text', (
|
||||
tester,
|
||||
) async {
|
||||
usePhoneSurface(tester);
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsHandler = () => Future.error(
|
||||
StateError(
|
||||
'server unavailable while listing chat sessions for this operator',
|
||||
),
|
||||
);
|
||||
await pumpIosMaterialChat(tester, gateway);
|
||||
|
||||
const message =
|
||||
'Bad state: server unavailable while listing chat sessions '
|
||||
'for this operator';
|
||||
expect(find.text(message), findsOneWidget);
|
||||
expectNormalTextStyle(tester, message);
|
||||
expect(find.text('No chat sessions on this server yet.'), findsNothing);
|
||||
expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
|
||||
/// Resolves the style actually painted for [message] and checks it is the
|
||||
/// ordinary Cupertino body style rather than MaterialApp's fallback style.
|
||||
void expectNormalTextStyle(WidgetTester tester, String message) {
|
||||
final paragraph = tester.renderObject<RenderParagraph>(find.text(message));
|
||||
final style = paragraph.text.style!;
|
||||
expect(
|
||||
style.fontSize,
|
||||
const CupertinoThemeData().textTheme.textStyle.fontSize,
|
||||
reason: 'message should not use MaterialApp\'s 48px fallback style',
|
||||
);
|
||||
expect(style.fontFamily, isNot('monospace'));
|
||||
expect(style.fontWeight, isNot(FontWeight.w900));
|
||||
expect(style.decoration, isNot(TextDecoration.underline));
|
||||
expect(style.color, isNot(const Color(0xD0FF0000)));
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
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 'chat_test_harness.dart';
|
||||
import 'fake_chat_gateway.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('material row star, rename, close confirm and reopen', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpMaterialChat(tester, gateway);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-star-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.lastFields('chat_star'), {
|
||||
'chat_query': {'session_id': 's2', 'starred': true},
|
||||
});
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Rename…'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-rename-field')),
|
||||
' Renamed chat ',
|
||||
);
|
||||
await tester.tap(find.text('Save'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.lastFields('chat_rename'), {
|
||||
'chat_rename': {'session_id': 's2', 'title': 'Renamed chat'},
|
||||
});
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Close chat…'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Close chat?'), findsOneWidget);
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.count('chat_close'), 0);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Close chat…'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Close chat'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.lastFields('chat_close'), {
|
||||
'chat_query': {'session_id': 's2'},
|
||||
});
|
||||
|
||||
await tester.ensureVisible(find.byKey(const Key('chat-actions-s4')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s4')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Reopen'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.lastFields('chat_reopen'), {
|
||||
'chat_query': {'session_id': 's4'},
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Cupertino close confirmation uses the action sheet flow', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpCupertinoChat(tester, gateway);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Close chat…'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
|
||||
expect(
|
||||
find.textContaining('marks it closed on every device'),
|
||||
findsOneWidget,
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Close chat'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.lastFields('chat_close'), {
|
||||
'chat_query': {'session_id': 's2'},
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('material rename disables Save while the name is blank', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpMaterialChat(tester, gateway);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Rename…'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.enterText(find.byKey(const Key('chat-rename-field')), ' ');
|
||||
await tester.pump();
|
||||
|
||||
final save = tester.widget<FilledButton>(
|
||||
find.widgetWithText(FilledButton, 'Save'),
|
||||
);
|
||||
expect(save.onPressed, isNull);
|
||||
expect(gateway.count('chat_rename'), 0);
|
||||
});
|
||||
|
||||
testWidgets('Cupertino rename disables Save while the name is blank', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpCupertinoChat(tester, gateway);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Rename…'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.enterText(find.byKey(const Key('chat-rename-field')), ' ');
|
||||
await tester.pump();
|
||||
|
||||
final save = tester.widget<CupertinoDialogAction>(
|
||||
find.widgetWithText(CupertinoDialogAction, 'Save'),
|
||||
);
|
||||
expect(save.onPressed, isNull);
|
||||
expect(gateway.count('chat_rename'), 0);
|
||||
});
|
||||
|
||||
testWidgets('material rename helper wraps instead of truncating at 2x', (
|
||||
tester,
|
||||
) async {
|
||||
usePhoneSurface(tester);
|
||||
tester.platformDispatcher.textScaleFactorTestValue = 2;
|
||||
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpMaterialChat(tester, gateway);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Rename…'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
const helper = 'This name is shared with every device.';
|
||||
expect(find.text(helper), findsOneWidget);
|
||||
expect(
|
||||
tester.widget<Text>(find.text(helper)).maxLines,
|
||||
2,
|
||||
reason: 'helperMaxLines defaults to one, which truncates the sentence',
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('opening a row calls onOpen with the server session', (
|
||||
tester,
|
||||
) async {
|
||||
JsonMap? opened;
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpMaterialChat(
|
||||
tester,
|
||||
gateway,
|
||||
onOpen: (session) => opened = session,
|
||||
);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-row-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(opened?['id'], 's2');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
|
||||
|
||||
import 'fake_chat_gateway.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('a stale refresh reply never replaces the latest listing', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
final first = Completer<JsonMap>();
|
||||
final second = Completer<JsonMap>();
|
||||
gateway.pendingSessions.addAll([first, second]);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-refresh')));
|
||||
await tester.pump();
|
||||
expect(gateway.count('chat_sessions'), 2);
|
||||
|
||||
second.complete({
|
||||
'chat_sessions': [
|
||||
{'id': 'new', 'title': 'Newest chat'},
|
||||
],
|
||||
});
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(find.text('Newest chat'), findsOneWidget);
|
||||
|
||||
first.complete({
|
||||
'chat_sessions': [
|
||||
{'id': 'old', 'title': 'Older chat'},
|
||||
],
|
||||
});
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(find.text('Older chat'), findsNothing);
|
||||
expect(find.text('Newest chat'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a reply completing after dispose changes nothing', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
final pending = Completer<JsonMap>();
|
||||
gateway.pendingSessions.add(pending);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: SizedBox()));
|
||||
pending.complete({
|
||||
'chat_sessions': [
|
||||
{'id': 'late', 'title': 'Late chat'},
|
||||
],
|
||||
});
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.text('Late chat'), findsNothing);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'chat_test_harness.dart';
|
||||
import 'fake_chat_gateway.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'material list keeps closed starred rows once and groups directories once',
|
||||
(tester) async {
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpMaterialChat(tester, gateway);
|
||||
|
||||
expect(find.text('Starred'), findsOneWidget);
|
||||
expect(find.text('Chats'), findsNWidgets(2));
|
||||
expect(find.text('Closed'), findsOneWidget);
|
||||
expect(find.text('Starred chat'), findsOneWidget);
|
||||
expect(find.text('Starred closed'), findsOneWidget);
|
||||
expect(find.text('Open chat'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.folder_outlined), findsNWidgets(4));
|
||||
expect(find.byType(Scaffold), findsOneWidget);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('material search distinguishes no-match and clears back', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpMaterialChat(tester, gateway);
|
||||
|
||||
await tester.enterText(find.byType(TextField), 'zzz');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('No chats match "zzz".'), findsOneWidget);
|
||||
expect(find.text('Open chat'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Clear search'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Open chat'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('material empty server shows the distinct empty message', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
await pumpMaterialChat(tester, gateway);
|
||||
expect(find.text('No chat sessions on this server yet.'), findsOneWidget);
|
||||
expect(find.textContaining('No chats match'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'Cupertino app renders standard controls, groups and renames without Material',
|
||||
(tester) async {
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpCupertinoChat(tester, gateway);
|
||||
|
||||
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
|
||||
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
|
||||
expect(find.byType(Scaffold), findsNothing);
|
||||
expect(
|
||||
tester.getTopLeft(find.byType(CupertinoSearchTextField)).dy,
|
||||
greaterThanOrEqualTo(
|
||||
tester.getBottomLeft(find.byType(CupertinoNavigationBar)).dy,
|
||||
),
|
||||
);
|
||||
expect(find.text('Chats · /work'), findsOneWidget);
|
||||
expect(find.text('Chats · /else'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-star-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.lastFields('chat_star'), {
|
||||
'chat_query': {'session_id': 's2', 'starred': true},
|
||||
});
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s2')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Rename…'), findsOneWidget);
|
||||
await tester.tap(find.text('Rename…'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
|
||||
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-rename-field')),
|
||||
'Renamed on Cupertino',
|
||||
);
|
||||
await tester.tap(find.text('Save'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.lastFields('chat_rename'), {
|
||||
'chat_rename': {'session_id': 's2', 'title': 'Renamed on Cupertino'},
|
||||
});
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-actions-s4')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Reopen'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.lastFields('chat_reopen'), {
|
||||
'chat_query': {'session_id': 's4'},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'Cupertino no-match message wraps and Clear search is its own button',
|
||||
(tester) async {
|
||||
usePhoneSurface(tester);
|
||||
final semantics = tester.ensureSemantics();
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpCupertinoChat(tester, gateway);
|
||||
|
||||
const query = 'zzz-no-match-with-a-long-query';
|
||||
await tester.enterText(find.byType(CupertinoSearchTextField), query);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
const message = 'No chats match "zzz-no-match-with-a-long-query".';
|
||||
expect(find.text(message), findsOneWidget);
|
||||
expect(find.text('Open chat'), findsNothing);
|
||||
final messageBox = tester.renderObject<RenderBox>(find.text(message));
|
||||
expect(
|
||||
messageBox.size.height,
|
||||
greaterThan(30),
|
||||
reason: 'the query message must wrap instead of being cut to one line',
|
||||
);
|
||||
|
||||
final clear = find.bySemanticsLabel('Clear search');
|
||||
expect(clear, findsOneWidget);
|
||||
expect(tester.getSemantics(clear).label, 'Clear search');
|
||||
|
||||
await tester.tap(find.text('Clear search'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Open chat'), findsOneWidget);
|
||||
semantics.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'Cupertino load failure wraps the reason and hides the empty message',
|
||||
(tester) async {
|
||||
usePhoneSurface(tester);
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsHandler = () => Future.error(
|
||||
StateError(
|
||||
'server unavailable while listing chat sessions for this operator',
|
||||
),
|
||||
);
|
||||
await pumpCupertinoChat(tester, gateway);
|
||||
|
||||
const message =
|
||||
'Bad state: server unavailable while listing chat sessions '
|
||||
'for this operator';
|
||||
expect(find.text(message), findsOneWidget);
|
||||
expect(find.text('No chat sessions on this server yet.'), findsNothing);
|
||||
final messageBox = tester.renderObject<RenderBox>(find.text(message));
|
||||
expect(
|
||||
messageBox.size.height,
|
||||
greaterThan(30),
|
||||
reason: 'the server reason must wrap instead of being cut to one line',
|
||||
);
|
||||
expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('Cupertino no-match message survives 2x text scaling', (
|
||||
tester,
|
||||
) async {
|
||||
usePhoneSurface(tester);
|
||||
tester.platformDispatcher.textScaleFactorTestValue = 2;
|
||||
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {'chat_sessions': sampleSessions()};
|
||||
await pumpCupertinoChat(tester, gateway);
|
||||
|
||||
await tester.enterText(
|
||||
find.byType(CupertinoSearchTextField),
|
||||
'zzz-no-match-with-a-long-query',
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
find.text('No chats match "zzz-no-match-with-a-long-query".'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('Clear search'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('duplicate Cupertino titles disambiguate the action labels', (
|
||||
tester,
|
||||
) async {
|
||||
final semantics = tester.ensureSemantics();
|
||||
final gateway = FakeChatGateway()
|
||||
..sessionsReply = {
|
||||
'chat_sessions': [
|
||||
{'id': 'd1', 'title': 'New chat', 'directory': '/work'},
|
||||
{'id': 'd2', 'title': 'New chat', 'directory': '/work'},
|
||||
],
|
||||
};
|
||||
await pumpCupertinoChat(tester, gateway);
|
||||
|
||||
expect(
|
||||
tester.getSemantics(find.byKey(const Key('chat-actions-d1'))).label,
|
||||
'Chat actions for New chat (d1)',
|
||||
);
|
||||
expect(
|
||||
tester.getSemantics(find.byKey(const Key('chat-actions-d2'))).label,
|
||||
'Chat actions for New chat (d2)',
|
||||
);
|
||||
semantics.dispose();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
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/ui/sessions/chat_sessions_screen.dart';
|
||||
|
||||
import 'fake_chat_gateway.dart';
|
||||
|
||||
List<JsonMap> sampleSessions() => [
|
||||
{'id': 's1', 'title': 'Starred chat', 'directory': '/work', 'starred': true},
|
||||
{'id': 's2', 'title': 'Open chat', 'directory': '/work'},
|
||||
{'id': 's3', 'title': 'Elsewhere chat', 'directory': '/else'},
|
||||
{
|
||||
'id': 's4',
|
||||
'title': 'Closed chat',
|
||||
'directory': '/else',
|
||||
'closed_at': '2026-01-01',
|
||||
},
|
||||
{
|
||||
'id': 's5',
|
||||
'title': 'Starred closed',
|
||||
'directory': '/work',
|
||||
'starred': true,
|
||||
'closed_at': '2026-01-02',
|
||||
},
|
||||
];
|
||||
|
||||
Future<void> pumpMaterialChat(
|
||||
WidgetTester tester,
|
||||
FakeChatGateway gateway, {
|
||||
ValueChanged<JsonMap>? onOpen,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> pumpCupertinoChat(
|
||||
WidgetTester tester,
|
||||
FakeChatGateway gateway, {
|
||||
ValueChanged<JsonMap>? onOpen,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
CupertinoApp(
|
||||
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// The screen's iOS/macOS path: Cupertino controls under the app's ordinary
|
||||
/// `MaterialApp` root, with no Material or CupertinoTheme ancestor.
|
||||
Future<void> pumpIosMaterialChat(
|
||||
WidgetTester tester,
|
||||
FakeChatGateway gateway, {
|
||||
ValueChanged<JsonMap>? onOpen,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.iOS),
|
||||
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Narrows the test surface to a phone so long messages must wrap.
|
||||
void usePhoneSurface(WidgetTester tester) {
|
||||
tester.view.physicalSize = const Size(390, 844);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'dart:async';
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
|
||||
/// Scripted gateway for session-browser widget tests.
|
||||
class FakeChatGateway implements ApiGateway {
|
||||
final calls = <({String type, JsonMap fields})>[];
|
||||
final pendingSessions = Queue<Completer<JsonMap>>();
|
||||
JsonMap sessionsReply = const {'chat_sessions': []};
|
||||
Future<JsonMap> Function()? sessionsHandler;
|
||||
JsonMap createReply = const {
|
||||
'chat_session': {'id': 'created', 'title': 'New chat'},
|
||||
};
|
||||
Future<JsonMap> Function()? directoriesHandler;
|
||||
Future<JsonMap> Function()? backendsHandler;
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||
calls.add((type: type, fields: fields));
|
||||
switch (type) {
|
||||
case 'chat_sessions':
|
||||
if (pendingSessions.isNotEmpty) {
|
||||
return pendingSessions.removeFirst().future;
|
||||
}
|
||||
if (sessionsHandler != null) return sessionsHandler!();
|
||||
return Future.value(sessionsReply);
|
||||
case 'chat_directories':
|
||||
return directoriesHandler?.call() ??
|
||||
Future.value(const {
|
||||
'chat_directories': ['/work', '/archive'],
|
||||
});
|
||||
case 'chat_backends':
|
||||
return backendsHandler?.call() ??
|
||||
Future.value(const {
|
||||
'chat_backends': ['opencode', 'codex'],
|
||||
});
|
||||
case 'chat_create':
|
||||
return Future.value(createReply);
|
||||
default:
|
||||
return Future.value(const {});
|
||||
}
|
||||
}
|
||||
|
||||
int count(String type) => calls.where((call) => call.type == type).length;
|
||||
|
||||
JsonMap? lastFields(String type) {
|
||||
for (final call in calls.reversed) {
|
||||
if (call.type == type) return call.fields;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { join, extname, resolve, sep } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
||||
|
||||
const root = resolve(process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/web'));
|
||||
const variant = process.env.PROBE_VARIANT ?? 'material';
|
||||
const artifactDir = process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'chat-sessions-capture');
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' };
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname));
|
||||
if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end();
|
||||
const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path;
|
||||
const file = await readFile(filePath);
|
||||
res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file);
|
||||
} catch { res.writeHead(404).end('not found'); }
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
const port = server.address().port;
|
||||
const profile = await mkdtemp(join(tmpdir(), 'chat-sessions-chrome-'));
|
||||
const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [
|
||||
'--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu',
|
||||
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank',
|
||||
], { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
let stderr = '';
|
||||
chrome.stderr.on('data', data => { stderr += data; });
|
||||
const waitFor = async fn => {
|
||||
for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); }
|
||||
throw new Error('Timed out waiting for Chrome DevTools');
|
||||
};
|
||||
let ws;
|
||||
try {
|
||||
const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]);
|
||||
ws = new WebSocket(endpoint);
|
||||
await once(ws, 'open');
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('message', event => {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg));
|
||||
if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
|
||||
});
|
||||
const send = (method, params = {}, sessionId) => new Promise(resolve => {
|
||||
const callId = ++id; pending.set(callId, resolve);
|
||||
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
|
||||
});
|
||||
const created = await send('Target.createTarget', { url: 'about:blank' });
|
||||
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
|
||||
const target = created.result.targetId;
|
||||
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId;
|
||||
await send('Page.enable', {}, session);
|
||||
await send('Runtime.enable', {}, session);
|
||||
const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, session);
|
||||
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
|
||||
const evaluate = async expression => {
|
||||
const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session);
|
||||
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
|
||||
return response.result?.result?.value;
|
||||
};
|
||||
await delay(3500);
|
||||
const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})");
|
||||
if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(2500);
|
||||
const clickLabel = async label => {
|
||||
const point = await evaluate(`(() => { const needle = ${JSON.stringify(label)}; const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === needle); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`);
|
||||
if (!point) return false;
|
||||
await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session);
|
||||
await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session);
|
||||
return true;
|
||||
};
|
||||
const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)");
|
||||
if (!labels?.some(x => x.includes('New chat'))) throw new Error(`Chat fixture semantics unavailable: ${JSON.stringify(labels)}`);
|
||||
if (process.env.PROBE_DEBUG) console.log(JSON.stringify(labels));
|
||||
const capture = async (name, width, height) => {
|
||||
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session);
|
||||
await delay(350);
|
||||
const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data;
|
||||
await (await import('node:fs/promises')).writeFile(`${artifactDir}/${variant}-${name}.png`, Buffer.from(data, 'base64'));
|
||||
};
|
||||
await capture('chat-sessions-desktop', 1280, 800);
|
||||
await capture('chat-sessions-phone', 390, 844);
|
||||
if (!await clickLabel('New chat')) throw new Error('Could not open create dialog');
|
||||
await delay(600);
|
||||
await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 680, deltaY: 598 }, session);
|
||||
await delay(350);
|
||||
const changedBody = await evaluate('document.body.innerText');
|
||||
await capture('chat-sessions-create-dialog', 390, 844);
|
||||
if (!changedBody.includes('Server directory') || !changedBody.includes('Backend') || !changedBody.includes('New chats use the server default model.')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`);
|
||||
if (!await clickLabel('Cancel')) throw new Error('Could not close create dialog');
|
||||
await delay(600);
|
||||
if (!await clickLabel('Chat actions for Open fixture')) throw new Error('Could not open row actions');
|
||||
await delay(600);
|
||||
const actionsBody = await evaluate('document.body.innerText');
|
||||
const actionLabels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || x.innerText || '').filter(Boolean)");
|
||||
await capture('chat-sessions-actions', 390, 844);
|
||||
if (!actionLabels.some(label => label.includes('Rename…'))) throw new Error(`Row actions unavailable: ${actionsBody} / ${actionLabels}`);
|
||||
console.log(JSON.stringify({ variant, labels, captures: [`${variant}-chat-sessions-desktop.png`, `${variant}-chat-sessions-phone.png`, `${variant}-chat-sessions-create-dialog.png`, `${variant}-chat-sessions-actions.png`], bodyChanged: true }, null, 2));
|
||||
} finally {
|
||||
ws?.close();
|
||||
chrome.kill('SIGTERM');
|
||||
await Promise.race([once(chrome, 'exit'), delay(3000)]);
|
||||
server.close();
|
||||
await rm(profile, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/session_screen.dart';
|
||||
|
||||
class _FixtureGateway implements ApiGateway {
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (type == 'chat_sessions') {
|
||||
return {
|
||||
'chat_sessions': [
|
||||
{
|
||||
'id': 'probe-open',
|
||||
'title': 'Open fixture',
|
||||
'directory': '/workspace/demo',
|
||||
'starred': true,
|
||||
},
|
||||
{
|
||||
'id': 'probe-closed',
|
||||
'title': 'Closed fixture',
|
||||
'directory': '/workspace/archive',
|
||||
'closed_at': '2026-01-01',
|
||||
},
|
||||
{
|
||||
'id': 'probe-stream',
|
||||
'title': 'Streaming fixture',
|
||||
'directory': '/workspace/demo',
|
||||
'running': true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (type == 'chat_directories') {
|
||||
return {
|
||||
'chat_directories': ['/workspace/demo', '/workspace/archive'],
|
||||
};
|
||||
}
|
||||
if (type == 'chat_backends') {
|
||||
return {
|
||||
'chat_backends': ['opencode', 'codex'],
|
||||
};
|
||||
}
|
||||
if (type == 'chat_create') {
|
||||
return {
|
||||
'chat_session': {
|
||||
'id': 'probe-new',
|
||||
'title': 'New fixture',
|
||||
'directory': '/workspace/demo',
|
||||
},
|
||||
};
|
||||
}
|
||||
return {'chat_session': {}};
|
||||
}
|
||||
}
|
||||
|
||||
const _probeStyle = String.fromEnvironment(
|
||||
'CHAT_PROBE_STYLE',
|
||||
defaultValue: 'material',
|
||||
);
|
||||
|
||||
void main() {
|
||||
final home = ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {});
|
||||
if (_probeStyle == 'cupertino') {
|
||||
runApp(CupertinoApp(home: home));
|
||||
return;
|
||||
}
|
||||
runApp(
|
||||
MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
home: home,
|
||||
),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user