fix: reconcile the running state when the app returns

A turn that starts or ends while the app is in the background leaves no
event behind, so the activity strip kept its old state (stayed visible
after the turn ended) and the sidebar's running marks went stale too.

- on return, read the server's active set and the transcript tail once
  and settle both the open chat's strip and the sidebar from them
- do the same on the first event after the stream reconnects, since a
  silent drop loses the same events without leaving the app
- opening a chat whose turn is already under way asks once, so the strip
  is right from the first frame
- when the server cannot answer, the tail decides (an assistant message
  without a completion time is a live turn); a failed request is never
  read as "everything is idle"
This commit is contained in:
blumia committed 2026-11-25 00:23:50 +08:00
1 parent 9564019a91
commit 00564fe94b
5 files changed
+139 -10

No files matched your search

+15
View File
@@ -5,6 +5,21 @@
--- ---
## 0.4.16 回到前台后重新对账运行状态(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 会话进行到一半把应用切到后台,期间这一轮结束了:回到前台时对话区会刷新出新内容,但输入框上方的运行状态条还停在切走时的样子(该消失却没消失)。侧栏的运行标记同样只看事件流,漏掉结束事件后也会一直转 |
| 会话状态条 | 回前台时不再只重载转录,还会读一次 `GET /api/session/active`,再按服务器答复重新算「这一轮是否在跑」:在跑就显示、结束就收起。服务器没答上来时退回转录尾部(最新一条 assistant 消息还没有 `completed` 时间就是在跑),不会把一次失败的请求当成「全部空闲」 |
| 侧栏 | 回前台时刷新活动会话集合(`refreshActive`),侧栏的运行标记与后台会话的嵌套标记随之更新;服务器明确答复后才覆盖本地集合,请求失败保留原状态 |
| 事件流重连 | 同一套对账也挂在事件流恢复后的第一个事件上:socket 静默断过(不一定切过后台)而漏掉「这一轮结束」时,状态条和侧栏同样会自愈 |
| 打开会话 | 打开一个已经在中途的会话时也问一次服务器,状态条从第一帧就是对的(以前要等下一批事件才知道在跑) |
| 测试 | 新增 `test/running_state_test.dart`:服务器说空闲/在跑、服务器无答复时按转录尾部判断(有未完成的 assistant 消息算在跑,全部完成则不算);83 项全过 |
| 验证 | 模拟器:另一个会话里跑一轮长命令 → 切到后台 → 等这一轮结束 → 回到前台:状态条不再出现,侧栏该会话的运行标记消失;再验回前台时仍在进行的一轮保持显示 |
| 版本 | **0.4.16(code 416)** |
---
## 0.4.15 后台任务条细节:外观一致、停止移到弹层、宠物站位(分支 `flutter`) ## 0.4.15 后台任务条细节:外观一致、停止移到弹层、宠物站位(分支 `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.4.15 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.4.16 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing over the OpenChamber private relay with end-to-end encryption; the pairing
link is pasted or scanned with the camera), session list with search and live link is pasted or scanned with the camera), session list with search and live
+67 -8
View File
@@ -984,13 +984,21 @@ class AppState extends ChangeNotifier {
} }
} }
Future<void> refreshActive() async { /// Reads the sessions the server says are executing. False when it could
/// not tell: the caller then keeps its own view instead of reading an empty
/// answer as "everything is idle".
Future<bool> refreshActive() async {
final cl = client; final cl = client;
if (cl == null) return; if (cl == null) return false;
try { try {
active = await cl.activeSessions(); final ids = await cl.activeSessions();
if (cl != client) return false;
active = ids;
notifyListeners(); notifyListeners();
} catch (_) {} return true;
} catch (_) {
return false;
}
} }
Future<void> refreshPerms() async { Future<void> refreshPerms() async {
@@ -1041,9 +1049,14 @@ class AppState extends ChangeNotifier {
if (cl == null) return; if (cl == null) return;
final gen = ++_streamGen; final gen = ++_streamGen;
_events?.cancel().ignore(); _events?.cancel().ignore();
var afterDrop = false;
Future<void> loop() async { Future<void> loop() async {
while (client == cl && gen == _streamGen) { while (client == cl && gen == _streamGen) {
final done = Completer<void>(); final done = Completer<void>();
// Events sent while the stream was down are gone; the first one
// after a drop means the server is back, so catch up on the state
// those events would have changed.
var catchUp = afterDrop;
_events = cl.streamEvents(types: _eventTypes).listen( _events = cl.streamEvents(types: _eventTypes).listen(
(ev) { (ev) {
if (client != cl) return; if (client != cl) return;
@@ -1051,6 +1064,10 @@ class AppState extends ChangeNotifier {
// every connection with `server.connected`), so the "reconnecting" // every connection with `server.connected`), so the "reconnecting"
// banner has done its job. // banner has done its job.
if (error == '连接中断,正在重连…') error = null; if (error == '连接中断,正在重连…') error = null;
if (catchUp) {
catchUp = false;
_resyncActivity();
}
_applyEvent(ev); _applyEvent(ev);
}, },
onError: (Object _) { onError: (Object _) {
@@ -1063,6 +1080,7 @@ class AppState extends ChangeNotifier {
); );
await done.future; await done.future;
if (client != cl || gen != _streamGen) return; if (client != cl || gen != _streamGen) return;
afterDrop = true;
error = '连接中断,正在重连…'; error = '连接中断,正在重连…';
notifyListeners(); notifyListeners();
await Future.delayed(const Duration(seconds: 2)); await Future.delayed(const Duration(seconds: 2));
@@ -1079,15 +1097,30 @@ class AppState extends ChangeNotifier {
_startStream(); _startStream();
refreshFollowUpBehavior(); refreshFollowUpBehavior();
await refreshSessions(); await refreshSessions();
if (chat != null) { await _resyncActivity();
await chat!.reloadTail(); if (chat != null) await chat!.reloadInbox();
await chat!.reloadInbox();
}
for (final workspace in terminals.values) { for (final workspace in terminals.values) {
await workspace.reconnectIfNeeded(); await workspace.reconnectIfNeeded();
} }
} }
/// Reconciles what the server says is executing with what the UI shows.
/// A turn that started or ended while the app was in the background (or
/// while the event stream was down) leaves no event behind, so the strips
/// would keep their old state; the server's active set and the transcript
/// tail say where things actually stand.
Future<void> _resyncActivity() async {
final cl = client;
if (cl == null) return;
final ch = chat;
final known = await refreshActive();
if (client != cl) return;
if (ch == null) return;
await ch.reloadTail();
if (client != cl || chat != ch) return;
ch.reconcileRunning(active, known: known);
}
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>? ?? {};
@@ -1251,7 +1284,14 @@ class AppState extends ChangeNotifier {
// the session's subagents in parallel fills the nested rows under it. // the session's subagents in parallel fills the nested rows under it.
notifyListeners(); notifyListeners();
unawaited(loadChildren(s)); unawaited(loadChildren(s));
// Opening a chat whose turn is already under way: the events that started
// it came while the chat was closed, so ask the server once.
final actives = refreshActive();
await chat!.load(); await chat!.load();
final known = await actives;
if (chat != null && chat!.session.id == s.id) {
chat!.reconcileRunning(active, known: known);
}
notifyListeners(); notifyListeners();
} }
@@ -1362,6 +1402,25 @@ class ChatState extends ChangeNotifier {
/// Public way to signal UI changes. /// Public way to signal UI changes.
void touch() => notifyListeners(); void touch() => notifyListeners();
/// Takes the server's word on whether a turn is still running — the events
/// that started or ended it can arrive while the chat is closed, or never
/// arrive because the stream was down. Without an answer from the server,
/// the tail decides: an assistant message that has not been marked complete
/// is a live turn.
void reconcileRunning(Set<String> activeIds, {required bool known}) {
final next = known ? activeIds.contains(id) : _tailRunning;
if (next == running) return;
running = next;
notifyListeners();
}
bool get _tailRunning {
for (var i = msgs.length - 1; i >= 0; i--) {
if (msgs[i].type == 'assistant') return msgs[i].completed == 0;
}
return false;
}
String get id => session.id; String get id => session.id;
String get dir => session.directory; String get dir => session.directory;
+1 -1
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.4.15+415 version: 0.4.16+416
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
+55
View File
@@ -0,0 +1,55 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/state.dart';
void main() {
// The app can be in the background while a turn starts or ends; the events
// that said so never arrive, so the chat's running flag has to be taken
// from the server again when the app comes back.
group('reconciling a turn on return', () {
late AppState app;
late ChatState chat;
setUp(() {
app = AppState();
chat = ChatState(app, Session(id: 'ses_a', title: '会话'));
});
tearDown(() {
chat.dispose();
app.dispose();
});
test('the server saying idle ends a turn that was left running', () {
chat.running = true;
chat.reconcileRunning({'ses_other'}, known: true);
expect(chat.running, isFalse);
});
test('the server saying running keeps the strip, even without events', () {
chat.running = false;
chat.reconcileRunning({'ses_a'}, known: true);
expect(chat.running, isTrue);
});
test('the server not answering falls back on the transcript tail', () {
chat.running = false;
chat.msgs = [
Message(id: 'u1', type: 'user'),
Message(id: 'a1', type: 'assistant', completed: 100),
Message(id: 'u2', type: 'user'),
Message(id: 'a2', type: 'assistant'),
];
chat.reconcileRunning(const {}, known: false);
expect(chat.running, isTrue);
chat.running = true;
chat.msgs = [
Message(id: 'u1', type: 'user'),
Message(id: 'a1', type: 'assistant', completed: 100),
];
chat.reconcileRunning(const {}, known: false);
expect(chat.running, isFalse);
});
});
}