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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-02 b2325: #2627 (#2642)
0xken157c070fd6174d
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 386dfbc8e..b187b2653 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -8358,176 +8358,188 @@ class _SwarmScreenState extends State<SwarmScreen> {(app.activeSwarm.isCompanions &&!_creatureEnabled) ||app.activeSwarm.isOrchestrator,- child: ExcludeFocus(- excluding:- app.activeSwarm.isStore ||- (app.activeSwarm.isCompanions &&- !_creatureEnabled) ||- app.activeSwarm.isOrchestrator,- child: Padding(- padding:- app.panes.isEmpty ||- app.activeSwarm.isSuperTab- ? EdgeInsets.zero- : const EdgeInsets.fromLTRB(- kWorkspaceInset,- kWorkspaceInset,- kWorkspaceInset,- 0,- ),- child: SuperTabWorkspace(- app: app,- onNewProject: () => unawaited(- _newAgent(newSwarmProject: true),- ),- onNewSwarm: () =>- _newTab(superTab: true),- onAddAgent: (group) => unawaited(- _addAgent(conversationId: group.id),- ),- canvas: Focus.withExternalFocusNode(- focusNode: _canvasFocus,- includeSemantics: false,- child: Stack(- children: [- Positioned.fill(- child: _underFirstMachine(- PaneShareStatus(- visible:- widget- .chrome- ?.showsShareStatus ==- true,- child: PaneOpacity(- opacity: appearancePrefsStore- .value- .effectivePaneOpacity,- child: PaneGrid(- notifier: app,- swarmMode: true,- onOpenModels:- _openPaneModels,- onSplitPane:- (paneId, axis) =>- unawaited(- _splitAgent(- axis,- paneId:- paneId,- ),+ child: TickerMode(+ enabled:+ !(app.activeSwarm.isStore ||+ (app.activeSwarm.isCompanions &&+ !_creatureEnabled) ||+ app.activeSwarm.isOrchestrator),+ child: ExcludeFocus(+ excluding:+ app.activeSwarm.isStore ||+ (app.activeSwarm.isCompanions &&+ !_creatureEnabled) ||+ app.activeSwarm.isOrchestrator,+ child: Padding(+ padding:+ app.panes.isEmpty ||+ app.activeSwarm.isSuperTab+ ? EdgeInsets.zero+ : const EdgeInsets.fromLTRB(+ kWorkspaceInset,+ kWorkspaceInset,+ kWorkspaceInset,+ 0,+ ),+ child: SuperTabWorkspace(+ app: app,+ onNewProject: () => unawaited(+ _newAgent(newSwarmProject: true),+ ),+ onNewSwarm: () =>+ _newTab(superTab: true),+ onAddAgent: (group) => unawaited(+ _addAgent(conversationId: group.id),+ ),+ canvas: Focus.withExternalFocusNode(+ focusNode: _canvasFocus,+ includeSemantics: false,+ child: Stack(+ children: [+ Positioned.fill(+ child: _underFirstMachine(+ PaneShareStatus(+ visible:+ widget+ .chrome+ ?.showsShareStatus ==+ true,+ child: PaneOpacity(+ opacity:+ appearancePrefsStore+ .value+ .effectivePaneOpacity,+ child: PaneGrid(+ notifier: app,+ swarmMode: true,+ onOpenModels:+ _openPaneModels,+ onSplitPane:+ (+ paneId,+ axis,+ ) => unawaited(+ _splitAgent(+ axis,+ paneId:+ paneId,),- devicesViewer:- app.devicesEnabled- ? _devicesViewer- : null,- devicesConversation:- app.devicesEnabled- ? _devicesConversation- : null,- companionViewer:- _creatureEnabled- ? _companionViewer- : null,- companionConversation:- _creatureEnabled- ? _companionConversation- : null,- soloFocused: _compact(- context,- ),- empty:- app.panes.isEmpty &&- !app- .activeSwarm- .isUtility &&- !app- .activeSwarm- .isOrchestrator- ? newHarnessOpensInBox ||- app- .activeSwarm- .isNewTabPage- ? _startGuide()- : HarnessStartPage(- key: ValueKey(- 'harness-start:${app.activeSwarmId}',- ),- focusNode:- _startSearchFocus,- createSearch: () => SwarmSearchController(- app,- _navigation- .recent,- projects:- _projects,- commands:- _searchCommands,- recentCommands:- () =>- _navigation.recentCommands,- // The first box a new- // person meets is the same- // box: its placeholder- // promises `?` and a way- // to create, so it has them.- modes:- _searchModes,- adding:- true,- offersCreate:- true,- placement:- HarnessPlacement.currentTab,- catalog:- _searchCatalog,- ),- onNewTab:- _newTab,- onNewPane: () => unawaited(- _addAgent(- query: '',+ ),+ devicesViewer:+ app.devicesEnabled+ ? _devicesViewer+ : null,+ devicesConversation:+ app.devicesEnabled+ ? _devicesConversation+ : null,+ companionViewer:+ _creatureEnabled+ ? _companionViewer+ : null,+ companionConversation:+ _creatureEnabled+ ? _companionConversation+ : null,+ soloFocused: _compact(+ context,+ ),+ empty:+ app+ .panes+ .isEmpty &&+ !app+ .activeSwarm+ .isUtility &&+ !app+ .activeSwarm+ .isOrchestrator+ ? newHarnessOpensInBox ||+ app+ .activeSwarm+ .isNewTabPage+ ? _startGuide()+ : HarnessStartPage(+ key: ValueKey(+ 'harness-start:${app.activeSwarmId}',+ ),+ focusNode:+ _startSearchFocus,+ createSearch: () => SwarmSearchController(+ app,+ _navigation+ .recent,+ projects:+ _projects,+ commands:+ _searchCommands,+ recentCommands: () =>+ _navigation.recentCommands,+ // The first box a new+ // person meets is the same+ // box: its placeholder+ // promises `?` and a way+ // to create, so it has them.+ modes:+ _searchModes,+ adding:+ true,+ offersCreate:+ true,+ placement:+ HarnessPlacement.currentTab,+ catalog:+ _searchCatalog,),- ),- onCommands:- _showSearchCommands,- onQuickStart:- _learning- .offer- ? _startQuickStart- : null,- onPractice:- _practiceKeyboard,- onNew: () => _newAgent(- placement:- HarnessPlacement.currentTab,- ),- onNewWithTask: (task) => _newAgent(- task:- task,- placement:- HarnessPlacement.currentTab,- ),- onStore:- _openStore,- onResourceSearch: (query) => _openSearch(- adding:- true,- query:- query,- ),- onChoose:- _chooseStartSearch,- )- : null,+ onNewTab:+ _newTab,+ onNewPane: () => unawaited(+ _addAgent(+ query: '',+ ),+ ),+ onCommands:+ _showSearchCommands,+ onQuickStart:+ _learning.offer+ ? _startQuickStart+ : null,+ onPractice:+ _practiceKeyboard,+ onNew: () => _newAgent(+ placement:+ HarnessPlacement.currentTab,+ ),+ onNewWithTask: (task) => _newAgent(+ task:+ task,+ placement:+ HarnessPlacement.currentTab,+ ),+ onStore:+ _openStore,+ onResourceSearch: (query) => _openSearch(+ adding:+ true,+ query:+ query,+ ),+ onChoose:+ _chooseStartSearch,+ )+ : null,+ ),),),),),- ),- if (_firstConnection(context)- case final connect?)- Positioned.fill(child: connect),- ],+ if (_firstConnection(context)+ case final connect?)+ Positioned.fill(+ child: connect,+ ),+ ],+ ),),),),diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 42f1716d7..c3ddfb581 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -2235,6 +2235,9 @@ class SuperTabController extends ChangeNotifier {void _keepRows(String id, List rows) {if (!_policy.drawsSaved) return;+ _recentChats+ ..remove(id)+ ..insert(0, id);final kept = _rows[id] ??= {};for (final row in rows) {final map = superTabMap(row);@@ -2261,6 +2264,8 @@ class SuperTabController extends ChangeNotifier {: shown;final rows = [for (final message in page) ?_rows[id]?[message.id]];return {+ if (_savedChatsOf(id) case final chats when chats.isNotEmpty)+ 'chats': chats,'format': superTabReadFormat,'savedAt': readAt.millisecondsSinceEpoch,'lastChangedAt': lastChangedAt,@@ -2276,6 +2281,81 @@ class SuperTabController extends ChangeNotifier {/// A conversation's page as the backend reads it.static const _savedPage = 100;+ /// How many other chats a saved view keeps the last rows of, newest read first, and how many rows of each: every chat then+ /// opens from this device, and its first read replaces them (Quiet Swarm, Speed). Inside the view, so they are this account's+ /// alone and go when it does; one over its limit drops the oldest chats first ([SuperTabSavedViews.write]).+ static const _savedChats = 5, _savedChatRows = 30;++ /// The chats this device read, newest first.+ final _recentChats = <String>[];++ List<Map<String, dynamic>> _savedChatsOf(String open) {+ final chats = <Map<String, dynamic>>[];+ for (final id in _recentChats) {+ if (chats.length == _savedChats) break;+ final shown = _messages[id];+ if (id == open ||+ shown == null ||+ shown.isEmpty ||+ snapshot?.conversation(id) == null)+ continue;+ final page = shown.length > _savedChatRows+ ? shown.sublist(shown.length - _savedChatRows)+ : shown;+ final rows = [for (final message in page) ?_rows[id]?[message.id]];+ if (rows.isNotEmpty) {+ chats.add({+ 'id': id,+ 'messages': rows,+ 'next': SuperTabPage.of(page.first).toJson(),+ });+ }+ }+ return chats;+ }++ /// Draws the other chats of a saved view, each only if the saved state lists it and all its rows are its own; a broken one is+ /// skipped. Each one's first read takes the latest page whole, as the saved page may be short of what came since.+ void _drawSavedChats(Object? chats, SuperTabSnapshot saved, String open) {+ if (chats is! List) return;+ // Saved newest first, and each one drawn goes to the front.+ for (final chat in chats.reversed) {+ try {+ final map = superTabMap(chat);+ final id = map['id'] as String;+ if (id == open || saved.conversation(id) == null) continue;+ final rows = [+ for (final row in map['messages'] as List) superTabMap(row),+ ];+ final messages = rows.map(SuperTabMessage.fromJson).toList();+ if (messages.isEmpty || messages.any((m) => m.conversationId != id))+ continue;+ _messages[id] = messages..sort(superTabMessageOrder);+ _keepRows(id, rows);+ _before[id] = SuperTabPage.read(map['next']);+ _latestWanted.add(id);+ } on FormatException {+ continue;+ } on TypeError {+ continue;+ }+ }+ }++ /// What the first read says this reader no longer has: its kept chats go with it.+ void _dropLostChats() {+ final state = snapshot;+ if (state == null) return;+ for (final id in _messages.keys.toList()) {+ if (id == selectedId || state.conversation(id) != null) continue;+ _messages.remove(id);+ _rows.remove(id);+ _before.remove(id);+ _latestWanted.remove(id);+ _recentChats.remove(id);+ }+ }+/// How long a saved view's cursor is good for: the backend keeps/// tombstones 7 days and reloads older cursors an hour before that.static const _savedFor = Duration(days: 6, hours: 23);@@ -2330,6 +2410,7 @@ class SuperTabController extends ChangeNotifier {_keepRows(id, rows);_before[id] = SuperTabPage.read(view['next']);}+ _drawSavedChats(view['chats'], saved, id is String ? id : selectedId);_showingSaved = true;loading = false;if (_startedAt != null) _changed();@@ -3482,6 +3563,7 @@ class SuperTabController extends ChangeNotifier {if (_showingSaved) {// Read now: the saved view, and its Updating line, give way._showingSaved = false;+ _dropLostChats();stateChanged = true;}} catch (failure) {diff --git a/desktop/lib/super_tabs/leaderboard/reader.dart b/desktop/lib/super_tabs/leaderboard/reader.dartindex 5fe568ddc..aacc0c1a4 100644--- a/desktop/lib/super_tabs/leaderboard/reader.dart+++ b/desktop/lib/super_tabs/leaderboard/reader.dart@@ -78,7 +78,7 @@ class SuperTabLeaderboardReader extends ChangeNotifier {board = null;error = null;}- _timer ??= Timer.periodic(every, (_) => unawaited(refresh()));+ _timer ??= Timer.periodic(every, (_) => unawaited(tick()));return refresh();}@@ -99,6 +99,10 @@ class SuperTabLeaderboardReader extends ChangeNotifier {_timer = null;}+ /// A timed read. A reader that is off screen skips it.+ @protected+ Future<void> tick() => refresh();+Future<void> refresh() async {final projectId = _projectId;if (projectId == null || _disposed) return;@@ -167,11 +171,13 @@ class SuperTabProjectBoard extends SuperTabLeaderboardReader {super.every = const Duration(minutes: 5),}) : super(tabId: controller.tabId, request: controller.request) {controller.addListener(_follow);+ controller.machinesChanged.addListener(_returned);_follow();}final SuperTabController controller;String? _following;+ bool _missed = false;/// The project whose board this is; null while none is open.String? get projectId => _following;@@ -189,9 +195,24 @@ class SuperTabProjectBoard extends SuperTabLeaderboardReader {}}+ /// A Swarm that isn't showing reads no board. One that missed a read takes it as it returns.+ @override+ Future<void> tick() {+ if (!controller.away) return refresh();+ _missed = true;+ return Future.value();+ }++ void _returned() {+ if (!_missed || controller.away) return;+ _missed = false;+ unawaited(refresh());+ }+@overridevoid dispose() {controller.removeListener(_follow);+ controller.machinesChanged.removeListener(_returned);super.dispose();}}diff --git a/desktop/lib/super_tabs/live_card.dart b/desktop/lib/super_tabs/live_card.dartindex b25bd29d7..4925eb61e 100644--- a/desktop/lib/super_tabs/live_card.dart+++ b/desktop/lib/super_tabs/live_card.dart@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';import '../shared/theme/pull_request_icon.dart';import '../widgets/desktop_chrome.dart';+import 'visible_tick.dart';import 'controller.dart';import 'live_card_model.dart';import 'live_card_pull_request.dart';@@ -44,7 +45,8 @@ class SuperTabLiveCard extends StatefulWidget {State<SuperTabLiveCard> createState() => _SuperTabLiveCardState();}-class _SuperTabLiveCardState extends State<SuperTabLiveCard> {+class _SuperTabLiveCardState extends State<SuperTabLiveCard>+ with WidgetsBindingObserver, VisibleTick<SuperTabLiveCard> {late List<SuperTabPullRequestCard> _watched = _pullRequests;/// A task card lists every pull request its group linked; a PR card its own.@@ -58,26 +60,44 @@ class _SuperTabLiveCardState extends State<SuperTabLiveCard> {];}+ /// Whether this card holds its pull requests' watch: only while on screen, so a Swarm that isn't showing asks GitHub nothing.+ bool _watching = false;++ void _hold(bool onScreen) {+ if (onScreen == _watching) return;+ _watching = onScreen;+ if (onScreen) {+ widget.facts.watch(_watched.map((c) => c.url));+ } else {+ widget.facts.unwatch(_watched.map((c) => c.url));+ }+ }+@override- void initState() {- super.initState();- widget.facts.watch(_watched.map((c) => c.url));+ void didChangeDependencies() {+ super.didChangeDependencies();+ _hold(onScreen);}+ @override+ void onScreenChanged(bool onScreen) => _hold(onScreen);+@overridevoid didUpdateWidget(SuperTabLiveCard old) {super.didUpdateWidget(old);+ final next = _pullRequests;// Watched again before the old ones are let go, so a rebuild never// stops the refresh of what it still shows.- final next = _pullRequests;- widget.facts.watch(next.map((c) => c.url));- old.facts.unwatch(_watched.map((c) => c.url));+ if (_watching) {+ widget.facts.watch(next.map((c) => c.url));+ old.facts.unwatch(_watched.map((c) => c.url));+ }_watched = next;}@overridevoid dispose() {- widget.facts.unwatch(_watched.map((c) => c.url));+ if (_watching) widget.facts.unwatch(_watched.map((c) => c.url));super.dispose();}diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 1a031c5b5..2bea9cf36 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -901,6 +901,9 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {}_syncTick();_redrawMoved();+ if (!c.away && _timer?.isActive != true && !_reading && widget.app?.foreground.value == true && (!kUnderTest || widget.readLocal != null)) {+ unawaited(_refresh());+ }}/// Redraws what no longer says what it drew, and nothing else.@@ -1020,7 +1023,8 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {await _readTeamSetup();} finally {_reading = false;- if (mounted && widget.app?.foreground.value == true) {+ // A Swarm that isn't showing reads nothing; coming back reads at once ([_machinesMoved]).+ if (mounted && !c.away && widget.app?.foreground.value == true) {_timer = Timer(const Duration(seconds: 15), _refresh);}}diff --git a/desktop/lib/super_tabs/pull_request_facts.dart b/desktop/lib/super_tabs/pull_request_facts.dartindex 9c039c330..70f413199 100644--- a/desktop/lib/super_tabs/pull_request_facts.dart+++ b/desktop/lib/super_tabs/pull_request_facts.dart@@ -52,6 +52,10 @@ class SuperTabPullRequestFacts extends ChangeNotifier {_schedule();}+ /// What is being watched now.+ @visibleForTesting+ Iterable<String> get watching => _watchers.keys;+void unwatch(Iterable<String> urls) {for (final url in urls) {final count = (_watchers[url] ?? 0) - 1;diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dartindex 7aa123c85..a6a092c87 100644--- a/desktop/lib/super_tabs/roster.dart+++ b/desktop/lib/super_tabs/roster.dart@@ -16,6 +16,7 @@ import '../terminal/terminal_theme_store.dart';import '../widgets/browser_menu_guard.dart';import '../widgets/desktop_chrome.dart';import '../widgets/harness_activity_mark.dart';+import 'visible_tick.dart';import 'agent_details.dart';import 'agent_mark.dart';import 'controller.dart';@@ -74,7 +75,8 @@ class SuperTabRoster extends StatefulWidget {State<SuperTabRoster> createState() => _SuperTabRosterState();}-class _SuperTabRosterState extends State<SuperTabRoster> {+class _SuperTabRosterState extends State<SuperTabRoster>+ with WidgetsBindingObserver, VisibleTick<SuperTabRoster> {/// One per agent menu open now, each keeping the browser's menu off.final _menuHolds = <Object>{};@@ -92,10 +94,6 @@ class _SuperTabRosterState extends State<SuperTabRoster> {tabId: c.tabId,);- /// One tick for the whole list, so ages and leases stay true on a quiet- /// Swarm (review of #2281); a change in the Swarm rebuilds it anyway.- Timer? _tick;-/// The project the list is narrowed to now, so its loss is told from the/// person simply opening another project's chat.String? _scopedId;@@ -139,17 +137,15 @@ class _SuperTabRosterState extends State<SuperTabRoster> {scheduleMicrotask(() {if (mounted) _followScope();});- _tick = Timer.periodic(- const Duration(seconds: 30),- (_) => mounted ? setState(() {}) : null,- );+ // One tick for the whole list while on screen, so ages and leases stay true on a quiet Swarm (review of #2281); a change in+ // the Swarm rebuilds it anyway.+ visibleTick(const Duration(seconds: 30));}@overridevoid dispose() {_menuHolds.forEach(BrowserMenuGuard.release);_menuHolds.clear();- _tick?.cancel();c.removeListener(_scopeMoved);_choice.removeListener(_scopeMoved);_ownBoard?.dispose();diff --git a/desktop/lib/super_tabs/saved_view.dart b/desktop/lib/super_tabs/saved_view.dartindex 29f5d8e05..666e687df 100644--- a/desktop/lib/super_tabs/saved_view.dart+++ b/desktop/lib/super_tabs/saved_view.dart@@ -131,12 +131,21 @@ class SuperTabSavedViews {// Only for the account using this device: after a sign-out in// another tab, or another account's claim, a late write keeps nothing.if (await storage.read(_owner) != account) return false;- final text = jsonEncode({- ...view,+ // Over the limit the oldest chats go first, so the open chat's view is still kept.+ final chats = [...view['chats'] as List? ?? const []];+ String encoded() => jsonEncode({+ for (final field in view.entries)+ if (field.key != 'chats') field.key: field.value,'parts': SuperTabParts.drawnOnly(view['parts'] as Map<String, dynamic>,),+ if (chats.isNotEmpty) 'chats': chats,});+ var text = encoded();+ while (_utf8Length(text) > maxBytes && chats.isNotEmpty) {+ chats.removeLast();+ text = encoded();+ }if (_utf8Length(text) > maxBytes) {await _forget(account, tabId);return false;diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex f936a62e1..7395c59bd 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -69,6 +69,7 @@ import 'switch_pm.dart';import 'project_status_card.dart';import 'pane_layout.dart';import 'view_room.dart';+import 'visible_tick.dart';import '../widgets/dial_list_scroll.dart';import '../widgets/laid_out_list.dart';@@ -4165,7 +4166,7 @@ class _SuperTabViewState extends State<SuperTabView>children: [_header(c.selected, narrow, showRoster),Expanded(- child: IndexedStack(+ child: SuperTabPages(index: _devicesVisible? 1: _notificationsVisiblediff --git a/desktop/lib/super_tabs/visible_tick.dart b/desktop/lib/super_tabs/visible_tick.dartnew file mode 100644index 000000000..74e0a04b4--- /dev/null+++ b/desktop/lib/super_tabs/visible_tick.dart@@ -0,0 +1,107 @@+import 'dart:async';++import 'package:flutter/widgets.dart';++/// A panel's timer that runs only while the panel is on screen: its subtree not muted by+/// [TickerMode] and the app not hidden. [Offstage] and [IndexedStack] don't mute anything, so what+/// hides a panel with one also needs a [TickerMode] ([SuperTabPages]). Coming back redraws at once,+/// so an age is never stale on screen (Quiet Swarm 6/6). Behind other windows that is nothing to+/// redraw and nothing to read.+mixin VisibleTick<T extends StatefulWidget>+ on State<T>, WidgetsBindingObserver {+ Duration? _every;+ Timer? _tick;+ bool _registered = false;+ bool _appShown = true;+ bool _onScreen = false;+ bool _known = false;++ /// Whether the panel can be seen now.+ bool get onScreen => _onScreen;++ /// Ticks every [every] while on screen. [onTick] redraws unless told otherwise.+ void visibleTick(Duration every) {+ _every = every;+ _observe();+ _restart();+ }++ /// Told when the panel leaves or returns, for what else it does on a timer.+ void onScreenChanged(bool onScreen) {}++ void onTick() {+ if (mounted) setState(() {});+ }++ void _observe() {+ if (_registered) return;+ _registered = true;+ WidgetsBinding.instance.addObserver(this);+ final state = WidgetsBinding.instance.lifecycleState;+ _appShown = state == null || _shows(state);+ }++ static bool _shows(AppLifecycleState state) =>+ state == AppLifecycleState.resumed || state == AppLifecycleState.inactive;++ void _restart() {+ _tick?.cancel();+ _tick = null;+ final every = _every;+ if (every != null && _onScreen) {+ _tick = Timer.periodic(every, (_) => onTick());+ }+ }++ void _settle(bool Function() now) {+ final next = now();+ final moved = _known && next != _onScreen;+ _known = true;+ _onScreen = next;+ if (_every != null && (moved || _tick == null)) _restart();+ if (!moved) return;+ onScreenChanged(next);+ if (next && mounted) setState(() {});+ }++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _observe();+ final enabled = TickerMode.valuesOf(context).enabled;+ _settle(() => enabled && _appShown);+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ _appShown = _shows(state);+ if (!mounted) return;+ final enabled = TickerMode.valuesOf(context).enabled;+ _settle(() => enabled && _appShown);+ }++ @override+ void dispose() {+ _tick?.cancel();+ if (_registered) WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }+}++/// The pages of one place, one showing. The hidden ones keep their state. An [IndexedStack] alone+/// leaves their timers running, as it doesn't mute them.+class SuperTabPages extends StatelessWidget {+ const SuperTabPages({super.key, required this.index, required this.children});++ final int index;+ final List<Widget> children;++ @override+ Widget build(BuildContext context) => IndexedStack(+ index: index,+ children: [+ for (var i = 0; i < children.length; i++)+ TickerMode(enabled: i == index, child: children[i]),+ ],+ );+}diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex 6f35b28ac..1a7f9c794 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -155,6 +155,27 @@ class WsRequestFailure implements Exception {/// One SSO-authenticated, machine-scoped connection to `/api/web-ws`.class WsConn {+ /// Above this a frame decodes in an isolate. Starting one holds this thread about 3 ms itself, the time of a decode of about+ /// this size on a current Mac (566 KB took 7 ms, measured for #2195), so below it the isolate would cost more than it saves.+ static const largeFrameChars = 256 * 1024;++ /// How a large frame decodes; tests hold it to see the order.+ @visibleForTesting+ static Future<Object?> Function(String raw) decodeLargeFrame =+ decodeInIsolate;++ /// The decoded frame, or null for what will not parse. `compute` hands the result back without a copy, and runs inline on the web.+ static Future<Object?> decodeInIsolate(String raw) =>+ compute(_decodeOrNull, raw);++ static Object? _decodeOrNull(String raw) {+ try {+ return jsonDecode(raw);+ } catch (_) {+ return null;+ }+ }+final String wsBaseUrl;final String autonomousEnv;final String machineId;@@ -444,8 +465,7 @@ class WsConn {if (Platform.isWindows && !(kUnderTest && allowLocalTcpFixture)) {throw StateError('The local daemon pipe is unavailable');}- final transport =- localTransport ?? LocalDaemonTransport.detect(uri);+ final transport = localTransport ?? LocalDaemonTransport.detect(uri);if (!transport.portAllowed) {throw StateError('The local daemon socket is unavailable');}@@ -605,8 +625,44 @@ class WsConn {}}+ /// Frames behind a large one wait for it, whatever their kind, so nothing overtakes it.+ Future<void> _decodeTail = Future<void>.value();+ int _decoding = 0;+void _onRaw(dynamic raw) {- final codec = _codec;+ // A frame belongs to the connection it came on, sealed or not, whenever its turn comes: once+ // that connection has gone, it reaches nothing, and its seal is never read afresh.+ final channel = _channel, codec = _codec;+ if (_decoding == 0 && !(raw is String && raw.length >= largeFrameChars)) {+ _handleRaw(raw, codec);+ return;+ }+ _decoding++;+ _decodeTail = _decodeTail+ .then((_) async {+ bool gone() => _closing || !identical(_channel, channel);+ if (gone()) return;+ if (raw is String && raw.length >= largeFrameChars) {+ Object? decoded;+ try {+ decoded = await decodeLargeFrame(raw);+ } catch (_) {+ // No isolate to be had: as it always was, on this thread.+ decoded = _decodeOrNull(raw);+ }+ if (gone()) return;+ if (decoded is Map<String, dynamic>) _handleMessage(decoded, codec);+ } else {+ _handleRaw(raw, codec);+ }+ })+ .catchError((Object _) {+ // Keep the queue alive: one frame that fails is dropped, as a bad frame always was.+ })+ .whenComplete(() => _decoding--);+ }++ void _handleRaw(dynamic raw, RelayCodec? codec) {if (raw is List<int>) {final bytes = Uint8List.fromList(raw);_inboundTail = _inboundTail@@ -627,6 +683,10 @@ class WsConn {} catch (_) {return;}+ _handleMessage(message, codec);+ }++ void _handleMessage(Map<String, dynamic> message, RelayCodec? codec) {if (message['type'] == 'machine_select_error') _selectRefused(message);if (codec != null) {_inboundTail = _inboundTaildiff --git a/desktop/test/devices_tab_test.dart b/desktop/test/devices_tab_test.dartindex 3a903841e..e2e91bd49 100644--- a/desktop/test/devices_tab_test.dart+++ b/desktop/test/devices_tab_test.dart@@ -78,6 +78,36 @@ void main() {);}+ // Task #2195: Offstage mutes nothing, so a Swarm hidden behind the Store would keep its timers.+ testWidgets('a canvas behind the Store runs no timers until it returns', (+ tester,+ ) async {+ final app = createApp(store: MemoryStore());+ await mount(tester, app);+ bool canvasTicks() => tester+ .widget<TickerMode>(+ find+ .descendant(+ of: find.byKey(+ const ValueKey('workspace-canvas'),+ skipOffstage: false,+ ),+ matching: find.byType(TickerMode, skipOffstage: false),+ skipOffstage: false,+ )+ .first,+ )+ .enabled;+ expect(canvasTicks(), isTrue);+ app.openStore();+ await tester.pumpAndSettle();+ expect(canvasTicks(), isFalse);+ app.openDevices();+ await tester.pumpAndSettle();+ expect(canvasTicks(), isTrue);+ await tester.pumpWidget(const SizedBox());+ });+test('restoring a Devices tab reserves chat before its conversation loads',() async {diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dartindex 68defb4e2..296427e2a 100644--- a/desktop/test/super_tab_chat_test.dart+++ b/desktop/test/super_tab_chat_test.dart@@ -132,6 +132,25 @@ void main() {}});+ testWidgets('a chat behind the terminals runs no timers until it returns', (+ tester,+ ) async {+ final server = ConversationServer()..append('Hello');+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ bool chatTicks() => TickerMode.valuesOf(+ tester.element(find.text('Hello', skipOffstage: false)),+ ).enabled;+ await showReadView(tester, c);+ expect(chatTicks(), isTrue);+ await showReadView(tester, c, terminals: true);+ expect(chatTicks(), isFalse);+ await showReadView(tester, c);+ expect(chatTicks(), isTrue);+ await closeReadView(tester, c);+ });+testWidgets('returning from terminals reads the already loaded transcript', (tester,) async {diff --git a/desktop/test/super_tab_live_card_test.dart b/desktop/test/super_tab_live_card_test.dartindex 73f09419e..5e08cbd19 100644--- a/desktop/test/super_tab_live_card_test.dart+++ b/desktop/test/super_tab_live_card_test.dart@@ -434,4 +434,32 @@ void main() {// The read mark it just made is saved a moment later.await tester.pump(const Duration(milliseconds: 250));});++ // Task #2195: a card on a Swarm that isn't showing asks nothing of GitHub.+ testWidgets('a card off screen does not watch its pull request, and watches again on coming back', (tester) async {+ final server = cardServer(mergedAt: 5);+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ await c.loadMessages('work');+ final group = c.snapshot!.conversation('work')!;+ final facts = SuperTabPullRequestFacts((urls) async => {'account': 'ada', 'rows': const <Object>[]});+ addTearDown(facts.dispose);+ Widget frame(bool on) => MaterialApp(+ home: Scaffold(+ body: TickerMode(+ enabled: on,+ child: SuperTabLiveCard(group: group, card: group.cards.of('message-2')!, controller: c, facts: facts),+ ),+ ),+ );+ await tester.pumpWidget(frame(false));+ expect(facts.watching, isEmpty);+ await tester.pumpWidget(frame(true));+ expect(facts.watching, isNotEmpty);+ await tester.pumpWidget(frame(false));+ expect(facts.watching, isEmpty);+ await tester.pumpWidget(const SizedBox());+ expect(facts.watching, isEmpty);+ });}diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dartindex 76347c841..4dd7fc21b 100644--- a/desktop/test/super_tab_machines_test.dart+++ b/desktop/test/super_tab_machines_test.dart@@ -2604,6 +2604,51 @@ void main() {},);+ // Task #2195: a Swarm that isn't showing reads no machine's usage.+ testWidgets('reads nothing while its Swarm is away, and reads at once on its return', (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ f.connection.server.state['machines'] = [+ {'machineId': 'm', 'contributorId': 'owner', 'maxAgents': 8},+ ];+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ var reads = 0;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SizedBox(+ width: 300,+ height: 400,+ child: SuperTabMachines(+ controller: c,+ app: f.app,+ onAddAgent: (_) {},+ readLocal: (_) async {+ reads++;+ return null;+ },+ ),+ ),+ ),+ ),+ );+ await tester.pump(const Duration(seconds: 1));+ expect(reads, greaterThan(0));+ c.away = true;+ await tester.pump(const Duration(seconds: 16));+ final atAway = reads;+ await tester.pump(const Duration(seconds: 40));+ expect(reads, atAway);+ c.away = false;+ await tester.pump(const Duration(seconds: 1));+ expect(reads, greaterThan(atAway));+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ });+testWidgets('machine settings show its name, Agents as memory allows, and Remove from this Swarm',(tester) async {diff --git a/desktop/test/super_tab_reading_client_test.dart b/desktop/test/super_tab_reading_client_test.dartindex 486a992d6..59f87f7e4 100644--- a/desktop/test/super_tab_reading_client_test.dart+++ b/desktop/test/super_tab_reading_client_test.dart@@ -489,6 +489,7 @@ void main() {async.elapse(const Duration(seconds: 1));expect(theirs!.showingSaved, isFalse);expect(theirs!.snapshot, isNull);+ expect(theirs!.messages('lead'), isEmpty);other.dispose();backend.servers['tab']!.holdReads!.complete();backend.servers['tab']!.holdReads = null;diff --git a/desktop/test/super_tab_saved_view_test.dart b/desktop/test/super_tab_saved_view_test.dartindex d4cb5e8f3..f975eb23b 100644--- a/desktop/test/super_tab_saved_view_test.dart+++ b/desktop/test/super_tab_saved_view_test.dart@@ -291,54 +291,316 @@ void _controllerTests() {});// Review of #1791, 2: the saved read is no longer bounded.- // Task #2169: Desktop draws at once, as the saved view is this account's own (SuperTabSavedViews is keyed by account).- group('on Desktop', () {- test('a saved view draws before the first read answers, and the read replaces it', () {- final server = ConversationServer()..append('Please start.');- final view = _saved(server);+ // Task #2195: every chat opens from what this device has for this account, and the read corrects it.+ group('the last messages of each chat', () {+ Map<String, dynamic> savedWithChats(+ ConversationServer server,+ Iterable<String> chats,+ ) {+ late Map<String, dynamic> view;+ fakeAsync((async) {+ final c = _controller(_Reads(server), reading: SuperTabReading.desktop)+ ..start();+ async.flushMicrotasks();+ for (final id in chats) {+ unawaited(c.loadMessages(id));+ async.flushMicrotasks();+ }+ view = c.savedView!;+ c.dispose();+ });+ return jsonDecode(jsonEncode(view)) as Map<String, dynamic>;+ }++ test('a chat read before opens at once after a restart, and its first read replaces it', () {+ final server = ConversationServer()+ ..append('Hello')+ ..append('In the other chat', conversationId: 'offline');+ final view = savedWithChats(server, ['offline']);fakeAsync((async) {server- ..append('Done.')+ ..append('Since', conversationId: 'offline')..holdReads = Completer<void>();- final c = _controller(_Reads(server), reading: SuperTabReading.desktop)..drawSaved(view);- expect(c.snapshot!.name, 'Pilot');- expect(c.messages('lead').single.text, 'Please start.');- expect(c.showingSaved, isTrue);- expect(c.loading, isFalse);- c.start();- async.flushMicrotasks();- expect(c.showingSaved, isTrue);+ final c = _controller(_Reads(server), reading: SuperTabReading.desktop)+ ..drawSaved(view);+ expect(+ c.messages('offline').map((m) => m.text),+ contains('In the other chat'),+ );server.holdReads!.complete();server.holdReads = null;+ c.start();+ async.flushMicrotasks();+ unawaited(c.loadMessages('offline'));+ async.flushMicrotasks();+ expect(+ c.messages('offline').map((m) => m.text),+ containsAll(['In the other chat', 'Since']),+ );+ c.dispose();+ });+ });++ test('a chat the reader lost goes when the first read answers', () {+ final server = ConversationServer()+ ..append('Hello')+ ..append('Secret', conversationId: 'offline');+ final view = savedWithChats(server, ['offline']);+ fakeAsync((async) {+ (server.state['conversations'] as List).removeWhere(+ (g) => g['id'] == 'offline',+ );+ final c = _controller(_Reads(server), reading: SuperTabReading.desktop)+ ..drawSaved(view);+ expect(c.messages('offline'), isNotEmpty);+ c.start();async.flushMicrotasks();expect(c.showingSaved, isFalse);- expect(c.messages('lead').map((m) => m.text), ['Please start.', 'Done.']);+ expect(c.messages('offline'), isEmpty);c.dispose();});});- test('a first read that is refused takes the saved view off the screen', () {- final server = ConversationServer()..append('Hello');- final view = _saved(server);+ test('a refused first read clears every chat', () {+ final server = ConversationServer()+ ..append('Hello')+ ..append('Secret', conversationId: 'offline');+ final view = savedWithChats(server, ['offline']);fakeAsync((async) {final c = SuperTabController(tabId: 'tab',accountId: 'owner',- request: (method, path, {body}) => Future.error(const SuperTabFailure('FORBIDDEN', 'You no longer have access.', statusCode: 403)),+ request: (method, path, {body}) => Future.error(+ const SuperTabFailure(+ 'FORBIDDEN',+ 'You no longer have access.',+ statusCode: 403,+ ),+ ),save: server.save,initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': 'lead'},reading: SuperTabReading.desktop,)..drawSaved(view);- expect(c.snapshot, isNotNull);+ expect(c.messages('offline'), isNotEmpty);+ c.start();+ async.flushMicrotasks();+ expect(c.messages('offline'), isEmpty);+ c.dispose();+ });+ });++ test('a chat the saved state does not list is never drawn, and a broken one is skipped', () {+ final server = ConversationServer()+ ..append('Hello')+ ..append('In the other chat', conversationId: 'offline');+ final view = savedWithChats(server, ['offline']);+ final chats = view['chats'] as List;+ final row = {+ ...(((chats.first as Map)['messages'] as List).first as Map),+ };+ chats+ ..add({+ 'id': 'private',+ 'messages': [+ {...row, 'conversationId': 'private'},+ ],+ })+ ..add({+ 'id': 'lead',+ 'messages': [row],+ })+ ..add('broken');+ fakeAsync((async) {+ final c = _controller(_Reads(server), reading: SuperTabReading.desktop)+ ..drawSaved(view);+ expect(c.messages('private'), isEmpty);+ expect(c.messages('offline'), isNotEmpty);+ expect(c.messages('lead').map((m) => m.conversationId).toSet(), {+ 'lead',+ });+ c.dispose();+ });+ });++ test(+ 'keeps at most 5 other chats of 30 rows each, the latest read first',+ () {+ final server = ConversationServer()..append('Hello');+ final ids = <String>[];+ final conversations = server.state['conversations'] as List;+ for (var i = 0; i < 7; i++) {+ final id = 'chat-$i';+ ids.add(id);+ conversations.add({+ ...(conversations.first as Map<String, dynamic>),+ 'id': id,+ });+ for (var m = 0; m < 40; m++) {+ server.append('m$m', conversationId: id);+ }+ }+ final view = savedWithChats(server, ids);+ final kept = view['chats'] as List;+ expect(kept.map((c) => (c as Map)['id']), [+ 'chat-6',+ 'chat-5',+ 'chat-4',+ 'chat-3',+ 'chat-2',+ ]);+ expect(((kept.first as Map)['messages'] as List).length, 30);+ },+ );++ test('a restart keeps the order the chats were read in', () {+ final server = ConversationServer()..append('Hello');+ final ids = <String>[];+ final conversations = server.state['conversations'] as List;+ for (var i = 0; i < 3; i++) {+ final id = 'chat-$i';+ ids.add(id);+ conversations.add({+ ...(conversations.first as Map<String, dynamic>),+ 'id': id,+ });+ server.append('m', conversationId: id);+ }+ final view = savedWithChats(server, ids);+ fakeAsync((async) {+ final c = _controller(_Reads(server), reading: SuperTabReading.desktop)+ ..drawSaved(view)+ ..start();+ async.flushMicrotasks();+ expect(+ (c.savedView!['chats'] as List).map((chat) => (chat as Map)['id']),+ ['chat-2', 'chat-1', 'chat-0'],+ );+ c.dispose();+ });+ });++ test(+ 'a view over its limit drops the oldest chats, and keeps the open one',+ () async {+ final store = MemoryStore();+ final views = SuperTabSavedViews(store, maxBytes: 4096);+ await views.claim('owner');+ final view = {+ ..._view(),+ 'chats': [+ {+ 'id': 'a',+ 'messages': [+ {'text': 'x' * 100},+ ],+ },+ {+ 'id': 'b',+ 'messages': [+ {'text': 'x' * 8000},+ ],+ },+ ],+ };+ expect(await views.write('owner', 'tab', view), isTrue);+ final kept = await views.read('owner', 'tab');+ expect(kept, isNotNull);+ expect((kept!['chats'] as List).map((c) => (c as Map)['id']), ['a']);+ },+ );++ test(+ 'a sent message shows before the server answers, with its quiet mark',+ () {+ final server = ConversationServer()..append('Hello');+ fakeAsync((async) {+ final c = _controller(+ _Reads(server),+ reading: SuperTabReading.desktop,+ )..start();+ async.flushMicrotasks();+ server.holdCommands = Completer<void>();+ c.setDraft('lead', 'On its way');+ unawaited(c.send());+ expect(c.outgoing('lead').single.text, 'On its way');+ expect(+ c.outgoing('lead').single.state,+ SuperTabOutgoingState.sending,+ );+ server.holdCommands!.complete();+ server.holdCommands = null;+ async.flushMicrotasks();+ c.dispose();+ });+ },+ );+ });++ // Task #2169: Desktop draws at once, as the saved view is this account's own (SuperTabSavedViews is keyed by account).+ group('on Desktop', () {+ test('a saved view draws before the first read answers, and the read replaces it', () {+ final server = ConversationServer()..append('Please start.');+ final view = _saved(server);+ fakeAsync((async) {+ server+ ..append('Done.')+ ..holdReads = Completer<void>();+ final c = _controller(_Reads(server), reading: SuperTabReading.desktop)+ ..drawSaved(view);+ expect(c.snapshot!.name, 'Pilot');+ expect(c.messages('lead').single.text, 'Please start.');+ expect(c.showingSaved, isTrue);+ expect(c.loading, isFalse);c.start();async.flushMicrotasks();- expect(c.accessRevoked, isTrue);+ expect(c.showingSaved, isTrue);+ server.holdReads!.complete();+ server.holdReads = null;+ async.flushMicrotasks();expect(c.showingSaved, isFalse);- expect(c.snapshot, isNull);- expect(c.messages('lead'), isEmpty);+ expect(c.messages('lead').map((m) => m.text), [+ 'Please start.',+ 'Done.',+ ]);c.dispose();});});++ test(+ 'a first read that is refused takes the saved view off the screen',+ () {+ final server = ConversationServer()..append('Hello');+ final view = _saved(server);+ fakeAsync((async) {+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: (method, path, {body}) => Future.error(+ const SuperTabFailure(+ 'FORBIDDEN',+ 'You no longer have access.',+ statusCode: 403,+ ),+ ),+ save: server.save,+ initial: {+ 'tabId': 'tab',+ 'accountId': 'owner',+ 'selectedId': 'lead',+ },+ reading: SuperTabReading.desktop,+ )..drawSaved(view);+ expect(c.snapshot, isNotNull);+ c.start();+ async.flushMicrotasks();+ expect(c.accessRevoked, isTrue);+ expect(c.showingSaved, isFalse);+ expect(c.snapshot, isNull);+ expect(c.messages('lead'), isEmpty);+ c.dispose();+ });+ },+ );});test('a saved view read after the Swarm was refused draws nothing', () {@@ -1150,42 +1412,39 @@ void _reviewTests() {});});- test(- 'an earlier page asked for over the saved view leaves no gap when the '- 'read replacing that view lands first',- () {- final server = ConversationServer();- for (var i = 1; i <= 120; i++) {+ test('an earlier page asked for over the saved view leaves no gap when the '+ 'read replacing that view lands first', () {+ final server = ConversationServer();+ for (var i = 1; i <= 120; i++) {+ server.append('m$i');+ }+ final view = _saved(server);+ fakeAsync((async) {+ for (var i = 121; i <= 270; i++) {server.append('m$i');}- final view = _saved(server);- fakeAsync((async) {- for (var i = 121; i <= 270; i++) {- server.append('m$i');- }- final reads = _Reads(server)..holdOlder = Completer<void>();- final c = _controller(reads)- ..drawSaved(view)- ..start();- // Scrolled up at once: from where the saved page said earlier- // continues, while the read replacing that page is on its way.- unawaited(c.loadMessages('lead', older: true));- async.flushMicrotasks();- expect(c.messages('lead').first.text, 'm171');- reads.holdOlder!.complete();- reads.holdOlder = null;- async.flushMicrotasks();+ final reads = _Reads(server)..holdOlder = Completer<void>();+ final c = _controller(reads)+ ..drawSaved(view)+ ..start();+ // Scrolled up at once: from where the saved page said earlier+ // continues, while the read replacing that page is on its way.+ unawaited(c.loadMessages('lead', older: true));+ async.flushMicrotasks();+ expect(c.messages('lead').first.text, 'm171');+ reads.holdOlder!.complete();+ reads.holdOlder = null;+ async.flushMicrotasks();- final sequences = c.messages('lead').map((m) => m.sequence).toList();- expect(sequences.last, 270);- for (var i = 1; i < sequences.length; i++) {- expect(sequences[i], sequences[i - 1] + 1, reason: 'at $i');- }- expect(c.hasOlder('lead'), sequences.first > 1);- c.dispose();- });- },- );+ final sequences = c.messages('lead').map((m) => m.sequence).toList();+ expect(sequences.last, 270);+ for (var i = 1; i < sequences.length; i++) {+ expect(sequences[i], sequences[i - 1] + 1, reason: 'at $i');+ }+ expect(c.hasOlder('lead'), sequences.first > 1);+ c.dispose();+ });+ });// Finding 2.test('nothing is written back while the saved view is on screen', () {diff --git a/desktop/test/super_tab_visible_tick_test.dart b/desktop/test/super_tab_visible_tick_test.dartnew file mode 100644index 000000000..08e39a5b7--- /dev/null+++ b/desktop/test/super_tab_visible_tick_test.dart@@ -0,0 +1,191 @@+import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/leaderboard/reader.dart';+import 'package:harness/super_tabs/visible_tick.dart';++import 'support/super_tab_fixture.dart';++// Task #2195: nothing redraws on a timer while it's off screen.++class _Panel extends StatefulWidget {+ const _Panel({required this.builds, required this.changes});+ final List<int> builds;+ final List<bool> changes;+ @override+ State<_Panel> createState() => _PanelState();+}++class _PanelState extends State<_Panel>+ with WidgetsBindingObserver, VisibleTick<_Panel> {+ @override+ void initState() {+ super.initState();+ visibleTick(const Duration(seconds: 1));+ }++ @override+ void onScreenChanged(bool onScreen) => widget.changes.add(onScreen);++ @override+ Widget build(BuildContext context) {+ widget.builds.add(1);+ return const SizedBox();+ }+}++Widget _frame(_Panel panel, {required bool on}) => Directionality(+ textDirection: TextDirection.ltr,+ child: TickerMode(enabled: on, child: panel),+);++void main() {+ testWidgets('ticks while on screen', (tester) async {+ final builds = <int>[], panel = _Panel(builds: builds, changes: []);+ await tester.pumpWidget(_frame(panel, on: true));+ builds.clear();+ await tester.pump(const Duration(seconds: 3));+ expect(builds, isNotEmpty);+ });++ testWidgets(+ 'does not tick or rebuild off screen, and redraws at once on coming back',+ (tester) async {+ final builds = <int>[],+ changes = <bool>[],+ panel = _Panel(builds: builds, changes: changes);+ await tester.pumpWidget(_frame(panel, on: false));+ builds.clear();+ await tester.pump(const Duration(seconds: 5));+ await tester.pump(const Duration(seconds: 5));+ expect(builds, isEmpty);+ await tester.pumpWidget(_frame(panel, on: true));+ expect(builds, isNotEmpty);+ expect(changes.last, isTrue);+ builds.clear();+ await tester.pump(const Duration(seconds: 2));+ expect(builds, isNotEmpty);+ },+ );++ testWidgets('stops when its tab leaves the screen', (tester) async {+ final builds = <int>[],+ changes = <bool>[],+ panel = _Panel(builds: builds, changes: changes);+ await tester.pumpWidget(_frame(panel, on: true));+ await tester.pumpWidget(_frame(panel, on: false));+ expect(changes.last, isFalse);+ builds.clear();+ await tester.pump(const Duration(seconds: 5));+ expect(builds, isEmpty);+ });++ testWidgets('stops while the app is hidden, and redraws when it returns', (+ tester,+ ) async {+ final builds = <int>[],+ changes = <bool>[],+ panel = _Panel(builds: builds, changes: changes);+ await tester.pumpWidget(_frame(panel, on: true));+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ await tester.pump();+ expect(changes.last, isFalse);+ builds.clear();+ await tester.pump(const Duration(seconds: 5));+ expect(builds, isEmpty);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await tester.pump();+ expect(changes.last, isTrue);+ expect(builds, isNotEmpty);+ });++ test('a project board reads nothing while its Swarm is away, and goes on when it returns', () async {+ final server = ConversationServer()+ ..leaderboard = {'people': const <Object>[]};+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ final board = SuperTabProjectBoard(+ c,+ every: const Duration(milliseconds: 5),+ );+ addTearDown(board.dispose);+ await Future<void>.delayed(const Duration(milliseconds: 30));+ expect(server.leaderboardReads, isNotEmpty);+ c.away = true;+ await Future<void>.delayed(const Duration(milliseconds: 10));+ final read = server.leaderboardReads.length;+ await Future<void>.delayed(const Duration(milliseconds: 40));+ expect(server.leaderboardReads, hasLength(read));+ c.away = false;+ await Future<void>.delayed(const Duration(milliseconds: 40));+ expect(server.leaderboardReads.length, greaterThan(read));+ });++ test('a project board reads at once when its Swarm returns, having missed a read', () {+ fakeAsync((async) {+ final server = ConversationServer()+ ..leaderboard = {'people': const <Object>[]};+ final c = server.controller();+ unawaited(c.refresh());+ async.flushMicrotasks();+ final board = SuperTabProjectBoard(c);+ async.flushMicrotasks();+ c.away = true;+ final read = server.leaderboardReads.length;+ async.elapse(const Duration(minutes: 6));+ expect(server.leaderboardReads, hasLength(read));+ c.away = false;+ async.flushMicrotasks();+ expect(server.leaderboardReads, hasLength(read + 1));+ c.away = true;+ c.away = false;+ async.flushMicrotasks();+ expect(+ server.leaderboardReads,+ hasLength(read + 1),+ reason: 'it missed nothing this time',+ );+ board.dispose();+ c.dispose();+ });+ });++ testWidgets('of a stack of pages, only the one showing ticks', (+ tester,+ ) async {+ final shown = <int>[], hidden = <int>[];+ Widget pages(int index) => Directionality(+ textDirection: TextDirection.ltr,+ child: SuperTabPages(+ index: index,+ children: [+ _Panel(builds: shown, changes: []),+ _Panel(builds: hidden, changes: []),+ ],+ ),+ );+ await tester.pumpWidget(pages(0));+ shown.clear();+ hidden.clear();+ await tester.pump(const Duration(seconds: 3));+ expect(shown, isNotEmpty);+ expect(hidden, isEmpty);+ await tester.pumpWidget(pages(1));+ shown.clear();+ hidden.clear();+ await tester.pump(const Duration(seconds: 3));+ expect(shown, isEmpty);+ expect(hidden, isNotEmpty);+ });++ testWidgets('leaves no timer behind when it goes', (tester) async {+ await tester.pumpWidget(_frame(_Panel(builds: [], changes: []), on: true));+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 2));+ });+}diff --git a/desktop/test/ws_conn_decode_test.dart b/desktop/test/ws_conn_decode_test.dartnew file mode 100644index 000000000..643d9e1bc--- /dev/null+++ b/desktop/test/ws_conn_decode_test.dart@@ -0,0 +1,293 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/ws/relay_codec.dart';+import 'package:harness/ws/ws_conn.dart';++// Task #2195: a big answer decodes off the UI thread, and frames stay in the order they came.++String _frame(int seq, {int pad = 0}) => jsonEncode({+ 'type': 'terminal_output',+ 'payload': {'streamId': 's', 'seq': seq, 'pad': 'x' * pad},+});++/// A seal nothing opens: whatever reaches the app from a sealed connection got past it.+class _ClosedSeal implements RelayCodec {+ int opened = 0;++ @override+ Map<String, dynamic> helloFrame() => {'type': 'e2e_hello', 'payload': {}};++ @override+ Future<bool> handleWelcome(Map<String, dynamic> payload) async => true;++ @override+ bool handleRekey(Map<String, dynamic> payload) => true;++ @override+ int get terminalP2pVersion => 1;++ @override+ Map<String, dynamic>? encodeFrame(Map<String, dynamic> frame) => frame;++ @override+ Map<String, dynamic>? decodeFrame(Map<String, dynamic> frame) {+ opened++;+ return null;+ }++ @override+ Uint8List? encodeBinary(Uint8List localFrame) => localFrame;++ @override+ Uint8List? decodeBinary(Uint8List wireFrame) {+ opened++;+ return null;+ }+}++void main() {+ late HttpServer server;+ late WebSocket socket;+ late WsConn conn;+ late List<int> arrived;+ final decoded = <int>[];+ Completer<void>? hold;++ setUp(() async {+ arrived = [];+ decoded.clear();+ hold = null;+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ final ready = Completer<WebSocket>(), connected = Completer<void>();+ unawaited(+ server.forEach((request) async {+ final s = await WebSocketTransformer.upgrade(request);+ s.listen((raw) {+ final frame = jsonDecode(raw as String) as Map<String, dynamic>;+ if (frame['type'] == 'machine_select') {+ s.add(+ jsonEncode({+ 'type': 'connected',+ 'payload': {'machineId': 'm'},+ }),+ );+ }+ });+ if (!ready.isCompleted) ready.complete(s);+ }),+ );+ WsConn.decodeLargeFrame = (raw) async {+ decoded.add(raw.length);+ await hold?.future;+ return jsonDecode(raw);+ };+ addTearDown(() => WsConn.decodeLargeFrame = WsConn.decodeInIsolate);+ conn = WsConn(+ wsBaseUrl: 'ws://127.0.0.1:${server.port}',+ autonomousEnv: 'prod',+ machineId: 'm',+ accessTokenProvider: (_, _) async => 'test-token',+ onAuthFailure: (_) {},+ onStatus: (status) {+ if (status == ConnectionStatus.connected && !connected.isCompleted)+ connected.complete();+ },+ onEvent: (event) {+ if (event['type'] == 'terminal_output')+ arrived.add((event['payload'] as Map)['seq'] as int);+ },+ );+ unawaited(conn.connect());+ socket = await ready.future;+ await connected.future;+ });++ tearDown(() async {+ await conn.close();+ await server.close(force: true);+ });++ Future<void> until(bool Function() done) async {+ for (var i = 0; i < 200 && !done(); i++) {+ await Future<void>.delayed(const Duration(milliseconds: 5));+ }+ }++ test(+ 'a large frame goes to the isolate decoder, a small one does not',+ () async {+ socket+ ..add(_frame(1))+ ..add(_frame(2, pad: WsConn.largeFrameChars));+ await until(() => arrived.length == 2);+ expect(arrived, [1, 2]);+ expect(decoded, hasLength(1));+ },+ );++ test('a small frame after a large one still arrives second', () async {+ hold = Completer<void>();+ socket+ ..add(_frame(1, pad: WsConn.largeFrameChars))+ ..add(_frame(2))+ ..add(_frame(3));+ await until(() => decoded.isNotEmpty);+ await Future<void>.delayed(const Duration(milliseconds: 30));+ expect(arrived, isEmpty);+ hold!.complete();+ await until(() => arrived.length == 3);+ expect(arrived, [1, 2, 3]);+ });++ test(+ 'a large frame that does not parse is dropped, and the next arrives',+ () async {+ socket+ ..add('{${'x' * WsConn.largeFrameChars}')+ ..add(_frame(2));+ await until(() => arrived.isNotEmpty);+ expect(arrived, [2]);+ },+ );++ test('a frame still arrives when the isolate cannot start', () async {+ WsConn.decodeLargeFrame = (_) => throw StateError('no isolate');+ socket.add(_frame(1, pad: WsConn.largeFrameChars));+ await until(() => arrived.isNotEmpty);+ expect(arrived, [1]);+ });++ // Security review 2 of #2627: a frame keeps the connection it came on. Finished after that connection went, it reaches nothing.+ test('a large frame whose connection drops while it decodes reaches nothing, nor does what waited behind it', () async {+ hold = Completer<void>();+ socket+ ..add(_frame(1, pad: WsConn.largeFrameChars))+ ..add(_frame(2));+ await until(() => decoded.isNotEmpty);+ await Future<void>.delayed(const Duration(milliseconds: 20));+ await conn.debugDropTransport();+ await Future<void>.delayed(const Duration(milliseconds: 20));+ hold!.complete();+ await Future<void>.delayed(const Duration(milliseconds: 40));+ expect(arrived, isEmpty);+ });++ test('a large frame still decoding at close reaches nothing', () async {+ hold = Completer<void>();+ socket+ ..add(_frame(1, pad: WsConn.largeFrameChars))+ ..add(_frame(2));+ await until(() => decoded.isNotEmpty);+ await conn.close();+ hold!.complete();+ await Future<void>.delayed(const Duration(milliseconds: 40));+ expect(arrived, isEmpty);+ });++ test(+ 'the real isolate decoder decodes, and says null for what will not parse',+ () async {+ expect(+ await WsConn.decodeInIsolate(_frame(1)),+ isA<Map<String, dynamic>>(),+ );+ expect(await WsConn.decodeInIsolate('{nope'), isNull);+ },+ );++ group('on a sealed connection', () {+ late HttpServer relay;+ late WebSocket wire;+ late WsConn sealed;+ late _ClosedSeal seal;+ late List<int> dispatched;+ late List<int> binaries;++ setUp(() async {+ seal = _ClosedSeal();+ dispatched = [];+ binaries = [];+ relay = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ final ready = Completer<WebSocket>();+ unawaited(+ relay.forEach((request) async {+ final s = await WebSocketTransformer.upgrade(request);+ s.listen((_) {});+ if (!ready.isCompleted) ready.complete(s);+ }),+ );+ sealed = WsConn(+ wsBaseUrl: 'ws://127.0.0.1:${relay.port}',+ autonomousEnv: 'prod',+ machineId: 'm',+ accessTokenProvider: (_, _) async => 'test-token',+ onAuthFailure: (_) {},+ relayCodecs: (_) async => seal,+ onStatus: (_) {},+ onEvent: (event) {+ final seq = (event['payload'] as Map?)?['seq'];+ if (seq is int) dispatched.add(seq);+ },+ );+ sealed.onBinaryFrame = (frame) async => binaries.add(frame.length);+ unawaited(sealed.connect());+ wire = await ready.future;+ await Future<void>.delayed(const Duration(milliseconds: 20));+ });++ tearDown(() async {+ await sealed.close();+ await relay.close(force: true);+ });++ // Security review 2 of #2627: the relay isn't trusted here. A large frame to hold the queue,+ // a forged one behind it, then a dropped socket must not make the forged one the machine's.+ test('a forged frame behind a large one, the socket then dropped, reaches nothing', () async {+ hold = Completer<void>();+ wire+ ..add(_frame(1, pad: WsConn.largeFrameChars))+ ..add(_frame(2))+ ..add(Uint8List.fromList([1, 2, 3]));+ await until(() => decoded.isNotEmpty);+ await Future<void>.delayed(const Duration(milliseconds: 20));+ await wire.close();+ await Future<void>.delayed(const Duration(milliseconds: 40));+ hold!.complete();+ await Future<void>.delayed(const Duration(milliseconds: 40));+ expect(dispatched, isEmpty);+ expect(binaries, isEmpty);+ });++ test(+ 'a forged frame behind a large one reaches nothing after close',+ () async {+ hold = Completer<void>();+ wire+ ..add(_frame(1, pad: WsConn.largeFrameChars))+ ..add(_frame(2));+ await until(() => decoded.isNotEmpty);+ await Future<void>.delayed(const Duration(milliseconds: 20));+ await sealed.close();+ hold!.complete();+ await Future<void>.delayed(const Duration(milliseconds: 40));+ expect(dispatched, isEmpty);+ },+ );++ test(+ 'with the socket up, a large frame goes through the seal like any other',+ () async {+ wire+ ..add(_frame(1, pad: WsConn.largeFrameChars))+ ..add(_frame(2));+ await until(() => seal.opened >= 2);+ expect(dispatched, isEmpty);+ },+ );+ });+}diff --git a/docs/plans/2026-11-02-quiet-swarm-design.md b/docs/plans/2026-11-02-quiet-swarm-design.mdnew file mode 100644index 000000000..445735daf--- /dev/null+++ b/docs/plans/2026-11-02-quiet-swarm-design.md@@ -0,0 +1,435 @@+# Quiet Swarm: the Desktop Swarm screen, redesigned (Dee)++Requested by [email protected]. Brainstormed 2026-11-02; direction A ("Quiet Slack") chosen, polished once, and approved by Dee on 2026-11-02 ("let's build it. make it super light and super clean. super fast to load the app and use too. no sluggish. try to reach zero latency.").++## Why++Dee: "it looks like a bad buffet rather than a carefully crafted product." Today's Swarm screen shows+everything at once: a 10-line Status card, a "While you were away" box and Shipped cards stacked over+the chat; an always-open right column of people with scores and 15+ agents with model, effort and task;+a sidebar with machines, models and red counts; 9 tabs across the top. Harness is a team chat where half+the team are agents, so it should feel like the team chats people already know (Slack, Discord,+Telegram): the conversation is the product, everything else is a way to reach a conversation.++## What the three apps taught us++- One column carries the day: the chat. Lists of people open only when asked.+- News is a place you visit (Slack's Activity, Discord's Inbox), never banners stacked over the chat.+- A row is one line. Bold means something new; one number means "this is for you".+- A bot's long job is one message that updates itself, not a new card per step.+- They open from what they already have and fill in the rest quietly.++## Goals++- Two columns at rest: sidebar and chat.+- Red numbers only mean "this is for you": Activity's count of what needs you, and on a project row the mentions of you that opening it will show.+- Every list row is one line.+- Each task is one chat message that keeps itself current until it merges; its thread holds the detail.+- People, agents, machines, models and devices are one click away, never on screen by default.+- It feels instant: opening the app, a project or a Swarm shows the last screen at once and fills in quietly; sending shows the message at once (see Speed).++## Non-goals++- No new features. Every function on today's screen keeps a home (table below).+- The terminal workspace and panes don't change; a project's panes stay behind its terminal button.+- The phone app follows in a second pass, after Desktop ships.++## Anti-goals++- A screen that is calmer but loses something a person relied on.+- More words. Headings, names and one status word; reasons go in tooltips.+- New colors, icons or controls outside the Harness design system.++## Rules++- Something new makes a row bold, with no dot. A project row's red number counts only messages that mention you that opening it shows (its chat and threads), Slack's way, chosen by Dee; opening it lands on the first one and reading clears it. Mentions inside task conversations go to Activity.+- Activity is the one place for everything new for you: Needs you, New replies (the old Threads view), Done today. No filter pills; every row one line.+- A task is one line in the chat: its name and one word (planned, working, in review, shipped), or Answer when it needs you.+- Members rows: name, then status word and mark. Role, model, effort and machine go on the agent's card.+- A Buddy's proposal shows as one line that opens; the PM's notices (stalled, idle, work changed) never show in the chat people read.+- People show as their username (the part of the email before @).+- Model, effort and machine appear only on an agent's card.+- Points: one number per person, rolling 7 days; the period is on hover. The crown follows the week's top name.+- Shortcuts show in menus, never on the screen at rest.++## Screens++The drawings show structure, not pixels. Bold can't be drawn in text; in the app a row with something new is bold.++Top bar: tabs stay, as Dee asked on 10-31, with names only (a tab's ⌘ number shows while you hold ⌘) and no count; a tab's name is bold when something there needs you. The right side keeps Search, Notifications and your avatar; Add Phone, Devices and the Store move into the avatar menu.++**0 · Top bar**+```+┌───────────────────────────────────────────────────────────────────────┐+│ lampOS strategies autonomous.ai hardware growth … + ⌕ ♢ D │+└───────────────────────────────────────────────────────────────────────┘+```++**1 · A project, at rest**+```+┌────────────────────┬──────────────────────────────────────────────────┐+│ autonomous.ai ▾ │ # openharness ▾ Members >_ │+│ │ │+│ Activity 3 │ ken15 6:50 PM │+│ Buddy │ Prod DB profile: five slow reads to fix. │+│ │ 4 replies │+│ Projects + │ │+│ # computer │ ✓ Closed agents leave the list shipped │+│ # lamp 2 │ │+│ # openharness │ ◐ Windows credential fix in review │+│ # physical-router │ │+│ # spaceship │ ▸ Proposal from diego: Activity read fix │+│ │ │+│ │ River 8:09 PM │+│ │ Three fixes are on main. │+│ │ │+│ │ ──────────────────── New ──────────────────── │+│ │ dee 8:41 PM │+│ │ ok i like a. let's make it perfect. │+│ │ │+│ │ ╭─────────────────────────────────────────────╮ │+│ │ │ Message #openharness + ↑ │ │+│ Manage │ ╰─────────────────────────────────────────────╯ │+└────────────────────┴──────────────────────────────────────────────────┘+```++**2 · A task's message, through its life**+```+┌────────────────────────────────────────────────────────┐+│ ◌ Phone Activity opens the right message planned │+├────────────────────────────────────────────────────────┤+│ ◐ Phone Activity opens the right message working │+├────────────────────────────────────────────────────────┤+│ ◐ Phone Activity opens the right message Answer │+├────────────────────────────────────────────────────────┤+│ ◐ Phone Activity opens the right message in review │+├────────────────────────────────────────────────────────┤+│ ✓ Phone Activity opens the right message shipped │+└────────────────────────────────────────────────────────┘+```++**3 · Clicking a task opens its conversation**+```+┌────────────────────┬──────────────────────────────────────────┬──────────────────────────────┐+│ autonomous.ai ▾ │ # openharness ▾ Members >_ │ Thread ✕ │+│ │ │ │+│ Activity 3 │ ✓ Closed agents leave the list shipped │ ◐ Windows credential fix │+│ Buddy │ │ Theo · in review │+│ │ ◐ Windows credential fix in review │ │+│ Projects + │ 3 replies │ Theo 8:12 PM │+│ # computer │ │ Ready: PR #2605. │+│ # lamp 2 │ River 8:09 PM │ │+│ # openharness │ Three fixes are on main. │ Reed 8:20 PM │+│ # physical-router │ │ With fixes: one Important. │+│ # spaceship │ ╭─────────────────────────────────────╮ │ │+│ │ │ Message #openharness + ↑ │ │ Theo 8:31 PM │+│ │ ╰─────────────────────────────────────╯ │ Fixed at 98bcfd21c. │+│ │ │ │+│ │ │ ╭─────────────────────────╮ │+│ │ │ │ Reply ↑ │ │+│ Manage │ │ ╰─────────────────────────╯ │+└────────────────────┴──────────────────────────────────────────┴──────────────────────────────┘+```++**4 · Members**+```+┌────────────────────┬──────────────────────────────────────────┬──────────────────────────────┐+│ autonomous.ai ▾ │ # openharness ▾ Members >_ │ This project ▾ ✕ │+│ │ │ │+│ Activity 3 │ ken15 6:50 PM │ People │+│ Buddy │ Prod DB profile: five slow reads to fix. │ ken15 ♛ 424 │+│ │ 4 replies │ diego 394 │+│ Projects + │ │ dee 339 │+│ # computer │ ✓ Closed agents leave the list shipped │ tony 239 │+│ # lamp 2 │ │ scholes 210 │+│ # openharness │ ╭─────────────────────────────────────╮ │ phamngochuy.1989 48 │+│ # physical-router │ │ Message #openharness + ↑ │ │ │+│ # spaceship │ ╰─────────────────────────────────────╯ │ Agents │+│ │ │ Nico waiting ◐ │+│ │ │ River working ● │+│ │ │ Theo working ● │+│ │ │ Iris working ● │+│ Manage │ │ Idle (10) ▸ │+└────────────────────┴──────────────────────────────────────────┴──────────────────────────────┘+```++**5 · A member's card**+```+┌──────────────────────────────────────────┐+│ Theo Dev │+│ Windows credential fix │+│ Opus · high · MacBooks-MacBook-Pro-9 │+│ │+│ Open terminal Details… │+└──────────────────────────────────────────┘+┌──────────────────────────────────────────┐+│ ken15 ♛ 424 points │+│ 111 shipped · 40 unblocked · 411 hours │+│ │+│ Manage people │+└──────────────────────────────────────────┘+```++**6 · Activity: everything new for you, in one place**+```+┌────────────────────┬──────────────────────────────────────────────────┐+│ autonomous.ai ▾ │ Activity │+│ │ │+│ Activity 3 │ Needs you │+│ Buddy │ ◐ W1 ships alone or waits? Answer │+│ │ ◐ Nico is waiting on you Open │+│ Projects + │ @ River mentioned you in # openharness 8:09 PM │+│ # computer │ │+│ # lamp 2 │ New replies │+│ # openharness │ Windows credential fix 3 new │+│ # physical-router │ Prod DB profile 1 new │+│ # spaceship │ │+│ │ Done today │+│ │ ✓ Closed agents leave the list 8:08 PM │+│ Manage │ ✓ Commits read Harness by Autonomous 8:28 PM │+└────────────────────┴──────────────────────────────────────────────────┘+```++**7 · Your Buddy**+```+┌────────────────────┬──────────────────────────────────────────────────┐+│ autonomous.ai ▾ │ Buddy │+│ │ │+│ Activity 3 │ dee 8:02 PM │+│ Buddy │ Draft a note to the team about the new look. │+│ │ │+│ Projects + │ Buddy 8:03 PM │+│ # computer │ Here's a draft: … │+│ # lamp 2 │ │+│ # openharness │ ╭─────────────────────────────────────────────╮ │+│ # physical-router │ │ Message Buddy New session + ↑ │ │+│ # spaceship │ ╰─────────────────────────────────────────────╯ │+│ Manage │ │+└────────────────────┴──────────────────────────────────────────────────┘+```++**8 · Swarm switcher**+```+┌────────────────────────────────┐+│ Personal │+│ autonomous.ai ✓ │+├────────────────────────────────┤+│ New Swarm │+└────────────────────────────────┘+```++**9 · Project menu**+```+┌──────────────────────────────────┐+│ Status ▸ │+│ Pull requests │+│ Instructions │+│ Sharing │+│ Notifications ▸ │+├──────────────────────────────────┤+│ Project settings… │+└──────────────────────────────────┘+```++**9b · Status**+```+┌────────────────────────────────────────────────────┐+│ Status · updated 8:33 PM ✕ │+│ │+│ Three fixes are on main tonight. Windows │+│ credential fix: last real Windows run going. │+│ Ken's five database fixes: one ready, four in │+│ review. Dee's calmer app: design out for review. │+└────────────────────────────────────────────────────┘+```++**10 · Manage › Machines**+```+┌────────────────────┬──────────────────────────────────────────────────┐+│ autonomous.ai ▾ │ Manage │+│ │ Machines Models Devices Swarm │+│ Activity 3 │ │+│ Buddy │ ~ Diego's Mac diego online │+│ │ ~ Mac 1 dee online │+│ Projects + │ ~ MacBookPro2021 phamngochuy.1989 online │+│ # computer │ ~ MacBooks-MacBook-Pro-9 scholes online │+│ # lamp 2 │ ~ MacBooks-MacBook-Pro-10 diego online │+│ # openharness │ ~ MacBooks-MacBook-Pro-19 tony online │+│ # physical-router │ ~ MACs-Mac-Studio ken15 online │+│ # spaceship │ ~ Mac 3 dee offline │+│ │ Teammates' agents paused │+│ │ ~ MacbookPro ken15 offline │+│ │ │+│ Manage │ Add machine │+└────────────────────┴──────────────────────────────────────────────────┘+```++**10b · Manage › Models**+```+┌────────────────────┬──────────────────────────────────────────────────┐+│ autonomous.ai ▾ │ Manage │+│ │ Machines Models Devices Swarm │+│ Activity 3 │ │+│ Buddy │ Opus 62% │+│ │ Sonnet 21% │+│ Projects + │ GPT-6.1 Sol 11% │+│ # computer │ DeepSeek v4.1 6% │+│ # lamp 2 │ │+│ # openharness │ Your models… │+│ # physical-router │ │+│ # spaceship │ │+│ Manage │ │+└────────────────────┴──────────────────────────────────────────────────┘+```++**10c · Manage › Swarm**+```+┌────────────────────┬──────────────────────────────────────────────────┐+│ autonomous.ai ▾ │ Manage │+│ │ Machines Models Devices Swarm │+│ Activity 3 │ │+│ Buddy │ Name autonomous.ai │+│ │ Owner ken15 │+│ Projects + │ People 6 Manage people │+│ # computer │ │+│ # lamp 2 │ Leave Swarm… │+│ # openharness │ │+│ # physical-router │ │+│ # spaceship │ │+│ Manage │ │+└────────────────────┴──────────────────────────────────────────────────┘+```++**11 · A new project**+```+┌────────────────────┬──────────────────────────────────────────────────┐+│ autonomous.ai ▾ │ # design ▾ Members >_ │+│ │ │+│ Activity 3 │ │+│ Buddy │ │+│ │ │+│ Projects + │ Discuss the plan with Product Manager. │+│ # computer │ │+│ # lamp 2 │ │+│ # openharness │ │+│ # physical-router │ │+│ # spaceship │ ╭─────────────────────────────────────────────╮ │+│ │ │ Message #design + ↑ │ │+│ Manage │ ╰─────────────────────────────────────────────╯ │+└────────────────────┴──────────────────────────────────────────────────┘+```++**11b · Activity, all caught up**+```+┌────────────────────┬──────────────────────────────────────────────────┐+│ autonomous.ai ▾ │ Activity │+│ │ All Decisions Mentions Replies Reactions │+│ Activity │ │+│ Buddy │ │+│ │ │+│ Projects + │ You're all caught up. │+│ # computer │ │+│ # lamp 2 │ │+│ # openharness │ │+│ # physical-router │ │+│ # spaceship │ │+│ Manage │ │+└────────────────────┴──────────────────────────────────────────────────┘+```++**12 · A narrow window**+```+┌──────────────────────────────────────────────┐+│ ☰ # openharness ▾ >_ │+│ │+│ ken15 6:50 PM │+│ Prod DB profile: five slow reads to fix. │+│ │+│ ✓ Closed agents leave the list │+│ shipped by Atlas for phamngochuy.1989 │+│ │+│ ╭─────────────────────────────────────────╮ │+│ │ Message #openharness + ↑ │ │+│ ╰─────────────────────────────────────────╯ │+└──────────────────────────────────────────────┘+```+## What moves where++Nothing is removed without a home.++| Today | New home |+| --- | --- |+| 9 tabs across the top, with ⌘ numbers and counts | Stay, as Dee asked on 10-31: names only, the ⌘ number while ⌘ is held, no count (a tab's name is bold when something there needs you) |+| Search, Notifications, Add Phone, Devices, Store, avatar (top right) | Search, Notifications and the avatar stay; Add Phone, Devices and the Store move into the avatar menu |+| New project row | The **+** beside Projects (the same action, once) |+| Your devices | Manage › Devices |+| Your models, and Models with its usage % | Manage › Models |+| Activity with 36, and the Threads view | Activity: Needs you, New replies, Done today; its number counts only what needs you |+| Project rows with counts and chevrons | One line: bold when new, a red number only for mentions that opening it shows (it clears as you read), the lock for private; a second click on the open project still shows its workgroups |+| Machines section | Manage › Machines, with Add machine |+| Chat header: chat, terminal, pull requests, ⋮ | `# name ▾` opens the project menu (Status, Pull requests, Instructions, Sharing, Notifications, then Project settings… for rename, switch PM, archived and delete); Members and the terminal stay as buttons |+| Status card above the chat | Project menu › Status opens the PM's report as today; its Needs you rows go to Activity; finished work also shows in Activity › Done today |+| "While you were away" box | Activity (Needs you, Replies, Done today); the chat keeps its "New" line |+| Shipped cards | The task's own message, in its merged state |+| Humans column (points, period picker, project scope, shipped, unblocked, hours lent) | Members › People with points (rolling 7 days, period on hover); the project-or-Swarm choice Dee added today becomes Members' heading; the rest on the person's card |+| Agents column (role, model, effort, task, status) | Members › Agents with role and status; task, model, effort and machine on the agent's card |+| Invite (+ by Humans) | Members' **+**, and Manage › Swarm › Invite |+| Delete Swarm (bottom of the switcher, owner only) | Manage › Swarm; Leave Swarm for members |++## Calls made by the PM (check these while reading)++- **A task's message is posted by the server**, one per task that has an Engineer, so Desktop, the phone and agents see the+ same thing. It is edited in place as the task moves (planned, working, waiting on a person, in review, shipped), and it+ replaces today's live task card and Shipped line. Review and test steps get no message of their own; a private task's+ message shows only to its audience. Its thread is the task's own conversation, opened on the right, with "Open in full" to+ give it the main column. This needs backend and phone work, included in the build plan.+- **Tabs stay** where they are, quieter (above). The switcher holds only Swarms.+- **Members keeps the project-or-Swarm choice** as its heading. Agents are grouped: waiting on a person first, then working;+ idle agents fold under "Idle (N)".+- **The PM keeps writing its status report**; it moves from above the chat to the project menu's Status.++## Speed: aim for zero felt latency++Dee: "super fast to load the app and use too. no sluggish. try to reach zero latency." Every surface:+- Opens from what it already has (the last state and messages kept on the device for the signed-in account) and corrects quietly when the server answers.+- Shows a sent message at once, with a quiet sending mark, never a spinner.+- Decodes server answers off the UI thread, and builds only the rows on screen.+- Redraws only what changed; nothing redraws on a timer while it's off screen.++What the code shows today and what fixes it:+- Every machine's 15-second check-in rereads and redraws the whole Swarm screen, even one you aren't+ looking at. Being fixed tonight: a check-in updates only what shows machines.+- Opening the app runs six steps one after another and waits for your profile. Being fixed tonight:+ independent steps run together and the last screen shows at once.+- Panels redraw on timers (machines every second, the people list every 30 seconds, points every+ minute, pull request checks every minute). This design removes those panels from the screen at rest;+ their timers run only while they are open.+- The app already logs how long opening a Swarm takes; the release is measured before and after.++## Approaches considered++- **A. Quiet Slack** (chosen): two columns, news as messages and in Activity, Members on demand,+ Manage for machines, models, devices and the Swarm.+- **B. Telegram list**: one list of every chat, newest first. Simplest, but projects lose their place+ and agents' chatter mixes with people's.+- **C. Trim today's screen**: keep three columns, shrink each. Least change, but three columns still+ compete.++## Left to the builder++Exact spacing, type and colors come from the Harness design system (desktop-design-system.md); the+drawings show structure, not pixels. Section collapse, keyboard order, hover cards and the narrow-window+breakpoint follow the existing components. The naming system's Swarm section is updated to match.++## Build plan once approved++In parallel, each with a review and a browser-build test; each Engineer commits this design with its plan:+1. Sidebar, top bar and Manage (Machines, Models, Devices, Swarm).+2. The server posts and edits one message per task (backend).+3. The chat: one-line task messages, one-line proposals, no Status card / "While you were away" / Shipped cards, PM notices hidden, the project menu.+4. Activity takes in Threads: three sections, one-line rows, no filters.+5. Members panel and member cards.+6. Zero felt latency: open from cache, send at once, decode off the UI thread, build only visible rows.+Already in flight: the heartbeat fix, opening at once, and the project-row red number (Slack's way).++The phone follows the same design in a second pass.diff --git a/docs/plans/2026-11-02-quiet-swarm-zero-latency-plan.md b/docs/plans/2026-11-02-quiet-swarm-zero-latency-plan.mdnew file mode 100644index 000000000..cf3369338--- /dev/null+++ b/docs/plans/2026-11-02-quiet-swarm-zero-latency-plan.md@@ -0,0 +1,86 @@+# Quiet Swarm 6/6: Zero Felt Latency Implementation Plan++> **How this is worked:** by the project's instructions, task by task, each failing test committed before its code.++**Goal:** Swarm chats open from what the device already has for the signed-in account, big answers decode off the UI thread, and nothing redraws on a timer while it's off screen.++**Architecture:** The saved view, already kept per account, also carries the last rows of the chats most recently read, so switching chat or project after a restart shows them at once and the read corrects them. `WsConn` decodes large frames in an isolate, in frame order. A small `State` mixin runs a panel's timer only while its subtree is on screen and the app is in front.++**Tech Stack:** Dart, Flutter 3.47.2, `flutter_test`.++**Spec:** `docs/plans/2026-11-02-quiet-swarm-design.md`, section "Speed: aim for zero felt latency". Task #2195 (Dee). Builds on #2617, and this branch includes it until it lands.++## Global Constraints++- Another account's cache is never shown. Rows live inside the per-account saved view, so its forgetting at sign-in covers them.+- No new colors, icons or controls, and nothing on screen changes but its speed.+- No on/off switch. Tests use a memory store and a fake sign-in.+- Swarm code stays out of `cli/src/core`.+- The PR body starts with: `Requested by [email protected] through Harness.`+- Two security reviews: Reed and Orion.++## Review Focus++1. **A chat the reader lost access to:** its kept rows go when the first read answers, not only the selected chat's. A private chat's rows are never drawn for a chat the saved state doesn't list.+2. **Frame order:** a small frame after a large one still arrives second, so replies and pushes can't swap.+3. **A frame that won't decode in the isolate:** dropped as a bad frame is today, with the queue alive.+4. **The app behind other windows, and a panel on a tab that isn't showing:** no timer runs, and coming back draws at once, so the "2 min ago" text is never stale on screen.+5. **The kept view growing past its limit:** the older chats go first, so the selected chat's view is still kept.++## What's already there++A sent message already shows at once with a quiet sending mark (`outgoing`, `SuperTabOutgoingState.sending`), and no spinner. This task adds a test to hold that, and no code. The chat's messages already build lazily. The sidebar, Activity, Members and machine lists belong to the other parts of this design, whose Engineers are changing them now, so they are left to them.++## Design++- **Growth:** at most 5 other chats of 30 rows each in a saved view, inside its existing 512 KB limit, deleted with the view (7 days, 3 Swarms, sign-out).+- **Concurrency:** decoding joins the existing inbound queue, so frames stay in order.+- **Read cost:** none added. Fewer redraws and reads while off screen.+- **Scale:** at 10x rows, the view hits its byte limit first, and older chats drop. The log's `first open` line warns first.+- **Compatibility:** a view from before this has no extra chats and reads as today. An older build ignores the new key.+- **Migration and rollback:** none. Rolling back ignores the key.+- **Audience:** only this account's saved view holds these rows, and the server still decides at each read.+- **Identity:** the Harness account, never the machine owner's login.+- **Failure:** a bad row or chat in the view is skipped. A failed isolate spawn decodes on the UI thread as today.+- **Platforms:** the web has no isolates, and `compute` runs inline there, as today. The web's view has the same limits.++---++### Task 1: Timers only while on screen++**Files:**+- Create: `desktop/lib/super_tabs/visible_tick.dart`+- Modify: `machines.dart`, `roster.dart`, `leaderboard/reader.dart` callers, `pull_request_facts.dart` callers+- Test: `desktop/test/super_tab_visible_tick_test.dart`++**Interfaces:**+- Produces: `mixin VisibleTick<T extends StatefulWidget> on State<T>` with `visibleTick(Duration every, VoidCallback onTick)` and `onVisibleChanged(bool)`.++- [ ] **Step 1: Commit the failing tests:** under `TickerMode(enabled: false)`, or with the app hidden, a panel's timer doesn't fire and it doesn't rebuild; back on screen it redraws at once and ticks again; a board's refresh stops off screen; a pull request card stops watching off screen.+- [ ] **Step 2: Watch them fail,** then implement, run them and commit.++### Task 2: Large answers decode off the UI thread++**Files:**+- Modify: `desktop/lib/ws/ws_conn.dart`+- Test: `desktop/test/ws_conn_decode_test.dart`++**Interfaces:**+- Produces: `decodeFrame(String raw) -> Future<Map<String, dynamic>>`, in an isolate above `largeFrameChars` (256 KB, where its start stops costing more than it saves).++- [ ] **Step 1: Commit the failing tests:** a large frame goes to the isolate decoder and a small one doesn't; a small frame after a large one arrives second; a bad large frame is dropped and the next arrives; a failed spawn still decodes.+- [ ] **Step 2: Watch them fail,** then implement, run them and commit.++### Task 3: The last messages of each chat++**Files:**+- Modify: `desktop/lib/super_tabs/controller.dart`+- Test: `desktop/test/super_tab_saved_view_test.dart`, `desktop/test/super_tab_reading_client_test.dart`++- [ ] **Step 1: Commit the failing tests:** a saved view holds other chats' last rows, and opening again shows them at once on selecting; a chat the reader lost goes after the first read; a refused read clears all; another account's are never read; the limits hold, the selected chat is kept and older chats drop; a sent message shows before the server answers (holds what's there).+- [ ] **Step 2: Watch them fail,** then implement, run them and commit.++### Task 4: Timings and proof++- [ ] **Step 1: Measure** first open, project switch and send-to-shown, before and after, with the same held steps in a test, and post them in a PR comment. This Mac can't build the macOS app, so real numbers come from `first open` after the Desktop release.+- [ ] **Step 2: Run** the Swarm and WebSocket tests, mark the PR ready, and ask Reed and Orion.