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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
perf(desktop): defer hidden terminal rendering until visible
dee485957984f27
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 7b76f65e6..0f21496a4 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -769,6 +769,7 @@ class _TerminalPanelState extends State<TerminalPanel>key: _terminalViewKey,controller: _controller,autoResize: widget.visible,+ renderingEnabled: widget.visible,scrollController: _scrollController,focusNode: _focusNode,autofocus: widget.focused && !showComposer,diff --git a/desktop/test/benchmarks/terminal_background_benchmark.dart b/desktop/test/benchmarks/terminal_background_benchmark.dartnew file mode 100644index 000000000..ee61a939d--- /dev/null+++ b/desktop/test/benchmarks/terminal_background_benchmark.dart@@ -0,0 +1,80 @@+import 'dart:convert';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:xterm/xterm.dart';++import '../swarm_screen_test.dart' show mount, terminal;+import '../swarm_state_test.dart' show createApp;+import 'swarm_benchmark.dart' show distribution;++/// Measures parsing and Flutter rendering of already-decoded streamed text.+/// No sockets, real sessions, native input or display timing are involved.+void main() {+ for (final count in [16, 48]) {+ testWidgets('background output with $count retained terminals', (+ tester,+ ) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ for (var i = 0; i < count; i++) {+ if (i > 0 && i % 4 == 0) app.newSwarm();+ final session = terminal('a$i', []);+ session.terminal.write(+ List.generate(1000, (line) => 'History line $line\r\n').join(),+ );+ app.adoptSessionForTest(session);+ }+ await mount(tester, app);+ for (var i = 0; i < count ~/ 4; i++) {+ app.stepSwarm(1);+ await tester.pump();+ }+ final visible = app.panes.map((pane) => pane.session!.terminal).toSet();+ final views = tester+ .stateList<TerminalViewState>(+ find.byType(TerminalView, skipOffstage: false),+ )+ .toList();+ final hidden = views+ .where((view) => !visible.contains(view.widget.terminal))+ .toList();+ expect(views, hasLength(count));+ expect(hidden, hasLength(count - 4));+ for (final scope in ['hidden', 'all']) {+ final destinations = scope == 'hidden' ? hidden : views;+ void writeBurst() {+ for (final view in destinations) {+ for (var packet = 0; packet < 4; packet++) {+ // Repaint one row to hold scrollback size constant.+ view.widget.terminal.write('\r\x1b[2KAgent update $packet');+ }+ }+ }++ for (var warmup = 0; warmup < 20; warmup++) {+ writeBurst();+ await tester.pump();+ }+ writeBurst();+ final dirty = hidden+ .where((view) => view.renderTerminal.debugNeedsLayout)+ .length;+ final scheduled = tester.binding.hasScheduledFrame;+ await tester.pump();+ final times = <int>[];+ for (var sample = 0; sample < 60; sample++) {+ final watch = Stopwatch()..start();+ writeBurst();+ await tester.pump();+ times.add(watch.elapsedMicroseconds);+ }+ debugPrint(+ 'TERMINAL_BACKGROUND_BENCH ${jsonEncode({'kind': 'headless_debug_cpu', 'retainedTerminals': count, 'hiddenTerminals': hidden.length, 'scope': scope, 'updatesPerTerminalPerSample': 4, 'hiddenRenderersNeedingLayout': dirty, 'scheduledFrame': scheduled, 'outputAndFrame': distribution(times)})}',+ );+ }+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+ }+}diff --git a/desktop/test/terminal_render_suspension_test.dart b/desktop/test/terminal_render_suspension_test.dartnew file mode 100644index 000000000..87b30f15c--- /dev/null+++ b/desktop/test/terminal_render_suspension_test.dart@@ -0,0 +1,298 @@+import 'dart:convert';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/widgets/pane_grid.dart';+import 'package:xterm/xterm.dart';++import 'swarm_screen_test.dart' show terminal;+import 'swarm_state_test.dart' show createApp;++Future<void> _output(+ TerminalSession session,+ int sequence,+ String text, {+ bool keyframe = false,+}) => session.handleBinary(+ TerminalBinaryFrame(+ kind: keyframe ? TerminalBinaryKind.keyframe : TerminalBinaryKind.output,+ streamId: session.streamId!,+ seq: sequence,+ bytes: utf8.encode(text),+ compressed: false,+ cols: keyframe ? 80 : null,+ rows: keyframe ? 24 : null,+ ),+);++Future<Color> _firstCellColor(+ WidgetTester tester,+ TerminalViewState view,+) async {+ final boundary = tester.renderObject<RenderRepaintBoundary>(+ find.byKey(const ValueKey('terminal pixels')),+ );+ final render = view.renderTerminal;+ final sample = boundary.globalToLocal(+ render.localToGlobal(+ render.getOffset(const CellOffset(0, 0)) ++ render.cellSize.center(Offset.zero),+ ),+ );+ return (await tester.runAsync(() async {+ final image = await boundary.toImage(pixelRatio: 1);+ try {+ final rgba = (await image.toByteData(+ format: ui.ImageByteFormat.rawRgba,+ ))!;+ final index = (sample.dy.floor() * image.width + sample.dx.floor()) * 4;+ return Color.fromARGB(+ rgba.getUint8(index + 3),+ rgba.getUint8(index),+ rgba.getUint8(index + 1),+ rgba.getUint8(index + 2),+ );+ } finally {+ image.dispose();+ }+ }))!;+}++void main() {+ testWidgets(+ 'hidden streamed output preserves selection, scroll and follow-tail without frames',+ (tester) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final a = terminal('a0', []);+ final b = terminal('a1', []);+ final history = List.generate(200, (i) => 'history line $i\r\n').join();+ await _output(a, 0, history, keyframe: true);+ await _output(b, 0, history, keyframe: true);+ app.adoptSessionForTest(a);+ app.adoptSessionForTest(b);+ final first = app.activeSwarmId;+ await tester.pumpWidget(+ MaterialApp(+ home: PaneGrid(+ notifier: app,+ swarmMode: true,+ empty: const SizedBox(),+ ),+ ),+ );+ await tester.pump(const Duration(milliseconds: 100));+ final viewA = tester.state<TerminalViewState>(+ find.byWidgetPredicate(+ (w) => w is TerminalView && w.terminal == a.terminal,+ ),+ );+ final viewB = tester.state<TerminalViewState>(+ find.byWidgetPredicate(+ (w) => w is TerminalView && w.terminal == b.terminal,+ ),+ );+ final renderA = viewA.renderTerminal;+ final scrollA = viewA.widget.scrollController!;+ final scrollB = viewB.widget.scrollController!;+ final selection = viewA.widget.controller!;+ scrollA.jumpTo(100);+ selection.setSelection(+ a.terminal.buffer.createAnchor(0, 3),+ a.terminal.buffer.createAnchor(7, 3),+ );+ await tester.pump();+ final selected = a.terminal.buffer.getText(selection.selection);+ final oldExtent = scrollB.position.maxScrollExtent;+ app.newSwarm();+ await tester.pump();+ await tester.pump();+ for (var i = 1; i <= 30; i++) {+ await _output(a, i, 'hidden output $i\r\n');+ await _output(b, i, 'hidden output $i\r\n');+ }+ expect(renderA.debugNeedsLayout, isFalse);+ expect(viewB.renderTerminal.debugNeedsLayout, isFalse);+ expect(tester.binding.hasScheduledFrame, isFalse);+ expect(a.terminal.buffer.getText(), contains('hidden output 30'));+ expect(scrollA.offset, 100);+ expect(scrollB.position.maxScrollExtent, oldExtent);+ app.selectSwarm(first);+ await tester.pump();+ expect(viewA.renderTerminal, same(renderA));+ expect(scrollA.offset, 100);+ expect(a.terminal.buffer.getText(selection.selection), selected);+ expect(scrollB.position.maxScrollExtent, greaterThan(oldExtent));+ expect(scrollB.offset, scrollB.position.maxScrollExtent);+ expect(a.status, TerminalSessionStatus.controlling);+ expect(b.status, TerminalSessionStatus.controlling);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );++ testWidgets(+ 'resuming reconciles changed terminal dimensions and preserves unchanged scroll regions',+ (tester) async {+ final buffer = Terminal();+ final enabled = ValueNotifier(true);+ await tester.pumpWidget(+ MaterialApp(+ home: ValueListenableBuilder<bool>(+ valueListenable: enabled,+ builder: (_, value, _) => Offstage(+ offstage: !value,+ child: TerminalView(buffer, renderingEnabled: value),+ ),+ ),+ ),+ );+ final columns = buffer.viewWidth;+ final rows = buffer.viewHeight;+ final resizes = <(int, int)>[];+ buffer.onResize = (w, h, _, _) => resizes.add((w, h));+ enabled.value = false;+ await tester.pump();+ // A remote keyframe can change the emulator's dimensions while the view+ // retains the same pixel size. Showing it must still reconcile the grid.+ buffer.resize(10, 5);+ buffer.write('new screen');+ resizes.clear();+ await tester.pump();+ expect(buffer.viewWidth, 10);+ expect(buffer.viewHeight, 5);+ expect(resizes, isEmpty);+ enabled.value = true;+ await tester.pump();+ expect((buffer.viewWidth, buffer.viewHeight), (columns, rows));+ expect(resizes, [(columns, rows)]);+ expect(buffer.buffer.getText(), contains('new screen'));++ buffer.write('\x1b[3;7r');+ await tester.pump();+ expect((buffer.buffer.marginTop, buffer.buffer.marginBottom), (2, 6));+ resizes.clear();+ enabled.value = false;+ await tester.pump();+ enabled.value = true;+ await tester.pump();+ expect(resizes, isEmpty);+ expect((buffer.buffer.marginTop, buffer.buffer.marginBottom), (2, 6));+ await tester.pumpWidget(const SizedBox());+ enabled.dispose();+ },+ );++ testWidgets('covered routes suspend a retained terminal widget until shown', (+ tester,+ ) async {+ final buffer = Terminal()..write('\x1b[41m \x1b[0m');+ final enabled = ValueNotifier(true);+ await tester.pumpWidget(+ MaterialApp(+ home: RepaintBoundary(+ key: const ValueKey('terminal pixels'),+ child: ValueListenableBuilder<bool>(+ valueListenable: enabled,+ child: TerminalView(buffer),+ builder: (_, value, child) => TickerMode(+ enabled: value,+ child: Offstage(offstage: !value, child: child),+ ),+ ),+ ),+ ),+ );+ final view = tester.state<TerminalViewState>(find.byType(TerminalView));+ final render = view.renderTerminal;+ expect(await _firstCellColor(tester, view), view.widget.theme.red);+ enabled.value = false;+ await tester.pump();+ for (var i = 0; i < 20; i++) {+ buffer.write('covered output $i\r\n');+ }+ buffer.write('\x1b[H\x1b[42m \x1b[0m');+ expect(render.debugNeedsLayout, isFalse);+ expect(tester.binding.hasScheduledFrame, isFalse);+ enabled.value = true;+ await tester.pump();+ expect(view.renderTerminal, same(render));+ expect(await _firstCellColor(tester, view), view.widget.theme.green);+ expect(buffer.buffer.getText(), contains('covered output 19'));+ buffer.write('visible output');+ expect(render.debugNeedsLayout, isTrue);+ await tester.pump();+ await tester.pumpWidget(const SizedBox());+ enabled.dispose();+ });++ testWidgets(+ 'native caret updates coalesce and refresh on the first resumed frame',+ (tester) async {+ final buffer = Terminal();+ final enabled = ValueNotifier(true);+ await tester.pumpWidget(+ MaterialApp(+ home: ValueListenableBuilder<bool>(+ valueListenable: enabled,+ builder: (_, value, _) => Offstage(+ offstage: !value,+ child: TerminalView(+ buffer,+ autofocus: true,+ renderingEnabled: value,+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ final view = tester.state<TerminalViewState>(find.byType(TerminalView));+ expect(tester.testTextInput.hasAnyClients, isTrue);+ expect(+ tester.testTextInput.log.where(+ (call) => call.method == 'TextInput.setCaretRect',+ ),+ isNotEmpty,+ );+ tester.testTextInput.log.clear();+ for (var i = 1; i <= 30; i++) {+ buffer.write('\r${List.filled(i, 'x').join()}');+ }+ expect(tester.testTextInput.log, isEmpty);+ await tester.pump();+ final rects = tester.testTextInput.log+ .where((call) => call.method == 'TextInput.setCaretRect')+ .toList();+ expect(rects, hasLength(1));+ final expected = view.renderTerminal.localToGlobal(+ view.renderTerminal.cursorOffset,+ );+ expect(rects.single.arguments['x'], expected.dx);+ expect(rects.single.arguments['y'], expected.dy);++ enabled.value = false;+ await tester.pump();+ tester.testTextInput.log.clear();+ buffer.write('\rhidden cursor');+ expect(tester.testTextInput.log, isEmpty);+ enabled.value = true;+ await tester.pump();+ final resumed = tester.testTextInput.log+ .where((call) => call.method == 'TextInput.setCaretRect')+ .toList();+ expect(resumed, hasLength(1));+ final current = view.renderTerminal.localToGlobal(+ view.renderTerminal.cursorOffset,+ );+ expect(resumed.single.arguments['x'], current.dx);+ expect(resumed.single.arguments['y'], current.dy);+ await tester.pumpWidget(const SizedBox());+ enabled.dispose();+ },+ );+}diff --git a/desktop/third_party/xterm/lib/src/terminal_view.dart b/desktop/third_party/xterm/lib/src/terminal_view.dartindex cfabb6f8c..32c9091d7 100644--- a/desktop/third_party/xterm/lib/src/terminal_view.dart+++ b/desktop/third_party/xterm/lib/src/terminal_view.dart@@ -33,6 +33,7 @@ class TerminalView extends StatefulWidget {this.padding,this.scrollController,this.autoResize = true,+ this.renderingEnabled = true,this.backgroundOpacity = 1,this.focusNode,this.autofocus = false,@@ -77,6 +78,12 @@ class TerminalView extends StatefulWidget {/// size changes. [true] by default.final bool autoResize;+ /// Whether output should schedule renderer layout/paint work. Disable while+ /// retaining a hidden view; the terminal buffer continues receiving output.+ /// Re-enabling reconciles geometry and scroll position on the next layout.+ /// An enclosing disabled [TickerMode] also suspends rendering updates.+ final bool renderingEnabled;+/// Opacity of the terminal background. Set to 0 to make the terminal/// background transparent.final double backgroundOpacity;@@ -260,6 +267,7 @@ class TerminalViewState extends State<TerminalView> {offset: offset,padding: MediaQuery.of(context).padding,autoResize: widget.autoResize,+ renderingEnabled: widget.renderingEnabled,textStyle: widget.textStyle,textScaler: widget.textScaler ?? MediaQuery.textScalerOf(context),theme: widget.theme,@@ -631,6 +639,7 @@ class _TerminalView extends LeafRenderObjectWidget {required this.offset,required this.padding,required this.autoResize,+ required this.renderingEnabled,required this.textStyle,required this.textScaler,required this.theme,@@ -652,6 +661,8 @@ class _TerminalView extends LeafRenderObjectWidget {final bool autoResize;+ final bool renderingEnabled;+final TerminalStyle textStyle;final TextScaler textScaler;@@ -678,6 +689,8 @@ class _TerminalView extends LeafRenderObjectWidget {offset: offset,padding: padding,autoResize: autoResize,+ renderingEnabled:+ renderingEnabled && TickerMode.valuesOf(context).enabled,textStyle: textStyle,textScaler: textScaler,theme: theme,@@ -693,6 +706,8 @@ class _TerminalView extends LeafRenderObjectWidget {@overridevoid updateRenderObject(BuildContext context, RenderTerminal renderObject) {renderObject+ ..renderingEnabled =+ renderingEnabled && TickerMode.valuesOf(context).enabled..terminal = terminal..controller = controller..offset = offsetdiff --git a/desktop/third_party/xterm/lib/src/ui/render.dart b/desktop/third_party/xterm/lib/src/ui/render.dartindex 4557c48c2..df79edd58 100644--- a/desktop/third_party/xterm/lib/src/ui/render.dart+++ b/desktop/third_party/xterm/lib/src/ui/render.dart@@ -1,5 +1,6 @@import 'dart:math' show max;import 'package:flutter/rendering.dart';+import 'package:flutter/scheduler.dart';import 'package:flutter/widgets.dart';import 'package:xterm/src/core/buffer/cell_offset.dart';import 'package:xterm/src/core/buffer/range.dart';@@ -24,6 +25,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {required ViewportOffset offset,required EdgeInsets padding,required bool autoResize,+ bool renderingEnabled = true,required TerminalStyle textStyle,required TextScaler textScaler,required TerminalTheme theme,@@ -38,6 +40,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {_offset = offset,_padding = padding,_autoResize = autoResize,+ _renderingEnabled = renderingEnabled,_focusNode = focusNode,_cursorType = cursorType,_alwaysShowCursor = alwaysShowCursor,@@ -53,9 +56,11 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {Terminal _terminal;set terminal(Terminal terminal) {if (_terminal == terminal) return;- if (attached) _terminal.removeListener(_onTerminalChange);+ if (attached && _renderingEnabled) {+ _terminal.removeListener(_onTerminalChange);+ }_terminal = terminal;- if (attached) _terminal.addListener(_onTerminalChange);+ if (attached && _renderingEnabled) _terminal.addListener(_onTerminalChange);_resizeTerminalIfNeeded();markNeedsLayout();}@@ -92,6 +97,22 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {markNeedsLayout();}+ bool _renderingEnabled;+ set renderingEnabled(bool value) {+ if (value == _renderingEnabled) return;+ _renderingEnabled = value;+ if (attached) {+ if (value) {+ _terminal.addListener(_onTerminalChange);+ } else {+ _terminal.removeListener(_onTerminalChange);+ }+ }+ // Catch up from the live buffer once, preserving follow-tail or the user's+ // scroll offset. Hidden output never queues a renderer layout or paint.+ if (value) markNeedsLayout();+ }+set textStyle(TerminalStyle value) {if (value == _painter.textStyle) return;_painter.textStyle = value;@@ -159,24 +180,27 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {final TerminalPainter _painter;var _stickToBottom = true;+ bool _editableRectPending = false;void _onScroll() {_stickToBottom = _scrollOffset >= _maxScrollExtent;+ if (!_renderingEnabled) return;markNeedsLayout();- _notifyEditableRect();+ _scheduleEditableRect();}void _onFocusChange() {markNeedsPaint();+ _scheduleEditableRect();}void _onTerminalChange() {markNeedsLayout();- _notifyEditableRect();+ _scheduleEditableRect();}void _onControllerUpdate() {- markNeedsLayout();+ if (_renderingEnabled) markNeedsLayout();}@override@@ -186,7 +210,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {void attach(PipelineOwner owner) {super.attach(owner);_offset.addListener(_onScroll);- _terminal.addListener(_onTerminalChange);+ if (_renderingEnabled) _terminal.addListener(_onTerminalChange);_controller.addListener(_onControllerUpdate);_focusNode.addListener(_onFocusChange);}@@ -214,6 +238,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {@overridevoid performLayout() {size = constraints.biggest;+ if (!_renderingEnabled) return;_updateViewportSize();@@ -222,6 +247,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {if (_stickToBottom) {_offset.correctBy(_maxScrollExtent - _scrollOffset);}+ _scheduleEditableRect();}/// Total height of the terminal in pixels. Includes scrollback buffer.@@ -315,6 +341,27 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {return _terminal.mouseInput(button, buttonState, position);}+ /// Layout can change the scroll offset and ancestors can move this view.+ /// Report the final caret once per frame, including when a retained view+ /// returns without fresh output. Unfocused terminals have no native caret.+ void _scheduleEditableRect() {+ if (_editableRectPending ||+ !attached ||+ !_renderingEnabled ||+ !_focusNode.hasFocus ||+ _onEditableRect == null) {+ return;+ }+ _editableRectPending = true;+ SchedulerBinding.instance.addPostFrameCallback((_) {+ _editableRectPending = false;+ if (!attached || !_renderingEnabled || !_focusNode.hasFocus || !hasSize) {+ return;+ }+ _notifyEditableRect();+ });+ }+void _notifyEditableRect() {final cursor = localToGlobal(cursorOffset);@@ -344,13 +391,19 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {if (_viewportSize != viewportSize) {_viewportSize = viewportSize;- _resizeTerminalIfNeeded();}+ // A retained view may have received a replacement screen while hidden,+ // even when its own pixel dimensions did not change.+ _resizeTerminalIfNeeded();}/// Notify the underlying terminal that the viewport size has changed.void _resizeTerminalIfNeeded() {- if (_autoResize && _viewportSize != null) {+ if (_renderingEnabled &&+ _autoResize &&+ _viewportSize != null &&+ (_terminal.viewWidth != _viewportSize!.width ||+ _terminal.viewHeight != _viewportSize!.height)) {_terminal.resize(_viewportSize!.width,_viewportSize!.height,diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.mdindex d660f9826..d6d7309fa 100644--- a/docs/harness-v2-performance.md+++ b/docs/harness-v2-performance.md@@ -1,6 +1,6 @@# Harness V2 performance checks-Measured on 2026-09-12, with retained-canvas and idle-work continuations on 2026-09-13, using Apple M2 Max, macOS 26.6.2, Flutter 3.47.2 and Dart 3.13.2.+Measured on 2026-09-12, with retained-canvas, idle-work and background-output continuations on 2026-09-13, using Apple M2 Max, macOS 26.6.2, Flutter 3.47.2 and Dart 3.13.2.The explicit benchmark runs in the headless Flutter test runner with isolated synthetic sessions. It never opens a sample-data app or connects to a real agent. Run it from `desktop/`:@@ -81,7 +81,32 @@ The empty Swarm's remaining timer belongs to its focused search field caret. Theflutter test test/benchmarks/terminal_idle_benchmark.dart --no-pub --reporter expanded```-Global link-modifier handlers are now registered only while a visible link is under the pointer, removing the per-retained-terminal listener from ordinary keyboard input. Hidden views clear hover state and skip link refresh callbacks. Tests cover focus/tab/zoom changes, covered routes, window inactivity and resumption, session replacement, read-only/connection ownership, and a stationary link pointer across session replacement and modifier release. The complete Flutter suite passes with 1,010 tests and one skip.+Global link-modifier handlers are now registered only while a visible link is under the pointer, removing the per-retained-terminal listener from ordinary keyboard input. Hidden views clear hover state and skip link refresh callbacks. Tests cover focus/tab/zoom changes, covered routes, window inactivity and resumption, session replacement, read-only/connection ownership, and a stationary link pointer across session replacement and modifier release. That continuation's full suite passed 1,010 tests with one skip.++## Rendering background output++Offstage had stopped hidden panes from painting, but their renderers still listened to every terminal write, requested layout and calculated native caret coordinates. The new `TerminalView.renderingEnabled` flag defaults to true; `TerminalPanel` supplies its visibility, and a disabled enclosing ticker mode also suspends the leaf renderer. A suspended renderer detaches its output listener and skips viewport/scroll reconciliation. The session continues parsing incoming output into its existing buffer.++Showing the view requests one layout against the current buffer. It preserves a manually chosen scroll offset or follows the new tail, and reconciles changed terminal dimensions even when the pane's pixel size is unchanged. Matching dimensions skip emulator resize, preserving a TUI's scrolling margins. Session/keyframe changes still update retained views as needed.++The paired headless workload starts with 1,000 history lines per terminal and four visible panes in a 1280×800 window. Each sample writes four short ANSI updates to one existing row in every selected terminal, then pumps Flutter. It uses 20 warmups and 60 measured samples, excluding sockets, binary decoding and physical display timing:++| Retained terminals | Output destinations | Before median / p95 | Final median / p95 | Hidden renderers needing layout before → after |+| ---: | --- | ---: | ---: | ---: |+| 16 | 12 hidden terminals | 0.901 / 1.366 ms | 0.110 / 0.169 ms | 12 → 0 |+| 16 | All 16 terminals | 1.117 / 2.027 ms | 0.757 / 0.921 ms | 12 → 0 |+| 48 | 44 hidden terminals | 1.255 / 1.641 ms | 0.206 / 0.227 ms | 44 → 0 |+| 48 | All 48 terminals | 1.574 / 1.836 ms | 0.766 / 0.945 ms | 44 → 0 |++Hidden-only bursts no longer schedule a Flutter frame in this workload. Their median CPU cost fell by 88% and 84%; the mixed visible/hidden workloads fell by 32% and 51%. These are headless debug CPU observations with host-load/JIT variability, not native latency or total app CPU reductions. Logs: `/private/tmp/harness-v2-background-before.log` and `/private/tmp/harness-v2-background-measured.log`.++```bash+flutter test test/benchmarks/terminal_background_benchmark.dart --no-pub --reporter expanded+```++Native caret coordinates now coalesce into one callback after the frame, using final scroll offsets and ancestor positions. Only a focused, enabled renderer schedules the update. Focus and restored layout refresh the caret even without new output. A test sends 30 cursor-changing writes before a frame and verifies one final native caret message; the terminal input dispatch path remains unchanged.++Four new checks cover real `TerminalSession.handleBinary` output while hidden, selection/manual-scroll/follow-tail preservation, first-frame raster pixels, changed terminal dimensions, unchanged TUI scroll margins, covered routes with a retained widget, and native caret coordinates on restoration. The final full suite passes 1,014 tests with one skip.## Terminal output allocationsdiff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdindex 39e401408..eda7d4004 100644--- a/docs/harness-v2-progress.md+++ b/docs/harness-v2-progress.md@@ -1,6 +1,6 @@# Harness App V2 — development handoff-Updated 2026-09-13 after the idle-work performance continuation. This is a working preview, not a release.+Updated 2026-09-13 after the background-output performance continuation. This is a working preview, not a release.## Resume here@@ -15,8 +15,9 @@ Updated 2026-09-13 after the idle-work performance continuation. This is a worki- The user requested research into expert developers' tools and a smaller feature set. [Developer-tool research and the keep/improve/remove/defer audit](harness-v2-developer-tools-research.md) documents firsthand sources and a proposed three-part focus: durable sessions, instant navigation, and steering agents without losing concentration.- Cmd+P now jumps to existing agents and Swarms with fuzzy project/machine context and bounded recent-work history. Cmd+Shift+F remains Add agent. The jump dialog has no transition or backdrop blur; selecting an existing view is focus-only, including terminals controlled elsewhere. The 2,000-agent headless search check measured 1.06 ms median / 1.15 ms p95 CPU time; this is not native display latency.- Swarm terminals now keep the same widget ancestry across tabs, zoom and presets, retaining unchanged cells and headers. The paired headless check reduced median tab-switch CPU time from 20.924 to 12.226 ms with 16 terminals and from 14.151 to 8.925 ms with 48; focus changes also improved. Settings route and section fades are removed. These are debug CPU measurements, not native input-to-display timings.-- Cursor timers now follow the active, focused terminal, stopping for hidden/covered views and inactive windows. With 48 retained terminals, the isolated five-second observation fell from 480 periodic callbacks to 10 in the foreground and zero when inactive. New swarm retains only its search caret timer. Link-modifier keyboard listeners exist only while hovering a visible link. The full suite now passes 1,010 tests with one skip.-- The final Release preview was rebuilt and normally relaunched; PID **50640** was the sole V2 instance at the last check. Revalidate the process before any later restart. CUA still reports `cgWindowNotFound` when selecting that full bundle path after this rebuild, as it did after an earlier CUA reset and normal relaunches. CUA's surface inventory lists the preview as running. An earlier relaunched process did have a 1280×840 onscreen CoreGraphics window. Bundle-ID selection was also ambiguous with the retained backup under `/Users/ab/code/harness-app-v2`; no backup was altered. Do not claim the new jump interaction, stable canvas or cursor lifecycle was reviewed in the live native window. The actual native titlebar/canvas had been reviewed before these continuations; the new picker was visually inspected in an isolated Flutter render with native font files and engine icons loaded.+- Cursor timers now follow the active, focused terminal, stopping for hidden/covered views and inactive windows. With 48 retained terminals, the isolated five-second observation fell from 480 periodic callbacks to 10 in the foreground and zero when inactive. New swarm retains only its search caret timer. Link-modifier keyboard listeners exist only while hovering a visible link. The idle-work continuation's full suite passed 1,010 tests with one skip.+- Ordinary hidden output now updates the buffer without scheduling a renderer frame. The paired 16/48-terminal debug benchmark reduced hidden-output median CPU cost by 88%/84%; mixed visible/hidden output improved by 32%/51%. Restoring a view reconciles its current buffer, scroll and dimensions once; native caret coordinates coalesce after the frame. The final full suite passes 1,014 tests with one skip.+- The final Release preview was rebuilt and normally relaunched; PID **69137** was the sole V2 instance at the last check. Revalidate the process before any later restart. CUA still reports `cgWindowNotFound` when selecting that full bundle path after this rebuild, as it did after an earlier CUA reset and normal relaunches. CUA's earlier surface inventory listed the preview as running. An earlier relaunched process did have a 1280×840 onscreen CoreGraphics window. Bundle-ID selection was also ambiguous with the retained backup under `/Users/ab/code/harness-app-v2`; no backup was altered. Do not claim the new jump interaction, stable canvas, cursor lifecycle or renderer restoration was reviewed in the live native window. The actual native titlebar/canvas had been reviewed before these continuations; the new picker was visually inspected in an isolated Flutter render with native font files and engine icons loaded. First-frame renderer pixels and native caret messages are now covered by isolated Flutter checks.- Continue implementation here. Do not create another repository or fork for V2.```bash@@ -75,6 +76,8 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83- `TerminalPane.lastViewSize` retains geometry. Hidden `TerminalPanel` views stop auto-resizing/reporting viewport and release input focus.- The cursor timer exists only while the visible terminal has actual keyboard focus, accepts input, is writable, has enabled ticker mode and the application is active. Focus, session, ticker-mode and lifecycle listeners update it directly; retained inactive panes have no cursor polling loop. Stopping restores only the local bright phase, preserving the remote program's cursor visibility.- Link-modifier keyboard handlers are registered only while a visible link is under the pointer. Hidden panes clear hover state and skip hover refresh work; mounting a replacement terminal refreshes a stationary pointer against the current buffer.+- Vendored `TerminalView.renderingEnabled` defaults to true and combines with the enclosing ticker mode at the leaf render widget. `TerminalPanel` supplies its visibility. Disabled renderers detach from ordinary terminal-write notifications and skip viewport/scroll work, while session buffers continue receiving output. Re-enabling requests one layout against the latest buffer, preserving manual scroll or following the tail.+- Renderer resize reconciles the emulator's actual dimensions with the visible viewport, including a changed screen received while hidden at the same pane size. Matching dimensions avoid redundant resize and preserve TUI scroll margins. Native caret coordinates update once after the frame for the focused renderer, including focus and view restoration without new output.- Compact headers remove routine transport/status/pin clutter, retaining exceptional states and offline/unavailable placeholders.- Existing terminal sessions/transports/renderer and patched `third_party/xterm` are retained. One regression verifies renderer identity, hidden geometry during window resize, and input going only to the active view.- Binary dispatch reads current session stream IDs and skips unrelated sessions before awaiting them, avoiding a scheduling turn per unrelated view. No duplicate stream registry is maintained. Socket FIFO remains in `WsConn`; regressions additionally exercise direct concurrent dispatch during tab reorder, hidden shared views, machine isolation, unknown streams and corrupt-frame recovery.@@ -159,7 +162,8 @@ The reopen binding follows the documented Mac tab-recovery shortcut in [Safari](| --- | --- || macOS debug build | Passed and launched from the monorepo with real saved Swarms and terminals. || macOS optimized local build | Passed and running with the real entry point and saved V2 state. Local ad hoc signing requires the command-line `ENABLE_HARDENED_RUNTIME=NO` override for Flutter's framework; distribution signing settings remain unchanged. The distribution Developer ID certificate is unavailable; nothing was uploaded. Normal asynchronous quit and relaunch were verified. Unlocked native review confirmed the taller tab container, edge-to-edge empty wallpaper, and the flat populated canvas joining the selected tab. The native hover rendering was also inspected in a local image. |-| Full Flutter suite | **1,010 passed, 1 skipped** on the final idle-work production code, including terminal, modal, persistence, layout and shortcut regressions. |+| Full Flutter suite | **1,014 passed, 1 skipped** on the final background-output production code, including terminal, modal, persistence, layout and shortcut regressions. |+| Hidden rendering and native caret | Four new checks cover binary output arriving without hidden layout/frame requests; retained selection, manual scroll and follow-tail; first-visible-frame raster pixels; changed emulator dimensions and preserved TUI scroll regions; covered routes; and coalesced/fresh caret coordinates. The focused restoration/IME/key-ownership run passed 22 checks. || Cursor and link activity | Four new checks cover one cursor clock across retained Swarms/focus/zoom, immediate suspension for inactive windows and disabled ticker mode, session replacement and read-only/connection ownership, and stationary link hover across session replacement/modifier release. The earlier focused cursor/session run passed 74 checks. || Retained canvas and header | Five new checks cover stable element ancestry and terminal State across tabs/zoom/presets, first-frame per-Swarm scrolling, tall splits and hidden geometry, font metrics at unchanged point size, and fresh header metadata/callbacks. Layout checks compare legacy and Swarm geometry for all fixed presets and auto layouts at two sizes. || Jump navigation | 13 new state/widget checks cover fuzzy context, shared/offline views, focus-only navigation, preserved layout and terminal state, bounded recents, stale results, captured destinations, immediate focus, keyboard scrolling, live discovery and Add separation. The three widget checks also pass after adding assertions that the first terminal key reaches only the destination session. |@@ -172,6 +176,7 @@ The reopen binding follows the documented Mac tab-recovery shortcut in [Safari](| Flutter analyzer | **0 errors, 0 warnings, 12 existing vendored xterm infos**; passes with `--no-fatal-infos`. || Headless performance | The prior five-case catalog/terminal/output benchmark passed. The paired retained-canvas continuation reran both 16/48-terminal cases with new focus measurements: tab medians 12.226 / 8.925 ms and focus medians 5.284 / 4.586 ms. Reproducible commands and limits in `docs/harness-v2-performance.md`. || Idle-work measurement | Both isolated timer scenarios passed: 16/48 retained terminals now share one focused cursor clock, with 10 callbacks in five seconds, and zero terminal cursor callbacks when the window is inactive or an empty Swarm is shown. Empty New swarm keeps its search field's caret timer. These are fake-clock structural counts, not native process CPU/battery measurements. |+| Background output measurement | Both 16/48-terminal cases passed with hidden-only and mixed output. Hidden dirty renderers fell from 12/44 to zero; hidden-only bursts schedule no frame in this workload. Final CPU medians are 0.110/0.206 ms for hidden output and 0.757/0.766 ms for all-terminal output. See performance notes for scope and paired results. || AppKit components and container | **170 assertions passed**: the original 151 component checks plus native-container checks at 880, 1280 and 1920 points. These verify height, traffic-light clearance/alignment, direct contact with the content edge and active-tab visibility. The optional container check creates a hidden native window; no window is displayed and no engine, account or terminal is accessed. || Remote terminals / production release | No remote takeover, release, installer, or production CLI update/restart. Cross-platform and end-to-end latency measurements remain. |@@ -181,9 +186,13 @@ Tests now exercise the actual V2 welcome/settings/linking flow. Usage pricing agEvidence on this Mac under `/private/tmp`:-- `harness-v2-idle-full-tests.log`: full 1,010-test pass on the final production changes.+- `harness-v2-background-full-tests.log`: full 1,014-test pass on the final production changes.+- `harness-v2-background-caret-tests.log`: 22 restoration/IME/key-ownership checks, including raster and native-caret assertions.+- `harness-v2-background-analyze.log`: latest diagnostics, 0 errors/warnings and 12 existing vendored infos.+- `harness-v2-background-before.log`, `harness-v2-background-measured.log`: paired parser/render CPU measurements and hidden layout/frame counts.+- `harness-v2-idle-full-tests.log`: full 1,010-test pass on the idle-work changes.- `harness-v2-idle-tests.log`: 74 cursor/session/focus/canvas checks before the hover-listener change.-- `harness-v2-idle-analyze.log`: latest diagnostics, 0 errors/warnings and 12 existing vendored infos.+- `harness-v2-idle-analyze.log`: earlier idle-work diagnostics, 0 errors/warnings and 12 existing vendored infos.- `harness-v2-idle-before.log`, `harness-v2-idle-measured.log`: paired periodic timer counts/callbacks with 16/48 retained terminals, active/inactive windows and empty Swarms.- `harness-v2-canvas-full-tests.log`: full 1,005-test pass on the final production changes.- `harness-v2-canvas-geometry.log`: 39 layout checks after adding the final test-only auto-layout comparison.@@ -214,7 +223,7 @@ Earlier logs contain superseded failures. Temporary logs and toolchains are loca## Remaining work-1. Restore CUA access to the current Release preview and review the new jump workflow, stable canvas, actual project starters and keyboard navigation. The tool currently reports `cgWindowNotFound`; the process is running. The user can change window size and Swarms; re-read UI state before actions and preserve their arrangement.+1. Restore CUA access to the current Release preview and review the new jump workflow, stable canvas, restored terminal output/caret, actual project starters and keyboard navigation. The tool currently reports `cgWindowNotFound`; the process is running. The user can change window size and Swarms; re-read UI state before actions and preserve their arrangement.2. Audit native drag/reorder, overflow, close-last-tab, renaming and accessibility without changing the user's saved agent memberships. Keep any integration runner separate and out of the foreground review app.3. Measure native terminal input and tab-switch responsiveness before making end-to-end latency claims. Headless CPU benchmarks are now recorded. Preserve the existing immediate first-input flush and shared retained renderers.4. Visually confirm app-menu modal behavior and overflow accessibility in AppKit; route/shortcut behavior is covered by passing Flutter tests.