fix: full chat history, picked model/agent, usage sheet, image previews

- The chat loaded only one page of history: a desc page's older side is
  cursor.next, not previous, and the server rejects a cursor combined
  with order (InvalidCursorError). The first page stores `next`, later
  pages pass only `cursor`. tool/history_probe.dart walks a 1698-message
  session down to the oldest message with no gaps.
- The message list is now reversed (newest at offset 0), so older pages
  grow above and the viewport stays put; near the top it loads by itself
  and a "load earlier" row remains as a fallback.
- The agent picker filtered only on mode, so Compaction/Title/Summary
  (primary but hidden) showed up. Filter `hidden` too, and mark the
  current model or agent with a check.
- The usage ring's sheet was guarded by a flag nothing ever set; the
  ring now opens the context detail sheet.
- Tool image previews use a self-loading dialog and Image.memory: no
  temp file and no path_provider, whose Android implementation throws
  ClassNotFoundException: Landroid/content/Context; on the emulator.
- "Add server" in the connected server sheet now opens the form and
  returns to the session list once connected.
- Add a Linux desktop target for fast local UI checks, plus the probe
  that pages history.
- Version 0.3.2 (code 302).
This commit is contained in:
blumia committed 2026-11-19 12:34:25 +08:00
1 parent 2f5aad3814
commit 61977d2b14
24 files changed
+834 -130

No files matched your search

