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

+3 -1
View File
@@ -197,7 +197,9 @@ class Client {
{int limit = 30, String? cursor, String order = 'desc', String? directory, bool partShells = true}) async {
final query = <String, String>{
'limit': '$limit',
'order': order,
// The server rejects a cursor combined with order: the cursor already
// carries the direction.
if (cursor == null) 'order': order,
if (cursor != null) 'cursor': cursor,
};
final r = await _json('GET', '/api/session/${Uri.encodeComponent(id)}/message',
+8 -3
View File
@@ -262,9 +262,14 @@ class AgentInfo {
final String id;
final String name;
final String mode;
AgentInfo(this.id, this.name, this.mode);
factory AgentInfo.fromJson(Map<String, dynamic> j) =>
AgentInfo(j['id'] as String, j['name'] as String? ?? '', j['mode'] as String? ?? '');
final bool hidden;
AgentInfo(this.id, this.name, this.mode, [this.hidden = false]);
factory AgentInfo.fromJson(Map<String, dynamic> j) => AgentInfo(
j['id'] as String,
j['name'] as String? ?? '',
j['mode'] as String? ?? '',
j['hidden'] as bool? ?? false,
);
}
class PermissionRequest {
+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),
],
),
),
);
}
}
+13 -1
View File
@@ -6,7 +6,11 @@ import '../storage.dart';
/// The first screen: the saved servers, or the connect form.
class ServersScreen extends StatefulWidget {
final AppState app;
const ServersScreen({super.key, required this.app});
/// Open the "add server" form straight away (pushed from the server sheet
/// while a connection is live).
final bool startEditing;
const ServersScreen({super.key, required this.app, this.startEditing = false});
@override
State<ServersScreen> createState() => _ServersScreenState();
@@ -25,6 +29,12 @@ class _ServersScreenState extends State<ServersScreen> {
bool _connecting = false;
String? _formError;
@override
void initState() {
super.initState();
if (widget.startEditing) _editing = true;
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
@@ -279,6 +289,8 @@ class _ServersScreenState extends State<ServersScreen> {
if (mounted) {
if (widget.app.client != null) {
setState(() => _editing = false);
// Pushed on top of a live session list: return there.
if (Navigator.of(context).canPop()) Navigator.of(context).pop();
} else {
setState(() {
_connecting = false;
+8 -1
View File
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import '../api/models.dart';
import '../state.dart';
import 'servers_screen.dart';
import 'chat_screen.dart';
/// The connected screen: the live session list.
@@ -317,7 +318,13 @@ class _SessionsScreenState extends State<SessionsScreen> {
ListTile(
leading: const Icon(Icons.add),
title: const Text('添加服务器'),
onTap: () => Navigator.pop(context),
onTap: () {
Navigator.pop(context);
Navigator.of(context).push(MaterialPageRoute(
builder: (_) =>
ServersScreen(app: app, startEditing: true),
));
},
),
if (app.client != null)
ListTile(
+36 -14
View File
@@ -473,14 +473,12 @@ class ChatState extends ChangeNotifier {
bool hasMore = false;
bool loadingOlder = false;
Map<String, List<String>> imagePaths = {};
final Map<String, String> previewCache = {};
bool previewOpen = false;
String previewTitle = '';
String? previewPath;
bool previewLoading = false;
int previewSeq = 0;
ModelRef? selectedModel;
String selectedAgent;
ChatState(this.app, this.session);
ChatState(this.app, this.session)
: selectedModel = session.model,
selectedAgent = session.agent;
/// Public way to signal UI changes.
void touch() => notifyListeners();
@@ -494,8 +492,9 @@ class ChatState extends ChangeNotifier {
try {
final page = await app.client!.listMessages(id, directory: dir);
_setMessages(page.data);
olderCursor = page.previous;
hasMore = page.previous != null;
// A desc page's `next` cursor points at the older side.
olderCursor = page.next;
hasMore = page.next != null;
loading = false;
notifyListeners();
await reloadTail();
@@ -524,9 +523,9 @@ class ChatState extends ChangeNotifier {
final seen = msgs.map((m) => m.id).toSet();
final older = page.data.where((m) => !seen.contains(m.id)).toList();
msgs = [...older, ...msgs];
_reindex();
olderCursor = page.previous;
hasMore = page.previous != null;
_sortMsgs();
olderCursor = page.next;
hasMore = page.next != null;
} catch (_) {}
loadingOlder = false;
notifyListeners();
@@ -534,6 +533,15 @@ class ChatState extends ChangeNotifier {
void _setMessages(List<Message> list) {
msgs = list;
_sortMsgs();
}
/// Oldest first: a page arrives newest-first (order: desc).
void _sortMsgs() {
msgs.sort((a, b) {
if (a.created == b.created) return a.id.compareTo(b.id);
return a.created.compareTo(b.created);
});
_reindex();
}
@@ -553,7 +561,7 @@ class ChatState extends ChangeNotifier {
created: DateTime.now().millisecondsSinceEpoch,
files: files?.map((f) => FileAttachment(f['name'] ?? '附件', '')).toList() ?? const [],
));
_reindex();
_sortMsgs();
notifyListeners();
try {
await app.client!.prompt(this.id, text: t, messageId: id, directory: dir, files: files);
@@ -617,6 +625,8 @@ class ChatState extends ChangeNotifier {
Future<void> switchModel(ModelRef model) async {
try {
await app.client!.switchModel(id, model, directory: dir);
selectedModel = model;
notifyListeners();
} catch (e) {
error = e.toString();
notifyListeners();
@@ -626,6 +636,8 @@ class ChatState extends ChangeNotifier {
Future<void> switchAgent(String agent) async {
try {
await app.client!.switchAgent(id, agent, directory: dir);
selectedAgent = agent;
notifyListeners();
} catch (e) {
error = e.toString();
notifyListeners();
@@ -719,6 +731,16 @@ class ChatState extends ChangeNotifier {
case 'session.tool.progress':
if (mid != null) _applyTool(mid, type, data);
break;
case 'session.model.selected':
final model = data['model'];
if (model is Map<String, dynamic>) {
selectedModel = ModelRef.fromJson(model);
}
break;
case 'session.agent.selected':
final agent = data['agent'];
if (agent is String && agent.isNotEmpty) selectedAgent = agent;
break;
}
notifyListeners();
}
@@ -726,7 +748,7 @@ class ChatState extends ChangeNotifier {
void _ensureAssistant(String id, int created) {
if (byId.containsKey(id)) return;
msgs.add(Message(id: id, type: 'assistant', created: created));
_reindex();
_sortMsgs();
}
void _applyDelta(String mid, int ordinal, String kind, String type, Map<String, dynamic> data) {