diff --git a/crates/buzz-acp/src/observer.rs b/crates/buzz-acp/src/observer.rs index 7cf21dec69..7b75468c6c 100644 --- a/crates/buzz-acp/src/observer.rs +++ b/crates/buzz-acp/src/observer.rs @@ -104,8 +104,9 @@ pub struct ObserverEvent { pub agent_index: Option, /// Buzz channel UUID for channel-scoped events. pub channel_id: Option, - /// NIP-10 thread root for thread-scoped events. - #[serde(skip_serializing_if = "Option::is_none")] + /// NIP-10 thread root for this frame's turn. Serializes as null for the + /// channel root so consumers can distinguish an explicit root rescope from + /// legacy frames that omitted scope metadata. pub thread_head_id: Option, /// ACP session ID when known. pub session_id: Option, @@ -208,3 +209,28 @@ pub fn context_for_turn( started_at: Some(started_at), } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn channel_root_scope_serializes_as_explicit_null() { + let event = ObserverEvent { + seq: 1, + timestamp: "2026-08-18T00:00:00Z".into(), + kind: "turn_liveness".into(), + agent_index: Some(0), + channel_id: Some("channel-1".into()), + thread_head_id: None, + session_id: Some("session-1".into()), + turn_id: Some("turn-1".into()), + started_at: None, + payload: serde_json::json!({}), + }; + + let json = serde_json::to_value(event).expect("serialize observer event"); + assert!(json.get("threadHeadId").is_some()); + assert!(json["threadHeadId"].is_null()); + } +} diff --git a/mobile/lib/features/channels/agent_activity/active_agent_turns.dart b/mobile/lib/features/channels/agent_activity/active_agent_turns.dart index 06b9d7f4ea..d06c8186fe 100644 --- a/mobile/lib/features/channels/agent_activity/active_agent_turns.dart +++ b/mobile/lib/features/channels/agent_activity/active_agent_turns.dart @@ -47,22 +47,26 @@ class AgentTurnState { bool get isWorking => phase == AgentTurnPhase.working; - AgentTurnState withActivity({required DateTime at, Duration? timeout}) => - AgentTurnState( - agentPubkey: agentPubkey, - channelId: channelId, - threadHeadId: threadHeadId, - turnId: turnId, - startedAt: startedAt, - lastActivityAt: at, - livenessTimeout: timeout ?? livenessTimeout, - phase: AgentTurnPhase.working, - triggeringEventId: triggeringEventId, - ); + AgentTurnState withActivity({ + required DateTime at, + required String? threadHeadId, + Duration? timeout, + }) => AgentTurnState( + agentPubkey: agentPubkey, + channelId: channelId, + threadHeadId: threadHeadId, + turnId: turnId, + startedAt: startedAt, + lastActivityAt: at, + livenessTimeout: timeout ?? livenessTimeout, + phase: AgentTurnPhase.working, + triggeringEventId: triggeringEventId, + ); AgentTurnState withTerminal({ required AgentTurnPhase phase, required DateTime at, + required String? threadHeadId, String? errorMessage, }) => AgentTurnState( agentPubkey: agentPubkey, @@ -133,6 +137,9 @@ List reduceAgentTurnStates( existing?.withTerminal( phase: terminalPhase, at: frameAt, + threadHeadId: frame.hasThreadScope + ? frame.threadHeadId + : existing.threadHeadId, errorMessage: _turnError(frame.payload), ) ?? AgentTurnState( @@ -172,6 +179,9 @@ List reduceAgentTurnStates( turnsById[matching.turnId] = matching.withTerminal( phase: terminalPhase, at: frameAt, + threadHeadId: frame.hasThreadScope + ? frame.threadHeadId + : matching.threadHeadId, errorMessage: _turnError(frame.payload), ); case 'turn_rescoped': @@ -202,6 +212,9 @@ List reduceAgentTurnStates( if (existing?.isWorking == true) { turnsById[turnId] = existing!.withActivity( at: frameAt, + threadHeadId: frame.hasThreadScope + ? frame.threadHeadId + : existing.threadHeadId, timeout: frame.kind == 'turn_liveness' ? _livenessTimeout(frame.payload) : null, diff --git a/mobile/lib/features/channels/agent_activity/observer_models.dart b/mobile/lib/features/channels/agent_activity/observer_models.dart index e6fd09d6a0..2f91f0cfa7 100644 --- a/mobile/lib/features/channels/agent_activity/observer_models.dart +++ b/mobile/lib/features/channels/agent_activity/observer_models.dart @@ -15,6 +15,7 @@ class ObserverFrame { final int? agentIndex; final String? channelId; final String? threadHeadId; + final bool hasThreadScope; final String? sessionId; final String? turnId; final String? startedAt; @@ -28,12 +29,13 @@ class ObserverFrame { this.agentIndex, this.channelId, this.threadHeadId, + bool? hasThreadScope, this.sessionId, this.turnId, this.startedAt, this.receivedAt, this.payload, - }); + }) : hasThreadScope = hasThreadScope ?? threadHeadId != null; factory ObserverFrame.fromJson( Map json, { @@ -45,6 +47,7 @@ class ObserverFrame { agentIndex: json['agentIndex'] as int?, channelId: json['channelId'] as String?, threadHeadId: json['threadHeadId'] as String?, + hasThreadScope: json.containsKey('threadHeadId'), sessionId: json['sessionId'] as String?, turnId: json['turnId'] as String?, startedAt: json['startedAt'] as String?, diff --git a/mobile/lib/features/channels/agent_activity/working_bots_provider.dart b/mobile/lib/features/channels/agent_activity/working_bots_provider.dart index b99769a1ca..b19a61968a 100644 --- a/mobile/lib/features/channels/agent_activity/working_bots_provider.dart +++ b/mobile/lib/features/channels/agent_activity/working_bots_provider.dart @@ -108,7 +108,11 @@ final composerActivityStateProvider = Provider.autoDispose final signals = {}; for (final entry in activeByAgent.entries) { - if (!channelAgents.contains(entry.key)) continue; + final hasValidatedObserverFrame = observerState.framesByAgent + .containsKey(entry.key); + if (!channelAgents.contains(entry.key) && !hasValidatedObserverFrame) { + continue; + } final turn = entry.value; if (!turn.isWorking && !canView(entry.key)) continue; signals[entry.key] = WorkingAgentSignal( diff --git a/mobile/test/features/channels/agent_activity/active_agent_turns_test.dart b/mobile/test/features/channels/agent_activity/active_agent_turns_test.dart index 89db258d42..5da622cad0 100644 --- a/mobile/test/features/channels/agent_activity/active_agent_turns_test.dart +++ b/mobile/test/features/channels/agent_activity/active_agent_turns_test.dart @@ -58,6 +58,112 @@ void main() { expect(turns.single.isWorking, isTrue); }); + test( + 'terminal and activity frames carry a rescope without a rescope event', + () { + final terminal = reduceAgentTurnStates({ + 'agent-a': [ + _frame( + seq: 1, + second: 1, + kind: 'turn_started', + threadHeadId: 'thread-a', + ), + _frame( + seq: 2, + second: 2, + kind: 'turn_completed', + threadHeadId: 'thread-b', + ), + ], + }, now: DateTime.utc(2026, 8, 16, 12, 0, 3)); + + expect(terminal.single.threadHeadId, 'thread-b'); + expect(terminal.single.phase, AgentTurnPhase.finished); + + final working = reduceAgentTurnStates({ + 'agent-a': [ + _frame( + seq: 1, + second: 1, + kind: 'turn_started', + threadHeadId: 'thread-a', + ), + _frame( + seq: 2, + second: 2, + kind: 'turn_liveness', + threadHeadId: 'thread-b', + ), + ], + }, now: DateTime.utc(2026, 8, 16, 12, 0, 3)); + + expect(working.single.threadHeadId, 'thread-b'); + expect(working.single.isWorking, isTrue); + }, + ); + + test( + 'explicit null scope moves later activity and terminal frames to root', + () { + List frames(String kind) => [ + _frame( + seq: 1, + second: 1, + kind: 'turn_started', + threadHeadId: 'thread-a', + ), + _frame(seq: 2, second: 2, kind: kind, hasThreadScope: true), + ]; + + final working = reduceAgentTurnStates({ + 'agent-a': frames('turn_liveness'), + }, now: DateTime.utc(2026, 8, 16, 12, 0, 3)); + expect(working.single.threadHeadId, isNull); + expect(working.single.isWorking, isTrue); + + final terminal = reduceAgentTurnStates({ + 'agent-a': frames('turn_completed'), + }, now: DateTime.utc(2026, 8, 16, 12, 0, 3)); + expect(terminal.single.threadHeadId, isNull); + expect(terminal.single.phase, AgentTurnPhase.finished); + }, + ); + + test('legacy scope omission preserves the latest known thread', () { + final turns = reduceAgentTurnStates({ + 'agent-a': [ + _frame( + seq: 1, + second: 1, + kind: 'turn_started', + threadHeadId: 'thread-a', + ), + _frame(seq: 2, second: 2, kind: 'turn_liveness'), + ], + }, now: DateTime.utc(2026, 8, 16, 12, 0, 3)); + + expect(turns.single.threadHeadId, 'thread-a'); + }); + + test('explicit rescope event moves a turn from a thread to root', () { + final turns = reduceAgentTurnStates({ + 'agent-a': [ + _frame( + seq: 1, + second: 1, + kind: 'turn_started', + threadHeadId: 'thread-a', + ), + _frame(seq: 2, second: 2, kind: 'turn_rescoped'), + _frame(seq: 3, second: 3, kind: 'turn_liveness'), + ], + }, now: DateTime.utc(2026, 8, 16, 12, 0, 4)); + + expect(turns.single.threadHeadId, isNull); + expect(turns.single.isWorking, isTrue); + }); + test('preserves explicit completion and error outcomes', () { final turns = reduceAgentTurnStates({ 'agent-a': [ @@ -436,6 +542,7 @@ ObserverFrame _frame({ String? turnId = 'turn-1', String channelId = 'channel-1', String? threadHeadId, + bool? hasThreadScope, String? sessionId, int? receivedSecond, String? startedAt, @@ -447,6 +554,7 @@ ObserverFrame _frame({ kind: kind, channelId: channelId, threadHeadId: threadHeadId, + hasThreadScope: hasThreadScope, sessionId: sessionId, turnId: turnId, startedAt: startedAt, diff --git a/mobile/test/features/channels/agent_activity/observer_subscription_test.dart b/mobile/test/features/channels/agent_activity/observer_subscription_test.dart index e343aaf75f..6f59538a7d 100644 --- a/mobile/test/features/channels/agent_activity/observer_subscription_test.dart +++ b/mobile/test/features/channels/agent_activity/observer_subscription_test.dart @@ -10,6 +10,28 @@ import 'package:buzz/shared/crypto/nip44.dart'; import 'package:buzz/shared/relay/relay.dart'; void main() { + test('decodes explicit root scope separately from legacy omission', () { + final explicitRoot = ObserverFrame.fromJson({ + 'seq': 1, + 'timestamp': '2026-04-30T12:00:01.000Z', + 'kind': 'turn_liveness', + 'channelId': 'channel-1', + 'threadHeadId': null, + 'turnId': 'turn-1', + }); + final legacy = ObserverFrame.fromJson({ + 'seq': 2, + 'timestamp': '2026-04-30T12:00:02.000Z', + 'kind': 'turn_liveness', + 'channelId': 'channel-1', + 'turnId': 'turn-1', + }); + + expect(explicitRoot.hasThreadScope, isTrue); + expect(explicitRoot.threadHeadId, isNull); + expect(legacy.hasThreadScope, isFalse); + }); + test('turn-scoped provider does not merge concurrent agent turns', () { final container = ProviderContainer( overrides: [ diff --git a/mobile/test/features/channels/agent_activity/working_bots_provider_test.dart b/mobile/test/features/channels/agent_activity/working_bots_provider_test.dart index a31fdf6418..c1d5569fd3 100644 --- a/mobile/test/features/channels/agent_activity/working_bots_provider_test.dart +++ b/mobile/test/features/channels/agent_activity/working_bots_provider_test.dart @@ -67,6 +67,44 @@ void main() { expect(state.humanTyping.single.pubkey, 'human'); }); + test('validated observer work survives unavailable agent lookups', () { + final observerTurn = _turn('agent-a'); + final container = ProviderContainer( + overrides: [ + currentPubkeyProvider.overrideWith((ref) => 'owner'), + channelMembersProvider( + _channelId, + ).overrideWith((ref) => Future>.error('offline')), + channelTypingProvider( + _channelId, + ).overrideWith(() => _FakeTypingNotifier(const [])), + agentMentionPubkeysProvider( + _channelId, + ).overrideWith((ref) => const {}), + agentOwnersProvider.overrideWithValue(const AsyncLoading()), + userCacheProvider.overrideWith(_FakeUserCacheNotifier.new), + observerRelayProvider.overrideWith( + () => _FakeObserverRelayNotifier({ + 'agent-a': [_observerFrame('agent-a')], + }), + ), + composerAgentTurnStatesProvider.overrideWithValue([observerTurn]), + ], + ); + addTearDown(container.dispose); + + final state = container.read( + composerActivityStateProvider(( + channelId: _channelId, + threadHeadId: null, + )), + ); + + expect(state.agents.single.pubkey, 'agent-a'); + expect(state.agents.single.source, AgentWorkingSource.observer); + expect(state.agents.single.canViewActivity, isTrue); + }); + test( 'thread scope requires typing and does not surface observer-only work', () {