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.

fix(swarm): the decisions list stops reloading the whole Swarm on every change (#1820)

0xken1519e2be0451ef
diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.ts
index 448d3d1ff..6523d7e76 100644
--- a/backend/integration/superTabRead.test.ts
+++ b/backend/integration/superTabRead.test.ts
@@ -686,6 +686,52 @@ describe('decisions asked of one person (v2)', () => {
expect((await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data.derived.decisionsWaiting).toBe(0)
})
+ it('reads only the conversations its decisions are in: a quiet one the reader still reads, not one they left, and no other quiet history', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const ask = async (conversationId: string, text: string) => (await post(s.tabId, { type: 'decision.ask', conversationId, personId: peer.sub,
+ questions: [question(text)] }, owner, s.lead)).body.data.result.decisionIds as string[]
+ const [kept] = await ask(s.web, 'Ship how?')
+ await ask(s.privateId, 'Keep it?')
+ // Both go quiet; the peer then leaves the private one.
+ await writeGroup(s.tabId, s.web, Date.now(), group => { group.archived = true; group.dormant = true })
+ await writeGroup(s.tabId, s.privateId, Date.now(), group => { group.dormant = true; group.audience = { people: [] } })
+ const read: string[] = []
+ const counted = new SuperTabStore(db.$extends({ query: { swarmGroup: { async findMany({ args, query }) {
+ const rows = await query(args)
+ read.push(...rows.map(row => row.key))
+ return rows
+ } } } }) as unknown as PrismaClient)
+ expect((await counted.decisions(peer, s.tabId, 'open')).decisions.map(d => d.id)).toEqual([kept])
+ // The finished work stays quiet and holds no decision: the list does not read it, as it would by loading every conversation.
+ expect(read).not.toContain(s.done)
+ })
+
+ it('marks which decisions wait, so an answer elsewhere and a new question read again though the count stays', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const ask = async (conversationId: string, text: string) => ((await post(s.tabId, { type: 'decision.ask', conversationId, personId: peer.sub,
+ questions: [question(text)] }, owner, s.lead)).body.data.result.decisionIds as string[])[0]!
+ const derived = async () => (await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data.derived
+ const first = await ask(s.web, 'Ship how?')
+ const before = await derived()
+ expect(before).toMatchObject({ decisionsWaiting: 1, decisionsDigest: expect.any(String) })
+ expect((await derived()).decisionsDigest).toBe(before.decisionsDigest)
+ expect(before.decisionsDigest).not.toContain(first)
+ // Answered on another device, and another question asked: still one waiting, another one.
+ expect((await post(s.tabId, { type: 'decision.answer', decisionId: first, choice: 0 }, peer)).status).toBe(200)
+ await ask(s.privateId, 'Keep it?')
+ const replaced = await derived()
+ expect(replaced.decisionsWaiting).toBe(1)
+ expect(replaced.decisionsDigest).not.toBe(before.decisionsDigest)
+ // The reader leaving the conversation moves it; with none left it is the same as for anyone with none.
+ await writeGroup(s.tabId, s.privateId, Date.now(), group => { group.audience = { people: [] } })
+ const left = await derived()
+ expect(left).toMatchObject({ decisionsWaiting: 0 })
+ expect(left.decisionsDigest).not.toBe(replaced.decisionsDigest)
+ expect((await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data.derived.decisionsDigest).toBe(left.decisionsDigest)
+ })
+
it('keeps one answer when two arrive at once, returns the same receipt for a retried answer, and refuses a person removed from the Swarm', async () => {
const s = await scene()
clock = Date.now()
diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.ts
index 93936c223..e7cfb0db6 100644
--- a/backend/src/superTabs/decisions.ts
+++ b/backend/src/superTabs/decisions.ts
@@ -3,6 +3,7 @@
* with one tap, and the answer reaches the asking agent and the Lead in the conversation it came from. Decisions live in
* SuperTabDecision, never in the tab state, as mentions do. A decision is not a private channel: anything private goes
* through Chat with PM. Called inside SuperTabStore's transactions. */
+import { createHash } from 'node:crypto'
import type { Prisma } from '@prisma/client'
import { z } from 'zod'
import { AGENT_ONLY, fail, isLeads, person, stableId, type Actor, type Conversation, type SuperTabState } from './model.js'
@@ -148,8 +149,12 @@ export async function waitingInProject(tx: Tx, tabId: string, projectId: string)
return groups.map(g => ({ conversationId: g.conversationId, personId: g.personId, count: g._count._all }))
}
-export async function decisionsWaiting(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>): Promise<number> {
- return (await readable(tx, tabId, state, actor, true)).length
+/** A person's open decisions: how many, and a digest of which. A client reads its list again when the digest moves, as
+ * when one is answered elsewhere and another asked, which leaves the count alone (review of #1820). Never what they ask. */
+export async function decisionsWaiting(tx: Tx, tabId: string, state: SuperTabState,
+ actor: Extract<Actor, { kind: 'person' }>): Promise<{ count: number; digest: string }> {
+ const ids = (await readable(tx, tabId, state, actor, true)).map(({ row }) => row.id).sort()
+ return { count: ids.length, digest: createHash('sha256').update(ids.join('\n')).digest('base64url').slice(0, 16) }
}
export async function listDecisions(tx: Tx, tabId: string, state: SuperTabState, actor: Actor, open: boolean) {
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index dab895c05..50aa6a65a 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -62,6 +62,8 @@ export interface Derived {
mentionsWaiting?: number
/** A person only: decisions asked of them, still open. */
decisionsWaiting?: number
+ /** A person only: a digest of which decisions are open, moving when they change though the count may not. */
+ decisionsDigest?: string
}
export interface OtherProjectWorkView {
conversationId: string; projectName: string; title: string; owns: string[]; status: WorkStatus; agentName: string; pr: string | null
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index 54169bb68..516132497 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -147,6 +147,7 @@ export class SwarmReads {
parts.lastChangedAt(tx, [tabId]),
])
return { parts: loaded, actor, lastChangedAt: newest.get(tabId) ?? null,
- view: readerView(loaded, actor, t0, { teamMachines, ...(counts ? { mentionsWaiting: counts[0], decisionsWaiting: counts[1] } : {}) }) }
+ view: readerView(loaded, actor, t0, { teamMachines,
+ ...(counts ? { mentionsWaiting: counts[0], decisionsWaiting: counts[1].count, decisionsDigest: counts[1].digest } : {}) }) }
}
}
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index cc598e476..5e8f8477b 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -32,6 +32,8 @@ export interface ReadExtras {
mentionsWaiting?: number
/** A person's open decisions (decisions.ts). */
decisionsWaiting?: number
+ /** Which ones they are, as a digest (decisions.ts). */
+ decisionsDigest?: string
}
const HEAD_FIELDS = ['version', 'id', 'name', 'project', 'projects', 'leadsConversationId', 'ownerId', 'environment',
@@ -101,5 +103,6 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:
...(visible.otherProjectsWork ? { otherProjectsWork: visible.otherProjectsWork } : {}),
...(actor.kind === 'person' && extras.mentionsWaiting !== undefined ? { mentionsWaiting: extras.mentionsWaiting } : {}),
...(actor.kind === 'person' && extras.decisionsWaiting !== undefined ? { decisionsWaiting: extras.decisionsWaiting } : {}),
+ ...(actor.kind === 'person' && extras.decisionsDigest !== undefined ? { decisionsDigest: extras.decisionsDigest } : {}),
}
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index ef5a339be..c0dd7b9a1 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1336,10 +1336,11 @@ export class SuperTabStore {
}
/** The caller's decisions in this Swarm, newest first: a person's asked of them, an agent's asked by it (a Lead's also
- * those asked in its project), still open or answered. */
+ * those asked in its project), still open or answered. A light load: the quiet conversations its decisions are in are
+ * read with them (decisions.ts conversationsOf), never the Swarm's whole history, read again on every change. */
async decisions(user: AuthUser, tabId: string, state: 'open' | 'answered', asAgentId?: string) {
return transaction(this.db, async tx => {
- const { state: tab } = await this.load(tx, user, tabId, { allGroups: true })
+ const { state: tab } = await this.load(tx, user, tabId)
const actor = await this.actor(tx, user, tab, asAgentId)
author(tab, actor)
return { decisions: await listDecisions(tx, tabId, tab, actor, state === 'open') }
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 38d2c2f28..21c806dc9 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -139,6 +139,10 @@ class SuperTabController extends ChangeNotifier {
/// The Swarm's parts as last read: what the next read asks changes for, and what [snapshot] is built from.
SuperTabParts? _parts;
+
+ /// The visibility epoch of the last read: it moves when who may read what changes (backend parts/commit.ts
+ /// `visibilityChanged`). Null before a read.
+ int? get visibilityEpoch => _parts?.epoch;
String? error, operationError, operationErrorCode;
/// One line for the sender after a command succeeds, from the backend: that a
diff --git a/desktop/lib/super_tabs/decisions.dart b/desktop/lib/super_tabs/decisions.dart
index 739edd10a..2a486c33c 100644
--- a/desktop/lib/super_tabs/decisions.dart
+++ b/desktop/lib/super_tabs/decisions.dart
@@ -37,8 +37,11 @@ class SuperTabDecision {
}
/// The reader's decisions in one Swarm: open and answered, read from the
-/// backend whenever the open count moves or the Swarm changes while one is
-/// open. One per controller, as the reader's tags are (notifications.dart).
+/// backend when the open ones change (their digest, or the count from a
+/// backend before it), when who may read what changes, and when the reader
+/// answers one. Not on every Swarm change: machine readings and messages change
+/// it every few seconds, and each read costs the backend a load. One per
+/// controller, as the reader's tags are (notifications.dart).
class SuperTabDecisions extends ChangeNotifier {
SuperTabDecisions._(this.controller) {
controller.addListener(_changed);
@@ -56,7 +59,10 @@ class SuperTabDecisions extends ChangeNotifier {
/// Decisions being answered: their buttons wait for the backend.
final Set<String> answering = {};
int? _count;
- int _lastChangedAt = -1;
+ String? _digest;
+ int? _epoch;
+ // The Swarm change a failed read saw: the next one tries again.
+ int? _failedAt;
Future<void>? _loading;
bool _dirty = false;
@@ -72,13 +78,22 @@ class SuperTabDecisions extends ChangeNotifier {
void _changed() {
final snapshot = controller.snapshot;
if (snapshot == null) return;
- final count = snapshot.decisionsWaiting;
- final moved = count != _count;
- if (!moved && controller.lastChangedAt == _lastChangedAt) return;
- _lastChangedAt = controller.lastChangedAt;
- _count = count;
- // Nothing open and nothing just answered: an idle Swarm reads nothing.
- if (count == 0 && !moved) return;
+ final epoch = controller.visibilityEpoch;
+ if (epoch != null && epoch != _epoch) {
+ // Who may read what changed: nothing read before shows until read again
+ // (review of #1820), even while the count stays.
+ if (_epoch != null && (open.isNotEmpty || answered.isNotEmpty)) {
+ open = answered = const [];
+ notifyListeners();
+ }
+ _epoch = epoch;
+ } else if (snapshot.decisionsWaiting == _count &&
+ snapshot.decisionsDigest == _digest &&
+ (_failedAt == null || _failedAt == controller.lastChangedAt)) {
+ return;
+ }
+ _count = snapshot.decisionsWaiting;
+ _digest = snapshot.decisionsDigest;
unawaited(load());
}
@@ -112,16 +127,22 @@ class SuperTabDecisions extends ChangeNotifier {
}
Future<void> _read() async {
+ final epoch = _epoch;
try {
final [nextOpen, nextAnswered] = await Future.wait([
_list('open'),
_list('answered'),
]);
+ // Read before who may read what changed: the read asked again since
+ // replaces it.
+ if (epoch != _epoch) return;
open = nextOpen;
answered = nextAnswered;
error = null;
+ _failedAt = null;
} catch (_) {
error = 'Could not load decisions. Try again.';
+ _failedAt = controller.lastChangedAt;
}
notifyListeners();
}
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 2bf399c03..b98081e29 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -230,7 +230,8 @@ class SuperTabSnapshot {
}),
localModels = SuperTabLocalModels.read(row['localModels']),
mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0,
- decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0 {
+ decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,
+ decisionsDigest = row['decisionsDigest'] as String? {
if (row['version'] != 1) {
throw const FormatException('Update Harness to open this Swarm.');
}
@@ -279,6 +280,10 @@ class SuperTabSnapshot {
/// Decisions asked of the reader and not yet answered, Swarm-wide; 0 from a
/// backend before decisions (backend superTabs/decisions.ts).
final int decisionsWaiting;
+
+ /// Which decisions wait, as a digest that moves when they change though the
+ /// count may not; null from a backend before it (superTabs/decisions.ts).
+ final String? decisionsDigest;
SuperTabConversation? conversation(String id) =>
conversations.where((c) => c.id == id).firstOrNull;
SuperTabAgent? agent(String id) =>
diff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dart
index f788de9dd..ad42a8499 100644
--- a/desktop/lib/super_tabs/parts.dart
+++ b/desktop/lib/super_tabs/parts.dart
@@ -262,6 +262,9 @@ class SuperTabParts {
if (_derived['decisionsWaiting'] case final num waiting) {
state['decisionsWaiting'] = waiting.toInt();
}
+ if (_derived['decisionsDigest'] case final String digest) {
+ state['decisionsDigest'] = digest;
+ }
return state;
}
diff --git a/desktop/test/super_tab_decisions_test.dart b/desktop/test/super_tab_decisions_test.dart
index cc78622b4..8a2df1a2d 100644
--- a/desktop/test/super_tab_decisions_test.dart
+++ b/desktop/test/super_tab_decisions_test.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
@@ -5,6 +6,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/rendering.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/decisions.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/view.dart';
@@ -53,7 +55,10 @@ ConversationServer swarm() {
return server;
}
-Future<void> showView(WidgetTester tester, ConversationServer server) async {
+Future<SuperTabController> showView(
+ WidgetTester tester,
+ ConversationServer server,
+) async {
await tester.binding.setSurfaceSize(const Size(1200, 900));
addTearDown(() => tester.binding.setSurfaceSize(null));
final c = server.controller(account: 'peer');
@@ -78,6 +83,7 @@ Future<void> showView(WidgetTester tester, ConversationServer server) async {
// The project's rows, Chat with PM among them, show once it is expanded.
if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
await tester.pumpAndSettle();
+ return c;
}
Finder notificationsEntry() =>
@@ -121,6 +127,92 @@ void main() {
);
});
+ group('reading the reader\'s decisions', () {
+ test(
+ 'a Swarm change that leaves the waiting count alone reads no decisions',
+ () async {
+ final server = swarm()..ask(['Ship how?']);
+ final controller = server.controller(account: 'peer');
+ addTearDown(controller.dispose);
+ final decisions = SuperTabDecisions.of(controller);
+ await controller.refresh();
+ await pumpEventQueue();
+ expect(decisions.open.single.question, 'Ship how?');
+ final reads = server.decisionReads;
+ final before = controller.lastChangedAt;
+
+ // A message, a machine reading: the Swarm changed, the count did not.
+ (server.state['conversations'] as List).first['title'] = 'Lead room';
+ await controller.refresh();
+ await pumpEventQueue();
+
+ expect(controller.lastChangedAt, isNot(before));
+ expect(server.decisionReads, reads);
+ },
+ );
+
+ test('reads again when the waiting count moves', () async {
+ // A backend from before the digest: the count alone tells.
+ final server = swarm()
+ ..decisionsDigestMissing = true
+ ..ask(['Ship how?']);
+ final controller = server.controller(account: 'peer');
+ addTearDown(controller.dispose);
+ final decisions = SuperTabDecisions.of(controller);
+ await controller.refresh();
+ await pumpEventQueue();
+
+ server.ask(['Name it?']);
+ await controller.refresh();
+ await pumpEventQueue();
+
+ expect(decisions.open.map((d) => d.question), ['Name it?', 'Ship how?']);
+ });
+
+ test('reads again when one is answered elsewhere and another asked, though the count stays', () async {
+ final server = swarm()..ask(['Ship how?']);
+ final controller = server.controller(account: 'peer');
+ addTearDown(controller.dispose);
+ final decisions = SuperTabDecisions.of(controller);
+ await controller.refresh();
+ await pumpEventQueue();
+ expect(decisions.open.single.question, 'Ship how?');
+
+ server
+ ..answerDecision('decision-1', 0)
+ ..ask(['Name it?']);
+ await controller.refresh();
+ await pumpEventQueue();
+
+ expect(controller.snapshot!.decisionsWaiting, 1);
+ expect(decisions.open.single.question, 'Name it?');
+ expect(decisions.answered.single.question, 'Ship how?');
+ });
+
+ test(
+ 'a read that failed is tried again on the next Swarm change',
+ () async {
+ final server = swarm()
+ ..failDecisions = true
+ ..ask(['Ship how?']);
+ final controller = server.controller(account: 'peer');
+ addTearDown(controller.dispose);
+ final decisions = SuperTabDecisions.of(controller);
+ await controller.refresh();
+ await pumpEventQueue();
+ expect(decisions.error, isNotNull);
+
+ server.failDecisions = false;
+ (server.state['conversations'] as List).first['title'] = 'Lead room';
+ await controller.refresh();
+ await pumpEventQueue();
+
+ expect(decisions.error, isNull);
+ expect(decisions.open.single.question, 'Ship how?');
+ },
+ );
+ });
+
group('the Decisions list', () {
testWidgets(
'lists one batch per ask, marks the recommendation, and answers with one tap',
@@ -157,6 +249,41 @@ void main() {
},
);
+ testWidgets(
+ 'drops the decisions of a conversation the reader leaves at once, though another keeps the count',
+ (tester) async {
+ final server = swarm()..ask(['Ship how?'], conversationId: 'pm-chat');
+ final c = await showView(tester, server);
+ await tester.tap(notificationsEntry());
+ await tester.pumpAndSettle();
+ expect(find.text('Ship how?'), findsOneWidget);
+
+ // The reader leaves the private chat and the Lead asks elsewhere:
+ // still one waiting. The new list is slow to come.
+ final pmChat = (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'pm-chat');
+ pmChat['audience'] = {'people': <Object>[]};
+ server
+ ..hideDecision('decision-1')
+ ..ask(['Name it?']);
+ server.parts.epoch++;
+ final slow = server.holdDecisions = Completer<void>();
+ await c.refresh();
+ await tester.pump();
+
+ expect(c.snapshot!.decisionsWaiting, 1);
+ expect(find.text('Ship how?'), findsNothing);
+ expect(find.text('Behind a flag · Recommended'), findsNothing);
+
+ server.holdDecisions = null;
+ slow.complete();
+ await tester.pumpAndSettle();
+ expect(find.text('Name it?'), findsOneWidget);
+ expect(find.text('Ship how?'), findsNothing);
+ },
+ );
+
testWidgets('says when nothing waits', (tester) async {
await showView(tester, swarm());
await tester.tap(notificationsEntry());
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index 94c86e306..3734f54fa 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -70,6 +70,7 @@ class SwarmPartsBackend {
'starts',
'mentionsWaiting',
'decisionsWaiting',
+ 'decisionsDigest',
'otherProjectsWork',
'githubApp',
}.contains(entry.key))
@@ -141,6 +142,8 @@ class SwarmPartsBackend {
'mentionsWaiting': state['mentionsWaiting'],
if (state['decisionsWaiting'] != null)
'decisionsWaiting': state['decisionsWaiting'],
+ if (state['decisionsDigest'] != null)
+ 'decisionsDigest': state['decisionsDigest'],
if (state['otherProjectsWork'] != null)
'otherProjectsWork': state['otherProjectsWork'],
};
@@ -393,6 +396,14 @@ class ConversationServer {
final mentions = <Map<String, dynamic>>[];
// Decisions asked of the reader, newest last, answered by GET .../decisions?state=.
final decisions = <Map<String, dynamic>>[];
+ // How many times a decisions list was read (open and answered each count).
+ int decisionReads = 0;
+ // While set, every read of a decisions list waits for it.
+ Completer<void>? holdDecisions;
+ // Every read of a decisions list fails, as offline.
+ bool failDecisions = false;
+ // A backend from before the decisions digest: it sends the count alone.
+ bool decisionsDigestMissing = false;
// How many times the mentions list was read.
int mentionReads = 0;
// A backend from before tags: it has no list route.
@@ -531,11 +542,10 @@ class ConversationServer {
messages.last['replyTo'] = command['replyTo'];
output['messageId'] = 'message-$revision';
} else if (command['type'] == 'decision.answer') {
- decisions.firstWhere((d) => d['id'] == command['decisionId'])
- ..['choice'] = command['choice']
- ..['answeredAt'] = '2026-10-27T06:00:00Z';
- state['decisionsWaiting'] = (state['decisionsWaiting'] as int) - 1;
- revision++;
+ answerDecision(
+ command['decisionId'] as String,
+ command['choice'] as int,
+ );
} else if (command['type'] == 'mention.done') {
mentions.firstWhere((m) => m['id'] == command['mentionId'])
..['resolvedAt'] = '2026-10-24T06:00:00Z'
@@ -688,6 +698,9 @@ class ConversationServer {
return jsonDecode(jsonEncode(board)) as Map<String, dynamic>;
}
if (uri.pathSegments.last == 'decisions') {
+ decisionReads++;
+ if (holdDecisions case final hold?) await hold.future;
+ if (failDecisions) throw StateError('Offline');
final open = uri.queryParameters['state'] == 'open';
return jsonDecode(
jsonEncode({
@@ -839,9 +852,41 @@ class ConversationServer {
}
state['decisionsWaiting'] =
((state['decisionsWaiting'] as int?) ?? 0) + questions.length;
+ _digestDecisions();
+ revision++;
+ }
+
+ /// The reader answers one, here or on another device.
+ void answerDecision(String id, int choice) {
+ decisions.firstWhere((d) => d['id'] == id)
+ ..['choice'] = choice
+ ..['answeredAt'] = '2026-10-27T06:00:00Z';
+ state['decisionsWaiting'] = (state['decisionsWaiting'] as int) - 1;
+ _digestDecisions();
revision++;
}
+ /// The reader can no longer read the conversation of decision [id]: the
+ /// backend leaves it out of its lists and its count.
+ void hideDecision(String id) {
+ final hidden = decisions.firstWhere((d) => d['id'] == id);
+ decisions.remove(hidden);
+ if (hidden['answeredAt'] == null) {
+ state['decisionsWaiting'] = (state['decisionsWaiting'] as int) - 1;
+ }
+ _digestDecisions();
+ revision++;
+ }
+
+ /// Which decisions are open, as the backend digests them.
+ void _digestDecisions() {
+ if (decisionsDigestMissing) return;
+ state['decisionsDigest'] = [
+ for (final d in decisions)
+ if (d['answeredAt'] == null) d['id'],
+ ].join(',');
+ }
+
/// Who asks, for the reads a [controller] makes: a private conversation is
/// read by its audience alone. A zone value, so that subclasses overriding
/// [request] keep it.