Skip to content

Commit ef4c935

Browse files
Alex VegaAlex Vega
authored andcommitted
fix(app): preserve storage-first capture through reconnects
Reclaim the active server owner before socket creation, read the newest ring head before recent repair, and bind canonical recovery to wall-clock lifecycle bounds instead of compressed STT offsets. Keep raw ring fragments local and assign only exact overlapping ownership. Tests: 252 focused Flutter tests; focused analyzer; Android Bluetooth outage and iOS process-restart physical runs. Failure-Class: new
1 parent 4bec4c8 commit ef4c935

12 files changed

Lines changed: 519 additions & 392 deletions
Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import 'package:omi/services/capture/capture_controller.dart';
2-
import 'package:omi/services/capture/capture_external_actions.dart';
32

43
class CaptureProvider extends CaptureController {
5-
CaptureProvider({CaptureExternalActions? externalActions}) : super(externalActions: externalActions);
4+
CaptureProvider({
5+
super.externalActions,
6+
super.inProgressConversationFetcher = fetchInProgressConversation,
7+
});
68
}

‎app/lib/services/capture/capture_controller.dart‎

Lines changed: 154 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,23 @@ import 'package:omi/backend/schema/message_event.dart'
7171
FreemiumThresholdReachedEvent,
7272
SegmentsDeletedEvent;
7373

74+
typedef InProgressConversationFetcher = Future<({List<ServerConversation> items, bool ok})> Function();
75+
typedef ConversationBoundarySecondsProvider = int Function();
76+
77+
Future<({List<ServerConversation> items, bool ok})> fetchInProgressConversation() => getConversationsResult(
78+
statuses: [ConversationStatus.in_progress],
79+
limit: 1,
80+
);
81+
82+
int configuredConversationBoundarySeconds() =>
83+
effectiveConversationBoundarySeconds(SharedPreferencesUtil().conversationSilenceDuration);
84+
7485
class CaptureController extends ChangeNotifier
7586
with MessageNotifierMixin
7687
implements ITransctiptSegmentSocketServiceListener {
88+
static const bool _blackboxHarnessEnabled = bool.fromEnvironment(
89+
'OMI_BLACKBOX_HARNESS',
90+
);
7791
static const MethodChannel _nativeBleTranscriptChannel = MethodChannel(
7892
'com.friend.ios/native_ble_transcript',
7993
);
@@ -88,6 +102,8 @@ class CaptureController extends ChangeNotifier
88102
final ConversationSessionWindow _conversationSessionWindow = ConversationSessionWindow();
89103

90104
CaptureExternalActions externalActions;
105+
final InProgressConversationFetcher _inProgressConversationFetcher;
106+
final ConversationBoundarySecondsProvider _conversationBoundarySecondsProvider;
91107
DeviceOnboardingProvider? deviceOnboardingProvider;
92108

93109
// Cache refresh for backend-created persons
@@ -102,6 +118,12 @@ class CaptureController extends ChangeNotifier
102118

103119
IWalService get _wal => ServiceManager.instance().wal;
104120

121+
void _blackboxTrace(String message) {
122+
if (_blackboxHarnessEnabled) {
123+
Logger.debug('[BLACKBOX_CAPTURE] $message');
124+
}
125+
}
126+
105127
AudioSource? _activeSource;
106128

107129
bool _isWalSupported = false;
@@ -170,8 +192,13 @@ class CaptureController extends ChangeNotifier
170192
return segmentPersonIds.difference(cachedIds).isNotEmpty;
171193
}
172194

