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.

5.0 KB
Raw Blame
library;

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import '../core/harness_file_store.dart';
import '../core/local_key_value_store.dart';

/// What happened on a harness while the person was looking elsewhere.
enum AlertKind {
  /// An agent finished its turn. The work you were waiting on is on screen.
  done('Glass'),

  /// A turn ended with an error. Keep the existing turn-end sound.
  failed('Glass'),

  /// An agent stopped and is waiting on a person — a question, a permission.
  /// Nothing moves until somebody answers, which is why it is the more
  /// insistent of the two sounds.
  needsYou('Submarine');

  const AlertKind(this.sound);

  /// A macOS system alert sound, played by name. Using the ones every Mac
  /// already has means no audio asset ships with the app, nothing has to be
  /// decoded, and the sounds sit at the volume the person set for alerts.
  final String sound;
}

/// An on/off preference kept in the app's own store.
///
/// OFF by default, and only the exact string `on` switches it on — a truncated
/// or hand-edited file lands on the default, so a damaged store cannot start
/// interrupting somebody who never asked. Every alert switch follows that rule,
/// so it is written once.
abstract class OnOffPreference extends ValueNotifier<bool> {
  OnOffPreference(this._key, {LocalKeyValueStore? storage})
    : _storage = storage ?? HarnessFileStore.shared,
      super(false);

  final String _key;
  final LocalKeyValueStore _storage;
  Future<void>? _save;

  Future<void> load() async {
    try {
      value = (await _storage.read(_key)) == 'on';
    } catch (_) {
      value = false;
    }
  }

  /// Apply now, persist in order — rapid flips coalesce so an older write
  /// cannot replace the final choice.
  Future<void> set(bool on) {
    if (value == on) return _save ?? Future.value();
    value = on;
    final pending = (_save ?? Future.value()).then(
      (_) => _storage.write(_key, on ? 'on' : 'off'),
    );
    _save = pending;
    return pending;
  }
}

/// Whether this computer plays a sound when an agent finishes or gets stuck.
///
/// OFF by default. An app that makes a noise nobody asked for is a bad guest,
/// and a swarm is many agents: the first thing a new user would hear is a
/// sound they did not choose, from a window they may not be looking at. It is
/// one switch away in Settings ▸ Notifications for anybody who wants it.
class AlertSoundStore extends OnOffPreference {
  AlertSoundStore({super.storage}) : super('app_alert_sounds');
}

/// Whether a banner appears in the window when an agent finishes or gets stuck.
///
/// OFF by default, like the sound. Both are interruptions, and an app that
/// interrupts without being asked is a bad guest whichever sense it reaches
/// for. One switch each in Settings ▸ Notifications.
class ScreenAlertStore extends OnOffPreference {
  ScreenAlertStore({super.storage}) : super('app_screen_alerts');
}

/// The stores the app reads, loaded at start-up beside the other preferences.
final alertSoundStore = AlertSoundStore();
final screenAlertStore = ScreenAlertStore();

/// Plays the alerts.
///
/// Separate from the store so the thing that DECIDES whether to make a noise
/// and the thing that makes it can be tested apart — and so a test can hear
/// what would have played without a Mac making a sound in CI.
class AlertSounds {
  AlertSounds({
    required this.store,
    MethodChannel? channel,
    this.now = _systemNow,
    this.gap = const Duration(milliseconds: 1500),
  }) : _channel = channel ?? const MethodChannel('harness/swarm_tabs');

  static DateTime _systemNow() => DateTime.now();

  final AlertSoundStore store;
  final MethodChannel _channel;
  final DateTime Function() now;

  /// The least time between two plays of the same sound.
  ///
  /// A swarm is many agents, and a batch of them finishing together is the
  /// ordinary case rather than the rare one — without this it is a burst of
  /// beeps that says nothing more than one beep would. Per sound, so an agent
  /// finishing never swallows the more urgent "somebody is waiting on you".
  final Duration gap;

  final _lastPlayed = <String, DateTime>{};

  /// Ask for a sound. Silent when the feature is off, and when the same kind
  /// played within [gap].
  ///
  /// Never throws and never awaits anything the caller depends on: this is
  /// called from the event dispatcher, and a platform that cannot make a noise
  /// must not break the frame that carried the news.
  void play(AlertKind kind) {
    if (!store.value) return;
    final at = now();
    final last = _lastPlayed[kind.sound];
    if (last != null && at.difference(last) < gap) return;
    _lastPlayed[kind.sound] = at;
    unawaited(
      _channel
          .invokeMethod<void>('playAlert', {'sound': kind.sound})
          .catchError((_) {}),
    );
  }

  /// For tests, and for a window that has been away long enough that the next
  /// event is news again rather than a continuation.
  @visibleForTesting
  void forget() => _lastPlayed.clear();
}