fix: reattach the terminal after an app restart

The terminal session id lived only in memory, so the first time the panel
opened after a launch it always created another PTY. The old shell stayed on
the server (unattached shells live for half an hour) but the client could no
longer find it.

The id is now remembered per connection and directory. On first open the
panel lists /api/terminal/sessions?cwd=<dir> and attaches to the remembered
session while the server still has it, showing its replayed history. Without
that id it adopts the newest running session of the directory, and only when
the directory has nothing does it create one. An explicit "close terminal"
forgets the id and forces a fresh shell, and a fatal SESSION_NOT_FOUND clears
it and recovers, so a server restart cannot leave a dead panel.

The panel is still one terminal per project, not a tab strip.

0.4.2 (402).
This commit is contained in:
blumia committed 2026-11-22 14:53:33 +08:00
1 parent d25167de58
commit 675d19d563
9 files changed
+287 -11

No files matched your search

+14
View File
@@ -5,6 +5,20 @@
--- ---
## 0.4.2 终端恢复:重启后接回原来的 shell(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 之前 `sessionId` 只在内存里:每次启动 App 后第一次打开终端都走 `POST /api/terminal/create`,旧 shell 还留在服务器上(无连接时 30 分钟空闲回收),只是再也接不回去 |
| 恢复 | 按连接 + 目录记住最后一次的终端 id(`openchamber.terminalSessions.<connId>`)。首次打开终端先 `GET /api/terminal/sessions?cwd=`:记得的 id 还在就直接 attach(服务端 snapshot 重放历史);不在了就采用该目录最新的运行中会话;一个都没有才新建 |
| 关闭 | 「关闭终端」先 DELETE 并忘掉记录,再用 `fresh` 新建,避免又接回刚关掉的会话;断开连接/切换服务器时照旧关闭 shell |
| 失效 | attach 收到 fatal `SESSION_NOT_FOUND`(例如服务端在中间重启过)时清掉记录并自动新建,不留死面板 |
| 单终端 | 仍是每个目录一个终端视图,不是多标签;同目录的其它会话保留给网页端,不会被删除 |
| 测试 | `test/terminal_restore_test.dart`:恢复优先级(记得的 > 最新运行中 > 最新)、按连接+目录保存与清除 |
| 版本 | **0.4.2(code 402)** |
---
## 0.4.1 宠物浮在消息之上、可拖动(分支 `flutter`) ## 0.4.1 宠物浮在消息之上、可拖动(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+5 -3
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.1 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.4.2 — 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
@@ -14,7 +14,9 @@ current one checked), copy / fork / revert, attachments (photos/files, kept
after a reload), the agent's native forms, permissions. The files sidebar also after a reload), the agent's native forms, permissions. The files sidebar also
carries the project knowledge (notes, todos, plans, and agent memory when the carries the project knowledge (notes, todos, plans, and agent memory when the
server enables it) and a full terminal with a Termux-style key bar; downloads server enables it) and a full terminal with a Termux-style key bar; downloads
show their progress and can be cancelled. The panel is a tab row with its own show their progress and can be cancelled. The terminal remembers its session
per connection and directory, so reopening it after an app restart attaches to
the shell the server still holds instead of starting another. The panel is a tab row with its own
close button, and each tab has its own header row. Starting a session opens a close button, and each tab has its own header row. Starting a session opens a
draft that only creates the session on the first send; the session list is draft that only creates the session on the first send; the session list is
grouped by project with date captions, pins, archive and swipe actions. The grouped by project with date captions, pins, archive and swipe actions. The
@@ -47,7 +49,7 @@ target used for local testing.
| `lib/appearance_prefs.dart` | Device-local theme mode and seed colour (`shared_preferences`) | | `lib/appearance_prefs.dart` | Device-local theme mode and seed colour (`shared_preferences`) |
| `lib/pets/` | Imported pet packs: the dsh-Go `pack.json` sprite format, unpacked into the app's documents, plus the one-sheet image cache | | `lib/pets/` | Imported pet packs: the dsh-Go `pack.json` sprite format, unpacked into the app's documents, plus the one-sheet image cache |
| `lib/widgets/pet_sprite.dart` | The pet strip above the composer and its sprite player (frames, moods, tap reactions) | | `lib/widgets/pet_sprite.dart` | The pet strip above the composer and its sprite player (frames, moods, tap reactions) |
| `lib/terminal_state.dart` | The terminal session: an xterm model plus the `/api/terminal/ws` socket (binary control frames), kept per workspace so closing the panel keeps the shell | | `lib/terminal_state.dart` | The terminal session: an xterm model plus the `/api/terminal/ws` socket (binary control frames), kept per workspace so closing the panel keeps the shell; the remembered session id lets a restart reattach |
| `lib/screens/` | Servers, the connected shell (`home_screen.dart`: drawer on a phone, two columns from 840 px), sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets, the native form dock, the files sidebar with the knowledge and terminal tabs); the message list is reversed so older pages grow above without moving the viewport | | `lib/screens/` | Servers, the connected shell (`home_screen.dart`: drawer on a phone, two columns from 840 px), sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets, the native form dock, the files sidebar with the knowledge and terminal tabs); the message list is reversed so older pages grow above without moving the viewport |
| `lib/widgets/` | The context usage ring | | `lib/widgets/` | The context usage ring |
+15
View File
@@ -739,6 +739,21 @@ class Client {
directory: directory); directory: directory);
} }
/// The terminals the server still holds for [cwd] (or all of them when it is
/// empty). The server keeps an unattached shell for half an hour, so a
/// client that remembers its session id can reattach after a restart.
Future<List<ServerTerminal>> listTerminals({String? cwd}) async {
final r = await _json('GET', '/api/terminal/sessions',
query: {if (cwd != null && cwd.isNotEmpty) 'cwd': cwd},
directory: cwd);
final raw = r['sessions'];
if (raw is! List) return const [];
return [
for (final entry in raw)
if (entry is Map<String, dynamic>) ServerTerminal.fromJson(entry),
];
}
/// The headers the terminal socket needs (auth, and the workspace the /// The headers the terminal socket needs (auth, and the workspace the
/// server routes the upgrade by). /// server routes the upgrade by).
Map<String, String> get eventHeaders => { Map<String, String> get eventHeaders => {
+24
View File
@@ -30,6 +30,30 @@ class TerminalSessionInfo {
); );
} }
/// A terminal the server still holds, from `GET /api/terminal/sessions`.
/// The id outlives this app process, so a restart can attach to the same
/// shell instead of making another one.
class ServerTerminal {
final String sessionId;
final String cwd;
final String status; // running | exited
final int? createdAt;
const ServerTerminal({
required this.sessionId,
this.cwd = '',
this.status = 'running',
this.createdAt,
});
factory ServerTerminal.fromJson(Map<String, dynamic> j) => ServerTerminal(
sessionId: j['sessionId'] as String? ?? '',
cwd: j['cwd'] as String? ?? '',
status: j['status'] as String? ?? 'running',
createdAt: (j['createdAt'] as num?)?.toInt(),
);
}
/// One frame from the server: a snapshot (the authoritative screen), output, /// One frame from the server: a snapshot (the authoritative screen), output,
/// an exit notice, or an error. /// an exit notice, or an error.
class TerminalEvent { class TerminalEvent {
+4 -2
View File
@@ -173,7 +173,7 @@ class _TerminalPanelState extends State<TerminalPanel> {
_t.link == TerminalLinkState.error) { _t.link == TerminalLinkState.error) {
// A dead session cannot restart in place; a fresh one replaces it. // A dead session cannot restart in place; a fresh one replaces it.
await _t.closeSession(); await _t.closeSession();
await _t.ensureOpen(); await _t.ensureOpen(fresh: true);
return; return;
} }
await _t.restart(); await _t.restart();
@@ -181,7 +181,9 @@ class _TerminalPanelState extends State<TerminalPanel> {
Future<void> _closeSession() async { Future<void> _closeSession() async {
await _t.closeSession(); await _t.closeSession();
if (mounted) await _t.ensureOpen(); // An explicit close must not adopt one of the server's other sessions for
// this directory (or the old one, if the DELETE lagged): start a new shell.
if (mounted) await _t.ensureOpen(fresh: true);
} }
// ------------------------------------------------------------- key bar // ------------------------------------------------------------- key bar
+54
View File
@@ -67,6 +67,7 @@ class Connection {
class Storage { class Storage {
static const _connsKey = 'openchamber.connections'; static const _connsKey = 'openchamber.connections';
static const _installKey = 'openchamber.installId'; static const _installKey = 'openchamber.installId';
static const _terminalPrefix = 'openchamber.terminalSessions.';
// v11 encrypts with AES-GCM and an Android Keystore-wrapped key by default. // v11 encrypts with AES-GCM and an Android Keystore-wrapped key by default.
final _secure = const FlutterSecureStorage(); final _secure = const FlutterSecureStorage();
@@ -92,6 +93,59 @@ class Storage {
await prefs.setString(_connsKey, jsonEncode(sorted.map((e) => e.toJson()).toList())); await prefs.setString(_connsKey, jsonEncode(sorted.map((e) => e.toJson()).toList()));
} }
// ------------------------------------------------------------- terminals
// The last terminal session per directory, so reopening the terminal after
// an app restart can reattach to the shell the server still holds instead of
// starting another one. Ids are meaningless across servers, hence one map
// per connection.
static String _terminalKey(String connectionId) =>
'$_terminalPrefix$connectionId';
Future<Map<String, String>> _terminalSessions(String connectionId) async {
if (connectionId.isEmpty) return {};
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString(_terminalKey(connectionId));
if (raw == null || raw.isEmpty) return {};
try {
final decoded = jsonDecode(raw);
if (decoded is! Map) return {};
return {
for (final entry in decoded.entries)
if (entry.key is String && entry.value is String)
entry.key as String: entry.value as String,
};
} catch (_) {
return {};
}
}
Future<String?> terminalSession(String connectionId, String directory) async =>
(await _terminalSessions(connectionId))[directory];
Future<void> saveTerminalSession(
String connectionId, String directory, String sessionId) async {
if (connectionId.isEmpty || directory.isEmpty || sessionId.isEmpty) return;
final prefs = await SharedPreferences.getInstance();
final map = await _terminalSessions(connectionId);
map[directory] = sessionId;
await prefs.setString(_terminalKey(connectionId), jsonEncode(map));
}
Future<void> clearTerminalSession(
String connectionId, String directory) async {
if (connectionId.isEmpty) return;
final prefs = await SharedPreferences.getInstance();
final map = await _terminalSessions(connectionId);
if (map.remove(directory) == null) return;
if (map.isEmpty) {
await prefs.remove(_terminalKey(connectionId));
} else {
await prefs.setString(_terminalKey(connectionId), jsonEncode(map));
}
}
Future<String> installId() async { Future<String> installId() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
var id = prefs.getString(_installKey); var id = prefs.getString(_installKey);
+102 -5
View File
@@ -32,6 +32,7 @@ class TerminalSessionState extends ChangeNotifier {
Timer? _resizeTimer; Timer? _resizeTimer;
bool _opened = false; bool _opened = false;
bool _disposed = false; bool _disposed = false;
bool _recovering = false;
TerminalSessionState(this.app, this.directory) { TerminalSessionState(this.app, this.directory) {
model.onOutput = _onOutput; model.onOutput = _onOutput;
@@ -92,18 +93,65 @@ class TerminalSessionState extends ChangeNotifier {
bool get isRunning => bool get isRunning =>
link == TerminalLinkState.open || link == TerminalLinkState.connecting; link == TerminalLinkState.open || link == TerminalLinkState.connecting;
/// Creates the session and attaches on first use; later calls just make sure /// Opens the terminal on first use; later calls just make sure the socket is
/// the socket is alive. /// alive. Unless [fresh] is set, the previous session for this directory is
Future<void> ensureOpen() async { /// picked up again when the server still holds it (the app may have been
/// restarted since), so the same shell — and its history — comes back.
Future<void> ensureOpen({bool fresh = false}) async {
if (_disposed) return; if (_disposed) return;
if (_opened) { if (_opened) {
if (_socket == null && link != TerminalLinkState.exited) await _attach(); if (_socket == null && link != TerminalLinkState.exited) await _attach();
return; return;
} }
_opened = true; _opened = true;
await _open(fresh: fresh);
}
Future<void> _open({required bool fresh}) async {
final client = app.client;
if (client == null) return;
_set(TerminalLinkState.creating);
if (!fresh && await _restore()) return;
await _create(); await _create();
} }
/// The session this panel should reattach to: the one remembered for the
/// directory while the server still lists it, else the newest running one,
/// else the newest one. Null means the server holds nothing for this
/// directory and a session has to be created.
static String? restoreCandidate(
String? saved, List<ServerTerminal> sessions) {
if (sessions.isEmpty) return null;
if (saved != null && sessions.any((s) => s.sessionId == saved)) {
return saved;
}
final running = sessions.where((s) => s.status == 'running').toList();
final pool = running.isNotEmpty ? running : sessions;
pool.sort((a, b) => (b.createdAt ?? 0).compareTo(a.createdAt ?? 0));
final id = pool.first.sessionId;
return id.isEmpty ? null : id;
}
Future<bool> _restore() async {
final client = app.client;
if (client == null) return false;
final saved = await _savedId();
final List<ServerTerminal> sessions;
try {
sessions = await client.listTerminals(cwd: directory);
} catch (_) {
// Let the create path report the failure; a listing error here should
// not be what the status bar shows.
return false;
}
final id = restoreCandidate(saved, sessions);
if (_disposed || id == null) return false;
sessionId = id;
await _remember(id);
await _attach();
return true;
}
Future<void> _create() async { Future<void> _create() async {
final client = app.client; final client = app.client;
if (client == null) return; if (client == null) return;
@@ -115,12 +163,35 @@ class TerminalSessionState extends ChangeNotifier {
sessionId = info.sessionId; sessionId = info.sessionId;
_cols = info.cols; _cols = info.cols;
_rows = info.rows; _rows = info.rows;
await _remember(info.sessionId);
await _attach(); await _attach();
} catch (error) { } catch (error) {
_set(TerminalLinkState.error, detail: _message(error)); _set(TerminalLinkState.error, detail: _message(error));
} }
} }
/// The connection a saved terminal id belongs to. A different saved server
/// has its own ids, and adopting one across servers would point at nothing.
String get _connectionId => app.conn?.id ?? '';
Future<String?> _savedId() async {
final id = _connectionId;
if (id.isEmpty) return null;
return app.storage.terminalSession(id, directory);
}
Future<void> _remember(String id) async {
final connection = _connectionId;
if (connection.isEmpty) return;
await app.storage.saveTerminalSession(connection, directory, id);
}
Future<void> _forget() async {
final connection = _connectionId;
if (connection.isEmpty) return;
await app.storage.clearTerminalSession(connection, directory);
}
Future<void> _attach() async { Future<void> _attach() async {
final client = app.client; final client = app.client;
final id = sessionId; final id = sessionId;
@@ -171,8 +242,15 @@ class TerminalSessionState extends ChangeNotifier {
break; break;
case 'error': case 'error':
if (event.fatal) { if (event.fatal) {
_set(TerminalLinkState.error, if (event.code == 'SESSION_NOT_FOUND') {
detail: event.message ?? event.code ?? '终端连接失败'); // The remembered id outlived the server's session (a server
// restart, or the idle reaper won a race with the attach): open a
// new shell instead of leaving a dead panel.
_recoverMissing();
} else {
_set(TerminalLinkState.error,
detail: event.message ?? event.code ?? '终端连接失败');
}
} }
break; break;
} }
@@ -236,6 +314,7 @@ class TerminalSessionState extends ChangeNotifier {
_opened = false; _opened = false;
link = TerminalLinkState.idle; link = TerminalLinkState.idle;
detail = null; detail = null;
await _forget();
await _socket?.dispose(); await _socket?.dispose();
_socket = null; _socket = null;
if (!_disposed) notifyListeners(); if (!_disposed) notifyListeners();
@@ -246,6 +325,24 @@ class TerminalSessionState extends ChangeNotifier {
} }
} }
/// Drops a session the server no longer has and opens another one in its
/// place, so a stale remembered id does not leave the panel unusable.
Future<void> _recoverMissing() async {
if (_recovering || _disposed) return;
_recovering = true;
try {
sessionId = null;
await _forget();
await _socket?.dispose();
_socket = null;
if (_disposed) return;
_opened = true;
await _create();
} finally {
_recovering = false;
}
}
@override @override
void dispose() { void dispose() {
_disposed = true; _disposed = true;
+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.1+401 version: 0.4.2+402
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
+68
View File
@@ -0,0 +1,68 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/terminal.dart';
import 'package:openchamber/storage.dart';
import 'package:openchamber/terminal_state.dart';
import 'package:shared_preferences/shared_preferences.dart';
ServerTerminal _term(String id,
{String status = 'running', int createdAt = 0, String cwd = '/repo'}) =>
ServerTerminal(
sessionId: id, cwd: cwd, status: status, createdAt: createdAt);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('restoreCandidate', () {
test('nothing on the server means a new session', () {
expect(TerminalSessionState.restoreCandidate('saved', const []), isNull);
});
test('the remembered session wins while the server still has it', () {
final chosen = TerminalSessionState.restoreCandidate('saved', [
_term('saved', createdAt: 1),
_term('newer', createdAt: 99),
]);
expect(chosen, 'saved');
});
test('without the remembered one, the newest running session is adopted',
() {
final chosen = TerminalSessionState.restoreCandidate('gone', [
_term('older', createdAt: 10),
_term('newer', createdAt: 30),
_term('exited-newest', status: 'exited', createdAt: 90),
]);
expect(chosen, 'newer');
});
test('when nothing runs, the newest session is shown so it can restart',
() {
final chosen = TerminalSessionState.restoreCandidate(null, [
_term('old-exit', status: 'exited', createdAt: 10),
_term('new-exit', status: 'exited', createdAt: 20),
]);
expect(chosen, 'new-exit');
});
});
test('remembered terminal ids are kept per connection and directory',
() async {
SharedPreferences.setMockInitialValues({});
final storage = Storage();
expect(await storage.terminalSession('srv_a', '/repo'), isNull);
await storage.saveTerminalSession('srv_a', '/repo', 'term-1');
await storage.saveTerminalSession('srv_a', '/other', 'term-2');
await storage.saveTerminalSession('srv_b', '/repo', 'term-3');
expect(await storage.terminalSession('srv_a', '/repo'), 'term-1');
expect(await storage.terminalSession('srv_a', '/other'), 'term-2');
expect(await storage.terminalSession('srv_b', '/repo'), 'term-3');
await storage.clearTerminalSession('srv_a', '/repo');
expect(await storage.terminalSession('srv_a', '/repo'), isNull);
expect(await storage.terminalSession('srv_a', '/other'), 'term-2');
expect(await storage.terminalSession('srv_b', '/repo'), 'term-3');
});
}