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.

11.8 KB
Raw Blame
import 'dart:ui' show Size;

import '../core/models.dart' show Agent, isAutomaticHarnessName, kUntitledPane;
import 'pane_preset.dart';
import 'pane_arrangement.dart';
import 'terminal_pane.dart';

/// A Personal project's own desk tab id: `project-`, 24 hex characters of
/// the project id's hash, then `-2`, `-3` for its further tabs.
final kProjectTabId = RegExp(
  r'^(project-[0-9a-f]{24})(?:-([2-9]|[1-9][0-9]+))?$',
);

/// A named arrangement of agents. Membership never owns the agent process.
/// Shared agents reuse the same pane/session across swarms, so the daemon has
/// exactly one controller and switching tabs cannot take over our own stream.
class Swarm {
  Swarm({
    required this.id,
    String name = defaultName,
    this.kind = 'harness',
    this.isNewTabPage = false,
    bool? nameIsCustom,
  }) : name = nameIsCustom == true ? name : normalizeName(name),
       nameIsCustom =
           nameIsCustom ??
           (normalizeName(name) != defaultName &&
               !(kind == 'store' && name == storeName) &&
               !(kind == 'companions' && name == companionsName) &&
               !(kind == 'devices' && name == devicesName));

  /// What the tab holds: `harness` — panes of agents (the default); `store` —
  /// the Harness Store, no panes. A store tab is a tab like any other —
  /// switched to, closed, restored — so browsing never covers the strip; it
  /// just is not somewhere a pane can land. Mutable because the store takes
  /// over the New Tab it was opened from, the way a first agent does.
  String kind;

  /// Marks a deliberately opened tab so subsequent actions use its destination.
  bool isNewTabPage;
  bool get isBlankNewTab =>
      isNewTabPage &&
      (kind == 'harness' || (isSuperTab && superTabId == null)) &&
      panes.isEmpty &&
      presets.isEmpty;
  bool get isSuperTab => kind == 'superTab';
  String? superTabId;
  bool get isStore => kind == 'store';
  bool get isCompanions => kind == 'companions';
  bool get isDevices => kind == 'devices';
  bool get isUtility => isStore || isCompanions || isDevices;

  /// A Personal project's own tab (super_tabs/personal_projects.dart, task
  /// #3099): it is named after its project, never after a harness in it.
  bool get isProjectTab => kProjectTabId.hasMatch(id);
  bool get isOrchestrator =>
      kind == 'orchestrator' &&
      orchestratorId != null &&
      orchestratorMachineId != null;
  String? orchestratorId, orchestratorMachineId;
  static const storeName = 'Harness Store';
  static const companionsName = 'Companions';
  static const devicesName = 'Devices';

  static const defaultName = 'New Tab';
  // 'New Harness' was the default until 2026-09-15, 'New Agent' for a day
  // after, and 'Untitled Tab' until 2026-09-24; a layout saved then still
  // carries one, as do builds that called tabs swarms. They all display the
  // current placeholder. Explicit custom
  // names bypass this normalization in the constructor.
  static String normalizeName(String name) =>
      const {
            'New Swarm',
            'New swarm',
            'New tab',
            'New Tab',
            'New Harness',
            'New Agent',
            'Untitled Tab',
          }.contains(name) ||
          isAutomaticHarnessName(name)
      ? defaultName
      : name;

  /// Mutable for one reason: a tab from before the desk (`swarm-N`, this
  /// window's numbering) is given a desk id on the first sync
  /// (`AppNotifier._deskStart`). Nothing else ever writes it.
  String id;
  String name;
  bool nameIsCustom;
  String? titleMachineId, titleAgentId;
  final List<TerminalPane> panes = [];
  final Map<int, PanePreset> presets = {};
  final Map<String, PaneArrangement> paneSizes = {};
  PaneArrangement? arranged;
  String? arrangedKey;
  Size? arrangedMinimum;
  int? focusedPaneId;
  int? zoomedPaneId;
  int? previousPaneId;
  int? gridColumns;
  final Map<int, int> pinnedSlots = {};

