feat: several terminal tabs per project, with a dropdown

A directory now has a TerminalWorkspace holding a list of tabs instead of a
single session. The status bar's left side became a dropdown: it shows the
active tab and its state ("终端 2 · 运行中") and lists the other tabs (the
active one checked) plus "新建终端". New tabs take the smallest free number,
so closing one frees its name.

Only the active tab keeps a socket: switching detaches the old tab and
attaches the new one, whose screen is replayed from the server snapshot; the
shell itself keeps running. The tab's model stays in memory, so switching
back is immediate.

The tab list (ids, labels, active one) is saved per connection and directory.
On the first open the server's sessions for the directory are reconciled with
it: saved labels and order are kept for sessions that still exist, sessions
opened elsewhere (web UI) are appended in creation order, and tabs whose
session is gone are dropped. Project-action command runners are not shown as
tabs. The 0.4.2 single-session value is read as one tab.

0.4.3 (403).
This commit is contained in:
blumia committed 2026-11-22 15:23:21 +08:00
1 parent 675d19d563
commit a7bc380ac0
9 files changed
+717 -298

No files matched your search

+14
View File
@@ -5,6 +5,20 @@
---
## 0.4.3 终端多标签:下拉切换、新建、按标签恢复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 多标签 | 每个目录一个 `TerminalWorkspace`,持有多个 `TerminalTab`(各自的 xterm 模型与 socket)。切换标签时旧标签 detach、新标签 attach,不同时占用多条 WebSocket;后台输出由服务端 snapshot 在切回时重放 |
| 下拉 | 状态条左侧变成标签下拉:显示「终端 N · 运行中」,菜单列出所有标签(当前项打勾)与「新建终端」。新建的标签自动用最小的空闲编号(终端 1、终端 2…) |
| 关闭/重启 | ⋮ 菜单改为「关闭此终端」,关掉当前标签并 DELETE;关掉最后一个会自动留一个新标签。重启只作用于当前标签,死会话在原标签内换成新会话 |
| 恢复 | 本机按连接 + 目录保存标签列表(id + 名称 + 活动标签)。启动后首次打开:`GET /api/terminal/sessions?cwd=` 与服务端对账,仍存在的会话按保存的顺序和名称还原,服务端新出现的会话(网页端开的)按创建时间追加成标签,服务端已没有的标签丢弃;一个都没有才新建。兼容 0.4.2 的单会话存档 |
| 过滤 | 只把 interactive 会话算作标签,project-action 的命令运行器不显示 |
| 测试 | `test/terminal_restore_test.dart`:标签对账(顺序、名称、丢弃、列表失败的兜底、过滤 action)、编号复用、按连接+目录保存标签与活动项、0.4.2 存档迁移 |
| 版本 | **0.4.3(code 403)** |
---
## 0.4.2 终端恢复:重启后接回原来的 shell(分支 `flutter`)
| 项 | 结果 |
+6 -5
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
Flutter to compare mobile UI maturity.
Status: 0.4.2 — servers (passwordless / password login, HTTP/HTTPS and
Status: 0.4.3 — servers (passwordless / password login, HTTP/HTTPS and
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
grouped per turn (icon, one-line summary, foldable run) with image previews, a
@@ -14,9 +14,10 @@ current one checked), copy / fork / revert, attachments (photos/files, kept
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
server enables it) and a full terminal with a Termux-style key bar; downloads
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
show their progress and can be cancelled. The terminal holds several tabs per
project, switched from a dropdown next to the status (new tab included), and
remembers them per connection and directory: reopening after an app restart
attaches to the shells the server still holds instead of starting new ones. The panel is a tab row with its own
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
grouped by project with date captions, pins, archive and swipe actions. The
@@ -49,7 +50,7 @@ target used for local testing.
| `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/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; the remembered session id lets a restart reattach |
| `lib/terminal_state.dart` | Terminal workspaces and tabs: each tab is an xterm model plus its `/api/terminal/ws` socket; switching detaches the old tab, the saved tab list 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/widgets/` | The context usage ring |
+21 -6
View File
@@ -38,20 +38,35 @@ class ServerTerminal {
final String cwd;
final String status; // running | exited
final int? createdAt;
final String mode; // interactive | command
final String purpose; // terminal | project-action (or empty)
const ServerTerminal({
required this.sessionId,
this.cwd = '',
this.status = 'running',
this.createdAt,
this.mode = 'interactive',
this.purpose = '',
});
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(),
);
/// A terminal a person opened. A project action's command runner is also a
/// PTY, but it is not one of the user's tabs.
bool get interactive => mode != 'command' && purpose != 'project-action';
factory ServerTerminal.fromJson(Map<String, dynamic> j) {
final purposeJson = j['purpose'];
return ServerTerminal(
sessionId: j['sessionId'] as String? ?? '',
cwd: j['cwd'] as String? ?? '',
status: j['status'] as String? ?? 'running',
createdAt: (j['createdAt'] as num?)?.toInt(),
mode: j['mode'] as String? ?? 'interactive',
purpose: purposeJson is Map
? purposeJson['type'] as String? ?? ''
: '',
);
}
}
/// One frame from the server: a snapshot (the authoritative screen), output,
+204 -119
View File
@@ -1,6 +1,7 @@
// The terminal tab: xterm renders the PTY, a status bar offers restart and
// close, and the key bar below sends what a phone keyboard cannot (Esc, Tab,
// Ctrl, arrows, punctuation), the way Termux does.
// The terminal tab: xterm renders the PTY, a status bar offers the tab
// dropdown (switch / new), restart and close, and the key bar below sends what
// a phone keyboard cannot (Esc, Tab, Ctrl, arrows, punctuation), the way
// Termux does.
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart';
@@ -46,14 +47,17 @@ class TerminalPanel extends StatefulWidget {
}
class _TerminalPanelState extends State<TerminalPanel> {
TerminalSessionState? _terminal;
late final TerminalWorkspace _workspace;
final FocusNode _focus = FocusNode();
/// The dropdown's value for "new terminal"; tab values are their index.
static const _newTab = -1;
@override
void initState() {
super.initState();
_terminal = widget.app.terminalFor(widget.directory);
_terminal!.ensureOpen();
_workspace = widget.app.terminalFor(widget.directory);
_workspace.ensureOpen();
}
@override
@@ -62,135 +66,208 @@ class _TerminalPanelState extends State<TerminalPanel> {
super.dispose();
}
TerminalSessionState get _t => _terminal!;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return ListenableBuilder(
listenable: _t,
listenable: _workspace,
builder: (context, _) {
return Column(
children: [
_statusBar(theme),
Expanded(
child: ColoredBox(
color: theme.brightness == Brightness.dark
? const Color(0xFF1E1E1E)
: Colors.white,
child: TerminalView(
_t.model,
focusNode: _focus,
theme: theme.brightness == Brightness.dark
? TerminalThemes.defaultTheme
: _lightTheme,
textStyle: const TerminalStyle(
fontSize: 13,
height: 1.25,
fontFamily: 'monospace',
final tab = _workspace.activeTab;
if (tab == null) return const SizedBox.shrink();
final state = tab.state;
return ListenableBuilder(
listenable: state,
builder: (context, _) {
return Column(
children: [
_statusBar(theme, tab, state),
Expanded(
child: ColoredBox(
color: theme.brightness == Brightness.dark
? const Color(0xFF1E1E1E)
: Colors.white,
child: TerminalView(
// A fresh view per tab, so scroll position and selection
// do not leak from the one before it.
key: ObjectKey(state),
state.model,
focusNode: _focus,
theme: theme.brightness == Brightness.dark
? TerminalThemes.defaultTheme
: _lightTheme,
textStyle: const TerminalStyle(
fontSize: 13,
height: 1.25,
fontFamily: 'monospace',
),
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
keyboardType: TextInputType.text,
deleteDetection: true,
backgroundOpacity: 1,
),
),
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
keyboardType: TextInputType.text,
deleteDetection: true,
backgroundOpacity: 1,
),
),
),
_keyBar(theme),
],
_keyBar(theme, state),
],
);
},
);
},
);
}
Widget _statusBar(ThemeData theme) {
Widget _statusBar(
ThemeData theme, TerminalTab tab, TerminalSessionState state) {
final scheme = theme.colorScheme;
final (label, color) = switch (_t.link) {
final (label, color) = switch (state.link) {
TerminalLinkState.idle => ('未启动', theme.hintColor),
TerminalLinkState.creating => ('正在创建…', theme.hintColor),
TerminalLinkState.connecting => ('正在连接…', theme.hintColor),
TerminalLinkState.reconnecting => ('连接中断,正在重连…', scheme.error),
TerminalLinkState.open => ('运行中', scheme.primary),
TerminalLinkState.exited => (_t.detail ?? '已退出', theme.hintColor),
TerminalLinkState.error => (_t.detail ?? '连接失败', scheme.error),
TerminalLinkState.exited => (state.detail ?? '已退出', theme.hintColor),
TerminalLinkState.error => (state.detail ?? '连接失败', scheme.error),
};
return Container(
padding: const EdgeInsets.fromLTRB(12, 2, 4, 2),
child: Row(
children: [
Icon(Icons.circle, size: 8, color: color),
const SizedBox(width: 6),
Expanded(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: color),
return Row(
children: [
Expanded(
child: PopupMenuButton<int>(
tooltip: '切换终端',
position: PopupMenuPosition.under,
onSelected: _onTabMenu,
itemBuilder: (_) => [
for (var i = 0; i < _workspace.tabs.length; i++)
PopupMenuItem<int>(
value: i,
child: Row(
children: [
Icon(
i == _workspace.activeIndex
? Icons.check
: Icons.terminal_outlined,
size: 18,
color: i == _workspace.activeIndex
? scheme.primary
: theme.hintColor,
),
const SizedBox(width: 10),
Expanded(
child: Text(
_workspace.tabs[i].label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
const PopupMenuDivider(),
const PopupMenuItem<int>(
value: _newTab,
child: Row(
children: [
Icon(Icons.add, size: 18),
SizedBox(width: 10),
Text('新建终端'),
],
),
),
],
child: Container(
height: 40,
padding: const EdgeInsets.fromLTRB(12, 2, 4, 2),
child: Row(
children: [
Icon(Icons.circle, size: 8, color: color),
const SizedBox(width: 6),
Flexible(
child: Text(
tab.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.5, fontWeight: FontWeight.w600),
),
),
const SizedBox(width: 4),
Flexible(
child: Text(
'· $label',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: color),
),
),
Icon(Icons.arrow_drop_down, size: 20, color: theme.hintColor),
],
),
),
),
IconButton(
tooltip: '键盘',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.keyboard_outlined, size: 18),
onPressed: () => _focus.requestFocus(),
),
IconButton(
tooltip: '重新启动',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.restart_alt, size: 18),
onPressed: _t.link == TerminalLinkState.exited ||
_t.link == TerminalLinkState.error
? _restart
: _t.isRunning
? _restart
: null,
),
PopupMenuButton<String>(
tooltip: '更多',
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) {
switch (value) {
case 'clear':
_t.model.write('\x1b[2J\x1b[H');
break;
case 'close':
_closeSession();
break;
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'clear', child: Text('清屏')),
PopupMenuItem(value: 'close', child: Text('关闭终端')),
],
),
],
),
),
IconButton(
tooltip: '键盘',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.keyboard_outlined, size: 18),
onPressed: () => _focus.requestFocus(),
),
IconButton(
tooltip: '重新启动',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.restart_alt, size: 18),
onPressed: state.link == TerminalLinkState.exited ||
state.link == TerminalLinkState.error ||
state.isRunning
? _restart
: null,
),
PopupMenuButton<String>(
tooltip: '更多',
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) {
switch (value) {
case 'clear':
state.model.write('\x1b[2J\x1b[H');
break;
case 'close':
_workspace.closeActive();
break;
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'clear', child: Text('清屏')),
PopupMenuItem(value: 'close', child: Text('关闭此终端')),
],
),
],
);
}
Future<void> _restart() async {
if (_t.link == TerminalLinkState.exited ||
_t.link == TerminalLinkState.error) {
// A dead session cannot restart in place; a fresh one replaces it.
await _t.closeSession();
await _t.ensureOpen(fresh: true);
return;
void _onTabMenu(int value) {
if (value == _newTab) {
_workspace.addTab();
} else {
_workspace.select(value);
}
await _t.restart();
}
Future<void> _closeSession() async {
await _t.closeSession();
// 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);
Future<void> _restart() async {
final state = _workspace.activeTab?.state;
if (state == null) return;
if (state.link == TerminalLinkState.error) {
// A dead session cannot restart in place; a fresh shell replaces it
// inside the same tab.
await state.closeSession();
await state.ensureOpen();
return;
}
await state.restart();
}
// ------------------------------------------------------------- key bar
/// Two rows of seven, the way Termux lays them out: the keys a phone
/// keyboard cannot produce, all reachable with a thumb.
Widget _keyBar(ThemeData theme) {
Widget _keyBar(ThemeData theme, TerminalSessionState state) {
return Container(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
@@ -201,22 +278,29 @@ class _TerminalPanelState extends State<TerminalPanel> {
mainAxisSize: MainAxisSize.min,
children: [
_keyRow([
_key('ESC', onTap: () => _sendKey(TerminalKey.escape)),
_key('/', onTap: () => _sendText('/')),
_key('—', onTap: () => _sendText('-')),
_key('HOME', onTap: () => _sendKey(TerminalKey.home)),
_key('↑', big: true, onTap: () => _sendKey(TerminalKey.arrowUp)),
_key('END', onTap: () => _sendKey(TerminalKey.end)),
_key('PGUP', onTap: () => _sendKey(TerminalKey.pageUp)),
_key('ESC', onTap: () => _sendKey(state, TerminalKey.escape)),
_key('/', onTap: () => _sendText(state, '/')),
_key('—', onTap: () => _sendText(state, '-')),
_key('HOME', onTap: () => _sendKey(state, TerminalKey.home)),
_key('↑',
big: true, onTap: () => _sendKey(state, TerminalKey.arrowUp)),
_key('END', onTap: () => _sendKey(state, TerminalKey.end)),
_key('PGUP', onTap: () => _sendKey(state, TerminalKey.pageUp)),
]),
_keyRow([
_key('TAB', onTap: () => _sendKey(TerminalKey.tab)),
_key('CTRL', active: _t.ctrl, onTap: _t.toggleCtrl),
_key('ALT', active: _t.alt, onTap: _t.toggleAlt),
_key('←', big: true, onTap: () => _sendKey(TerminalKey.arrowLeft)),
_key('↓', big: true, onTap: () => _sendKey(TerminalKey.arrowDown)),
_key('→', big: true, onTap: () => _sendKey(TerminalKey.arrowRight)),
_key('PGDN', onTap: () => _sendKey(TerminalKey.pageDown)),
_key('TAB', onTap: () => _sendKey(state, TerminalKey.tab)),
_key('CTRL', active: state.ctrl, onTap: state.toggleCtrl),
_key('ALT', active: state.alt, onTap: state.toggleAlt),
_key('←',
big: true,
onTap: () => _sendKey(state, TerminalKey.arrowLeft)),
_key('↓',
big: true,
onTap: () => _sendKey(state, TerminalKey.arrowDown)),
_key('→',
big: true,
onTap: () => _sendKey(state, TerminalKey.arrowRight)),
_key('PGDN', onTap: () => _sendKey(state, TerminalKey.pageDown)),
]),
],
),
@@ -264,8 +348,9 @@ class _TerminalPanelState extends State<TerminalPanel> {
);
}
void _sendKey(TerminalKey key) =>
_t.model.keyInput(key, ctrl: _t.ctrl, alt: _t.alt, shift: _t.shift);
void _sendKey(TerminalSessionState state, TerminalKey key) => state.model
.keyInput(key, ctrl: state.ctrl, alt: state.alt, shift: state.shift);
void _sendText(String text) => _t.model.textInput(text);
void _sendText(TerminalSessionState state, String text) =>
state.model.textInput(text);
}
+11 -11
View File
@@ -120,12 +120,12 @@ class AppState extends ChangeNotifier {
String? _sessionsNext;
bool loadingMoreSessions = false;
/// Terminals by workspace directory: switching sessions or tabs keeps the
/// shell alive, and each directory gets its own.
final Map<String, TerminalSessionState> terminals = {};
/// Terminal workspaces by directory: each holds that directory's tabs and
/// keeps their shells alive while sessions/tabs are switched.
final Map<String, TerminalWorkspace> terminals = {};
TerminalSessionState terminalFor(String directory) => terminals.putIfAbsent(
directory, () => TerminalSessionState(this, directory));
TerminalWorkspace terminalFor(String directory) => terminals.putIfAbsent(
directory, () => TerminalWorkspace(this, directory));
/// Public way to signal UI changes (notifyListeners is protected).
void touch() => notifyListeners();
@@ -297,11 +297,11 @@ class AppState extends ChangeNotifier {
}
Future<void> disconnect() async {
for (final terminal in terminals.values) {
// Closing the shell on the server is right when the connection itself
for (final workspace in terminals.values) {
// Closing the shells on the server is right when the connection itself
// goes away; a panel close only detaches.
await terminal.closeSession();
terminal.dispose();
await workspace.closeAll();
workspace.dispose();
}
terminals.clear();
client?.close();
@@ -759,8 +759,8 @@ class AppState extends ChangeNotifier {
await chat!.reloadTail();
await chat!.reloadInbox();
}
for (final terminal in terminals.values) {
await terminal.reconnectIfNeeded();
for (final workspace in terminals.values) {
await workspace.reconnectIfNeeded();
}
}
+60 -23
View File
@@ -64,6 +64,21 @@ class Connection {
);
}
/// One remembered terminal tab: the server's session id and the local label.
class SavedTerminalTab {
final String id;
final String label;
const SavedTerminalTab(this.id, this.label);
}
/// The terminal tabs remembered for one directory, with the tab that was
/// showing.
class SavedTerminalTabs {
final List<SavedTerminalTab> tabs;
final String? activeId;
const SavedTerminalTabs(this.tabs, this.activeId);
}
class Storage {
static const _connsKey = 'openchamber.connections';
static const _installKey = 'openchamber.installId';
@@ -95,49 +110,71 @@ class Storage {
// ------------------------------------------------------------- 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.
// The terminal tabs per directory, so reopening the terminal after an app
// restart can reattach to the shells the server still holds instead of
// starting new ones. 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 {
Future<Map<String, dynamic>> _terminalMap(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 {};
}
if (decoded is Map) return Map<String, dynamic>.from(decoded);
} catch (_) {}
return {};
}
Future<String?> terminalSession(String connectionId, String directory) async =>
(await _terminalSessions(connectionId))[directory];
/// The tabs saved for [directory], or null when there are none. A value
/// written by 0.4.2 (a bare session id) is read as a single tab.
Future<SavedTerminalTabs?> terminalTabs(
String connectionId, String directory) async {
final entry = (await _terminalMap(connectionId))[directory];
if (entry is String && entry.isNotEmpty) {
return SavedTerminalTabs(
[SavedTerminalTab(entry, '终端 1')], entry);
}
if (entry is! Map) return null;
final rawTabs = entry['tabs'];
if (rawTabs is! List) return null;
final tabs = <SavedTerminalTab>[];
for (final raw in rawTabs) {
if (raw is! Map) continue;
final id = raw['id'];
final label = raw['label'];
if (id is! String || id.isEmpty) continue;
tabs.add(SavedTerminalTab(
id, label is String && label.trim().isNotEmpty ? label : '终端'));
}
if (tabs.isEmpty) return null;
final active = entry['active'];
return SavedTerminalTabs(tabs, active is String ? active : null);
}
Future<void> saveTerminalSession(
String connectionId, String directory, String sessionId) async {
if (connectionId.isEmpty || directory.isEmpty || sessionId.isEmpty) return;
Future<void> saveTerminalTabs(
String connectionId, String directory, SavedTerminalTabs value) async {
if (connectionId.isEmpty || directory.isEmpty) return;
final prefs = await SharedPreferences.getInstance();
final map = await _terminalSessions(connectionId);
map[directory] = sessionId;
final map = await _terminalMap(connectionId);
map[directory] = {
'tabs': [
for (final tab in value.tabs) {'id': tab.id, 'label': tab.label},
],
if (value.activeId != null) 'active': value.activeId,
};
await prefs.setString(_terminalKey(connectionId), jsonEncode(map));
}
Future<void> clearTerminalSession(
Future<void> clearTerminalTabs(
String connectionId, String directory) async {
if (connectionId.isEmpty) return;
final prefs = await SharedPreferences.getInstance();
final map = await _terminalSessions(connectionId);
final map = await _terminalMap(connectionId);
if (map.remove(directory) == null) return;
if (map.isEmpty) {
await prefs.remove(_terminalKey(connectionId));
+303 -94
View File
@@ -1,6 +1,7 @@
// The live terminal: the xterm model the view renders, and the socket that
// carries its bytes. Kept on AppState so closing the panel (or switching
// tabs) does not end the shell; reattaching replays the server's snapshot.
// carries its bytes. A directory can hold several tabs; the workspace keeps
// them and owns which one is attached, so closing the panel (or switching
// tabs) does not end the shells — reattaching replays the server's snapshot.
import 'dart:async';
import 'package:flutter/foundation.dart';
@@ -8,11 +9,280 @@ import 'package:xterm/xterm.dart';
import 'api/terminal.dart';
import 'state.dart';
import 'storage.dart';
/// One terminal tab. [state] holds the model and the socket; the label is the
/// local name ("终端 1") the dropdown shows.
class TerminalTab {
final TerminalSessionState state;
String label;
TerminalTab(this.state, this.label);
}
/// A tab before its state exists: [id] is the server session when the tab is
/// restored, null when it is about to be created.
class TerminalTabPlan {
final String? id;
final String label;
const TerminalTabPlan({this.id, required this.label});
}
/// Every terminal tab of one working directory, and which one is showing.
class TerminalWorkspace extends ChangeNotifier {
final AppState app;
final String directory;
final List<TerminalTab> tabs = [];
int activeIndex = 0;
bool _loaded = false;
bool _disposed = false;
TerminalWorkspace(this.app, this.directory);
TerminalTab? get activeTab => tabs.isEmpty
? null
: tabs[activeIndex.clamp(0, tabs.length - 1)];
String get _connectionId => app.conn?.id ?? '';
/// Opens the workspace on first use: the saved tabs and the server's sessions
/// for this directory are reconciled, then the active tab attaches. Later
/// calls just make sure its socket is alive.
Future<void> ensureOpen() async {
if (_disposed) return;
if (_loaded) {
await activeTab?.state.ensureOpen();
return;
}
_loaded = true;
await _load();
}
Future<void> _load() async {
final saved = await _savedTabs();
final server = await _serverTabs();
final plans = planTabs(saved: saved?.tabs ?? const [], server: server);
await _applyPlans(plans, activeId: saved?.activeId);
await activeTab?.state.ensureOpen();
}
/// Tabs to show, given what was saved locally and what the server holds for
/// the directory. A saved tab whose session is gone is dropped; sessions
/// from elsewhere (the web UI, another phone) become tabs of their own.
static List<TerminalTabPlan> planTabs({
required List<SavedTerminalTab> saved,
required List<ServerTerminal>? server,
}) {
final plans = <TerminalTabPlan>[];
String label() => freeLabel(plans.map((p) => p.label));
if (server == null) {
// The listing failed: trust what was saved, and let the attach path
// report a dead id.
for (final tab in saved) {
plans.add(TerminalTabPlan(id: tab.id, label: tab.label));
}
if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const [])));
return plans;
}
// Project-action command runners are PTYs too, but they are not the
// person's terminal tabs.
final sessions = [
for (final s in server)
if (s.interactive) s,
];
final byId = {for (final s in sessions) s.sessionId: s};
final seen = <String>{};
for (final tab in saved) {
if (!byId.containsKey(tab.id) || !seen.add(tab.id)) continue;
plans.add(TerminalTabPlan(id: tab.id, label: tab.label));
}
final rest = [
for (final s in sessions)
if (s.sessionId.isNotEmpty && !seen.contains(s.sessionId)) s,
]..sort((a, b) => (a.createdAt ?? 0).compareTo(b.createdAt ?? 0));
for (final session in rest) {
if (!seen.add(session.sessionId)) continue;
plans.add(TerminalTabPlan(id: session.sessionId, label: label()));
}
if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const [])));
return plans;
}
/// The first free "终端 N" among [labels], so closing a tab makes its number
/// available again.
static String freeLabel(Iterable<String> labels) {
final used = <int>{};
for (final label in labels) {
final match = RegExp(r'^终端 (\d+)$').firstMatch(label.trim());
if (match != null) used.add(int.parse(match.group(1)!));
}
var n = 1;
while (used.contains(n)) {
n++;
}
return '终端 $n';
}
Future<SavedTerminalTabs?> _savedTabs() async {
final connection = _connectionId;
if (connection.isEmpty) return null;
return app.storage.terminalTabs(connection, directory);
}
/// The interactive terminals the server holds for this directory, or null
/// when the listing failed (then the saved tabs are kept as they are).
Future<List<ServerTerminal>?> _serverTabs() async {
final client = app.client;
if (client == null) return null;
try {
final all = await client.listTerminals(cwd: directory);
return [
for (final session in all)
if (session.interactive) session,
];
} catch (_) {
return null;
}
}
Future<void> _applyPlans(List<TerminalTabPlan> plans,
{String? activeId}) async {
final reuse = <String, TerminalTab>{};
for (final tab in tabs) {
final id = tab.state.sessionId;
if (id != null) reuse[id] = tab;
}
final next = <TerminalTab>[];
for (final plan in plans) {
final existing = plan.id == null ? null : reuse[plan.id];
final state = existing?.state ??
TerminalSessionState(app, directory,
onSessionIdChanged: _persistLater);
if (plan.id != null) state.sessionId = plan.id;
next.add(TerminalTab(state, plan.label));
}
for (final tab in tabs) {
if (!next.any((entry) => entry.state == tab.state)) tab.state.dispose();
}
tabs
..clear()
..addAll(next);
final match = activeId == null
? -1
: tabs.indexWhere((tab) => tab.state.sessionId == activeId);
activeIndex = match >= 0 ? match : tabs.length - 1;
notifyListeners();
await _persist();
}
void _persistLater() {
unawaited(_persist());
}
Future<void> _persist() async {
final connection = _connectionId;
if (connection.isEmpty || _disposed) return;
final saved = [
for (final tab in tabs)
if (tab.state.sessionId case final id?)
SavedTerminalTab(id, tab.label),
];
if (saved.isEmpty) {
await app.storage.clearTerminalTabs(connection, directory);
return;
}
await app.storage.saveTerminalTabs(connection, directory,
SavedTerminalTabs(saved, activeTab?.state.sessionId));
}
/// Switches tabs: the old one detaches (its shell stays on the server) and
/// the new one attaches or is created.
Future<void> select(int index) async {
if (_disposed || tabs.isEmpty) return;
index = index.clamp(0, tabs.length - 1);
if (index == activeIndex) return;
final previous = activeTab;
activeIndex = index;
notifyListeners();
await previous?.state.detach();
await activeTab?.state.ensureOpen();
await _persist();
}
/// Adds an empty tab and shows it; its shell is created on open.
Future<void> addTab() async {
if (_disposed) return;
final previous = activeTab;
final state = TerminalSessionState(app, directory,
onSessionIdChanged: _persistLater);
tabs.add(TerminalTab(state, freeLabel(tabs.map((tab) => tab.label))));
activeIndex = tabs.length - 1;
notifyListeners();
await previous?.state.detach();
await state.ensureOpen();
await _persist();
}
/// Closes the active tab on the server and in the list; when it was the last
/// one, a fresh tab takes its place so the panel stays usable.
Future<void> closeActive() async {
if (_disposed || tabs.isEmpty) return;
final closing = tabs.removeAt(activeIndex.clamp(0, tabs.length - 1));
if (tabs.isEmpty) {
final state = TerminalSessionState(app, directory,
onSessionIdChanged: _persistLater);
tabs.add(TerminalTab(state, freeLabel(const [])));
activeIndex = 0;
} else {
activeIndex = activeIndex.clamp(0, tabs.length - 1);
}
notifyListeners();
await closing.state.closeSession();
closing.state.dispose();
await activeTab?.state.ensureOpen();
await _persist();
}
/// Ends every shell and forgets the directory's tabs (an explicit
/// disconnect, not the panel closing).
Future<void> closeAll() async {
final connection = _connectionId;
for (final tab in List.of(tabs)) {
await tab.state.closeSession();
tab.state.dispose();
}
tabs.clear();
_loaded = false;
if (connection.isNotEmpty) {
await app.storage.clearTerminalTabs(connection, directory);
}
notifyListeners();
}
/// After the app returns from the background: the socket may be dead
/// without having reported it.
Future<void> reconnectIfNeeded() async {
await activeTab?.state.reconnectIfNeeded();
}
@override
void dispose() {
_disposed = true;
for (final tab in tabs) {
tab.state.dispose();
}
super.dispose();
}
}
class TerminalSessionState extends ChangeNotifier {
final AppState app;
final String directory;
/// Called when [sessionId] changes (created, replaced, cleared), so the
/// workspace can save its tab list.
final VoidCallback? onSessionIdChanged;
final Terminal model = Terminal(maxLines: 5000);
TerminalSocket? _socket;
@@ -34,7 +304,7 @@ class TerminalSessionState extends ChangeNotifier {
bool _disposed = false;
bool _recovering = false;
TerminalSessionState(this.app, this.directory) {
TerminalSessionState(this.app, this.directory, {this.onSessionIdChanged}) {
model.onOutput = _onOutput;
model.onResize = (cols, rows, _, __) {
_cols = cols;
@@ -43,6 +313,31 @@ class TerminalSessionState extends ChangeNotifier {
};
}
bool get isOpen => link == TerminalLinkState.open;
bool get isRunning =>
link == TerminalLinkState.open || link == TerminalLinkState.connecting;
/// Attaches to the tab's session, or creates one when the tab has none yet.
Future<void> ensureOpen() async {
if (_disposed) return;
if (!_opened) {
_opened = true;
if (sessionId == null) {
await _create();
} else {
await _attach();
}
return;
}
if (_socket == null && link != TerminalLinkState.exited) await _attach();
}
/// Drops the socket without ending the shell; [ensureOpen] attaches again.
Future<void> detach() async {
await _socket?.dispose();
_socket = null;
}
void toggleCtrl() {
ctrl = !ctrl;
notifyListeners();
@@ -89,69 +384,6 @@ class TerminalSessionState extends ChangeNotifier {
}
}
bool get isOpen => link == TerminalLinkState.open;
bool get isRunning =>
link == TerminalLinkState.open || link == TerminalLinkState.connecting;
/// Opens the terminal on first use; later calls just make sure the socket is
/// alive. Unless [fresh] is set, the previous session for this directory is
/// 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 (_opened) {
if (_socket == null && link != TerminalLinkState.exited) await _attach();
return;
}
_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();
}
/// 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 {
final client = app.client;
if (client == null) return;
@@ -163,35 +395,13 @@ class TerminalSessionState extends ChangeNotifier {
sessionId = info.sessionId;
_cols = info.cols;
_rows = info.rows;
await _remember(info.sessionId);
onSessionIdChanged?.call();
await _attach();
} catch (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 {
final client = app.client;
final id = sessionId;
@@ -305,8 +515,7 @@ class TerminalSessionState extends ChangeNotifier {
if (_socket == null) await _attach();
}
/// Ends the shell on the server and drops the socket; the next
/// [ensureOpen] starts a fresh session.
/// Ends the shell on the server and drops the socket.
Future<void> closeSession() async {
final client = app.client;
final id = sessionId;
@@ -314,7 +523,7 @@ class TerminalSessionState extends ChangeNotifier {
_opened = false;
link = TerminalLinkState.idle;
detail = null;
await _forget();
onSessionIdChanged?.call();
await _socket?.dispose();
_socket = null;
if (!_disposed) notifyListeners();
@@ -326,13 +535,13 @@ 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.
/// place, so a stale id does not leave the tab unusable.
Future<void> _recoverMissing() async {
if (_recovering || _disposed) return;
_recovering = true;
try {
sessionId = null;
await _forget();
onSessionIdChanged?.call();
await _socket?.dispose();
_socket = null;
if (_disposed) return;
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones."
publish_to: 'none'
version: 0.4.2+402
version: 0.4.3+403
environment:
sdk: ^3.14.0
+97 -39
View File
@@ -5,64 +5,122 @@ 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'}) =>
{String status = 'running',
int createdAt = 0,
String cwd = '/repo',
String purpose = 'terminal'}) =>
ServerTerminal(
sessionId: id, cwd: cwd, status: status, createdAt: createdAt);
sessionId: id,
cwd: cwd,
status: status,
createdAt: createdAt,
purpose: purpose);
SavedTerminalTab _saved(String id, String label) => SavedTerminalTab(id, label);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('restoreCandidate', () {
test('nothing on the server means a new session', () {
expect(TerminalSessionState.restoreCandidate('saved', const []), isNull);
group('planTabs', () {
test('nothing saved and nothing on the server means one new tab', () {
final plans =
TerminalWorkspace.planTabs(saved: const [], server: const []);
expect(plans, hasLength(1));
expect(plans.single.id, isNull);
expect(plans.single.label, '终端 1');
});
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('saved labels stick to the sessions that are still there', () {
final plans = TerminalWorkspace.planTabs(
saved: [_saved('a', '构建'), _saved('b', '日志')],
server: [_term('a', createdAt: 1), _term('b', createdAt: 2)],
);
expect(plans.map((p) => p.id), ['a', 'b']);
expect(plans.map((p) => p.label), ['构建', '日志']);
});
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('a saved session the server no longer has is dropped', () {
final plans = TerminalWorkspace.planTabs(
saved: [_saved('gone', '终端 1'), _saved('alive', '终端 2')],
server: [_term('alive', createdAt: 1)],
);
expect(plans.map((p) => p.id), ['alive']);
expect(plans.single.label, '终端 2');
});
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('sessions opened elsewhere become tabs in creation order', () {
final plans = TerminalWorkspace.planTabs(
saved: const [],
server: [
_term('new', createdAt: 30),
_term('old', createdAt: 10),
_term('mid', createdAt: 20),
_term('action', createdAt: 5, purpose: 'project-action'),
],
);
expect(plans.map((p) => p.id), ['old', 'mid', 'new']);
expect(plans.map((p) => p.label), ['终端 1', '终端 2', '终端 3']);
});
test('a failed listing keeps the saved tabs', () {
final plans = TerminalWorkspace.planTabs(
saved: [_saved('a', '终端 1'), _saved('b', '终端 2')],
server: null,
);
expect(plans.map((p) => p.id), ['a', 'b']);
expect(plans.map((p) => p.label), ['终端 1', '终端 2']);
});
test('a failed listing with nothing saved still opens one tab', () {
final plans = TerminalWorkspace.planTabs(saved: const [], server: null);
expect(plans, hasLength(1));
expect(plans.single.id, isNull);
});
});
test('remembered terminal ids are kept per connection and directory',
() async {
group('freeLabel', () {
test('picks the first unused number so a closed tab frees its name', () {
expect(TerminalWorkspace.freeLabel([]), '终端 1');
expect(TerminalWorkspace.freeLabel(['终端 1', '终端 3']), '终端 2');
expect(TerminalWorkspace.freeLabel(['终端 1', '终端 2']), '终端 3');
expect(TerminalWorkspace.freeLabel(['构建']), '终端 1');
});
});
test('terminal tabs are kept per connection and directory', () async {
SharedPreferences.setMockInitialValues({});
final storage = Storage();
expect(await storage.terminalSession('srv_a', '/repo'), isNull);
expect(await storage.terminalTabs('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');
await storage.saveTerminalTabs(
'srv_a',
'/repo',
const SavedTerminalTabs(
[SavedTerminalTab('a', '终端 1'), SavedTerminalTab('b', '构建')],
'b',
),
);
final loaded = await storage.terminalTabs('srv_a', '/repo');
expect(loaded, isNotNull);
expect(loaded!.tabs.map((t) => t.id), ['a', 'b']);
expect(loaded.tabs.map((t) => t.label), ['终端 1', '构建']);
expect(loaded.activeId, 'b');
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');
// Another server's directory is a different set.
expect(await storage.terminalTabs('srv_b', '/repo'), isNull);
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');
await storage.clearTerminalTabs('srv_a', '/repo');
expect(await storage.terminalTabs('srv_a', '/repo'), isNull);
});
test('a 0.4.2 single-session value is read as one tab', () async {
SharedPreferences.setMockInitialValues({
'openchamber.terminalSessions.srv_a': '{"\\/repo":"term-1"}',
});
final loaded = await Storage().terminalTabs('srv_a', '/repo');
expect(loaded, isNotNull);
expect(loaded!.tabs.single.id, 'term-1');
expect(loaded.activeId, 'term-1');
});
}