173-
CaptureController({CaptureExternalActions? externalActions})
174-
: externalActions = externalActions ?? const NoopCaptureExternalActions() {
195+
CaptureController({
196+
CaptureExternalActions? externalActions,
197+
InProgressConversationFetcher inProgressConversationFetcher = fetchInProgressConversation,
198+
ConversationBoundarySecondsProvider conversationBoundarySecondsProvider = configuredConversationBoundarySeconds,
199+
}) : externalActions = externalActions ?? const NoopCaptureExternalActions(),
200+
_inProgressConversationFetcher = inProgressConversationFetcher,
201+
_conversationBoundarySecondsProvider = conversationBoundarySecondsProvider {
175202
// Restore a persisted device mute so it survives an app kill/restart. When
176203
// the device reconnects, streamDeviceRecording() reads _isPaused as
177204
// `wasPaused` and re-applies the mute instead of silently resuming.
@@ -717,7 +744,18 @@ class CaptureController extends ChangeNotifier
717744
effectiveConfig = null;
718745
}
719746

747+
// A process restart loses the in-memory owner while the backend may still
748+
// have an open conversation. Reclaim it before constructing the socket so
749+
// client_conversation_id is present on the first request. Loading it after
750+
// the socket is ready is too late: the backend has already created a new
751+
// conversation and the app-down audio becomes ownerless fragments.
752+
await _reclaimInProgressConversationBeforeSocket();
753+
720754
// Connect to the transcript socket
755+
_blackboxTrace(
756+
'socket_connect force=$force resume_owner=${_activeConversationId ?? 'none'} '
757+
'session_start=$_sessionStartSeconds preview_segments=${segments.length}',
758+
);
721759
final connectedSocket = await ServiceManager.instance().socket.conversation(
722760
codec: codec,
723761
sampleRate: sampleRate,
@@ -2194,31 +2232,73 @@ class CaptureController extends ChangeNotifier
21942232
}
21952233
}
21962234

