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.

Desktop: a Swarm opens from what changed since, with its chat at once, and never says Sign in while signed in (#1803)

0xken15a2c69843cc29
diff --git a/desktop/lib/settings/sections/account_section.dart b/desktop/lib/settings/sections/account_section.dart
index 1fcbd7122..a021a0055 100644
--- a/desktop/lib/settings/sections/account_section.dart
+++ b/desktop/lib/settings/sections/account_section.dart
@@ -83,9 +83,12 @@ class AccountSection extends StatelessWidget {
? 'Your Harness sign-in in this browser.'
: 'Your Harness sign-in on this computer.',
child: SingleChildScrollView(
- // Only where Super Tabs are kept on this device (the web's) does
- // Account say so; Desktop keeps none and its page is as it was.
- child: notifier.superTabs.reading.drawsSaved
+ // Only the browser's reading, which draws a kept view at once, says
+ // it keeps Super Tabs; Desktop's, drawn once confirmed and another
+ // account's forgotten at sign-in, leaves its page as it was.
+ child:
+ notifier.superTabs.reading.drawsSaved &&
+ !notifier.superTabs.reading.confirmsSaved
? Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index f182f06b9..07e064f7e 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -98,6 +98,7 @@ import '../core/harness_file_store.dart';
import '../super_tabs/attachment_upload.dart';
import '../super_tabs/client.dart';
import '../super_tabs/controller.dart';
+import '../super_tabs/view_store.dart';
import '../super_tabs/notifications.dart' show superTabMentionNotice;
import '../measurement/setup_preference_store.dart';
import '../devices/device_hosts.dart';
@@ -1751,6 +1752,7 @@ class AppNotifier extends ChangeNotifier {
late final superTabs = SuperTabClient(
storage: localStore ?? HarnessFileStore.shared,
+ viewStorage: localStore ?? swarmViewStore(),
upload: uploadWith(() => api),
onMention: superTabMentionNotice(systemNotifications),
onTagCounts: notifyListeners,
diff --git a/desktop/lib/state/workspace_chrome.dart b/desktop/lib/state/workspace_chrome.dart
index fbdb853f8..427d2d35a 100644
--- a/desktop/lib/state/workspace_chrome.dart
+++ b/desktop/lib/state/workspace_chrome.dart
@@ -72,7 +72,7 @@ class WorkspaceChrome {
this.labelsPaneStatus = false,
this.compactPaneHeader = false,
this.superTabRecovers = false,
- this.superTabReading = const SuperTabReading(),
+ this.superTabReading = SuperTabReading.desktop,
this.subscriptionsNeedComputer = false,
});
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 245006548..9d0f29b0f 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -27,6 +27,7 @@ class SuperTabClient {
SuperTabClient({
required this.transport,
required this.storage,
+ LocalKeyValueStore? viewStorage,
this.onSnapshot,
this.onTabs,
this.onSelection,
@@ -34,9 +35,13 @@ class SuperTabClient {
this.onTagCounts,
this.upload = refuseUpload,
this.discoveryInterval = const Duration(seconds: 15),
- });
+ }) : viewStorage = viewStorage ?? storage;
final SuperTabTransport transport;
final LocalKeyValueStore storage;
+
+ /// Where each Swarm's saved view is kept ([SuperTabSavedViews]): a few
+ /// hundred KB each, so Desktop keeps them out of [storage]'s small file.
+ final LocalKeyValueStore viewStorage;
final void Function(SuperTabController)? onSnapshot;
final void Function(List<SuperTabListing>, Set<String> hidden)? onTabs;
@@ -106,7 +111,7 @@ class SuperTabClient {
bool _isAway(String id) => !_pageVisible || id != _shown;
- late final _views = SuperTabSavedViews(storage);
+ late final _views = SuperTabSavedViews(viewStorage);
final _viewSaves = <String, Timer>{};
final _viewSavedAt = <String, DateTime>{};
final _viewVersions = <String, int>{};
@@ -487,10 +492,7 @@ class SuperTabClient {
..onArrived = onMention;
_tagCounts.remove(id);
_loaded[id] = controller;
- controller.start();
- // After the first read is asked for: reading and drawing a saved view
- // takes the main thread a moment a phone's first read need not wait on.
- if (_reading.drawsSaved) {
+ Future<void> drawSaved() async {
// Behind the lock shared with this browser's other tabs: one iOS has
// suspended may hold it. Past a short wait, open with no saved view.
final view = await _views
@@ -500,6 +502,14 @@ class SuperTabClient {
controller.drawSaved(view);
}
}
+
+ // Desktop's saved view is a local file, read before the first read so
+ // that read asks only for what changed since it.
+ if (_reading.drawsSaved && _reading.confirmsSaved) await drawSaved();
+ controller.start();
+ // After the first read is asked for: reading and drawing a saved view
+ // takes the main thread a moment a phone's first read need not wait on.
+ if (_reading.drawsSaved && !_reading.confirmsSaved) await drawSaved();
return controller;
}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 9467d952c..709111bce 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -515,7 +515,8 @@ class SuperTabController extends ChangeNotifier {
/// Draws a [savedView] kept from an earlier visit while the first read is
/// on its way, and holds its parts: the first read asks only for what
- /// changed since, and replaces it. One for another Swarm, one too old for
+ /// changed since, and replaces it. With [SuperTabReading.confirmsSaved] it
+ /// only holds them, for that read to draw. One for another Swarm, one too old for
/// its cursor, one that no longer parses, or one after a read has landed,
/// draws nothing.
void drawSaved(Map<String, dynamic> view) {
@@ -536,6 +537,14 @@ class SuperTabController extends ChangeNotifier {
];
final messages = rows.map(SuperTabMessage.fromJson).toList();
final changedAt = (view['lastChangedAt'] as num).toInt();
+ if (_policy.confirmsSaved) {
+ // Held for the first read to start from, drawn once it answers; the
+ // conversation it showed is read beside it.
+ _parts = parts;
+ _partsReadAt = savedAt;
+ if (id == selectedId) _savedSelection = true;
+ return;
+ }
snapshot = saved;
lastChangedAt = changedAt;
_parts = parts;
@@ -897,8 +906,10 @@ class SuperTabController extends ChangeNotifier {
..ignore())
: null;
try {
+ final heldSaved = _parts != null && stateReads == 0;
final read = await _readParts();
if (_disposed || accessRevoked) return;
+ final stateMs = took.elapsedMilliseconds;
final parts = _parts!;
_refreshFailing = false;
unreachableSince = null;
@@ -915,7 +926,7 @@ class SuperTabController extends ChangeNotifier {
// A part or a value worked out at read time (an agent seen down, a
// limit that ran out) changed: the snapshot is built again. The first
// read over a saved view wins, whatever it saved.
- final moved = read.changed || _showingSaved;
+ final moved = read.changed || _showingSaved || snapshot == null;
if (moved) {
// A closed group named by the saved selection is read by id: a first
// load has only the active groups.
@@ -979,6 +990,9 @@ class SuperTabController extends ChangeNotifier {
}
}
}
+ // A first open draws its sidebar now, not once its chat answers.
+ if (stateReads == 1) _changed();
+ final sidebarMs = took.elapsedMilliseconds;
lastChangedAt = parts.lastChangedAt;
// Every state read, a quiet one too: a count a failed read left open is
// finished; one that is known reads nothing.
@@ -993,6 +1007,15 @@ class SuperTabController extends ChangeNotifier {
? (query: earlyQuery!, page: early)
: null,
));
+ if (stateReads == 1) {
+ // Where a first open's time went, from the tab asking to the chat it shows.
+ appLog.debug(
+ 'swarm',
+ 'first open: sidebar after $sidebarMs ms, chat after ${took.elapsedMilliseconds} ms '
+ '(state read $stateMs ms, ${read.full ? 'first load' : 'changes since the saved view'}'
+ '${heldSaved ? '' : ', no saved view'})',
+ );
+ }
if (_showingSaved) {
// Read now: the saved view, and its Updating line, give way.
_showingSaved = false;
diff --git a/desktop/lib/super_tabs/reading.dart b/desktop/lib/super_tabs/reading.dart
index b3dbfd1b7..83234ee0a 100644
--- a/desktop/lib/super_tabs/reading.dart
+++ b/desktop/lib/super_tabs/reading.dart
@@ -1,8 +1,9 @@
-/// How a Swarm tab keeps itself current. The defaults are Desktop's: a full
-/// read every poll, whether or not the tab is on screen, the first read's
-/// failure shown at once, and the messages read after the state. The web
-/// build turns on the rest (`lib/web/shell/web_chrome.dart`), because a phone
-/// pays for every read in data, battery and main-thread time (#180's report).
+/// How a Swarm tab keeps itself current. The defaults: a full read every poll,
+/// whether or not the tab is on screen, the first read's failure shown at
+/// once, and the messages read after the state. Desktop reads with [desktop];
+/// the web build turns on the rest (`lib/web/shell/web_chrome.dart`), because
+/// a phone pays for every read in data, battery and main-thread time (#180's
+/// report).
class SuperTabReading {
const SuperTabReading({
this.quietPoll,
@@ -12,8 +13,18 @@ class SuperTabReading {
this.connectGrace = Duration.zero,
this.messagesWithState = false,
this.drawsSaved = false,
+ this.confirmsSaved = false,
});
+ /// Desktop's: a first open asks for the state and the open conversation at
+ /// once, and a Swarm seen before asks only for what changed since, drawing
+ /// nothing kept until that read has said what the reader may still see.
+ static const desktop = SuperTabReading(
+ messagesWithState: true,
+ drawsSaved: true,
+ confirmsSaved: true,
+ );
+
/// Null keeps a full read every poll. Otherwise, once the open conversation
/// has had no new message and the person has done nothing for [quietAfter],
/// the full read comes this often; the polls between only ask the open
@@ -43,6 +54,11 @@ class SuperTabReading {
/// (`SuperTabSavedViews`).
final bool drawsSaved;
+ /// With [drawsSaved], true holds a saved view's parts for the first read
+ /// to start from but draws them only once that read has answered, so a
+ /// conversation the reader lost since is never on screen.
+ final bool confirmsSaved;
+
/// Whether the poll adapts at all; false is Desktop's fixed period.
bool get adapts => quietPoll != null || pausesAway;
}
diff --git a/desktop/lib/super_tabs/view_store.dart b/desktop/lib/super_tabs/view_store.dart
new file mode 100644
index 000000000..e616a285d
--- /dev/null
+++ b/desktop/lib/super_tabs/view_store.dart
@@ -0,0 +1,2 @@
+export 'view_store_native.dart'
+ if (dart.library.js_interop) 'view_store_web.dart';
diff --git a/desktop/lib/super_tabs/view_store_native.dart b/desktop/lib/super_tabs/view_store_native.dart
new file mode 100644
index 000000000..aa2332904
--- /dev/null
+++ b/desktop/lib/super_tabs/view_store_native.dart
@@ -0,0 +1,12 @@
+import 'dart:io';
+
+import '../core/harness_file_store.dart';
+import '../core/local_key_value_store.dart';
+
+/// Where Desktop keeps each Swarm's saved view: a file of its own beside the
+/// app's `state.json`, which stays small because every setting rewrites it.
+LocalKeyValueStore swarmViewStore() => HarnessFileStore(
+ directory: Directory(
+ '${HarnessFileStore.defaultDirectoryPath()}${Platform.pathSeparator}swarm-views',
+ ),
+);
diff --git a/desktop/lib/super_tabs/view_store_web.dart b/desktop/lib/super_tabs/view_store_web.dart
new file mode 100644
index 000000000..efe145fb8
--- /dev/null
+++ b/desktop/lib/super_tabs/view_store_web.dart
@@ -0,0 +1,5 @@
+import '../core/harness_file_store.dart';
+import '../core/local_key_value_store.dart';
+
+/// A browser keeps saved views in its own storage, as it always has.
+LocalKeyValueStore swarmViewStore() => HarnessFileStore.shared;
diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dart
index 0fc28bf27..333d18f5f 100644
--- a/desktop/lib/super_tabs/workspace.dart
+++ b/desktop/lib/super_tabs/workspace.dart
@@ -433,6 +433,19 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
_terminalRequest = null;
return canvas;
}
+ Widget waiting(Object? error) => Stack(
+ children: [
+ Offstage(child: canvas),
+ Center(
+ child: error != null
+ ? Text(error.toString())
+ : const CircularProgressIndicator(),
+ ),
+ ],
+ );
+ // A restored Swarm draws before the signed-in account's profile answers:
+ // it waits for the account rather than opening as nobody's.
+ if (app.currentUser == null) return waiting(null);
return FutureBuilder<SuperTabController>(
future: app.superTabs.open(id),
builder: (context, state) {
@@ -440,16 +453,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
if (controller == null ||
controller.tabId != id ||
controller.accountId != app.currentUser?.id) {
- return Stack(
- children: [
- Offstage(child: canvas),
- Center(
- child: state.hasError
- ? Text(state.error.toString())
- : const CircularProgressIndicator(),
- ),
- ],
- );
+ return waiting(state.hasError ? state.error : null);
}
return ListenableBuilder(
listenable: controller,
diff --git a/desktop/test/super_tab_machine_freshness_test.dart b/desktop/test/super_tab_machine_freshness_test.dart
index 198c77525..06214f4a8 100644
--- a/desktop/test/super_tab_machine_freshness_test.dart
+++ b/desktop/test/super_tab_machine_freshness_test.dart
@@ -818,26 +818,34 @@ void main() {
addTearDown(() => appLog = previous);
});
- test(
- 'records how long a read took, its kind and last change, nothing it said',
- () async {
- final server = ConversationServer();
- server.state['name'] = 'PRIVATE_SWARM_NAME';
- final c = server.controller();
- await c.refresh();
- final read = log.lines.where((l) => l.startsWith('debug swarm')).single;
- expect(
- read,
- matches(
- RegExp(
- r'^debug swarm state read in \d+ ms '
- r'\((first load|changes), last changed \d+\)$',
- ),
+ test('records how long a read took, its kind and last change, nothing it said', () async {
+ final server = ConversationServer();
+ server.state['name'] = 'PRIVATE_SWARM_NAME';
+ final c = server.controller();
+ await c.refresh();
+ final lines = log.lines.where((l) => l.startsWith('debug swarm'));
+ expect(lines, hasLength(2));
+ expect(
+ lines.first,
+ matches(
+ RegExp(
+ r'^debug swarm state read in \d+ ms '
+ r'\((first load|changes), last changed \d+\)$',
),
- );
- expect(log.lines.join('\n'), isNot(contains('PRIVATE')));
- },
- );
+ ),
+ );
+ // A first open also says where its time went.
+ expect(
+ lines.last,
+ matches(
+ RegExp(
+ r'^debug swarm first open: sidebar after \d+ ms, chat after \d+ ms '
+ r'\(state read \d+ ms, first load, no saved view\)$',
+ ),
+ ),
+ );
+ expect(log.lines.join('\n'), isNot(contains('PRIVATE')));
+ });
test('records a failure with how long it took and what kind, not what was said', () async {
final server = ConversationServer();
diff --git a/desktop/test/super_tab_saved_view_test.dart b/desktop/test/super_tab_saved_view_test.dart
index bd15025cf..07018e51e 100644
--- a/desktop/test/super_tab_saved_view_test.dart
+++ b/desktop/test/super_tab_saved_view_test.dart
@@ -47,6 +47,7 @@ void main() {
group('review of #1723', _reviewTests);
group('re-review of #1727', _reReviewTests);
group('Clear now', _clearTests);
+ group('Desktop', _desktopTests);
test('keeps what the Swarm draws, not what it never shows', () async {
final store = MemoryStore();
@@ -156,12 +157,16 @@ class _Reads {
final ConversationServer server;
final paths = <String>[];
bool missing = false;
+ Completer<void>? holdMessages;
Future<Map<String, dynamic>> call(
String method,
String path, {
Map<String, dynamic>? body,
- }) {
+ }) async {
if (method == 'GET') paths.add(path);
+ if (holdMessages case final hold? when path.endsWith('/messages')) {
+ await hold.future;
+ }
if (missing) {
return Future.error(
const SuperTabFailure(
@@ -1005,3 +1010,126 @@ void _clearTests() {
});
});
}
+
+void _desktopTests() {
+ test('a saved view is drawn only once the first read says what the '
+ 'reader may still see', () {
+ final server = ConversationServer()..append('Hello');
+ final view = _saved(server);
+ fakeAsync((async) {
+ // Since the save, the reader lost one of its groups.
+ (server.state['conversations'] as List).removeWhere(
+ (g) => g['id'] == 'offline',
+ );
+ server.holdReads = Completer<void>();
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: SuperTabReading.desktop)
+ ..drawSaved(view);
+ expect(c.snapshot, isNull);
+ c.start();
+ async.flushMicrotasks();
+ expect(c.snapshot, isNull);
+ expect(c.showingSaved, isFalse);
+ // Only what changed since the save, beside the open conversation.
+ expect(reads.paths, [
+ '/api/super-tabs/tab/conversations/lead/messages',
+ startsWith('/api/super-tabs/tab/changes?cursor='),
+ ]);
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.flushMicrotasks();
+ expect(c.snapshot!.name, 'Pilot');
+ expect(c.snapshot!.conversation('offline'), isNull);
+ expect(c.messages('lead').single.text, 'Hello');
+ c.dispose();
+ });
+ });
+
+ test('a Swarm opened again reads what changed since, with its chat beside '
+ 'it, and draws once that answers', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = MemoryStore();
+ final first =
+ _client(_Transport(server), store, reading: SuperTabReading.desktop)
+ ..bind('owner')
+ ..show('tab');
+ first.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ first.show(null);
+ async.flushMicrotasks();
+ first.dispose();
+ // The app started again on this computer.
+ final transport = _Transport(server)..hold = Completer<void>();
+ final paths = <String>[];
+ final second = SuperTabClient(
+ transport: (method, path, {body}) {
+ paths.add(path);
+ return transport.call(method, path, body: body);
+ },
+ storage: store,
+ discoveryInterval: Duration.zero,
+ )..reading = SuperTabReading.desktop;
+ second
+ ..bind('owner')
+ ..show('tab');
+ SuperTabController? c;
+ second.open('tab').then((opened) => c = opened);
+ async.flushMicrotasks();
+ expect(c!.snapshot, isNull);
+ expect(paths.where((p) => p.contains('/api/super-tabs/tab/')), [
+ '/api/super-tabs/tab/conversations/lead/messages',
+ startsWith('/api/super-tabs/tab/changes?cursor='),
+ ]);
+ transport.hold!.complete();
+ transport.hold = null;
+ async.flushMicrotasks();
+ expect(c!.snapshot!.name, 'Pilot');
+ expect(c!.messages('lead').single.text, 'Hello');
+ second.dispose();
+ });
+ });
+
+ test('a first open shows its sidebar before its chat answers', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server)..holdMessages = Completer<void>();
+ final c = _controller(reads, reading: SuperTabReading.desktop);
+ String? drawn;
+ c.addListener(() => drawn ??= c.snapshot?.name);
+ c.start();
+ async.flushMicrotasks();
+ expect(drawn, 'Pilot');
+ reads.holdMessages!.complete();
+ async.flushMicrotasks();
+ expect(c.messages('lead').single.text, 'Hello');
+ c.dispose();
+ });
+ });
+
+ test('saved views go to their own store, apart from the app\'s state', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = MemoryStore(), views = MemoryStore();
+ final client = SuperTabClient(
+ transport: _Transport(server).call,
+ storage: store,
+ viewStorage: views,
+ discoveryInterval: Duration.zero,
+ )..reading = SuperTabReading.desktop;
+ client
+ ..bind('owner')
+ ..show('tab');
+ client.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ client.show(null);
+ async.flushMicrotasks();
+ expect(views.values[_viewKey], isNotNull);
+ expect(
+ store.values.keys.where((k) => k.contains('super_tab.view')),
+ isEmpty,
+ );
+ client.dispose();
+ });
+ });
+}
diff --git a/desktop/test/super_tab_workspace_test.dart b/desktop/test/super_tab_workspace_test.dart
index 8bac67e4e..fe40d7b01 100644
--- a/desktop/test/super_tab_workspace_test.dart
+++ b/desktop/test/super_tab_workspace_test.dart
@@ -10,6 +10,53 @@ import 'package:harness/ws/local_cli_discovery.dart';
import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
void main() {
+ testWidgets(
+ 'a signed-in person never sees Sign in while their account is still read',
+ (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ // A restored Swarm tab draws before the account's profile has answered.
+ final profile = f.app.currentUser;
+ f.app.currentUser = null;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: f.app,
+ builder: (_, _) => SuperTabWorkspace(
+ app: f.app,
+ canvas: PaneGrid(notifier: f.app, swarmMode: true),
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 50));
+ expect(find.textContaining('Sign in'), findsNothing);
+ expect(find.byType(CircularProgressIndicator), findsOneWidget);
+
+ f.app.currentUser = profile;
+ // The account is known: the Swarm opens and reads as it always has.
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ for (
+ var i = 0;
+ i < 40 && find.byType(SuperTabView).evaluate().isEmpty;
+ i++
+ ) {
+ await tester.pump(const Duration(milliseconds: 50));
+ expect(find.textContaining('Sign in'), findsNothing);
+ }
+ expect(find.byType(SuperTabView), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+
testWidgets(
'a stopped native stream keeps its Resume action after a chat round trip',
(tester) async {