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

+15
View File
@@ -27,6 +27,21 @@
--- ---
## 0.3.4 主题与工具细节(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 暗色主题代码块/行内代码 | `gpt_markdown` 用的是它自带的 `material_ui` 移植版 Material,`Theme.of` 找不到宿主主题时回落成**亮色**,于是代码块面板亮、正文黑。现在渲染前用同一套亮/暗 `mui.ThemeData` 包一层,面板、行内代码、表格、语法配色都跟随应用主题 |
| 折叠时视口跳动 | 折叠/展开会改变分组高度:现在记录表头在屏幕上的位置,重建后按差值补偿滚动;若因列表边界补不回来,就把表头停到列表顶部。展开时始终看到分组头部,不再落到分组末尾 |
| 工具详情 | 不再直接铺请求 JSON:`运行` 显示完整命令(可选中、换行)+ 输出,其它工具显示摘要之外的参数与结果;输出为空时显示「无输出」。`toolOutput` 在 `content` 为空时回退到 `metadata` 的 output/result/stdout |
| 图片读取 | `读取`/`写入`/`编辑` 指向图片时,该行不再展开,路径直接可点,打开大图预览 |
| 会话不自动刷新 | SSE 增加 30s 心跳超时(服务端每几秒发 `: heartbeat`),断流会被发现并重连;应用回到前台时重开事件流、刷新会话列表并 `reloadTail()`(合并而不是替换已加载的历史页) |
| 「载入更早」误显示 | 服务端对已经包含全部内容的页也会给 cursor,现在短于一页即视为没有更早内容 |
| openui-lang | 暂未渲染:pub 上的 `openui_lang` 0.18.2 组件签名与 OpenChamber 的 DSL 不一致(`Card` 首参是 children 而非标题,且没有 `Badge`/`KeyValue`/`Stat`/`Details`),接入需要一层组件映射;本轮先跳过 |
| 版本 | **0.3.4(code 304)** |
---
## 0.3.3 工具调用展示(分支 `flutter`) ## 0.3.3 工具调用展示(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+1 -1
View File
@@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. Flutter to compare mobile UI maturity.
Status: 0.3.3 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.3.4 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live
events, chat with streaming Markdown and full history paging, tool steps events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a grouped per turn (icon, one-line summary, foldable run) with image previews, a
+8 -1
View File
@@ -324,7 +324,14 @@ class Client {
throw ApiError(res.statusCode, 'event stream failed'); throw ApiError(res.statusCode, 'event stream failed');
} }
String data = ''; 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 (line.isEmpty) {
if (data.isNotEmpty) { if (data.isNotEmpty) {
final ev = jsonDecode(data) as Map<String, dynamic>; final ev = jsonDecode(data) as Map<String, dynamic>;
+16 -1
View File
@@ -14,15 +14,30 @@ class OpenChamberApp extends StatefulWidget {
State<OpenChamberApp> createState() => _OpenChamberAppState(); State<OpenChamberApp> createState() => _OpenChamberAppState();
} }
class _OpenChamberAppState extends State<OpenChamberApp> { class _OpenChamberAppState extends State<OpenChamberApp>
with WidgetsBindingObserver {
final AppState app = AppState(); final AppState app = AppState();
@override @override
void initState() { void initState() {
super.initState(); super.initState();
WidgetsBinding.instance.addObserver(this);
app.init(); 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ListenableBuilder( return ListenableBuilder(
+182 -38
View File
@@ -5,8 +5,12 @@ import 'dart:typed_data';
import 'package:file_picker/file_picker.dart'; import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:gpt_markdown/gpt_markdown.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/client.dart';
import '../api/models.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). /// header of each run folds it away (key: message id and start part).
final Set<String> _collapsedSteps = {}; 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 @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -136,6 +144,7 @@ class _ChatScreenState extends State<ChatScreen> {
final rows = _rows(); final rows = _rows();
final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0; final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0;
return ListView.builder( return ListView.builder(
key: _listKey,
controller: _scroll, controller: _scroll,
reverse: true, reverse: true,
itemCount: rows.length + olderSlot, 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) { Widget _textRow(String id, int part) {
final m = chat.byId[id]!; final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink(); if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final text = m.content[part].text; final text = m.content[part].text;
return Padding( return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
child: GptMarkdown( child: mui.Theme(
text, data: _mdTheme(Theme.of(context)),
// The server already streams deltas; show them as they arrive. child: GptMarkdown(
isStreaming: false, text,
style: const TextStyle(fontSize: 15, height: 1.45), // 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 : running
? '执行中 · $tools 次工具调用' ? '执行中 · $tools 次工具调用'
: '已完成 · $tools 次工具调用'; : '已完成 · $tools 次工具调用';
final headerKey =
_headerKeys.putIfAbsent('$id/$start', () => GlobalKey());
return GestureDetector( return GestureDetector(
key: headerKey,
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () => setState(() { onTap: () => _toggleGroup(id, start, collapsed, headerKey),
final key = '$id/$start';
collapsed ? _collapsedSteps.remove(key) : _collapsedSteps.add(key);
}),
child: Padding( child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 12, 2), padding: const EdgeInsets.fromLTRB(14, 10, 12, 2),
child: Row( 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 /// One step: a rounded icon, a label, the one-line summary, and details
/// when opened. /// when opened.
Widget _stepRow(String id, int part) { Widget _stepRow(String id, int part) {
@@ -482,7 +545,11 @@ class _ChatScreenState extends State<ChatScreen> {
final open = chat.expanded.contains(key); final open = chat.expanded.contains(key);
final label = _stepLabel(p); final label = _stepLabel(p);
final summary = _stepSummary(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( return Container(
margin: const EdgeInsets.only(left: 22), margin: const EdgeInsets.only(left: 22),
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -492,12 +559,14 @@ class _ChatScreenState extends State<ChatScreen> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
InkWell( InkWell(
onTap: () { onTap: image != null
setState(() { ? () => _openPreview(_ImageRef(image, summary.split('/').last))
open ? chat.expanded.remove(key) : chat.expanded.add(key); : () {
}); setState(() {
if (!open && !reasoning) chat.ensureToolLoaded(id); open ? chat.expanded.remove(key) : chat.expanded.add(key);
}, });
if (!open && !reasoning) chat.ensureToolLoaded(id);
},
child: Padding( child: Padding(
padding: const EdgeInsets.fromLTRB(10, 3, 10, 3), padding: const EdgeInsets.fromLTRB(10, 3, 10, 3),
child: Row( child: Row(
@@ -536,11 +605,19 @@ class _ChatScreenState extends State<ChatScreen> {
child: Text(summary, child: Text(summary,
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, 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, if (image != null)
size: 16, color: theme.hintColor), 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) { Widget _stepDetails(ContentPart p, bool reasoning) {
final theme = Theme.of(context); final theme = Theme.of(context);
if (reasoning) { if (reasoning) {
@@ -583,7 +710,16 @@ class _ChatScreenState extends State<ChatScreen> {
); );
} }
final input = p.state?.input ?? const <String, dynamic>{}; 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); final output = toolOutput(p);
const mono = TextStyle(fontSize: 12, height: 1.45, fontFamily: 'monospace');
return Padding( return Padding(
padding: const EdgeInsets.fromLTRB(10, 2, 10, 8), padding: const EdgeInsets.fromLTRB(10, 2, 10, 8),
child: Container( child: Container(
@@ -596,22 +732,26 @@ class _ChatScreenState extends State<ChatScreen> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (input.isNotEmpty) if (command.isNotEmpty)
SelectableText(const JsonEncoder.withIndent(' ').convert(input), SelectableText(command,
style: const TextStyle( style: mono.copyWith(color: theme.colorScheme.onSurface)),
fontSize: 12, if (command.isNotEmpty) const SizedBox(height: 6),
fontFamily: 'monospace', for (final e in extras)
height: 1.4)), Padding(
if (input.isNotEmpty && output.isNotEmpty) padding: const EdgeInsets.only(bottom: 2),
const SizedBox(height: 6), child: Text('${e.key}: ${e.value}',
if (output.isNotEmpty) style: mono.copyWith(
SelectableText(output, fontSize: 11.5, color: theme.hintColor)),
style: TextStyle( ),
fontSize: 12, if (extras.isNotEmpty) const SizedBox(height: 4),
height: 1.4, SelectableText(
color: p.state?.error != null output.isEmpty ? (shell ? '无输出' : '无内容') : output,
? theme.colorScheme.error style: mono.copyWith(
: theme.colorScheme.onSurfaceVariant)), color: p.state?.error != null
? theme.colorScheme.error
: theme.colorScheme.onSurfaceVariant,
),
),
], ],
), ),
), ),
@@ -1431,8 +1571,12 @@ String toolOutput(ContentPart p) {
final st = p.state; final st = p.state;
if (st == null) return ''; if (st == null) return '';
final out = st.content.where((c) => c.type == 'text').map((c) => c.text).join('\n'); final out = st.content.where((c) => c.type == 'text').map((c) => c.text).join('\n');
if (out.isEmpty) return st.error ?? ''; if (out.isNotEmpty) return out;
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; m.id;
} }
StreamSubscription<Map<String, dynamic>>? _events;
int _streamGen = 0;
void _startStream() { void _startStream() {
final cl = client; final cl = client;
if (cl == null) return; if (cl == null) return;
final gen = ++_streamGen;
_events?.cancel().ignore();
Future<void> loop() async { Future<void> loop() async {
while (client == cl) { while (client == cl && gen == _streamGen) {
try { final done = Completer<void>();
await for (final ev in cl.streamEvents(types: _eventTypes)) { _events = cl.streamEvents(types: _eventTypes).listen(
(ev) {
if (client != cl) return; if (client != cl) return;
_applyEvent(ev); _applyEvent(ev);
} },
} catch (_) { onError: (Object _) {
// Connection dropped; fall through to the retry below. if (!done.isCompleted) done.complete();
} },
if (client != cl) return; onDone: () {
if (!done.isCompleted) done.complete();
},
cancelOnError: true,
);
await done.future;
if (client != cl || gen != _streamGen) return;
error = '连接中断,正在重连…'; error = '连接中断,正在重连…';
notifyListeners(); notifyListeners();
await Future.delayed(const Duration(seconds: 2)); await Future.delayed(const Duration(seconds: 2));
@@ -294,6 +306,16 @@ class AppState extends ChangeNotifier {
loop(); 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) { void _applyEvent(Map<String, dynamic> ev) {
final type = ev['type'] as String? ?? ''; final type = ev['type'] as String? ?? '';
final data = ev['data'] as Map<String, dynamic>? ?? {}; final data = ev['data'] as Map<String, dynamic>? ?? {};
@@ -492,9 +514,11 @@ class ChatState extends ChangeNotifier {
try { try {
final page = await app.client!.listMessages(id, directory: dir); final page = await app.client!.listMessages(id, directory: dir);
_setMessages(page.data); _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; olderCursor = page.next;
hasMore = page.next != null; hasMore = page.next != null && page.data.length >= _pageSize;
loading = false; loading = false;
notifyListeners(); notifyListeners();
await reloadTail(); 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 { Future<void> reloadTail() async {
try { try {
final page = await app.client!.listMessages(id, directory: dir); 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(); notifyListeners();
} catch (_) {} } catch (_) {}
} }
static const _pageSize = 30;
Future<void> loadOlder() async { Future<void> loadOlder() async {
if (!hasMore || loadingOlder) return; if (!hasMore || loadingOlder) return;
loadingOlder = true; loadingOlder = true;
@@ -525,7 +564,7 @@ class ChatState extends ChangeNotifier {
msgs = [...older, ...msgs]; msgs = [...older, ...msgs];
_sortMsgs(); _sortMsgs();
olderCursor = page.next; olderCursor = page.next;
hasMore = page.next != null; hasMore = page.next != null && page.data.length >= _pageSize;
} catch (_) {} } catch (_) {}
loadingOlder = false; loadingOlder = false;
notifyListeners(); notifyListeners();
+1 -2
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.3.3+303 version: 0.3.4+304
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
@@ -16,7 +16,6 @@ dependencies:
file_picker: ^13.0.0 file_picker: ^13.0.0
gpt_markdown: ^1.4.0 gpt_markdown: ^1.4.0
socks5_proxy: ^2.1.2 socks5_proxy: ^2.1.2
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter
+37
View File
@@ -0,0 +1,37 @@
// Prints live SSE events for a few seconds: their type, session id and the
// keys of their payload. Run against a live server:
// dart run tool/event_probe.dart [seconds]
import 'dart:async';
import 'dart:io';
import 'package:openchamber/api/client.dart';
Future<void> main(List<String> args) async {
final seconds = args.isEmpty ? 20 : int.tryParse(args[0]) ?? 20;
final client = Client(Uri.parse('http://127.0.0.1:3000'));
final seen = <String, int>{};
final sub = client.streamEvents(types: [
'session.created', 'session.renamed', 'session.execution.started',
'session.execution.succeeded', 'session.execution.failed',
'session.execution.interrupted', 'session.step.started',
'session.step.ended', 'session.step.failed', 'session.text.started',
'session.text.delta', 'session.text.ended', 'session.reasoning.started',
'session.reasoning.delta', 'session.reasoning.ended',
'session.tool.called', 'session.tool.success', 'session.tool.failed',
'permission.asked', 'permission.replied',
]).listen((ev) {
final type = ev['type'] as String? ?? '';
final data = ev['data'] as Map<String, dynamic>? ?? {};
seen[type] = (seen[type] ?? 0) + 1;
final sid = data['sessionID'] ?? data['sessionId'];
print('$type session=$sid message=${data['assistantMessageID'] ?? data['messageID']} '
'keys=${data.keys.take(6).join(',')}');
}, onError: (Object e) => print('stream error: $e'));
await Future.delayed(Duration(seconds: seconds));
await sub.cancel();
print('----');
print(seen);
client.close();
exit(0);
}
+58
View File
@@ -0,0 +1,58 @@
// Creates a throwaway session, prompts it, and prints the live events for it:
// type, session id, assistant message id and payload keys. This is how the
// chat's streaming path is checked against a real server.
// dart run tool/live_probe.dart [seconds]
import 'dart:async';
import 'dart:io';
import 'package:openchamber/api/client.dart';
const types = [
'session.created', 'session.renamed', 'session.execution.started',
'session.execution.succeeded', 'session.execution.failed',
'session.execution.interrupted', 'session.step.started',
'session.step.ended', 'session.step.failed', 'session.text.started',
'session.text.delta', 'session.text.ended', 'session.reasoning.started',
'session.reasoning.delta', 'session.reasoning.ended',
'session.tool.called', 'session.tool.success', 'session.tool.failed',
'permission.asked', 'permission.replied',
];
Future<void> main(List<String> args) async {
final seconds = args.isEmpty ? 40 : int.tryParse(args[0]) ?? 40;
final dir = Directory.current.path;
final client = Client(Uri.parse('http://127.0.0.1:3000'));
final session = await client.createSession(title: 'event probe', directory: dir);
print('session ${session.id}');
final counts = <String, int>{};
final sub = client.streamEvents(types: types).listen((ev) {
final type = ev['type'] as String? ?? '';
final data = ev['data'] as Map<String, dynamic>? ?? {};
final sid = data['sessionID'];
if (sid != session.id) return;
counts[type] = (counts[type] ?? 0) + 1;
print('$type msg=${data['assistantMessageID'] ?? data['messageID']} '
'part=${data['partID']} keys=${data.keys.join(',')}');
}, onError: (Object e) => print('stream error: $e'));
await Future.delayed(const Duration(milliseconds: 500));
await client.prompt(session.id,
text: 'Reply with the single word: pong', directory: dir);
print('prompted');
await Future.delayed(Duration(seconds: seconds));
await sub.cancel();
final page = await client.listMessages(session.id, limit: 50, directory: dir);
print('---- messages: ${page.data.length}');
for (final m in page.data.reversed) {
final parts = m.content.map((p) => '${p.type}${p.name == null ? '' : '(${p.name})'}').join(',');
print('${m.id} ${m.type} parts=[$parts]');
}
print('---- event counts: $counts');
await client.deleteSession(session.id);
client.close();
exit(0);
}