2197-
Future _loadInProgressConversation() async {
2198-
var convos = await getConversations(
2199-
statuses: [ConversationStatus.in_progress],
2200-
limit: 1,
2235+
Future<void> _reclaimInProgressConversationBeforeSocket() async {
2236+
if (_activeConversationId != null) return;
2237+
2238+
final result = await _inProgressConversationFetcher();
2239+
if (!result.ok) {
2240+
_blackboxTrace('pre_socket_reclaim outcome=fetch_failed');
2241+
return;
2242+
}
2243+
if (result.items.isEmpty) {
2244+
_blackboxTrace('pre_socket_reclaim outcome=none');
2245+
return;
2246+
}
2247+
2248+
final conversation = result.items.first;
2249+
_conversation = conversation;
2250+
_activeConversationId = conversation.id;
2251+
final authoritativeStart = (conversation.startedAt ?? conversation.createdAt).millisecondsSinceEpoch ~/ 1000;
2252+
_sessionStartSeconds = _conversationSessionWindow.reclaim(
2253+
conversationId: conversation.id,
2254+
serverStartedAtSeconds: authoritativeStart,
2255+
nowSeconds: _nowSeconds,
2256+
);
2257+
_applyInProgressConversationProjection(conversation);
2258+
_blackboxTrace(
2259+
'pre_socket_reclaim outcome=reclaimed owner=${conversation.id} '
2260+
'session_start=$_sessionStartSeconds server_start=$authoritativeStart',
2261+
);
2262+
}
2263+
2264+
@visibleForTesting
2265+
Future<void> reclaimInProgressConversationBeforeSocketForTesting() => _reclaimInProgressConversationBeforeSocket();
2266+
2267+
@visibleForTesting
2268+
String? get activeConversationIdForTesting => _activeConversationId;
2269+
2270+
@visibleForTesting
2271+
int get sessionStartSecondsForTesting => _sessionStartSeconds;
2272+
2273+
void _applyInProgressConversationProjection(ServerConversation conversation) {
2274+
segments = LiveTranscriptPreview.reconcile(
2275+
current: segments,
2276+
serverSnapshot: conversation.transcriptSegments,
22012277
);
2202-
_conversation = convos.isNotEmpty ? convos.first : null;
2278+
// Merge server photos with locally-captured temp photos to avoid losing
2279+
// photos that haven't been processed server-side yet.
2280+
final serverPhotos = conversation.photos;
2281+
final localTempPhotos = photos.where((p) => p.id.startsWith('temp_img_')).toList();
2282+
final serverPhotoIds = serverPhotos.map((p) => p.id).toSet();
2283+
final mergedPhotos = List<ConversationPhoto>.from(serverPhotos);
2284+
for (final local in localTempPhotos) {
2285+
if (!serverPhotoIds.contains(local.id)) {
2286+
mergedPhotos.add(local);
2287+
}
2288+
}
2289+
photos = mergedPhotos;
2290+
}
2291+
2292+
Future _loadInProgressConversation() async {
2293+
final result = await _inProgressConversationFetcher();
2294+
if (!result.ok) {
2295+
_blackboxTrace('in_progress_refresh outcome=fetch_failed');
2296+
return;
2297+
}
2298+
_conversation = result.items.isNotEmpty ? result.items.first : null;
22032299
if (_conversation != null) {
22042300
_activeConversationId ??= _conversation!.id;
2205-
segments = LiveTranscriptPreview.reconcile(
2206-
current: segments,
2207-
serverSnapshot: _conversation!.transcriptSegments,
2208-
);
2209-
// Merge server photos with locally-captured temp photos to avoid losing
2210-
// photos that haven't been processed server-side yet.
2211-
final serverPhotos = _conversation!.photos;
2212-
final localTempPhotos = photos.where((p) => p.id.startsWith('temp_img_')).toList();
2213-
final serverPhotoIds = serverPhotos.map((p) => p.id).toSet();
2214-
// Keep local temp photos that aren't already on the server
2215-
final mergedPhotos = List<ConversationPhoto>.from(serverPhotos);
2216-
for (final local in localTempPhotos) {
2217-
if (!serverPhotoIds.contains(local.id)) {
2218-
mergedPhotos.add(local);
2219-
}
2220-
}
2221-
photos = mergedPhotos;
2301+
_applyInProgressConversationProjection(_conversation!);
22222302
} else if (!_canRefreshInProgressConversation) {
22232303
segments = [];
22242304
photos = [];
@@ -2236,16 +2316,33 @@ class CaptureController extends ChangeNotifier
22362316
'phase=${event.lifecyclePhase ?? 'legacy'}',
22372317
);
22382318
if (event.isInProgress) {
2319+
final previousOwner = _activeConversationId;
22392320
_activeConversationId = event.conversationId;
22402321
_sessionStartSeconds = _conversationSessionWindow.observe(
22412322
conversationId: event.conversationId,
22422323
nowSeconds: _nowSeconds,
22432324
);
2325+
_blackboxTrace(
2326+
'session_in_progress owner=${event.conversationId} '
2327+
'previous_owner=${previousOwner ?? 'none'} '
2328+
'recording_session=${event.recordingSessionId ?? 'none'} '
2329+
'lifecycle_version=${event.lifecycleVersion ?? -1} '
2330+
'lifecycle_sequence=${event.lifecycleSequence ?? -1} '
2331+
'session_start=$_sessionStartSeconds '
2332+
'next_start=${_conversationSessionWindow.nextStartSeconds ?? 0}',
2333+
);
22442334
}
22452335
return;
22462336
}
22472337

22482338
if (event is ConversationProcessingStartedEvent) {
2339+
final completionObservedAtSeconds = _nowSeconds;
2340+
final storageAuthoritativeCompletion = _ringAudioTailSession != null ||
2341+
DeviceStorageProtocolPolicy.usesStorageAuthoritativeAudio(
2342+
_recordingDevice?.firmwareRevision,
2343+
);
2344+
final activeOwnerBeforeCompletion = _activeConversationId;
2345+
final queuedStartBeforeCompletion = _conversationSessionWindow.nextStartSeconds;
22492346
if (_activeConversationId == event.memory.id) {
22502347
_activeConversationId = null;
22512348
}
@@ -2256,11 +2353,23 @@ class CaptureController extends ChangeNotifier
22562353
);
22572354
_pendingAutoSyncConversationId = event.memory.id;
22582355

2356+
_blackboxTrace(
2357+
'processing_started owner=${event.memory.id} '
2358+
'active_before=${activeOwnerBeforeCompletion ?? 'none'} '
2359+
'queued_start_before=${queuedStartBeforeCompletion ?? 0} '
2360+
'completed_start=$_pendingAutoSyncSessionStart '
2361+
'next_start=${_conversationSessionWindow.nextStartSeconds ?? 0} '
2362+
'server_started_at=${event.memory.startedAt?.millisecondsSinceEpoch ?? 0} '
2363+
'server_segments=${event.memory.transcriptSegments.length}',
2364+
);
2365+
22592366
// Force-drain tail buffer, stamp WALs with conversation ID, then clear state.
22602367
// Store the future so the coordinated transfer wake waits for the stamp.
22612368
_pendingFinalizeAndStamp = _finalizeAndStampSession(
22622369
_pendingAutoSyncSessionStart,
22632370
event.memory,
2371+
completionObservedAtSeconds: completionObservedAtSeconds,
2372+
storageAuthoritative: storageAuthoritativeCompletion,
22642373
);
22652374

22662375
_resetStateVariables();
@@ -2444,23 +2553,37 @@ class CaptureController extends ChangeNotifier
24442553
/// Called from synchronous onMessageEventReceived — fire-and-forget async.
24452554
Future<void> _finalizeAndStampSession(
24462555
int sessionStartSeconds,
2447-
ServerConversation conversation,
2448-
) async {
2556+
ServerConversation conversation, {
2557+
required int completionObservedAtSeconds,
2558+
required bool storageAuthoritative,
2559+
}) async {
24492560
try {
24502561
final phoneSync = _wal.getSyncs().phone;
24512562
await phoneSync.finalizeCurrentSession();
24522563
if (sessionStartSeconds > 0) {
24532564
final hasServerSpeechProof = ConversationCaptureWindow.hasServerSpeechProof(
24542565
conversation.transcriptSegments,
24552566
);
2456-
final captureWindow = ConversationCaptureWindow.fromTranscript(
2457-
sessionOriginSeconds: conversation.startedAt == null
2458-
? sessionStartSeconds
2459-
: conversation.startedAt!.millisecondsSinceEpoch ~/ 1000,
2567+
final sessionOriginSeconds = conversation.startedAt == null
2568+
? sessionStartSeconds
2569+
: conversation.startedAt!.millisecondsSinceEpoch ~/ 1000;
2570+
final captureWindow = ConversationCaptureWindow.forCompletion(
2571+
storageAuthoritative: storageAuthoritative,
2572+
sessionOriginSeconds: sessionOriginSeconds,
24602573
fallbackStartSeconds: sessionStartSeconds,
2461-
fallbackEndSeconds: _nowSeconds,
2574+
completionObservedAtSeconds: completionObservedAtSeconds,
2575+
conversationBoundarySeconds: _conversationBoundarySecondsProvider(),
24622576
segments: conversation.transcriptSegments,
24632577
);
2578+
_blackboxTrace(
2579+
'canonical_stamp owner=${conversation.id} '
2580+
'session_start=$sessionStartSeconds '
2581+
'capture_start=${captureWindow.startSeconds} '
2582+
'capture_end=${captureWindow.endSeconds} '
2583+
'storage_authoritative=$storageAuthoritative '
2584+
'speech_proof=$hasServerSpeechProof '
2585+
'next_start=${_conversationSessionWindow.nextStartSeconds ?? 0}',
2586+
);
24642587
await phoneSync.stampConversationId(
24652588
captureWindow.startSeconds,
24662589
conversation.id,

‎app/lib/services/capture/conversation_capture_window.dart‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,31 @@ class ConversationCaptureWindow {
1414
static bool hasServerSpeechProof(List<TranscriptSegment> segments) =>
1515
segments.any((segment) => segment.text.trim().isNotEmpty && segment.end > segment.start);
1616

17+
factory ConversationCaptureWindow.forCompletion({
18+
required bool storageAuthoritative,
19+
required int sessionOriginSeconds,
20+
required int fallbackStartSeconds,
21+
required int completionObservedAtSeconds,
22+
required int conversationBoundarySeconds,
23+
required List<TranscriptSegment> segments,
24+
}) {
25+
if (storageAuthoritative) {
26+
return ConversationCaptureWindow.fromStorageLifecycle(
27+
sessionOriginSeconds: sessionOriginSeconds,
28+
fallbackStartSeconds: fallbackStartSeconds,
29+
completionObservedAtSeconds: completionObservedAtSeconds,
30+
conversationBoundarySeconds: conversationBoundarySeconds,
31+
segments: segments,
32+
);
33+
}
34+
return ConversationCaptureWindow.fromTranscript(
35+
sessionOriginSeconds: sessionOriginSeconds,
36+
fallbackStartSeconds: fallbackStartSeconds,
37+
fallbackEndSeconds: completionObservedAtSeconds,
38+
segments: segments,
39+
);
40+
}
41+
1742
factory ConversationCaptureWindow.fromTranscript({
1843
required int sessionOriginSeconds,
1944
required int fallbackStartSeconds,
@@ -35,4 +60,49 @@ class ConversationCaptureWindow {
3560
endSeconds: sessionOriginSeconds + lastSpeechOffset + transcriptMarginSeconds,
3661
);
3762
}
63+
64+
/// Resolves a storage-authoritative SD-ring session in wall-clock time.
65+
///
66+
/// STT offsets measure only audio submitted to the socket. Pendant VAD and a
67+
/// disconnected interval both compress that audio clock, so adding the last
68+
/// transcript offset to [sessionOriginSeconds] can close the durable window
69+
/// before recovered speech that occurred later in wall-clock time. Natural
70+
/// completion is observed after [conversationBoundarySeconds] of silence;
71+
/// that lifecycle edge therefore supplies the missing wall-clock bound.
72+
factory ConversationCaptureWindow.fromStorageLifecycle({
73+
required int sessionOriginSeconds,
74+
required int fallbackStartSeconds,
75+
required int completionObservedAtSeconds,
76+
required int conversationBoundarySeconds,
77+
required List<TranscriptSegment> segments,
78+
int transcriptMarginSeconds = 5,
79+
}) {
80+
if (segments.isEmpty) {
81+
return ConversationCaptureWindow(
82+
startSeconds: fallbackStartSeconds,
83+
endSeconds: completionObservedAtSeconds,
84+
);
85+
}
86+
87+
final transcriptWindow = ConversationCaptureWindow.fromTranscript(
88+
sessionOriginSeconds: sessionOriginSeconds,
89+
fallbackStartSeconds: fallbackStartSeconds,
90+
fallbackEndSeconds: completionObservedAtSeconds,
91+
segments: segments,
92+
transcriptMarginSeconds: transcriptMarginSeconds,
93+
);
94+
final start = max(
95+
fallbackStartSeconds,
96+
sessionOriginSeconds - transcriptMarginSeconds,
97+
);
98+
final lifecycleSpeechEnd = completionObservedAtSeconds - conversationBoundarySeconds + transcriptMarginSeconds;
99+
final end = min(
100+
completionObservedAtSeconds,
101+
max(transcriptWindow.endSeconds, lifecycleSpeechEnd),
102+
);
103+
return ConversationCaptureWindow(
104+
startSeconds: start,
105+
endSeconds: max(start, end),
106+
);
107+
}
38108
}

0 commit comments

Comments
 (0)