fix: dark markdown, steadier folds, readable tool details, live refresh

- gpt_markdown renders through its own Material port, whose Theme.of falls
  back to a light theme: code panels stayed light and their text black in
  the dark theme. The chat now wraps markdown in a matching `mui.Theme`.
- Folding a run changed the height below its header and threw the header
  out of view. The toggle remembers the header's screen position, corrects
  the scroll offset, and parks the header at the top when the run is
  longer than the viewport.
- Step details show what a tool actually did: the command and its output
  for shell steps, the remaining inputs and the result for the rest, in
  monospace; toolOutput falls back to metadata. A read/write/edit of an
  image is no longer foldable — its path opens the preview.
- The event stream now times out without a heartbeat, so a half-open
  connection is noticed and reopened; returning to the foreground restarts
  the stream, refreshes the session list and the open chat, and reloadTail
  merges the newest page instead of dropping loaded history.
- A page shorter than the limit means there is nothing older, so short
  sessions no longer offer "load earlier".
- Version 0.3.4 (code 304).
This commit is contained in:
blumia committed 2026-11-19 20:18:04 +08:00
1 parent 2baa0a2730
commit 32277564f9
9 files changed
+369 -55

No files matched your search

+8 -1
View File
@@ -324,7 +324,14 @@ class Client {
throw ApiError(res.statusCode, 'event stream failed');
}
String data = '';
await for (final line in utf8.decoder.bind(res).transform(const LineSplitter())) {
// The server sends a `: heartbeat` comment every few seconds; if nothing
// at all arrives for a while the connection is dead and the caller should
// reconnect rather than wait on a half-open socket.
final lines = utf8.decoder
.bind(res)
.transform(const LineSplitter())
.timeout(const Duration(seconds: 30));
await for (final line in lines) {
if (line.isEmpty) {
if (data.isNotEmpty) {
final ev = jsonDecode(data) as Map<String, dynamic>;
+16 -1
View File
@@ -14,15 +14,30 @@ class OpenChamberApp extends StatefulWidget {
State<OpenChamberApp> createState() => _OpenChamberAppState();
}
class _OpenChamberAppState extends State<OpenChamberApp> {
class _OpenChamberAppState extends State<OpenChamberApp>
with WidgetsBindingObserver {
final AppState app = AppState();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
app.init();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// The socket often dies while the app sits in the background; nothing
// reports it, so reopen the stream and refresh the open chat on return.
if (state == AppLifecycleState.resumed) app.onResumed();
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
+182 -38
View File
@@ -5,8 +5,12 @@ 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 'package:gpt_markdown/gpt_markdown.dart';
// gpt_markdown renders through its own Material port; its colours come from
// that port's theme, so the chat has to hand it ours.
import 'package:material_ui/material_ui.dart' as mui;
import '../api/client.dart';
import '../api/models.dart';
@@ -38,6 +42,10 @@ class _ChatScreenState extends State<ChatScreen> {
/// header of each run folds it away (key: message id and start part).
final Set<String> _collapsedSteps = {};
/// Lets a fold keep its own header where it was on screen.
final Map<String, GlobalKey> _headerKeys = {};
final GlobalKey _listKey = GlobalKey();
@override
void initState() {
super.initState();
@@ -136,6 +144,7 @@ class _ChatScreenState extends State<ChatScreen> {
final rows = _rows();
final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0;
return ListView.builder(
key: _listKey,
controller: _scroll,
reverse: true,
itemCount: rows.length + olderSlot,
@@ -397,17 +406,32 @@ class _ChatScreenState extends State<ChatScreen> {
}
}
/// gpt_markdown builds its widgets with `material_ui`, whose Theme.of has a
/// light fallback: without this the code panel and inline chips stayed light
/// (and their text dark) in the dark theme.
static mui.ThemeData _mdTheme(ThemeData theme) => mui.ThemeData(
useMaterial3: true,
brightness: theme.brightness,
colorScheme: mui.ColorScheme.fromSeed(
seedColor: theme.colorScheme.primary,
brightness: theme.brightness,
),
);
Widget _textRow(String id, int part) {
final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final text = m.content[part].text;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
child: GptMarkdown(
text,
// The server already streams deltas; show them as they arrive.
isStreaming: false,
style: const TextStyle(fontSize: 15, height: 1.45),
child: mui.Theme(
data: _mdTheme(Theme.of(context)),
child: GptMarkdown(
text,
// The server already streams deltas; show them as they arrive.
isStreaming: false,
style: const TextStyle(fontSize: 15, height: 1.45),
),
),
);
}
@@ -434,12 +458,12 @@ class _ChatScreenState extends State<ChatScreen> {
: running
? '执行中 · $tools 次工具调用'
: '已完成 · $tools 次工具调用';
final headerKey =
_headerKeys.putIfAbsent('$id/$start', () => GlobalKey());
return GestureDetector(
key: headerKey,
behavior: HitTestBehavior.opaque,
onTap: () => setState(() {
final key = '$id/$start';
collapsed ? _collapsedSteps.remove(key) : _collapsedSteps.add(key);
}),
onTap: () => _toggleGroup(id, start, collapsed, headerKey),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 12, 2),
child: Row(
@@ -468,6 +492,45 @@ class _ChatScreenState extends State<ChatScreen> {
);
}
/// Folds or unfolds a run, then puts its header back where it was: folding
/// changes the height below it, which would otherwise move the whole run
/// out of view under the finger.
void _toggleGroup(String id, int start, bool collapsed, GlobalKey key) {
final before = key.currentContext?.findRenderObject() as RenderBox?;
final target =
before != null && before.attached ? before.localToGlobal(Offset.zero).dy : null;
setState(() {
final k = '$id/$start';
collapsed ? _collapsedSteps.remove(k) : _collapsedSteps.add(k);
});
WidgetsBinding.instance.addPostFrameCallback((_) {
final box = key.currentContext?.findRenderObject() as RenderBox?;
if (box == null || !box.attached || !_scroll.hasClients) return;
final pos = _scroll.position;
var top = box.localToGlobal(Offset.zero).dy;
if (target != null) {
// The run changed height below its header; pull the list back so the
// header sits exactly where it was clicked.
final want = (pos.pixels + (target - top))
.clamp(pos.minScrollExtent, pos.maxScrollExtent);
if ((want - pos.pixels).abs() > 0.5) {
_scroll.jumpTo(want);
top = box.localToGlobal(Offset.zero).dy;
}
}
final list = _listKey.currentContext?.findRenderObject() as RenderBox?;
if (list == null) return;
final listTop = list.localToGlobal(Offset.zero).dy;
final listBottom = listTop + list.size.height;
// A run that is longer than the viewport cannot keep its header at the
// click point; park it at the top instead so it stays on screen.
if (top >= listTop + 4 && top <= listBottom - 60) return;
final want = (_scroll.position.pixels - (top - listTop))
.clamp(pos.minScrollExtent, pos.maxScrollExtent);
_scroll.jumpTo(want);
});
}
/// One step: a rounded icon, a label, the one-line summary, and details
/// when opened.
Widget _stepRow(String id, int part) {
@@ -482,7 +545,11 @@ class _ChatScreenState extends State<ChatScreen> {
final open = chat.expanded.contains(key);
final label = _stepLabel(p);
final summary = _stepSummary(p);
final refs = reasoning ? const <_ImageRef>[] : toolImages(p, chat.dir);
// A read of an image is a link to the picture, not a fold.
final image = _imageArg(p);
final refs = reasoning || image != null
? const <_ImageRef>[]
: toolImages(p, chat.dir);
return Container(
margin: const EdgeInsets.only(left: 22),
decoration: BoxDecoration(
@@ -492,12 +559,14 @@ class _ChatScreenState extends State<ChatScreen> {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InkWell(
onTap: () {
setState(() {
open ? chat.expanded.remove(key) : chat.expanded.add(key);
});
if (!open && !reasoning) chat.ensureToolLoaded(id);
},
onTap: image != null
? () => _openPreview(_ImageRef(image, summary.split('/').last))
: () {
setState(() {
open ? chat.expanded.remove(key) : chat.expanded.add(key);
});
if (!open && !reasoning) chat.ensureToolLoaded(id);
},
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 3, 10, 3),
child: Row(
@@ -536,11 +605,19 @@ class _ChatScreenState extends State<ChatScreen> {
child: Text(summary,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 13, color: theme.hintColor)),
style: TextStyle(
fontSize: 13,
color: image != null
? theme.colorScheme.primary
: theme.hintColor)),
),
],
Icon(open ? Icons.expand_less : Icons.expand_more,
size: 16, color: theme.hintColor),
if (image != null)
Icon(Icons.open_in_full,
size: 14, color: theme.colorScheme.primary)
else
Icon(open ? Icons.expand_less : Icons.expand_more,
size: 16, color: theme.hintColor),
],
),
),
@@ -565,12 +642,62 @@ class _ChatScreenState extends State<ChatScreen> {
),
),
),
if (open) _stepDetails(p, reasoning),
if (open && image == null) _stepDetails(p, reasoning),
],
),
);
}
static const _imageExts = {
'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'avif',
};
/// The file a read/write/edit step points at, when it is an image.
String? _imageArg(ContentPart p) {
if (p.type != 'tool') return null;
final name = p.name ?? '';
if (name != 'read' && name != 'write' && name != 'edit') return null;
final input = p.state?.input ?? const <String, dynamic>{};
final v = input['filePath'] ?? input['path'] ?? input['file'];
if (v is! String || v.isEmpty) return null;
final ext = v.contains('.') ? v.split('.').last.toLowerCase() : '';
if (!_imageExts.contains(ext)) return null;
if (v.startsWith('/') || chat.dir.isEmpty) return v;
return '${chat.dir}/$v';
}
/// The input field already shown by the row's summary.
static String? _primaryInput(ContentPart p) {
switch (p.name ?? '') {
case 'bash':
case 'shell':
case 'execute':
return 'command';
case 'read':
case 'write':
case 'edit':
return 'filePath';
case 'grep':
case 'glob':
case 'find':
return 'pattern';
case 'webfetch':
case 'web_fetch':
return 'url';
case 'task':
return 'description';
case 'skill':
return 'id';
default:
return null;
}
}
static bool _isShell(ContentPart p) =>
const {'bash', 'shell', 'execute'}.contains(p.name ?? '');
/// What the step actually did: the command or path, the rest of the input,
/// and the result — never the request JSON as a blob.
Widget _stepDetails(ContentPart p, bool reasoning) {
final theme = Theme.of(context);
if (reasoning) {
@@ -583,7 +710,16 @@ class _ChatScreenState extends State<ChatScreen> {
);
}
final input = p.state?.input ?? const <String, dynamic>{};
final primary = _primaryInput(p);
final extras = <MapEntry<String, String>>[
for (final e in input.entries)
if (e.key != primary && '${e.value}'.trim().isNotEmpty)
MapEntry(e.key, '${e.value}'),
];
final shell = _isShell(p);
final command = shell ? '${input['command'] ?? ''}'.trim() : '';
final output = toolOutput(p);
const mono = TextStyle(fontSize: 12, height: 1.45, fontFamily: 'monospace');
return Padding(
padding: const EdgeInsets.fromLTRB(10, 2, 10, 8),
child: Container(
@@ -596,22 +732,26 @@ class _ChatScreenState extends State<ChatScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (input.isNotEmpty)
SelectableText(const JsonEncoder.withIndent(' ').convert(input),
style: const TextStyle(
fontSize: 12,
fontFamily: 'monospace',
height: 1.4)),
if (input.isNotEmpty && output.isNotEmpty)
const SizedBox(height: 6),
if (output.isNotEmpty)
SelectableText(output,
style: TextStyle(
fontSize: 12,
height: 1.4,
color: p.state?.error != null
? theme.colorScheme.error
: theme.colorScheme.onSurfaceVariant)),
if (command.isNotEmpty)
SelectableText(command,
style: mono.copyWith(color: theme.colorScheme.onSurface)),
if (command.isNotEmpty) const SizedBox(height: 6),
for (final e in extras)
Padding(
padding: const EdgeInsets.only(bottom: 2),
child: Text('${e.key}: ${e.value}',
style: mono.copyWith(
fontSize: 11.5, color: theme.hintColor)),
),
if (extras.isNotEmpty) const SizedBox(height: 4),
SelectableText(
output.isEmpty ? (shell ? '无输出' : '无内容') : output,
style: mono.copyWith(
color: p.state?.error != null
? theme.colorScheme.error
: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
@@ -1431,8 +1571,12 @@ String toolOutput(ContentPart p) {
final st = p.state;
if (st == null) return '';
final out = st.content.where((c) => c.type == 'text').map((c) => c.text).join('\n');
if (out.isEmpty) return st.error ?? '';
return out;
if (out.isNotEmpty) return out;
for (final key in const ['output', 'result', 'stdout', 'text', 'content']) {
final v = st.metadata?[key];
if (v is String && v.isNotEmpty) return v;
}
return st.error ?? '';
}
+51 -12
View File
@@ -272,20 +272,32 @@ class AppState extends ChangeNotifier {
m.id;
}
StreamSubscription<Map<String, dynamic>>? _events;
int _streamGen = 0;
void _startStream() {
final cl = client;
if (cl == null) return;
final gen = ++_streamGen;
_events?.cancel().ignore();
Future<void> loop() async {
while (client == cl) {
try {
await for (final ev in cl.streamEvents(types: _eventTypes)) {
while (client == cl && gen == _streamGen) {
final done = Completer<void>();
_events = cl.streamEvents(types: _eventTypes).listen(
(ev) {
if (client != cl) return;
_applyEvent(ev);
}
} catch (_) {
// Connection dropped; fall through to the retry below.
}
if (client != cl) return;
},
onError: (Object _) {
if (!done.isCompleted) done.complete();
},
onDone: () {
if (!done.isCompleted) done.complete();
},
cancelOnError: true,
);
await done.future;
if (client != cl || gen != _streamGen) return;
error = '连接中断,正在重连…';
notifyListeners();
await Future.delayed(const Duration(seconds: 2));
@@ -294,6 +306,16 @@ class AppState extends ChangeNotifier {
loop();
}
/// Reopens the event stream and refreshes what is on screen. Called when the
/// app comes back to the foreground: a socket that died while the process
/// was in the background never reports it.
Future<void> onResumed() async {
if (client == null) return;
_startStream();
await refreshSessions();
if (chat != null) await chat!.reloadTail();
}
void _applyEvent(Map<String, dynamic> ev) {
final type = ev['type'] as String? ?? '';
final data = ev['data'] as Map<String, dynamic>? ?? {};
@@ -492,9 +514,11 @@ class ChatState extends ChangeNotifier {
try {
final page = await app.client!.listMessages(id, directory: dir);
_setMessages(page.data);
// A desc page's `next` cursor points at the older side.
// A desc page's `next` cursor points at the older side. The server also
// hands out a cursor for a page that already holds everything, so a
// short page means there is nothing older.
olderCursor = page.next;
hasMore = page.next != null;
hasMore = page.next != null && page.data.length >= _pageSize;
loading = false;
notifyListeners();
await reloadTail();
@@ -505,14 +529,29 @@ class ChatState extends ChangeNotifier {
}
}
/// Refreshes the newest page without dropping the older pages that were
/// already loaded; the server's copy wins for messages it returns.
Future<void> reloadTail() async {
try {
final page = await app.client!.listMessages(id, directory: dir);
_setMessages(page.data);
if (msgs.isEmpty) {
_setMessages(page.data);
} else {
final fresh = {for (final m in page.data) m.id: m};
final merged = <Message>[
for (final m in msgs) fresh.remove(m.id) ?? m,
for (final m in page.data)
if (fresh.containsKey(m.id)) m,
];
msgs = merged;
_sortMsgs();
}
notifyListeners();
} catch (_) {}
}
static const _pageSize = 30;
Future<void> loadOlder() async {
if (!hasMore || loadingOlder) return;
loadingOlder = true;
@@ -525,7 +564,7 @@ class ChatState extends ChangeNotifier {
msgs = [...older, ...msgs];
_sortMsgs();
olderCursor = page.next;
hasMore = page.next != null;
hasMore = page.next != null && page.data.length >= _pageSize;
} catch (_) {}
loadingOlder = false;
notifyListeners();