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.

20.1 KB
Raw Blame
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';

import '../core/models.dart' show Agent;
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
import '../state/phone_desk.dart' show PhoneDesk;
import 'engine_identity.dart';

/// The one "Edit name" dialog, opened from every place a name is shown.
///
/// Pulled out of the rail so the pane header could use it too: two copies would
/// have been two sets of error handling for one rename, and the second is the
/// one that quietly stops matching.
///
/// Keyboard-complete on purpose — autofocus, Enter submits, Escape closes —
/// because the way in is a double click but the way through should never need
/// the mouse again.
///
/// And sized for a thumb as much as for a pointer, because the other way in is
/// the phone's `⋯` sheet: the name at 17pt in a 50pt field, selected so the
/// first key replaces it, and 46pt buttons. The title stays small — it names
/// the act; the name is what the dialog is for.
Future<void> showAgentRenameDialog(
  BuildContext context,
  AppNotifier notifier,
  String machineId,
  String agentId,
  String currentName,
) {
  final place = _placeOf(notifier, machineId, agentId);
  final agent = place.agent;
  return showAppDialog<void>(
    context: context,
    builder: (_) => _RenameDialog(
      title: 'Rename Harness',
      currentName: currentName,
      detail: place.detail,
      leading: agent == null
          ? null
          : EngineMark(
              engine: agent.engine,
              displayName: agent.engineDisplayName,
              size: 32,
            ),
      onSave: (name) => notifier.renameAgent(machineId, agentId, name),
    ),
  );
}

/// The same dialog for a computer — Settings ▸ Computers. Its name is the account's, kept by the
/// backend ([AppNotifier.renameMachine]), so it holds to the backend's length.
Future<void> showMachineRenameDialog(
  BuildContext context,
  AppNotifier notifier,
  String machineId,
) {
  final machine = notifier.stateOf(machineId)?.machine;
  if (machine == null) return Future.value();
  final hostname = machine.hostname?.trim() ?? '';
  return showAppDialog<void>(
    context: context,
    builder: (_) => _RenameDialog(
      title: 'Rename Computer',
      currentName: machine.displayName,
      // What the computer calls itself, which a rename does not change — the one name left to
      // tell it by once its own has gone.
      detail: hostname == machine.displayName ? '' : hostname,
      leading: Icon(
        LucideIcons.laptopMinimal300,
        size: 28,
        color: grid.AppPalette.textSecondary,
      ),
      maxLength: AppNotifier.machineNameMaxLength,
      onSave: (name) => notifier.renameMachine(machineId, name),
    ),
  );
}

/// The same dialog for a desk tab — held from its chip in Find. The desktop's "Rename Tab", and
/// the name every computer's tab row then shows ([AppNotifier.renameDeskTab]).
///
/// [currentName] is the name the chip shows, which for a tab nobody named is the one its
/// harnesses give it (`deskTabNames`) — what the person is looking at when they hold it.
Future<void> showDeskTabRenameDialog(
  BuildContext context,
  AppNotifier notifier,
  String tabId,
  String currentName,
) => showAppDialog<void>(
  context: context,
  builder: (_) => _RenameDialog(
    title: 'Rename Tab',
    currentName: currentName,
    detail: '',
    maxLength: PhoneDesk.nameMaxLength,
    onSave: (name) async {
      final trimmed = name.trim();
      if (trimmed.isEmpty) return 'Name cannot be empty';
      if (trimmed.length > PhoneDesk.nameMaxLength) {
        return 'Use ${PhoneDesk.nameMaxLength} characters or fewer.';
      }
      // Closed on another computer while the dialog was open: a rename now would change nothing.
      if (!notifier.deskTabs.any((tab) => tab.id == tabId)) {
        return 'This tab has been closed.';
      }
      if (!notifier.deskWritable) return 'Rename failed. Try again later.';
      notifier.renameDeskTab(tabId, trimmed);
      return null;
    },
  ),
);

/// The field's corner — the buttons' too. Its focus ring stands 4 outside it,
/// on the same curve.
const double _fieldRadius = kDialogControlRadius;

