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.

4.3 KB
Raw Blame
import 'dart:async';

import 'package:flutter/foundation.dart';

import '../core/pull_request_status.dart';
import 'app_state.dart';
import 'workspace_status.dart';

typedef _Identity = (String, String, String?, String?, String?);

/// One PR reader for the focused harness, including a dependent viewer's owner.
/// Never publishes a late reply for a different pane or branch.
class WorkspacePullRequest extends ChangeNotifier {
  WorkspacePullRequest(
    this.app, {
    Future<Map<String, dynamic>> Function(String, String)? read,
    DateTime Function()? now,
  }) : _read = read ?? app.readAgentPullRequest,
       _now = now ?? DateTime.now {
    app.addListener(_focusChanged);
    app.foreground.addListener(_scheduleRefresh);
    _focusChanged();
  }
  final AppNotifier app;
  final Future<Map<String, dynamic>> Function(String, String) _read;
  final DateTime Function() _now;
  static const _interval = Duration(seconds: 60);
  final _cache = <_Identity, (DateTime, PullRequestStatus?)>{};
  _Identity? _identity;
  PullRequestStatus? value;
  Timer? _timer;
  int _revision = 0;
  int? _pendingRevision;
  bool _disposed = false;

  void _focusChanged() {
    final focused = WorkspacePaneContext.focused(app);
    final agent = focused?.agent;
    // A cloud harness's pull request is on its frame, from its maker: nothing
    // here has its branch to ask Git about.
    if (agent?.cloud case final cloud?) {
      final link = cloud.pullRequest;
      final number = link == null
          ? null
          : int.tryParse(
              RegExp(r'/pull/(\d+)$').firstMatch(link.url)?.group(1) ?? '',
            );
      final identity = (
        focused!.pane.machineId,
        agent!.id,
        null,
        link?.url,
        null,
      );
      if (identity == _identity) return;
      _identity = identity;
      ++_revision;
      value = PullRequestStatus.fromResult(
        link == null
            ? null
            : {
                'status': 'found',
                'number': number,
                'state': 'Open',
                'url': link.url,
              },
      );
      notifyListeners();
      return;
    }
    final project = agent == null
        ? null
        : app.stateOf(focused!.pane.machineId)?.projectOf(agent);
    final identity =
        focused == null || agent == null || project?.shownBranch == null
        ? null
        : (
            focused.pane.machineId,
            agent.id,
            project?.cwd,
            project?.remote,
            project?.shownBranch,
          );
    if (identity == _identity) return;
    _identity = identity;
    ++_revision;
    final cached = _cache[identity];
    value = cached?.$2;
    notifyListeners();
    _scheduleRefresh();
  }

  void _scheduleRefresh() {
    _timer?.cancel();
    _timer = null;
    if (_disposed || !app.foreground.value) return;
    final identity = _identity, revision = _revision;
    if (identity == null) return;
    // Visibility changes do not cancel a request already sent to the daemon.
    // Let that lookup fill this identity's cache without starting another one.
    if (_pendingRevision == revision) return;
    final cached = _cache[identity];
    final age = cached == null ? _interval : _now().difference(cached.$1);
    if (age >= Duration.zero && age < _interval) {
      _timer = Timer(_interval - age, () => _refresh(identity, revision));
    } else {
      unawaited(_refresh(identity, revision));
    }
  }

  Future<void> _refresh(_Identity identity, int revision) async {
    if (_disposed ||
        revision != _revision ||
        !app.foreground.value ||
        _pendingRevision == revision) {
      return;
    }
    _pendingRevision = revision;
    Map<String, dynamic>? result;
    try {
      result = await _read(identity.$1, identity.$2);
    } catch (_) {
      /* Hidden until available. */
    }
    if (_pendingRevision == revision) _pendingRevision = null;
    if (_disposed || revision != _revision) return;
    value = PullRequestStatus.fromResult(result);
    if (_cache.length >= 32 && !_cache.containsKey(identity)) {
      _cache.remove(_cache.keys.first);
    }
    _cache[identity] = (_now(), value);
    notifyListeners();
    _scheduleRefresh();
  }

  @override
  void dispose() {
    _disposed = true;
    _revision++;
    _timer?.cancel();
    app.removeListener(_focusChanged);
    app.foreground.removeListener(_scheduleRefresh);
    super.dispose();
  }
}