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.

10.4 KB
Raw Blame
import 'swarm_search_field.dart';

import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/theme/app_type.dart';
import 'package:harness/terminal/terminal_text.dart';

import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
import '../state/swarm_attention.dart';
import '../state/swarm_navigation.dart';
import 'engine_identity.dart';

// Ink on the dialog. Dark palettes keep the white ramp it was tuned in; light
// ones take the semantic text tokens, because black at these alphas falls
// under 4.5:1 there.
Color get _ink => grid.AppTheme.pick(grid.AppPalette.textPrimary, Colors.white);
Color get _inkSoft =>
    grid.AppTheme.pick(grid.AppPalette.textSecondary, Colors.white70);
Color get _inkMuted =>
    grid.AppTheme.pick(grid.AppPalette.textSecondary, Colors.white60);
Color get _inkFaint =>
    grid.AppTheme.pick(grid.AppPalette.textSecondary, Colors.white54);

Future<SwarmAttentionEntry?> showSwarmAttention(
  BuildContext context,
  AppNotifier app,
  SwarmNavigationHistory history,
) => showAppDialog<SwarmAttentionEntry>(
  context: context,
  transitionDuration: Duration.zero,
  veilBlur: 0,
  builder: (_) => _SwarmAttention(app: app, recent: history.recent),
);

class _SwarmAttention extends StatefulWidget {
  const _SwarmAttention({required this.app, required this.recent});
  final AppNotifier app;
  final List<String> recent;

  @override
  State<_SwarmAttention> createState() => _SwarmAttentionState();
}

class _SwarmAttentionState extends State<_SwarmAttention> {
  final _scroll = ScrollController();
  late List<SwarmAttentionEntry> _catalog;
  List<SwarmAttentionEntry> _rows = [];
  String _query = '';
  String? _selectedId;
  int _cursor = 0;
  double _rowHeight = 104;
  bool _revealScheduled = false;
  late final _targetName = widget.app.activeSwarm.name;

  @override
  void initState() {
    super.initState();
    _refreshCatalog();
    widget.app.addListener(_onAppChanged);
  }

  void _onAppChanged() => setState(_refreshCatalog);

  void _refreshCatalog() {
    _catalog = swarmAttentionEntries(widget.app, recent: widget.recent);
    _filter();
  }

  void _filter() {
    _rows = filterSwarmAttention(_catalog, _query);
    final index = _rows.indexWhere((row) => row.id == _selectedId);
    _cursor = _rows.isEmpty
        ? 0
        : index >= 0
        ? index
        : _cursor.clamp(0, _rows.length - 1);
    _selectedId = _rows.isEmpty ? null : _rows[_cursor].id;
    _revealSelection();
  }

  void _move(int delta) {
    if (_rows.isEmpty) return;
    setState(() {
      _cursor = (_cursor + delta) % _rows.length;
      _selectedId = _rows[_cursor].id;
    });
    // The list dimensions are already known during a key event. Move before
    // paint so the new highlight and its row arrive in the same frame.
    _scrollToSelection();
  }

  void _revealSelection() {
    if (_revealScheduled) return;
    _revealScheduled = true;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _revealScheduled = false;
      if (mounted) _scrollToSelection();
    });
  }

  void _scrollToSelection() {
    if (!_scroll.hasClients || _rows.isEmpty) return;
    final top = _cursor * _rowHeight;
    final bottom = top + _rowHeight;
    final position = _scroll.position;
    final offset = top < position.pixels
        ? top
        : bottom > position.pixels + position.viewportDimension
        ? bottom - position.viewportDimension
        : position.pixels;
    final target = offset.clamp(0.0, position.maxScrollExtent);
    if (target != position.pixels) _scroll.jumpTo(target);
  }

  void _submit() {
    if (_rows.isNotEmpty && _rows[_cursor].available) {
      Navigator.pop(context, _rows[_cursor]);
    }
  }

  @override
  void dispose() {
    widget.app.removeListener(_onAppChanged);
    _scroll.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    TerminalFontScope.watch(context);
    final scale = MediaQuery.textScalerOf(context);
    // The name, two lines of the question, and the place it came from.
    _rowHeight =
        (scale.scale(AppType.monoLabelSize) * 1.35 +
                scale.scale(AppType.bodySize) * 1.35 * 2 +
                scale.scale(AppType.monoMetaSize) * 1.3 +
                36)
            .clamp(104, double.infinity);
    final selected = _rows.isEmpty ? null : _rows[_cursor];
    return Dialog(
      alignment: const Alignment(0, -0.5),
      insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 48),
      child: SizedBox(
        width: 660,
        height: 560,
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              Row(
                children: [
                  Text('Needs input', style: AppType.heading()),
                  const SizedBox(width: 8),
                  Text(
                    '${_catalog.length}',
                    style: AppType.monoMeta(color: _inkFaint),
                  ),
                  const Spacer(),
                  IconButton(
                    tooltip: 'Close notifications',
                    onPressed: () => Navigator.pop(context),
                    icon: const Icon(AppIcons.close, size: 18),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              SwarmSearchField(
                autofocus: true,
                hintText: 'Find a question, harness, or project',
                onChanged: (value) => setState(() {
                  _query = value;
                  _cursor = 0;
                  _selectedId = null;
                  _filter();
                }),
                onMove: _move,
                onSubmitted: _submit,
              ),
              const SizedBox(height: 12),
              Expanded(
                child: _rows.isEmpty
                    ? Center(
                        child: Text(
                          _catalog.isEmpty
                              ? 'No harnesses need your input'
                              : 'No matching questions',
                          style: AppType.body(color: _inkMuted),
                        ),
                      )
                    : ListView.builder(
                        controller: _scroll,
                        itemCount: _rows.length,
                        itemExtent: _rowHeight,
                        itemBuilder: (context, index) {
                          final row = _rows[index];
                          final destination = row.destination;
                          return ListTile(
                            key: ValueKey(row.id),
                            enabled: row.available,
                            selected: index == _cursor,
                            selectedColor: _ink,
                            selectedTileColor: grid
                                .AppTheme
                                .palette
                                .value
                                .foreground
                                .withValues(alpha: .10),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 12,
                            ),
                            leading: EngineMark(
                              engine: destination.engine,
                              size: 20,
                            ),
                            title: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text(
                                  destination.title,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: AppType.monoLabel(height: 1.35),
                                ),
                                const SizedBox(height: 2),
                                Text(
                                  row.question.prompt,
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: AppType.body(
                                    height: 1.35,
                                    color: _inkSoft,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  destination.detail,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: AppType.monoMeta(
                                    height: 1.3,
                                    color: _inkFaint,
                                  ),
                                ),
                              ],
                            ),
                            trailing: Text(
                              !row.available
                                  ? 'Unavailable'
                                  : destination.hasView
                                  ? 'Jump'
                                  : 'Open Harness',
                              style: AppType.monoMeta(color: _inkFaint),
                            ),
                            onTap: row.available
                                ? () => Navigator.pop(context, row)
                                : null,
                          );
                        },
                      ),
              ),
              const SizedBox(height: 12),
              Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  selected != null && !selected.available
                      ? 'This harness’s terminal is unavailable · Esc to close'
                      : selected != null && !selected.destination.hasView
                      ? '↵ Open Harness in $_targetName · Esc to close'
                      : '↑↓ or ⌃N ⌃P to choose · Return to jump · Esc to close',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: AppType.monoMeta(color: _inkFaint),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}