/// ⚠️ A widget that OWNS its controller, not a `StatefulBuilder` over one made
/// beside `showDialog`.
///
/// That is what this file used to be, and it crashed the app on Escape: the
/// controller was disposed the moment `showDialog`'s future resolved, which is
/// when the route STARTS animating out — the dialog is still on screen and
/// still rebuilding for the length of that transition, and the first rebuild
/// after the dispose threw "A TextEditingController was used after being
/// disposed" and took the window to a red screen.
///
/// A `State` disposes on unmount instead, which happens after the transition
/// has finished and the route is gone, so there is nothing left to rebuild.
class _RenameDialog extends StatefulWidget {
  const _RenameDialog({
    required this.title,
    required this.currentName,
    required this.detail,
    required this.onSave,
    this.leading,
    this.maxLength,
  });

  /// The act, small, over the field — "Rename Harness".
  final String title;
  final String currentName;

  /// Where the thing lives, under the title; empty for nothing.
  final String detail;

  /// The mark beside the title — an engine's, for an agent.
  final Widget? leading;

  /// The longest name the field takes; null for no limit of its own.
  final int? maxLength;

  /// Sends the name. Null when it took, or the refusal to show under the field.
  final Future<String?> Function(String name) onSave;

  @override
  State<_RenameDialog> createState() => _RenameDialogState();
}

class _RenameDialogState extends State<_RenameDialog> {
  /// Opens with the whole name selected, as the tab rename dialog does: the
  /// name is there to be replaced, so the first key wipes it, and a thumb that
  /// meant to edit it still has the caret.
  late final _controller = TextEditingController(text: widget.currentName)
    ..selection = TextSelection(
      baseOffset: 0,
      extentOffset: widget.currentName.length,
    );

  /// The field's focus, which is what draws the ring around it.
  final _focus = FocusNode();

  /// The text as of the last edit. The controller also notifies on a caret
  /// move, and only a change to the name itself takes an error back.
  ///
  /// ⚠️ Set in [initState], not by a `late` initializer: that would first run
  /// inside [_onEdit] — after the edit — and read the new text as the old one,
  /// so the first keystroke would change nothing on screen.
  late String _text;

  /// The CLI's refusal, shown under the field. Null until one arrives.
  String? _error;

  /// A rename is on its way to the machine: Save spins, and nothing sends a
  /// second one behind it.
  bool _busy = false;

  @override
  void initState() {
    super.initState();
    _text = _controller.text;
    _controller.addListener(_onEdit);
    _focus.addListener(_onFocus);
  }

