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.

Merge remote-tracking branch 'origin/main' into pr-195

bubu-dudubc46a2a89367
diff --cc desktop/lib/screens/swarm_screen.dart
index 2c1d257ab,6402a4a6d..4926226b6
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@@ -36,10 -42,15 +42,16 @@@ import '../shortcuts/keymap_host.dart'
import '../shortcuts/keymap_native.dart';
import '../shortcuts/keymap_settings.dart';
import '../state/app_state.dart';
+ import '../state/notification_inbox.dart';
+ import '../widgets/notification_inbox.dart';
+ import '../widgets/workspace_notifications_button.dart';
import '../state/harness_sessions.dart';
+ import '../state/harness_activity.dart';
import '../state/harness_placement.dart';
import '../state/new_harness.dart';
+import 'swarm_menu_bus.dart';
+ import '../state/device_form.dart';
+ import '../state/device_finder.dart';
import '../state/pane_arrangement.dart';
import '../terminal/terminal_viewport.dart';
import '../terminal/terminal_text.dart';
@@@ -144,30 -200,33 +201,46 @@@ typedef _NewHarnessContext = (
String? projectName,
});
- /// The command box's title line, a step quieter than the rows under it.
- TextStyle get _boxCaption =>
- grid.AppType.monoLabel(color: kBoxFaint, fontWeight: FontWeight.w400);
+ /// The command box's title line, a step quieter than the rows under it. The
+ /// box is drawn on the terminal's ground, so its muted ink comes from there.
+ TextStyle get _boxCaption => grid.AppType.monoLabel(
+ color: terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ ).muted,
+ fontWeight: FontWeight.w400,
+ );
+
+ /// The veil a workspace dialog drops over the panes behind it. Near-black on a
+ /// dark palette; on a light one a near-black sheet would be the loudest thing
+ /// on screen, so it is the workspace's own grey, which still sits a step below
+ /// the dialog's lighter ground.
+ Color get _workspaceVeil => grid.AppTheme.pick(
+ grid.AppPalette.swarmField,
+ Colors.black,
+ ).withValues(alpha: .94);
class _SwarmScreenState extends State<SwarmScreen> {
- static const _channel = MethodChannel('harness/swarm_tabs');
+ /// The title bar's seam: the `harness/swarm_tabs` channel on macOS — and
+ /// in anything forced onto the native-tabs path, so a test can still mock
+ /// the channel — and the Linux menu bar's bus here. One set of payloads
+ /// out, one switch of actions back.
+ late final SwarmMenuBus _menuBus = widget.nativeTabs == true
+ ? SwarmMenuBus.forChannel()
+ : swarmMenuBus;
/// The tab the middle button went down on, so an up that slid onto another
/// tab closes nothing. Null between presses.
String? _middleDownTab;
late final bool _native =
- widget.nativeTabs ?? (Platform.isMacOS && !kUnderTest);
+ widget.nativeTabs ?? (RuntimePlatform.isMacOS && !kUnderTest);
+
+ /// A menu bar is listening: AppKit's on macOS, the in-window bar on Linux.
+ /// Not the same as [_native], which is whether AppKit also draws the tab
+ /// strip and the title-bar buttons. On Linux Flutter still draws those, so
+ /// the strip stays and only the menu state and actions cross the bus.
- late final bool _menuHost = _native || (Platform.isLinux && !kUnderTest);
++ late final bool _menuHost =
++ _native || (RuntimePlatform.isLinux && !kUnderTest);
late final SwarmProjectStore _projects =
widget.projectStore ??
SwarmProjectStore(storage: kUnderTest ? null : HarnessFileStore.shared);
@@@ -466,15 -745,19 +757,19 @@@
AppKeymap? _sentKeymap;
int? _sentKeymapVersion;
+ bool? _sentDaemonCommands;
void _syncKeymap() {
- if (!_native ||
+ if (!_menuHost ||
- (_sentKeymap == _keymap && _sentKeymapVersion == _keymap.version)) {
+ (_sentKeymap == _keymap &&
+ _sentKeymapVersion == _keymap.version &&
+ _sentDaemonCommands == daemonCommandsActive.value)) {
return;
}
_sentKeymap = _keymap;
_sentKeymapVersion = _keymap.version;
+ _sentDaemonCommands = daemonCommandsActive.value;
unawaited(
- _channel.invokeMethod<void>(
+ _menuBus.send(
'keymapState',
nativeKeymapSnapshot(
_keymap,
@@@ -488,6 -771,7 +783,7 @@@
void _keymapChanged() {
_syncKeymap();
- if (_native) _syncNative();
++ if (_menuHost) _syncNative();
if (mounted) setState(() {});
_search?.refreshCommands();
}
@@@ -717,10 -1103,9 +1113,9 @@@
void _onboardingChanged() {
if (!mounted) return;
- _machinesPanel?.rebuild();
_modelsOverlay?.markNeedsBuild();
_harnessesOverlay?.markNeedsBuild();
- if (_native) _syncNative();
+ if (_menuHost) _syncNative();
setState(() {});
}
@@@ -773,9 -1324,64 +1334,64 @@@
// `_syncNative` — which is subscribed to the APP, not to this notifier. A
// mark that only called setState redrew a tab strip the native window does
// not use, and the badge a person can actually see never moved.
- if (_native) _syncNative();
+ if (_menuHost) _syncNative();
}
+ /// A closed tab left the keyboard on the tab strip. Flutter's focus moves
+ /// there now, before the next frame: a key typed in between must reach
+ /// neither the closed tab's terminal nor the one beside it.
+ void _followTabStripFocus() {
+ if (!mounted || !app.tabStripFocused) return;
+ final request = app.tabStripFocusRequest;
+ if (request == _tabStripRequest) return;
+ _tabStripRequest = request;
+ if (ModalRoute.of(context)?.isCurrent == false) return;
+ _tabStripFocus.requestFocus();
+ FocusManager.instance.applyFocusChangesIfNeeded();
+ }
+
+ void _tabStripFocusChanged() {
+ if (!mounted) return;
+ setState(() {});
- if (_native) _syncNative();
++ if (_menuHost) _syncNative();
+ }
+
+ /// ⏎ on the strip goes into the selected tab. Chords are left to the keymap,
+ /// so shortcuts still work here. Anything else typed — letters, arrows, Tab —
+ /// was meant for the tab that closed and goes nowhere: not into the tab
+ /// beside it, and not into a pane by focus traversal.
+ KeyEventResult _onTabStripKey(FocusNode node, KeyEvent event) {
+ if (!node.hasPrimaryFocus) return KeyEventResult.ignored;
+ final keyboard = HardwareKeyboard.instance;
+ if (keyboard.isMetaPressed ||
+ keyboard.isControlPressed ||
+ keyboard.isAltPressed) {
+ return KeyEventResult.ignored;
+ }
+ final key = event.logicalKey;
+ // A held ⏎ enters once; its repeats are not typed into the terminal.
+ if (event is KeyDownEvent &&
+ (key == LogicalKeyboardKey.enter ||
+ key == LogicalKeyboardKey.numpadEnter)) {
+ if (app.tabStripFocused) {
+ app.focusFromTabStrip();
+ } else {
+ _focusWorkspaceInput();
+ }
+ }
+ return KeyEventResult.handled;
+ }
+
+ /// The keyboard back to the workspace after a picker or dialog closes: the
+ /// tab strip while a closed tab left it there, else the focused pane.
+ bool _focusWorkspaceInput() {
+ if (app.tabStripFocused) {
+ _tabStripFocus.requestFocus();
+ return true;
+ }
+ return app.focusedPane?.session?.focusInput() == true;
+ }
+
void _restoreEmptyFocus() {
if (!mounted ||
app.panes.isNotEmpty ||
@@@ -1581,10 -2276,10 +2286,10 @@@
_canvasFocus.descendantsAreFocusable = _search == null;
if (_search == null &&
ModalRoute.of(context)?.isCurrent != false &&
- app.focusedPane?.session?.focusInput() != true) {
+ !_focusWorkspaceInput()) {
_shellFocus.requestFocus();
}
- if (_native) _syncNative();
+ if (_menuHost) _syncNative();
}
}
if (restoreEntry) await _ensureEmptyEntry();
@@@ -2544,39 -3251,952 +3261,952 @@@
void _modelManagerChanged() {
_syncToolbarNotices();
- if (_native && mounted) _syncNative();
+ if (_menuHost && mounted) _syncNative();
}
- Future<void> _openModelManager() async {
- final openingPanel = _modelsOverlay;
- if (openingPanel == null) dismissTransientMenus();
- await app.modelManager.open();
- if (app.modelManager.error == null &&
- identical(_modelsOverlay, openingPanel)) {
- _closeModelsControls(restoreFocus: false);
+ // ── the daemon (daemons/README.md) ─────────────────────────────────────────
+
+ /// A `daemon_*` or `pair` frame to this computer's harnessd, only while
+ /// daemons are on here: off (or not decided yet), nothing is sent.
+ bool _sendDaemonFrame(String type, Map<String, dynamic> payload) =>
+ !_zoo.isPreview && _zoo.loaded && app.sendDaemonFrame(type, payload);
+
+ void _experimentalFeaturesChanged() {
+ setState(() {});
- if (_native) _syncNative();
++ if (_menuHost) _syncNative();
+ final choice = _creatureChoice;
+ if (_creatureEnabled == choice) return;
+ final hadOverlay = _daemonOverlay != null || _hatchOverlay != null;
+ _creatureEnabled = choice;
+ _closeDaemonHint();
+ _closeDaemon(restoreFocus: false);
+ _closeHatch(restoreFocus: false);
+ _face.dismissVoice();
+ _brain.reset();
+ _plates.reset();
+ _syncDaemon();
+ // A setting change must leave keyboard focus in Settings.
+ if (hadOverlay && _routeIsCurrent && !_dialogOpen) _returnFocusToPane();
+ }
+
+ Map<String, Object?> get _daemonPayload {
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ return {
+ 'visible': _slotShown,
+ 'glyph': _face.glyph,
+ // The ten cells as drawn (centred on the base sprite, a shiny `*` in
+ // the gutter). Counts and progress stay out of the focus bar.
+ 'cell': _face.cell,
+ 'foreground': daemonSlotInk(_face, theme).withValues(alpha: 1).toARGB32(),
+ 'patch': daemonSlotPatch(_face, theme)?.toARGB32(),
+ 'open': _daemonOverlay != null,
+ 'busy': _face.revealing || _zoo.hatchingEgg != null,
+ 'label': _face.label,
+ 'detail': _face.detail,
+ 'tooltip': _daemonTooltip,
+ // Exactly as sent, keys first: native makes the offered keys buttons,
+ // once the line is armed (drawn, with its detail, a moment ago).
+ 'voice': _nativeVoice,
+ 'voiceActions': [
+ for (final action in _face.voiceActions)
+ {'key': action.key, 'label': action.label},
+ ],
+ 'voiceArmed': _voiceArmed,
+ 'voiceColor': (_face.voiceAlert ? theme.yellow : daemonDimInk(theme))
+ .toARGB32(),
+ };
+ }
+
+ /// The spoken line for native: as the face shows it, with a brain line's
+ /// keys first even if an older brain put them elsewhere, and the pair
+ /// harness's `<nick>` before its own words.
+ String? get _nativeVoice {
+ final voice = _face.voice;
+ if (voice == null) return null;
+ final nick = _face.voiceFromPair ? daemonPairNick(_face.name) : '';
+ final actions = _face.voiceActions;
+ if (actions.isEmpty) return '$nick$voice';
+ final split = splitDaemonKeys(voice, actions);
+ return split.keys.isEmpty
+ ? '$nick$voice'
+ : '[${split.keys.join('/')}] $nick${split.rest}';
+ }
+
+ String get _daemonTooltip {
+ if (!_zoo.isPreview) return _face.tooltip;
+ return '${_face.tooltip}\nLocal preview · Settings → Experimental';
+ }
+
+ /// Whether a key on the spoken line counts yet.
+ bool get _voiceArmed {
+ final id = _face.voiceSayId;
+ return id == null || _brain.armed(id);
+ }
+
+ String? _voiceShownFor;
+ String? _detailOverlayFor;
+
+ /// A brain line began or ended. One with keys is acknowledged to harnessd
+ /// once it is on screen, and, when it carries a `detail`, once that is on
+ /// screen too, in full, in a disclosure under the status line.
+ void _voiceChanged() {
+ final id = _face.voiceSayId;
+ if (_face.voice == null || id == null) {
+ _voiceShownFor = null;
+ if (_detailOverlayFor != null) _closeDaemonHint();
+ return;
}
- if (app.modelManager.error case final error? when mounted) {
- if (_modelsOverlay == null) {
- ScaffoldMessenger.of(context)
- .showSnackBar(SnackBar(content: Text(error)));
- }
+ if (id == _voiceShownFor) return;
+ _voiceShownFor = id;
+ if (_detailOverlayFor != null && _detailOverlayFor != id) {
+ _closeDaemonHint();
}
+ final keyed = _face.voiceActions.any((a) => a.key != 'g');
+ if (!keyed) return;
+ final detail = _face.voiceDetail;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || _face.voiceSayId != id) return;
+ if (detail == null || detail.isEmpty) {
+ // The line is everything its keys act on.
+ _brain.shown(id);
+ return;
+ }
+ _showVoiceDetail(id, detail);
+ });
}
- void _toggleModelsControls({ModelsTab initialTab = ModelsTab.all}) {
- if (_modelsOverlay != null) {
- _closeModelsControls();
+ void _showVoiceDetail(String id, String detail) {
+ final harness = _face.voiceHarness;
+ final title = [
+ if (_face.voiceFromPair) '${daemonPairNick(_face.name).trim()} asks',
+ ?harness?.label,
+ _face.voiceConfirm != null
+ ? 'what a yes turns on'
+ : id.startsWith('lesson:')
+ ? 'the lesson, in full'
+ : 'exactly what a key does',
+ ].join(' · ');
+ final shown = _showDaemonOverlay(
+ key: ValueKey('daemon-detail-$id'),
+ interactive: true,
+ showFor: DaemonFace.voiceFor,
+ child: Builder(
+ builder: (context) => ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: workspaceBarCellSizeOf(context).width * 84,
+ ),
+ child: DaemonDetailNotice(
+ title: title,
+ detail: detail,
+ actions: _face.voiceActions,
+ onShown: () {
+ if (_face.voiceSayId == id) _brain.shown(id);
+ },
+ ),
+ ),
+ ),
+ );
+ if (shown) _detailOverlayFor = id;
+ }
+
+ void _faceChanged() {
+ // Two lines can read the same (the same command asked twice): the line's
+ // id, not its words, decides whether it is new.
+ if (mounted && _zoo.loaded) _voiceChanged();
+ if (!mounted || !_native) return;
+ _sendDaemonState();
+ }
+
+ /// Faces and frames repaint only the native slot; tabs and terminals stay
+ /// put. Native hears nothing until the slot is shown, and one `visible:
+ /// false` when it goes.
+ void _sendDaemonState() {
+ if (!_slotShown) {
+ if (_lastDaemonPayload == null) return;
+ _lastDaemonPayload = null;
- unawaited(_channel.invokeMethod<void>('daemonState', {'visible': false}));
++ unawaited(_menuBus.send('daemonState', {'visible': false}));
return;
}
- if (!_shortcutsEnabled || _newHarness?.requestDismiss() == false) return;
- _closeNewHarness(restoreFocus: false);
- _closeSearch(restoreFocus: false);
- _closeCommandBar(restoreFocus: false);
- dismissTransientMenus();
- _preparePaneFocus();
- _onboarding.acknowledge(OnboardingStep.models);
- app.modelManager.setPanelVisible(true);
- unawaited(app.modelManager.dismissIntroduction());
+ final payload = _daemonPayload;
+ final key = jsonEncode(payload);
+ if (key == _lastDaemonPayload) return;
+ _lastDaemonPayload = key;
- unawaited(_channel.invokeMethod<void>('daemonState', payload));
++ unawaited(_menuBus.send('daemonState', payload));
+ }
+
+ /// Opened from Cmd-O: the daemon's `find` habit.
+ void _noteFound() {
+ if (_foundSomething || !_zoo.loaded) return;
+ _foundSomething = true;
+ _syncDaemon();
+ }
+
+ bool _noteKey(KeyEvent event) {
+ // Off, this is not here at all: every key goes where it went before.
+ if (event is! KeyDownEvent || _zoo.daemons == DaemonsSwitch.off) {
+ return false;
+ }
+ _noteWindowInput();
+ if (!_zoo.loaded) return false;
+ _noteInput();
+ // ⌘⌥ plus an offered key answers the daemon's line: `[y]` is ⌘⌥Y.
+ final keyboard = HardwareKeyboard.instance;
+ if (keyboard.isMetaPressed &&
+ keyboard.isAltPressed &&
+ !keyboard.isControlPressed &&
+ _face.voiceActions.isNotEmpty) {
+ final label = event.logicalKey.keyLabel.toLowerCase();
+ // Only a line that is armed: drawn, with what its keys do, a moment
+ // ago. `[g]` opens at any time.
+ if (_face.voiceActions.any((a) => a.key == label) &&
+ (label == 'g' || _voiceArmed)) {
+ _answerDaemon(label);
+ return true;
+ }
+ }
+ _face.noteKey(
+ enter:
+ event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter,
+ );
+ return false;
+ }
+
+ /// Answer the daemon's spoken line with one of its offered keys: only once
+ /// it is armed (`[g]` opens at any time).
+ void _answerDaemon(String key) {
+ final sayId = _face.voiceSayId;
+ final action = _face.voiceActions.where((a) => a.key == key).firstOrNull;
+ if (sayId == null || action == null) return;
+ final opens = key == 'g' && _face.voiceTarget?.key != null;
+ if (!opens && !_brain.armed(sayId)) return;
+ _answerLine(sayId, action, _face.voiceTarget);
+ _face.answered();
+ }
+
+ /// A key on a line the brain wrote (the status line's, an ask, a brief
+ /// item, a confirmation): `[g]` opens the harness, which is the window's to
+ /// do; a confirmation's y or n is `daemon_confirm`; any other key goes to
+ /// the brain as `daemon_act`. The brain sends nothing for a line that is
+ /// not armed yet.
+ void _answerLine(String id, DaemonAction action, DaemonAbout? about) {
+ if (action.key == 'g' && about?.key != null) {
+ _openHarness(about!);
+ return;
+ }
+ if (id.isEmpty) return;
+ if (id.startsWith('confirm:')) {
+ final rest = id.substring('confirm:'.length);
+ final colon = rest.indexOf(':');
+ if (colon <= 0) return;
+ _brain.confirm(
+ rest.substring(0, colon),
+ rest.substring(colon + 1),
+ accept: action.key == 'y',
+ );
+ return;
+ }
+ _brain.act(id, action.choice);
+ }
+
+ /// Show a harness the daemon named, wherever it is.
+ void _openHarness(DaemonAbout about) {
+ if (!mounted) return;
+ _closeDaemon(restoreFocus: false);
+ _closeDaemonHint();
+ unawaited(
+ app.revealAgentFromAlert(about.machineId, about.agentId).catchError((
+ Object _,
+ ) {
+ // Gone since, or on a machine this window cannot reach.
+ _face.sayNote('that harness is not here any more.');
+ }),
+ );
+ }
+
+ /// The pair harness on this computer (`autonomous/pair`), when known: the
+ /// one a talk reached, else the one this machine lists.
+ ({String machineId, String agentId})? get _pairHarness {
+ final local = app.localMachineState;
+ if (local == null) return null;
+ final machineId = local.machine.machineId;
+ final agentId =
+ _brain.pairAgentId ??
+ local.agents.where((a) => a.dsh == 'autonomous/pair').firstOrNull?.id;
+ return agentId == null ? null : (machineId: machineId, agentId: agentId);
+ }
+
+ /// The whole conversation: the pair harness's own pane.
+ void _openConversation() {
+ final pair = _pairHarness;
+ if (pair == null) return;
+ _openHarness(DaemonAbout(pair.machineId, pair.agentId));
+ }
+
+ /// `~/.config/harness/pair.jsonc`, written with no rules when it is not
+ /// there yet, opened in the editor `.jsonc` files open in.
+ Future<void> _openPairRules() async {
+ try {
+ final file = await ensurePairRules();
+ if (!await launchUrl(file.uri)) {
+ throw StateError('No editor opens .jsonc files. Open ${file.path}.');
+ }
+ } catch (error) {
+ if (mounted) {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(content: Text('Couldn’t open pair.jsonc. $error')),
+ );
+ }
+ }
+ }
+
+ /// "Talk to daemon": the panel, with the talk box ready.
+ void _talkToDaemon() {
+ if (!_zoo.loaded) return;
+ if (_daemonOverlay != null) _closeDaemon(restoreFocus: false);
+ if (!_brain.paired) {
+ _face.sayNote(
+ _brain.active
+ ? 'pair a daemon first: its panel has [ pair ].'
+ : 'harnessd here cannot talk yet. update it.',
+ );
+ }
+ _toggleDaemon(talk: true);
+ }
+
+ // ── idle: away at the window ───────────────────────────────────────────────
+
+ /// No key or pointer this long, with the window in front, is away:
+ /// harnessd hears `daemon_presence { active: false, awayMs }`.
+ static const _idleAfter = Duration(minutes: 5);
+ DateTime? _lastInput;
+ DateTime? _idleSince;
+ Timer? _idleTimer;
+
+ void _notePointer(PointerEvent event) {
+ // Off, this is not here at all.
+ if (_zoo.daemons == DaemonsSwitch.off) return;
+ if (!_slotShown) {
+ // Until the slot has its place: whether a button is held and whether
+ // the pointer is on the bar, so it never arrives under a click.
+ _pointerHeld = event.down;
+ final workspace = context.findRenderObject();
+ _pointerOverBar =
+ !_native &&
+ event is! PointerRemovedEvent &&
+ workspace is RenderBox &&
+ workspace.globalToLocal(event.position).dy >=
+ workspace.size.height - _statusBarHeight;
+ _noteWindowInput();
+ }
+ if (!_zoo.loaded) return;
+ if (event is PointerDownEvent ||
+ event is PointerScrollEvent ||
+ event is PointerHoverEvent) {
+ _noteInput();
+ }
+ }
+
+ /// A key or the pointer, anywhere in the window: the slot's quiet moment
+ /// starts again.
+ void _noteWindowInput() {
+ if (_slotShown) return;
+ _lastWindowInput = (widget.daemonClock ?? DateTime.now)();
+ if (_zoo.loaded && _slotTimer == null) {
+ _slotTimer = Timer(_slotSettle, _checkSlot);
+ }
+ }
+
+ /// Show the slot once daemons are on and the window is quiet: no button
+ /// held, the pointer off the bar, and no input for [_slotSettle] (at once
+ /// when nothing has been touched yet). Tabs never shift under a click.
+ void _checkSlot() {
+ _slotTimer?.cancel();
+ _slotTimer = null;
+ if (!mounted || _slotShown || !_zoo.loaded) return;
+ final last = _lastWindowInput;
+ final quiet = last == null
+ ? _slotSettle
+ : (widget.daemonClock ?? DateTime.now)().difference(last);
+ if (_pointerHeld || _pointerOverBar || quiet < _slotSettle) {
+ _slotTimer = Timer(
+ quiet < _slotSettle ? _slotSettle - quiet : _slotSettle,
+ _checkSlot,
+ );
+ return;
+ }
+ _slotShown = true;
- if (_native) _syncNative();
++ if (_menuHost) _syncNative();
+ setState(() {});
+ }
+
+ /// Daemons came on or went off in this window.
+ void _daemonsSwitched(bool on) {
+ if (_daemonCommandsOn != on) {
+ _daemonCommandsOn = on;
+ daemonCommandsActive.value = on;
+ _syncKeymap();
+ _search?.refreshCommands();
+ }
+ if (on) {
+ if (!_daemonSettingsLoaded && !_zoo.isPreview) {
+ _daemonSettingsLoaded = true;
+ unawaited(_daemonSettings.load());
+ }
+ _face.brainActive = _brain.active;
+ if (_brain.active) unawaited(_sendPresence());
+ _checkSlot();
+ } else {
+ // All of it goes: the slot, its line, the panel, a reveal, what the
+ // brain said. The bar is the one it was before daemons existed.
+ _slotTimer?.cancel();
+ _slotTimer = null;
+ _slotShown = false;
+ _pointerHeld = false;
+ _pointerOverBar = false;
+ _lastWindowInput = null;
+ _closeHatch(restoreFocus: false);
+ _face.dismissVoice();
+ _brain.reset();
+ _plates.reset();
+ if (_native) _sendDaemonState();
+ }
- if (_native) _syncNative();
++ if (_menuHost) _syncNative();
+ }
+
+ void _noteInput() {
+ final now = (widget.daemonClock ?? DateTime.now)();
+ _lastInput = now;
+ if (_idleSince case final since?) {
+ // Back from idle: a return, with how long.
+ _idleSince = null;
+ if (app.inForeground) {
+ unawaited(_sendPresence(away: now.difference(since)));
+ }
+ }
+ _idleTimer ??= Timer(_idleAfter, _checkIdle);
+ }
+
+ void _checkIdle() {
+ _idleTimer = null;
+ final last = _lastInput;
+ if (!mounted || last == null || _idleSince != null) return;
+ final now = (widget.daemonClock ?? DateTime.now)();
+ final quiet = now.difference(last);
+ if (quiet < _idleAfter) {
+ _idleTimer = Timer(_idleAfter - quiet, _checkIdle);
+ return;
+ }
+ // Only in front: a window behind others already said it is away.
+ if (!app.inForeground || !_zoo.loaded || !_brain.active) return;
+ _idleSince = last;
+ unawaited(_sendPresence(idle: quiet));
+ }
+
+ /// A guest's turns that finish now finished while the person was away if
+ /// the window has not been in use for `earn.night.awayMinutes`.
+ bool get _awayForNight {
+ final minutes = _zoo.roster.rules.earn.awayMinutes;
+ final now = (widget.daemonClock ?? DateTime.now)();
+ final since = _awaySince ?? _idleSince ?? _lastInput;
+ return since != null &&
+ (_awaySince != null || _idleSince != null) &&
+ now.difference(since) >= Duration(minutes: minutes);
+ }
+
+ void _brainChanged() {
+ // Heard while daemons are off (or not decided yet): nothing shows.
+ if (!mounted || !_zoo.loaded) return;
+ final firstHeard = !_face.brainActive && _brain.active;
+ _face.brainActive = _brain.active;
+ if (firstHeard) unawaited(_sendPresence());
+ final brief = _brain.brief;
+ if (brief != null && !identical(brief, _lastBrief)) {
+ _lastBrief = brief;
+ _showBrief(brief);
+ }
+ _daemonOverlay?.markNeedsBuild();
+ _syncDaemon();
+ // A line arming changes what native may click.
+ _faceChanged();
+ // The brain's state changing is news from agents too.
+ if (_brain.state?.working == true) _face.pulse();
+ }
+
+ /// `daemon_presence`: whether you are at this window, how long you were
+ /// away, and (for a guest, whose zoo is local) which daemon it pairs with.
+ Future<void> _sendPresence({Duration? away, Duration? idle}) async {
+ if (!_zoo.loaded || !_brain.active) return;
+ // harnessd knows the pair by its species.
+ final pair = app.isGuest ? _zoo.zoo.byUid(_zoo.zoo.pair)?.id : null;
+ _presencePair = pair;
+ final pane = app.focusedPane;
+ final agentId = pane?.agentId;
+ _presenceFocus = agentId == null ? null : '${pane!.machineId}/$agentId';
+ _presenceAutonomy = app.isGuest ? _zoo.zoo.autonomy : null;
+ _presenceConsent = app.isGuest ? _zoo.zoo.watching : null;
+ await _brain.presence(
+ // Idle in front of the window is away, with how long it has been.
+ active: app.inForeground && idle == null,
+ away: idle ?? away,
+ pair: pair,
+ autonomy: _presenceAutonomy,
+ consent: _presenceConsent,
+ focusMachineId: agentId == null ? null : pane!.machineId,
+ focusAgentId: agentId,
+ );
+ }
+
+ /// The brief on return: a short list under the status line, each item as
+ /// sent, keys first. It stays up while its keys work (a minute) when an
+ /// item has any, else 10 s; it is in the panel until the next one.
+ void _showBrief(DaemonBrief brief) {
+ if (!app.inForeground || (brief.line.isEmpty && brief.items.isEmpty)) {
+ return;
+ }
+ final keyed = brief.items.any(
+ (item) => item.actions.any((a) => a.key != 'g'),
+ );
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ _showDaemonOverlay(
+ key: const ValueKey('daemon-brief'),
+ interactive: true,
+ showFor: keyed ? DaemonBrief.keysFor : const Duration(seconds: 10),
+ child: DaemonBriefNotice(
+ name: _face.name,
+ brief: brief,
+ live: brief.keysLive(_brain.now()),
+ armed: _brain.armed,
+ arming: _brain,
+ onShown: _brain.shown,
+ onAnswer: (id, action, about) {
+ final opens = action.key == 'g' && about?.key != null;
+ if (!opens && !_brain.armed(id)) return;
+ _closeDaemonHint();
+ _answerLine(id, action, about);
+ },
+ ),
+ );
+ });
+ }
+
+ String? _lastZooScope;
+ int? _lastHabits;
+ String? _lastEggId;
+ bool _zooWasLoaded = false;
+
+ void _zooChanged() {
+ if (!mounted) return;
+ if (!_zoo.loaded || _lastZooScope != _zoo.scope) {
+ _closeDaemonHint();
+ _closeDaemon(restoreFocus: false);
+ _lastHabits = null;
+ _lastEggId = null;
+ _lastZooScope = _zoo.scope;
+ }
+ if (_zoo.loaded) {
+ final habits = _zoo.habitsCounted;
+ final egg = _zoo.readyEgg;
+ final beforeHatch = _zoo.zoo.daemons.isEmpty;
+ if (beforeHatch &&
+ _lastHabits != null &&
+ (habits > _lastHabits! || (egg != null && _lastEggId == null))) {
+ final scope = _zoo.scope;
+ final left = _zoo.habitsNeeded - habits;
+ final ready = egg != null;
+ // One short, and what is left is the habit it cannot come without.
+ final required = _zoo.habitsRequiredLeft.firstOrNull;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || _zoo.scope != scope || _face.revealing) return;
+ _showDaemonNotice(
+ ready
+ ? 'Your egg is ready.'
+ : left <= 0
+ ? 'The egg is on its way.'
+ : left == 1 && required != null
+ ? '${required.label}, and it hatches.'
+ : left == 1
+ ? 'One habit left. Something stirs.'
+ : 'One step closer. $left to go.',
+ action: ready ? 'hatch' : 'view',
+ onAction: _activateDaemon,
+ key: const ValueKey('daemon-habit-notice'),
+ );
+ });
+ }
+ _lastHabits = habits;
+ _lastEggId = egg?.id;
+ }
+ // A guest's pair, dial and consent live in its local zoo; the brain
+ // hears of a change.
+ if (app.isGuest &&
+ _brain.active &&
+ (_zoo.zoo.byUid(_zoo.zoo.pair)?.id != _presencePair ||
+ _zoo.zoo.autonomy != _presenceAutonomy ||
+ _zoo.zoo.watching != _presenceConsent)) {
+ _presencePair = _zoo.zoo.byUid(_zoo.zoo.pair)?.id;
+ _presenceAutonomy = _zoo.zoo.autonomy;
+ _presenceConsent = _zoo.zoo.watching;
+ unawaited(
+ _brain.guest(
+ pair: _presencePair,
+ autonomy: _presenceAutonomy,
+ consent: _presenceConsent,
+ ),
+ );
+ }
+ if (_zoo.loaded != _zooWasLoaded) {
+ _zooWasLoaded = _zoo.loaded;
+ _daemonsSwitched(_zoo.loaded);
+ setState(() {});
+ }
+ _maybeShowDaemonHint();
+ }
+
+ void _daemonEnvironmentChanged() {
+ final wasForeground = _awaySince == null;
+ _face.setEnvironment(
+ foreground: app.inForeground,
+ reduceMotion: _reduceMotion,
+ );
+ if (app.inForeground) {
+ _maybeShowDaemonHint();
+ if (!wasForeground) {
+ final away = (widget.daemonClock ?? DateTime.now)().difference(
+ _awaySince!,
+ );
+ _awaySince = null;
+ unawaited(_sendPresence(away: away));
+ }
+ } else {
+ _closeDaemonHint();
+ if (wasForeground) {
+ _awaySince = (widget.daemonClock ?? DateTime.now)();
+ unawaited(_sendPresence());
+ }
+ }
+ }
+
+ void _closeDaemonHint() {
+ _detailOverlayFor = null;
+ _daemonHintTimer?.cancel();
+ _daemonHintTimer = null;
+ _daemonHintOverlay?.remove();
+ _daemonHintOverlay?.dispose();
+ _daemonHintOverlay = null;
+ }
+
+ /// "A daemon is inside." once per account, beside the nest, never taking
+ /// focus. Scheduled from state changes, never from build().
+ void _maybeShowDaemonHint() {
+ if (!mounted || _daemonHintPending || !_zoo.needsHint) return;
+ _daemonHintPending = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _daemonHintPending = false;
+ if (!mounted || !_daemonNoticeAllowed || !_zoo.needsHint) return;
+ if (Overlay.maybeOf(context) == null || !_zoo.acknowledgeHint()) return;
+ _showDaemonNotice(
+ 'A daemon is inside.',
+ key: const ValueKey('daemon-arrival-hint'),
+ );
+ });
+ }
+
+ bool get _daemonNoticeAllowed =>
+ _shortcutsEnabled &&
+ app.inForeground &&
+ _daemonOverlay == null &&
+ _hatchOverlay == null &&
+ _search == null &&
+ _newHarness == null &&
+ !_commandBarOpen &&
+ !_machinesVisible &&
+ !_modelsVisible &&
+ !_harnessesVisible;
+
+ void _showDaemonNotice(
+ String message, {
+ required Key key,
+ String? action,
+ VoidCallback? onAction,
+ Duration showFor = const Duration(seconds: 6),
+ }) => _showDaemonOverlay(
+ key: key,
+ interactive: onAction != null,
+ showFor: showFor,
+ child: DaemonNotice(message: message, action: action, onAction: onAction),
+ );
+
+ /// A note beside the slot: it never takes focus on arrival, and takes
+ /// clicks only when it has something to click.
+ bool _showDaemonOverlay({
+ required Key key,
+ required Widget child,
+ required bool interactive,
+ Duration showFor = const Duration(seconds: 6),
+ }) {
+ if (!mounted || !_daemonNoticeAllowed) return false;
+ final overlay = Overlay.maybeOf(context);
+ if (overlay == null) return false;
+ _closeDaemonHint();
+ _daemonHintOverlay = OverlayEntry(
+ builder: (context) {
+ final cell = workspaceBarCellSizeOf(context);
+ return Positioned(
+ top: (_native ? 0.0 : _tabBarHeight) + cell.width,
+ right: cell.width,
+ child: IgnorePointer(
+ ignoring: !interactive,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: math.max(
+ 0,
+ MediaQuery.sizeOf(context).width - cell.width * 2,
+ ),
+ ),
+ child: KeyedSubtree(key: key, child: child),
+ ),
+ ),
+ );
+ },
+ );
+ overlay.insert(_daemonHintOverlay!);
+ _daemonHintTimer = Timer(showFor, _closeDaemonHint);
+ return true;
+ }
+
+ /// A click on the status slot: a ready egg hatches; otherwise the daemon is
+ /// booped and its panel opens (or closes).
+ void _activateDaemon() {
+ _closeDaemonHint();
+ if (!_shortcutsEnabled ||
+ _hatchOverlay != null ||
+ _face.revealing ||
+ !_zoo.loaded) {
+ return;
+ }
+ final egg = _zoo.readyEgg;
+ if (_face.def == null && egg != null) {
+ _hatch(egg);
+ return;
+ }
+ if (_daemonOverlay == null) _face.boop();
+ _toggleDaemon();
+ }
+
+ void _toggleDaemon({bool talk = false}) {
+ _closeDaemonHint();
+ if (_daemonOverlay != null) {
+ _closeDaemon();
+ return;
+ }
+ if (!_zoo.loaded ||
+ _hatchOverlay != null ||
+ _newHarness?.requestDismiss() == false) {
+ return;
+ }
+ _closeNewHarness(restoreFocus: false);
+ _closeSearch(restoreFocus: false);
+ _closeCommandBar(restoreFocus: false);
+ dismissTransientMenus();
+ _preparePaneFocus();
+ _daemonOverlay = OverlayEntry(
+ builder: (context) => _anchoredBesideSlot(
+ onBarrierTap: _closeDaemon,
+ child: DaemonPanel(
+ key: ValueKey(_zoo.scope),
+ face: _face,
+ brain: _brain.active ? _brain : null,
+ onAnswer: _answerLine,
+ onOpenConversation: _zoo.isPreview || _pairHarness == null
+ ? null
+ : _openConversation,
+ onOpenRules: _zoo.isPreview
+ ? null
+ : () => unawaited(_openPairRules()),
+ talkShortcut: _keymap.hint('app.daemon_talk'),
+ focusTalk: talk,
+ onClose: _closeDaemon,
+ onHatch: _hatch,
+ shortcut: (command) => _keymap.hint(command),
+ onCommand: (command) {
+ _closeDaemon(restoreFocus: false);
+ _runShortcut(command);
+ },
+ ),
+ ),
+ );
+ Overlay.of(context).insert(_daemonOverlay!);
+ _unregisterDaemon = registerTransientMenu(
+ () => _closeDaemon(restoreFocus: false),
+ );
+ _face.look();
+ _face.seen();
- if (_native) _syncNative();
++ if (_menuHost) _syncNative();
+ setState(() {});
+ }
+
+ /// The panel and the hatch reveal float above the status slot, at the bottom
+ /// right, with a barrier that closes them: [cells] terminal cells wide at
+ /// most (the reveal is wider, for a plate's 56 columns).
+ Widget _anchoredBesideSlot({
+ required Widget child,
+ required VoidCallback onBarrierTap,
+ int cells = 46,
+ }) => LayoutBuilder(
+ builder: (context, constraints) {
+ final top = _native ? 0.0 : _tabBarHeight;
+ final bottom = _statusBarHeight;
+ return Stack(
+ children: [
+ Positioned.fill(
+ top: top,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onBarrierTap,
+ child: const SizedBox.expand(),
+ ),
+ ),
+ Positioned(
+ bottom: bottom + 8,
+ right: 10,
+ width: (constraints.maxWidth - 20).clamp(
+ 0,
+ terminalCellSizeOf(context).width * cells,
+ ),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: (constraints.maxHeight - top - bottom - 20).clamp(
+ 0,
+ 720,
+ ),
+ ),
+ child: KeymapProvider(keymap: _keymap, child: child),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+
+ void _closeDaemon({bool restoreFocus = true}) {
+ if (_daemonOverlay == null) return;
+ _unregisterDaemon?.call();
+ _unregisterDaemon = null;
+ _daemonOverlay?.remove();
+ _daemonOverlay?.dispose();
+ _daemonOverlay = null;
+ if (!mounted) return;
- if (_native) _syncNative();
++ if (_menuHost) _syncNative();
+ setState(() {});
+ if (restoreFocus) _returnFocusToPane();
+ }
+
+ void _returnFocusToPane() {
+ _shellFocus.requestFocus();
+ if (app.focusedPane case final pane?) {
+ app.focusPane(pane.id, reveal: true);
+ }
+ }
+
+ /// Open an egg. The slot keeps showing the egg, and native hears nothing of
+ /// the hatchling, until the reveal has finished.
+ void _hatch(ZooEgg egg) {
+ if (_hatchOverlay != null || _zoo.hatchingEgg != null || !mounted) return;
+ _closeDaemon(restoreFocus: false);
+ _closeDaemonHint();
+ _closeSearch(restoreFocus: false);
+ _closeCommandBar(restoreFocus: false);
+ dismissTransientMenus();
+ // After the person's third hatch, any key skips to the card.
+ final skippable = _zoo.zoo.daemons.length >= 3;
+ // A duplicate's level-up is told against the zoo before the hatch.
+ final before = _zoo.zoo;
+ _face.beginReveal(kind: egg.kind);
+ final result = _zoo.hatch(egg.id);
+ _preparePaneFocus();
+ _hatchOverlay = OverlayEntry(
+ builder: (context) => _anchoredBesideSlot(
+ onBarrierTap: _closeHatch,
+ cells: daemonRevealCells,
+ child: DaemonHatchReveal(
+ roster: _zoo.roster,
+ egg: egg,
+ result: result,
+ zoo: () => _zoo.zoo,
+ reduceMotion: _reduceMotion,
+ skippable: skippable,
+ before: before,
+ // Nobody has said yet whether it may watch: after the card, the
+ // first-day screen (README, "What your daemon sees").
+ needsConsent: !_zoo.isPreview && before.consent == null,
+ onConsent: (watching) => _zoo.consent(watching: watching),
+ onSuggest: () => _zoo.autonomy('suggest'),
+ plates: _plates,
+ // The name it is given at the hatch (`zoo.nickname { uid, name }`).
+ onName: _zoo.nickname,
+ onStage: _face.revealAt,
+ onRevealed: _face.endReveal,
+ onClose: _closeHatch,
+ ),
+ ),
+ );
+ Overlay.of(context).insert(_hatchOverlay!);
+ _unregisterHatch = registerTransientMenu(
+ () => _closeHatch(restoreFocus: false),
+ );
- if (_native) _syncNative();
++ if (_menuHost) _syncNative();
+ setState(() {});
+ }
+
+ void _closeHatch({bool restoreFocus = true}) {
+ if (_hatchOverlay == null) return;
+ _unregisterHatch?.call();
+ _unregisterHatch = null;
+ _hatchOverlay?.remove();
+ _hatchOverlay?.dispose();
+ _hatchOverlay = null;
+ _face.endReveal();
+ if (!mounted) return;
- if (_native) _syncNative();
++ if (_menuHost) _syncNative();
+ setState(() {});
+ if (restoreFocus) _returnFocusToPane();
+ }
+
+ Future<void> _openModelManager() async {
+ final openingPanel = _modelsOverlay;
+ if (openingPanel == null) dismissTransientMenus();
+ await app.modelManager.open();
+ if (app.modelManager.error == null &&
+ identical(_modelsOverlay, openingPanel)) {
+ _closeModelsControls(restoreFocus: false);
+ }
+ if (app.modelManager.error case final error? when mounted) {
+ if (_modelsOverlay == null) {
+ ScaffoldMessenger.of(context)
+ .showSnackBar(SnackBar(content: Text(error)));
+ }
+ }
+ }
+
+ void _toggleModelsControls({ModelsTab initialTab = ModelsTab.all}) {
+ if (_modelsOverlay != null) {
+ _closeModelsControls();
+ return;
+ }
+ if (!_shortcutsEnabled || _newHarness?.requestDismiss() == false) return;
+ _closeNewHarness(restoreFocus: false);
+ _closeSearch(restoreFocus: false);
+ _closeCommandBar(restoreFocus: false);
+ dismissTransientMenus();
+ _preparePaneFocus();
+ _onboarding.acknowledge(OnboardingStep.models);
+ app.modelManager.setPanelVisible(true);
+ unawaited(app.modelManager.dismissIntroduction());
unawaited(app.modelManager.refresh());
unawaited(_modelsMenu!.refresh());
_modelsOverlay = OverlayEntry(