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

+15
View File
@@ -739,6 +739,21 @@ class Client {
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
/// server routes the upgrade by).
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,
/// an exit notice, or an error.
class TerminalEvent {