  /// What a tab is called after the first harness opened into it: that
  /// harness's project — the folder it works in, as the pane header shows it —
  /// because a tab holds a piece of work, and the work is where the harness is
  /// (owner, 2026-09-24). A harness with no project falls back to its own name,
  /// and one with neither leaves the tab new.
  static String titleFor(Agent? agent) {
    final project = agent?.project?.label.trim();
    if (project != null && project.isNotEmpty) return project;
    if (agent == null || agent.displayName == kUntitledPane) return defaultName;
    return agent.displayName;
  }

  bool get isEmptyStarter =>
      !isSuperTab && name == defaultName && panes.isEmpty && presets.isEmpty;

  PaneArrangement? get manualLayout => paneSizes['${panes.length}:manual'];

  List<TerminalPane> get panesInReadingOrder {
    final ordered = panes.toList();
    final layout = arranged?.tiles.length == panes.length
        ? arranged
        : manualLayout;
    if (layout == null || layout.tiles.length != panes.length) return ordered;
    // Splits insert beside their source in the list, which may differ from
    // the visible order. Read each row left to right before reflowing.
    final tiles = {
      for (var i = 0; i < panes.length; i++) panes[i]: layout.tiles[i],
    };
    ordered.sort((a, b) {
      final row = tiles[a]!.top.compareTo(tiles[b]!.top);
      return row != 0 ? row : tiles[a]!.left.compareTo(tiles[b]!.left);
    });
    return ordered;
  }

  void savePaneSizes(String key, PaneArrangement arrangement) {
    paneSizes[key] = arrangement;
    while (paneSizes.length > 64) {
      paneSizes.remove(paneSizes.keys.first);
    }
  }

  void remove(TerminalPane pane) {
    if (!panes.contains(pane)) return;
    final manual = manualLayout;
    final ordered = panesInReadingOrder;
    panes
      ..clear()
      ..addAll(ordered);
    final index = panes.indexOf(pane);
    panes.removeAt(index);
    // Layouts are kept per pane count, so the harness split for a viewer and
    // its terminal would otherwise wait for the next two tiles of any kind.
    // Only the split Harness itself made goes; one the user dragged is theirs.
    if (panes.length == 1 &&
        identical(manual, PaneArrangement.viewerBesideTerminal)) {
      paneSizes.remove('2:manual');
    }
    // Every removal returns to the default for the remaining count, including
    // when that count has an older preset or dragged proportions saved.
    presets.remove(panes.length);
    paneSizes.removeWhere((key, _) => key.startsWith('${panes.length}:'));
    pinnedSlots.remove(pane.id);
    // Keep pins attached to their panes without undoing the visible order.
    pinnedSlots.updateAll((id, _) => panes.indexWhere((p) => p.id == id));
    arranged = null;
    arrangedKey = null;
    arrangedMinimum = null;
    gridColumns = null;
    if (focusedPaneId == pane.id) {
      focusedPaneId = panes.isEmpty
          ? null
          : panes[index.clamp(0, panes.length - 1)].id;
    }
    if (zoomedPaneId == pane.id) zoomedPaneId = null;
    if (previousPaneId == pane.id) previousPaneId = null;
  }

  Map<String, Object?> toJson() {
    final agents = panes
        .where((p) => !isCompanions && p.agentId != null)
        .toList(growable: false);
    return {
      'id': id,
      'name': name,
      if (nameIsCustom) 'nameIsCustom': true,
      if (isNewTabPage) 'newTabPage': true,
      if (titleMachineId != null) 'titleMachineId': titleMachineId,
      if (titleAgentId != null) 'titleAgentId': titleAgentId,
      if (kind != 'harness') 'kind': kind,
      if (superTabId != null) 'superTabId': superTabId,
      if (isOrchestrator) 'orchestratorId': orchestratorId,
      if (isOrchestrator) 'orchestratorMachineId': orchestratorMachineId,
      'focus': agents.indexWhere((p) => p.id == focusedPaneId),
      'previousFocus': agents.indexWhere((p) => p.id == previousPaneId),
      'zoom': agents.indexWhere((p) => p.id == zoomedPaneId),
      'presets': {for (final e in presets.entries) '${e.key}': e.value.id},
      if (paneSizes.isNotEmpty)
        'paneSizes': {
          for (final e in paneSizes.entries) e.key: e.value.toJson(),
        },
      'panes': [
        for (final p in agents)
          PaneLayoutEntry(
            machineId: p.machineId,
            agentId: p.agentId!,
            composerVisible: p.composerVisible,
            pinnedSlot: pinnedSlots[p.id],
          ).toJson(),
      ],
    };
  }
}

