import 'dart:async'; import 'package:flutter/material.dart'; import '../api/models.dart'; import '../state.dart'; import 'servers_screen.dart'; /// The session list: a drawer on a phone, a persistent column on a wide /// layout. Selecting a session opens it in the chat beside it (the shell owns /// that), so this only reports the choice through [onOpened]. class SessionListPane extends StatefulWidget { final AppState app; /// Called after a session was opened, so the drawer can close itself. final VoidCallback? onOpened; const SessionListPane({super.key, required this.app, this.onOpened}); @override State createState() => _SessionListPaneState(); } class _SessionListPaneState extends State { bool _searchOpen = false; Timer? _timer; late final TextEditingController _searchCtrl; @override void initState() { super.initState(); _searchCtrl = TextEditingController(); } @override void dispose() { _timer?.cancel(); _searchCtrl.dispose(); super.dispose(); } void _onSearchChanged(String v) { _timer?.cancel(); _timer = Timer(const Duration(milliseconds: 350), () { if (v.isEmpty) { widget.app.refreshSessions(); } else { widget.app.searchSessions(v); } }); } @override Widget build(BuildContext context) { final app = widget.app; return ListenableBuilder( listenable: app, builder: (context, _) { final scheme = Theme.of(context).colorScheme; return SafeArea( child: Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(4, 6, 4, 0), child: Row( children: [ IconButton( icon: const Icon(Icons.dns_outlined), tooltip: '服务器', onPressed: _instancesSheet, ), const Expanded( child: Text('会话', style: TextStyle( fontSize: 20, fontWeight: FontWeight.w600)), ), IconButton( icon: Icon(_searchOpen ? Icons.close : Icons.search), tooltip: '搜索', onPressed: () { setState(() { _searchOpen = !_searchOpen; if (!_searchOpen) { _searchCtrl.clear(); app.refreshSessions(); } }); }, ), IconButton( icon: const Icon(Icons.add), tooltip: '新建会话', onPressed: _newSessionSheet, ), ], ), ), if (_searchOpen) Padding( padding: const EdgeInsets.fromLTRB(12, 2, 12, 4), child: TextField( controller: _searchCtrl, autofocus: true, onChanged: _onSearchChanged, decoration: const InputDecoration( hintText: '搜索会话', prefixIcon: Icon(Icons.search), border: OutlineInputBorder(), isDense: true, ), ), ), if (app.error != null) Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( children: [ Expanded( child: Text(app.error!, style: TextStyle( color: scheme.error, fontSize: 13)), ), TextButton( onPressed: app.refreshSessions, child: const Text('重试')), ], ), ), Expanded(child: _body()), ], ), ); }, ); } Widget _body() { final app = widget.app; if (app.sessionsLoading && app.sessions.isEmpty) { return const Center(child: CircularProgressIndicator()); } if (app.sessions.isEmpty) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ const Text('暂无会话'), const SizedBox(height: 8), FilledButton( onPressed: _newSessionSheet, child: const Text('新建会话')), ], ), ); } return RefreshIndicator( onRefresh: app.refreshSessions, child: ListView.builder( itemCount: app.sessions.length, itemBuilder: (context, i) { final s = app.sessions[i]; final running = app.active.contains(s.id); final selected = widget.app.chat?.session.id == s.id; return ListTile( selected: selected, title: Text(s.title.isEmpty ? '(无标题会话)' : s.title, maxLines: 1, overflow: TextOverflow.ellipsis), subtitle: Text(_subtitle(s), maxLines: 1, overflow: TextOverflow.ellipsis), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ if (running) Padding( padding: const EdgeInsets.only(right: 8), child: Icon(Icons.circle, size: 10, color: Theme.of(context).colorScheme.primary), ), PopupMenuButton( onSelected: (v) => _sessionAction(s, v), itemBuilder: (_) => const [ PopupMenuItem(value: 'rename', child: Text('重命名')), PopupMenuItem(value: 'archive', child: Text('归档')), PopupMenuItem(value: 'delete', child: Text('删除')), ], ), ], ), onTap: () { app.openChat(s); widget.onOpened?.call(); }, ); }, ), ); } String _subtitle(Session s) { final parts = []; if (s.agent.isNotEmpty) parts.add(s.agent); if (s.model != null) parts.add(widget.app.modelName(s.model)); if (s.updated > 0) { final t = DateTime.fromMillisecondsSinceEpoch(s.updated); parts.add('${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')} ' '${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}'); } return parts.join(' · '); } void _sessionAction(Session s, String v) { switch (v) { case 'rename': _rename(s); break; case 'archive': widget.app.client?.updateSession(s.id, archived: true); break; case 'delete': _confirmDelete(s); break; } } void _rename(Session s) { final ctrl = TextEditingController(text: s.title); showDialog( context: context, builder: (context) => AlertDialog( title: const Text('重命名'), content: TextField(controller: ctrl, autofocus: true), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('取消')), FilledButton( onPressed: () { Navigator.pop(context); widget.app.client?.updateSession(s.id, title: ctrl.text); }, child: const Text('保存'), ), ], ), ); } void _confirmDelete(Session s) { showDialog( context: context, builder: (context) => AlertDialog( title: const Text('删除会话?'), content: Text('“${s.title}”及其子会话将被删除,且无法恢复。'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('取消')), FilledButton( onPressed: () { Navigator.pop(context); widget.app.client?.deleteSession(s.id); widget.app.sessions.removeWhere((x) => x.id == s.id); widget.app.touch(); }, child: const Text('删除'), ), ], ), ); } void _newSessionSheet() { final ctrl = TextEditingController(); showModalBottomSheet( context: context, builder: (context) => Padding( padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Text('新建会话', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), const SizedBox(height: 12), TextField( controller: ctrl, autofocus: true, decoration: const InputDecoration( hintText: '标题(可选)', border: OutlineInputBorder()), ), const SizedBox(height: 12), FilledButton( onPressed: () async { Navigator.pop(context); final s = await widget.app.client?.createSession( title: ctrl.text, directory: widget.app.directory); if (s != null) { widget.app.sessions.insert(0, s); widget.app.touch(); widget.app.openChat(s); widget.onOpened?.call(); } }, child: const Text('创建'), ), ], ), ), ); } void _instancesSheet() { final app = widget.app; showModalBottomSheet( context: context, builder: (context) => SafeArea( child: Column( mainAxisSize: MainAxisSize.min, children: [ const Padding( padding: EdgeInsets.all(12), child: Text('服务器', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), ), for (final c in app.connections) ...[ ListTile( title: Text(c.label), subtitle: Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'), trailing: app.conn?.id == c.id ? Text('已连接', style: TextStyle( color: Theme.of(context).colorScheme.primary)) : null, onTap: () { Navigator.pop(context); if (app.conn?.id != c.id) app.switchTo(c); }, ), ], ListTile( leading: const Icon(Icons.add), title: const Text('添加服务器'), onTap: () { Navigator.pop(context); Navigator.of(context).push(MaterialPageRoute( builder: (_) => ServersScreen(app: app, startEditing: true), )); }, ), if (app.client != null) ListTile( leading: const Icon(Icons.link_off), title: const Text('断开当前连接'), onTap: () { Navigator.pop(context); app.disconnect(); }, ), const SizedBox(height: 8), ], ), ), ); } }