feat: a new-session draft and a sidebar grouped by project

- Starting a session opens NewSessionScreen instead of a title sheet: a
  project chip (GET /api/project, one row per canonical), a model/agent
  chip, attachments and the composer. Nothing is created on the server
  until the first send, which posts the session with its directory, model
  and agent and then sends that message.
- The draft lives in AppState (memory only): leaving it keeps it; the
  sidebar shows a draft row with its first line and a discard button; a
  failed create stays on the draft with its text.
- The session list groups by project (chat folders under 聊天), dates the
  rows (今天/昨天/本周早些时候/更早), pins through
  session.metadata.openchamber.pinned, archives on demand, pages with
  "载入更多", and swipes to pin/archive/delete (flutter_slidable).
- Child sessions are hidden; a parent's row shows its children's activity.
- The chat app bar follows the live session list, so the title the server
  generates from the first message appears at once.
- Attachments and the model picker move to shared widgets, used by the
  chat and the draft.
- 0.3.13 (313).
This commit is contained in:
blumia committed 2026-11-21 14:29:52 +08:00
1 parent 5a371e4faf
commit fff6562cbc
14 files changed
+1775 -366

No files matched your search

+38 -202
View File
@@ -3,14 +3,15 @@ import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/markdown_view.dart';
import '../widgets/model_picker.dart';
import '../widgets/usage_ring.dart';
import 'files_panel.dart';
@@ -39,10 +40,7 @@ class _ChatScreenState extends State<ChatScreen> {
final FocusNode _inputFocus = FocusNode();
final ScrollController _scroll = ScrollController();
bool _stick = true;
bool _pickerOpen = false;
String _pickerKind = 'model';
String _pickerFilter = '';
List<_Attach> _attachments = [];
List<ComposerAttachment> _attachments = [];
bool _attaching = false;
/// Decoded user attachments, so a rebuild does not base64-decode again.
@@ -109,8 +107,7 @@ class _ChatScreenState extends State<ChatScreen> {
tooltip: '会话',
onPressed: widget.onOpenSessions,
),
title: Text(widget.session.title.isEmpty ? '会话' : widget.session.title,
maxLines: 1, overflow: TextOverflow.ellipsis),
title: Text(_title(), maxLines: 1, overflow: TextOverflow.ellipsis),
actions: [
Padding(
padding: const EdgeInsets.only(right: 4),
@@ -122,13 +119,21 @@ class _ChatScreenState extends State<ChatScreen> {
child: Text(_modelLabel(),
maxLines: 1, overflow: TextOverflow.ellipsis),
),
onPressed: () => _openPicker('model'),
onPressed: () => showModelPickerSheet(
context,
app: widget.app,
kind: 'model',
model: chat.selectedModel ?? widget.session.model,
agent: chat.selectedAgent,
onModel: (m) => chat.switchModel(m),
onAgent: (a) => chat.switchAgent(a),
),
),
),
IconButton(
icon: const Icon(Icons.view_sidebar_outlined),
tooltip: '文件',
onPressed: () => showFilesPanel(context, widget.app, widget.session),
onPressed: () => showFilesPanel(context, widget.app, chat.dir),
),
],
),
@@ -394,6 +399,17 @@ class _ChatScreenState extends State<ChatScreen> {
}
}
/// The session's title as the list has it: the server names a session from
/// its first message, which arrives after this screen was built.
String _title() {
for (final session in widget.app.sessions) {
if (session.id == widget.session.id && session.title.isNotEmpty) {
return session.title;
}
}
return widget.session.title.isEmpty ? '会话' : widget.session.title;
}
Widget _userRow(String id) {
final m = chat.byId[id]!;
final theme = Theme.of(context);
@@ -1695,33 +1711,10 @@ class _ChatScreenState extends State<ChatScreen> {
}
/// Attachment chips with a thumbnail, unfolded above the input bar.
Widget _attachmentTray() {
return SizedBox(
height: 46,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
for (var i = 0; i < _attachments.length; i++)
Padding(
padding: const EdgeInsets.only(right: 6),
child: InputChip(
avatar: _attachments[i].path != null
? CircleAvatar(
backgroundImage: FileImage(File(_attachments[i].path!)),
)
: const Icon(Icons.insert_drive_file, size: 16),
label: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 160),
child: Text(_attachments[i].name,
maxLines: 1, overflow: TextOverflow.ellipsis),
),
onDeleted: () => setState(() => _attachments.removeAt(i)),
),
),
],
),
);
}
Widget _attachmentTray() => AttachmentTray(
items: _attachments,
onRemove: (i) => setState(() => _attachments.removeAt(i)),
);
String _modelLabel() {
final m = chat.selectedModel ?? widget.session.model;
@@ -1760,63 +1753,24 @@ class _ChatScreenState extends State<ChatScreen> {
Future<void> _pickFiles() async {
setState(() => _attaching = true);
try {
final files = await FilePicker.pickFiles();
if (files.isEmpty) return;
for (final f in files) {
final bytes = await f.readAsBytes();
if (bytes.length > 10 * 1024 * 1024) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('附件不能超过 10MB')));
continue;
final picked = await pickComposerAttachments(context);
if (picked.isEmpty) return;
setState(() {
for (final file in picked) {
if (_attachments.length >= 5) break;
_attachments.add(file);
}
final name = f.name;
final mime = _mime(name);
final dataUrl = 'data:$mime;base64,${base64Encode(bytes)}';
String? keptPath;
if (mime.startsWith('image/') && f.path != null) {
keptPath = await _keepImage(f.path!, name);
}
setState(() {
if (_attachments.length >= 5) return;
_attachments.add(_Attach(name: name, mime: mime, dataUrl: dataUrl, path: keptPath));
});
}
});
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('选择失败:$e')));
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('选择失败:$e')));
}
} finally {
if (mounted) setState(() => _attaching = false);
}
}
Future<String?> _keepImage(String src, String name) async {
try {
// No plugin needed: a cache copy is enough for the message being sent.
final d = Directory('${Directory.systemTemp.path}/openchamber-attachments');
await d.create(recursive: true);
final dst = '${d.path}/${DateTime.now().microsecondsSinceEpoch}-${name.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_')}';
await File(src).copy(dst);
return dst;
} catch (_) {
return null;
}
}
static String _mime(String name) {
final ext = name.contains('.') ? name.split('.').last.toLowerCase() : '';
switch (ext) {
case 'png': return 'image/png';
case 'jpg': case 'jpeg': return 'image/jpeg';
case 'gif': return 'image/gif';
case 'webp': return 'image/webp';
case 'pdf': return 'application/pdf';
case 'txt': return 'text/plain';
case 'json': return 'application/json';
default: return 'application/octet-stream';
}
}
// ---------------------------------------------------------- permissions
/// The agent's blocking questions sit just above the composer, like the
@@ -1870,116 +1824,6 @@ class _ChatScreenState extends State<ChatScreen> {
// -------------------------------------------------------------- sheets
void _openPicker(String kind) {
widget.app.refreshModels();
setState(() {
_pickerOpen = true;
_pickerKind = kind;
_pickerFilter = '';
});
_pickerSheet(context);
}
void _pickerSheet(BuildContext context) {
if (!_pickerOpen) return;
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
expand: false,
initialChildSize: 0.8,
maxChildSize: 0.92,
builder: (context, controller) => ListenableBuilder(
listenable: chat,
builder: (context, _) {
final title = _pickerKind == 'agent' ? '选择智能体' : '选择模型';
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 4),
child: Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: SegmentedButton<String>(
segments: const [
ButtonSegment(value: 'model', label: Text('模型')),
ButtonSegment(value: 'agent', label: Text('智能体')),
],
selected: {_pickerKind},
showSelectedIcon: false,
onSelectionChanged: (s) {
setState(() => _pickerKind = s.first);
widget.app.refreshModels();
},
),
),
Padding(
padding: const EdgeInsets.all(12),
child: TextField(
onChanged: (v) => setState(() => _pickerFilter = v),
decoration: const InputDecoration(hintText: '搜索', border: OutlineInputBorder(), isDense: true),
),
),
Expanded(
child: _pickerItems(controller),
),
],
);
},
),
),
).then((_) => _pickerOpen = false);
}
Widget _pickerItems(ScrollController controller) {
final filter = _pickerFilter.toLowerCase();
// (key, title, modelOrAgent, selected)
final items = <(String, String, Object?, bool)>[];
if (_pickerKind == 'model') {
final current = chat.selectedModel;
for (final m in widget.app.modelList) {
final selected = current != null &&
current.providerId == m.providerId &&
current.id == m.id;
items.add(
('${m.providerId}/${m.id}', m.name, ModelRef(m.id, m.providerId), selected));
}
} else {
for (final a in widget.app.agentList) {
// Compaction, Title and Summary are primary but hidden.
if (a.mode != 'primary' || a.hidden) continue;
items.add(('agent/${a.id}', a.name, a.id, chat.selectedAgent == a.id));
}
}
final visible = items
.where((e) => filter.isEmpty || e.$2.toLowerCase().contains(filter))
.toList();
if (visible.isEmpty) {
return const Center(child: Text('没有结果'));
}
return ListView.builder(
controller: controller,
itemCount: visible.length,
itemBuilder: (context, i) {
final it = visible[i];
return ListTile(
title: Text(it.$2),
trailing: it.$4 ? const Icon(Icons.check) : null,
onTap: () {
Navigator.pop(context);
setState(() => _pickerOpen = false);
if (it.$3 is ModelRef) {
chat.switchModel(it.$3 as ModelRef);
} else {
chat.switchAgent(it.$3 as String);
}
},
);
},
);
}
void _confirm({required String title, required String message, required String confirm, required VoidCallback onConfirm}) {
showDialog(
context: context,
@@ -2188,14 +2032,6 @@ class _Step {
const _Step(this.msgId, this.index, this.part);
}
class _Attach {
final String name;
final String mime;
final String dataUrl;
final String? path;
_Attach({required this.name, required this.mime, required this.dataUrl, this.path});
}
class _ImageRef {
final String source;
final String label;