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 filterChatSessions(List 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 sessions})> groupChatSessions( List sessions, ) { final groups = >{}; for (final session in sessions) { groups.putIfAbsent('${session['directory'] ?? ''}', () => []).add(session); } return groups.entries .map((entry) => (directory: entry.key, sessions: entry.value)) .toList(); } /// The list's sections in on-screen order: Starred (open chats, by name, so /// each keeps its place), Chats (open, server recency) and Closed (server /// recency). Empty sections are left out. List<({String title, List sessions})> chatSessionSections( List visible, ) { bool closed(JsonMap s) => s['closed_at'] != null; bool starred(JsonMap s) => s['starred'] == true && !closed(s); final sections = [ ( title: 'Starred', sessions: sortStarredChatSessions(visible.where(starred)), ), ( title: 'Chats', sessions: visible.where((s) => !starred(s) && !closed(s)).toList(), ), (title: 'Closed', sessions: visible.where(closed).toList()), ]; return [ for (final section in sections) if (section.sessions.isNotEmpty) section, ]; } /// Starred chats alphabetically by their shown title, ignoring case; equal /// titles keep a fixed order by id. List sortStarredChatSessions(Iterable sessions) => sessions.toList()..sort((a, b) { final byTitle = chatSessionTitle( a, ).toLowerCase().compareTo(chatSessionTitle(b).toLowerCase()); if (byTitle != 0) return byTitle; return '${a['id'] ?? ''}'.compareTo('${b['id'] ?? ''}'); }); /// Whether a section's rows are split under directory headings. Starred keeps /// its alphabetical order whole, so a name is always in the same place. bool chatSectionGroupsByDirectory(String title) => title != 'Starred'; /// The rows of [sections] in the order the list draws them: each open /// section's rows, directory group by directory group. A folded section /// draws no rows. List chatSessionsInListOrder( List<({String title, List sessions})> sections, { required bool Function(String title) isOpen, }) => [ for (final section in sections) if (isOpen(section.title)) if (chatSectionGroupsByDirectory(section.title)) for (final group in groupChatSessions(section.sessions)) ...group.sessions else ...section.sessions, ]; String chatSessionActivity({required bool running, required bool unseen}) => running ? 'streaming' : unseen ? 'new' : 'idle'; /// A server timestamp as epoch milliseconds. Accepts an epoch number or an /// ISO-8601 string and reports `0` for anything unusable, so callers never /// invent a time for a missing field. int chatSessionMillis(Object? value) { if (value is int) return value > 0 ? value : 0; if (value is num) return value > 0 ? value.toInt() : 0; final text = '${value ?? ''}'.trim(); if (text.isEmpty) return 0; final number = int.tryParse(text); if (number != null) return number > 0 ? number : 0; return DateTime.tryParse(text)?.millisecondsSinceEpoch ?? 0; } /// Native reported values only; missing and invalid values remain unavailable. JsonMap? chatUsageSnapshot(Object? value) { if (value is! Map || value is List) return null; final usage = Map.from(value); final result = {}; 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; }