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.8 KB
Raw Blame
import 'dart:async';
import 'dart:convert';

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

/// Remembers which agents were on screen, so reopening the app returns to the
/// desk it was left on rather than to whatever happens to load first.
///
/// Only the intent is stored — machine and agent ids. Sizes, sessions and
/// stream ids are all facts about a particular run and would be lies by the
/// next one.
class PaneLayoutStore {
  PaneLayoutStore({LocalKeyValueStore? storage})
    : _storage = storage ?? HarnessFileStore.shared;

  static const _key = 'terminal_pane_layout';

  /// The ceiling on tiles, enforced on the way IN as well as out: a file written
  /// by a future build that allows more must not make this one try to open
  /// terminals it has nowhere to put.
  ///
  /// Nine, because ⌘1–⌘9 already addresses that many and a tenth would have no
  /// key. It is a CEILING, not a target — how many actually fit is decided by
  /// the window, since every terminal has a floor of 40 columns and 12 rows
  /// that both this app and the daemon enforce. On a 1280px window with the
  /// rail open that is about three columns; on a 2560px display, six.
  static const maxPanes = 9;

  final LocalKeyValueStore _storage;
  LocalKeyValueStore get storage => _storage;
  String? _pendingSwarmSnapshot;
  Completer<void>? _swarmSave;

  Future<void> flushSwarms() => _swarmSave?.future ?? Future<void>.value();

  /// Failure is silent and lands on an empty layout, which is exactly the
  /// first-run state. A corrupt state file is a reason to open the app the way
  /// a new user sees it, not a reason to refuse to start.
  Future<List<PaneLayoutEntry>> load() async {
    try {
      final raw = await _storage.read(_key);
      if (raw == null || raw.isEmpty) return const [];
      final decoded = jsonDecode(raw);
      if (decoded is! List) return const [];
      final entries = <PaneLayoutEntry>[];
      for (final item in decoded) {
        final entry = PaneLayoutEntry.fromJson(item);
        // One agent cannot be in two tiles: the daemon keeps a single
        // controller per agent, so a duplicate would take its own twin over the
        // moment both opened. Dropping it here means a hand-edited or
        // downgraded file cannot produce that fight.
        if (entry == null ||
            entries.any(
              (existing) =>
                  existing.machineId == entry.machineId &&
                  existing.agentId == entry.agentId,
            )) {
          continue;
        }
        entries.add(entry);
        if (entries.length == maxPanes) break;
      }
      return entries;
    } catch (_) {
      return const [];
    }
  }

  Future<Map<String, dynamic>?> loadSwarms() async {
    try {
      final value = await _storage.read('swarm_layout_v1');
      if (value == null) return null;
      final decoded = jsonDecode(value);
      if (decoded is! Map<String, dynamic> ||
          decoded['version'] != 1 ||
          decoded['swarms'] is! List) {
        return null;
      }
      return decoded;
    } catch (_) {
      return null;
    }
  }

  Future<void> saveSwarms(List<Swarm> swarms, String activeId) {
    // Capture each request before yielding, but keep only the latest snapshot
    // while a write is pending. Holding a navigation key must not queue a full
    // state-file rewrite for every intermediate focus or tab selection.
    try {
      _pendingSwarmSnapshot = jsonEncode({
        'version': 1,
        'activeId': activeId,
        'swarms': swarms.map((s) => s.toJson()).toList(),
      });
    } catch (_) {
      return Future<void>.value();
    }
    final active = _swarmSave;
    if (active != null) return active.future;
    final completion = Completer<void>();
    _swarmSave = completion;
    unawaited(_drainSwarmSnapshots(completion));
    return completion.future;
  }

  Future<void> _drainSwarmSnapshots(Completer<void> completion) async {
    while (_pendingSwarmSnapshot != null) {
      final snapshot = _pendingSwarmSnapshot!;
      _pendingSwarmSnapshot = null;
      try {
        await _storage.write('swarm_layout_v1', snapshot);
      } catch (_) {
        // Keep the current desk usable when storage is unavailable. A newer
        // queued snapshot still gets its own attempt.
      }
    }
    // Clear synchronously before completing: a save requested by a completion
    // listener must start a fresh drain rather than join an already-ended one.
    _swarmSave = null;
    completion.complete();
  }

  Future<void> save(List<PaneLayoutEntry> entries) async {
    try {
      final capped = entries.take(maxPanes).map((e) => e.toJson()).toList();
      await _storage.write(_key, jsonEncode(capped));
    } catch (_) {
      // Kept in memory for this run; see above.
    }
  }
}