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

+135
View File
@@ -0,0 +1,135 @@
// Attachments shared by the chat composer and the new-session draft: what a
// picked file becomes (a data URL the server stores) and the chips that show
// it above the input.
import 'dart:convert';
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
class ComposerAttachment {
final String name;
final String mime;
final String dataUrl;
final String? path;
const ComposerAttachment({
required this.name,
required this.mime,
required this.dataUrl,
this.path,
});
bool get isImage => mime.startsWith('image/');
}
/// Opens the system picker and turns each choice into an attachment. Files
/// over 10 MB are refused with a message instead of being dropped silently.
Future<List<ComposerAttachment>> pickComposerAttachments(
BuildContext context) async {
final picked = await FilePicker.pickFiles();
if (picked.isEmpty) return const [];
final out = <ComposerAttachment>[];
for (final file in picked) {
final bytes = await file.readAsBytes();
if (bytes.length > 10 * 1024 * 1024) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('附件不能超过 10MB')));
}
continue;
}
final mime = _mimeOf(file.name);
String? keptPath;
if (mime.startsWith('image/') && file.path != null) {
keptPath = await _keepImage(file.path!, file.name);
}
out.add(ComposerAttachment(
name: file.name,
mime: mime,
dataUrl: 'data:$mime;base64,${base64Encode(bytes)}',
path: keptPath,
));
}
return out;
}
/// Chips with a thumbnail, unfolded above the input bar.
class AttachmentTray extends StatelessWidget {
final List<ComposerAttachment> items;
final ValueChanged<int> onRemove;
const AttachmentTray({
super.key,
required this.items,
required this.onRemove,
});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 46,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
for (var i = 0; i < items.length; i++)
Padding(
padding: const EdgeInsets.only(right: 6),
child: InputChip(
avatar: items[i].path != null
? CircleAvatar(
backgroundImage: FileImage(File(items[i].path!)),
)
: const Icon(Icons.insert_drive_file, size: 16),
label: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 160),
child: Text(items[i].name,
maxLines: 1, overflow: TextOverflow.ellipsis),
),
onDeleted: () => onRemove(i),
),
),
],
),
);
}
}
String _mimeOf(String name) {
final ext = name.split('.').last.toLowerCase();
return switch (ext) {
'png' => 'image/png',
'jpg' || 'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'webp' => 'image/webp',
'bmp' => 'image/bmp',
'avif' => 'image/avif',
'ico' => 'image/x-icon',
'pdf' => 'application/pdf',
'json' => 'application/json',
'md' || 'markdown' => 'text/markdown',
'txt' => 'text/plain',
'csv' => 'text/csv',
'html' => 'text/html',
'xml' => 'text/xml',
'zip' => 'application/zip',
_ => 'application/octet-stream',
};
}
Future<String?> _keepImage(String src, String name) async {
try {
// No plugin needed: a cache copy is enough for the message being sent.
final dir = Directory(
'${Directory.systemTemp.path}/openchamber-attachments');
await dir.create(recursive: true);
final safe =
name.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_');
final dst =
'${dir.path}/${DateTime.now().microsecondsSinceEpoch}-$safe';
await File(src).copy(dst);
return dst;
} catch (_) {
return null;
}
}
+157
View File
@@ -0,0 +1,157 @@
// The model / agent picker, shared by the chat's app-bar chip and the
// new-session draft (where it chooses what the session will start on).
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../state.dart';
Future<void> showModelPickerSheet(
BuildContext context, {
required AppState app,
required String kind,
required ModelRef? model,
required String agent,
required ValueChanged<ModelRef> onModel,
required ValueChanged<String> onAgent,
}) {
app.refreshModels();
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
expand: false,
initialChildSize: 0.8,
maxChildSize: 0.92,
builder: (context, controller) => _PickerSheet(
app: app,
kind: kind,
model: model,
agent: agent,
scrollController: controller,
onModel: onModel,
onAgent: onAgent,
),
),
);
}
class _PickerSheet extends StatefulWidget {
final AppState app;
final String kind;
final ModelRef? model;
final String agent;
final ScrollController scrollController;
final ValueChanged<ModelRef> onModel;
final ValueChanged<String> onAgent;
const _PickerSheet({
required this.app,
required this.kind,
required this.model,
required this.agent,
required this.scrollController,
required this.onModel,
required this.onAgent,
});
@override
State<_PickerSheet> createState() => _PickerSheetState();
}
class _PickerSheetState extends State<_PickerSheet> {
late String _kind = widget.kind;
String _filter = '';
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: widget.app,
builder: (context, _) => Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 4),
child: Text(_kind == 'agent' ? '选择智能体' : '选择模型',
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: {_kind},
showSelectedIcon: false,
onSelectionChanged: (s) {
setState(() => _kind = s.first);
widget.app.refreshModels();
},
),
),
Padding(
padding: const EdgeInsets.all(12),
child: TextField(
onChanged: (v) => setState(() => _filter = v),
decoration: const InputDecoration(
hintText: '搜索',
border: OutlineInputBorder(),
isDense: true),
),
),
Expanded(child: _items()),
],
),
);
}
Widget _items() {
final filter = _filter.toLowerCase();
// (key, title, modelOrAgent, selected)
final items = <(String, String, Object?, bool)>[];
if (_kind == 'model') {
for (final m in widget.app.modelList) {
final selected = widget.model != null &&
widget.model!.providerId == m.providerId &&
widget.model!.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, widget.agent == 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: widget.scrollController,
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);
if (it.$3 is ModelRef) {
widget.onModel(it.$3 as ModelRef);
} else {
widget.onAgent(it.$3 as String);
}
},
);
},
);
}
}