/// Session-free history: closing a view never owns the agent's lifetime.
sealed class ClosedWork {
  const ClosedWork({required this.historyId});
  final String historyId;
}

class ClosedAgent extends ClosedWork {
  ClosedAgent(
    TerminalPane pane,
    Swarm swarm, {
    required super.historyId,
    required this.name,
    required this.machineName,
    required this.engine,
  }) : swarmId = swarm.id,
       swarmName = swarm.name,
       index = swarm.panes.indexOf(pane),
       machineId = pane.machineId,
       agentId = pane.agentId!,
       composerVisible = pane.composerVisible,
       pinnedSlot = swarm.pinnedSlots[pane.id],
       manualLayout = swarm.manualLayout,
       remainingAgents = List.unmodifiable([
         for (final other in swarm.panes)
           if (other != pane) (other.machineId, other.agentId),
       ]),
       remainingReadingOrder = List.unmodifiable([
         for (final other in swarm.panesInReadingOrder)
           if (other != pane) (other.machineId, other.agentId),
       ]),
       zoomed = swarm.zoomedPaneId == pane.id;

  final String swarmId, swarmName, machineId, machineName, agentId, name;
  final String? engine;
  final int index;
  final bool composerVisible, zoomed;
  final int? pinnedSlot;
  final PaneArrangement? manualLayout;
  final List<(String, String?)> remainingAgents;
  final List<(String, String?)> remainingReadingOrder;
}

/// Terminal buffers and controllers are released normally; a reopened view
/// reuses any live peer.
class ClosedSwarm extends ClosedWork {
  ClosedSwarm(
    Swarm swarm, {
    required super.historyId,
    required this.index,
    Swarm? replacement,
    this.engine,
  }) : id = swarm.id,
       name = swarm.name,
       nameIsCustom = swarm.nameIsCustom,
       titleMachineId = swarm.titleMachineId,
       titleAgentId = swarm.titleAgentId,
       kind = swarm.kind,
       superTabId = swarm.superTabId,
       orchestratorId = swarm.orchestratorId,
       orchestratorMachineId = swarm.orchestratorMachineId,
       gridColumns = swarm.gridColumns,
       focus = swarm.panes.indexWhere((p) => p.id == swarm.focusedPaneId),
       previousFocus = swarm.panes.indexWhere(
         (p) => p.id == swarm.previousPaneId,
       ),
       zoom = swarm.panes.indexWhere((p) => p.id == swarm.zoomedPaneId),
       presets = Map.unmodifiable(swarm.presets),
       paneSizes = Map.unmodifiable(swarm.paneSizes),
       panes = List.unmodifiable([
         for (final pane in swarm.panes)
           (
             machineId: pane.machineId,
             agentId: pane.agentId,
             composerVisible: pane.composerVisible,
             pinnedSlot: swarm.pinnedSlots[pane.id],
           ),
       ]),
       replacementId = replacement?.id;

  final String id;
  final String name;
  final bool nameIsCustom;
  final String? titleMachineId, titleAgentId;

  /// So a closed store tab reopens as the store, not as an empty harness tab.
  final String kind;
  final String? superTabId;
  final String? orchestratorId, orchestratorMachineId;
  final String? engine;
  final int index;
  final int? gridColumns;
  final int focus;
  final int previousFocus;
  final int zoom;
  final Map<int, PanePreset> presets;
  final Map<String, PaneArrangement> paneSizes;
  final List<
    ({String machineId, String? agentId, bool composerVisible, int? pinnedSlot})
  >
  panes;
  final String? replacementId;

  bool replacesUntouchedWelcome(Swarm swarm) =>
      swarm.id == replacementId &&
      swarm.name == Swarm.defaultName &&
      swarm.panes.isEmpty &&
      swarm.presets.isEmpty;
}