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.

6.9 KB
Raw Blame
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_font_store.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/terminal_composer.dart';
import 'package:harness/widgets/terminal_panel.dart';
import 'package:xterm/xterm.dart';

/// OS text scaling must not apply a second multiplier to terminal cells or input.
AppNotifier _notifier() {
  final app = AppNotifier(
    config: AppConfig.dev,
    authSession: AuthSession(),
    configStore: null,
  );
  final machine = Machine(
    machineId: 'm1',
    apiKey: '',
    authMode: MachineAuthMode.remote,
    name: 'm1',
    status: 'online',
  );
  app.machines = [machine];
  // `localOnly: false` — the composer only exists for a REMOTE pane, which is
  // exactly the case this isolation protects.
  app.machineStates['m1'] = MachineState(machine)..localOnly = false;
  return app;
}

Future<TerminalSession> _liveSession() async {
  const streamId = '00112233-4455-6677-8899-aabbccddeeff';
  Object? openRequestId;
  final session = TerminalSession(
    machineId: 'm1',
    agentId: 'a1',
    agentName: 'a1',
    engineId: 'claude',
    send: (type, payload) async {
      if (type == 'terminal_open') openRequestId = payload['requestId'];
      return true;
    },
    sendBinary: (_) async => true,
  );
  await session.open(initialCols: 80, initialRows: 24);
  await session.handleFrame('terminal_ready', {
    'requestId': openRequestId,
    'protocolVersion': 3,
    'streamId': streamId,
    'agentId': 'a1',
  });
  await session.handleBinary(
    TerminalBinaryFrame(
      kind: TerminalBinaryKind.keyframe,
      streamId: streamId,
      seq: 0,
      bytes: Uint8List.fromList(utf8.encode(r'$ ')),
      compressed: false,
      cols: 80,
      rows: 24,
    ),
  );
  return session;
}

/// An isolated pane under OS text scaling, outside the app-wide no-scaling scope.
Widget _host(AppNotifier app, TerminalSession session, {double uiScale = 1}) =>
    MaterialApp(
      theme: grid.buildAppTheme(brightness: Brightness.dark),
      builder: (context, child) => MediaQuery.withClampedTextScaling(
        minScaleFactor: uiScale,
        maxScaleFactor: uiScale,
        child: child ?? const SizedBox.shrink(),
      ),
      // ⚠️ Zero, and the test is worthless without it. `MaterialApp` wraps its
      // theme in an `AnimatedTheme` that lerps over 200ms, so a single `pump()`
      // still reports the OLD ThemeData — which made an earlier version of this
      // test pass with the guard REMOVED. Measure after the theme has actually
      // arrived, and settle rather than pumping one frame.
      themeAnimationDuration: Duration.zero,
      home: Scaffold(
        body: SizedBox(
          width: 900,
          height: 400,
          child: TerminalPanel(
            notifier: app,
            session: session,
            focused: true,
            composerVisible: true,
            onToggleComposer: () {},
          ),
        ),
      ),
    );

/// A large OS text scale makes an accidental second multiplier visible.
const double _maxScale = 1.5;

void main() {
  testWidgets('the terminal grid does not apply a second text scale', (
    tester,
  ) async {
    final app = _notifier();
    final session = await _liveSession();
    await tester.pumpWidget(_host(app, session, uiScale: _maxScale));
    await tester.pumpAndSettle();

    final view = tester.widget<TerminalView>(find.byType(TerminalView));
    // Explicit, not inherited: without this the view falls back to the ambient
    // scaler would multiply the chosen cell size again.
    expect(
      view.textScaler,
      TextScaler.noScaling,
      reason:
          'TerminalView must use the chosen point size without a second scale',
    );
    session.dispose();
    app.dispose();
  });

  testWidgets('the terminal is drawn ONLY from its own settings', (
    tester,
  ) async {
    // The renderer and app controls share the persisted terminal preference.
    final app = _notifier();
    final session = await _liveSession();
    await tester.pumpWidget(_host(app, session, uiScale: _maxScale));
    await tester.pumpAndSettle();

    final view = tester.widget<TerminalView>(find.byType(TerminalView));
    expect(
      view.textStyle,
      same(terminalFontStore.value),
      reason: "the face and size are the terminal store's, not the theme's",
    );
    expect(view.padding, const EdgeInsets.all(10));
    expect(view.textScaler, TextScaler.noScaling);

    session.dispose();
    app.dispose();
  });

  testWidgets(
    'the composer uses the terminal point size without a second scale',
    (tester) async {
      final app = _notifier();
      final session = await _liveSession();
      await tester.pumpWidget(_host(app, session, uiScale: _maxScale));
      await tester.pump();

      // The RENDERED size, not the requested one: `style.fontSize` would pass
      // even with the scaler applied on top of it, which is the bug.
      final field = find.descendant(
        of: find.byType(TerminalComposer),
        matching: find.byType(EditableText),
      );
      final editable = tester.widget<EditableText>(field);
      expect(
        editable.textScaler ?? MediaQuery.textScalerOf(tester.element(field)),
        TextScaler.noScaling,
        reason:
            'what is typed here lands in the terminal, so it wears the '
            'terminal face at the terminal size',
      );
      session.dispose();
      app.dispose();
    },
  );

  testWidgets(
    'ambient text scaling cannot change the pane height the terminal gets',
    (tester) async {
      // Ambient scaling must not silently take rows away from the terminal.
      final app = _notifier();
      final session = await _liveSession();

      await tester.pumpWidget(_host(app, session));
      await tester.pumpAndSettle();
      final restingComposer = tester.getSize(find.byType(TerminalComposer));
      final restingTerminal = tester.getSize(find.byType(TerminalView));

      await tester.pumpWidget(_host(app, session, uiScale: _maxScale));
      await tester.pumpAndSettle();
      final scaledComposer = tester.getSize(find.byType(TerminalComposer));
      final scaledTerminal = tester.getSize(find.byType(TerminalView));

      expect(
        scaledComposer.height,
        restingComposer.height,
        reason:
            'the composer box is pinned; if it grows it steals terminal rows '
            'and pushes a terminal_resize to the remote agent',
      );
      expect(scaledTerminal.height, restingTerminal.height);
      session.dispose();
      app.dispose();
    },
  );
}