Merge branch 'worktree-agent-a2791c24c562412e3'
# Conflicts: # app/lib/features/chat/conversation/chat_thread_view.dart # internal/protocol/message.go
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../core/api_gateway.dart';
|
||||
import '../core/servers/chat/chat_server_pool.dart';
|
||||
import '../features/terminal/terminal_hub.dart';
|
||||
import '../features/terminal/terminal_layout.dart';
|
||||
import '../features/terminal/terminal_machines.dart';
|
||||
import '../features/terminal/terminal_surface.dart';
|
||||
import '../features/terminal/terminal_toggle_button.dart';
|
||||
|
||||
/// The app's machine terminals: one hub over every connected machine (the
|
||||
/// chat pool's, else the app's own server), kept for the app's lifetime so
|
||||
/// shells and their output survive navigation and hidden panels.
|
||||
class AppTerminals {
|
||||
AppTerminals({
|
||||
required ChatServerPool? pool,
|
||||
required Listenable connection,
|
||||
required bool Function() connected,
|
||||
required ApiGateway gateway,
|
||||
required String machineId,
|
||||
required String machineName,
|
||||
required this.layout,
|
||||
}) : machines = pool != null
|
||||
? PoolTerminalMachines(pool)
|
||||
: SingleTerminalMachines(
|
||||
connection: connection,
|
||||
connected: connected,
|
||||
machine: TerminalMachine(
|
||||
id: machineId,
|
||||
name: machineName,
|
||||
gateway: gateway,
|
||||
),
|
||||
) {
|
||||
hub = TerminalHub(machines);
|
||||
}
|
||||
|
||||
final ValueNotifier<List<TerminalMachine>> machines;
|
||||
final TerminalLayout layout;
|
||||
late final TerminalHub hub;
|
||||
|
||||
/// [shell] with the terminal panel, window or page around it.
|
||||
Widget surround(Widget shell, {required bool cupertino}) => TerminalSurface(
|
||||
hub: hub,
|
||||
layout: layout,
|
||||
cupertino: cupertino,
|
||||
child: shell,
|
||||
);
|
||||
|
||||
/// The bar button showing or hiding the terminal.
|
||||
Widget toggle({required bool cupertino}) =>
|
||||
TerminalToggleButton(layout: layout, cupertino: cupertino);
|
||||
|
||||
void dispose() {
|
||||
hub.dispose();
|
||||
machines.dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../features/terminal/terminal_layout.dart';
|
||||
import '../core/session/server_session.dart';
|
||||
import '../ui/scale/ui_scale.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
@@ -60,6 +61,7 @@ Future<void> runPipelinesApp({
|
||||
// not hold the first frame, and applies when it lands.
|
||||
final animationSpeed = AnimationSpeedController.instance.restore();
|
||||
final uiScale = UiScaleController.instance.restore();
|
||||
final terminalLayout = TerminalLayout.instance.restore();
|
||||
final quickSwitchAnimation = QuickSwitchAnimationController.instance
|
||||
.restore();
|
||||
final font = AppFontController.instance.restore(wait: appFontStartupWait);
|
||||
@@ -68,6 +70,7 @@ Future<void> runPipelinesApp({
|
||||
await font;
|
||||
await animationSpeed;
|
||||
await uiScale;
|
||||
await terminalLayout;
|
||||
await quickSwitchAnimation;
|
||||
final server = await resolveLaunchServer(
|
||||
base: base,
|
||||
|
||||
@@ -32,6 +32,8 @@ import '../features/updates/launch_update_dialog.dart';
|
||||
import '../features/updates/web_release.dart';
|
||||
import '../features/settings/server_connections.dart';
|
||||
import 'app.dart';
|
||||
import 'app_terminals.dart';
|
||||
import '../features/terminal/terminal_layout.dart';
|
||||
import 'app_route.dart';
|
||||
import 'app_router.dart';
|
||||
import 'app_session.dart';
|
||||
@@ -82,9 +84,13 @@ class PipelinesApp extends StatefulWidget {
|
||||
this.androidInstaller = downloadAndInstall,
|
||||
this.webRefresher = refreshWebPage,
|
||||
this.tabLocationsStore,
|
||||
this.terminalLayout,
|
||||
});
|
||||
|
||||
final TabLocationsStore? tabLocationsStore;
|
||||
|
||||
/// The terminal surface's saved layout; null is the device's own.
|
||||
final TerminalLayout? terminalLayout;
|
||||
final ServerEndpoint server;
|
||||
final PipelinesClient? client;
|
||||
final bool? cupertino;
|
||||
@@ -195,6 +201,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
},
|
||||
);
|
||||
NotificationServiceHandoff? _deliveryHandoff;
|
||||
late final AppTerminals _terminals;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -213,6 +220,18 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
serverId: widget.serverId,
|
||||
);
|
||||
bindServerIdentity(_session.gateway, widget.serverId);
|
||||
_terminals = AppTerminals(
|
||||
pool: widget.chatPool,
|
||||
connection: _session,
|
||||
connected: () => _session.connected,
|
||||
gateway: _session.gateway,
|
||||
machineId: widget.serverId ?? 'server',
|
||||
machineName:
|
||||
widget.servers?.catalog.active?.name ??
|
||||
widget.server.uri?.host ??
|
||||
'This server',
|
||||
layout: widget.terminalLayout ?? TerminalLayout.instance,
|
||||
);
|
||||
_ownsProvider = widget.routeInformationProvider == null;
|
||||
_provider =
|
||||
widget.routeInformationProvider ??
|
||||
@@ -421,6 +440,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
if (_ownsProvider) {
|
||||
(_provider as PlatformRouteInformationProvider).dispose();
|
||||
}
|
||||
_terminals.dispose();
|
||||
_session.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
@@ -697,7 +717,8 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
Widget _buildShell(BuildContext context, AppRoute route) =>
|
||||
ValueListenableBuilder<int>(
|
||||
valueListenable: _attentionCount,
|
||||
builder: (context, count, _) => _shellFor(route, count),
|
||||
builder: (context, count, _) =>
|
||||
_terminals.surround(_shellFor(route, count), cupertino: _cupertino),
|
||||
);
|
||||
|
||||
Widget _shellFor(AppRoute route, int attentionCount) {
|
||||
@@ -715,6 +736,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
final runsRoute = tab(AppDestination.runs);
|
||||
final chatRoute = tab(AppDestination.chat);
|
||||
return AdaptiveShell(
|
||||
barActions: [_terminals.toggle(cupertino: _cupertino)],
|
||||
attentionCount: attentionCount,
|
||||
cupertino: _cupertino,
|
||||
destination: _destinationOf(route.kind),
|
||||
@@ -803,6 +825,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
// Settings is a page of the Pipelines tab (its bar's gear), not a
|
||||
// tab; the shell shows it with Back to Pipelines.
|
||||
AppDestination.settings: (_) => SettingsScreen(
|
||||
terminalLayout: _terminals.layout,
|
||||
navigationScope: _navigationScope,
|
||||
client: _session.client,
|
||||
// A phone signs in at the web login; a browser has its own.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../../terminal/terminal_open_action.dart';
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
@@ -1412,6 +1413,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
chatShellRunMenuAction(onPressed: _runShellFromMenu),
|
||||
if (_shellRuns.finishedIds.isNotEmpty)
|
||||
chatShellDismissAllMenuAction(onPressed: _dismissFinishedShellRuns),
|
||||
?terminalOpenMenuAction(
|
||||
context,
|
||||
gateway: widget.gateway,
|
||||
directory: directory,
|
||||
onRefused: (refusal) => _showCommandNotice(
|
||||
"Couldn't open a terminal: $refusal",
|
||||
failed: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
controls: [
|
||||
if (hasModel)
|
||||
|
||||
@@ -14,6 +14,8 @@ import 'files_upload_notice.dart';
|
||||
import 'files_viewer.dart';
|
||||
import 'files_header.dart';
|
||||
import '../../../ui/layout/app_overflow_menu.dart';
|
||||
import '../../terminal/terminal_open_action.dart';
|
||||
import '../../terminal/terminal_scope.dart';
|
||||
|
||||
const double filesPanelMinWidth = 280;
|
||||
const double filesPanelMaxWidth = 420;
|
||||
@@ -23,8 +25,9 @@ double filesPanelWidth(double available) => (available * filesPanelFraction)
|
||||
.clamp(filesPanelMinWidth, filesPanelMaxWidth);
|
||||
|
||||
/// The actions of an entry's row or tile menu. Open and Download are for
|
||||
/// files; Rename, Move and Delete apply to files and folders alike.
|
||||
enum FileAction { open, download, rename, move, delete }
|
||||
/// files, Open in terminal for folders (where the app has a terminal);
|
||||
/// Rename, Move and Delete apply to files and folders alike.
|
||||
enum FileAction { open, download, terminal, rename, move, delete }
|
||||
|
||||
class FilesPanel extends StatefulWidget {
|
||||
const FilesPanel({
|
||||
@@ -180,6 +183,12 @@ class _FilesPanelState extends State<FilesPanel> {
|
||||
endpoint: _endpoint,
|
||||
entry: entry,
|
||||
),
|
||||
// A refusal shows in the terminal the surface opens.
|
||||
FileAction.terminal => openInTerminal(
|
||||
context,
|
||||
controller.gateway,
|
||||
entry.path,
|
||||
),
|
||||
FileAction.rename => renameEntry(context, controller, entry),
|
||||
FileAction.move => moveEntry(context, controller, entry),
|
||||
FileAction.delete => deleteEntry(context, controller, entry),
|
||||
@@ -189,6 +198,11 @@ class _FilesPanelState extends State<FilesPanel> {
|
||||
AppMenuAction(value: FileAction.open, label: 'Open'),
|
||||
AppMenuAction(value: FileAction.download, label: 'Download'),
|
||||
],
|
||||
if (entry.isDir && TerminalScope.maybeOf(context) != null)
|
||||
const AppMenuAction(
|
||||
value: FileAction.terminal,
|
||||
label: terminalOpenActionLabel,
|
||||
),
|
||||
const AppMenuAction(value: FileAction.rename, label: 'Rename…'),
|
||||
const AppMenuAction(value: FileAction.move, label: 'Move…'),
|
||||
const AppMenuAction(
|
||||
|
||||
@@ -28,7 +28,7 @@ class ChatShellTerminals {
|
||||
final void Function(String runId, Object error) onError;
|
||||
|
||||
final Map<String, ChatShellTerminalSession> _sessions = {};
|
||||
final Map<String, _InputPipe> _inputs = {};
|
||||
final Map<String, ChatShellInputPipe> _inputs = {};
|
||||
final Map<String, Timer> _resizes = {};
|
||||
final Map<String, (int, int)> _sentSizes = {};
|
||||
bool _disposed = false;
|
||||
@@ -74,7 +74,7 @@ class ChatShellTerminals {
|
||||
_inputs
|
||||
.putIfAbsent(
|
||||
runId,
|
||||
() => _InputPipe(
|
||||
() => ChatShellInputPipe(
|
||||
(data) => _repository.input(_sessionId, runId, data),
|
||||
(error) => onError(runId, error),
|
||||
),
|
||||
@@ -106,11 +106,12 @@ class ChatShellTerminals {
|
||||
}
|
||||
}
|
||||
|
||||
/// One run's typed input on its way to the server, in order: what arrives
|
||||
/// One terminal's typed input on its way to the server (a chat run's or a
|
||||
/// machine terminal's), in order: what arrives
|
||||
/// while a request is in flight goes in the next one. Nothing is kept once
|
||||
/// sent, and a refusal discards what was waiting rather than retyping it.
|
||||
class _InputPipe {
|
||||
_InputPipe(this._send, this._failed);
|
||||
class ChatShellInputPipe {
|
||||
ChatShellInputPipe(this._send, this._failed);
|
||||
|
||||
final Future<void> Function(String data) _send;
|
||||
final void Function(Object error) _failed;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import '../terminal/terminal_layout.dart';
|
||||
import 'settings_terminal_section.dart';
|
||||
import '../../ui/adaptive/segmented_bar.dart';
|
||||
import 'dart:async';
|
||||
|
||||
@@ -66,12 +68,17 @@ class SettingsScreen extends StatefulWidget {
|
||||
this.deliveryServiceController,
|
||||
this.fonts,
|
||||
this.animationSpeed,
|
||||
this.terminalLayout,
|
||||
});
|
||||
|
||||
/// The device's interface font; defaults to the app's shared controller.
|
||||
final AppFontController? fonts;
|
||||
final AnimationSpeedController? animationSpeed;
|
||||
|
||||
/// The terminal surface's layout (its mode is chosen here); null is the
|
||||
/// device's own.
|
||||
final TerminalLayout? terminalLayout;
|
||||
|
||||
/// Android background delivery; hidden when absent or unsupported.
|
||||
final NotificationServiceBridge? deliveryService;
|
||||
final NotificationServiceController? deliveryServiceController;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../terminal/terminal_layout.dart';
|
||||
import 'settings_group.dart';
|
||||
import 'settings_theme.dart';
|
||||
|
||||
/// Appearance → Terminal: whether the terminal docks at the bottom of the
|
||||
/// window or floats over it (Ctrl+` shows and hides it either way).
|
||||
class SettingsTerminalSection extends StatelessWidget {
|
||||
const SettingsTerminalSection({super.key, required this.layout});
|
||||
|
||||
final TerminalLayout layout;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: layout,
|
||||
builder: (context, _) {
|
||||
final cupertino = usesCupertinoControls(context);
|
||||
final Widget choice = cupertino
|
||||
? CupertinoSlidingSegmentedControl<TerminalMode>(
|
||||
groupValue: layout.mode,
|
||||
children: {
|
||||
for (final mode in TerminalMode.values)
|
||||
mode: Padding(
|
||||
key: ValueKey('settings-terminal-${mode.name}'),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: Text(mode.label),
|
||||
),
|
||||
},
|
||||
onValueChanged: (mode) {
|
||||
if (mode != null) layout.setMode(mode);
|
||||
},
|
||||
)
|
||||
: SegmentedButton<TerminalMode>(
|
||||
segments: [
|
||||
for (final mode in TerminalMode.values)
|
||||
ButtonSegment(
|
||||
value: mode,
|
||||
label: Text(
|
||||
mode.label,
|
||||
key: ValueKey('settings-terminal-${mode.name}'),
|
||||
),
|
||||
icon: Icon(
|
||||
mode == TerminalMode.panel
|
||||
? Icons.call_to_action_outlined
|
||||
: Icons.picture_in_picture_alt_outlined,
|
||||
),
|
||||
),
|
||||
],
|
||||
selected: {layout.mode},
|
||||
onSelectionChanged: (modes) => layout.setMode(modes.first),
|
||||
);
|
||||
return SettingsGroup(
|
||||
title: 'Terminal',
|
||||
footer: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(
|
||||
'Saved on this device. Ctrl+` shows or hides the terminal; on '
|
||||
'a narrow window it opens full screen. Shells keep running '
|
||||
'while it is hidden.',
|
||||
),
|
||||
if (layout.saveFailed)
|
||||
Text(
|
||||
'Could not save; applies until reload.',
|
||||
style: TextStyle(color: settingsErrorColor(context)),
|
||||
),
|
||||
],
|
||||
),
|
||||
children: [
|
||||
SettingsGroupItem(
|
||||
child: Semantics(
|
||||
label: 'Terminal placement',
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: choice,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,9 @@ extension _SettingsTopicPages on _SettingsScreenState {
|
||||
SettingsFontSection(
|
||||
controller: widget.fonts ?? AppFontController.instance,
|
||||
),
|
||||
SettingsTerminalSection(
|
||||
layout: widget.terminalLayout ?? TerminalLayout.instance,
|
||||
),
|
||||
],
|
||||
),
|
||||
SettingsTopic.connection: (_) => SettingsPageBody(
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../chat/shell/chat_shell_terminal_keys.dart';
|
||||
import '../chat/shell/chat_shell_terminal_view.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_tab.dart';
|
||||
|
||||
/// The selected terminal: its emulator (focused when shown), what the
|
||||
/// operator should know about it (ended, machine offline, ends with the
|
||||
/// server) and, with [keys], the touch key toolbar.
|
||||
class TerminalBody extends StatelessWidget {
|
||||
const TerminalBody({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.cupertino,
|
||||
this.keys = false,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final bool cupertino;
|
||||
final bool keys;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final tab = hub.selected;
|
||||
if (tab == null) return _empty(context);
|
||||
final notes = <String>[
|
||||
if (!tab.connected)
|
||||
'${tab.machineName} is not connected; the terminal resumes when it is.'
|
||||
else if (!tab.info.running)
|
||||
tab.info.endedText
|
||||
else if (!tab.info.persistent)
|
||||
'This shell ends if the server on ${tab.machineName} restarts '
|
||||
'(tmux is not installed there).',
|
||||
?tab.error,
|
||||
?hub.error,
|
||||
];
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
child: ChatShellTerminalView(
|
||||
key: ValueKey('terminal-view-${tab.key}'),
|
||||
session: tab.session,
|
||||
cupertino: cupertino,
|
||||
fill: true,
|
||||
autofocus: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
for (final note in notes)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 0, 12, 8),
|
||||
child: Text(note, style: _noteStyle(context)),
|
||||
),
|
||||
if (keys && tab.session.live && tab.connected)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
child: ChatShellTerminalKeys(
|
||||
session: tab.session,
|
||||
cupertino: cupertino,
|
||||
field: chatShellTouchFirst(),
|
||||
),
|
||||
),
|
||||
if (!tab.info.running && tab.connected) _closeEnded(tab),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
TextStyle? _noteStyle(BuildContext context) => cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
|
||||
color: CupertinoColors.secondaryLabel.resolveFrom(context),
|
||||
)
|
||||
: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
);
|
||||
|
||||
Widget _closeEnded(TerminalTab tab) {
|
||||
void close() => unawaited(hub.close(tab));
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: cupertino
|
||||
? CupertinoButton(onPressed: close, child: const Text('Close tab'))
|
||||
: TextButton(onPressed: close, child: const Text('Close tab')),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _empty(BuildContext context) {
|
||||
final machines = hub.connected;
|
||||
final text = machines.isEmpty
|
||||
? 'No machine is connected.'
|
||||
: 'No terminals are open.';
|
||||
void open() => unawaited(hub.open());
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(text, style: _noteStyle(context)),
|
||||
if (hub.error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Text(error, style: _noteStyle(context)),
|
||||
),
|
||||
if (machines.isNotEmpty)
|
||||
cupertino
|
||||
? CupertinoButton(
|
||||
onPressed: open,
|
||||
child: const Text('New terminal'),
|
||||
)
|
||||
: FilledButton.tonal(
|
||||
onPressed: open,
|
||||
child: const Text('New terminal'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'terminal_body.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_tab_strip.dart';
|
||||
|
||||
/// Margin a maximised window keeps from the edges of the app.
|
||||
const double terminalFloatMargin = 8;
|
||||
|
||||
/// [rect] moved and shrunk to fit inside [bounds], at least the minimum
|
||||
/// window size where the bounds allow it.
|
||||
Rect fitTerminalFloat(Rect rect, Size bounds) {
|
||||
final width = rect.width
|
||||
.clamp(terminalFloatMinSize.width, double.infinity)
|
||||
.clamp(0.0, bounds.width);
|
||||
final height = rect.height
|
||||
.clamp(terminalFloatMinSize.height, double.infinity)
|
||||
.clamp(0.0, bounds.height);
|
||||
final left = rect.left.clamp(0.0, bounds.width - width);
|
||||
final top = rect.top.clamp(0.0, bounds.height - height);
|
||||
return Rect.fromLTWH(left, top, width, height);
|
||||
}
|
||||
|
||||
/// The terminal as a window over the app: moved by its title bar, resized
|
||||
/// from its lower right corner, minimised to its title bar or maximised to
|
||||
/// the app. Its frame is kept in [layout].
|
||||
class TerminalFloat extends StatelessWidget {
|
||||
const TerminalFloat({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
required this.bounds,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
final Size bounds;
|
||||
|
||||
/// Where the window is drawn now.
|
||||
Rect get frame => layout.maximized
|
||||
? (Offset.zero & bounds).deflate(terminalFloatMargin)
|
||||
: fitTerminalFloat(layout.floatRect, bounds);
|
||||
|
||||
void _move(Offset delta) {
|
||||
if (layout.maximized) return;
|
||||
layout.setFloatRect(frame.shift(delta), save: false);
|
||||
}
|
||||
|
||||
void _resize(Offset delta) {
|
||||
final rect = frame;
|
||||
layout.setFloatRect(
|
||||
fitTerminalFloat(
|
||||
Rect.fromLTWH(
|
||||
rect.left,
|
||||
rect.top,
|
||||
rect.width + delta.dx,
|
||||
rect.height + delta.dy,
|
||||
),
|
||||
bounds,
|
||||
),
|
||||
save: false,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final rect = frame;
|
||||
final title = _titleBar(context);
|
||||
final Widget window;
|
||||
if (layout.minimized) {
|
||||
window = SizedBox(width: rect.width, child: title);
|
||||
} else {
|
||||
window = SizedBox.fromSize(
|
||||
size: rect.size,
|
||||
child: Stack(
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
title,
|
||||
TerminalTabStrip(
|
||||
hub: hub,
|
||||
layout: layout,
|
||||
cupertino: cupertino,
|
||||
),
|
||||
Expanded(
|
||||
child: TerminalBody(hub: hub, cupertino: cupertino),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (!layout.maximized)
|
||||
PositionedDirectional(end: 0, bottom: 0, child: _corner()),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return Positioned(
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
child: Semantics(
|
||||
container: true,
|
||||
label: 'Terminal window',
|
||||
child: _chrome(context, window),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _chrome(BuildContext context, Widget child) {
|
||||
if (!cupertino) {
|
||||
return Material(
|
||||
elevation: 8,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
color: Theme.of(context).colorScheme.surfaceContainer,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: CupertinoColors.secondarySystemBackground.resolveFrom(context),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: CupertinoColors.separator.resolveFrom(context),
|
||||
),
|
||||
boxShadow: const [BoxShadow(blurRadius: 16, color: Color(0x33000000))],
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Material(type: MaterialType.transparency, child: child),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _titleBar(BuildContext context) {
|
||||
final label = Text(
|
||||
hub.selected?.title ?? 'Terminal',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: cupertino
|
||||
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
|
||||
: Theme.of(context).textTheme.titleSmall,
|
||||
);
|
||||
final drag = MouseRegion(
|
||||
cursor: layout.maximized
|
||||
? SystemMouseCursors.basic
|
||||
: SystemMouseCursors.move,
|
||||
child: GestureDetector(
|
||||
key: const ValueKey('terminal-float-title'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
// The window follows the pointer from where it went down.
|
||||
dragStartBehavior: DragStartBehavior.down,
|
||||
onPanUpdate: (details) => _move(details.delta),
|
||||
onPanEnd: (_) => unawaited(layout.save()),
|
||||
onDoubleTap: () => layout.setMaximized(!layout.maximized),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(start: 12),
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: label,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(child: drag),
|
||||
_button(
|
||||
layout.minimized ? 'Restore' : 'Minimise',
|
||||
layout.minimized ? Icons.expand_less : Icons.minimize,
|
||||
layout.minimized ? CupertinoIcons.chevron_up : CupertinoIcons.minus,
|
||||
() => layout.setMinimized(!layout.minimized),
|
||||
),
|
||||
_button(
|
||||
layout.maximized ? 'Restore size' : 'Maximise',
|
||||
layout.maximized ? Icons.fullscreen_exit : Icons.fullscreen,
|
||||
layout.maximized
|
||||
? CupertinoIcons.fullscreen_exit
|
||||
: CupertinoIcons.fullscreen,
|
||||
() => layout.setMaximized(!layout.maximized),
|
||||
),
|
||||
_button(
|
||||
'Hide terminal',
|
||||
Icons.close,
|
||||
CupertinoIcons.xmark,
|
||||
layout.hide,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _button(
|
||||
String label,
|
||||
IconData material,
|
||||
IconData cupertinoIcon,
|
||||
VoidCallback onPressed,
|
||||
) => cupertino
|
||||
? CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: onPressed,
|
||||
child: Icon(cupertinoIcon, semanticLabel: label),
|
||||
)
|
||||
: IconButton(tooltip: label, onPressed: onPressed, icon: Icon(material));
|
||||
|
||||
Widget _corner() => Semantics(
|
||||
label: 'Resize terminal window',
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.resizeDownRight,
|
||||
child: GestureDetector(
|
||||
key: const ValueKey('terminal-float-resize'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
dragStartBehavior: DragStartBehavior.down,
|
||||
onPanUpdate: (details) => _resize(details.delta),
|
||||
onPanEnd: (_) => unawaited(layout.save()),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: Icon(
|
||||
cupertino ? CupertinoIcons.arrow_down_right : Icons.south_east,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'terminal_info.dart';
|
||||
import 'terminal_machines.dart';
|
||||
import 'terminal_tab.dart';
|
||||
|
||||
/// Every machine terminal the app shows, across the connected machines:
|
||||
/// the tabs, the selected one, and their link to each machine's socket.
|
||||
///
|
||||
/// The hub belongs to the app, not to a view: terminals keep running and
|
||||
/// keep their output while the panel is hidden or the window is minimised.
|
||||
/// When a machine connects (first, or again after a drop or a server
|
||||
/// restart) its terminals are listed, new ones get a tab, and every tab
|
||||
/// resumes its output from the last byte it holds.
|
||||
class TerminalHub extends ChangeNotifier {
|
||||
TerminalHub(this.machines);
|
||||
|
||||
final TerminalMachines machines;
|
||||
final Map<String, _Link> _links = {};
|
||||
bool _active = false;
|
||||
final List<TerminalTab> _tabs = [];
|
||||
String? _selected;
|
||||
bool _disposed = false;
|
||||
|
||||
/// The last refusal of an open or close, in the server's words.
|
||||
String? error;
|
||||
|
||||
List<TerminalTab> get tabs => List.unmodifiable(_tabs);
|
||||
List<TerminalMachine> get connected => machines.value;
|
||||
|
||||
TerminalTab? get selected =>
|
||||
_tabs.where((tab) => tab.key == _selected).firstOrNull ??
|
||||
_tabs.firstOrNull;
|
||||
|
||||
/// Whether the tabs come from more than one machine (or more than one
|
||||
/// is connected), so each names its machine.
|
||||
bool get multiMachine =>
|
||||
connected.length > 1 ||
|
||||
_tabs.map((tab) => tab.machineId).toSet().length > 1;
|
||||
|
||||
/// Starts following the machines: their terminals are listed now and on
|
||||
/// every reconnect. The surface calls it the first time the terminal is
|
||||
/// shown, so an app that never shows it sends no terminal requests (each
|
||||
/// connection sends one request at a time; the first screen's read goes
|
||||
/// first).
|
||||
void activate() {
|
||||
if (_active || _disposed) return;
|
||||
_active = true;
|
||||
machines.addListener(_machinesChanged);
|
||||
_machinesChanged();
|
||||
}
|
||||
|
||||
bool get active => _active;
|
||||
|
||||
void select(TerminalTab tab) {
|
||||
if (_selected == tab.key) return;
|
||||
_selected = tab.key;
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// The machine [gateway] belongs to, if it is connected.
|
||||
TerminalMachine? machineFor(String? id) =>
|
||||
connected.where((machine) => machine.id == id).firstOrNull;
|
||||
|
||||
/// Opens a shell on [machineId] (the first connected machine when null)
|
||||
/// in [cwd] (home when empty) and selects its tab. Returns the refusal.
|
||||
Future<String?> open({String? machineId, String cwd = ''}) async {
|
||||
activate();
|
||||
final machine = machineId == null
|
||||
? connected.firstOrNull
|
||||
: machineFor(machineId);
|
||||
if (machine == null) {
|
||||
return error = 'No machine is connected to open a terminal on.';
|
||||
}
|
||||
try {
|
||||
final reply = await machine.gateway.call('terminal_open', {
|
||||
'terminal_request': {'cwd': ?(cwd.isEmpty ? null : cwd)},
|
||||
});
|
||||
final record = reply['terminal'];
|
||||
if (record is! Map) throw StateError('The server sent no terminal.');
|
||||
final tab = _adopt(machine, TerminalInfo.fromJson(record));
|
||||
_selected = tab.key;
|
||||
error = null;
|
||||
_notify();
|
||||
return null;
|
||||
} catch (failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends [tab]'s shell (and its tmux session) and removes the tab. A tab
|
||||
/// whose machine is not connected cannot be closed yet.
|
||||
Future<String?> close(TerminalTab tab) async {
|
||||
if (!tab.connected) {
|
||||
return error = '${tab.machineName} is not connected.';
|
||||
}
|
||||
try {
|
||||
await tab.gateway.call('terminal_close', {
|
||||
'terminal_request': {'terminal_id': tab.info.id},
|
||||
});
|
||||
_remove(tab.key);
|
||||
error = null;
|
||||
return null;
|
||||
} catch (failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
TerminalTab _adopt(TerminalMachine machine, TerminalInfo info) {
|
||||
final key = terminalKey(machine.id, info.id);
|
||||
final existing = _tabs.where((tab) => tab.key == key).firstOrNull;
|
||||
if (existing != null) {
|
||||
existing.machineName = machine.name;
|
||||
existing.attach(machine.gateway, info);
|
||||
return existing;
|
||||
}
|
||||
final tab = TerminalTab(
|
||||
machineId: machine.id,
|
||||
machineName: machine.name,
|
||||
gateway: machine.gateway,
|
||||
info: info,
|
||||
)..addListener(_notify);
|
||||
_tabs.add(tab);
|
||||
unawaited(tab.resume());
|
||||
return tab;
|
||||
}
|
||||
|
||||
void _remove(String key) {
|
||||
final index = _tabs.indexWhere((tab) => tab.key == key);
|
||||
if (index < 0) return;
|
||||
final tab = _tabs.removeAt(index);
|
||||
if (_selected == key) {
|
||||
_selected = _tabs.isEmpty
|
||||
? null
|
||||
: _tabs[index.clamp(0, _tabs.length - 1)].key;
|
||||
}
|
||||
tab
|
||||
..removeListener(_notify)
|
||||
..dispose();
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _machinesChanged() {
|
||||
if (_disposed) return;
|
||||
final ids = {for (final machine in connected) machine.id};
|
||||
for (final id in _links.keys.where((id) => !ids.contains(id)).toList()) {
|
||||
_links.remove(id)!.cancel();
|
||||
for (final tab in _tabs.where((tab) => tab.machineId == id)) {
|
||||
tab.disconnected();
|
||||
}
|
||||
}
|
||||
for (final machine in connected) {
|
||||
final link = _links[machine.id];
|
||||
if (link != null && identical(link.gateway, machine.gateway)) continue;
|
||||
link?.cancel();
|
||||
_links[machine.id] = _Link(
|
||||
machine.gateway,
|
||||
machine.gateway.frames.listen((frame) => _frame(machine, frame)),
|
||||
);
|
||||
unawaited(_sync(machine));
|
||||
}
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Lists [machine]'s terminals: each gets (or keeps) a tab, which then
|
||||
/// resumes its output; tabs of terminals the machine no longer has go.
|
||||
Future<void> _sync(TerminalMachine machine) async {
|
||||
final List<TerminalInfo> infos;
|
||||
try {
|
||||
infos = terminalInfos(await machine.gateway.call('terminal_list'));
|
||||
} catch (failure) {
|
||||
// A server without terminals answers with an error; its tabs stay.
|
||||
error = '$failure';
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
if (_disposed || !identical(_links[machine.id]?.gateway, machine.gateway)) {
|
||||
return;
|
||||
}
|
||||
final listed = <String>{};
|
||||
for (final info in infos.where((info) => !info.closed)) {
|
||||
listed.add(_adopt(machine, info).key);
|
||||
}
|
||||
for (final tab in _tabs.toList()) {
|
||||
if (tab.machineId == machine.id && !listed.contains(tab.key)) {
|
||||
_remove(tab.key);
|
||||
}
|
||||
}
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _frame(TerminalMachine machine, JsonMap frame) {
|
||||
if (frame['type'] != 'terminal_event') return;
|
||||
final event = frame['terminal_event'];
|
||||
if (event is! Map) return;
|
||||
final key = terminalKey(machine.id, '${event['terminal_id'] ?? ''}');
|
||||
final record = event['terminal'];
|
||||
if (record is Map) {
|
||||
final info = TerminalInfo.fromJson(record);
|
||||
if (info.closed) return _remove(key);
|
||||
// A terminal another client opened appears here too.
|
||||
if (!_tabs.any((tab) => tab.key == key)) {
|
||||
_adopt(machine, info);
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
}
|
||||
_tabs.where((tab) => tab.key == key).firstOrNull?.frame(event);
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
if (_active) machines.removeListener(_machinesChanged);
|
||||
for (final link in _links.values) {
|
||||
link.cancel();
|
||||
}
|
||||
for (final tab in _tabs) {
|
||||
tab.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class _Link {
|
||||
_Link(this.gateway, this.frames);
|
||||
final ApiGateway gateway;
|
||||
final StreamSubscription<JsonMap> frames;
|
||||
void cancel() => unawaited(frames.cancel());
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import '../../core/api_gateway.dart';
|
||||
|
||||
/// One machine terminal as the server records it (`terminal_list`,
|
||||
/// `terminal_event`): a login shell on that machine, running or ended.
|
||||
class TerminalInfo {
|
||||
const TerminalInfo({
|
||||
required this.id,
|
||||
required this.cwd,
|
||||
required this.status,
|
||||
this.title = '',
|
||||
this.shell = '',
|
||||
this.tmux = '',
|
||||
this.reason = '',
|
||||
this.exitCode,
|
||||
this.createdAt = 0,
|
||||
this.cols = 0,
|
||||
this.rows = 0,
|
||||
this.stream = '',
|
||||
this.outputEnd = 0,
|
||||
});
|
||||
|
||||
factory TerminalInfo.fromJson(Map json) => TerminalInfo(
|
||||
id: '${json['id'] ?? ''}',
|
||||
cwd: '${json['cwd'] ?? ''}',
|
||||
status: '${json['status'] ?? ''}',
|
||||
title: '${json['title'] ?? ''}',
|
||||
shell: '${json['shell'] ?? ''}',
|
||||
tmux: '${json['tmux'] ?? ''}',
|
||||
reason: '${json['reason'] ?? ''}',
|
||||
exitCode: (json['exit_code'] as num?)?.toInt(),
|
||||
createdAt: (json['created_at'] as num?)?.toInt() ?? 0,
|
||||
cols: (json['cols'] as num?)?.toInt() ?? 0,
|
||||
rows: (json['rows'] as num?)?.toInt() ?? 0,
|
||||
stream: '${json['stream'] ?? ''}',
|
||||
outputEnd: (json['output_end'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
|
||||
final String id;
|
||||
final String cwd;
|
||||
|
||||
/// running, exited or closed.
|
||||
final String status;
|
||||
|
||||
/// The last window title the shell set, or empty.
|
||||
final String title;
|
||||
final String shell;
|
||||
|
||||
/// The tmux session keeping the shell alive across server restarts;
|
||||
/// empty when the shell ends with the server.
|
||||
final String tmux;
|
||||
|
||||
/// Why an ended terminal ended, when it was not its own exit.
|
||||
final String reason;
|
||||
final int? exitCode;
|
||||
final int createdAt;
|
||||
final int cols;
|
||||
final int rows;
|
||||
|
||||
/// Names the server process's output stream: a restarted server starts
|
||||
/// a new one, whose byte offsets begin again at zero.
|
||||
final String stream;
|
||||
final int outputEnd;
|
||||
|
||||
/// This record naming output [stream] (lifecycle frames carry none).
|
||||
TerminalInfo withStream(String stream) => TerminalInfo(
|
||||
id: id,
|
||||
cwd: cwd,
|
||||
status: status,
|
||||
title: title,
|
||||
shell: shell,
|
||||
tmux: tmux,
|
||||
reason: reason,
|
||||
exitCode: exitCode,
|
||||
createdAt: createdAt,
|
||||
cols: cols,
|
||||
rows: rows,
|
||||
stream: stream,
|
||||
outputEnd: outputEnd,
|
||||
);
|
||||
|
||||
bool get running => status == 'running';
|
||||
bool get closed => status == 'closed';
|
||||
bool get persistent => tmux.isNotEmpty;
|
||||
|
||||
/// What an ended terminal shows instead of a prompt.
|
||||
String get endedText {
|
||||
if (reason.isNotEmpty) return reason;
|
||||
final code = exitCode;
|
||||
return code == null ? 'The shell ended.' : 'The shell exited with $code.';
|
||||
}
|
||||
}
|
||||
|
||||
/// The terminal records of a `terminal_list` reply.
|
||||
List<TerminalInfo> terminalInfos(JsonMap reply) => [
|
||||
for (final value in (reply['terminals'] as List?) ?? const [])
|
||||
if (value is Map) TerminalInfo.fromJson(value),
|
||||
];
|
||||
@@ -0,0 +1,161 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const terminalLayoutKey = 'pipelines.terminal-layout.v1';
|
||||
|
||||
/// Where the terminal shows on a wide window.
|
||||
enum TerminalMode {
|
||||
panel('Bottom panel'),
|
||||
float('Floating window');
|
||||
|
||||
const TerminalMode(this.label);
|
||||
final String label;
|
||||
}
|
||||
|
||||
/// The default and smallest heights of the bottom panel, and the smallest
|
||||
/// floating window; layouts clamp to what the window allows.
|
||||
const double terminalPanelDefaultHeight = 300;
|
||||
const double terminalPanelMinHeight = 120;
|
||||
const Size terminalFloatMinSize = Size(320, 200);
|
||||
const Rect terminalFloatDefaultRect = Rect.fromLTWH(80, 80, 720, 420);
|
||||
|
||||
abstract interface class TerminalLayoutStore {
|
||||
Future<String?> load();
|
||||
Future<bool> save(String value);
|
||||
}
|
||||
|
||||
class SharedTerminalLayoutStore implements TerminalLayoutStore {
|
||||
const SharedTerminalLayoutStore();
|
||||
@override
|
||||
Future<String?> load() async {
|
||||
try {
|
||||
return (await SharedPreferences.getInstance()).getString(
|
||||
terminalLayoutKey,
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> save(String value) async {
|
||||
try {
|
||||
return await (await SharedPreferences.getInstance()).setString(
|
||||
terminalLayoutKey,
|
||||
value,
|
||||
);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The terminal surface's device-local layout: the mode, whether it is
|
||||
/// shown, the bottom panel's height and the floating window's frame and
|
||||
/// state. Every change is saved, so a reload reopens it as it was.
|
||||
class TerminalLayout extends ChangeNotifier {
|
||||
TerminalLayout({TerminalLayoutStore? store})
|
||||
: _store = store ?? const SharedTerminalLayoutStore();
|
||||
static final instance = TerminalLayout();
|
||||
final TerminalLayoutStore _store;
|
||||
int _revision = 0;
|
||||
|
||||
TerminalMode mode = TerminalMode.panel;
|
||||
bool visible = false;
|
||||
double panelHeight = terminalPanelDefaultHeight;
|
||||
Rect floatRect = terminalFloatDefaultRect;
|
||||
bool minimized = false;
|
||||
bool maximized = false;
|
||||
|
||||
/// Whether the last change could not be saved.
|
||||
bool saveFailed = false;
|
||||
|
||||
Future<void> restore() async {
|
||||
final revision = _revision;
|
||||
final raw = await _store.load();
|
||||
if (revision != _revision || raw == null) return;
|
||||
try {
|
||||
final json = jsonDecode(raw) as Map;
|
||||
mode = TerminalMode.values.asNameMap()[json['mode']] ?? mode;
|
||||
visible = json['visible'] == true;
|
||||
panelHeight = _finite(json['panel_height']) ?? panelHeight;
|
||||
final rect = json['float'];
|
||||
if (rect is List && rect.length == 4) {
|
||||
final values = rect.map(_finite).toList();
|
||||
if (!values.contains(null)) {
|
||||
floatRect = Rect.fromLTWH(
|
||||
values[0]!,
|
||||
values[1]!,
|
||||
values[2]!,
|
||||
values[3]!,
|
||||
);
|
||||
}
|
||||
}
|
||||
minimized = json['minimized'] == true;
|
||||
maximized = json['maximized'] == true;
|
||||
} catch (_) {
|
||||
return;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setMode(TerminalMode value) => _change(() => mode = value);
|
||||
void toggle() => _change(() {
|
||||
visible = !visible;
|
||||
if (visible) minimized = false;
|
||||
});
|
||||
void show() => _change(() {
|
||||
visible = true;
|
||||
minimized = false;
|
||||
});
|
||||
void hide() => _change(() => visible = false);
|
||||
void setPanelHeight(double value, {bool save = true}) =>
|
||||
_change(() => panelHeight = value, save: save);
|
||||
void setFloatRect(Rect value, {bool save = true}) =>
|
||||
_change(() => floatRect = value, save: save);
|
||||
void setMinimized(bool value) => _change(() {
|
||||
minimized = value;
|
||||
if (value) maximized = false;
|
||||
});
|
||||
void setMaximized(bool value) => _change(() {
|
||||
maximized = value;
|
||||
if (value) minimized = false;
|
||||
});
|
||||
|
||||
/// Saves the current layout (a drag saves once, when it ends).
|
||||
Future<void> save() async {
|
||||
final revision = _revision;
|
||||
final saved = await _store.save(
|
||||
jsonEncode({
|
||||
'mode': mode.name,
|
||||
'visible': visible,
|
||||
'panel_height': panelHeight,
|
||||
'float': [
|
||||
floatRect.left,
|
||||
floatRect.top,
|
||||
floatRect.width,
|
||||
floatRect.height,
|
||||
],
|
||||
'minimized': minimized,
|
||||
'maximized': maximized,
|
||||
}),
|
||||
);
|
||||
if (revision != _revision || saved != saveFailed) return;
|
||||
saveFailed = !saved;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _change(VoidCallback change, {bool save = true}) {
|
||||
_revision++;
|
||||
change();
|
||||
notifyListeners();
|
||||
if (save) unawaited(this.save());
|
||||
}
|
||||
|
||||
static double? _finite(Object? value) =>
|
||||
value is num && value.isFinite ? value.toDouble() : null;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../../core/servers/chat/chat_server_pool.dart';
|
||||
|
||||
/// One connected machine terminals can be opened on.
|
||||
@immutable
|
||||
class TerminalMachine {
|
||||
const TerminalMachine({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.gateway,
|
||||
});
|
||||
|
||||
/// The saved machine's identity (the chat pool's server id).
|
||||
final String id;
|
||||
final String name;
|
||||
|
||||
/// That machine's own authenticated connection.
|
||||
final ApiGateway gateway;
|
||||
}
|
||||
|
||||
/// The machines connected now, in the saved order.
|
||||
typedef TerminalMachines = ValueListenable<List<TerminalMachine>>;
|
||||
|
||||
/// The chat pool's connected machines: one terminal surface across every
|
||||
/// saved machine, each terminal on its own machine's socket.
|
||||
class PoolTerminalMachines extends ValueNotifier<List<TerminalMachine>> {
|
||||
PoolTerminalMachines(this.pool) : super(const []) {
|
||||
pool.addListener(_update);
|
||||
_update();
|
||||
}
|
||||
|
||||
final ChatServerPool pool;
|
||||
|
||||
void _update() {
|
||||
final next = [
|
||||
for (final machine in pool.machines)
|
||||
if (machine.connected && machine.adapter != null)
|
||||
TerminalMachine(
|
||||
id: machine.server.id,
|
||||
name: machine.server.name,
|
||||
gateway: machine.adapter!,
|
||||
),
|
||||
];
|
||||
if (!_same(next, value)) value = next;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
pool.removeListener(_update);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's one server, while its connection is up.
|
||||
class SingleTerminalMachines extends ValueNotifier<List<TerminalMachine>> {
|
||||
SingleTerminalMachines({
|
||||
required this.connection,
|
||||
required this.machine,
|
||||
required this.connected,
|
||||
}) : super(const []) {
|
||||
connection.addListener(_update);
|
||||
_update();
|
||||
}
|
||||
|
||||
final Listenable connection;
|
||||
final TerminalMachine machine;
|
||||
final bool Function() connected;
|
||||
|
||||
void _update() {
|
||||
final next = connected() ? [machine] : const <TerminalMachine>[];
|
||||
if (!_same(next, value)) value = next;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
connection.removeListener(_update);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
bool _same(List<TerminalMachine> a, List<TerminalMachine> b) =>
|
||||
a.length == b.length &&
|
||||
[
|
||||
for (var i = 0; i < a.length; i++)
|
||||
a[i].id == b[i].id &&
|
||||
a[i].name == b[i].name &&
|
||||
identical(a[i].gateway, b[i].gateway),
|
||||
].every((same) => same);
|
||||
@@ -0,0 +1,90 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// One choice of a [TerminalMenuButton].
|
||||
class TerminalChoice<T> {
|
||||
const TerminalChoice(this.value, this.label, {this.checked, this.key});
|
||||
final T value;
|
||||
final String label;
|
||||
|
||||
/// Non-null draws the choice as a checkable item.
|
||||
final bool? checked;
|
||||
final Key? key;
|
||||
}
|
||||
|
||||
/// An icon button opening the host's menu: a Material popup menu, or a
|
||||
/// Cupertino action sheet with Cancel.
|
||||
class TerminalMenuButton<T> extends StatelessWidget {
|
||||
const TerminalMenuButton({
|
||||
super.key,
|
||||
required this.cupertino,
|
||||
required this.label,
|
||||
required this.icon,
|
||||
required this.cupertinoIcon,
|
||||
required this.choices,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final bool cupertino;
|
||||
final String label;
|
||||
final IconData icon;
|
||||
final IconData cupertinoIcon;
|
||||
final List<TerminalChoice<T>> choices;
|
||||
final ValueChanged<T> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!cupertino) {
|
||||
return PopupMenuButton<T>(
|
||||
tooltip: label,
|
||||
icon: Icon(icon),
|
||||
onSelected: onSelected,
|
||||
itemBuilder: (_) => [
|
||||
for (final choice in choices)
|
||||
choice.checked == null
|
||||
? PopupMenuItem<T>(
|
||||
key: choice.key,
|
||||
value: choice.value,
|
||||
child: Text(choice.label),
|
||||
)
|
||||
: CheckedPopupMenuItem<T>(
|
||||
key: choice.key,
|
||||
value: choice.value,
|
||||
checked: choice.checked!,
|
||||
child: Text(choice.label),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: () => _sheet(context),
|
||||
child: Icon(cupertinoIcon, semanticLabel: label),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _sheet(BuildContext context) async {
|
||||
final picked = await showCupertinoModalPopup<T>(
|
||||
context: context,
|
||||
builder: (sheet) => CupertinoActionSheet(
|
||||
title: Text(label),
|
||||
actions: [
|
||||
for (final choice in choices)
|
||||
CupertinoActionSheetAction(
|
||||
key: choice.key,
|
||||
isDefaultAction: choice.checked ?? false,
|
||||
onPressed: () => Navigator.of(sheet).pop(choice.value),
|
||||
child: Text(
|
||||
choice.checked ?? false ? '${choice.label} ✓' : choice.label,
|
||||
),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.of(sheet).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (picked != null) onSelected(picked);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../../ui/adaptive/segmented_bar_overflow.dart';
|
||||
import 'terminal_scope.dart';
|
||||
|
||||
const String terminalOpenActionLabel = 'Open in terminal';
|
||||
|
||||
/// Opens a terminal in [directory] on [gateway]'s machine through the app's
|
||||
/// terminal surface; a refusal goes to [onRefused]. Does nothing outside a
|
||||
/// [TerminalScope].
|
||||
void openInTerminal(
|
||||
BuildContext context,
|
||||
ApiGateway gateway,
|
||||
String directory, {
|
||||
void Function(String refusal)? onRefused,
|
||||
}) {
|
||||
final actions = TerminalScope.maybeOf(context);
|
||||
if (actions == null) return;
|
||||
unawaited(
|
||||
actions.openAt(gateway, directory).then((refusal) {
|
||||
if (refusal != null) onRefused?.call(refusal);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// The chat actions menu's "Open in terminal" for the chat's folder, or
|
||||
/// null when the app has no terminal surface or the chat no folder.
|
||||
Widget? terminalOpenMenuAction(
|
||||
BuildContext context, {
|
||||
required ApiGateway gateway,
|
||||
required String directory,
|
||||
void Function(String refusal)? onRefused,
|
||||
}) {
|
||||
if (TerminalScope.maybeOf(context) == null || directory.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return SegmentedOverflowAction(
|
||||
key: const ValueKey<String>('chat-open-terminal-action'),
|
||||
overflowEntry: SegmentedOverflowEntry(
|
||||
label: terminalOpenActionLabel,
|
||||
icon: Icons.terminal,
|
||||
onPressed: () =>
|
||||
openInTerminal(context, gateway, directory, onRefused: onRefused),
|
||||
),
|
||||
child: const SizedBox.shrink(),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'terminal_body.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_tab_strip.dart';
|
||||
|
||||
/// Opens the terminals full screen (a narrow window has no room for a
|
||||
/// panel or a window), with the touch key toolbar. Resolves when closed;
|
||||
/// the shells keep running.
|
||||
Future<void> openTerminalPage(
|
||||
BuildContext context, {
|
||||
required TerminalHub hub,
|
||||
required TerminalLayout layout,
|
||||
required bool cupertino,
|
||||
}) {
|
||||
Widget page(BuildContext _) =>
|
||||
TerminalPage(hub: hub, layout: layout, cupertino: cupertino);
|
||||
return Navigator.of(context).push<void>(
|
||||
cupertino
|
||||
? CupertinoPageRoute<void>(builder: page)
|
||||
: MaterialPageRoute<void>(builder: page),
|
||||
);
|
||||
}
|
||||
|
||||
class TerminalPage extends StatelessWidget {
|
||||
const TerminalPage({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final body = ListenableBuilder(
|
||||
listenable: hub,
|
||||
builder: (context, _) => SafeArea(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TerminalTabStrip(
|
||||
hub: hub,
|
||||
layout: layout,
|
||||
cupertino: cupertino,
|
||||
showModes: false,
|
||||
),
|
||||
Expanded(
|
||||
child: TerminalBody(hub: hub, cupertino: cupertino, keys: true),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(middle: Text('Terminal')),
|
||||
child: Material(type: MaterialType.transparency, child: body),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Terminal')),
|
||||
body: body,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../ui/adaptive/resize_grip.dart';
|
||||
import 'terminal_body.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_tab_strip.dart';
|
||||
|
||||
/// Arrow-key step of the panel's resize handle.
|
||||
const double terminalPanelKeyStep = 24;
|
||||
|
||||
/// Space the docked panel always leaves the app above it.
|
||||
const double terminalPanelAppMin = 160;
|
||||
|
||||
/// [height] within what a window [available] tall allows the panel.
|
||||
double terminalPanelHeight(double height, double available) {
|
||||
final max = (available - terminalPanelAppMin).clamp(
|
||||
terminalPanelMinHeight,
|
||||
double.infinity,
|
||||
);
|
||||
return height.clamp(terminalPanelMinHeight, max);
|
||||
}
|
||||
|
||||
/// The terminal docked at the bottom of the window, filling the height its
|
||||
/// parent gives it (the layout's, see [terminalPanelHeight]): a resize
|
||||
/// handle on its top edge (drag, or the arrow keys), the tabs and the
|
||||
/// selected terminal.
|
||||
class TerminalPanel extends StatefulWidget {
|
||||
const TerminalPanel({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
required this.available,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
|
||||
/// The height of the window the panel shares with the app.
|
||||
final double available;
|
||||
|
||||
@override
|
||||
State<TerminalPanel> createState() => _TerminalPanelState();
|
||||
}
|
||||
|
||||
class _TerminalPanelState extends State<TerminalPanel> {
|
||||
bool _active = false;
|
||||
|
||||
double get _height =>
|
||||
terminalPanelHeight(widget.layout.panelHeight, widget.available);
|
||||
|
||||
void _resize(double height, {bool save = true}) =>
|
||||
widget.layout.setPanelHeight(
|
||||
terminalPanelHeight(height, widget.available),
|
||||
save: save,
|
||||
);
|
||||
|
||||
String _describe(double height) =>
|
||||
'${terminalPanelHeight(height, widget.available).round()} pixels';
|
||||
|
||||
KeyEventResult _key(FocusNode _, KeyEvent event) {
|
||||
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
|
||||
_resize(_height + terminalPanelKeyStep);
|
||||
} else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
|
||||
_resize(_height - terminalPanelKeyStep);
|
||||
} else {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final height = _height;
|
||||
final handle = Semantics(
|
||||
identifier: 'terminal-panel-resize',
|
||||
label: 'Terminal height',
|
||||
hint: 'Drag, or use the arrow keys, to resize the terminal',
|
||||
slider: true,
|
||||
value: _describe(height),
|
||||
increasedValue: _describe(height + terminalPanelKeyStep),
|
||||
decreasedValue: _describe(height - terminalPanelKeyStep),
|
||||
onIncrease: () => _resize(height + terminalPanelKeyStep),
|
||||
onDecrease: () => _resize(height - terminalPanelKeyStep),
|
||||
child: Focus(
|
||||
onKeyEvent: _key,
|
||||
onFocusChange: (value) => setState(() => _active = value),
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.resizeRow,
|
||||
child: GestureDetector(
|
||||
key: const ValueKey('terminal-panel-resize'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
excludeFromSemantics: true,
|
||||
dragStartBehavior: DragStartBehavior.down,
|
||||
onVerticalDragStart: (_) => setState(() => _active = true),
|
||||
onVerticalDragUpdate: (details) =>
|
||||
_resize(_height - details.delta.dy, save: false),
|
||||
onVerticalDragEnd: (_) {
|
||||
setState(() => _active = false);
|
||||
unawaited(widget.layout.save());
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Center(
|
||||
child: AdaptiveResizeGrip(compact: true, emphasized: _active),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
final surface = widget.cupertino
|
||||
? CupertinoColors.systemBackground.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.surfaceContainerLow;
|
||||
final divider = widget.cupertino
|
||||
? CupertinoColors.separator.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.outlineVariant;
|
||||
return Semantics(
|
||||
container: true,
|
||||
label: 'Terminal panel',
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: surface,
|
||||
border: Border(top: BorderSide(color: divider)),
|
||||
),
|
||||
child: Material(
|
||||
type: MaterialType.transparency,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
handle,
|
||||
TerminalTabStrip(
|
||||
hub: widget.hub,
|
||||
layout: widget.layout,
|
||||
cupertino: widget.cupertino,
|
||||
),
|
||||
Expanded(
|
||||
child: TerminalBody(
|
||||
hub: widget.hub,
|
||||
cupertino: widget.cupertino,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../../core/servers/server_scope.dart';
|
||||
|
||||
/// What screens below the app's terminal surface may ask of it.
|
||||
abstract interface class TerminalActions {
|
||||
/// Shows the terminal (panel, window or page) or hides it.
|
||||
void toggle();
|
||||
|
||||
/// Opens a new terminal in [cwd] on the machine [gateway] belongs to and
|
||||
/// shows it. Returns the refusal, or null.
|
||||
Future<String?> openAt(ApiGateway gateway, String cwd);
|
||||
}
|
||||
|
||||
/// Gives screens (a chat's header, the Files panel) the app's terminal
|
||||
/// surface. Absent in standalone screens and tests, which then offer no
|
||||
/// terminal actions.
|
||||
class TerminalScope extends InheritedWidget {
|
||||
const TerminalScope({super.key, required this.actions, required super.child});
|
||||
|
||||
final TerminalActions actions;
|
||||
|
||||
static TerminalActions? maybeOf(BuildContext context) =>
|
||||
context.dependOnInheritedWidgetOfExactType<TerminalScope>()?.actions;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(TerminalScope oldWidget) =>
|
||||
oldWidget.actions != actions;
|
||||
}
|
||||
|
||||
/// The machine id [gateway] was bound to, for a terminal opened from a
|
||||
/// chat or its Files panel.
|
||||
String? terminalMachineOf(ApiGateway gateway) => serverIdentity(gateway);
|
||||
@@ -0,0 +1,61 @@
|
||||
import 'dart:convert';
|
||||
|
||||
/// Characters of output one tab holds before its oldest are dropped (about
|
||||
/// the server's 1 MiB tail).
|
||||
const int terminalHeldLimit = 1 << 20;
|
||||
|
||||
/// The text of [text] after its first [bytes] UTF-8 bytes (a cut inside a
|
||||
/// character drops that character's remaining bytes).
|
||||
String terminalSkipBytes(String text, int bytes) {
|
||||
if (bytes <= 0) return text;
|
||||
final encoded = utf8.encode(text);
|
||||
if (bytes >= encoded.length) return '';
|
||||
var cut = bytes;
|
||||
while (cut < encoded.length && (encoded[cut] & 0xC0) == 0x80) {
|
||||
cut++;
|
||||
}
|
||||
return utf8.decode(encoded.sublist(cut), allowMalformed: true);
|
||||
}
|
||||
|
||||
/// One terminal's output as the client holds it: the text covering
|
||||
/// absolute bytes [start, end) of the server's stream named [stream].
|
||||
class TerminalStream {
|
||||
String text = '';
|
||||
int start = 0;
|
||||
int end = 0;
|
||||
String stream = '';
|
||||
|
||||
/// Whether nothing was received yet.
|
||||
bool get empty => stream.isEmpty && end == 0;
|
||||
|
||||
/// Replaces the held copy with a read of the server's retained tail.
|
||||
void reset(String output, int outputStart, String name) {
|
||||
text = output;
|
||||
start = outputStart;
|
||||
end = outputStart + utf8.encode(output).length;
|
||||
stream = name;
|
||||
_bound();
|
||||
}
|
||||
|
||||
/// Adds the part of [chunk] (covering [offset, chunkEnd)) past [end] and
|
||||
/// returns it; null when the chunk starts after [end] (a gap).
|
||||
String? add(String chunk, int offset, int chunkEnd) {
|
||||
if (chunkEnd <= end) return '';
|
||||
if (offset > end) return null;
|
||||
final fresh = terminalSkipBytes(chunk, end - offset);
|
||||
text += fresh;
|
||||
end = chunkEnd;
|
||||
_bound();
|
||||
return fresh;
|
||||
}
|
||||
|
||||
void _bound() {
|
||||
if (text.length <= terminalHeldLimit + terminalHeldLimit ~/ 2) return;
|
||||
var cut = text.length - terminalHeldLimit;
|
||||
// Never split a surrogate pair.
|
||||
final unit = text.codeUnitAt(cut);
|
||||
if (unit >= 0xDC00 && unit <= 0xDFFF) cut++;
|
||||
text = text.substring(cut);
|
||||
start = end - utf8.encode(text).length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'terminal_float.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_page.dart';
|
||||
import 'terminal_panel.dart';
|
||||
import 'terminal_scope.dart';
|
||||
|
||||
/// Below this width the terminal opens as a full-screen page.
|
||||
const double terminalNarrowWidth = 600;
|
||||
|
||||
/// Whether [event] is the terminal's toggle shortcut, Ctrl+` on every
|
||||
/// platform (Cmd+` switches windows on macOS).
|
||||
bool terminalToggleShortcut(KeyEvent event, HardwareKeyboard keyboard) =>
|
||||
event is KeyDownEvent &&
|
||||
event.logicalKey == LogicalKeyboardKey.backquote &&
|
||||
keyboard.isControlPressed &&
|
||||
!keyboard.isMetaPressed &&
|
||||
!keyboard.isAltPressed;
|
||||
|
||||
/// The app's one terminal surface around [child] (the shell): the bottom
|
||||
/// panel or the floating window on a wide window, a full-screen page on a
|
||||
/// narrow one. It owns the toggle shortcut and gives screens below it
|
||||
/// [TerminalActions] through [TerminalScope]. [child] keeps its place in
|
||||
/// the tree whatever is shown, so showing the terminal never rebuilds the
|
||||
/// app's state.
|
||||
class TerminalSurface extends StatefulWidget {
|
||||
const TerminalSurface({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
State<TerminalSurface> createState() => _TerminalSurfaceState();
|
||||
}
|
||||
|
||||
class _TerminalSurfaceState extends State<TerminalSurface>
|
||||
implements TerminalActions {
|
||||
bool _pageOpen = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
HardwareKeyboard.instance.addHandler(_key);
|
||||
widget.layout.addListener(_layoutChanged);
|
||||
// A terminal left shown before a reload reattaches at once.
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _layoutChanged());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
HardwareKeyboard.instance.removeHandler(_key);
|
||||
widget.layout.removeListener(_layoutChanged);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _layoutChanged() {
|
||||
if (mounted && widget.layout.visible && !_narrow) widget.hub.activate();
|
||||
}
|
||||
|
||||
bool get _narrow => MediaQuery.sizeOf(context).width < terminalNarrowWidth;
|
||||
|
||||
/// The shortcut is handled before the focused widget, so it toggles even
|
||||
/// while the terminal itself has the keyboard.
|
||||
bool _key(KeyEvent event) {
|
||||
if (!mounted || !terminalToggleShortcut(event, HardwareKeyboard.instance)) {
|
||||
return false;
|
||||
}
|
||||
toggle();
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
void toggle() {
|
||||
if (_narrow) {
|
||||
unawaited(_openPage());
|
||||
} else {
|
||||
widget.layout.toggle();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> openAt(ApiGateway gateway, String cwd) async {
|
||||
final machine = terminalMachineOf(gateway);
|
||||
final refusal = await widget.hub.open(machineId: machine, cwd: cwd);
|
||||
if (!mounted) return refusal;
|
||||
if (_narrow) {
|
||||
unawaited(_openPage());
|
||||
} else {
|
||||
widget.layout.show();
|
||||
}
|
||||
return refusal;
|
||||
}
|
||||
|
||||
Future<void> _openPage() async {
|
||||
widget.hub.activate();
|
||||
if (_pageOpen) return;
|
||||
_pageOpen = true;
|
||||
try {
|
||||
await openTerminalPage(
|
||||
context,
|
||||
hub: widget.hub,
|
||||
layout: widget.layout,
|
||||
cupertino: widget.cupertino,
|
||||
);
|
||||
} finally {
|
||||
_pageOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => TerminalScope(
|
||||
actions: this,
|
||||
child: ListenableBuilder(
|
||||
listenable: Listenable.merge([widget.hub, widget.layout]),
|
||||
builder: (context, child) => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final layout = widget.layout;
|
||||
final shown = layout.visible && !_narrow;
|
||||
final panel = shown && layout.mode == TerminalMode.panel;
|
||||
final float = shown && layout.mode == TerminalMode.float;
|
||||
final height = panel
|
||||
? terminalPanelHeight(layout.panelHeight, constraints.maxHeight)
|
||||
: 0.0;
|
||||
return Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
bottom: height,
|
||||
// The app above a docked panel has no system inset below it.
|
||||
child: MediaQuery.removePadding(
|
||||
context: context,
|
||||
removeBottom: panel,
|
||||
child: child!,
|
||||
),
|
||||
),
|
||||
if (panel)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
height: height,
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: TerminalPanel(
|
||||
key: const ValueKey('terminal-panel'),
|
||||
hub: widget.hub,
|
||||
layout: layout,
|
||||
cupertino: widget.cupertino,
|
||||
available: constraints.maxHeight,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (float)
|
||||
TerminalFloat(
|
||||
key: const ValueKey('terminal-float'),
|
||||
hub: widget.hub,
|
||||
layout: layout,
|
||||
cupertino: widget.cupertino,
|
||||
bounds: constraints.biggest,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
child: widget.child,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../chat/shell/chat_shell_run.dart';
|
||||
import '../chat/shell/chat_shell_terminal_session.dart';
|
||||
import '../chat/shell/chat_shell_terminals.dart';
|
||||
import 'terminal_info.dart';
|
||||
import 'terminal_stream.dart';
|
||||
|
||||
/// One open machine terminal in the app: its record, the output held for
|
||||
/// redraws, and the emulator session the panel, window and page draw (the
|
||||
/// chat shell's own, so typing, links and colours behave the same).
|
||||
///
|
||||
/// It outlives every view: hiding the panel keeps it, and reconnecting
|
||||
/// resumes its output from the last byte it holds.
|
||||
class TerminalTab extends ChangeNotifier {
|
||||
TerminalTab({
|
||||
required this.machineId,
|
||||
required this.machineName,
|
||||
required this._gateway,
|
||||
required this._info,
|
||||
}) {
|
||||
session = ChatShellTerminalSession(
|
||||
_run(),
|
||||
onInput: _input,
|
||||
onResize: _resized,
|
||||
);
|
||||
session.terminal.onTitleChange = _titled;
|
||||
}
|
||||
|
||||
final String machineId;
|
||||
String machineName;
|
||||
ApiGateway _gateway;
|
||||
TerminalInfo _info;
|
||||
late final ChatShellTerminalSession session;
|
||||
final TerminalStream _stream = TerminalStream();
|
||||
ChatShellInputPipe? _pipe;
|
||||
Timer? _resize;
|
||||
(int, int)? _sentSize;
|
||||
String _oscTitle = '';
|
||||
bool _disposed = false;
|
||||
bool _reading = false;
|
||||
bool _again = false;
|
||||
|
||||
/// False while the terminal's machine is not connected.
|
||||
bool connected = true;
|
||||
|
||||
/// The last refusal of input, a resize or a read, in the server's words.
|
||||
String? error;
|
||||
|
||||
String get key => terminalKey(machineId, _info.id);
|
||||
TerminalInfo get info => _info;
|
||||
ApiGateway get gateway => _gateway;
|
||||
|
||||
/// The window title the shell set (seen in its output or recorded by the
|
||||
/// server), else the folder it started in.
|
||||
String get title {
|
||||
if (_oscTitle.isNotEmpty) return _oscTitle;
|
||||
if (_info.title.isNotEmpty) return _info.title;
|
||||
return terminalFolderLabel(_info.cwd);
|
||||
}
|
||||
|
||||
ChatShellRun _run() => ChatShellRun(
|
||||
id: _info.id,
|
||||
command: title,
|
||||
directory: _info.cwd,
|
||||
status: _info.running ? 'running' : 'exited',
|
||||
startedAt: _info.createdAt,
|
||||
output: _stream.text,
|
||||
outputStart: _stream.start,
|
||||
outputEnd: _stream.end,
|
||||
terminal: true,
|
||||
cols: _info.cols,
|
||||
rows: _info.rows,
|
||||
);
|
||||
|
||||
/// The machine connected again (or for the first time): requests go
|
||||
/// through [gateway] and the output resumes from the held end.
|
||||
void attach(ApiGateway gateway, TerminalInfo info) {
|
||||
_gateway = gateway;
|
||||
connected = true;
|
||||
_sentSize = null;
|
||||
_update(info);
|
||||
unawaited(resume());
|
||||
}
|
||||
|
||||
void disconnected() {
|
||||
connected = false;
|
||||
_pipe = null;
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Reads what the server retains after the held end (all of it on a new
|
||||
/// stream or after a gap) and subscribes this connection to the rest.
|
||||
Future<void> resume() async {
|
||||
if (_disposed) return;
|
||||
if (_reading) {
|
||||
_again = true;
|
||||
return;
|
||||
}
|
||||
_reading = true;
|
||||
try {
|
||||
do {
|
||||
_again = false;
|
||||
final same = !_stream.empty && _info.stream == _stream.stream;
|
||||
await _read(same ? _stream.end : null);
|
||||
} while (_again && !_disposed);
|
||||
error = null;
|
||||
} catch (failure) {
|
||||
error = '$failure';
|
||||
} finally {
|
||||
_reading = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _read(int? after) async {
|
||||
final reply = await _gateway.call('terminal_output', {
|
||||
'terminal_request': {'terminal_id': _info.id, 'after': ?after},
|
||||
});
|
||||
final record = reply['terminal'];
|
||||
if (_disposed || record is! Map) return;
|
||||
final info = TerminalInfo.fromJson(record);
|
||||
_info = info;
|
||||
if (after != null && info.stream != _stream.stream) {
|
||||
// The server restarted since: its stream starts again at zero.
|
||||
return _read(null);
|
||||
}
|
||||
final output = '${record['output'] ?? ''}';
|
||||
final start = (record['output_start'] as num?)?.toInt() ?? 0;
|
||||
if (after == null || start > _stream.end) {
|
||||
_stream.reset(output, start, info.stream);
|
||||
session.replay(_run());
|
||||
} else {
|
||||
_append(output, start, start + _byteLength(output));
|
||||
}
|
||||
if (!info.running) session.finish(_run());
|
||||
}
|
||||
|
||||
/// One pushed `terminal_event` for this terminal.
|
||||
void frame(Map event) {
|
||||
final record = event['terminal'];
|
||||
if (record is Map) {
|
||||
_update(TerminalInfo.fromJson(record));
|
||||
return;
|
||||
}
|
||||
final output = '${event['output'] ?? ''}';
|
||||
final offset = (event['offset'] as num?)?.toInt() ?? 0;
|
||||
final end = (event['end'] as num?)?.toInt() ?? 0;
|
||||
_append(output, offset, end);
|
||||
}
|
||||
|
||||
void _append(String output, int offset, int end) {
|
||||
final before = _stream.end;
|
||||
final fresh = _stream.add(output, offset, end);
|
||||
if (fresh == null) {
|
||||
// Frames were missed: read the retained tail again.
|
||||
unawaited(resume());
|
||||
return;
|
||||
}
|
||||
if (fresh.isNotEmpty) session.append(_run(), fresh, before, end);
|
||||
}
|
||||
|
||||
void _update(TerminalInfo info) {
|
||||
final ended = _info.running && !info.running;
|
||||
// A lifecycle record carries no stream; keep the one the output has.
|
||||
_info = info.stream.isEmpty ? info.withStream(_stream.stream) : info;
|
||||
if (ended) {
|
||||
_resize?.cancel();
|
||||
_pipe = null;
|
||||
session.finish(_run());
|
||||
}
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _titled(String title) {
|
||||
if (title == _oscTitle) return;
|
||||
_oscTitle = title.trim();
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _input(String data) {
|
||||
if (_disposed || !connected) return;
|
||||
final id = _info.id;
|
||||
final gateway = _gateway;
|
||||
(_pipe ??= ChatShellInputPipe(
|
||||
(data) => gateway.call('terminal_input', {
|
||||
'terminal_request': {'terminal_id': id, 'data': data},
|
||||
}),
|
||||
(failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
},
|
||||
)).add(data);
|
||||
}
|
||||
|
||||
void _resized(int cols, int rows) {
|
||||
if (_disposed || !_info.running || !connected) return;
|
||||
_resize?.cancel();
|
||||
_resize = Timer(chatShellResizeDelay, () {
|
||||
if (_sentSize == (cols, rows) || !connected) return;
|
||||
_sentSize = (cols, rows);
|
||||
_gateway
|
||||
.call('terminal_resize', {
|
||||
'terminal_request': {
|
||||
'terminal_id': _info.id,
|
||||
'cols': cols,
|
||||
'rows': rows,
|
||||
},
|
||||
})
|
||||
.catchError((Object failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
return <String, dynamic>{};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_resize?.cancel();
|
||||
_pipe = null;
|
||||
session.terminal.onTitleChange = null;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
String terminalKey(String machineId, String terminalId) =>
|
||||
'$machineId/$terminalId';
|
||||
|
||||
/// The last folder of [cwd] ("~" for a home directory), for a tab title.
|
||||
String terminalFolderLabel(String cwd) {
|
||||
final parts = cwd.split('/').where((part) => part.isNotEmpty).toList();
|
||||
if (parts.isEmpty) return '/';
|
||||
if (parts.length == 2 && (parts[0] == 'Users' || parts[0] == 'home')) {
|
||||
return '~';
|
||||
}
|
||||
return parts.last;
|
||||
}
|
||||
|
||||
int _byteLength(String text) => utf8.encode(text).length;
|
||||
@@ -0,0 +1,181 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_menu.dart';
|
||||
import 'terminal_tab.dart';
|
||||
|
||||
/// The terminal's header: one tab per terminal (title, and the machine when
|
||||
/// tabs come from several), New terminal (choosing the machine when more
|
||||
/// than one is connected), the mode menu, and the host's own [trailing]
|
||||
/// window buttons.
|
||||
class TerminalTabStrip extends StatelessWidget {
|
||||
const TerminalTabStrip({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
this.trailing = const [],
|
||||
this.showModes = true,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
final List<Widget> trailing;
|
||||
|
||||
/// False on the narrow page, which has no panel or window to choose.
|
||||
final bool showModes;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final selected = hub.selected;
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
for (final (index, tab) in hub.tabs.indexed)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 4),
|
||||
child: Semantics(
|
||||
identifier: 'terminal-tab-$index',
|
||||
child: _tab(context, tab, tab == selected),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
_newTerminal(context),
|
||||
if (showModes)
|
||||
TerminalMenuButton<_Option>(
|
||||
cupertino: cupertino,
|
||||
label: 'Terminal options',
|
||||
icon: Icons.more_vert,
|
||||
cupertinoIcon: CupertinoIcons.ellipsis,
|
||||
choices: [
|
||||
for (final mode in TerminalMode.values)
|
||||
TerminalChoice(
|
||||
_Option(mode),
|
||||
mode.label,
|
||||
checked: layout.mode == mode,
|
||||
key: ValueKey('terminal-mode-${mode.name}'),
|
||||
),
|
||||
const TerminalChoice(
|
||||
_Option(null),
|
||||
'Hide terminal',
|
||||
key: ValueKey('terminal-hide'),
|
||||
),
|
||||
],
|
||||
onSelected: (option) => option.mode == null
|
||||
? layout.hide()
|
||||
: layout.setMode(option.mode!),
|
||||
),
|
||||
...trailing,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _label(TerminalTab tab) =>
|
||||
hub.multiMachine ? '${tab.title} · ${tab.machineName}' : tab.title;
|
||||
|
||||
Widget _tab(BuildContext context, TerminalTab tab, bool selected) {
|
||||
final label = Text(
|
||||
_label(tab),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: tab.info.running
|
||||
? null
|
||||
: const TextStyle(fontStyle: FontStyle.italic),
|
||||
);
|
||||
void close() => unawaited(hub.close(tab));
|
||||
if (cupertino) {
|
||||
final color = selected
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: CupertinoColors.label.resolveFrom(context);
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: () => hub.select(tab),
|
||||
child: DefaultTextStyle.merge(
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontWeight: selected ? FontWeight.w600 : null,
|
||||
),
|
||||
child: label,
|
||||
),
|
||||
),
|
||||
CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: close,
|
||||
child: const Icon(
|
||||
CupertinoIcons.xmark_circle_fill,
|
||||
semanticLabel: 'Close terminal',
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return InputChip(
|
||||
label: label,
|
||||
selected: selected,
|
||||
showCheckmark: false,
|
||||
tooltip: '${tab.machineName}: ${tab.info.cwd}',
|
||||
onSelected: (_) => hub.select(tab),
|
||||
onDeleted: close,
|
||||
deleteButtonTooltipMessage: 'Close terminal',
|
||||
);
|
||||
}
|
||||
|
||||
Widget _newTerminal(BuildContext context) {
|
||||
final machines = hub.connected;
|
||||
if (machines.length > 1) {
|
||||
return TerminalMenuButton<String>(
|
||||
cupertino: cupertino,
|
||||
label: 'New terminal',
|
||||
icon: Icons.add,
|
||||
cupertinoIcon: CupertinoIcons.add,
|
||||
choices: [
|
||||
for (final machine in machines)
|
||||
TerminalChoice(
|
||||
machine.id,
|
||||
machine.name,
|
||||
key: ValueKey('terminal-new-${machine.id}'),
|
||||
),
|
||||
],
|
||||
onSelected: (id) => unawaited(hub.open(machineId: id)),
|
||||
);
|
||||
}
|
||||
final enabled = machines.isNotEmpty;
|
||||
void open() => unawaited(hub.open());
|
||||
return cupertino
|
||||
? CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: enabled ? open : null,
|
||||
child: const Icon(
|
||||
CupertinoIcons.add,
|
||||
semanticLabel: 'New terminal',
|
||||
),
|
||||
)
|
||||
: IconButton(
|
||||
tooltip: 'New terminal',
|
||||
onPressed: enabled ? open : null,
|
||||
icon: const Icon(Icons.add),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A mode to switch to, or (null) hiding the terminal.
|
||||
class _Option {
|
||||
const _Option(this.mode);
|
||||
final TerminalMode? mode;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_scope.dart';
|
||||
|
||||
/// The shell bar's Terminal button: shows or hides the terminal (Ctrl+`).
|
||||
class TerminalToggleButton extends StatelessWidget {
|
||||
const TerminalToggleButton({
|
||||
super.key,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
});
|
||||
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
|
||||
static const String label = 'Terminal (Ctrl+`)';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final actions = TerminalScope.maybeOf(context);
|
||||
if (actions == null) return const SizedBox.shrink();
|
||||
return ListenableBuilder(
|
||||
listenable: layout,
|
||||
builder: (context, _) {
|
||||
final shown = layout.visible;
|
||||
if (cupertino) {
|
||||
return CupertinoButton(
|
||||
key: const ValueKey('shell.terminal'),
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: actions.toggle,
|
||||
child: Icon(
|
||||
CupertinoIcons.chevron_left_slash_chevron_right,
|
||||
semanticLabel: label,
|
||||
),
|
||||
);
|
||||
}
|
||||
return IconButton(
|
||||
key: const ValueKey('shell.terminal'),
|
||||
tooltip: label,
|
||||
isSelected: shown,
|
||||
onPressed: actions.toggle,
|
||||
icon: const Icon(Icons.terminal),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,13 @@ class AdaptiveShell extends StatefulWidget {
|
||||
this.onSearch,
|
||||
this.attentionCount = 0,
|
||||
this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(),
|
||||
this.barActions = const [],
|
||||
});
|
||||
|
||||
/// Actions every destination's bar ends with (the Terminal toggle), after
|
||||
/// the screen's own or Search.
|
||||
final List<Widget> barActions;
|
||||
|
||||
/// Where each destination's dragged list-pane width is kept on this device.
|
||||
final ListPaneWidthStore listPaneWidthStore;
|
||||
|
||||
@@ -409,6 +414,7 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
|
||||
tooltip: 'Search',
|
||||
icon: const Icon(Icons.search),
|
||||
),
|
||||
...widget.barActions,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
# Permanent terminal (bottom panel / floating window)
|
||||
|
||||
A full terminal available from every destination, independent of chats. It
|
||||
keeps running when the panel is hidden, the app navigates or reloads, and
|
||||
(where tmux is installed) across Pipelines server restarts.
|
||||
|
||||
## Behaviour
|
||||
|
||||
- **Modes** (Settings → Appearance → Terminal, or the terminal's own ⋮
|
||||
menu): *Bottom panel* docks under the app (the app shrinks above it,
|
||||
never hidden under it); *Floating window* is a window over the app. Both
|
||||
are toggled by the bar's Terminal button (every destination's bar ends
|
||||
with it) and **Ctrl+`** (Cmd+` is the macOS window switcher). The
|
||||
shortcut is a global key handler, so it toggles even while the terminal
|
||||
has the keyboard.
|
||||
- **Bottom panel:** resized by dragging its top edge (the app's
|
||||
`AdaptiveResizeGrip`; arrow keys too, slider semantics); its height is
|
||||
remembered. The panel always leaves the app at least 160 px.
|
||||
- **Floating window:** dragged by its title bar, resized from its lower
|
||||
right corner, double-click or Maximise fills the app (8 px margin),
|
||||
Minimise collapses it to its title bar, × hides it. Frame and state are
|
||||
remembered.
|
||||
- **Narrow windows (< 600 px):** the terminal opens as a full-screen page
|
||||
(Material/Cupertino route) with the chat terminal's key toolbar (Paste,
|
||||
Enter, Ctrl-C, Tab, Esc, arrows, and the typing field on Android/iOS).
|
||||
- **Tabs:** one per terminal; the title is the shell's OSC 0/2 title
|
||||
(followed by the emulator, also recorded by the server for the list),
|
||||
else the start folder (`~` for home). Ended terminals are italic and show
|
||||
why they ended with a Close tab button. With more than one machine
|
||||
connected (or tabs from several) each tab names its machine, and New
|
||||
terminal (+) asks which machine. ⨯ on a tab closes it, which kills the
|
||||
shell (and its tmux session).
|
||||
- **Open in terminal:** the chat header's More menu (the chat's folder,
|
||||
on the chat's machine) and a folder's ⋮ menu in the Files panel open a
|
||||
new terminal there and show the surface.
|
||||
- **Permanence:** the app's `TerminalHub` lives as long as the app; hiding
|
||||
or minimising never closes a shell. Reopening redraws the same emulator.
|
||||
The layout (mode, shown, height, frame) is saved per device, so a reload
|
||||
reopens the terminal, lists the machine's terminals and resumes each
|
||||
from its retained output. A dropped connection resumes after the last
|
||||
byte held; a restarted server (new stream) is read again from its start.
|
||||
- **Keyboard:** a focused terminal gets every key (Ctrl-C, Esc, Tab, arrows,
|
||||
Ctrl-letters); paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking
|
||||
elsewhere moves focus away normally.
|
||||
- No terminal request is sent until the terminal is first shown (or a
|
||||
terminal is opened): each connection sends one request at a time, so the
|
||||
first screen's read is never queued behind `terminal_list`.
|
||||
|
||||
## Protocol (server)
|
||||
|
||||
`internal/protocol/terminal.go`; documented in `docs/cli.md` ("Machine
|
||||
terminals"). Body `terminal_request {terminal_id?, cwd?, cols?, rows?,
|
||||
data?, after?}`.
|
||||
|
||||
- `terminal_open {cwd, cols, rows}` → `terminal` (subscribes the
|
||||
connection to its output first).
|
||||
- `terminal_list` → `terminals` (running and ended, oldest first; live
|
||||
records carry their current title, size and `stream`).
|
||||
- `terminal_input {terminal_id, data}` (UTF-8, ≤ 16 KiB, 64-request queue),
|
||||
`terminal_resize {terminal_id, cols, rows}` (clamped 20–500 × 4–200).
|
||||
- `terminal_output {terminal_id, after}` → `terminal` with `output`,
|
||||
`output_start`, `output_end`, `stream`; subscribes the connection.
|
||||
- `terminal_close {terminal_id}` → the closed record (runs off the read
|
||||
loop: it waits up to 3 s for the shell).
|
||||
- Pushed `terminal_event`: output `{terminal_id, output, offset, end}` to
|
||||
subscribed connections, lifecycle `{terminal_id, terminal}` (opened,
|
||||
title, exited, closed) to every connection. A slow connection's queue
|
||||
(256 frames) drops output; the client sees the offset gap and re-reads.
|
||||
|
||||
## Persistence
|
||||
|
||||
- **tmux present** (looked up on PATH, then /opt/homebrew/bin,
|
||||
/usr/local/bin, /usr/bin): each shell is `$SHELL -l` (else `/bin/sh`) as
|
||||
the only pane of session `pipelines-<id>` on a Pipelines-owned tmux
|
||||
server, `tmux -L pipelines -f /dev/null` (never the operator's own server
|
||||
or config; `TMUX`/`TMUX_PANE` are stripped). Options: status off, mouse
|
||||
on (wheel scrolls tmux history), history-limit 10000, escape-time 10,
|
||||
set-titles on with the pane title. The server shows it through an
|
||||
ordinary `attach-session` client in a PTY (creack/pty, the chat shell's
|
||||
`startChatShellTerminal`). On shutdown the client gets SIGHUP and the
|
||||
session stays; on start `recover` lists the DB's running terminals and
|
||||
reattaches each whose session is alive (a fresh output stream: tmux
|
||||
redraws the screen). A client that exits while its session lives is
|
||||
replaced (up to 5 times).
|
||||
- **No tmux:** the shell is a direct child; it ends with the server and is
|
||||
listed as ended with the reason ("tmux is not installed on this
|
||||
machine"); running tabs say "This shell ends if the server on <machine>
|
||||
restarts (tmux is not installed there)".
|
||||
- DB table `terminals` (additive): id, title, cwd, shell, created_at, tmux,
|
||||
status, ended_at, exit_code, reason, cols, rows. Ended records beyond 16
|
||||
are pruned. Output stays in memory (1 MiB tail per terminal).
|
||||
|
||||
## Security
|
||||
|
||||
- Only reachable through the authenticated `/connect` websocket, like chat
|
||||
shell commands; any connection of that server may list, type into or
|
||||
close its terminals.
|
||||
- The start folder must exist inside the operator's home after resolving
|
||||
symlinks (the Files panel's containment); `~`, `~/sub` and absolute paths
|
||||
are accepted, `~user` and relative paths refused.
|
||||
- Input is never logged or stored: the server skips its request log line
|
||||
for `terminal_input`/`terminal_resize`, nothing is written to the DB, and
|
||||
the client's input pipe (`ChatShellInputPipe`, shared with chat shells)
|
||||
keeps nothing once sent.
|
||||
|
||||
## Limits and known gaps
|
||||
|
||||
- 8 running terminals per machine; 1 MiB retained output per terminal.
|
||||
- A tmux shell's exit status is not reported (only direct shells have it).
|
||||
- The client transport sends one request at a time per connection, so a
|
||||
keystroke waits behind any slower request on the same machine (as chat
|
||||
shell input already does).
|
||||
- Opening a terminal elsewhere (another device) adds its tab here too: the
|
||||
tabs are the machine's terminals.
|
||||
- After a server restart the reattached output starts with tmux's redraw
|
||||
of the screen; older lines are in tmux's history (mouse wheel), not in
|
||||
the emulator's own scrollback.
|
||||
- Mobile (narrow page, soft-keyboard field) is verified by widget tests and
|
||||
a narrow Chrome capture only; no device test ran. Android/Linux builds
|
||||
were not run.
|
||||
- `test/application` and `test/features/settings` have 51 failures that are
|
||||
identical on the base commit 8f06f12d (pending `LaunchUpdateChecker`
|
||||
timers etc.); none is new.
|
||||
|
||||
## Files
|
||||
|
||||
- Server: `internal/protocol/terminal.go`, `message.go`;
|
||||
`internal/pipeline/terminals.go`, `store.go`;
|
||||
`internal/server/terminal_{manager,supervise,process,tmux,clients,title,cwd,handlers}.go`,
|
||||
`websocket.go`; tests `terminal_ws_test.go`, `terminal_restart_test.go`,
|
||||
`internal/pipeline/terminals_test.go`; `docs/cli.md`.
|
||||
- App: `lib/features/terminal/` (`terminal_{info,stream,tab,hub,machines,layout,scope,surface,panel,float,page,body,tab_strip,menu,toggle_button,open_action}.dart`),
|
||||
`lib/application/app_terminals.dart`, `pipelines_app.dart`,
|
||||
`bootstrap.dart`, `lib/shell/adaptive_shell.dart` (`barActions`),
|
||||
`lib/features/settings/settings_terminal_section.dart` (+ screen/topic
|
||||
pages), `lib/features/chat/conversation/chat_thread_view.dart` (Open in
|
||||
terminal), `lib/features/chat/files/files_panel.dart` (folder action),
|
||||
`lib/features/chat/shell/chat_shell_terminals.dart` (`ChatShellInputPipe`
|
||||
made public). Tests `test/features/terminal/`. Probe fixture
|
||||
`tool/perf/terminal_fixture.dart` (`?terminals=1`, `?terminal=panel|float`).
|
||||
|
||||
## Verification
|
||||
|
||||
Go 1.x / Flutter 3.44.6, macOS host, tmux 3.7c (/opt/homebrew/bin/tmux).
|
||||
|
||||
- `go test ./internal/protocol ./internal/pipeline ./internal/server -count=1`:
|
||||
`ok …/protocol 0.188s`, `ok …/pipeline 8.193s`, `ok …/server 69.120s`.
|
||||
Terminal tests: open/list/input/resize/output-resume/close over the
|
||||
websocket with two clients; shell exit status; cwd containment, input
|
||||
bounds, unknown ids, the 8-terminal limit; tmux survives a manager
|
||||
restart (list running, screen redrawn, shell variable kept, close kills
|
||||
the session); a killed tmux client is replaced; without tmux the stop and
|
||||
a crashed record are listed as ended with their reasons; OSC titles.
|
||||
`-race -count=4` on the terminal tests: ok. Each tmux test uses its own
|
||||
socket and removes it. `go vet`, `gofmt -l`: clean.
|
||||
`GOOS=freebsd go build ./internal/server`, `GOOS=linux go test -c`: ok.
|
||||
- `tool/memwatch/full.sh test/features/terminal`: `PASS: 15 passed`
|
||||
(hub: lazy activation, ordered output + gap re-read, reconnect resume
|
||||
and new-stream re-read, open/select/close, foreign open/close frames,
|
||||
titles and ended reason, input, multi-machine, refusals; surface: Ctrl+`
|
||||
and button toggle while the terminal has focus, hiding keeps shells,
|
||||
panel drag-resize remembered and app shrinks, float drag/resize/
|
||||
minimise/maximise, tabs select/close/new, mode switch from the menu,
|
||||
Settings mode choice, narrow full-screen page with key toolbar).
|
||||
- `tool/memwatch/full.sh test/features/chat`: `PASS: 1137 passed, 0 failed`.
|
||||
- `test/application test/shell test/features/settings`: 129 passed, 51
|
||||
failed — the same 51 failing tests as the base commit (compared by name).
|
||||
- `tool/analyze.sh`: clean. `flutter build web`: built.
|
||||
`FLUTTER_XCODE_ARCHS=arm64 flutter build macos`: built (35.0MB).
|
||||
- Real Chrome (`tool/capture`, probe `?terminals=1`, 1280x820), inspected:
|
||||
`/tmp/terminal-panel/panel-{light,dark}/01-panel.png`,
|
||||
`03-panel-three-tabs.png`, `04-panel-taller.png` (dragged up 200 px);
|
||||
`/tmp/terminal-panel/typed-{light,dark}/01-panel-tab2-typed.png` (second
|
||||
tab, `pwd`+Enter typed as key events, focused cursor);
|
||||
`/tmp/terminal-panel/float-{light,dark}/01-float.png`,
|
||||
`02-float-moved-resized.png`, `03-float-minimised.png`,
|
||||
`04-float-maximised.png`;
|
||||
`/tmp/terminal-panel/settings-light/0{1,2,3}-*.png` (Appearance →
|
||||
Terminal, choosing Floating window, then the bar button);
|
||||
`/tmp/terminal-panel/narrow-light/01-narrow-page.png` (560 px page with
|
||||
key toolbar); `/tmp/terminal-panel/cupertino-dark/0{1,2}-*.png`
|
||||
(Cupertino, two machines: tabs name their machine, New terminal asks
|
||||
which); `/tmp/terminal-panel/chat-open/02-chat-opened-terminal.png`
|
||||
(chat More → Open in terminal opened `/workspace/demo`).
|
||||
- Scratch server end to end (`go build ./cmd/pipelines-server`; `env -i`
|
||||
with HOME, XDG_DATA_HOME, DB and `TMUX_TMPDIR` under `/tmp/term-e2e`,
|
||||
OS-chosen loopback port, `SHELL=/bin/bash`; Node websocket driver
|
||||
`/tmp/term-e2e/drive.mjs`, script `/tmp/term-e2e/run.sh`; server stopped
|
||||
and tmux server gone afterwards):
|
||||
|
||||
```
|
||||
opened term_c76697ebb5a10ce7 cwd=/tmp/term-e2e/home shell=/bin/bash tmux=pipelines-term_c76697ebb5a10ce7 size=100x30
|
||||
typed command ran: before-restart-42 seen
|
||||
server 94915 stopped
|
||||
tmux sessions while the server is down:
|
||||
pipelines-term_c76697ebb5a10ce7 pane_pid=94934
|
||||
tmux scrollback while the server is down:
|
||||
line-1 / line-2 / line-3 / before-restart-42
|
||||
server pid 94951 port 62223
|
||||
list after restart: term_c76697ebb5a10ce7 running tmux=pipelines-term_c76697ebb5a10ce7 stream=e5cca0de2a86
|
||||
reattached output (1463 bytes) has earlier lines: line-1=true line-3=true before-restart-42=true
|
||||
shell state survived: KEEP=kept-across-restart
|
||||
close: terminal_close status=closed
|
||||
list after close: 0 terminals
|
||||
tmux sessions after close: no server running on /private/tmp/term-e2e/tmux/tmux-501/pipelines
|
||||
input lines logged: 0
|
||||
KEEP in log: 0
|
||||
```
|
||||
@@ -0,0 +1,151 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_machines.dart';
|
||||
|
||||
/// One machine's terminals as a server holds them, answering the terminal
|
||||
/// requests and pushing frames like the real one.
|
||||
class TerminalGateway implements ApiGateway {
|
||||
TerminalGateway({this.stream = 's1'});
|
||||
|
||||
final _frames = StreamController<JsonMap>.broadcast();
|
||||
final List<JsonMap> requests = [];
|
||||
final Map<String, JsonMap> terminals = {};
|
||||
final Map<String, String> output = {};
|
||||
String stream;
|
||||
int _next = 0;
|
||||
|
||||
/// When set, requests of this type fail with this message.
|
||||
final Map<String, String> refuse = {};
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => _frames.stream;
|
||||
|
||||
List<JsonMap> bodies(String type) => [
|
||||
for (final request in requests)
|
||||
if (request['type'] == type)
|
||||
Map<String, dynamic>.from(request['terminal_request'] as Map? ?? {}),
|
||||
];
|
||||
|
||||
JsonMap add(String id, {String cwd = '/Users/op', String text = ''}) {
|
||||
final record = <String, dynamic>{
|
||||
'id': id,
|
||||
'cwd': cwd,
|
||||
'shell': '/bin/zsh',
|
||||
'status': 'running',
|
||||
'tmux': 'pipelines-$id',
|
||||
'cols': 80,
|
||||
'rows': 24,
|
||||
'created_at': 1,
|
||||
};
|
||||
terminals[id] = record;
|
||||
output[id] = text;
|
||||
return record;
|
||||
}
|
||||
|
||||
JsonMap _record(String id, {bool withOutput = false, int after = 0}) {
|
||||
final text = output[id] ?? '';
|
||||
final bytes = utf8.encode(text);
|
||||
final start = after.clamp(0, bytes.length);
|
||||
return {
|
||||
...terminals[id]!,
|
||||
'stream': stream,
|
||||
'output_end': bytes.length,
|
||||
if (withOutput) 'output': utf8.decode(bytes.sublist(start)),
|
||||
if (withOutput) 'output_start': start,
|
||||
};
|
||||
}
|
||||
|
||||
/// The shell writes [text]: it is retained and pushed.
|
||||
void write(String id, String text, {bool push = true}) {
|
||||
final offset = utf8.encode(output[id] ?? '').length;
|
||||
output[id] = (output[id] ?? '') + text;
|
||||
if (push) {
|
||||
pushOutput(id, text, offset);
|
||||
}
|
||||
}
|
||||
|
||||
void pushOutput(String id, String text, int offset) => _frames.add({
|
||||
'type': 'terminal_event',
|
||||
'terminal_event': {
|
||||
'terminal_id': id,
|
||||
'output': text,
|
||||
'offset': offset,
|
||||
'end': offset + utf8.encode(text).length,
|
||||
},
|
||||
});
|
||||
|
||||
void lifecycle(String id, Map<String, dynamic> changes) {
|
||||
terminals[id] = {...terminals[id]!, ...changes};
|
||||
_frames.add({
|
||||
'type': 'terminal_event',
|
||||
'terminal_event': {'terminal_id': id, 'terminal': _record(id)},
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
requests.add({'type': type, ...fields});
|
||||
final refusal = refuse[type];
|
||||
if (refusal != null) throw StateError(refusal);
|
||||
final body = (fields['terminal_request'] as Map?) ?? const {};
|
||||
final id = '${body['terminal_id'] ?? ''}';
|
||||
switch (type) {
|
||||
case 'terminal_list':
|
||||
return {
|
||||
'type': type,
|
||||
'terminals': [for (final id in terminals.keys) _record(id)],
|
||||
};
|
||||
case 'terminal_open':
|
||||
final next = 'term_${++_next}';
|
||||
final cwd = '${body['cwd'] ?? ''}';
|
||||
add(next, cwd: cwd.isEmpty ? '/Users/op' : cwd, text: r'$ ');
|
||||
return {'type': type, 'terminal': _record(next)};
|
||||
case 'terminal_output':
|
||||
return {
|
||||
'type': type,
|
||||
'terminal': _record(
|
||||
id,
|
||||
withOutput: true,
|
||||
after: (body['after'] as num?)?.toInt() ?? 0,
|
||||
),
|
||||
};
|
||||
case 'terminal_close':
|
||||
final record = {..._record(id), 'status': 'closed'};
|
||||
terminals.remove(id);
|
||||
return {'type': type, 'terminal': record};
|
||||
case 'terminal_input':
|
||||
return {'type': type};
|
||||
case 'terminal_resize':
|
||||
return {'type': type, 'terminal': _record(id)};
|
||||
}
|
||||
throw StateError('unexpected $type');
|
||||
}
|
||||
|
||||
Future<void> close() => _frames.close();
|
||||
}
|
||||
|
||||
/// A machine list tests change by hand.
|
||||
class TestMachines extends ValueNotifier<List<TerminalMachine>> {
|
||||
TestMachines(super.value);
|
||||
}
|
||||
|
||||
TerminalMachine machine(String id, TerminalGateway gateway, {String? name}) =>
|
||||
TerminalMachine(id: id, name: name ?? id, gateway: gateway);
|
||||
|
||||
/// A layout store kept in memory.
|
||||
class MemoryLayoutStore implements TerminalLayoutStore {
|
||||
String? saved;
|
||||
int saves = 0;
|
||||
@override
|
||||
Future<String?> load() async => saved;
|
||||
@override
|
||||
Future<bool> save(String value) async {
|
||||
saved = value;
|
||||
saves++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_tab.dart';
|
||||
import 'package:xterm/core.dart';
|
||||
|
||||
import 'terminal_fixtures.dart';
|
||||
|
||||
String screen(TerminalTab tab) {
|
||||
final buffer = tab.session.terminal.buffer;
|
||||
return [
|
||||
for (var y = 0; y < buffer.height; y++)
|
||||
buffer.lines[y].getText().trimRight(),
|
||||
].where((line) => line.isNotEmpty).join('\n');
|
||||
}
|
||||
|
||||
void main() {
|
||||
late TerminalGateway mac;
|
||||
late TestMachines machines;
|
||||
late TerminalHub hub;
|
||||
|
||||
setUp(() {
|
||||
mac = TerminalGateway();
|
||||
machines = TestMachines([machine('mac', mac, name: 'Mac')]);
|
||||
hub = TerminalHub(machines);
|
||||
});
|
||||
tearDown(() async {
|
||||
hub.dispose();
|
||||
await mac.close();
|
||||
});
|
||||
|
||||
Future<void> settle() => Future<void>.delayed(Duration.zero);
|
||||
|
||||
test('nothing is requested until the terminal is first shown', () async {
|
||||
mac.add('term_a', text: 'hello\r\n');
|
||||
await settle();
|
||||
expect(mac.requests, isEmpty);
|
||||
hub.activate();
|
||||
await settle();
|
||||
await settle();
|
||||
expect(mac.requests.map((r) => r['type']), [
|
||||
'terminal_list',
|
||||
'terminal_output',
|
||||
]);
|
||||
expect(hub.tabs.single.title, '~');
|
||||
expect(screen(hub.tabs.single), 'hello');
|
||||
});
|
||||
|
||||
test('live output appends in order; a gap reads the tail again', () async {
|
||||
mac.add('term_a', text: r'$ ');
|
||||
hub.activate();
|
||||
await settle();
|
||||
await settle();
|
||||
final tab = hub.tabs.single;
|
||||
mac.write('term_a', 'ls\r\nREADME\r\n');
|
||||
await settle();
|
||||
expect(screen(tab), '\$ ls\nREADME');
|
||||
// A frame the client missed: the next one starts after its end.
|
||||
mac.write('term_a', 'missed\r\n', push: false);
|
||||
mac.write('term_a', 'after\r\n');
|
||||
await settle();
|
||||
await settle();
|
||||
expect(screen(tab), '\$ ls\nREADME\nmissed\nafter');
|
||||
final reads = mac.bodies('terminal_output');
|
||||
expect(reads.last['after'], greaterThan(0));
|
||||
});
|
||||
|
||||
test('a reconnect resumes after the held end; a restarted server '
|
||||
'(new stream) is read again from its start', () async {
|
||||
mac.add('term_a', text: 'one\r\n');
|
||||
hub.activate();
|
||||
await settle();
|
||||
await settle();
|
||||
final tab = hub.tabs.single;
|
||||
machines.value = [];
|
||||
await settle();
|
||||
expect(tab.connected, isFalse);
|
||||
mac.write('term_a', 'two\r\n', push: false);
|
||||
final again = TerminalGateway()
|
||||
..terminals.addAll(mac.terminals)
|
||||
..output.addAll(mac.output);
|
||||
machines.value = [machine('mac', again, name: 'Mac')];
|
||||
await settle();
|
||||
await settle();
|
||||
expect(identical(hub.tabs.single, tab), isTrue);
|
||||
expect(tab.connected, isTrue);
|
||||
expect(again.bodies('terminal_output').single['after'], 5);
|
||||
expect(screen(tab), 'one\ntwo');
|
||||
// The server restarted: the tmux client redrew the screen into a new
|
||||
// stream starting at zero.
|
||||
machines.value = [];
|
||||
await settle();
|
||||
final restarted = TerminalGateway(stream: 's2')
|
||||
..terminals.addAll(mac.terminals)
|
||||
..output['term_a'] = 'one\r\ntwo\r\n\$ ';
|
||||
machines.value = [machine('mac', restarted, name: 'Mac')];
|
||||
await settle();
|
||||
await settle();
|
||||
await settle();
|
||||
expect(
|
||||
restarted.bodies('terminal_output').last.containsKey('after'),
|
||||
isFalse,
|
||||
);
|
||||
expect(screen(tab), 'one\ntwo\n\$');
|
||||
await again.close();
|
||||
await restarted.close();
|
||||
});
|
||||
|
||||
test('open selects a new tab; close removes it; another client\'s '
|
||||
'terminal appears and its close removes it', () async {
|
||||
expect(await hub.open(cwd: '/Users/op/src'), isNull);
|
||||
await settle();
|
||||
expect(mac.bodies('terminal_open').single['cwd'], '/Users/op/src');
|
||||
final first = hub.selected!;
|
||||
expect(first.title, 'src');
|
||||
expect(await hub.open(), isNull);
|
||||
await settle();
|
||||
expect(hub.tabs, hasLength(2));
|
||||
expect(hub.selected, isNot(first));
|
||||
hub.select(first);
|
||||
expect(hub.selected, first);
|
||||
expect(await hub.close(first), isNull);
|
||||
expect(hub.tabs, hasLength(1));
|
||||
mac.add('term_other');
|
||||
mac.lifecycle('term_other', {});
|
||||
await settle();
|
||||
await settle();
|
||||
expect(hub.tabs, hasLength(2));
|
||||
mac.lifecycle('term_other', {'status': 'closed'});
|
||||
await settle();
|
||||
expect(hub.tabs, hasLength(1));
|
||||
});
|
||||
|
||||
test(
|
||||
'the shell title wins over the folder; an ended terminal says why',
|
||||
() async {
|
||||
mac.add('term_a', text: '\x1b]0;vim notes.md\x07');
|
||||
hub.activate();
|
||||
await settle();
|
||||
await settle();
|
||||
final tab = hub.tabs.single;
|
||||
expect(tab.title, 'vim notes.md');
|
||||
expect(tab.session.live, isTrue);
|
||||
mac.lifecycle('term_a', {
|
||||
'status': 'exited',
|
||||
'reason':
|
||||
'The Pipelines server restarted and this shell ended with it.',
|
||||
});
|
||||
await settle();
|
||||
expect(tab.session.live, isFalse);
|
||||
expect(tab.info.endedText, contains('ended with it'));
|
||||
},
|
||||
);
|
||||
|
||||
test('typed input and the laid-out size go to the server', () async {
|
||||
mac.add('term_a');
|
||||
hub.activate();
|
||||
await settle();
|
||||
await settle();
|
||||
final tab = hub.tabs.single;
|
||||
tab.session.terminal.textInput('ls');
|
||||
tab.session.terminal.keyInput(TerminalKey.enter);
|
||||
await settle();
|
||||
expect(
|
||||
mac.bodies('terminal_input').map((body) => body['data']).join(),
|
||||
'ls\r',
|
||||
);
|
||||
});
|
||||
|
||||
test('several machines: New terminal opens on the chosen one, tabs name '
|
||||
'their machine', () async {
|
||||
final linux = TerminalGateway();
|
||||
machines.value = [
|
||||
machine('mac', mac, name: 'Mac'),
|
||||
machine('linux', linux, name: 'Linux'),
|
||||
];
|
||||
hub.activate();
|
||||
await settle();
|
||||
expect(hub.multiMachine, isTrue);
|
||||
expect(await hub.open(machineId: 'linux'), isNull);
|
||||
expect(linux.bodies('terminal_open'), hasLength(1));
|
||||
expect(mac.bodies('terminal_open'), isEmpty);
|
||||
expect(hub.selected!.machineName, 'Linux');
|
||||
expect(await hub.open(machineId: 'gone'), contains('No machine'));
|
||||
await linux.close();
|
||||
});
|
||||
|
||||
test('a refused open is kept for the surface to show', () async {
|
||||
mac.refuse['terminal_open'] = 'this machine already has 8 open terminals';
|
||||
expect(await hub.open(), contains('8 open terminals'));
|
||||
expect(hub.error, contains('8 open terminals'));
|
||||
expect(hub.tabs, isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_keys.dart';
|
||||
import 'package:pipelines_app/features/settings/settings_terminal_section.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_float.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_surface.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_toggle_button.dart';
|
||||
import 'package:xterm/xterm.dart';
|
||||
|
||||
import 'terminal_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
late TerminalGateway mac;
|
||||
late TerminalHub hub;
|
||||
late MemoryLayoutStore store;
|
||||
late TerminalLayout layout;
|
||||
|
||||
setUp(() {
|
||||
mac = TerminalGateway()
|
||||
..add('term_a', cwd: '/Users/op/src', text: 'alpha\r\n')
|
||||
..add('term_b', cwd: '/Users/op/docs', text: 'beta\r\n');
|
||||
hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')]));
|
||||
store = MemoryLayoutStore();
|
||||
layout = TerminalLayout(store: store);
|
||||
});
|
||||
tearDown(() async {
|
||||
hub.dispose();
|
||||
await mac.close();
|
||||
});
|
||||
|
||||
Future<void> pumpApp(
|
||||
WidgetTester tester, {
|
||||
Size size = const Size(1200, 800),
|
||||
}) async {
|
||||
tester.view.physicalSize = size;
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: TerminalSurface(
|
||||
hub: hub,
|
||||
layout: layout,
|
||||
cupertino: false,
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('App'),
|
||||
actions: [TerminalToggleButton(layout: layout, cupertino: false)],
|
||||
),
|
||||
body: const TextField(key: Key('app-field')),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<void> ctrlBacktick(WidgetTester tester) async {
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.backquote);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Map<String, dynamic> saved() =>
|
||||
jsonDecode(store.saved!) as Map<String, dynamic>;
|
||||
|
||||
testWidgets('Ctrl+` and the bar button toggle the bottom panel; hiding '
|
||||
'keeps every shell', (tester) async {
|
||||
await pumpApp(tester);
|
||||
expect(find.byKey(const ValueKey('terminal-panel')), findsNothing);
|
||||
await ctrlBacktick(tester);
|
||||
expect(find.byKey(const ValueKey('terminal-panel')), findsOneWidget);
|
||||
expect(find.text('src'), findsOneWidget);
|
||||
expect(find.text('docs'), findsOneWidget);
|
||||
expect(saved()['visible'], isTrue);
|
||||
// The terminal has the keyboard, yet the shortcut still hides it.
|
||||
await tester.tap(find.byType(TerminalView));
|
||||
await tester.pump();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.keyX);
|
||||
await tester.pump();
|
||||
expect(mac.bodies('terminal_input').last['data'], 'x');
|
||||
await ctrlBacktick(tester);
|
||||
expect(find.byKey(const ValueKey('terminal-panel')), findsNothing);
|
||||
expect(hub.tabs, hasLength(2));
|
||||
expect(mac.bodies('terminal_close'), isEmpty);
|
||||
await tester.tap(find.byTooltip(TerminalToggleButton.label));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const ValueKey('terminal-panel')), findsOneWidget);
|
||||
// Reopening draws the same emulator, output and all.
|
||||
expect(find.byType(TerminalView), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('the panel resizes from its top edge and remembers its height', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpApp(tester);
|
||||
await ctrlBacktick(tester);
|
||||
final before = tester
|
||||
.getSize(find.byKey(const ValueKey('terminal-panel')))
|
||||
.height;
|
||||
expect(before, terminalPanelDefaultHeight);
|
||||
await tester.drag(
|
||||
find.byKey(const ValueKey('terminal-panel-resize')),
|
||||
const Offset(0, -120),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final after = tester
|
||||
.getSize(find.byKey(const ValueKey('terminal-panel')))
|
||||
.height;
|
||||
expect(after, closeTo(before + 120, 1));
|
||||
expect(saved()['panel_height'], closeTo(after, 1));
|
||||
// The app above shrinks rather than hiding under it.
|
||||
final field = tester.getRect(find.byType(Scaffold).first);
|
||||
expect(field.bottom, closeTo(800 - after, 1));
|
||||
final restored = TerminalLayout(store: store);
|
||||
await restored.restore();
|
||||
expect(restored.panelHeight, closeTo(after, 1));
|
||||
expect(restored.visible, isTrue);
|
||||
// The resized terminal tells the server its new size.
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
expect(mac.bodies('terminal_resize'), isNotEmpty);
|
||||
});
|
||||
|
||||
testWidgets('the floating window moves, resizes, minimises and maximises', (
|
||||
tester,
|
||||
) async {
|
||||
layout
|
||||
..setMode(TerminalMode.float)
|
||||
..show();
|
||||
await pumpApp(tester);
|
||||
await tester.pump();
|
||||
final window = find.byKey(const ValueKey('terminal-float'));
|
||||
expect(window, findsOneWidget);
|
||||
final start = layout.floatRect;
|
||||
await tester.drag(
|
||||
find.byKey(const ValueKey('terminal-float-title')),
|
||||
const Offset(60, 40),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(layout.floatRect.topLeft, start.topLeft + const Offset(60, 40));
|
||||
await tester.drag(
|
||||
find.byKey(const ValueKey('terminal-float-resize')),
|
||||
const Offset(80, 50),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(layout.floatRect.size, start.size + const Offset(80, 50));
|
||||
expect(saved()['float'][2], closeTo(start.width + 80, 1));
|
||||
await tester.tap(find.byTooltip('Minimise'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(TerminalView), findsNothing);
|
||||
expect(hub.tabs, hasLength(2));
|
||||
await tester.tap(find.byTooltip('Restore'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(TerminalView), findsOneWidget);
|
||||
await tester.tap(find.byTooltip('Maximise'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
tester.getRect(
|
||||
find.descendant(of: window, matching: find.byType(Material)).first,
|
||||
),
|
||||
const Rect.fromLTWH(0, 0, 1200, 800).deflate(terminalFloatMargin),
|
||||
);
|
||||
await tester.tap(find.byTooltip('Restore size'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(layout.maximized, isFalse);
|
||||
});
|
||||
|
||||
testWidgets('tabs select and close their terminals; New terminal opens one', (
|
||||
tester,
|
||||
) async {
|
||||
layout.show();
|
||||
await pumpApp(tester);
|
||||
await tester.pumpAndSettle();
|
||||
expect(hub.selected!.info.id, 'term_a');
|
||||
await tester.tap(find.text('docs'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(hub.selected!.info.id, 'term_b');
|
||||
await tester.tap(find.byTooltip('New terminal'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(mac.bodies('terminal_open'), hasLength(1));
|
||||
expect(hub.tabs, hasLength(3));
|
||||
expect(hub.selected!.info.id, 'term_1');
|
||||
await tester.tap(find.byTooltip('Close terminal').first);
|
||||
await tester.pumpAndSettle();
|
||||
expect(mac.bodies('terminal_close').single['terminal_id'], 'term_a');
|
||||
expect(find.text('src'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('the options menu switches between panel and window', (
|
||||
tester,
|
||||
) async {
|
||||
layout.show();
|
||||
await pumpApp(tester);
|
||||
await tester.tap(find.byTooltip('Terminal options'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const ValueKey('terminal-mode-float')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(layout.mode, TerminalMode.float);
|
||||
expect(find.byKey(const ValueKey('terminal-float')), findsOneWidget);
|
||||
expect(find.byKey(const ValueKey('terminal-panel')), findsNothing);
|
||||
expect(saved()['mode'], 'float');
|
||||
await tester.tap(find.byTooltip('Terminal options'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const ValueKey('terminal-hide')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const ValueKey('terminal-float')), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('Settings chooses the mode', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: SingleChildScrollView(
|
||||
child: SettingsTerminalSection(layout: layout),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('Terminal'), findsOneWidget);
|
||||
await tester.tap(find.byKey(const ValueKey('settings-terminal-float')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(layout.mode, TerminalMode.float);
|
||||
await tester.tap(find.byKey(const ValueKey('settings-terminal-panel')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(layout.mode, TerminalMode.panel);
|
||||
});
|
||||
|
||||
testWidgets('a narrow window opens the terminal full screen with the key '
|
||||
'toolbar', (tester) async {
|
||||
layout.show();
|
||||
await pumpApp(tester, size: const Size(390, 800));
|
||||
// The panel is not drawn on a phone even when left shown.
|
||||
expect(find.byKey(const ValueKey('terminal-panel')), findsNothing);
|
||||
await tester.tap(find.byTooltip(TerminalToggleButton.label));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.widgetWithText(AppBar, 'Terminal'), findsOneWidget);
|
||||
expect(find.byType(TerminalView), findsOneWidget);
|
||||
expect(find.byType(ChatShellTerminalKeys), findsOneWidget);
|
||||
await tester.tap(find.byKey(const Key('chat-shell-key-ctrl-c')));
|
||||
await tester.pump();
|
||||
expect(mac.bodies('terminal_input').last['data'], '\x03');
|
||||
await tester.pageBack();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(TerminalView), findsNothing);
|
||||
expect(hub.tabs, hasLength(2));
|
||||
});
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import 'chat_new_session_fixture.dart';
|
||||
import 'chat_turn_diff_fixture.dart';
|
||||
import 'chat_question_fixture.dart';
|
||||
import 'chat_shell_fixture.dart';
|
||||
import 'terminal_fixture.dart';
|
||||
import 'chat_shown_fixture.dart';
|
||||
import 'chat_scroll_fixture.dart';
|
||||
|
||||
@@ -42,6 +43,7 @@ void configurePerfFixture(Map<String, String> params) {
|
||||
configureChatScrollFixture(params);
|
||||
configureChatQuestionFixture(params);
|
||||
configureChatShellFixture(params);
|
||||
configureTerminalFixture(params);
|
||||
}
|
||||
|
||||
int get _hits => int.tryParse(_params['hits'] ?? '') ?? 0;
|
||||
@@ -132,6 +134,8 @@ bool get _scrollVariety => ['msgs', 'rich', 'older'].any(_params.containsKey);
|
||||
|
||||
/// Unsolicited envelopes that follow a reply: the `?quota=` usage frame.
|
||||
List<JsonMap> perfChatFollowUps(JsonMap request) {
|
||||
final terminal = terminalFixtureFollowUps(request);
|
||||
if (terminal.isNotEmpty) return terminal;
|
||||
final answered = chatQuestionFollowUps(request);
|
||||
if (answered.isNotEmpty) return answered;
|
||||
final shell = chatShellFollowUps(request);
|
||||
@@ -233,6 +237,8 @@ String _answer(int i) =>
|
||||
|
||||
/// Chat replies for `?chats=N`, or null to fall through to the fixture.
|
||||
JsonMap? perfChatReply(JsonMap request) {
|
||||
final terminal = terminalFixtureReply(request);
|
||||
if (terminal != null) return terminal;
|
||||
if (_chats == 0) return null;
|
||||
final question = chatQuestionReply(request);
|
||||
if (question != null) return question;
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
// Machine terminals for the full-app probe (`?terminals=1`): the machine
|
||||
// lists two running tmux-backed shells (a coloured `go test` run and a
|
||||
// home shell) and terminal_open/input/resize/output/close answer as the
|
||||
// server does, with the output frames that follow. Typed text is echoed and
|
||||
// Enter prints a fresh prompt. `?terminal=panel` or `?terminal=float` opens
|
||||
// the terminal at launch in that mode.
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
|
||||
|
||||
bool _enabled = false;
|
||||
final Map<String, JsonMap> _terminals = {};
|
||||
final Map<String, String> _output = {};
|
||||
int _opened = 0;
|
||||
|
||||
const String _prompt = '\x1b[1;32moperator@mac\x1b[0m:\x1b[1;34m%s\x1b[0m\$ ';
|
||||
|
||||
String _promptAt(String folder) => _prompt.replaceFirst('%s', folder);
|
||||
|
||||
void configureTerminalFixture(Map<String, String> params) {
|
||||
_enabled = params['terminals'] == '1';
|
||||
if (!_enabled) return;
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
_terminals
|
||||
..clear()
|
||||
..['term_build'] = _record(
|
||||
'term_build',
|
||||
'/Users/operator/src/pipelines',
|
||||
now - 600000,
|
||||
title: 'go test ./internal/server',
|
||||
)
|
||||
..['term_home'] = _record('term_home', '/Users/operator', now - 300000);
|
||||
_output
|
||||
..clear()
|
||||
..['term_build'] =
|
||||
'${_promptAt('~/src/pipelines')}go test ./internal/server -run Terminal\r\n'
|
||||
'\x1b[32m=== RUN\x1b[0m TestTerminalOverWebsocket\r\n'
|
||||
'\x1b[32m--- PASS\x1b[0m: TestTerminalOverWebsocket (0.19s)\r\n'
|
||||
'\x1b[32m=== RUN\x1b[0m TestTerminalTmuxSurvivesRestart\r\n'
|
||||
'\x1b[32m--- PASS\x1b[0m: TestTerminalTmuxSurvivesRestart (0.27s)\r\n'
|
||||
'\x1b[33m--- SKIP\x1b[0m: TestTerminalWindows (0.00s)\r\n'
|
||||
'\x1b[1;32mok\x1b[0m \tgit.a-wan.net/alan/pipelines/internal/server\t2.758s\r\n'
|
||||
'${_promptAt('~/src/pipelines')}'
|
||||
..['term_home'] =
|
||||
'${_promptAt('~')}ls\r\n'
|
||||
'\x1b[1;34mDesktop\x1b[0m \x1b[1;34mDocuments\x1b[0m '
|
||||
'\x1b[1;34mDownloads\x1b[0m \x1b[1;34msrc\x1b[0m notes.md\r\n'
|
||||
'${_promptAt('~')}';
|
||||
final mode = switch (params['terminal']) {
|
||||
'panel' => TerminalMode.panel,
|
||||
'float' => TerminalMode.float,
|
||||
_ => null,
|
||||
};
|
||||
if (mode != null) {
|
||||
TerminalLayout.instance
|
||||
..mode = mode
|
||||
..visible = true;
|
||||
}
|
||||
}
|
||||
|
||||
JsonMap _record(String id, String cwd, int created, {String title = ''}) => {
|
||||
'id': id,
|
||||
'cwd': cwd,
|
||||
'title': title,
|
||||
'shell': '/bin/zsh',
|
||||
'created_at': created,
|
||||
'tmux': 'pipelines-$id',
|
||||
'status': 'running',
|
||||
'cols': 100,
|
||||
'rows': 24,
|
||||
};
|
||||
|
||||
JsonMap _withOutput(String id, int after) {
|
||||
final bytes = utf8.encode(_output[id] ?? '');
|
||||
final start = after.clamp(0, bytes.length);
|
||||
return {
|
||||
..._terminals[id]!,
|
||||
'stream': 'fixture',
|
||||
'output_end': bytes.length,
|
||||
'output': utf8.decode(bytes.sublist(start)),
|
||||
'output_start': start,
|
||||
};
|
||||
}
|
||||
|
||||
JsonMap _body(JsonMap request) =>
|
||||
Map<String, dynamic>.from(request['terminal_request'] as Map? ?? {});
|
||||
|
||||
JsonMap? terminalFixtureReply(JsonMap request) {
|
||||
if (!_enabled) return null;
|
||||
final id = request['id'];
|
||||
final type = '${request['type']}';
|
||||
final body = _body(request);
|
||||
final terminal = '${body['terminal_id'] ?? ''}';
|
||||
switch (type) {
|
||||
case 'terminal_list':
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
'terminals': [
|
||||
for (final key in _terminals.keys)
|
||||
{..._terminals[key]!, 'stream': 'fixture'},
|
||||
],
|
||||
};
|
||||
case 'terminal_open':
|
||||
final next = 'term_new${++_opened}';
|
||||
final cwd = '${body['cwd'] ?? ''}';
|
||||
_terminals[next] = _record(
|
||||
next,
|
||||
cwd.isEmpty ? '/Users/operator' : cwd,
|
||||
DateTime.now().millisecondsSinceEpoch,
|
||||
);
|
||||
_output[next] = _promptAt(cwd.isEmpty ? '~' : cwd);
|
||||
return {'id': id, 'type': type, 'terminal': _terminals[next]};
|
||||
case 'terminal_output':
|
||||
if (!_terminals.containsKey(terminal)) break;
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
'terminal': _withOutput(
|
||||
terminal,
|
||||
(body['after'] as num?)?.toInt() ?? 0,
|
||||
),
|
||||
};
|
||||
case 'terminal_input':
|
||||
case 'terminal_resize':
|
||||
return {'id': id, 'type': type};
|
||||
case 'terminal_close':
|
||||
final record = _terminals.remove(terminal);
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
'terminal': {...?record, 'status': 'closed'},
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The output the shell writes after typed input: the echo, and a new
|
||||
/// prompt on Enter.
|
||||
List<JsonMap> terminalFixtureFollowUps(JsonMap request) {
|
||||
if (!_enabled || request['type'] != 'terminal_input') return const [];
|
||||
final body = _body(request);
|
||||
final terminal = '${body['terminal_id'] ?? ''}';
|
||||
if (!_terminals.containsKey(terminal)) return const [];
|
||||
final data = '${body['data'] ?? ''}';
|
||||
final folder = terminal == 'term_build' ? '~/src/pipelines' : '~';
|
||||
final echo = data.replaceAll('\r', '\r\n${_promptAt(folder)}');
|
||||
final offset = utf8.encode(_output[terminal]!).length;
|
||||
_output[terminal] = _output[terminal]! + echo;
|
||||
return [
|
||||
{
|
||||
'type': 'terminal_event',
|
||||
'terminal_event': {
|
||||
'terminal_id': terminal,
|
||||
'output': echo,
|
||||
'offset': offset,
|
||||
'end': offset + utf8.encode(echo).length,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -782,6 +782,8 @@ class _FixtureSink implements WebSocketSink {
|
||||
/// `?perf=1` prints frame timings (tool/perf/frame_log.dart);
|
||||
/// `?hits=N`, `?chats=N` and `?graph=1` add bench data
|
||||
/// (tool/perf/perf_fixture.dart);
|
||||
/// `?terminals=1` lists two machine terminals, and `?terminal=panel` or
|
||||
/// `?terminal=float` opens them at launch (tool/perf/terminal_fixture.dart);
|
||||
/// `?theme=dark` / `?theme=light` pins the platform brightness the app's
|
||||
/// `ThemeMode.system` follows (omitted: the browser's color scheme).
|
||||
///
|
||||
|
||||
Reference in New Issue
Block a user