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.

Batch O: sidebar reads each project once (#2077), idle-stop note never fails the Lead poll (#2079) (#2082)

0xken15410c40a25a9c
diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.ts
index 69bdcd9f4..3590f0ad9 100644
--- a/backend/integration/superTabTidy.test.ts
+++ b/backend/integration/superTabTidy.test.ts
@@ -205,6 +205,31 @@ describe('a worker left idle', () => {
}
})
+ it('is stopped, as a Reviewer whose newest group is asleep, with its line in the Lead conversation and the poll intact (review of #2073)', async () => {
+ const f = await swarm()
+ const review = String((await f.execute({ type: 'conversation.create', title: 'Review: Parser', brief: 'Review it', reviewOf: f.group,
+ checks: [{ description: 'Verdict', independent: false }] })).result.conversationId)
+ const reviewerHarness = randomUUID()
+ const reviewer = await f.add(review, 'test-host', reviewerHarness, 'Reviewer')
+ await f.started(reviewer, { role: 'reviewer' })
+ const verdict = String((await f.execute({ type: 'work.assign', conversationId: review, agentId: reviewer })).result.assignmentId)
+ await f.execute({ type: 'work.cancel', conversationId: review, assignmentId: verdict, reason: 'Verdict given' })
+ await f.delivered()
+ // Asleep but not archived, quiet for an hour, and read by the Lead's poll all the same: the review went on to another
+ // Reviewer whose attempt made progress 10 minutes ago. A post into it finds nothing.
+ const part = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: review } })
+ const quiet = new Date(f.clock.now - 60 * MINUTE)
+ f.clock.now += 20 * MINUTE
+ const data = part.data as Record<string, unknown>
+ await db.swarmGroup.update({ where: { id: part.id }, data: { dormant: true, lastActivityAt: quiet, data: { ...data, dormant: true,
+ lastActivityAt: quiet.toISOString(), assignment: { ...data.assignment as object, agentId: 'another-reviewer', progressAt: f.clock.now - 10 * MINUTE } } } })
+ await f.observe('test-host', [f.harness.worker, reviewerHarness], { harnessUncommitted: { [f.harness.worker]: false, [reviewerHarness]: false } })
+ await f.timed.deliveries(host, f.tab, f.lead)
+ expect((await f.timed.read(owner, f.tab)).state.agents.find(a => a.id === reviewer)!.workDecision).toBe('stop')
+ expect((await f.lines()).filter(m => (m.source as { agentId?: string }).agentId === reviewer))
+ .toEqual([expect.objectContaining({ conversationId: 'lead', text: 'Reviewer stopped: no work for 15 minutes.' })])
+ })
+
it('is kept once the owner turned tidying off', async () => {
const f = await swarm()
await f.execute({ type: 'tab.tidy', enabled: false })
diff --git a/backend/src/superTabs/tidy.test.ts b/backend/src/superTabs/tidy.test.ts
index 12ec831dd..0f44fd85d 100644
--- a/backend/src/superTabs/tidy.test.ts
+++ b/backend/src/superTabs/tidy.test.ts
@@ -116,6 +116,18 @@ describe('stopping idle workers', () => {
expect(stopIdleWorkers(finished, 'lead', at, new Set())).toHaveLength(1)
})
+ it('says so in a group the poll loaded, never in an asleep one, which would refuse the line (review of #2073)', () => {
+ const reviewer = () => worker({ role: 'reviewer' })
+ const asleep = group({ id: 'r2', reviewOf: 'g1', assignment: done({ id: 'a3' }), lastActivityAt: iso(START) })
+ const older = group({ id: 'r1', reviewOf: 'g1', assignment: done({ id: 'a2' }), lastActivityAt: iso(START - 5 * MINUTE) })
+ const finished = group({ agentIds: ['L', 'b'], assignment: done({ agentId: 'b' }) })
+ const loaded = swarm({ agents: [reviewer()], groups: [finished, older] })
+ expect(stopIdleWorkers(loaded, 'lead', at, new Set(), [asleep])).toEqual([expect.objectContaining({ conversationId: 'r1' })])
+ const alone = swarm({ agents: [reviewer()], groups: [finished] })
+ expect(stopIdleWorkers(alone, 'lead', at, new Set(), [asleep])).toEqual([expect.objectContaining({ conversationId: 'lead' })])
+ expect(target(alone).workDecision).toBe('stop')
+ })
+
it('does nothing once the owner turned tidying off, or for another project\'s workers', () => {
const off = swarm()
off.tidy = false
diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.ts
index 02f9876bf..589589f91 100644
--- a/backend/src/superTabs/tidy.ts
+++ b/backend/src/superTabs/tidy.ts
@@ -83,9 +83,9 @@ function reportedClean(state: SuperTabState, worker: Agent, now: number): boolea
* Marks for stopping every worker of the project idle for IDLE_STOP_MS: started by the Swarm (a person's own session is
* theirs to close), not a Lead, with no active task, no message waiting for it (`busy`), its host reporting nothing
* uncommitted, not waiting to resume after a usage limit, and, for a Reviewer, no re-check pending. Each gets one quiet
- * line, to nobody, in its most recent group. Run on its Lead's poll, which knows what is waiting. `asleep` are the groups
- * of its Reviewers that ordinary loads leave out: an archived review group still says whose re-check may come (review of
- * #1807).
+ * line, to nobody, in its most recent loaded group, else the Lead conversation. Run on its Lead's poll, which knows what
+ * is waiting. `asleep` are the groups of its Reviewers that ordinary loads leave out: an archived review group still says
+ * whose re-check may come (review of #1807).
*/
export function stopIdleWorkers(state: SuperTabState, projectId: string, now: number, busy: ReadonlySet<string>,
asleep: readonly GroupActivity[] = []): MessageDraft[] {
@@ -107,7 +107,8 @@ export function stopIdleWorkers(state: SuperTabState, projectId: string, now: nu
worker.idleStop = { previous: worker.workDecision ?? null }
worker.workDecision = 'stop'
worker.releaseId = stableId('idle-stop', worker.id, String(since))
- const last = groups.filter(g => !g.archived).sort((a, b) => (time(b.lastActivityAt) ?? 0) - (time(a.lastActivityAt) ?? 0))[0]
+ // Only a group the poll loaded takes the line: an asleep one refuses posts, and its refusal would fail the whole poll.
+ const last = groups.filter(g => !g.archived && state.conversations.some(c => c.id === g.id)).sort((a, b) => (time(b.lastActivityAt) ?? 0) - (time(a.lastActivityAt) ?? 0))[0]
rows.push({ id: stableId('idle-stop', worker.id, String(since), 'line'), conversationId: last?.id ?? project.leadConversationId, replyTo: null, recipients: [],
author: { kind: 'agent', id: lead.id, name: lead.name, displayName: agentDisplayName(state.agents, lead.id), membershipGeneration: lead.membershipGeneration },
text: `${worker.displayName ?? worker.name} stopped: no work for 15 minutes.`, source: { kind: 'idle-stop', agentId: worker.id } })
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 4946144d2..147ca6f89 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -1191,15 +1191,53 @@ class SuperTabController extends ChangeNotifier {
/// The signed-in person's private chat with [projectId]'s Product Manager:
/// that project's private conversation whose audience is them alone.
- SuperTabConversation? pmChat(String projectId) => snapshot?.conversations
- .where(
- (g) =>
- !g.isBuddyChat &&
- g.projectId == projectId &&
- g.audience?.length == 1 &&
- g.audience!.single == accountId,
- )
- .firstOrNull;
+ SuperTabConversation? pmChat(String projectId) =>
+ _indexed()?.pmChats[projectId];
+
+ /// [projectId]'s conversations, open and closed, in the snapshot's order.
+ List<SuperTabConversation> projectConversations(String projectId) =>
+ _indexed()?.byProject[projectId] ?? const [];
+
+ /// [snapshot]'s conversations by project, and each project's [pmChat],
+ /// worked out once per snapshot: the sidebar asks for them on every
+ /// rebuild, and a snapshot is replaced, never changed, when the Swarm moves.
+ ({
+ SuperTabSnapshot of,
+ Map<String, List<SuperTabConversation>> byProject,
+ Map<String, SuperTabConversation> pmChats,
+ })?
+ _index;
+
+ ({
+ SuperTabSnapshot of,
+ Map<String, List<SuperTabConversation>> byProject,
+ Map<String, SuperTabConversation> pmChats,
+ })?
+ _indexed() {
+ final snapshot = this.snapshot;
+ if (snapshot == null) return null;
+ if (_index case final index? when identical(index.of, snapshot)) {
+ return index;
+ }
+ final byProject = <String, List<SuperTabConversation>>{};
+ final pmChats = <String, SuperTabConversation>{};
+ for (final g in snapshot.conversations) {
+ byProject.putIfAbsent(g.projectId, () => []).add(g);
+ if (!g.isBuddyChat &&
+ g.audience?.length == 1 &&
+ g.audience!.single == accountId) {
+ pmChats.putIfAbsent(g.projectId, () => g);
+ }
+ }
+ return _index = (
+ of: snapshot,
+ byProject: {
+ for (final MapEntry(:key, :value) in byProject.entries)
+ key: List.unmodifiable(value),
+ },
+ pmChats: pmChats,
+ );
+ }
/// Whether the Swarm has Buddies on: each person's Buddy chats take Chat
/// with PM's place (spec: Buddies, 10-28).
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index 59fa6d9e6..ad353d2d0 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -24,9 +24,15 @@ import 'project_github.dart';
/// The Swarm's Product Managers' conversation, listed as a channel among the projects.
const kProductManagersChannel = 'product-managers';
-/// A project's Product Manager by name, as its Chat with PM is listed.
-String pmChatName(SuperTabSnapshot snapshot, SuperTabProject project) {
- final pmId = snapshot.conversation(project.leadConversationId)?.leadId;
+/// A project's Product Manager by name, as its Chat with PM is listed;
+/// [lead] is the project's Lead conversation when the caller holds it.
+String pmChatName(
+ SuperTabSnapshot snapshot,
+ SuperTabProject project, {
+ SuperTabConversation? lead,
+}) {
+ final pmId =
+ (lead ?? snapshot.conversation(project.leadConversationId))?.leadId;
return pmId == null
? 'Product Manager'
: snapshot.agentName(pmId, fallback: 'Product Manager');
@@ -163,27 +169,62 @@ class ProjectSidebar extends StatelessWidget {
/// right end shows or hides its conversations (Dee, 2026-10-28).
Widget _row(
SuperTabConversation group, {
- SuperTabProject? project,
+ _ProjectReading? reading,
String? label,
String? key,
}) {
+ final project = reading?.project;
final selected =
!devicesSelected &&
!notificationsSelected &&
controller.selectedId == group.id;
- final groups = project == null
- ? [group]
- : controller.snapshot!.conversations.where(
- (g) => g.projectId == project.id && !g.closed,
- );
- final waiting = groups.any((g) => needsHuman(g) > 0);
+ final waiting = reading == null
+ ? needsHuman(group) > 0
+ : reading.waiting.isNotEmpty;
// A project's PM chat shows its own count rather than the dot.
- final pmChat = project == null ? null : controller.pmChat(project.id);
- final projectPmUnread = pmChat == null ? 0 : controller.unreadCount(pmChat);
- final unread = groups.any(
- (g) =>
- controller.unread(g) && (projectPmUnread == 0 || g.id != pmChat?.id),
+ final pmChat = reading?.pmChat;
+ final projectPmUnread = reading?.pmUnread ?? 0;
+ final unread = reading == null
+ ? controller.unread(group)
+ : reading.unread.any((id) => projectPmUnread == 0 || id != pmChat?.id);
+ return _drawRow(
+ group,
+ project: project,
+ label: label,
+ key: key,
+ selected: selected,
+ waiting: waiting,
+ unread: unread,
+ pmChat: pmChat,
+ projectPmUnread: projectPmUnread,
+ selectedProjectId: reading?.sidebar.selectedProjectId,
);
+ }
+
+ /// A workgroup's row from what its project's reading already asked.
+ Widget _workgroupRow(SuperTabConversation group, _ProjectReading reading) =>
+ _drawRow(
+ group,
+ selected:
+ !devicesSelected &&
+ !notificationsSelected &&
+ controller.selectedId == group.id,
+ waiting: reading.waiting.contains(group.id),
+ unread: reading.unread.contains(group.id),
+ );
+
+ Widget _drawRow(
+ SuperTabConversation group, {
+ SuperTabProject? project,
+ String? label,
+ String? key,
+ required bool selected,
+ required bool waiting,
+ required bool unread,
+ SuperTabConversation? pmChat,
+ int projectPmUnread = 0,
+ String? selectedProjectId,
+ }) {
final expanded =
project != null && controller.expandedProjects.contains(project.id);
// A collapsed project shows as selected while one of its conversations it
@@ -194,7 +235,7 @@ class ProjectSidebar extends StatelessWidget {
!expanded &&
!devicesSelected &&
!notificationsSelected &&
- controller.selected?.projectId == project.id &&
+ selectedProjectId == project.id &&
controller.selectedId != pmChat?.id);
final style = DesktopChrome.control(
medium: unread || highlighted,
@@ -409,13 +450,14 @@ class ProjectSidebar extends StatelessWidget {
/// A project's "Closed (N)" row and, when it is open, the closed groups under it: archived ones and finished
/// ones that left the active set, as read for the project so far.
- List<Widget> _closed(SuperTabProject project) {
- final groups = controller.snapshot!.conversations
+ List<Widget> _closed(_ProjectReading reading) {
+ final project = reading.project;
+ final pmChat = reading.pmChat?.id;
+ final groups = reading.conversations
.where(
(g) =>
- g.projectId == project.id &&
g.id != project.leadConversationId &&
- g.id != controller.pmChat(project.id)?.id &&
+ g.id != pmChat &&
!g.isBuddyChat &&
!controller.hiddenByBuddies(g) &&
g.closed,
@@ -495,20 +537,24 @@ class ProjectSidebar extends StatelessWidget {
/// The signed-in person's private chat with each project's Product
/// Manager, as direct messages below the projects so a collapsed project
/// never hides them; the first click opens one.
- List<Widget> _pmChats(List<SuperTabProject> projects) => [
+ List<Widget> _pmChats(
+ List<SuperTabProject> projects,
+ _SidebarReading reading,
+ ) => [
for (final project in projects)
- ?_pmChat(project, named: projects.length > 1),
+ ?_pmChat(reading.of(project), named: projects.length > 1),
];
- Widget? _pmChat(SuperTabProject project, {required bool named}) {
+ Widget? _pmChat(_ProjectReading reading, {required bool named}) {
final snapshot = controller.snapshot!;
- final pmId = snapshot.conversation(project.leadConversationId)?.leadId;
- final chat = controller.pmChat(project.id);
+ final project = reading.project;
+ final lead = reading.lead;
+ final chat = reading.pmChat;
if (chat == null && !controller.canWrite) return null;
return SuperTabPmChatRow(
key: ValueKey('super-pm-chat-${project.id}'),
- agentId: pmId,
- name: pmChatName(snapshot, project),
+ agentId: lead?.leadId,
+ name: pmChatName(snapshot, project, lead: lead),
project: named ? project.name : null,
selected:
chat != null &&
@@ -516,7 +562,7 @@ class ProjectSidebar extends StatelessWidget {
!notificationsSelected &&
controller.selectedId == chat.id,
unread: chat != null && controller.unread(chat),
- unreadCount: chat == null ? 0 : controller.unreadCount(chat),
+ unreadCount: reading.pmUnread,
onTap: chat != null
? () => onSelect(chat.id)
: controller.saving || controller.hasPendingAction
@@ -575,12 +621,12 @@ class ProjectSidebar extends StatelessWidget {
/// A project's open conversations, newest first: the most recently created
/// has the highest number, and one without a number predates numbering.
- List<SuperTabConversation> _newestFirst(SuperTabProject project) {
- final pmChat = controller.pmChat(project.id)?.id;
- final groups = controller.snapshot!.conversations
+ List<SuperTabConversation> _newestFirst(_ProjectReading reading) {
+ final project = reading.project;
+ final pmChat = reading.pmChat?.id;
+ final groups = reading.conversations
.where(
(g) =>
- g.projectId == project.id &&
g.id != project.leadConversationId &&
g.id != pmChat &&
!g.isBuddyChat &&
@@ -639,8 +685,9 @@ class ProjectSidebar extends StatelessWidget {
),
);
- List<Widget> _workgroups(SuperTabProject project) {
- final groups = _newestFirst(project);
+ List<Widget> _workgroups(_ProjectReading reading) {
+ final project = reading.project;
+ final groups = _newestFirst(reading);
return groups.isEmpty
? [
Padding(
@@ -662,14 +709,18 @@ class ProjectSidebar extends StatelessWidget {
: [
_NewestConversations(
key: ValueKey('super-project-list-${project.id}'),
- rows: [for (final group in groups) (group.id, _row(group))],
+ rows: [
+ for (final group in groups)
+ (group.id, () => _workgroupRow(group, reading)),
+ ],
// Never behind "… N more": the open one, and those with
// something to read or answer.
kept: {
if (!devicesSelected && !notificationsSelected)
controller.selectedId,
for (final group in groups)
- if (controller.unread(group) || needsHuman(group) > 0)
+ if (reading.unread.contains(group.id) ||
+ reading.waiting.contains(group.id))
group.id,
},
more: (hidden, onTap) => _moreRow(project, hidden, onTap),
@@ -679,22 +730,25 @@ class ProjectSidebar extends StatelessWidget {
/// Every project with its workgroups, and the Product Managers'
/// conversation, which every person in the Swarm reads, by name from A to Z.
- List<(String, Widget)> _channels(SuperTabSnapshot? snapshot) => [
+ List<(String, Widget)> _channels(
+ SuperTabSnapshot? snapshot,
+ _SidebarReading reading,
+ ) => [
if (snapshot?.conversation(snapshot.leadsConversationId ?? '')
case final leads?)
(kProductManagersChannel, _row(leads, label: kProductManagersChannel)),
for (final project in snapshot?.projects ?? const <SuperTabProject>[])
- if (snapshot?.conversation(project.leadConversationId) case final lead?)
+ if (reading.of(project) case final read when read.lead != null)
(
project.name,
Column(
key: ValueKey('super-project-${project.id}'),
mainAxisSize: MainAxisSize.min,
children: [
- _row(lead, project: project),
+ _row(read.lead!, reading: read),
if (controller.expandedProjects.contains(project.id)) ...[
- ..._workgroups(project),
- ..._closed(project),
+ ..._workgroups(read),
+ ..._closed(read),
],
],
),
@@ -706,7 +760,8 @@ class ProjectSidebar extends StatelessWidget {
final snapshot = controller.snapshot;
final projects = snapshot?.projects ?? const <SuperTabProject>[];
final buddiesOn = controller.buddiesOn;
- final pmChats = buddiesOn ? const <Widget>[] : _pmChats(projects);
+ final reading = _SidebarReading(controller, needsHuman);
+ final pmChats = buddiesOn ? const <Widget>[] : _pmChats(projects, reading);
return Material(
color: DesktopChrome.surface,
child: ListView(
@@ -763,7 +818,7 @@ class ProjectSidebar extends StatelessWidget {
onToggleCollapsed: controller.toggleProjectsGroup,
),
if (controller.projectsGroupOpen)
- for (final (_, channel) in _channels(snapshot)) channel,
+ for (final (_, channel) in _channels(snapshot, reading)) channel,
const SizedBox(height: 16),
if (pmChats.isNotEmpty) ...[
SuperTabSectionHeading(
@@ -838,8 +893,9 @@ class _NewestConversations extends StatefulWidget {
static const shown = 8;
- /// Each conversation's id and row, newest first.
- final List<(String, Widget)> rows;
+ /// Each conversation's id and how its row is built, newest first: only the
+ /// rows shown are built.
+ final List<(String, Widget Function())> rows;
/// Listed even when older than the newest.
final Set<String> kept;
@@ -866,7 +922,7 @@ class _NewestConversationsState extends State<_NewestConversations> {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
- for (final (_, row) in visible) row,
+ for (final (_, row) in visible) row(),
if (visible.length < rows.length)
widget.more(
rows.length - visible.length,
@@ -876,3 +932,54 @@ class _NewestConversationsState extends State<_NewestConversations> {
);
}
}
+
+/// What one build of the sidebar reads, each piece once: per row, a Swarm's
+/// thousands of conversations were scanned again on every rebuild (Diego,
+/// 10-29).
+class _SidebarReading {
+ _SidebarReading(this.controller, this.needsHuman);
+ final SuperTabController controller;
+ final int Function(SuperTabConversation group) needsHuman;
+ final _projects = <String, _ProjectReading>{};
+
+ _ProjectReading of(SuperTabProject project) =>
+ _projects.putIfAbsent(project.id, () => _ProjectReading(this, project));
+
+ /// The project of the open conversation.
+ late final selectedProjectId = controller.selected?.projectId;
+}
+
+/// One build's reading of a project, each part asked once and only when a
+/// row needs it.
+class _ProjectReading {
+ _ProjectReading(this.sidebar, this.project);
+ final _SidebarReading sidebar;
+ final SuperTabProject project;
+
+ late final conversations = sidebar.controller.projectConversations(
+ project.id,
+ );
+ late final SuperTabConversation? lead =
+ conversations
+ .where((g) => g.id == project.leadConversationId)
+ .firstOrNull ??
+ sidebar.controller.snapshot?.conversation(project.leadConversationId);
+ late final pmChat = sidebar.controller.pmChat(project.id);
+ late final pmUnread = switch (pmChat) {
+ final chat? => sidebar.controller.unreadCount(chat),
+ null => 0,
+ };
+
+ /// The open conversations that need a human, and those with unread messages.
+ Set<String> get waiting => _open.waiting;
+ Set<String> get unread => _open.unread;
+ late final _open = () {
+ final waiting = <String>{}, unread = <String>{};
+ for (final g in conversations) {
+ if (g.closed) continue;
+ if (sidebar.needsHuman(g) > 0) waiting.add(g.id);
+ if (sidebar.controller.unread(g)) unread.add(g.id);
+ }
+ return (waiting: waiting, unread: unread);
+ }();
+}
diff --git a/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart b/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart
new file mode 100644
index 000000000..03681aa3b
--- /dev/null
+++ b/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart
@@ -0,0 +1,113 @@
+// Run explicitly: flutter test test/benchmarks/super_tab_sidebar_benchmark.dart --reporter expanded
+// Headless CPU measurements of one Swarm sidebar rebuild, not display latency.
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/project_sidebar.dart';
+
+import '../support/super_tab_fixture.dart';
+import 'swarm_benchmark.dart' show distribution;
+
+void main() {
+ for (final (projects, perProject) in [(5, 50), (20, 200)]) {
+ testWidgets(
+ 'Swarm sidebar rebuild with $projects projects x $perProject conversations',
+ (tester) async {
+ final server = ConversationServer();
+ final ids = ['lead', for (var p = 1; p < projects; p++) 'p$p'];
+ server.state['projects'] = [
+ for (final id in ids)
+ projectFixture(
+ id,
+ 'Project $id',
+ id == 'lead' ? 'lead' : 'lead-$id',
+ ),
+ ];
+ final conversations = server.state['conversations'] as List;
+ for (final id in ids) {
+ if (id != 'lead') {
+ conversations.add({
+ ...conversationFixture('lead-$id', 'Lead'),
+ 'projectId': id,
+ });
+ }
+ conversations.add({
+ ...conversationFixture('pm-$id', 'Chat with PM'),
+ 'projectId': id,
+ 'audience': {
+ 'people': [
+ {'id': 'owner'},
+ ],
+ },
+ });
+ for (var n = 1; n <= perProject; n++) {
+ conversations.add({
+ ...conversationFixture('g-$id-$n', 'Group $n'),
+ 'projectId': id,
+ 'number': n,
+ 'archived': n % 4 == 0,
+ });
+ }
+ }
+ final controller = server.controller(
+ initial: {
+ 'tabId': 'tab',
+ 'accountId': 'owner',
+ 'expandedProjects': ids,
+ },
+ );
+ await controller.refresh();
+
+ late StateSetter rebuild;
+ await tester.binding.setSurfaceSize(const Size(280, 1000));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: StatefulBuilder(
+ builder: (context, setState) {
+ rebuild = setState;
+ return ProjectSidebar(
+ controller: controller,
+ onSelect: controller.select,
+ onAddAgent: (_) {},
+ needsHuman: (_) => 0,
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+
+ Future<int> once() async {
+ final watch = Stopwatch()..start();
+ rebuild(() {});
+ await tester.pump();
+ return watch.elapsedMicroseconds;
+ }
+
+ for (var i = 0; i < 20; i++) {
+ await once();
+ }
+ final times = [for (var i = 0; i < 100; i++) await once()];
+ // ignore: avoid_print
+ print(
+ jsonEncode({
+ 'benchmark': 'super_tab_sidebar_rebuild',
+ 'projects': projects,
+ 'conversationsPerProject': perProject,
+ ...distribution(times),
+ }),
+ );
+
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+ }
+}
diff --git a/desktop/test/super_tab_sidebar_scale_test.dart b/desktop/test/super_tab_sidebar_scale_test.dart
new file mode 100644
index 000000000..ac22cb098
--- /dev/null
+++ b/desktop/test/super_tab_sidebar_scale_test.dart
@@ -0,0 +1,160 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/project_sidebar.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// Counts how often each project's Chat with PM is looked up.
+class _CountingController extends SuperTabController {
+ _CountingController(ConversationServer server, {required super.initial})
+ : super(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: server.request,
+ save: server.save,
+ pollInterval: Duration.zero,
+ );
+
+ final pmChatLookups = <String, int>{};
+
+ @override
+ SuperTabConversation? pmChat(String projectId) {
+ pmChatLookups.update(projectId, (n) => n + 1, ifAbsent: () => 1);
+ return super.pmChat(projectId);
+ }
+}
+
+const _projects = 20, _perProject = 200;
+
+/// [_projects] projects, each with its Lead, the reader's Chat with PM and
+/// [_perProject] workgroups, every fourth of them closed.
+List<String> _manyProjects(ConversationServer server) {
+ final ids = ['lead', for (var p = 1; p < _projects; p++) 'p$p'];
+ server.state['projects'] = [
+ for (final id in ids)
+ projectFixture(id, 'Project $id', id == 'lead' ? 'lead' : 'lead-$id'),
+ ];
+ final conversations = server.state['conversations'] as List;
+ for (final id in ids) {
+ if (id != 'lead') {
+ conversations.add({
+ ...conversationFixture('lead-$id', 'Lead'),
+ 'projectId': id,
+ });
+ }
+ conversations.add({
+ ...conversationFixture('pm-$id', 'Chat with PM'),
+ 'projectId': id,
+ 'audience': {
+ 'people': [
+ {'id': 'owner'},
+ ],
+ },
+ });
+ for (var n = 1; n <= _perProject; n++) {
+ conversations.add({
+ ...conversationFixture('g-$id-$n', 'Group $n'),
+ 'projectId': id,
+ 'number': n,
+ 'archived': n % 4 == 0,
+ });
+ }
+ }
+ return ids;
+}
+
+void main() {
+ test('a Chat with PM made after a read is found in the next one', () async {
+ final server = ConversationServer();
+ final controller = server.controller();
+ await controller.refresh();
+ expect(controller.pmChat('lead'), isNull);
+ expect(controller.projectConversations('lead').map((g) => g.id), [
+ 'lead',
+ 'offline',
+ ]);
+
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('pm-lead', 'Chat with PM'),
+ 'audience': {
+ 'people': [
+ {'id': 'owner'},
+ ],
+ },
+ });
+ server.revision++;
+ await controller.refresh();
+
+ expect(controller.pmChat('lead')?.id, 'pm-lead');
+ expect(controller.projectConversations('lead').map((g) => g.id), [
+ 'lead',
+ 'offline',
+ 'pm-lead',
+ ]);
+ await controller.flush();
+ controller.dispose();
+ });
+
+ testWidgets(
+ 'one sidebar build looks up each Chat with PM once and asks each open conversation once',
+ (tester) async {
+ final server = ConversationServer();
+ final ids = _manyProjects(server);
+ final controller = _CountingController(
+ server,
+ initial: {
+ 'tabId': 'tab',
+ 'accountId': 'owner',
+ 'expandedProjects': ids,
+ },
+ );
+ await controller.refresh();
+ expect(controller.snapshot!.conversations, hasLength(2 + 19 + 20 * 201));
+
+ final asked = <String, int>{};
+ late StateSetter rebuild;
+ await tester.binding.setSurfaceSize(const Size(280, 1000));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: StatefulBuilder(
+ builder: (context, setState) {
+ rebuild = setState;
+ return ProjectSidebar(
+ controller: controller,
+ onSelect: controller.select,
+ onAddAgent: (_) {},
+ needsHuman: (group) {
+ asked.update(group.id, (n) => n + 1, ifAbsent: () => 1);
+ return 0;
+ },
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+
+ controller.pmChatLookups.clear();
+ asked.clear();
+ rebuild(() {});
+ await tester.pump();
+
+ expect(controller.pmChatLookups.keys, unorderedEquals(ids));
+ expect(controller.pmChatLookups.values, everyElement(1));
+ // Each project's 150 open workgroups, its Lead and its Chat with PM.
+ expect(asked, hasLength(20 * 152 + 1));
+ expect(asked.values, everyElement(1));
+
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+}