  /// The route's entrance, watched once — see [_raiseKeyboard].
  Animation<double>? _entrance;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_entrance != null) return;
    final entrance = ModalRoute.of(context)?.animation;
    if (entrance == null) return;
    _entrance = entrance;
    if (entrance.isCompleted) {
      WidgetsBinding.instance.addPostFrameCallback((_) => _raiseKeyboard());
    } else {
      entrance.addStatusListener(_onEntrance);
    }
  }

  void _onEntrance(AnimationStatus status) {
    if (!status.isCompleted) return;
    _entrance?.removeStatusListener(_onEntrance);
    _raiseKeyboard();
  }

  /// ⚠️ `autofocus` alone left the phone with no keyboard. The phone's `⋯` sheet
  /// pops and this dialog pushes in the same frame, and the autofocus landed
  /// while the sheet was still leaving — the field came up unfocused, or focused
  /// with the keyboard never shown. So once the dialog has finished arriving the
  /// focus is asked for again, and a field that already holds it asks for the
  /// keyboard outright (a no-op where there is no soft keyboard).
  void _raiseKeyboard() {
    if (!mounted || _busy) return;
    if (_focus.hasFocus) {
      unawaited(SystemChannels.textInput.invokeMethod<void>('TextInput.show'));
    } else {
      _focus.requestFocus();
    }
  }

  @override
  void dispose() {
    _entrance?.removeStatusListener(_onEntrance);
    _controller.dispose();
    _focus.dispose();
    super.dispose();
  }

  String get _name => _controller.text.trim();

  bool get _unchanged => _name == widget.currentName.trim();

  /// Save is offered only for a name that is there and is new: the same name
  /// sent back was a round trip for nothing, and an empty one was only ever
  /// going to be refused.
  bool get _canSave => !_busy && _name.isNotEmpty && !_unchanged;

  void _onFocus() => setState(() {});

  /// An edit takes back the last refusal — it was about a name that is not
  /// there any more — and moves Save with it.
  void _onEdit() {
    if (_controller.text == _text) return;
    setState(() {
      _text = _controller.text;
      _error = null;
    });
  }

  Future<void> _submit() async {
    if (_busy) return;
    // Enter on the name it already has: nothing to send, and closing is what
    // Save would have done had there been anything to save. An empty name goes
    // through — the notifier refuses it on the spot, without a round trip, and
    // the refusal is the answer the Enter was owed.
    if (_name.isNotEmpty && _unchanged) {
      Navigator.of(context).pop();
      return;
    }
    setState(() {
      _busy = true;
      _error = null;
    });
    final result = await widget.onSave(_controller.text);
    // ⚠️ `mounted` is not "still open". Cancel, the veil and Escape all stay
    // live while Save spins, and a dialog closed that way is still mounted for
    // the length of its fade — so an answer landing inside those 140ms found
    // `mounted` true and popped again. The dialog was already going; the route
    // that pop took was the terminal page under it. Only a route that is still
    // in the navigator's history is this dialog's to close.
    if (!mounted || !(ModalRoute.of(context)?.isActive ?? false)) return;
    if (result == null) {
      Navigator.of(context).pop();
      return;
    }
    setState(() {
      _busy = false;
      _error = result;
    });
    _focus.requestFocus();
  }

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    // The red tuned as ink on a dark surface, not [grid.AppPalette.dangerFill]:
    // that one is darkened to carry white lettering, and as the lettering
    // itself it measured 3.1:1 on this card.
    final danger = Theme.of(context).colorScheme.error;
    final error = _error;
    return Dialog(
      // 16 from a phone's edges rather than Material's 40, so the field is as
      // wide as the name needs, up to the 360 the dialog stops at on anything
      // wider.
      insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
      child: Semantics(
        scopesRoute: true,
        namesRoute: true,
        explicitChildNodes: true,
        label: widget.title,
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 360),
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _heading(),
                const SizedBox(height: 18),
                _field(danger: danger, error: error),
                if (error != null)
                  Semantics(
                    liveRegion: true,
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(2, 10, 2, 0),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(top: 1),
                            child: Icon(
                              LucideIcons.circleAlert300,
                              size: 15,
                              color: danger,
                            ),
                          ),
                          const SizedBox(width: 6),
                          Expanded(
                            child: Text(
                              error,
                              style: TextStyle(
                                color: danger,
                                fontSize: 13,
                                height: 1.35,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                const SizedBox(height: 20),
                _actions(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// What is being renamed: its mark, the act, and where it lives. Small on
  /// purpose — the field under it is what the dialog is for.
  Widget _heading() {
    final leading = widget.leading;
    return Row(
      children: [
        if (leading != null) ...[
          SizedBox.square(dimension: 32, child: Center(child: leading)),
          const SizedBox(width: 12),
        ],
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                widget.title,
                style: TextStyle(
                  color: grid.AppPalette.textPrimary,
                  fontSize: 17,
                  fontWeight: grid.AppFont.semibold,
                ),
              ),
              if (widget.detail.isNotEmpty) ...[
                const SizedBox(height: 2),
                Text(
                  widget.detail,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: grid.AppPalette.textSecondary,
                    fontSize: 13,
                  ),
                ),
              ],
            ],
          ),
        ),
      ],
    );
  }

  /// The name, in a field recessed below the card, with a ring around it while
  /// it has focus — in red, while a refusal stands under it.
  Widget _field({required Color danger, required String? error}) {
    final accent = grid.AppPalette.accent;
    final ring = error != null
        ? danger.withValues(alpha: 0.2)
        : _focus.hasFocus
        ? accent.withValues(alpha: 0.3)
        : Colors.transparent;
    OutlineInputBorder border(Color color, {double width = 1}) =>
        OutlineInputBorder(
          borderRadius: BorderRadius.circular(_fieldRadius),
          borderSide: BorderSide(color: color, width: width),
        );
    return AnimatedContainer(
      duration: MediaQuery.disableAnimationsOf(context)
          ? Duration.zero
          : const Duration(milliseconds: 150),
      curve: Curves.easeOut,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(_fieldRadius),
        // A ring rather than a glow: no blur, spread only, so it reads as the
        // field's edge standing out rather than as light behind it.
        boxShadow: [BoxShadow(color: ring, spreadRadius: 4)],
      ),
      child: TextField(
        controller: _controller,
        focusNode: _focus,
        autofocus: true,
        // Held still while the machine answers: an edit made under the spinner
        // would be a name nobody sent.
        readOnly: _busy,
        inputFormatters: [
          if (widget.maxLength case final max?)
            LengthLimitingTextInputFormatter(max),
        ],
        textInputAction: TextInputAction.done,
        style: grid.kFieldTextStyle.copyWith(
          fontSize: 17,
          letterSpacing: grid.AppFont.trackingFor(17),
        ),
        onSubmitted: (_) => unawaited(_submit()),
        decoration: InputDecoration(
          filled: true,
          fillColor: grid.AppPalette.panelBg,
          isDense: true,
          constraints: const BoxConstraints(minHeight: 50),
          contentPadding: const EdgeInsets.fromLTRB(14, 15, 8, 15),
          border: border(error != null ? danger : grid.AppGlass.hair),
          enabledBorder: border(error != null ? danger : grid.AppGlass.hair),
          focusedBorder: border(error != null ? danger : accent, width: 1.5),
          suffixIcon: _controller.text.isEmpty || _busy
              ? null
              : IconButton(
                  tooltip: 'Clear',
                  visualDensity: VisualDensity.compact,
                  onPressed: () {
                    _controller.clear();
                    _focus.requestFocus();
                  },
                  icon: Icon(
                    LucideIcons.circleX300,
                    size: 18,
                    color: grid.AppPalette.textFaint,
                  ),
                ),
          suffixIconConstraints: const BoxConstraints(
            minWidth: 44,
            minHeight: 44,
          ),
        ),
      ),
    );
  }

  /// Cancel and Save, half the width each and tall enough for a thumb.
  ///
  /// Cancel is a neutral well rather than accent text: blue lettering on this
  /// card measured 3.0:1, and a way out does not need the accent to be found.
  Widget _actions() {
    final accent = grid.AppPalette.accent;
    return Row(
      children: [
        Expanded(
          child: FilledButton(
            style: appDialogButtonStyle(
              background: grid.AppSurface.recess,
              foreground: grid.AppPalette.textPrimary,
            ),
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
        ),
        const SizedBox(width: 10),
        Expanded(
          child: FilledButton(
            style: appDialogButtonStyle(
              background: accent,
              foreground: Colors.white,
              // Kept at full colour while it spins: the press was taken, and a
              // button that greyed out under the thumb would read as refused.
              disabledBackground: _busy
                  ? accent
                  : accent.withValues(alpha: 0.22),
              // Disabled, white at 40% vanishes into the pale wash a light card
              // makes of the accent (1.1:1); there the label takes the accent
              // itself — 4.0:1, the wash alone saying it is off. Dark: 3.5:1.
              disabledForeground: _busy
                  ? Colors.white
                  : grid.AppTheme.pick(
                      accent,
                      Colors.white.withValues(alpha: 0.4),
                    ),
            ),
            onPressed: _canSave ? () => unawaited(_submit()) : null,
            child: _busy
                ? Semantics(
                    label: 'Saving',
                    child: SizedBox.square(
                      dimension: 18,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        color: Colors.white,
                        backgroundColor: Colors.white.withValues(alpha: 0.35),
                      ),
                    ),
                  )
                : const Text('Save'),
          ),
        ),
      ],
    );
  }
}

/// Where an agent runs, for the line under the title: the agent (for its
/// engine's mark) and "machine · folder" — the two names every other place
/// tells it apart by.
///
/// Read once, when the dialog opens. An agent missing from its machine's list
/// leaves the mark out and names the machine alone; the rename then answers
/// for itself.
({Agent? agent, String detail}) _placeOf(
  AppNotifier notifier,
  String machineId,
  String agentId,
) {
  final machine = notifier.stateOf(machineId);
  final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
  return (
    agent: agent,
    detail: [
      ?machine?.machine.displayName,
      ?agent?.project?.label,
    ].where((part) => part.isNotEmpty).join(' · '),
  );
}