Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Say when a shared harness is not running, and tidy the shared view (#425)

Jacob Pham64f2657fa7a4
diff --git a/desktop/lib/sharing/shared_agent_page.dart b/desktop/lib/sharing/shared_agent_page.dart
index a8fb7dbd0..0cc483c11 100644
--- a/desktop/lib/sharing/shared_agent_page.dart
+++ b/desktop/lib/sharing/shared_agent_page.dart
@@ -148,7 +148,7 @@ class _SharedAgentPageState extends State<SharedAgentPage> {
child: Column(
children: [
Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Row(
children: [
Link(
diff --git a/desktop/lib/sharing/shared_harness_bar.dart b/desktop/lib/sharing/shared_harness_bar.dart
new file mode 100644
index 000000000..1c8229ce9
--- /dev/null
+++ b/desktop/lib/sharing/shared_harness_bar.dart
@@ -0,0 +1,227 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/theme/workspace_bar_style.dart';
+import '../widgets/terminal_text_action.dart';
+import '../widgets/workspace_bar_control.dart';
+
+/// What a reader of a shared harness is looking at, most urgent first.
+enum SharedPaneStatus {
+ ended('Sharing ended'),
+ reconnecting('Reconnecting'),
+ notRunning('Not running'),
+ live('Live');
+
+ const SharedPaneStatus(this.label);
+ final String label;
+
+ static SharedPaneStatus of({
+ required bool ended,
+ required bool connected,
+ required bool terminalStopped,
+ }) {
+ if (ended) return SharedPaneStatus.ended;
+ if (!connected) return SharedPaneStatus.reconnecting;
+ if (terminalStopped) return SharedPaneStatus.notRunning;
+ return SharedPaneStatus.live;
+ }
+
+ /// Why the screen may be empty, shown under the bar; null when it is not.
+ String? get notice => this == SharedPaneStatus.notRunning
+ ? 'The owner’s harness isn’t running right now. '
+ 'This view reconnects when it starts again.'
+ : null;
+
+ Color get color => switch (this) {
+ SharedPaneStatus.live => grid.AppPalette.online,
+ SharedPaneStatus.reconnecting => grid.AppPalette.warn,
+ SharedPaneStatus.notRunning ||
+ SharedPaneStatus.ended => grid.AppPalette.textFaint,
+ };
+}
+
+/// The one bar above a shared harness: name, state and read-only label on the
+/// left, the reader's actions on the right. Workspace bar type and height, so a
+/// shared pane reads like any other pane header.
+class SharedHarnessBar extends StatelessWidget {
+ const SharedHarnessBar({
+ super.key,
+ required this.name,
+ required this.status,
+ required this.commentsSelected,
+ required this.onToggleComments,
+ required this.onClose,
+ this.detail,
+ this.viewerSelected,
+ this.onSelectViewer,
+ this.onRetry,
+ });
+
+ final String name;
+ final String? detail;
+ final SharedPaneStatus status;
+ final bool commentsSelected;
+ final VoidCallback onToggleComments;
+ final VoidCallback onClose;
+
+ /// Null hides the Terminal/Viewer switch: the pane shows one of them only.
+ final bool? viewerSelected;
+ final ValueChanged<bool>? onSelectViewer;
+ final VoidCallback? onRetry;
+
+ /// Below this width the actions move to a second row instead of squeezing
+ /// the name to nothing.
+ static const narrowWidth = 640.0;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final cell = workspaceBarCellSizeOf(context);
+ final height = workspaceBarControlHeight(context);
+ Widget row(List<Widget> children) => SizedBox(
+ height: height,
+ child: Row(children: children),
+ );
+ return Container(
+ padding: EdgeInsets.symmetric(horizontal: cell.width),
+ color: grid.AppSurface.recess,
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final identity = _identity(cell);
+ final actions = _actions(cell);
+ if (constraints.maxWidth >= narrowWidth) {
+ return row([Expanded(child: Row(children: identity)), ...actions]);
+ }
+ return Column(
+ children: [
+ row(identity),
+ row([const Spacer(), ...actions]),
+ ],
+ );
+ },
+ ),
+ );
+ }
+
+ List<Widget> _identity(Size cell) {
+ final muted = workspaceBarTextStyle(color: grid.AppPalette.textSecondary);
+ return [
+ Flexible(
+ child: Text(
+ name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: workspaceBarTextStyle(
+ color: grid.AppPalette.textPrimary,
+ emphasized: true,
+ ),
+ ),
+ ),
+ if (detail case final detail?)
+ Text(' · $detail', maxLines: 1, style: muted),
+ SizedBox(width: cell.width * 2),
+ Text('●', style: workspaceBarTextStyle(color: status.color)),
+ SizedBox(width: cell.width),
+ Text(status.label, style: muted),
+ Text(' · ', style: muted),
+ Text('View only', style: muted),
+ ];
+ }
+
+ List<Widget> _actions(Size cell) {
+ final viewer = viewerSelected;
+ return [
+ if (viewer != null && onSelectViewer != null) ...[
+ _ViewTab(
+ label: 'Terminal',
+ selected: !viewer,
+ onPressed: () => onSelectViewer!(false),
+ ),
+ _ViewTab(
+ label: 'Viewer',
+ selected: viewer,
+ onPressed: () => onSelectViewer!(true),
+ ),
+ SizedBox(width: cell.width),
+ ],
+ if (onRetry case final retry?)
+ TerminalTextAction(label: 'Retry', onPressed: retry),
+ TerminalTextAction(
+ label: commentsSelected ? 'Watch' : 'Comments',
+ onPressed: onToggleComments,
+ ),
+ Tooltip(
+ message: 'Close shared harness',
+ child: TerminalTextAction(label: 'Close', onPressed: onClose),
+ ),
+ ];
+ }
+}
+
+/// A Terminal/Viewer choice drawn like a workspace tab: the selection is a
+/// fill, hover and focus are bold text.
+class _ViewTab extends StatelessWidget {
+ const _ViewTab({
+ required this.label,
+ required this.selected,
+ required this.onPressed,
+ });
+
+ final String label;
+ final bool selected;
+ final VoidCallback onPressed;
+
+ @override
+ Widget build(BuildContext context) {
+ final cell = workspaceBarCellSizeOf(context);
+ final size = workspaceBarTextSizeOf(context, label);
+ return WorkspaceBarControl(
+ label: label,
+ selected: selected,
+ selectedBackground: grid.AppPalette.windowBg,
+ onPressed: onPressed,
+ builder: (context, emphasized) => SizedBox(
+ width: size.width + cell.width * 2,
+ height: workspaceBarControlHeight(context),
+ child: Center(
+ child: Text(
+ label,
+ style: workspaceBarTextStyle(
+ color: selected
+ ? grid.AppPalette.textPrimary
+ : grid.AppPalette.textSecondary,
+ emphasized: emphasized,
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// One quiet line under the bar: why the terminal is empty or has ended.
+class SharedHarnessNotice extends StatelessWidget {
+ const SharedHarnessNotice(this.message, {super.key});
+
+ final String message;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final cell = workspaceBarCellSizeOf(context);
+ return Container(
+ width: double.infinity,
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width,
+ vertical: cell.height / 2,
+ ),
+ decoration: BoxDecoration(
+ border: Border(bottom: BorderSide(color: grid.AppPalette.divider)),
+ ),
+ child: Text(
+ message,
+ style: workspaceBarTextStyle(color: grid.AppPalette.textSecondary),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/sharing/shared_harness_panel.dart b/desktop/lib/sharing/shared_harness_panel.dart
index 070145a60..4e00a1ead 100644
--- a/desktop/lib/sharing/shared_harness_panel.dart
+++ b/desktop/lib/sharing/shared_harness_panel.dart
@@ -8,7 +8,6 @@ import 'package:harness/terminal/terminal_text.dart';
import '../core/models.dart';
import '../logging/app_log.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/skeleton.dart';
import '../state/app_state.dart';
import '../state/terminal_pane.dart';
import '../terminal/terminal_binary.dart';
@@ -16,8 +15,10 @@ import '../terminal/terminal_session.dart';
import '../widgets/terminal_panel.dart';
import '../ws/ws_conn.dart';
import '../viewer/observer_relay_codec.dart';
-import '../widgets/terminal_text_action.dart';
import 'harness_comments.dart';
+import 'shared_harness_bar.dart';
+import 'shared_terminal_watch.dart';
+import 'shared_viewer_view.dart';
class SharedHarnessPanel extends StatefulWidget {
const SharedHarnessPanel({
@@ -47,6 +48,7 @@ class SharedHarnessPanel extends StatefulWidget {
class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
late WsConn _connection;
late TerminalSession _terminal;
+ late SharedTerminalWatch _watch;
ConnectionStatus _status = ConnectionStatus.connecting;
String? _failure;
String _viewerMessage = 'Waiting for the live viewer…';
@@ -63,6 +65,19 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
int _generation = 0;
bool _commentsSelected = false, _commentsOpened = false;
final _commentUpdates = ValueNotifier<int>(0);
+
+ /// Terminal and viewer share the pane side by side from this width.
+ static const _splitWidth = 880.0;
+
+ /// Comments sit beside the output from this width, and replace it below.
+ static const _commentsBesideWidth = 1000.0;
+
+ /// Most harnesses never produce a viewer; theirs stays out of the layout
+ /// until the owner machine says one is coming.
+ bool get _hasViewer =>
+ _image != null ||
+ (_lastViewerState.isNotEmpty && _lastViewerState != 'waiting');
+
@override
void initState() {
super.initState();
@@ -85,6 +100,17 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
onOpenStalled: () => _connection.forceReconnect(),
resyncTimeout: const Duration(seconds: 15),
);
+ _watch = SharedTerminalWatch(
+ _terminal,
+ canRetry: () =>
+ generation == _generation &&
+ !_ended &&
+ _status == ConnectionStatus.connected,
+ onChanged: () {
+ if (mounted && generation == _generation) setState(() {});
+ },
+ );
+ _lastViewerState = '';
_connection = WsConn(
wsBaseUrl: widget.notifier.config.wsBaseUrl,
autonomousEnv:
@@ -126,47 +152,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
final type = frame['type'] as String,
payload = Map<String, dynamic>.from(frame['payload'] as Map);
if (type == 'observer_viewer') {
- if (!mounted || _ended) {
- appLog.warn(
- 'share',
- 'pane ${widget.pane.id} dropped viewer frame ${payload['state']} (mounted=$mounted ended=$_ended)',
- );
- return;
- }
- Uint8List? next;
- try {
- if (payload['data'] is String) {
- next = base64Decode(payload['data'] as String);
- }
- } on FormatException catch (error) {
- appLog.warn(
- 'share',
- 'pane ${widget.pane.id} viewer frame did not decode: $error',
- );
- return;
- }
- // On change only: live frames come 2–3 a second, and a line per frame
- // would bury the one that matters — the first, and every refusal.
- final state = '${payload['state']}';
- if (state != _lastViewerState) {
- _lastViewerState = state;
- appLog.debug(
- 'share',
- 'pane ${widget.pane.id} viewer $state bytes=${next?.length ?? 0}'
- '${payload['message'] != null ? ' · ${payload['message']}' : ''}',
- );
- }
- setState(() {
- if (next != null) {
- if (_image == null && !_viewerChosen) _viewerSelected = true;
- _image = next;
- }
- _viewerMessage =
- payload['message'] as String? ??
- (payload['state'] == 'live'
- ? 'Live viewer'
- : 'Opening the viewer…');
- });
+ _onViewerFrame(payload);
} else if (type == 'observer_comments') {
_commentUpdates.value++;
} else {
@@ -204,6 +190,48 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
}
}
+ void _onViewerFrame(Map<String, dynamic> payload) {
+ if (!mounted || _ended) {
+ appLog.warn(
+ 'share',
+ 'pane ${widget.pane.id} dropped viewer frame ${payload['state']} (mounted=$mounted ended=$_ended)',
+ );
+ return;
+ }
+ Uint8List? next;
+ try {
+ if (payload['data'] is String) {
+ next = base64Decode(payload['data'] as String);
+ }
+ } on FormatException catch (error) {
+ appLog.warn(
+ 'share',
+ 'pane ${widget.pane.id} viewer frame did not decode: $error',
+ );
+ return;
+ }
+ // On change only: live frames come 2–3 a second, and a line per frame
+ // would bury the one that matters — the first, and every refusal.
+ final state = '${payload['state']}';
+ if (state != _lastViewerState) {
+ _lastViewerState = state;
+ appLog.debug(
+ 'share',
+ 'pane ${widget.pane.id} viewer $state bytes=${next?.length ?? 0}'
+ '${payload['message'] != null ? ' · ${payload['message']}' : ''}',
+ );
+ }
+ setState(() {
+ if (next != null) {
+ if (_image == null && !_viewerChosen) _viewerSelected = true;
+ _image = next;
+ }
+ _viewerMessage =
+ payload['message'] as String? ??
+ (payload['state'] == 'live' ? 'Live viewer' : 'Opening the viewer…');
+ });
+ }
+
void _end(String reason) {
if (!mounted || _ended) return;
setState(() {
@@ -224,8 +252,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
(!oldWidget.hasAccess ||
widget.grant.id != oldWidget.grant.id ||
widget.grant.ownerPublicKey != oldWidget.grant.ownerPublicKey)) {
- unawaited(_connection.close());
- _terminal.dispose();
+ _closeSession();
_ended = false;
_failure = null;
_image = null;
@@ -236,223 +263,88 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
@override
void dispose() {
- unawaited(_connection.close());
- _terminal.dispose();
+ _closeSession();
_commentUpdates.dispose();
super.dispose();
}
- void _retry() {
+ void _closeSession() {
unawaited(_connection.close());
+ _watch.dispose();
_terminal.dispose();
+ }
+
+ void _retry() {
+ _closeSession();
_ended = false;
_failure = null;
_status = ConnectionStatus.connecting;
setState(_start);
}
+ void _toggleComments() => setState(() {
+ _commentsSelected = !_commentsSelected;
+ _commentsOpened = true;
+ });
+
+ void _selectViewer(bool viewer) => setState(() {
+ _viewerChosen = true;
+ _viewerSelected = viewer;
+ });
+
+ String? get _detail {
+ final parts = [
+ widget.grant.engine,
+ widget.pane.sharedOwnerName,
+ ].whereType<String>().where((part) => part.isNotEmpty);
+ return parts.isEmpty ? null : parts.join(' · ');
+ }
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
TerminalFontScope.watch(context);
- final live = !_ended && _status == ConnectionStatus.connected;
- return Column(
- children: [
- Container(
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
- color: grid.AppSurface.recess,
- child: Column(
- children: [
- Row(
- children: [
- Expanded(
- child: Text(
- widget.grant.name,
- overflow: TextOverflow.ellipsis,
- style: terminalContentStyle().copyWith(
- fontWeight: FontWeight.bold,
- ),
- ),
- ),
- const SizedBox(width: 8),
- Text('View only', style: terminalContentStyle()),
- IconButton(
- tooltip: 'Close shared harness',
- onPressed: widget.onClose,
- icon: const Icon(Icons.close, size: 16),
- ),
- ],
- ),
- Row(
- children: [
- Expanded(
- child: Text(
- _ended
- ? 'Sharing ended'
- : live
- ? 'Live'
- : 'Reconnecting',
- style: terminalContentStyle(
- color: grid.AppPalette.textSecondary,
- ),
- ),
- ),
- if (_ended && widget.hasAccess)
- TerminalTextAction(label: 'Retry', onPressed: _retry),
- TerminalTextAction(
- label: _commentsSelected ? 'Watch' : 'Comments',
- onPressed: () => setState(() {
- _commentsSelected = !_commentsSelected;
- _commentsOpened = true;
- }),
- ),
- ],
- ),
- ],
- ),
- ),
- if (_failure != null)
- Container(
- width: double.infinity,
- padding: const EdgeInsets.all(12),
- color: grid.AppSurface.recess,
- child: Text(_failure!, style: grid.AppType.body()),
- ),
- Expanded(
- child: LayoutBuilder(
- builder: (context, size) {
- final wide = size.maxWidth >= 1000;
- final commentsWidth = wide
- ? (terminalCellSizeOf(context).width * 44).clamp(
- 280.0,
- size.maxWidth * .45,
- )
- : size.maxWidth;
- return Stack(
+ final status = SharedPaneStatus.of(
+ ended: _ended,
+ connected: _status == ConnectionStatus.connected,
+ terminalStopped: _watch.stopped,
+ );
+ final notice = _failure ?? status.notice;
+ return LayoutBuilder(
+ builder: (context, size) {
+ final commentsBeside = size.maxWidth >= _commentsBesideWidth;
+ final commentsWidth = commentsBeside
+ ? (terminalCellSizeOf(context).width * 44).clamp(
+ 280.0,
+ size.maxWidth * .45,
+ )
+ : size.maxWidth;
+ final besideComments = _commentsSelected && commentsBeside;
+ final outputWidth =
+ size.maxWidth - (besideComments ? commentsWidth : 0);
+ final split = _hasViewer && outputWidth >= _splitWidth;
+ return Column(
+ children: [
+ SharedHarnessBar(
+ name: widget.grant.name,
+ detail: _detail,
+ status: status,
+ commentsSelected: _commentsSelected,
+ onToggleComments: _toggleComments,
+ onClose: widget.onClose,
+ viewerSelected: _hasViewer && !split ? _viewerSelected : null,
+ onSelectViewer: _selectViewer,
+ onRetry: _ended && widget.hasAccess ? _retry : null,
+ ),
+ if (notice != null) SharedHarnessNotice(notice),
+ Expanded(
+ child: Stack(
children: [
Positioned.fill(
- right: _commentsSelected && wide ? commentsWidth : 0,
+ right: besideComments ? commentsWidth : 0,
child: Offstage(
- offstage: _commentsSelected && !wide,
- child: LayoutBuilder(
- builder: (context, constraints) {
- Widget terminal() => TerminalPanel(
- notifier: widget.notifier,
- session: _terminal,
- focused: widget.notifier.isPaneFocused(
- widget.pane.id,
- ),
- visible: widget.visible,
- showHeader: false,
- readOnly: true,
- viewportSize: constraints.biggest,
- );
- Widget viewer() => ColoredBox(
- color: grid.AppPalette.windowBg,
- child: Center(
- child: _image == null
- ? Padding(
- padding: const EdgeInsets.all(24),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- if (!_ended)
- const Skeleton(
- width: 220,
- height: 130,
- ),
- const SizedBox(height: 14),
- Text(
- _viewerMessage,
- textAlign: TextAlign.center,
- style: grid.AppType.body(
- color:
- grid.AppPalette.textSecondary,
- ),
- ),
- ],
- ),
- )
- : Image.memory(
- _image!,
- gaplessPlayback: true,
- fit: BoxFit.contain,
- semanticLabel:
- 'Live output from ${widget.grant.name}',
- errorBuilder: (_, _, _) => const Text(
- 'Waiting for the next viewer frame.',
- ),
- ),
- ),
- );
- if (constraints.maxWidth >= 880) {
- return Row(
- children: [
- Expanded(flex: 5, child: terminal()),
- VerticalDivider(
- width: 1,
- color: grid.AppPalette.textFaint,
- ),
- Expanded(flex: 4, child: viewer()),
- ],
- );
- }
- return Column(
- children: [
- Row(
- children: [
- TextButton(
- onPressed: () => setState(() {
- _viewerChosen = true;
- _viewerSelected = false;
- }),
- child: Text(
- 'Terminal',
- style: TextStyle(
- fontWeight: !_viewerSelected
- ? FontWeight.w600
- : FontWeight.normal,
- ),
- ),
- ),
- TextButton(
- onPressed: () => setState(() {
- _viewerChosen = true;
- _viewerSelected = true;
- }),
- child: Text(
- 'Viewer',
- style: TextStyle(
- fontWeight: _viewerSelected
- ? FontWeight.w600
- : FontWeight.normal,
- ),
- ),
- ),
- const Spacer(),
- Flexible(
- child: Text(
- widget.pane.sharedOwnerName ??
- 'Shared harness',
- overflow: TextOverflow.ellipsis,
- style: grid.AppType.monoLabel(
- fontWeight: grid.AppFont.regular,
- ),
- ),
- ),
- const SizedBox(width: 12),
- ],
- ),
- Expanded(
- child: IndexedStack(
- index: _viewerSelected ? 1 : 0,
- children: [terminal(), viewer()],
- ),
- ),
- ],
- );
- },
- ),
+ offstage: _commentsSelected && !commentsBeside,
+ child: _output(split),
),
),
if (_commentsOpened)
@@ -463,33 +355,64 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
width: commentsWidth,
child: Offstage(
offstage: !_commentsSelected,
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: grid.AppPalette.windowBg,
- border: Border(
- left: BorderSide(color: grid.AppPalette.divider),
- ),
- ),
- child: HarnessComments(
- updates: _commentUpdates,
- onSignIn: widget.onSignIn,
- manage: (action, payload) => _connection.request(
- 'observer_$action',
- payload: {
- 'agentId': widget.grant.agentId,
- ...payload,
- },
- ),
- ),
- ),
+ child: _comments(),
),
),
],
- );
- },
- ),
- ),
- ],
+ ),
+ ),
+ ],
+ );
+ },
);
}
+
+ Widget _output(bool split) => LayoutBuilder(
+ builder: (context, constraints) {
+ final terminal = TerminalPanel(
+ notifier: widget.notifier,
+ session: _terminal,
+ focused: widget.notifier.isPaneFocused(widget.pane.id),
+ visible: widget.visible,
+ showHeader: false,
+ readOnly: true,
+ viewportSize: constraints.biggest,
+ );
+ if (!_hasViewer) return terminal;
+ final viewer = SharedViewerView(
+ name: widget.grant.name,
+ image: _image,
+ message: _viewerMessage,
+ ended: _ended,
+ );
+ if (!split) {
+ return IndexedStack(
+ index: _viewerSelected ? 1 : 0,
+ children: [terminal, viewer],
+ );
+ }
+ return Row(
+ children: [
+ Expanded(flex: 5, child: terminal),
+ VerticalDivider(width: 1, color: grid.AppPalette.divider),
+ Expanded(flex: 4, child: viewer),
+ ],
+ );
+ },
+ );
+
+ Widget _comments() => DecoratedBox(
+ decoration: BoxDecoration(
+ color: grid.AppPalette.windowBg,
+ border: Border(left: BorderSide(color: grid.AppPalette.divider)),
+ ),
+ child: HarnessComments(
+ updates: _commentUpdates,
+ onSignIn: widget.onSignIn,
+ manage: (action, payload) => _connection.request(
+ 'observer_$action',
+ payload: {'agentId': widget.grant.agentId, ...payload},
+ ),
+ ),
+ );
}
diff --git a/desktop/lib/sharing/shared_terminal_watch.dart b/desktop/lib/sharing/shared_terminal_watch.dart
new file mode 100644
index 000000000..5fa06285d
--- /dev/null
+++ b/desktop/lib/sharing/shared_terminal_watch.dart
@@ -0,0 +1,71 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import '../terminal/terminal_session.dart';
+
+/// Whether the owner machine answered that [session]'s terminal is not
+/// running, as opposed to not having opened it yet: a stream the daemon closed
+/// (the tmux pane exited) carries its reason, a refused open is an error. A
+/// lost relay is not an answer; the pane already says Reconnecting for it.
+bool sharedTerminalStopped(TerminalSession session) => switch (session.status) {
+ TerminalSessionStatus.error =>
+ session.errorCode != TerminalSession.disconnectedCode,
+ TerminalSessionStatus.takenOver => true,
+ TerminalSessionStatus.closed => session.errorMessage != null,
+ _ => false,
+};
+
+/// Tracks whether a shared pane's terminal is running and, while it is not,
+/// asks for it again: an owner who restarts the harness keeps its agent id, so
+/// the same open succeeds once there is a pane to stream.
+///
+/// [stopped] is sticky across those retries: each reopen passes through
+/// `opening`, and the label must not flash "Live" every [retryEvery].
+class SharedTerminalWatch {
+ SharedTerminalWatch(
+ this.session, {
+ required this.canRetry,
+ required this.onChanged,
+ this.retryEvery = const Duration(seconds: 10),
+ }) {
+ session.addListener(_update);
+ }
+
+ final TerminalSession session;
+ final bool Function() canRetry;
+ final VoidCallback onChanged;
+ final Duration retryEvery;
+ Timer? _retry;
+ bool _stopped = false;
+
+ bool get stopped => _stopped;
+
+ void _update() {
+ if (session.status == TerminalSessionStatus.controlling) {
+ _set(false);
+ } else if (sharedTerminalStopped(session)) {
+ _set(true);
+ }
+ }
+
+ void _set(bool stopped) {
+ if (stopped) {
+ _retry ??= Timer.periodic(retryEvery, (_) {
+ if (canRetry()) unawaited(session.reopen());
+ });
+ } else {
+ _retry?.cancel();
+ _retry = null;
+ }
+ if (stopped == _stopped) return;
+ _stopped = stopped;
+ onChanged();
+ }
+
+ void dispose() {
+ _retry?.cancel();
+ _retry = null;
+ session.removeListener(_update);
+ }
+}
diff --git a/desktop/lib/sharing/shared_viewer_view.dart b/desktop/lib/sharing/shared_viewer_view.dart
new file mode 100644
index 000000000..27c3d3af9
--- /dev/null
+++ b/desktop/lib/sharing/shared_viewer_view.dart
@@ -0,0 +1,60 @@
+import 'dart:typed_data';
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/skeleton.dart';
+
+/// The owner's live viewer as a reader sees it: the latest frame, or what the
+/// owner machine says about it while there is none.
+class SharedViewerView extends StatelessWidget {
+ const SharedViewerView({
+ super.key,
+ required this.name,
+ required this.image,
+ required this.message,
+ required this.ended,
+ });
+
+ final String name;
+ final Uint8List? image;
+ final String message;
+ final bool ended;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final frame = image;
+ return ColoredBox(
+ color: grid.AppPalette.windowBg,
+ child: Center(
+ child: frame != null
+ ? Image.memory(
+ frame,
+ gaplessPlayback: true,
+ fit: BoxFit.contain,
+ semanticLabel: 'Live output from $name',
+ errorBuilder: (_, _, _) =>
+ const Text('Waiting for the next viewer frame.'),
+ )
+ : Padding(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (!ended) const Skeleton(width: 220, height: 130),
+ const SizedBox(height: 14),
+ Text(
+ message,
+ textAlign: TextAlign.center,
+ style: grid.AppType.body(
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index b7b8b5faa..4699dd01a 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -9776,7 +9776,7 @@ class AppNotifier extends ChangeNotifier {
// now, and each attempt lands here again through the `reconnecting` status. A pane already
// dark with this very message has nothing to learn and nothing to repaint.
if (session.status == TerminalSessionStatus.error &&
- session.errorCode == 'TERMINAL_DISCONNECTED' &&
+ session.errorCode == TerminalSession.disconnectedCode &&
session.errorMessage == message) {
continue;
}
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index 5d62885f0..808d41946 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -128,6 +128,9 @@ class _ActiveUpload {
/// reopen. Transport loss still freezes input until the user opens a session.
class TerminalSession extends ChangeNotifier {
static const protocolVersion = 3;
+
+ /// [errorCode] after [transportLost]: the link dropped, not the terminal.
+ static const disconnectedCode = 'TERMINAL_DISCONNECTED';
static const minCols = 40;
static const maxCols = 300;
static const minRows = 12;
@@ -1585,7 +1588,7 @@ class TerminalSession extends ChangeNotifier {
streamId = null;
linkMode = null;
status = TerminalSessionStatus.error;
- errorCode = 'TERMINAL_DISCONNECTED';
+ errorCode = disconnectedCode;
errorMessage = message;
_abortActiveUpload();
notifyListeners();
diff --git a/desktop/test/shared_harness_panel_test.dart b/desktop/test/shared_harness_panel_test.dart
index 3eb6d8765..ba5931c23 100644
--- a/desktop/test/shared_harness_panel_test.dart
+++ b/desktop/test/shared_harness_panel_test.dart
@@ -240,22 +240,19 @@ void main() {
// Receiving the request on the server does not mean its reply has
// reached the UI yet. Wait for the response we are about to inspect.
await settleNetwork(
- () =>
- requests.any((r) => r['type'] == 'observer_viewer') &&
- find
- .textContaining('The viewer will appear', skipOffstage: false)
- .evaluate()
- .isNotEmpty,
+ () => requests.any((r) => r['type'] == 'observer_viewer'),
);
- // Narrow: the terminal is in front and the viewer waits behind its tab —
- // until the first frame lands, which brings it forward by itself (below).
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 30)),
+ );
+ await tester.pump();
+ // A harness with no viewer yet gets the whole pane for its terminal:
+ // no empty viewer column, no Terminal/Viewer switch.
expect(
find.textContaining('The viewer will appear', skipOffstage: false),
- findsOneWidget,
+ findsNothing,
);
- if (width < 880) {
- expect(find.textContaining('The viewer will appear'), findsNothing);
- }
+ expect(find.text('Viewer'), findsNothing);
expect(
requests.map((r) => r['type']),
isNot(contains('terminal_resize')),
@@ -394,4 +391,96 @@ void main() {
app.dispose();
},
);
+
+ testWidgets(
+ 'a harness the owner is not running says so instead of showing Live',
+ (tester) async {
+ tester.view.physicalSize = const Size(1100, 760);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final sockets = <WebSocket>[];
+ late HttpServer server;
+ await tester.runAsync(() async {
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((request) async {
+ final ws = await WebSocketTransformer.upgrade(request);
+ sockets.add(ws);
+ ws.listen((raw) {
+ if (raw is! String || ws.readyState != WebSocket.open) return;
+ final frame = jsonDecode(raw) as Map<String, dynamic>;
+ final p = frame['payload'] as Map;
+ if (frame['type'] == 'machine_select') {
+ ws.add(
+ jsonEncode({
+ 'type': 'connected',
+ 'payload': {'machineId': 'shared', 'readOnly': true},
+ }),
+ );
+ } else if (frame['type'] == 'terminal_open') {
+ ws.add(
+ jsonEncode({
+ 'type': 'terminal_error',
+ 'payload': {
+ 'requestId': p['requestId'],
+ 'protocolVersion': 3,
+ 'code': 'TERMINAL_RUNTIME_UNAVAILABLE',
+ },
+ }),
+ );
+ }
+ });
+ });
+ });
+ final app = AppNotifier(
+ config: AppConfig(
+ apiBaseUrl: 'http://127.0.0.1:9',
+ localCliBaseUrl: 'http://127.0.0.1:${server.port}',
+ ),
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ final grant = SharedHarness(
+ id: 'grant',
+ agentId: 'agent',
+ name: 'Stopped harness',
+ engine: 'codex',
+ expiresAt: DateTime(2027),
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SharedHarnessPanel(
+ notifier: app,
+ pane: TerminalPane(id: 1, machineId: 'shared', agentId: 'agent'),
+ grant: grant,
+ hasAccess: true,
+ visible: true,
+ onClose: () {},
+ ),
+ ),
+ ),
+ );
+ for (var i = 0; i < 100; i++) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 20)),
+ );
+ await tester.pump();
+ if (find.text('Not running').evaluate().isNotEmpty) break;
+ }
+ expect(find.text('Not running'), findsOneWidget);
+ expect(find.text('Live'), findsNothing);
+ expect(find.textContaining('isn’t running right now'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ await tester.runAsync(() async {
+ for (final ws in sockets) {
+ unawaited(ws.close());
+ }
+ await server.close(force: true);
+ });
+ await tester.pump(const Duration(seconds: 6));
+ },
+ );
}
diff --git a/desktop/test/shared_terminal_watch_test.dart b/desktop/test/shared_terminal_watch_test.dart
new file mode 100644
index 000000000..b650b7e7e
--- /dev/null
+++ b/desktop/test/shared_terminal_watch_test.dart
@@ -0,0 +1,144 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/sharing/shared_harness_bar.dart';
+import 'package:harness/sharing/shared_terminal_watch.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/terminal/terminal_session.dart';
+
+void main() {
+ const streamId = '00112233-4455-6677-8899-aabbccddeeff';
+
+ ({TerminalSession session, List<Map<String, dynamic>> sent}) observer() {
+ final sent = <Map<String, dynamic>>[];
+ final session = TerminalSession(
+ machineId: 'shared',
+ agentId: 'agent',
+ agentName: 'Demo',
+ engineId: 'codex',
+ readOnly: true,
+ send: (type, payload) async {
+ sent.add({'type': type, ...payload});
+ return true;
+ },
+ sendBinary: (_) async => false,
+ );
+ return (session: session, sent: sent);
+ }
+
+ List<Map<String, dynamic>> opens(List<Map<String, dynamic>> sent) =>
+ sent.where((frame) => frame['type'] == 'terminal_open').toList();
+
+ Future<void> attach(TerminalSession session, Object? requestId) async {
+ await session.handleFrame('terminal_ready', {
+ 'requestId': requestId,
+ 'protocolVersion': 3,
+ 'streamId': streamId,
+ 'agentId': 'agent',
+ });
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: streamId,
+ seq: 0,
+ bytes: Uint8List.fromList(utf8.encode('back again')),
+ compressed: false,
+ cols: 80,
+ rows: 24,
+ ),
+ );
+ }
+
+ testWidgets(
+ 'a refused open reads as stopped, retries until the harness is back, then stops retrying',
+ (tester) async {
+ final (:session, :sent) = observer();
+ var changes = 0;
+ final watch = SharedTerminalWatch(
+ session,
+ canRetry: () => true,
+ onChanged: () => changes++,
+ );
+ await session.open();
+ await session.handleFrame('terminal_error', {
+ 'requestId': opens(sent).single['requestId'],
+ 'code': 'TERMINAL_RUNTIME_UNAVAILABLE',
+ });
+ expect(watch.stopped, isTrue);
+ expect(changes, 1);
+
+ await tester.pump(const Duration(seconds: 10));
+ expect(opens(sent), hasLength(2));
+ // The retry passes through `opening`; the reader keeps seeing why.
+ expect(session.status, TerminalSessionStatus.opening);
+ expect(watch.stopped, isTrue);
+
+ await attach(session, opens(sent).last['requestId']);
+ expect(watch.stopped, isFalse);
+ expect(changes, 2);
+ await tester.pump(const Duration(seconds: 30));
+ expect(opens(sent), hasLength(2));
+
+ watch.dispose();
+ session.dispose();
+ },
+ );
+
+ testWidgets('a stream the owner daemon closes reads as stopped', (
+ tester,
+ ) async {
+ final (:session, :sent) = observer();
+ final watch = SharedTerminalWatch(
+ session,
+ canRetry: () => false,
+ onChanged: () {},
+ );
+ await session.open();
+ await attach(session, opens(sent).single['requestId']);
+ expect(watch.stopped, isFalse);
+ await session.handleFrame('terminal_closed', {
+ 'streamId': streamId,
+ 'reason': 'tmux pane/control client closed',
+ });
+ expect(watch.stopped, isTrue);
+ // Not while the pane cannot reach the owner: no retry goes out.
+ await tester.pump(const Duration(seconds: 30));
+ expect(opens(sent), hasLength(1));
+ watch.dispose();
+ session.dispose();
+ });
+
+ testWidgets('a lost relay is not a stopped harness', (tester) async {
+ final (:session, :sent) = observer();
+ final watch = SharedTerminalWatch(
+ session,
+ canRetry: () => true,
+ onChanged: () {},
+ );
+ await session.open();
+ await attach(session, opens(sent).single['requestId']);
+ session.transportLost('Waiting for the owner to reconnect.');
+ expect(session.errorCode, TerminalSession.disconnectedCode);
+ expect(watch.stopped, isFalse);
+ await tester.pump(const Duration(seconds: 30));
+ expect(opens(sent), hasLength(1));
+ watch.dispose();
+ session.dispose();
+ });
+
+ test('pane status puts the most urgent state first', () {
+ SharedPaneStatus of(bool ended, bool connected, bool stopped) =>
+ SharedPaneStatus.of(
+ ended: ended,
+ connected: connected,
+ terminalStopped: stopped,
+ );
+ expect(of(true, true, true), SharedPaneStatus.ended);
+ expect(of(false, false, true), SharedPaneStatus.reconnecting);
+ expect(of(false, true, true), SharedPaneStatus.notRunning);
+ expect(of(false, true, false), SharedPaneStatus.live);
+ expect(SharedPaneStatus.notRunning.notice, isNotNull);
+ expect(SharedPaneStatus.live.notice, isNull);
+ });
+}