fix: clear a stale relay banner once the connection is back

- resuming from the background can fail the first relay request (DNS not
  ready yet) while a later session read and the event stream work; the
  banner stayed because only the exact "Connection lost, reconnecting…"
  text was ever cleared, and a successful session read did not clear it
- transport errors (connect, session list/search/more, archive, active,
  permissions, chat settings, projects, fs home, models) are now marked as
  such and cleared by any successful read or by an event arriving on the
  restarted stream; a pin/archive action error is left for the next action
- the sidebar Retry now reconnects the stored connection when there is no
  client, otherwise re-reads the session list and clears the stale error
- version 0.6.4+604; tests cover the stale-error clearing and rollback
This commit is contained in:
blumia committed 2026-11-27 18:37:19 +08:00
1 parent ba3c820186
commit 9ae1e9b97a
6 files changed
+177 -6

No files matched your search

+10
View File
@@ -5,6 +5,16 @@
---
## 0.6.4 Relay 错误横幅在后台恢复后不消失(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 原因 | 从后台恢复时,Relay 隧道第一次请求可能因 DNS/网络尚未就绪失败,`refreshSessions` 把「无法连接 Relay…」写进 `AppState.error`;后续会话列表或事件流成功后没有清除它(事件流只清除固定的「Connection lost, reconnecting…」文案)。侧栏的「重试」只调用 `refreshSessions`,成功也不清错误,所以看起来没有反应,尽管会话、文件和实时更新都已恢复 |
| 修复 | 区分传输错误与会话操作错误:会话列表、搜索、加载更多、归档、活动状态、权限、聊天设置、项目、文件主页、模型等任一成功请求,以及事件流恢复后的任意事件,都会清除传输错误;置顶/归档等动作错误不会被例行刷新清掉。侧栏「重试」改为 `retryConnection()`:没有客户端时重连已保存的连接,否则重新拉取会话列表并清掉过期的传输错误 |
| 版本 | **0.6.4(code 604)** |
---
## 0.6.3 文件侧栏的 gitignore 开关改用服务端值(分支 `flutter`)
| 项 | 结果 |
+1 -1
View File
@@ -6,7 +6,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity.
Status: 0.6.3 — servers (passwordless / password login, HTTP/HTTPS and
Status: 0.6.4 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
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
+1 -1
View File
@@ -131,7 +131,7 @@ class _SessionListPaneState extends State<SessionListPane> {
color: scheme.error, fontSize: 13)),
),
TextButton(
onPressed: _app.refreshSessions,
onPressed: _app.retryConnection,
child: const AppText('Retry')),
],
),
+56 -3
View File
@@ -90,6 +90,12 @@ class AppState extends ChangeNotifier {
List<Session> sessions = [];
bool sessionsLoading = false;
String? error;
/// True when [error] came from the transport (connect, session list or the
/// event stream) rather than one session action. A successful read clears
/// only this kind, so an action error is not wiped by a routine refresh.
bool _connectionError = false;
Set<String> active = {};
List<PermissionRequest> perms = [];
Map<String, String> modelNames = {};
@@ -210,6 +216,7 @@ class AppState extends ChangeNotifier {
settings['allowPromptingSubagentSessions'] == true;
showGitignored = settings['filesViewShowGitignored'] == true;
_applyToolSettings(settings);
_clearConnectionError();
notifyListeners();
} catch (_) {}
}
@@ -398,6 +405,7 @@ class AppState extends ChangeNotifier {
final message = friendlyConnectError(failure ?? tr('Pairing failed'));
debugPrint('pair: failed: $message');
error = message;
_connectionError = true;
_lastError = message;
notifyListeners();
return false;
@@ -447,6 +455,7 @@ class AppState extends ChangeNotifier {
if (busy) return;
busy = true;
error = null;
_connectionError = false;
notifyListeners();
final cl = _buildClient(c);
try {
@@ -481,6 +490,7 @@ class AppState extends ChangeNotifier {
} catch (e) {
busy = false;
error = friendlyConnectError(e);
_connectionError = true;
if (!silent) {
// Surface in the form: the UI reads error itself.
_lastError = error;
@@ -521,6 +531,31 @@ class AppState extends ChangeNotifier {
String? get lastError => _lastError;
void clearLastError() => _lastError = null;
/// Drops a transport error once a request or event proves the connection is
/// back. A session-action error (pin, archive) is left alone.
void _clearConnectionError() {
if (!_connectionError) return;
_connectionError = false;
error = null;
}
/// The sidebar banner's Retry: reconnect when the client is gone, otherwise
/// read the session list again. The successful read clears a stale
/// transport error; an action error is simply dismissed.
Future<void> retryConnection() async {
final current = conn;
if (client == null) {
if (current != null) await connect(current, silent: true);
return;
}
if (!_connectionError) {
error = null;
notifyListeners();
return;
}
await refreshSessions();
}
void _connected(Client cl, Connection c) {
client = cl;
conn = c;
@@ -546,6 +581,7 @@ class AppState extends ChangeNotifier {
refreshPerms();
refreshModels();
refreshChatSettings();
_clearConnectionError();
notifyListeners();
}
@@ -578,6 +614,7 @@ class AppState extends ChangeNotifier {
_sessionsNext = null;
perms = [];
error = null;
_connectionError = false;
notifyListeners();
}
@@ -602,9 +639,11 @@ class AppState extends ChangeNotifier {
sessions = page.data;
_sessionsNext = page.next;
sessionsLoading = false;
_clearConnectionError();
} catch (e) {
sessionsLoading = false;
error = e.toString();
_connectionError = true;
}
notifyListeners();
}
@@ -621,6 +660,7 @@ class AppState extends ChangeNotifier {
// sessions.
_sessionsNext = null;
sessionsLoading = false;
_clearConnectionError();
} catch (_) {
sessionsLoading = false;
}
@@ -682,6 +722,7 @@ class AppState extends ChangeNotifier {
project.withMeta(byPath[slashPath(project.canonical)] ??
byPath[slashPath(project.canonical).toLowerCase()]),
];
_clearConnectionError();
notifyListeners();
} catch (_) {}
}
@@ -736,8 +777,10 @@ class AppState extends ChangeNotifier {
...page.data.where((s) => !known.contains(s.id)),
];
_sessionsNext = page.next;
_clearConnectionError();
} catch (e) {
error = e.toString();
_connectionError = true;
} finally {
loadingMoreSessions = false;
notifyListeners();
@@ -753,8 +796,10 @@ class AppState extends ChangeNotifier {
final page = await cl.listSessions(archived: true, limit: 100);
archivedSessions = page.data;
archivedLoaded = true;
_clearConnectionError();
} catch (e) {
error = e.toString();
_connectionError = true;
} finally {
archivedLoading = false;
notifyListeners();
@@ -895,6 +940,7 @@ class AppState extends ChangeNotifier {
chatsRoot = info.chatsRoot.isNotEmpty ? info.chatsRoot : null;
chatRoots = roots.toList();
if (info.home.isNotEmpty) homeDirectory = info.home;
_clearConnectionError();
notifyListeners();
} catch (_) {}
}
@@ -952,6 +998,7 @@ class AppState extends ChangeNotifier {
_patchSession(session.id, (s) => s.copyWith(metadata: metadata));
} catch (e) {
error = e.toString();
_connectionError = false;
notifyListeners();
}
}
@@ -980,6 +1027,7 @@ class AppState extends ChangeNotifier {
notifyListeners();
} catch (e) {
error = e.toString();
_connectionError = false;
notifyListeners();
}
}
@@ -1127,6 +1175,7 @@ class AppState extends ChangeNotifier {
final ids = await cl.activeSessions();
if (cl != client) return false;
active = ids;
_clearConnectionError();
notifyListeners();
return true;
} catch (_) {
@@ -1139,6 +1188,7 @@ class AppState extends ChangeNotifier {
if (cl == null) return;
try {
perms = await cl.pendingPermissions(directory);
_clearConnectionError();
notifyListeners();
} catch (_) {}
}
@@ -1159,6 +1209,7 @@ class AppState extends ChangeNotifier {
modelNames = names;
modelLimits = limits;
modelList = models;
_clearConnectionError();
notifyListeners();
} catch (_) {}
try {
@@ -1194,9 +1245,10 @@ class AppState extends ChangeNotifier {
(ev) {
if (client != cl) return;
// Anything arriving means the stream is back (the server greets
// every connection with `server.connected`), so the "reconnecting"
// banner has done its job.
if (error == tr('Connection lost, reconnecting…')) error = null;
// every connection with `server.connected`), so a connection
// banner has done its job — including a relay error left over
// from a request that failed while the tunnel was reconnecting.
_clearConnectionError();
if (catchUp) {
catchUp = false;
_resyncActivity();
@@ -1215,6 +1267,7 @@ class AppState extends ChangeNotifier {
if (client != cl || gen != _streamGen) return;
afterDrop = true;
error = tr('Connection lost, reconnecting…');
_connectionError = true;
notifyListeners();
await Future.delayed(const Duration(seconds: 2));
}
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones."
publish_to: 'none'
version: 0.6.3+603
version: 0.6.4+604
environment:
sdk: ^3.14.0
+108
View File
@@ -0,0 +1,108 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/api/transport.dart';
import 'package:openchamber/state.dart';
/// A relay connection that drops the first session-list read, then works.
class _FakeTransport implements Transport {
bool failList;
bool failArchive;
_FakeTransport({this.failList = true, this.failArchive = false});
@override
Future<TransportResponse> send(TransportRequest r) async {
if (r.path == '/api/session' && failList) {
failList = false;
return _reply(503, {
'error':
'Could not connect to the relay: SocketException: Failed host lookup: relay.example'
});
}
if (r.path == '/api/session') {
return _reply(200, {
'data': [
{
'id': 'ses_1',
'title': 'Session',
'time': {'created': 1, 'updated': 2},
'location': {'directory': '/home/me/project'},
}
]
});
}
if (r.path.startsWith('/api/session/') && r.method == 'PATCH') {
if (failArchive) {
return _reply(500, {'error': 'archive failed'});
}
return _reply(200, {'data': <String, dynamic>{}});
}
return _reply(200, <String, dynamic>{});
}
TransportResponse _reply(int status, Object body) => TransportResponse(
status,
const {'content-type': 'application/json'},
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
);
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
void main() {
test('a successful session read clears a stale relay error', () async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport();
app.client = Client(Uri.parse('http://test'), transport: transport);
await app.refreshSessions();
expect(app.error, contains('relay'));
// The tunnel came back on its own; the next read succeeds.
await app.refreshSessions();
expect(app.sessions, hasLength(1));
expect(app.error, isNull);
});
test('the banner Retry reads the list again and clears the error', () async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport();
app.client = Client(Uri.parse('http://test'), transport: transport);
await app.refreshSessions();
expect(app.error, isNotNull);
await app.retryConnection();
expect(app.sessions, hasLength(1));
expect(app.error, isNull);
});
test('a session action error is not wiped by a routine refresh', () async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport(failList: false, failArchive: true);
app.client = Client(Uri.parse('http://test'), transport: transport);
await app.setArchived(Session(id: 'ses_2', title: 'Old'), true);
expect(app.error, contains('archive failed'));
await app.refreshSessions();
// The banner Retry dismisses action errors; a background refresh does not.
expect(app.error, contains('archive failed'));
});
}