+177 -98
View File
@@ -7,8 +7,8 @@ import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gpt_markdown/gpt_markdown.dart';
import 'package:path_provider/path_provider.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/usage_ring.dart';
@@ -31,10 +31,6 @@ class _ChatScreenState extends State<ChatScreen> {
bool _pickerOpen = false;
String _pickerKind = 'model';
String _pickerFilter = '';
bool _usageOpen = false;
String _previewTitle = '';
File? _previewFile;
bool _previewLoading = false;
List<_Attach> _attachments = [];
bool _attaching = false;
@@ -42,13 +38,19 @@ class _ChatScreenState extends State<ChatScreen> {
void initState() {
super.initState();
chat.addListener(_onChat);
// The list is reversed: offset 0 is the newest message (the bottom), and
// older pages grow above without moving what is on screen.
_scroll.addListener(() {
final atEnd = _scroll.position.pixels >=
_scroll.position.maxScrollExtent - 40;
if (_stick != atEnd) setState(() => _stick = atEnd);
final atBottom = _scroll.position.pixels <= 40;
if (_stick != atBottom) setState(() => _stick = atBottom);
final remaining =
_scroll.position.maxScrollExtent - _scroll.position.pixels;
if (remaining < 240 && chat.hasMore && !chat.loadingOlder) {
_loadOlder();
}
});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) _scroll.jumpTo(_scroll.position.maxScrollExtent);
if (_scroll.hasClients) _scroll.jumpTo(0);
});
}
@@ -56,9 +58,7 @@ class _ChatScreenState extends State<ChatScreen> {
if (mounted) setState(() {});
if (_stick) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
if (_scroll.hasClients) _scroll.jumpTo(0);
});
}
}
@@ -130,16 +130,39 @@ class _ChatScreenState extends State<ChatScreen> {
return const Center(child: CircularProgressIndicator());
}
final rows = _rows();
final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0;
return ListView.builder(
controller: _scroll,
itemCount: rows.length,
reverse: true,
itemCount: rows.length + olderSlot,
itemBuilder: (context, i) {
final r = rows[i];
return _row(r);
// i counts from the newest row up.
if (i < rows.length) return _row(rows[rows.length - 1 - i]);
if (chat.loadingOlder) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: Center(
child: SizedBox(
width: 22, height: 22, child: CircularProgressIndicator(strokeWidth: 2)),
),
);
}
return Center(
child: TextButton(
onPressed: _loadOlder,
child: const Text('载入更早的消息'),
),
);
},
);
}
/// Loads an older page; the reversed list keeps the viewport in place.
Future<void> _loadOlder() async {
if (!chat.hasMore || chat.loadingOlder) return;
await chat.loadOlder();
}
List<_Row> _rows() {
final out = <_Row>[];
for (var mi = 0; mi < chat.msgs.length; mi++) {
@@ -688,16 +711,9 @@ class _ChatScreenState extends State<ChatScreen> {
}
String _modelLabel() {
ModelRef? m;
for (var i = chat.msgs.length - 1; i >= 0; i--) {
if (chat.msgs[i].model != null) {
m = chat.msgs[i].model;
break;
}
}
m ??= widget.session.model;
final m = chat.selectedModel ?? widget.session.model;
final model = m == null ? '模型' : widget.app.modelName(m);
final agent = widget.session.agent;
final agent = chat.selectedAgent;
return agent.isEmpty ? model : '$model · $agent';
}
@@ -763,8 +779,8 @@ class _ChatScreenState extends State<ChatScreen> {
Future<String?> _keepImage(String src, String name) async {
try {
final dir = await getApplicationSupportDirectory();
final d = Directory('${dir.path}/attachments');
// 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);
@@ -897,14 +913,22 @@ class _ChatScreenState extends State<ChatScreen> {
Widget _pickerItems(ScrollController controller) {
final filter = _pickerFilter.toLowerCase();
final items = <(String, String, Object?)>[]; // (key, title, modelOrAgent)
// (key, title, modelOrAgent, selected)
final items = <(String, String, Object?, bool)>[];
if (_pickerKind == 'model') {
final current = chat.selectedModel;
for (final m in widget.app.modelList) {
items.add(('${m.providerId}/${m.id}', m.name, ModelRef(m.id, m.providerId)));
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) {
if (a.mode == 'primary') items.add(('agent/${a.id}', a.name, a.id));
// 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
@@ -920,6 +944,7 @@ class _ChatScreenState extends State<ChatScreen> {
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);
@@ -957,81 +982,20 @@ class _ChatScreenState extends State<ChatScreen> {
// ------------------------------------------------------------ previews
Future<void> _openPreview(_ImageRef ref) async {
setState(() {
_previewTitle = ref.label;
_previewFile = null;
_previewLoading = true;
});
_previewDialog(context);
try {
final bytes = await _loadPreview(ref.source);
final dir = await getApplicationSupportDirectory();
final d = Directory('${dir.path}/previews');
await d.create(recursive: true);
final f = File(
'${d.path}/${DateTime.now().microsecondsSinceEpoch}-${ref.label.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_')}');
await f.writeAsBytes(bytes);
if (mounted) {
setState(() {
_previewFile = f;
_previewLoading = false;
});
}
} catch (e) {
if (mounted) {
setState(() => _previewLoading = false);
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('无法预览:$e')));
}
}
}
void _previewDialog(BuildContext context) {
showDialog(
await showDialog(
context: context,
builder: (context) => Dialog(
insetPadding: const EdgeInsets.all(12),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.9),
child: ListenableBuilder(
listenable: chat,
builder: (context, _) => Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(12),
child: Text(_previewTitle, maxLines: 2, overflow: TextOverflow.ellipsis),
),
if (_previewLoading)
const Padding(
padding: EdgeInsets.all(40),
child: CircularProgressIndicator(),
)
else if (_previewFile != null)
Flexible(child: Image.file(_previewFile!, fit: BoxFit.contain)),
const SizedBox(height: 8),
],
),
),
),
builder: (_) => _ImagePreviewDialog(
title: ref.label,
source: ref.source,
directory: chat.dir,
client: widget.app.client!,
),
);
}
Future<Uint8List> _loadPreview(String source) async {
if (source.startsWith('data:')) {
final comma = source.indexOf(',');
final meta = source.substring(5, comma);
if (!meta.contains('base64')) throw Exception('不支持的 data URL');
return base64Decode(source.substring(comma + 1));
}
final bytes = await widget.app.client!.rawFile(source, directory: chat.dir);
return Uint8List.fromList(bytes);
}
// ------------------------------------------------------------ usage
void _usageSheet(BuildContext context) {
if (!_usageOpen) return;
final r = chat.usageReading();
showModalBottomSheet(
context: context,
@@ -1043,7 +1007,7 @@ class _ChatScreenState extends State<ChatScreen> {
children: [
const Text('上下文占用', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
const SizedBox(height: 12),
_usageRow('模型', widget.app.modelName(_lastModel())),
_usageRow('模型', widget.app.modelName(chat.selectedModel ?? _lastModel())),
_usageRow('已用 tokens', _fmtTokens(r.$1)),
if (r.$5) ...[
_usageRow('上下文上限', _fmtTokens(r.$2)),
@@ -1057,7 +1021,7 @@ class _ChatScreenState extends State<ChatScreen> {
],
),
),
).then((_) => _usageOpen = false);
);
}
ModelRef? _lastModel() {
@@ -1167,3 +1131,118 @@ String toolOutput(ContentPart p) {
if (out.isEmpty) return st.error ?? '';
return out;
}
/// A full-screen-ish image preview that loads itself: the dialog is created
/// first, so the image and its spinner must live in a StatefulWidget.
class _ImagePreviewDialog extends StatefulWidget {
final String title;
final String source;
final String directory;
final Client client;
const _ImagePreviewDialog({
required this.title,
required this.source,
required this.directory,
required this.client,
});
@override
State<_ImagePreviewDialog> createState() => _ImagePreviewDialogState();
}
class _ImagePreviewDialogState extends State<_ImagePreviewDialog> {
Uint8List? _bytes;
Object? _error;
bool _loading = true;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
try {
// Decoded straight from memory: no temp file, no platform plugin.
final bytes = await _fetch();
if (mounted) {
setState(() {
_bytes = bytes;
_loading = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_error = e;
_loading = false;
});
}
}
}
Future<Uint8List> _fetch() async {
final source = widget.source;
if (source.startsWith('data:')) {
final comma = source.indexOf(',');
if (comma < 0) throw Exception('无效的 data URL');
final meta = source.substring(5, comma);
if (!meta.contains('base64')) throw Exception('不支持的 data URL');
return base64Decode(source.substring(comma + 1));
}
final bytes =
await widget.client.rawFile(source, directory: widget.directory);
return Uint8List.fromList(bytes);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
Widget body;
if (_loading) {
body = const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
);
} else if (_bytes != null) {
body = Flexible(child: Image.memory(_bytes!, fit: BoxFit.contain));
} else {
body = Padding(
padding: const EdgeInsets.all(24),
child: SelectableText('无法预览:$_error',
style: TextStyle(color: theme.colorScheme.error)),
);
}
return Dialog(
insetPadding: const EdgeInsets.all(12),
child: ConstrainedBox(
constraints:
BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.9),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 4, 0),
child: Row(
children: [
Expanded(
child: Text(widget.title,
maxLines: 2, overflow: TextOverflow.ellipsis),
),
IconButton(
icon: const Icon(Icons.close),
tooltip: '关闭',
onPressed: () => Navigator.pop(context),
),
],
),
),
body,
const SizedBox(height: 8),
],
),
),
);
}
}