fix(mobile): honor observer frame scope updates

Co-authored-by: Kenny Lopez <klopez4212@gmail.com>
Signed-off-by: Kenny Lopez <klopez4212@gmail.com>
This commit is contained in:
Princess Donut
2026-08-18 15:01:47 +01:00
parent 88f5ba2e6d
commit 287e562280
7 changed files with 230 additions and 16 deletions

View File

@@ -104,8 +104,9 @@ pub struct ObserverEvent {
pub agent_index: Option<usize>,
/// Buzz channel UUID for channel-scoped events.
pub channel_id: Option<String>,
/// 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<String>,
/// ACP session ID when known.
pub session_id: Option<String>,
@@ -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());
}
}

View File

@@ -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<AgentTurnState> reduceAgentTurnStates(
existing?.withTerminal(
phase: terminalPhase,
at: frameAt,
threadHeadId: frame.hasThreadScope
? frame.threadHeadId
: existing.threadHeadId,
errorMessage: _turnError(frame.payload),
) ??
AgentTurnState(
@@ -172,6 +179,9 @@ List<AgentTurnState> 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<AgentTurnState> 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,

View File

@@ -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<String, dynamic> 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?,

View File

@@ -108,7 +108,11 @@ final composerActivityStateProvider = Provider.autoDispose
final signals = <String, WorkingAgentSignal>{};
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(

View File

@@ -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<ObserverFrame> 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,

View File

@@ -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: [

View File

@@ -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<List<ChannelMember>>.error('offline')),
channelTypingProvider(
_channelId,
).overrideWith(() => _FakeTypingNotifier(const [])),
agentMentionPubkeysProvider(
_channelId,
).overrideWith((ref) => const <String>{}),
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',
() {