From 5bd9d2c5d2912d9c8dbdcdf710d643a1d8ad91a2 Mon Sep 17 00:00:00 2001 From: klopez4212 Date: Thu, 19 Nov 2026 10:32:12 +0000 Subject: [PATCH] Transcribe Bestie hold recordings into text on device (#9645) Hold Bestie to record with the waveform and slide-up cancel interaction from #8665, then release to send an on-device transcript as a normal text message. Stay on Home with a loader inside Bestie until delivery succeeds, then open chat. Failures expose Retry/Discard; saved recordings and signed messages remain recoverable without duplicate sends. Saved audio is excluded from OS backup. Existing composer voice notes are unchanged. Separate exploration from #8665. Transcription requires iOS 26 and a supported language. Android reports unavailable before capture because its generic recognizer cannot guarantee saved-file input. Validation: at `b5dc83bbf5`, 5,046 Flutter tests (71 skipped), 27 crypto tests, analysis and required push checks pass. Prior native changes at `30a397f83c`: Android build and 33 tests pass; iOS simulator compilation and backup-exclusion test pass, with one unchanged document-picker timeout passing on isolated rerun. Earlier iPhone preview was tested with saved profile preserved; these latest fixes have not been installed on the physical phone. --------- Signed-off-by: kenny lopez Signed-off-by: Tom Brow Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow Co-authored-by: studio Co-authored-by: corey <2dafccf60ea6d431a568f6d67fc600160d92a51e415e09dc8b213b8e360663d5@buzz.block.builderlab.xyz> --- .../android/app/src/main/AndroidManifest.xml | 1 + .../buzz/mobile/DeviceTranscriptionPlugin.kt | 25 + .../xyz/block/buzz/mobile/MainActivity.kt | 4 + .../app/src/main/res/xml/backup_rules.xml | 1 + .../main/res/xml/data_extraction_rules.xml | 2 + mobile/ios/Runner.xcodeproj/project.pbxproj | 8 + mobile/ios/Runner/AppDelegate.swift | 30 +- .../Runner/DeviceTranscriptionPlugin.swift | 120 +++ .../DeviceTranscriptionStorageTests.swift | 19 + .../channels/bestie_conversation.dart | 33 +- .../bestie_transcription_control.dart | 335 +++++++++ .../bestie_transcription_delivery.dart | 68 ++ .../channels/bestie_transcription_draft.dart | 179 +++++ .../channels/bestie_transcription_job.dart | 175 +++++ ...estie_transcription_loading_indicator.dart | 99 +++ .../channels/bestie_transcription_status.dart | 74 ++ .../bestie_transcription_surface.dart | 455 ++++++++++++ .../channels/channel_detail_page.dart | 2 + .../channels/default_agent_launcher.dart | 74 +- .../channels/send_message_provider.dart | 9 +- .../channels/voice_note_recording.dart | 27 +- .../channels/voice_note_waveform.dart | 6 +- mobile/lib/features/home/home_page.dart | 64 +- .../lib/features/home/messages_filters.dart | 4 +- .../home/messages_navigation_bar.dart | 321 ++++---- mobile/lib/shared/recording_haptics.dart | 37 + .../transcription/device_transcription.dart | 31 + .../widgets/agent_navigation_overlay.dart | 36 + .../widgets/duo_workspace_scaffold.dart | 9 +- .../lib/shared/widgets/filter_chip_bar.dart | 5 +- .../bestie_transcription_control_test.dart | 697 ++++++++++++++++++ .../bestie_transcription_draft_test.dart | 128 ++++ .../channels/channel_detail_page_test.dart | 2 + .../channels/notification_reply_test.dart | 2 + mobile/test/features/home/home_page_test.dart | 49 +- 35 files changed, 2916 insertions(+), 215 deletions(-) create mode 100644 mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/DeviceTranscriptionPlugin.kt create mode 100644 mobile/ios/Runner/DeviceTranscriptionPlugin.swift create mode 100644 mobile/ios/RunnerTests/DeviceTranscriptionStorageTests.swift create mode 100644 mobile/lib/features/channels/bestie_transcription_control.dart create mode 100644 mobile/lib/features/channels/bestie_transcription_delivery.dart create mode 100644 mobile/lib/features/channels/bestie_transcription_draft.dart create mode 100644 mobile/lib/features/channels/bestie_transcription_job.dart create mode 100644 mobile/lib/features/channels/bestie_transcription_loading_indicator.dart create mode 100644 mobile/lib/features/channels/bestie_transcription_status.dart create mode 100644 mobile/lib/features/channels/bestie_transcription_surface.dart create mode 100644 mobile/lib/shared/recording_haptics.dart create mode 100644 mobile/lib/shared/transcription/device_transcription.dart create mode 100644 mobile/lib/shared/widgets/agent_navigation_overlay.dart create mode 100644 mobile/test/features/channels/bestie_transcription_control_test.dart create mode 100644 mobile/test/features/channels/bestie_transcription_draft_test.dart diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml index 09a8b7f08b..a999429a8b 100644 --- a/mobile/android/app/src/main/AndroidManifest.xml +++ b/mobile/android/app/src/main/AndroidManifest.xml @@ -87,6 +87,7 @@ In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. --> + diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/DeviceTranscriptionPlugin.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/DeviceTranscriptionPlugin.kt new file mode 100644 index 0000000000..6bda6aab79 --- /dev/null +++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/DeviceTranscriptionPlugin.kt @@ -0,0 +1,25 @@ +package xyz.block.buzz.mobile + +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MethodChannel + +/** Fail before capture: Android's generic recognizer cannot guarantee file input. */ +class DeviceTranscriptionPlugin(messenger: BinaryMessenger) { + private val channel = MethodChannel(messenger, "buzz/transcription") + + init { + channel.setMethodCallHandler { call, result -> + when (call.method) { + "cancel" -> result.success(null) + "prepare", "transcribe" -> result.error( + "unavailable", + "Transcribing saved recordings is not available on Android yet.", + null, + ) + else -> result.notImplemented() + } + } + } + + fun dispose() { channel.setMethodCallHandler(null) } +} diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt index 377626d737..0f7a493f24 100644 --- a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt +++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt @@ -130,6 +130,7 @@ class MainActivity : FlutterFragmentActivity() { private var mediaUploadChannel: MethodChannel? = null private var ageSignalChannel: MethodChannel? = null private val ageSignalRequest = AgeSignalRequest() + private var deviceTranscriptionPlugin: DeviceTranscriptionPlugin? = null private var huddleMediaPlugin: HuddleMediaPlugin? = null private var hapticsPlugin: HapticsPlugin? = null private var hostedHpkePlugin: HostedHpkePlugin? = null @@ -138,6 +139,7 @@ class MainActivity : FlutterFragmentActivity() { override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) + deviceTranscriptionPlugin = DeviceTranscriptionPlugin(flutterEngine.dartExecutor.binaryMessenger) flutterEngine.platformViewsController.registry.registerViewFactory( "buzz/transparent-avatar", TransparentAvatarViewFactory(flutterEngine.dartExecutor.binaryMessenger), @@ -236,6 +238,8 @@ class MainActivity : FlutterFragmentActivity() { } override fun onDestroy() { + deviceTranscriptionPlugin?.dispose() + deviceTranscriptionPlugin = null browserAuthPlugin?.dispose() browserAuthPlugin = null identityFilePlugin?.dispose() diff --git a/mobile/android/app/src/main/res/xml/backup_rules.xml b/mobile/android/app/src/main/res/xml/backup_rules.xml index 043933e36d..183089dc03 100644 --- a/mobile/android/app/src/main/res/xml/backup_rules.xml +++ b/mobile/android/app/src/main/res/xml/backup_rules.xml @@ -1,6 +1,7 @@ + diff --git a/mobile/android/app/src/main/res/xml/data_extraction_rules.xml b/mobile/android/app/src/main/res/xml/data_extraction_rules.xml index 14dafc9901..c4769cebd0 100644 --- a/mobile/android/app/src/main/res/xml/data_extraction_rules.xml +++ b/mobile/android/app/src/main/res/xml/data_extraction_rules.xml @@ -6,12 +6,14 @@ app data still backs up and transfers as before. --> + + diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj index e193686465..0e2f3088f5 100644 --- a/mobile/ios/Runner.xcodeproj/project.pbxproj +++ b/mobile/ios/Runner.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + A96450000000000000000001 /* DeviceTranscriptionStorageTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96450000000000000000002 /* DeviceTranscriptionStorageTests.swift */; }; + A17100012F4100100A17E001 /* DeviceTranscriptionPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = A17100022F4100100A17E001 /* DeviceTranscriptionPlugin.swift */; }; ACAF00000000000000000001 /* ToastLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACAF00000000000000000002 /* ToastLayer.swift */; }; BC0010000000000000000003 /* BrowserAuthBridgeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC0010000000000000000004 /* BrowserAuthBridgeTests.swift */; }; BC0010000000000000000001 /* BuzzBrowserAuthBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC0010000000000000000002 /* BuzzBrowserAuthBridge.swift */; }; @@ -111,6 +113,8 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + A96450000000000000000002 /* DeviceTranscriptionStorageTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceTranscriptionStorageTests.swift; sourceTree = ""; }; + A17100022F4100100A17E001 /* DeviceTranscriptionPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceTranscriptionPlugin.swift; sourceTree = ""; }; ACAF00000000000000000002 /* ToastLayer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToastLayer.swift; sourceTree = ""; }; BC0010000000000000000004 /* BrowserAuthBridgeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserAuthBridgeTests.swift; sourceTree = ""; }; BC0010000000000000000002 /* BuzzBrowserAuthBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BuzzBrowserAuthBridge.swift; sourceTree = ""; }; @@ -229,6 +233,7 @@ isa = PBXGroup; children = ( 331C807B294A618700263BE5 /* RunnerTests.swift */, + A96450000000000000000002 /* DeviceTranscriptionStorageTests.swift */, BC0010000000000000000004 /* BrowserAuthBridgeTests.swift */, F84380010000000000000002 /* ProfileSetupRecoveryTests.swift */, AB1200132F40400100A17E01 /* NativeMessageImageLoaderTests.swift */, @@ -351,6 +356,7 @@ CA8300022F50000100A17E01 /* IosMediaCarousel.swift */, AC7400022F50000100A17E01 /* ThemePaginationGeometry.swift */, 4A71C0202F4100100A17E01 /* VoiceNotePackager.swift */, + A17100022F4100100A17E001 /* DeviceTranscriptionPlugin.swift */, 4A71C0222F4110100A17E01 /* MP4Canonicalizer.swift */, 4A71C0242F4120100A17E01 /* NativeAttachmentPopoverMenu.swift */, 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, @@ -651,6 +657,7 @@ buildActionMask = 2147483647; files = ( 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + A96450000000000000000001 /* DeviceTranscriptionStorageTests.swift in Sources */, BC0010000000000000000003 /* BrowserAuthBridgeTests.swift in Sources */, F84380010000000000000001 /* ProfileSetupRecoveryTests.swift in Sources */, AB1200032F40400100A17E01 /* NativeMessageImageLoaderTests.swift in Sources */, @@ -707,6 +714,7 @@ CA8300012F50000100A17E01 /* IosMediaCarousel.swift in Sources */, AC7400012F50000100A17E01 /* ThemePaginationGeometry.swift in Sources */, 4A71C01F2F4100100A17E01 /* VoiceNotePackager.swift in Sources */, + A17100012F4100100A17E001 /* DeviceTranscriptionPlugin.swift in Sources */, 4A71C0212F4110100A17E01 /* MP4Canonicalizer.swift in Sources */, 4A71C0232F4120100A17E01 /* NativeAttachmentPopoverMenu.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift index ccc42d80d6..8f613e98e0 100644 --- a/mobile/ios/Runner/AppDelegate.swift +++ b/mobile/ios/Runner/AppDelegate.swift @@ -35,6 +35,8 @@ import os.log private var communityKeyboardChannel: FlutterMethodChannel? private var communityKeyboardObserver: NSObjectProtocol? private var hapticsChannel: FlutterMethodChannel? + private let voiceStartFeedback = UIImpactFeedbackGenerator(style: .medium) + private let voiceCancelFeedback = UIImpactFeedbackGenerator(style: .rigid) private var appGroupChannel: FlutterMethodChannel? private var diagnosticsChannel: FlutterMethodChannel? private var shareSuggestions: ShareSuggestions? @@ -61,6 +63,7 @@ import os.log private var photoLibrarySaver: PhotoLibrarySaver? private var hostedHpkeChannel: FlutterMethodChannel? private var browserAuthBridge: BuzzBrowserAuthBridge? + private var deviceTranscriptionPlugin: DeviceTranscriptionPlugin? private var huddleMediaPlugin: HuddleMediaPlugin? override func application( @@ -131,6 +134,7 @@ import os.log result(FlutterError(code: "backup_unavailable", message: nil, details: nil)) } } + deviceTranscriptionPlugin = DeviceTranscriptionPlugin(messenger: messenger) huddleMediaPlugin = HuddleMediaPlugin(messenger: messenger) if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "BuzzIosNavigationBar") { registrar.register(IosNavigationBarFactory(messenger: messenger, parent: registrar.viewController), withId: "buzz/ios_navigation_bar") @@ -189,14 +193,30 @@ import os.log name: "buzz/haptics", binaryMessenger: messenger ) - hapticsChannel?.setMethodCallHandler { call, result in - guard call.method == "success" || call.method == "error" else { + hapticsChannel?.setMethodCallHandler { [weak self] call, result in + guard let self else { + result(FlutterMethodNotImplemented) + return + } + switch call.method { + case "voicePrepareStart": + self.voiceStartFeedback.prepare() + case "voicePrepareCancel": + self.voiceCancelFeedback.prepare() + case "voiceStart": + self.voiceStartFeedback.impactOccurred(intensity: 1) + self.voiceCancelFeedback.prepare() + case "voiceCancel": + self.voiceCancelFeedback.impactOccurred(intensity: 1) + self.voiceCancelFeedback.prepare() + case "success", "error": + let generator = UINotificationFeedbackGenerator() + generator.prepare() + generator.notificationOccurred(call.method == "error" ? .error : .success) + default: result(FlutterMethodNotImplemented) return } - let generator = UINotificationFeedbackGenerator() - generator.prepare() - generator.notificationOccurred(call.method == "error" ? .error : .success) result(nil) } qrScannerChannel = FlutterMethodChannel( diff --git a/mobile/ios/Runner/DeviceTranscriptionPlugin.swift b/mobile/ios/Runner/DeviceTranscriptionPlugin.swift new file mode 100644 index 0000000000..a955bd1db8 --- /dev/null +++ b/mobile/ios/Runner/DeviceTranscriptionPlugin.swift @@ -0,0 +1,120 @@ +import AVFoundation +import Flutter +import Speech + +/// File-based on-device recognition. Capture and waveform remain owned by Flutter. +@MainActor +final class DeviceTranscriptionPlugin { + private let channel: FlutterMethodChannel + private var operation: Task? + private var owner: String? + private var cancelAnalysis: (() -> Void)? + + /// Applies to new and existing durable drafts before Flutter opens their journal. + static func excludeDraftsFromBackup(in support: URL) throws { + var drafts = support.appendingPathComponent("bestie-transcripts", isDirectory: true) + try FileManager.default.createDirectory(at: drafts, withIntermediateDirectories: true) + var values = URLResourceValues() + values.isExcludedFromBackup = true + try drafts.setResourceValues(values) + } + + init(messenger: FlutterBinaryMessenger) { + channel = FlutterMethodChannel(name: "buzz/transcription", binaryMessenger: messenger) + channel.setMethodCallHandler { [weak self] call, reply in + guard let self, let args = call.arguments as? [String: Any], + let id = args["id"] as? String else { + reply(FlutterError(code: "arguments", message: "Invalid transcription request.", details: nil)) + return + } + if call.method == "cancel" { + if owner == id { + let task = operation + let cancel = cancelAnalysis + owner = nil + operation = nil + cancelAnalysis = nil + task?.cancel() + cancel?() + } + reply(nil) + return + } + if call.method == "storageDirectory" { + do { + let support = try FileManager.default.url( + for: .applicationSupportDirectory, in: .userDomainMask, + appropriateFor: nil, create: true) + try Self.excludeDraftsFromBackup(in: support) + reply(support.path) + } catch { + reply(FlutterError(code: "storage_failed", message: error.localizedDescription, details: nil)) + } + return + } + guard call.method == "prepare" || call.method == "transcribe" else { + reply(FlutterMethodNotImplemented); return + } + guard #available(iOS 26.0, *) else { + reply(FlutterError(code: "unavailable", message: "On-device transcription requires iOS 26.", details: nil)); return + } + guard owner == nil || owner == id else { + reply(FlutterError(code: "busy", message: "Another transcription is active.", details: nil)); return + } + owner = id + operation = Task { [weak self] in + guard let self else { return } + defer { + if owner == id { owner = nil; cancelAnalysis = nil; operation = nil } + } + do { + guard SpeechTranscriber.isAvailable, + let locale = await SpeechTranscriber.supportedLocale(equivalentTo: Locale.current) + else { throw TranscriptionFailure.unavailable } + let transcriber = SpeechTranscriber(locale: locale, preset: .transcription) + if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) { + try await request.downloadAndInstall() + } + try Task.checkCancellation() + if call.method == "prepare" { + reply(nil) + return + } + guard let path = args["path"] as? String else { throw TranscriptionFailure.invalidFile } + let file = try AVAudioFile(forReading: URL(fileURLWithPath: path)) + let analyzer = SpeechAnalyzer(modules: [transcriber]) + cancelAnalysis = { Task { await analyzer.cancelAndFinishNow() } } + let results = Task { + var text = "" + for try await result in transcriber.results { + if result.isFinal { text += String(result.text.characters) } + } + return text.trimmingCharacters(in: .whitespacesAndNewlines) + } + do { + try await analyzer.start(inputAudioFile: file, finishAfterFile: true) + let text = try await results.value + try Task.checkCancellation() + reply(text) + } catch { + results.cancel() + await analyzer.cancelAndFinishNow() + throw error + } + } catch { + reply(FlutterError(code: "transcription_failed", message: error.localizedDescription, details: nil)) + } + } + } + } +} + +private enum TranscriptionFailure: LocalizedError { + case unavailable, invalidFile + var errorDescription: String? { + switch self { + case .unavailable: return "On-device transcription is unavailable for this device or language." + case .invalidFile: return "The saved recording could not be opened." + } + } +} diff --git a/mobile/ios/RunnerTests/DeviceTranscriptionStorageTests.swift b/mobile/ios/RunnerTests/DeviceTranscriptionStorageTests.swift new file mode 100644 index 0000000000..fd80edaf74 --- /dev/null +++ b/mobile/ios/RunnerTests/DeviceTranscriptionStorageTests.swift @@ -0,0 +1,19 @@ +import Foundation +import Testing +@testable import Buzz + +struct DeviceTranscriptionStorageTests { + @Test @MainActor + func `Existing recordings survive backup exclusion`() throws { + let support = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: support) } + let drafts = support.appendingPathComponent("bestie-transcripts", isDirectory: true) + try FileManager.default.createDirectory(at: drafts, withIntermediateDirectories: true) + let audio = drafts.appendingPathComponent("saved.wav") + let bytes = Data([1, 2, 3]) + try bytes.write(to: audio) + try DeviceTranscriptionPlugin.excludeDraftsFromBackup(in: support) + #expect(try drafts.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup == true) + #expect(try Data(contentsOf: audio) == bytes) + } +} diff --git a/mobile/lib/features/channels/bestie_conversation.dart b/mobile/lib/features/channels/bestie_conversation.dart index b1da64c413..ad51ffc826 100644 --- a/mobile/lib/features/channels/bestie_conversation.dart +++ b/mobile/lib/features/channels/bestie_conversation.dart @@ -70,18 +70,7 @@ Future openBestieConversation( } // Only the lookup is guarded; an open conversation can be replaced. release(); - final pane = ConversationPaneScope.maybeOf(context); - if (pane != null) { - pane.open(channel.id, (_) => ChannelDetailPage(channel: channel)); - } else { - await Navigator.of(context).push( - MaterialPageRoute( - // Native glass and video layers must track the live route. - allowSnapshotting: false, - builder: (_) => ChannelDetailPage(channel: channel), - ), - ); - } + await openBestieDestination(context, channel); } catch (error) { if (context.mounted) { ScaffoldMessenger.of(context).showFeedbackSnackBar( @@ -96,3 +85,23 @@ Future openBestieConversation( if (context.mounted) onResolving?.call(false); } } + +/// Both taps and delivered notes retain Home's split-pane destination and never +/// navigate over a newer route. +Future openBestieDestination( + BuildContext context, + Channel channel, +) async { + if (!context.mounted || ModalRoute.of(context)?.isCurrent == false) return; + final pane = ConversationPaneScope.maybeOf(context); + if (pane != null) { + pane.open(channel.id, (_) => ChannelDetailPage(channel: channel)); + } else { + await Navigator.of(context).push( + MaterialPageRoute( + allowSnapshotting: false, + builder: (_) => ChannelDetailPage(channel: channel), + ), + ); + } +} diff --git a/mobile/lib/features/channels/bestie_transcription_control.dart b/mobile/lib/features/channels/bestie_transcription_control.dart new file mode 100644 index 0000000000..a1f6278ba6 --- /dev/null +++ b/mobile/lib/features/channels/bestie_transcription_control.dart @@ -0,0 +1,335 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:record/record.dart'; + +import '../../shared/huddle/huddle_session.dart'; +import '../../shared/transcription/device_transcription.dart'; +import '../../shared/widgets/app_route_observer.dart'; +import 'bestie_transcription_job.dart'; +import 'bestie_transcription_draft.dart'; +import 'voice_note_recording.dart'; +import 'bestie_transcription_surface.dart'; +import 'bestie_conversation.dart'; +import '../../shared/recording_haptics.dart'; + +/// Independent PCM capture; ordinary composer voice notes keep their AAC format. +final bestieTranscriptionRecorderProvider = + Provider( + (ref) => + () => DeviceVoiceNoteRecorder( + recordConfig: const RecordConfig( + encoder: AudioEncoder.wav, + iosConfig: IosRecordConfig( + allowHapticsAndSystemSoundsDuringRecording: true, + ), + sampleRate: 16000, + numChannels: 1, + autoGain: true, + echoCancel: true, + noiseSuppress: true, + ), + fileExtension: 'wav', + ), + ); + +class _DictationRouteObserver extends RouteAware { + _DictationRouteObserver(this.cancel); + final VoidCallback cancel; + @override + void didPushNext() => cancel(); +} + +/// Hold the Bestie button to capture, release to transcribe and send plain text. +class BestieTranscriptionControl extends HookConsumerWidget { + const BestieTranscriptionControl({ + super.key, + required this.scope, + required this.recipient, + required this.child, + }); + final String scope; + final String? recipient; + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final store = ref.watch(bestieTranscriptStoreProvider(scope)); + final job = ref.watch(bestieTranscriptionJobProvider(scope)); + final progress = useValueListenable(job); + final phase = useState('Restoring'); + final error = useState(null); + final draft = useState(null); + final recorder = useRef(null); + final speech = useRef(null); + final generation = useRef(0); + final started = useRef(false); + final cancelOnRelease = useState(false); + final levels = useRef?>(null); + final samples = useState>([]); + final timer = useRef(null); + final elapsed = useState(Duration.zero); + final alive = useRef(true); + bool current(int token) => + alive.value && context.mounted && token == generation.value; + void report(Object failure) { + if (!alive.value || !context.mounted) return; + error.value = failure is PlatformException + ? failure.message ?? 'Transcription failed.' + : failure is StateError + ? failure.message + : 'Could not finish transcription. Retry or discard the saved recording.'; + phase.value = ''; + } + + Future cancel() async { + // Release has already committed this send. A route/lifecycle callback + // cannot revoke a publication that may have reached the relay. + if (phase.value == 'Sending') return; + final cancellation = ++generation.value; + timer.value?.cancel(); + final capture = recorder.value; + recorder.value = null; + started.value = false; + final transcription = speech.value; + speech.value = null; + // Stop microphone and recognition immediately; meter teardown must not + // hold either resource open while its stream subscription settles. + final stopCapture = capture == null + ? Future.value() + : capture.cancel().whenComplete(capture.dispose); + final stopSpeech = transcription?.cancel().catchError((Object _) {}); + await Future.wait([ + stopCapture, + ?stopSpeech, + if (levels.value != null) levels.value!.cancel(), + ]); + // A released recording still being saved keeps Home busy until its + // retention settles, so no new hold can race it for the slot. + if (current(cancellation) && + phase.value != 'Sending' && + phase.value != 'Saving' && + phase.value != 'Discarding') { + phase.value = ''; + } + } + + Future restore() async { + try { + final saved = await store.read(); + if (!alive.value || !context.mounted) return; + draft.value = job.value.draft == null ? saved : null; + phase.value = ''; + } catch (failure) { + report(failure); + } + } + + Future process(BestieTranscriptDraft pending, int token) async { + phase.value = 'Opening conversation'; + try { + final channel = await job.destination(pending); + if (!current(token)) return; + // Keep progress on Home, but let delivery survive the user leaving it. + final delivery = job.run(pending, channel); + draft.value = null; + phase.value = ''; + final sent = await delivery; + if (!sent || !current(token) || !context.mounted) return; + unawaited(openBestieDestination(context, channel)); + } catch (failure) { + if (current(token)) report(failure); + } + } + + Future finish() async { + if (phase.value != 'Listening') { + if (phase.value == 'Preparing speech') { + await cancel(); + report( + StateError( + 'Speech was not ready. Hold again and wait for Listening before speaking.', + ), + ); + } + return; + } + if (cancelOnRelease.value || !started.value) { + await cancel(); + return; + } + final capture = recorder.value; + if (capture == null || phase.value != 'Listening') return; + final destination = recipient; + if (destination == null) { + await cancel(); + return; + } + recorder.value = null; + started.value = false; + timer.value?.cancel(); + unawaited(levels.value?.cancel()); + final token = generation.value; + phase.value = 'Saving'; + try { + final saved = await store.retain(capture.stop(), destination); + if (!alive.value || !context.mounted) return; + // The slot is occupied even if a route push or backgrounding cancelled + // this release, so keep it visible for Retry and block new captures. + draft.value = saved; + if (!current(token)) { + phase.value = ''; + return; + } + unawaited(HapticFeedback.mediumImpact()); + await process(saved, token); + } catch (failure) { + // Reconcile with the slot even after a cancel: a save that failed + // after journaling still left a draft to retry or discard. + if (alive.value && context.mounted) { + await restore(); + if (current(token)) report(failure); + } + } finally { + await capture.dispose(); + } + } + + Future start() async { + if (recipient == null || + phase.value.isNotEmpty || + draft.value != null || + job.busy || + progress.draft != null || + error.value != null) { + return; + } + if (ref.read(huddleSessionProvider).isInSession) { + report(StateError('Leave the Huddle before dictating.')); + return; + } + final token = ++generation.value; + phase.value = 'Preparing speech'; + elapsed.value = Duration.zero; + cancelOnRelease.value = false; + samples.value = []; + final native = ref.read(deviceTranscriptionProvider)(); + speech.value = native; + try { + await native.prepare().timeout(const Duration(minutes: 2)); + if (!current(token)) return; + final capture = ref.read(bestieTranscriptionRecorderProvider)(); + recorder.value = capture; + levels.value = capture.levels.listen((value) { + if (current(token)) { + samples.value = [ + ...samples.value.skip(samples.value.length > 40 ? 1 : 0), + value, + ]; + } + }); + await capture.start(); + if (!current(token)) return; + started.value = true; + phase.value = 'Listening'; + unawaited(recordingHaptic()); + final watch = Stopwatch()..start(); + timer.value = Timer.periodic(const Duration(milliseconds: 200), (_) { + if (!current(token)) return; + elapsed.value = watch.elapsed; + if (watch.elapsed >= voiceNoteMaxDuration) unawaited(finish()); + }); + } catch (failure) { + if (current(token)) { + await cancel(); + report(failure); + } + } + } + + useEffect(() { + unawaited(restore()); + return () { + alive.value = false; + unawaited(cancel()); + }; + }, const []); + useEffect(() { + if (recorder.value != null || speech.value != null) unawaited(cancel()); + return null; + }, [recipient]); + useOnAppLifecycleStateChange((_, next) { + if (next == AppLifecycleState.paused || + next == AppLifecycleState.detached) { + unawaited(cancel()); + } + }); + final route = ModalRoute.of(context); + useEffect(() { + if (route == null) return null; + final observer = _DictationRouteObserver(() => unawaited(cancel())); + appRouteObserver.subscribe(observer, route); + return () => appRouteObserver.unsubscribe(observer); + }, [route]); + return BestieTranscriptionSurface( + enabled: recipient != null && !job.busy && progress.draft == null, + recording: phase.value == 'Listening', + preparing: phase.value == 'Preparing speech', + processingLabel: job.busy + ? '${progress.phase} transcript' + : phase.value == 'Discarding' + ? 'Discarding transcript' + : 'Saving recording', + finalizing: + phase.value == 'Saving' || phase.value == 'Opening conversation', + sending: job.busy || phase.value == 'Discarding', + restoring: phase.value == 'Restoring', + restoreFailed: + error.value != null && draft.value == null && progress.draft == null, + hasPending: draft.value != null || (!job.busy && progress.draft != null), + elapsed: elapsed.value, + samples: samples.value, + error: + error.value ?? + (progress.error == null + ? null + : 'Could not send transcript. Recording saved.'), + cancelled: cancelOnRelease, + start: start, + finish: finish, + cancel: cancel, + retry: () async { + final pending = draft.value ?? progress.draft; + if (pending == null || phase.value.isNotEmpty) return; + error.value = null; + await process(pending, ++generation.value); + }, + restore: () async { + error.value = null; + await restore(); + }, + discardPending: () async { + if (phase.value.isNotEmpty) return; + phase.value = 'Discarding'; + try { + if (job.value.draft != null) { + await job.discard(); + } else { + await store.clear(); + } + if (context.mounted) { + draft.value = null; + error.value = null; + phase.value = ''; + } + } catch (failure) { + report(failure); + } + }, + child: child, + ); + } +} diff --git a/mobile/lib/features/channels/bestie_transcription_delivery.dart b/mobile/lib/features/channels/bestie_transcription_delivery.dart new file mode 100644 index 0000000000..9ebedfc7f7 --- /dev/null +++ b/mobile/lib/features/channels/bestie_transcription_delivery.dart @@ -0,0 +1,68 @@ +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../../shared/relay/relay.dart'; +import 'channel.dart'; +import 'bestie_transcription_draft.dart'; +import 'send_message_provider.dart'; + +/// Sends text only, retaining the original signed event after uncertain delivery. +Future deliverBestieTranscript( + Ref ref, + BestieTranscriptStore store, + BestieTranscriptDraft draft, + Channel channel, + void Function() validate, +) async { + validate(); + final session = ref.read(relaySessionProvider.notifier); + final event = draft.event; + if (event != null) { + // Never re-sign an uncertain delivery. Its exact ID makes retries idempotent. + try { + await session.publish(event); + } catch (failure) { + if (!failure.toString().contains( + 'invalid: event timestamp too far from server time', + )) { + rethrow; + } + final accepted = await session.queryRelay([ + NostrFilter(kinds: [event.kind], ids: [event.id]), + ]); + validate(); + if (!accepted.any((candidate) => candidate.id == event.id)) { + await SignedEventRelay( + session: session, + nsec: ref.read(relayConfigProvider).nsec, + ).submit( + kind: event.kind, + content: event.content, + tags: event.tags, + onSigned: (renewed) async { + await store.update(draft, event: renewed); + validate(); + }, + ); + } + } + } else { + final text = draft.text?.trim() ?? ''; + if (text.isEmpty) throw StateError('No speech was recognized.'); + validate(); + await ref + .read(sendMessageProvider) + .call( + channelId: channel.id, + channel: channel, + content: text, + mentionPubkeys: [draft.recipient], + validateDelivery: validate, + beforePublish: (event) async { + await store.update(draft, event: event); + validate(); + }, + ); + } + await store.clear(id: draft.id); + return channel; +} diff --git a/mobile/lib/features/channels/bestie_transcription_draft.dart b/mobile/lib/features/channels/bestie_transcription_draft.dart new file mode 100644 index 0000000000..3cc9a2bb8e --- /dev/null +++ b/mobile/lib/features/channels/bestie_transcription_draft.dart @@ -0,0 +1,179 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter/services.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:uuid/uuid.dart'; + +import '../../shared/relay/relay.dart'; +import 'voice_note_recording.dart'; + +/// One pending utterance per account/community, retaining its original recipient. +class BestieTranscriptDraft { + const BestieTranscriptDraft({ + required this.id, + required this.recipient, + required this.audioPath, + this.text, + this.event, + }); + final String id; + final String recipient; + final String audioPath; + final String? text; + final NostrEvent? event; +} + +final bestieTranscriptDirectoryProvider = + Provider Function()>( + (ref) => () async { + if (!Platform.isIOS) return getApplicationSupportDirectory(); + final path = await const MethodChannel( + 'buzz/transcription', + ).invokeMethod('storageDirectory', {'id': 'storage'}); + if (path == null) { + throw StateError('Private transcript storage unavailable.'); + } + return Directory(path); + }, + ); +final bestieTranscriptStoreProvider = + Provider.family( + (ref, scope) => BestieTranscriptStore( + scope, + ref.watch(bestieTranscriptDirectoryProvider), + ), + ); + +/// Atomic, serialized storage. Audio is local-only and deleted on acceptance/discard. +class BestieTranscriptStore { + BestieTranscriptStore(this.scope, this.directory); + final String scope; + final Future Function() directory; + static final _writes = >{}; + Future _mutate(Future Function(File) action) async { + final previous = _writes[scope]; + final done = Completer(); + _writes[scope] = done.future; + try { + await previous; + final root = Directory('${(await directory()).path}/bestie-transcripts'); + await root.create(recursive: true); + return await action( + File('${root.path}/${sha256.convert(utf8.encode(scope))}.json'), + ); + } finally { + done.complete(); + if (identical(_writes[scope], done.future)) _writes.remove(scope); + } + } + + Future> _data(File file) async => + jsonDecode(await file.readAsString()) as Map; + Future _write(File file, Map data) async { + final temp = File('${file.path}.tmp'); + await temp.writeAsString(jsonEncode(data), flush: true); + await temp.rename(file.path); + } + + BestieTranscriptDraft _decode(File file, Map data) => + BestieTranscriptDraft( + id: data['id'] as String, + recipient: data['recipient'] as String, + // Until promotion finishes, the original recording is authoritative. + audioPath: data['source'] as String? ?? '${file.path}.wav', + text: data['text'] as String?, + event: data['event'] == null + ? null + : NostrEvent.fromJson(data['event'] as Map), + ); + Future read() => _mutate( + (file) async => + await file.exists() ? _decode(file, await _data(file)) : null, + ); + + /// Reserve the slot before finalizing capture so remounts wait for recovery. + Future retain( + Future recording, + String recipient, + ) { + // Observe native failure immediately, even while an older disk operation + // or the OS directory lookup still owns the serialized queue. + VoiceNoteRecording? completed; + Object? failure; + StackTrace? failureStack; + final finalization = recording.then( + (note) { + completed = note; + }, + onError: (Object error, StackTrace stack) { + failure = error; + failureStack = stack; + }, + ); + return _mutate((file) async { + await finalization; + if (failure != null) Error.throwWithStackTrace(failure!, failureStack!); + final note = completed!; + if (await file.exists()) { + throw StateError('A previous transcript still needs delivery.'); + } + final source = note.file.path; + final data = { + 'id': const Uuid().v4(), + 'recipient': recipient, + 'source': source, + }; + // Journal first, pointing at the original: a failed or interrupted + // promotion stays recoverable from it, and discard removes both copies. + await _write(file, data); + final promoted = File('${file.path}.wav.tmp'); + await File(source).copy(promoted.path); + await promoted.rename('${file.path}.wav'); + data.remove('source'); + await _write(file, data); + await File(source).delete(); + return _decode(file, data); + }); + } + + Future update( + BestieTranscriptDraft draft, { + String? text, + NostrEvent? event, + }) => _mutate((file) async { + final data = await _data(file); + if (data['id'] != draft.id) { + throw StateError('The saved transcript changed.'); + } + if (text != null) data['text'] = text; + if (event != null) data['event'] = event.toJson(); + await _write(file, data); + return _decode(file, data); + }); + Future clear({String? id}) => _mutate((file) async { + if (id != null && await file.exists() && (await _data(file))['id'] != id) { + return; + } + // Best effort: Discard must still remove a journal that cannot be read. + String? source; + try { + if (await file.exists()) { + source = (await _data(file))['source'] as String?; + } + } catch (_) { + source = null; + } + for (final audio in [ + File('${file.path}.wav'), + File('${file.path}.wav.tmp'), + if (source != null) File(source), + ]) { + if (await audio.exists()) await audio.delete(); + } + if (await file.exists()) await file.delete(); + }); +} diff --git a/mobile/lib/features/channels/bestie_transcription_job.dart b/mobile/lib/features/channels/bestie_transcription_job.dart new file mode 100644 index 0000000000..3dc09c36a5 --- /dev/null +++ b/mobile/lib/features/channels/bestie_transcription_job.dart @@ -0,0 +1,175 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../../shared/me/me_sync.dart'; +import '../../shared/transcription/device_transcription.dart'; +import 'bestie_transcription_delivery.dart'; +import 'bestie_transcription_draft.dart'; +import 'channel.dart'; +import 'channel_management_provider.dart'; + +class BestieTranscriptionProgress { + const BestieTranscriptionProgress({ + this.channel, + this.draft, + this.phase = '', + this.error, + }); + final Channel? channel; + final BestieTranscriptDraft? draft; + final String phase; + final Object? error; +} + +final bestieTranscriptionJobProvider = + Provider.family((ref, scope) { + final job = BestieTranscriptionJob( + ref, + scope, + ref.read(bestieTranscriptStoreProvider(scope)), + ); + ref.onDispose(job.dispose); + ref.listen(meSyncProvider, (_, next) { + if (next.config.nsec == null || next.cacheKey != scope) job.abort(); + }); + return job; + }); + +/// A released utterance belongs to the account/community, not the Home widget. +class BestieTranscriptionJob + extends ValueNotifier { + BestieTranscriptionJob(this.ref, this.scope, this.store) + : super(const BestieTranscriptionProgress()); + final Ref ref; + final String scope; + final BestieTranscriptStore store; + DeviceTranscription? _speech; + bool _disposed = false; + int _generation = 0; + bool get busy => value.phase.isNotEmpty; + void _validate(int generation) { + if (_disposed || + generation != _generation || + ref.read(meSyncProvider).config.nsec == null || + ref.read(meSyncProvider).cacheKey != scope) { + throw StateError('The account or community changed.'); + } + } + + Future destination(BestieTranscriptDraft draft) => + ref.read(channelActionsProvider).openDm(pubkeys: [draft.recipient]); + + /// Returns true only after this attempt confirms successful delivery. + Future run(BestieTranscriptDraft draft, Channel channel) async { + if (busy) return false; + final generation = ++_generation; + var saved = draft; + value = BestieTranscriptionProgress( + channel: channel, + draft: saved, + phase: 'Transcribing', + ); + DeviceTranscription? native; + try { + _validate(generation); + if (saved.text == null && saved.event == null) { + native = ref.read(deviceTranscriptionProvider)(); + _speech = native; + final text = await native + .transcribe(saved.audioPath) + .timeout(const Duration(seconds: 65)); + _validate(generation); + if (text.trim().isEmpty) { + throw StateError( + 'No speech recognized. Retry or discard the recording.', + ); + } + saved = await store.update(saved, text: text); + } + _validate(generation); + value = BestieTranscriptionProgress( + channel: channel, + draft: saved, + phase: 'Sending', + ); + await deliverBestieTranscript( + ref, + store, + saved, + channel, + () => _validate(generation), + ); + _validate(generation); + value = const BestieTranscriptionProgress(); + return true; + } catch (error) { + try { + saved = await store.read() ?? saved; + } catch (_) { + /* Keep recovery. */ + } + if (!_disposed && generation == _generation) { + value = BestieTranscriptionProgress( + channel: channel, + draft: saved, + error: error, + ); + } + return false; + } finally { + if (identical(_speech, native)) _speech = null; + try { + await native?.cancel(); + } catch (_) { + /* Already stopped. */ + } + } + } + + Future retry() async { + final draft = value.draft; + final channel = value.channel; + if (draft != null && channel != null) await run(draft, channel); + } + + Future discard() async { + if (busy) return; + final pending = value; + final generation = ++_generation; + value = BestieTranscriptionProgress( + channel: pending.channel, + draft: pending.draft, + phase: 'Discarding', + ); + try { + await store.clear(id: pending.draft?.id); + if (!_disposed && generation == _generation) { + value = const BestieTranscriptionProgress(); + } + } catch (error) { + if (!_disposed && generation == _generation) { + value = BestieTranscriptionProgress( + channel: pending.channel, + draft: pending.draft, + error: error, + ); + } + } + } + + void abort() { + _generation++; + unawaited(_speech?.cancel().catchError((Object _) {})); + _speech = null; + if (!_disposed) value = const BestieTranscriptionProgress(); + } + + @override + void dispose() { + abort(); + _disposed = true; + super.dispose(); + } +} diff --git a/mobile/lib/features/channels/bestie_transcription_loading_indicator.dart b/mobile/lib/features/channels/bestie_transcription_loading_indicator.dart new file mode 100644 index 0000000000..7890bf1707 --- /dev/null +++ b/mobile/lib/features/channels/bestie_transcription_loading_indicator.dart @@ -0,0 +1,99 @@ +import 'dart:math' show pi; + +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../../shared/theme/theme.dart'; + +/// The shared mobile loading indicator, matching the desktop arc spinner. +class BestieTranscriptionLoadingIndicator extends HookConsumerWidget { + /// The spinner diameter. + final double size; + + /// An optional spinner color. Defaults to the active accent color. + final Color? color; + + /// The accessibility announcement for this loading state. + final String semanticLabel; + + /// Creates a looping arc loading indicator. + const BestieTranscriptionLoadingIndicator({ + this.size = 40, + this.color, + this.semanticLabel = 'Loading', + super.key, + }); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final reducedMotion = MediaQuery.disableAnimationsOf(context); + final animation = useAnimationController( + duration: const Duration(milliseconds: 380), + ); + + useEffect(() { + if (reducedMotion) { + animation + ..stop() + ..value = 0; + } else { + animation.repeat(); + } + return animation.stop; + }, [animation, reducedMotion]); + + final spinnerColor = color ?? context.colors.primary; + final strokeWidth = (size / 6).clamp(2.0, 4.0); + + return Semantics( + liveRegion: true, + label: semanticLabel, + child: ExcludeSemantics( + child: RotationTransition( + key: const ValueKey('buzz-loading-indicator-spinner'), + turns: animation, + child: CustomPaint( + size: Size.square(size), + painter: _ArcSpinnerPainter( + color: spinnerColor, + strokeWidth: strokeWidth, + ), + ), + ), + ), + ); + } +} + +class _ArcSpinnerPainter extends CustomPainter { + final Color color; + final double strokeWidth; + + const _ArcSpinnerPainter({required this.color, required this.strokeWidth}); + + @override + void paint(Canvas canvas, Size size) { + final center = size.center(Offset.zero); + final radius = (size.shortestSide - strokeWidth) / 2; + final bounds = Rect.fromCircle(center: center, radius: radius); + final trackPaint = Paint() + ..color = color.withValues(alpha: color.a * 0.1) + ..style = PaintingStyle.stroke + ..strokeWidth = strokeWidth; + final arcPaint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeWidth = strokeWidth; + + canvas + ..drawCircle(center, radius, trackPaint) + ..drawArc(bounds, -pi / 2, 7 * pi / 12, false, arcPaint); + } + + @override + bool shouldRepaint(_ArcSpinnerPainter oldDelegate) { + return color != oldDelegate.color || strokeWidth != oldDelegate.strokeWidth; + } +} diff --git a/mobile/lib/features/channels/bestie_transcription_status.dart b/mobile/lib/features/channels/bestie_transcription_status.dart new file mode 100644 index 0000000000..75bd4b52f4 --- /dev/null +++ b/mobile/lib/features/channels/bestie_transcription_status.dart @@ -0,0 +1,74 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../../shared/me/me_sync.dart'; +import '../../shared/theme/theme.dart'; +import 'bestie_transcription_job.dart'; + +/// Keeps pending speech visible and recoverable in its destination conversation. +class BestieTranscriptionStatus extends HookConsumerWidget { + const BestieTranscriptionStatus({super.key, required this.channelId}); + final String channelId; + @override + Widget build(BuildContext context, WidgetRef ref) { + final sync = ref.watch(meSyncProvider); + if (sync.config.nsec == null) return const SizedBox.shrink(); + return _SignedInTranscriptionStatus( + channelId: channelId, + scope: sync.cacheKey, + ); + } +} + +class _SignedInTranscriptionStatus extends HookConsumerWidget { + const _SignedInTranscriptionStatus({ + required this.channelId, + required this.scope, + }); + final String channelId; + final String scope; + @override + Widget build(BuildContext context, WidgetRef ref) { + final job = ref.watch(bestieTranscriptionJobProvider(scope)); + final progress = useValueListenable(job); + if (progress.channel?.id != channelId || + progress.draft == null || + progress.error == null) { + return const SizedBox.shrink(); + } + return Material( + color: context.controlSurface, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: Grid.sm, + vertical: Grid.xxs, + ), + child: Row( + children: [ + Expanded( + child: Semantics( + liveRegion: true, + child: Text( + progress.error != null + ? 'Could not send transcript. Recording saved.' + : '${progress.phase}…', + ), + ), + ), + if (progress.error != null) ...[ + TextButton( + onPressed: job.busy ? null : job.discard, + child: const Text('Discard'), + ), + TextButton( + onPressed: job.busy ? null : job.retry, + child: const Text('Retry'), + ), + ], + ], + ), + ), + ); + } +} diff --git a/mobile/lib/features/channels/bestie_transcription_surface.dart b/mobile/lib/features/channels/bestie_transcription_surface.dart new file mode 100644 index 0000000000..03394cdb1d --- /dev/null +++ b/mobile/lib/features/channels/bestie_transcription_surface.dart @@ -0,0 +1,455 @@ +import 'dart:async'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import '../../shared/recording_haptics.dart'; +import '../../shared/theme/theme.dart'; +import '../../shared/widgets/navigation_button_surface.dart'; +import '../../shared/widgets/concentric_sheet_surface.dart'; +import '../../shared/widgets/agent_navigation_overlay.dart'; +import 'bestie_transcription_loading_indicator.dart'; +import 'voice_note_recording.dart'; +import 'voice_note_waveform.dart'; + +/// Recording presentation from PR #8665, with transcription behind its callbacks. +class BestieTranscriptionSurface extends HookWidget { + const BestieTranscriptionSurface({ + super.key, + required this.enabled, + required this.recording, + this.preparing = false, + this.processingLabel = 'Processing transcript', + required this.finalizing, + required this.sending, + required this.restoring, + required this.restoreFailed, + required this.hasPending, + required this.elapsed, + required this.samples, + required this.error, + required this.cancelled, + required this.start, + required this.finish, + required this.cancel, + required this.retry, + required this.restore, + required this.discardPending, + required this.child, + }); + final bool preparing; + final String processingLabel; + final bool enabled, + recording, + finalizing, + sending, + restoring, + restoreFailed, + hasPending; + final Duration elapsed; + final List samples; + final String? error; + final ValueNotifier cancelled; + final Future Function() start, + finish, + cancel, + retry, + restore, + discardPending; + final Widget child; + @override + Widget build(BuildContext context) { + final alive = useRef(true); + final cancelHapticPrepared = useRef(false); + useEffect( + () => () { + alive.value = false; + }, + const [], + ); + final active = + preparing || + recording || + (!finalizing && !sending && (hasPending || restoreFailed)); + final recordingCallback = AgentNavigationOverlay.recordingCallbackOf( + context, + ); + useEffect(() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (alive.value && context.mounted) { + recordingCallback?.call(recording); + } + }); + return null; + }, [recording, recordingCallback]); + final latestRecordingCallback = useRef(recordingCallback); + latestRecordingCallback.value = recordingCallback; + useEffect(() { + return () { + WidgetsBinding.instance.addPostFrameCallback((_) { + latestRecordingCallback.value?.call(false); + }); + }; + }, const []); + final overlay = AgentNavigationOverlay.maybeOf(context); + useEffect(() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (alive.value && context.mounted) overlay?.value = recording; + }); + return null; + }, [recording, overlay]); + final canRecord = + enabled && !active && !restoring && !finalizing && !sending; + final recoveryPortal = useMemoized(OverlayPortalController.new); + final recoveryLink = useMemoized(LayerLink.new); + final recoveryAnchor = useMemoized(GlobalKey.new); + final recovering = active && !recording && !preparing; + final showRecovery = + recovering && !AgentNavigationOverlay.menuOpenOf(context); + useEffect(() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!context.mounted) return; + if (showRecovery) { + recoveryPortal.show(); + } else { + recoveryPortal.hide(); + } + }); + return null; + }, [showRecovery]); + final pill = Semantics( + key: const ValueKey('default-agent-voice-status'), + liveRegion: preparing || sending || finalizing, + value: preparing + ? 'Preparing speech. Wait before speaking.' + : recording + ? cancelled.value + ? 'Release to cancel' + : 'Recording ${formatVoiceNoteDuration(elapsed)}' + : sending + ? processingLabel + : finalizing + ? 'Saving recording' + : restoring + ? 'Restoring transcript' + : restoreFailed + ? 'Could not restore transcript' + : hasPending + ? 'Transcript awaiting delivery' + : null, + hint: preparing + ? 'Release to cancel preparation.' + : canRecord + ? 'Hold to record a transcript. Release to send. Slide up to cancel.' + : recording + ? 'Release to send. Slide up to cancel.' + : null, + customSemanticsActions: canRecord + ? { + const CustomSemanticsAction(label: 'Record transcript'): () => + unawaited(start()), + } + : recording || preparing + ? { + const CustomSemanticsAction(label: 'Discard transcript'): () => + unawaited(cancel()), + } + : null, + child: Listener( + onPointerDown: (_) { + if (canRecord) unawaited(prepareRecordingHaptic()); + }, + onPointerCancel: (_) => unawaited(cancel()), + child: GestureDetector( + excludeFromSemantics: true, + behavior: HitTestBehavior.opaque, + onLongPressStart: enabled ? (_) => unawaited(start()) : null, + onLongPressMoveUpdate: (details) { + if (recording) { + final willCancel = details.offsetFromOrigin.dy < -64; + if (details.offsetFromOrigin.dy < -24 && + !cancelHapticPrepared.value) { + cancelHapticPrepared.value = true; + unawaited(prepareRecordingHaptic(cancel: true)); + } else if (details.offsetFromOrigin.dy >= -24) { + cancelHapticPrepared.value = false; + } + if (willCancel && !cancelled.value) { + unawaited(recordingHaptic(cancel: true)); + } + cancelled.value = willCancel; + } + }, + onLongPressEnd: (_) => unawaited(finish()), + onLongPressCancel: () => unawaited(cancel()), + child: AnimatedContainer( + key: const ValueKey('default-agent-voice-pill'), + duration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 220), + curve: Curves.easeInOutCubic, + width: active ? 224 + Grid.xs * 2 : 56, + height: 56, + // Keep one native glass view mounted while the finger is down. + // Replacing its UIKit subtree cancels the active iOS touch. + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: NavigationButtonSurface( + child: Stack( + fit: StackFit.expand, + children: [ + Positioned.fill( + child: IgnorePointer( + child: DecoratedBox( + key: const ValueKey( + 'default-agent-voice-surface', + ), + decoration: BoxDecoration( + color: recording + ? context.colors.primary + : active && + NavigationGlassGroup.maybeOf(context) + ? context.controlSurface + : Colors.transparent, + borderRadius: BorderRadius.circular( + Radii.navigationCapsule, + ), + ), + ), + ), + ), + Positioned.fill( + child: !active + ? const SizedBox.shrink() + : Padding( + padding: const EdgeInsets.symmetric( + horizontal: Grid.xxs, + ), + child: ClipRect( + child: OverflowBox( + alignment: Alignment.centerRight, + minWidth: + 224 + Grid.xs * 2 - Grid.xxs * 2, + maxWidth: + 224 + Grid.xs * 2 - Grid.xxs * 2, + child: Row( + children: [ + if (!recording && + !sending && + (hasPending || restoreFailed)) + IconButton( + tooltip: 'Discard transcript', + onPressed: () => + unawaited(discardPending()), + icon: const Icon(Icons.close), + ), + Expanded( + child: sending || finalizing + ? const Center( + child: BestieTranscriptionLoadingIndicator( + semanticLabel: + 'Sending transcript', + size: 28, + ), + ) + : preparing + ? const Text( + 'Preparing speech…', + textAlign: TextAlign.center, + ) + : restoreFailed + ? TextButton( + onPressed: restoring + ? null + : () => unawaited( + restore(), + ), + child: Text( + error!, + maxLines: 2, + ), + ) + : hasPending + ? TextButton( + onPressed: () => + unawaited(retry()), + child: Text( + 'Retry transcript', + ), + ) + : VoiceNoteWaveform( + color: context + .colors + .onPrimary, + samples: [ + ...List.filled( + 41 - samples.length, + 0.0, + ), + ...samples, + ], + progress: 1, + fadeEdges: true, + height: 32, + ), + ), + if (recording) + const SizedBox(width: 48), + ], + ), + ), + ), + ), + ), + // The avatar can itself own an iOS video platform view. + // Keep it mounted at the same location throughout the hold. + Positioned( + right: 0, + top: 0, + width: 56, + height: 56, + child: ExcludeSemantics( + excluding: active, + child: IgnorePointer( + ignoring: active, + child: Opacity( + opacity: !active || recording ? 1 : 0, + child: TooltipTheme( + data: TooltipTheme.of(context).copyWith( + triggerMode: TooltipTriggerMode.manual, + ), + child: finalizing || sending + ? Center( + child: + BestieTranscriptionLoadingIndicator( + semanticLabel: processingLabel, + size: 28, + ), + ) + : recovering + ? const SizedBox.shrink() + : child, + ), + ), + ), + ), + ), + if (recording) + Positioned( + right: 0, + top: 0, + width: 56, + height: 56, + child: IconButton( + tooltip: 'Send transcript', + onPressed: () => unawaited(finish()), + icon: const SizedBox.square(dimension: 48), + ), + ), + ], + ), + ), + ), + if (recording) + Positioned( + bottom: 56 + Grid.xs, + width: 224 + Grid.xs * 2, + right: 0, + child: Center( + child: Semantics( + label: cancelled.value + ? 'Release to cancel' + : 'Slide up to cancel', + child: IgnorePointer( + child: AnimatedScale( + key: const ValueKey('voice-cancel-target'), + scale: cancelled.value ? 1.15 : 1, + duration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 220), + curve: Curves.easeOutBack, + child: ConcentricSheetSurface( + enabled: true, + usesGlass: true, + providesSheetSurface: false, + padding: EdgeInsets.zero, + minimumRadius: 24, + contentClipRadius: 24, + color: cancelled.value + ? context.colors.error + : context.colors.surfaceContainerHighest, + glassTintColor: cancelled.value + ? context.colors.error + : null, + child: AnimatedContainer( + duration: + MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 140), + width: 48, + height: 48, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: + defaultTargetPlatform == + TargetPlatform.iOS + ? Colors.transparent + : cancelled.value + ? context.colors.error + : context.colors.surfaceContainerHighest, + ), + child: Icon( + Icons.close, + color: cancelled.value + ? context.colors.onError + : context.colors.onSurface, + ), + ), + ), + ), + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + return OverlayPortal( + controller: recoveryPortal, + overlayChildBuilder: (overlayContext) { + final box = + recoveryAnchor.currentContext?.findRenderObject() as RenderBox?; + final origin = box?.localToGlobal(Offset.zero) ?? Offset.zero; + final right = origin.dx + (box?.size.width ?? 56); + final screen = MediaQuery.sizeOf(overlayContext); + final left = (right - 256).clamp(8.0, screen.width - 264); + final below = origin.dy < 72; + return Positioned.fill( + child: Align( + alignment: Alignment.topLeft, + child: CompositedTransformFollower( + link: recoveryLink, + showWhenUnlinked: false, + targetAnchor: below ? Alignment.bottomRight : Alignment.topRight, + followerAnchor: below + ? Alignment.topRight + : Alignment.bottomRight, + offset: Offset(left - (right - 256), below ? 8 : -8), + child: SizedBox(width: 256, height: 56, child: pill), + ), + ), + ); + }, + child: CompositedTransformTarget( + key: recoveryAnchor, + link: recoveryLink, + child: recovering ? child : pill, + ), + ); + } +} diff --git a/mobile/lib/features/channels/channel_detail_page.dart b/mobile/lib/features/channels/channel_detail_page.dart index b11580fff6..d77895cfcc 100644 --- a/mobile/lib/features/channels/channel_detail_page.dart +++ b/mobile/lib/features/channels/channel_detail_page.dart @@ -1,3 +1,4 @@ +import 'bestie_transcription_status.dart'; import '../../shared/widgets/duo_toolbar.dart'; import 'composer_geometry.dart'; import 'message_author_visibility.dart'; @@ -927,6 +928,7 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { child: Column( mainAxisSize: MainAxisSize.min, children: [ + BestieTranscriptionStatus(channelId: channel.id), ?assistant.pendingNotice, ComposeBar( channelId: channel.id, diff --git a/mobile/lib/features/channels/default_agent_launcher.dart b/mobile/lib/features/channels/default_agent_launcher.dart index 087b88c880..e4e4285c81 100644 --- a/mobile/lib/features/channels/default_agent_launcher.dart +++ b/mobile/lib/features/channels/default_agent_launcher.dart @@ -15,11 +15,11 @@ import '../../shared/theme/theme.dart'; import '../../shared/widgets/agent_navigation_icon.dart'; import '../../shared/widgets/avatar_image.dart'; import '../../shared/widgets/preset_agent_avatar.dart'; -import '../../shared/widgets/navigation_button_surface.dart'; import '../../shared/widgets/buzz_callout.dart'; import 'first_agent_callout.dart'; import 'empty_bestie_avatar.dart'; import 'bestie_conversation.dart'; +import 'bestie_transcription_control.dart'; /// Persistent shortcut to the agent chosen in Agents. class DefaultAgentLauncher extends HookConsumerWidget { @@ -100,6 +100,16 @@ class DefaultAgentLauncher extends HookConsumerWidget { } } + Widget withTranscription(Widget child) { + if (scope.config.nsec?.isNotEmpty != true) return child; + return BestieTranscriptionControl( + key: ValueKey('transcription:${scope.cacheKey}'), + scope: scope.cacheKey, + recipient: preference.isLoading || preference.hasError ? null : pubkey, + child: child, + ); + } + return BuzzCallout( message: 'Create your first agent', visible: showCallout, @@ -116,36 +126,38 @@ class DefaultAgentLauncher extends HookConsumerWidget { fallback: const AgentNavigationIcon(size: 24), ), ], - child: NavigationButtonSurface( - child: SizedBox.square( - dimension: 56, - child: IconButton( - tooltip: label, - padding: EdgeInsets.zero, - onPressed: opening.value || preference.isLoading ? null : open, - icon: ExcludeSemantics( - child: resolving.value - ? const SizedBox.square( - dimension: 22, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : pubkey == null - ? preference.isLoading || preference.hasError - ? const AgentNavigationIcon(size: 24) - : const EmptyBestieAvatar() - : usesInsetAgentArtwork(profile?.avatarUrl) - ? PresetAgentAvatar( - imageUrl: profile!.avatarUrl!, - size: 47.88, - fallback: Center(child: Text(profile.initial)), - ) - : AvatarImage( - imageUrl: profile?.avatarUrl, - radius: 18, - isAgent: true, - backgroundColor: context.controlSurface, - fallback: Center(child: Text(profile?.initial ?? 'A')), - ), + child: withTranscription( + SizedBox( + child: SizedBox.square( + dimension: 56, + child: IconButton( + tooltip: label, + padding: EdgeInsets.zero, + onPressed: opening.value || preference.isLoading ? null : open, + icon: ExcludeSemantics( + child: resolving.value + ? const SizedBox.square( + dimension: 22, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : pubkey == null + ? preference.isLoading || preference.hasError + ? const AgentNavigationIcon(size: 24) + : const EmptyBestieAvatar() + : usesInsetAgentArtwork(profile?.avatarUrl) + ? PresetAgentAvatar( + imageUrl: profile!.avatarUrl!, + size: 47.88, + fallback: Center(child: Text(profile.initial)), + ) + : AvatarImage( + imageUrl: profile?.avatarUrl, + radius: 18, + isAgent: true, + backgroundColor: context.controlSurface, + fallback: Center(child: Text(profile?.initial ?? 'A')), + ), + ), ), ), ), diff --git a/mobile/lib/features/channels/send_message_provider.dart b/mobile/lib/features/channels/send_message_provider.dart index 5d6179ed92..4d1b67bca1 100644 --- a/mobile/lib/features/channels/send_message_provider.dart +++ b/mobile/lib/features/channels/send_message_provider.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../shared/mentions/mention_tags.dart'; @@ -63,6 +65,8 @@ class SendMessage { List? mentionPubkeys, Channel? channel, List> mediaTags = const [], + FutureOr Function(NostrEvent)? beforePublish, + void Function()? validateDelivery, Future Function()? mayPublish, }) async { _ensureDeliveryValid(); @@ -123,7 +127,10 @@ class SendMessage { kind: EventKind.streamMessage, content: content, tags: tags, - onSigned: (event) { + onSigned: (event) async { + await beforePublish?.call(event); + _ensureDeliveryValid(); + validateDelivery?.call(); localMessage = event; _markLocalMessageForAnimation(channelId, event.id); _addLocalMessage(channelId, event); diff --git a/mobile/lib/features/channels/voice_note_recording.dart b/mobile/lib/features/channels/voice_note_recording.dart index 219100f57c..19a6d09ca5 100644 --- a/mobile/lib/features/channels/voice_note_recording.dart +++ b/mobile/lib/features/channels/voice_note_recording.dart @@ -114,9 +114,21 @@ class DeviceVoiceNoteRecorder implements VoiceNoteRecorder { DeviceVoiceNoteRecorder({ VoiceNoteRecorderBackend? backend, Future Function()? temporaryDirectory, + this.recordConfig = const RecordConfig( + encoder: AudioEncoder.aacLc, + bitRate: 96000, + sampleRate: 44100, + numChannels: 1, + autoGain: true, + echoCancel: true, + noiseSuppress: true, + ), + this.fileExtension = 'm4a', }) : _recorder = backend ?? _DeviceVoiceNoteRecorderBackend(), _temporaryDirectory = temporaryDirectory ?? getTemporaryDirectory; + final RecordConfig recordConfig; + final String fileExtension; final VoiceNoteRecorderBackend _recorder; final Future Function() _temporaryDirectory; final StreamController _levels = StreamController.broadcast(); @@ -166,19 +178,8 @@ class DeviceVoiceNoteRecorder implements VoiceNoteRecorder { _ensureStartupActive(generation); final path = '${directory.path}${Platform.pathSeparator}' - 'voice-note-${DateTime.now().millisecondsSinceEpoch}.m4a'; - await _recorder.start( - const RecordConfig( - encoder: AudioEncoder.aacLc, - bitRate: 96000, - sampleRate: 44100, - numChannels: 1, - autoGain: true, - echoCancel: true, - noiseSuppress: true, - ), - path: path, - ); + 'voice-note-${DateTime.now().microsecondsSinceEpoch}.$fileExtension'; + await _recorder.start(recordConfig, path: path); _nativeStarted = true; _ensureStartupActive(generation); _path = path; diff --git a/mobile/lib/features/channels/voice_note_waveform.dart b/mobile/lib/features/channels/voice_note_waveform.dart index 4eb44a948d..eba31ab60b 100644 --- a/mobile/lib/features/channels/voice_note_waveform.dart +++ b/mobile/lib/features/channels/voice_note_waveform.dart @@ -31,6 +31,7 @@ class VoiceNoteWaveform extends StatelessWidget { this.minimumBarHeight = 4, this.maximumBarHeight, this.colorOpacity = 1, + this.color, }); final List samples; @@ -41,6 +42,7 @@ class VoiceNoteWaveform extends StatelessWidget { final double minimumBarHeight; final double? maximumBarHeight; final double colorOpacity; + final Color? color; @override Widget build(BuildContext context) { @@ -50,7 +52,9 @@ class VoiceNoteWaveform extends StatelessWidget { painter: _VoiceNoteWaveformPainter( samples: samples, progress: progress.clamp(0.0, 1.0), - activeColor: colorScheme.primary.withValues(alpha: colorOpacity), + activeColor: (color ?? colorScheme.primary).withValues( + alpha: colorOpacity, + ), inactiveColor: colorScheme.onSurfaceVariant.withValues(alpha: 0.46), minimumBarHeight: minimumBarHeight, maximumBarHeight: maximumBarHeight ?? height, diff --git a/mobile/lib/features/home/home_page.dart b/mobile/lib/features/home/home_page.dart index e2427180f6..2e1ff87519 100644 --- a/mobile/lib/features/home/home_page.dart +++ b/mobile/lib/features/home/home_page.dart @@ -1,3 +1,5 @@ +import 'dart:ui' as ui; + import 'package:duo_kit/duo_kit.dart'; import '../../shared/widgets/adaptive_conversation_pane.dart'; @@ -84,6 +86,7 @@ class HomePage extends HookConsumerWidget { final showWorkspaceNavigation = wide || conversations.selectedId == null; final communitySurfaceProgress = useState(0.0); + final recordingFocus = useState(false); final filter = useState('All'); final hasUnreadInbox = ref.watch(inboxHasUnreadProvider); final inboxLabel = hasUnreadInbox ? 'Activity, unread items' : 'Activity'; @@ -172,7 +175,8 @@ class HomePage extends HookConsumerWidget { : Stack( alignment: Alignment.center, children: [ - defaultTargetPlatform == TargetPlatform.iOS + defaultTargetPlatform == TargetPlatform.iOS && + !recordingFocus.value ? IosGlassNavigationButton( icon: IosGlassNavigationIcon.bell, semanticLabel: inboxLabel, @@ -185,6 +189,7 @@ class HomePage extends HookConsumerWidget { : IconButton.filledTonal( tooltip: inboxLabel, style: IconButton.styleFrom( + shape: const CircleBorder(), backgroundColor: context.colors.surfaceContainerHighest, foregroundColor: context.colors.onSurface, @@ -246,7 +251,9 @@ class HomePage extends HookConsumerWidget { const SizedBox(width: Grid.xs), SizedBox( key: avatarKey, - child: defaultTargetPlatform == TargetPlatform.iOS + child: + defaultTargetPlatform == TargetPlatform.iOS && + !recordingFocus.value ? IosMessageCreateButton( actions: moreActions, dividerBefore: OrganizationEnvironment.enabled @@ -262,6 +269,26 @@ class HomePage extends HookConsumerWidget { height: 44, plain: false, ) + : recordingFocus.value && + defaultTargetPlatform == TargetPlatform.iOS + ? SizedBox.square( + dimension: 44, + child: DecoratedBox( + decoration: BoxDecoration( + shape: BoxShape.circle, + color: context.colors.surfaceContainerHighest, + ), + child: Center( + child: ClipOval( + child: CommunityAvatar( + name: communityName, + relayUrl: community?.relayUrl, + size: 36, + ), + ), + ), + ), + ) : AndroidExpandingMenuButton( label: 'Community menu', backgroundColor: context.colors.surfaceContainerHighest, @@ -281,6 +308,7 @@ class HomePage extends HookConsumerWidget { ]; }, messagesFilters: (isCollapsed) => MessagesFilters( + useNativeGlass: !recordingFocus.value, isCollapsed: isCollapsed, selected: filter.value, onSelected: (value) { @@ -306,9 +334,33 @@ class HomePage extends HookConsumerWidget { communitySurfaceProgress.value = progress; }, ); + final focusedMessages = Stack( + children: [ + ImageFiltered( + key: const ValueKey('voice-recording-focus'), + enabled: recordingFocus.value, + imageFilter: ui.ImageFilter.blur(sigmaX: 6, sigmaY: 6), + child: ExcludeSemantics( + excluding: recordingFocus.value, + child: messages, + ), + ), + Positioned.fill( + child: IgnorePointer( + ignoring: !recordingFocus.value, + child: ColoredBox( + color: recordingFocus.value + ? context.colors.surface.withValues(alpha: 0.18) + : Colors.transparent, + ), + ), + ), + ], + ); final bottom = mobileTabBarBottom(context); Widget navigationBar(Axis axis) => MessagesNavigationBar( axis: axis, + onRecordingChanged: (value) => recordingFocus.value = value, onSearch: openSearch, agent: ConversationPaneScope( controller: conversations, @@ -330,6 +382,7 @@ class HomePage extends HookConsumerWidget { ], ); return DuoWorkspaceScaffold( + navigationOverflow: 100, navigationBuilder: (context, placement) => _NativeControlsGate( builder: (_, nativeControlsVisible) => wide || @@ -343,7 +396,8 @@ class HomePage extends HookConsumerWidget { MediaQuery.sizeOf(context), strip!.rect.center.dx, ) - - strip.rect.center.dx, + strip.rect.center.dx - + 100, 0, ), child: SafeArea( @@ -460,7 +514,7 @@ class HomePage extends HookConsumerWidget { mobileTabBarBottomGap, ), ), - child: messages, + child: focusedMessages, ), Positioned( left: 0, @@ -495,7 +549,7 @@ class HomePage extends HookConsumerWidget { ); }, ) - : messages, + : focusedMessages, ), ), ), diff --git a/mobile/lib/features/home/messages_filters.dart b/mobile/lib/features/home/messages_filters.dart index f55366cf6a..61d9186a48 100644 --- a/mobile/lib/features/home/messages_filters.dart +++ b/mobile/lib/features/home/messages_filters.dart @@ -13,16 +13,18 @@ class MessagesFilters extends StatelessWidget { this.isCollapsed = false, required this.selected, required this.onSelected, + this.useNativeGlass = true, }); final bool isCollapsed; final String selected; final ValueChanged onSelected; + final bool useNativeGlass; @override Widget build(BuildContext context) => SizedBox( width: double.infinity, child: FilterChipBar( - useNativeGlass: true, + useNativeGlass: useNativeGlass, matchNativeWidths: true, labelOffset: defaultTargetPlatform == TargetPlatform.android ? const Offset(-0.5, -1) diff --git a/mobile/lib/features/home/messages_navigation_bar.dart b/mobile/lib/features/home/messages_navigation_bar.dart index 69aca5fcf4..38781c3328 100644 --- a/mobile/lib/features/home/messages_navigation_bar.dart +++ b/mobile/lib/features/home/messages_navigation_bar.dart @@ -1,5 +1,7 @@ import 'dart:async'; +import '../../shared/widgets/agent_navigation_overlay.dart'; + import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -18,152 +20,212 @@ class MessagesNavigationBar extends HookWidget { required this.onSearch, required this.creationActions, required this.agent, + this.onRecordingChanged, this.axis = Axis.horizontal, }); final Axis axis; final VoidCallback onSearch; final Widget agent; + final ValueChanged? onRecordingChanged; final List<({String label, String symbol, VoidCallback? onPressed})> creationActions; @override Widget build(BuildContext context) { final menuOpen = useState(false); - useEffect(() { - menuOpen.value = false; - return null; - }, [axis]); - if (axis == Axis.vertical) { - return SizedBox( - width: 56, - height: 168 + Grid.xs * 2, - child: Stack( - children: [ - IosMessageCreateButton( - key: const ValueKey('vertical-create-menu'), - mergingNavigation: true, - navigationAxis: Axis.vertical, - onMenuVisibilityChanged: (visible) => menuOpen.value = visible, - actions: creationActions, - dividerBefore: const {2}, - sectionTitles: const {0: 'Solo', 2: 'Team'}, - accessibilityLabel: 'New', - width: 56, - height: 168 + Grid.xs * 2, - plain: false, - ), - Positioned( - top: 0, - width: 56, - height: 56 + Grid.xs / 2, - child: ClipRect( - child: Align( - alignment: Alignment.topCenter, - child: _MenuNudge( - axis: Axis.vertical, - offset: menuOpen.value ? 56 + Grid.xs : 0, - menuOpen: menuOpen.value, - alignment: Alignment.center, - child: _search(context), - ), - ), - ), - ), - Positioned( - bottom: 0, - width: 56, - height: 56 + Grid.xs / 2, - child: ClipRect( - child: Align( - alignment: Alignment.bottomCenter, - child: _MenuNudge( - axis: Axis.vertical, - offset: menuOpen.value ? -56 - Grid.xs : 0, - menuOpen: menuOpen.value, - alignment: Alignment.center, - child: NavigationGlassGroup(child: agent), - ), - ), - ), - ), - ], - ), - ); + final menuMoving = useState(false); + final disableAnimations = MediaQuery.disableAnimationsOf(context); + void menuVisibilityChanged(bool visible) { + if (menuOpen.value == visible) return; + menuMoving.value = !disableAnimations; + menuOpen.value = visible; } - if (defaultTargetPlatform == TargetPlatform.iOS) { - return SizedBox( - width: 256, - height: 56, - child: Stack( - children: [ - IosMessageCreateButton( - key: const ValueKey('horizontal-create-menu'), - mergingNavigation: true, - onMenuVisibilityChanged: (visible) => menuOpen.value = visible, - actions: creationActions, - dividerBefore: const {2}, - sectionTitles: const {0: 'Solo', 2: 'Team'}, - label: 'New', - showIconWithLabel: true, - accessibilityLabel: 'New', + useEffect(() { + menuOpen.value = false; + menuMoving.value = false; + return null; + }, [axis]); + final overlay = useState(false); + Widget hideDuringVoice(Widget child) => ExcludeSemantics( + excluding: overlay.value, + child: IgnorePointer( + ignoring: overlay.value, + child: Opacity(opacity: overlay.value ? 0 : 1, child: child), + ), + ); + return AgentNavigationOverlay( + active: overlay, + menuOpen: menuOpen.value || menuMoving.value, + onRecordingChanged: onRecordingChanged, + child: Builder( + builder: (context) { + if (axis == Axis.vertical) { + return SizedBox( + width: 256, + height: 168 + Grid.xs * 2, + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned( + right: 0, + child: hideDuringVoice( + IosMessageCreateButton( + key: const ValueKey('vertical-create-menu'), + mergingNavigation: true, + navigationAxis: Axis.vertical, + onMenuVisibilityChanged: menuVisibilityChanged, + actions: creationActions, + dividerBefore: const {2}, + sectionTitles: const {0: 'Solo', 2: 'Team'}, + accessibilityLabel: 'New', + width: 56, + height: 168 + Grid.xs * 2, + plain: false, + ), + ), + ), + Positioned( + right: 0, + top: 0, + width: 56, + height: 56 + Grid.xs / 2, + child: ClipRect( + child: Align( + alignment: Alignment.topCenter, + child: _MenuNudge( + axis: Axis.vertical, + offset: menuOpen.value ? 56 + Grid.xs : 0, + menuOpen: menuOpen.value, + alignment: Alignment.center, + child: hideDuringVoice(_search(context)), + ), + ), + ), + ), + Positioned( + bottom: 0, + right: 0, + width: 256, + height: 56, + child: OverflowBox( + alignment: Alignment.centerRight, + minWidth: 0, + maxWidth: 256, + child: Align( + widthFactor: 1, + alignment: Alignment.centerRight, + child: _MenuNudge( + axis: Axis.vertical, + offset: menuOpen.value ? -56 - Grid.xs : 0, + menuOpen: menuOpen.value, + alignment: Alignment.center, + onEnd: () => menuMoving.value = false, + child: NavigationGlassGroup(child: agent), + ), + ), + ), + ), + ], + ), + ); + } + if (defaultTargetPlatform == TargetPlatform.iOS) { + return SizedBox( width: 256, height: 56, - plain: false, - ), - Positioned( - left: 0, - width: 72, - top: 0, - bottom: 0, - child: ClipRect( - child: Align( - alignment: Alignment.centerLeft, - child: _MenuNudge( - offset: menuOpen.value ? 100 : 0, - menuOpen: menuOpen.value, - alignment: Alignment.center, - child: _search(context), + child: Stack( + clipBehavior: Clip.none, + children: [ + hideDuringVoice( + IosMessageCreateButton( + key: const ValueKey('horizontal-create-menu'), + mergingNavigation: true, + onMenuVisibilityChanged: menuVisibilityChanged, + actions: creationActions, + dividerBefore: const {2}, + sectionTitles: const {0: 'Solo', 2: 'Team'}, + label: 'New', + showIconWithLabel: true, + accessibilityLabel: 'New', + width: 256, + height: 56, + plain: false, + ), + ), + Positioned( + left: 0, + width: 72, + top: 0, + bottom: 0, + child: ClipRect( + child: Align( + alignment: Alignment.centerLeft, + child: _MenuNudge( + offset: menuOpen.value ? 100 : 0, + menuOpen: menuOpen.value, + alignment: Alignment.center, + child: hideDuringVoice(_search(context)), + ), + ), + ), + ), + Positioned( + right: 0, + width: 256, + top: 0, + bottom: 0, + child: OverflowBox( + alignment: Alignment.centerRight, + minWidth: 0, + maxWidth: 256, + child: Align( + widthFactor: 1, + alignment: Alignment.centerRight, + child: _MenuNudge( + offset: menuOpen.value ? -100 : 0, + menuOpen: menuOpen.value, + alignment: Alignment.center, + onEnd: () => menuMoving.value = false, + child: NavigationGlassGroup(child: agent), + ), + ), + ), + ), + ], + ), + ); + } + return SizedBox( + width: 224 + Grid.xs * 2, + height: 56, + child: Stack( + clipBehavior: Clip.none, + children: [ + hideDuringVoice( + Builder( + builder: (controlsContext) => Row( + mainAxisSize: MainAxisSize.min, + children: [ + NavigationButtonSurface(child: _search(context)), + const SizedBox(width: Grid.xs), + AndroidExpandingMenuButton( + expansionBoundsContext: controlsContext, + actions: creationActions, + dividerBefore: const {2}, + sectionTitles: const {0: 'Solo', 2: 'Team'}, + ), + const SizedBox(width: Grid.xs), + const SizedBox.square(dimension: 56), + ], + ), ), ), - ), + Positioned(right: 0, top: 0, child: agent), + ], ), - Positioned( - right: 0, - width: 72, - top: 0, - bottom: 0, - child: ClipRect( - child: Align( - alignment: Alignment.centerRight, - child: _MenuNudge( - offset: menuOpen.value ? -100 : 0, - menuOpen: menuOpen.value, - alignment: Alignment.center, - child: NavigationGlassGroup(child: agent), - ), - ), - ), - ), - ], - ), - ); - } - return Builder( - builder: (controlsContext) => Row( - mainAxisSize: MainAxisSize.min, - children: [ - NavigationButtonSurface(child: _search(context)), - const SizedBox(width: Grid.xs), - AndroidExpandingMenuButton( - expansionBoundsContext: controlsContext, - actions: creationActions, - dividerBefore: const {2}, - sectionTitles: const {0: 'Solo', 2: 'Team'}, - ), - const SizedBox(width: Grid.xs), - agent, - ], + ); + }, ), ); } @@ -189,7 +251,9 @@ class _MenuNudge extends StatelessWidget { required this.menuOpen, required this.alignment, required this.child, + this.onEnd, }); + final VoidCallback? onEnd; final double offset; final Axis axis; final bool menuOpen; @@ -207,6 +271,7 @@ class _MenuNudge extends StatelessWidget { child: ExcludeSemantics( excluding: menuOpen, child: AnimatedContainer( + onEnd: onEnd, duration: duration, curve: Curves.easeOutCubic, transformAlignment: alignment, diff --git a/mobile/lib/shared/recording_haptics.dart b/mobile/lib/shared/recording_haptics.dart new file mode 100644 index 0000000000..83994e2cfd --- /dev/null +++ b/mobile/lib/shared/recording_haptics.dart @@ -0,0 +1,37 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +const _channel = MethodChannel('buzz/haptics'); + +Future _native(String method) async { + if (kIsWeb || defaultTargetPlatform != TargetPlatform.iOS) return false; + try { + await _channel.invokeMethod(method); + return true; + } on PlatformException { + return false; + } on MissingPluginException { + return false; + } +} + +/// Warms the iPhone feedback engine before the hold or cancel threshold. +Future prepareRecordingHaptic({bool cancel = false}) async { + await _native(cancel ? 'voicePrepareCancel' : 'voicePrepareStart'); +} + +/// Delivers recording feedback without allowing platform errors to stop capture. +Future recordingHaptic({bool cancel = false}) async { + if (await _native(cancel ? 'voiceCancel' : 'voiceStart')) return; + try { + if (cancel) { + await HapticFeedback.selectionClick(); + } else { + await HapticFeedback.mediumImpact(); + } + } on PlatformException { + // Recording must work even if feedback is unavailable. + } on MissingPluginException { + // Some embedders have no haptic engine. + } +} diff --git a/mobile/lib/shared/transcription/device_transcription.dart b/mobile/lib/shared/transcription/device_transcription.dart new file mode 100644 index 0000000000..c4a1ddf070 --- /dev/null +++ b/mobile/lib/shared/transcription/device_transcription.dart @@ -0,0 +1,31 @@ +import 'package:flutter/services.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:uuid/uuid.dart'; + +/// On-device recognition of a finalized local 16 kHz mono PCM WAV file. +abstract interface class DeviceTranscription { + Future prepare(); + Future transcribe(String path); + Future cancel(); +} + +/// Each capture owns an independent cancellation token. +final deviceTranscriptionProvider = Provider( + (ref) => NativeDeviceTranscription.new, +); + +class NativeDeviceTranscription implements DeviceTranscription { + static const _channel = MethodChannel('buzz/transcription'); + final _id = const Uuid().v4(); + @override + Future prepare() => _channel.invokeMethod('prepare', {'id': _id}); + @override + Future transcribe(String path) async => + (await _channel.invokeMethod('transcribe', { + 'id': _id, + 'path': path, + }))?.trim() ?? + ''; + @override + Future cancel() => _channel.invokeMethod('cancel', {'id': _id}); +} diff --git a/mobile/lib/shared/widgets/agent_navigation_overlay.dart b/mobile/lib/shared/widgets/agent_navigation_overlay.dart new file mode 100644 index 0000000000..757d5fc7bc --- /dev/null +++ b/mobile/lib/shared/widgets/agent_navigation_overlay.dart @@ -0,0 +1,36 @@ +import 'package:flutter/widgets.dart'; + +/// Coordinates the expanded agent control with the shortcuts it covers. +class AgentNavigationOverlay extends InheritedWidget { + const AgentNavigationOverlay({ + super.key, + required this.active, + this.onRecordingChanged, + this.menuOpen = false, + required super.child, + }); + final ValueNotifier active; + final ValueChanged? onRecordingChanged; + final bool menuOpen; + + static bool menuOpenOf(BuildContext context) => + context + .dependOnInheritedWidgetOfExactType() + ?.menuOpen ?? + false; + + static ValueChanged? recordingCallbackOf(BuildContext context) => + context + .dependOnInheritedWidgetOfExactType() + ?.onRecordingChanged; + + static ValueNotifier? maybeOf(BuildContext context) => context + .dependOnInheritedWidgetOfExactType() + ?.active; + + @override + bool updateShouldNotify(AgentNavigationOverlay oldWidget) => + active != oldWidget.active || + menuOpen != oldWidget.menuOpen || + onRecordingChanged != oldWidget.onRecordingChanged; +} diff --git a/mobile/lib/shared/widgets/duo_workspace_scaffold.dart b/mobile/lib/shared/widgets/duo_workspace_scaffold.dart index 0cb9ec3825..01a902b48c 100644 --- a/mobile/lib/shared/widgets/duo_workspace_scaffold.dart +++ b/mobile/lib/shared/widgets/duo_workspace_scaffold.dart @@ -8,9 +8,11 @@ class DuoWorkspaceScaffold extends StatelessWidget { const DuoWorkspaceScaffold({ required this.body, required this.navigationBuilder, + this.navigationOverflow = 0, super.key, }); + final double navigationOverflow; final Widget body; final FoldNavigationBuilder navigationBuilder; @@ -28,7 +30,12 @@ class DuoWorkspaceScaffold extends StatelessWidget { body, if (strip != null) Positioned.fromRect( - rect: strip.rect, + rect: Rect.fromLTRB( + strip.rect.left - navigationOverflow, + strip.rect.top, + strip.rect.right + navigationOverflow, + strip.rect.bottom, + ), child: MediaQuery( data: MediaQuery.of(context).copyWith( padding: EdgeInsets.only( diff --git a/mobile/lib/shared/widgets/filter_chip_bar.dart b/mobile/lib/shared/widgets/filter_chip_bar.dart index 2d58a2a635..1fd958a3b4 100644 --- a/mobile/lib/shared/widgets/filter_chip_bar.dart +++ b/mobile/lib/shared/widgets/filter_chip_bar.dart @@ -260,7 +260,10 @@ class FilterChipBar extends StatelessWidget { final chip = FilterChip( selected: isSelected, showCheckmark: false, - shape: useNativeGlass || defaultTargetPlatform == TargetPlatform.android + shape: + useNativeGlass || + matchNativeWidths || + defaultTargetPlatform == TargetPlatform.android ? const StadiumBorder() : RoundedRectangleBorder( borderRadius: BorderRadius.circular(Radii.lg), diff --git a/mobile/test/features/channels/bestie_transcription_control_test.dart b/mobile/test/features/channels/bestie_transcription_control_test.dart new file mode 100644 index 0000000000..ff00e22222 --- /dev/null +++ b/mobile/test/features/channels/bestie_transcription_control_test.dart @@ -0,0 +1,697 @@ +import 'dart:async'; +import 'package:buzz/features/channels/bestie_transcription_loading_indicator.dart'; +import 'dart:io'; + +import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channels_provider.dart'; +import 'package:buzz/features/channels/channel_management_provider.dart'; +import 'package:buzz/features/channels/send_message_provider.dart'; +import 'package:buzz/shared/me/me_sync.dart'; +import 'package:buzz/shared/relay/relay.dart'; +import 'package:nostr/nostr.dart' as nostr; +import '../../shared/me/me_sync_test.dart' show FakeRelay; +import 'package:buzz/features/channels/bestie_transcription_control.dart'; +import 'package:buzz/features/channels/bestie_transcription_draft.dart'; +import 'package:buzz/features/channels/voice_note_recording.dart'; +import 'package:buzz/features/channels/voice_note_waveform.dart'; +import 'package:buzz/features/channels/bestie_transcription_status.dart'; +import 'package:buzz/features/channels/bestie_transcription_job.dart'; +import 'package:buzz/features/channels/bestie_transcription_surface.dart'; +import 'package:buzz/shared/widgets/app_route_observer.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; +import 'package:buzz/shared/transcription/device_transcription.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:image_picker/image_picker.dart'; + +class _Store extends BestieTranscriptStore { + _Store() : super('test', () async => Directory.systemTemp); + BestieTranscriptDraft? saved; + Completer? retention; + Object? retentionFailure; + Completer? deletion; + @override + Future read() async => saved; + @override + Future retain( + Future recording, + String recipient, + ) async { + await recording; + await retention?.future; + saved = BestieTranscriptDraft( + id: 'one', + recipient: recipient, + audioPath: '/saved.wav', + ); + if (retentionFailure case final failure?) throw failure; + return saved!; + } + + @override + Future update( + BestieTranscriptDraft draft, { + String? text, + NostrEvent? event, + }) async { + return saved = BestieTranscriptDraft( + id: draft.id, + recipient: draft.recipient, + audioPath: draft.audioPath, + text: text ?? saved?.text, + event: event ?? saved?.event, + ); + } + + @override + Future clear({String? id}) async { + await deletion?.future; + saved = null; + } +} + +class _Recorder implements VoiceNoteRecorder { + bool cancelled = false; + int stops = 0; + int starts = 0; + final amplitudes = StreamController.broadcast(); + @override + Stream get levels => amplitudes.stream; + @override + Future start() async { + starts++; + } + + @override + Future stop() async { + stops++; + return VoiceNoteRecording( + file: XFile('/local.wav'), + duration: const Duration(seconds: 3), + waveform: [0.5], + ); + } + + @override + Future cancel() async { + cancelled = true; + } + + @override + Future dispose() async {} +} + +class _Speech implements DeviceTranscription { + final result = Completer(); + Completer? preparation; + Object? preparationFailure; + int transcriptions = 0; + bool cancelled = false; + @override + Future prepare() async { + await preparation?.future; + if (preparationFailure case final failure?) throw failure; + } + + @override + Future transcribe(String path) { + transcriptions++; + return result.future; + } + + @override + Future cancel() async { + cancelled = true; + } +} + +void main() { + late _Store store; + late _Actions actions; + late _Recorder recorder; + late _Speech speech; + late FakeRelay relay; + late MeSync sync; + late ValueNotifier showControl; + late ConversationPaneController pane; + void reset() { + store = _Store(); + actions = _Actions(); + showControl = ValueNotifier(true); + pane = ConversationPaneController(); + recorder = _Recorder(); + speech = _Speech(); + relay = FakeRelay(); + sync = MeSync( + relay, + RelayConfig( + baseUrl: 'https://transcript.test', + nsec: nostr.Keys.generate().nsec, + ), + ); + } + + Future mount(WidgetTester tester) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + meSyncProvider.overrideWithValue(sync), + relaySessionProvider.overrideWith(() => relay), + channelsProvider.overrideWith(_NoChannels.new), + channelActionsProvider.overrideWithValue(actions), + sendMessageProvider.overrideWithValue( + SendMessage( + signedEventRelay: SignedEventRelay( + session: relay, + nsec: sync.config.nsec, + ), + fetchMembers: (_) async => [ + ChannelMember( + pubkey: sync.pubkey, + role: 'member', + joinedAt: DateTime(2026), + ), + ChannelMember( + pubkey: 'a' * 64, + role: 'bot', + joinedAt: DateTime(2026), + ), + ], + readUserCache: () => {}, + addLocalMessage: (_, _) {}, + completeLocalMessage: (_, _) {}, + removeLocalMessage: (_, _) {}, + ), + ), + bestieTranscriptStoreProvider(sync.cacheKey).overrideWithValue(store), + bestieTranscriptionRecorderProvider.overrideWithValue(() => recorder), + deviceTranscriptionProvider.overrideWithValue(() => speech), + ], + child: MaterialApp( + theme: AppTheme.light(), + navigatorObservers: [appRouteObserver], + home: Scaffold( + body: Center( + child: ConversationPaneScope( + controller: pane, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const BestieTranscriptionStatus( + channelId: '11111111-1111-4111-8111-111111111111', + ), + ValueListenableBuilder( + valueListenable: showControl, + builder: (_, visible, _) => !visible + ? const SizedBox() + : BestieTranscriptionControl( + scope: sync.cacheKey, + recipient: 'a' * 64, + child: SizedBox( + width: 56, + height: 56, + child: IconButton( + tooltip: 'Chat with your Bestie', + onPressed: () {}, + icon: const Text('Bestie'), + ), + ), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future hold(WidgetTester tester) async { + final gesture = await tester.startGesture( + tester.getCenter(find.text('Bestie')), + ); + await tester.pump(const Duration(milliseconds: 600)); + if (speech.preparation == null) { + await tester.pumpAndSettle(); + expect(find.byType(VoiceNoteWaveform), findsOneWidget); + final pill = tester.widget( + find.byKey(const ValueKey('default-agent-voice-pill')), + ); + expect(pill.duration, const Duration(milliseconds: 220)); + expect(pill.curve, Curves.easeInOutCubic); + expect(pill.constraints?.maxWidth, 224 + Grid.xs * 2); + } else { + await tester.pump(); + } + return gesture; + } + + testWidgets( + 'release sends finalized text with no media and retries the identical signed event', + (tester) async { + reset(); + relay.loseAcknowledgment = true; + await mount(tester); + final gesture = await hold(tester); + await gesture.up(); + await tester.pump(); + speech.result.complete('Please summarize my open tasks.'); + await tester.pumpAndSettle(); + expect( + relay.events, + hasLength(1), + reason: tester + .widgetList(find.byType(Text)) + .map((t) => t.data) + .join(' | '), + ); + final sent = relay.events.single; + expect(sent.content, 'Please summarize my open tasks.'); + expect(sent.tags.where((tag) => tag.first == 'imeta'), isEmpty); + expect(sent.tags, contains(equals(['p', 'a' * 64]))); + expect(store.saved?.event?.id, sent.id); + relay.loseAcknowledgment = false; + expect(pane.selectedId, isNull); + await tester.tap(find.text('Retry transcript')); + await tester.pumpAndSettle(); + expect(relay.writes, 2); + expect(relay.events.single.id, sent.id); + expect(speech.transcriptions, 1); + expect(store.saved, isNull); + expect(pane.selectedId, '11111111-1111-4111-8111-111111111111'); + await tester.pumpWidget(const SizedBox()); + }, + ); + testWidgets( + 'discard reserves the job before deletion and rejects concurrent retry', + (tester) async { + reset(); + relay.loseAcknowledgment = true; + await mount(tester); + final gesture = await hold(tester); + await gesture.up(); + await tester.pump(); + speech.result.complete('Keep this signed event'); + await tester.pumpAndSettle(); + expect(relay.writes, 1); + final container = ProviderScope.containerOf( + tester.element(find.byType(BestieTranscriptionStatus)), + ); + final job = container.read(bestieTranscriptionJobProvider(sync.cacheKey)); + store.deletion = Completer(); + final discard = job.discard(); + await tester.pump(); + expect(job.busy, isTrue); + await job.retry(); + expect(relay.writes, 1); + expect(store.saved, isNotNull); + store.deletion!.complete(); + await discard; + await tester.pumpAndSettle(); + expect(store.saved, isNull); + expect(job.busy, isFalse); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets( + 'Home recovery cannot retry while discard is deleting its journal', + (tester) async { + reset(); + store.saved = const BestieTranscriptDraft( + id: 'one', + recipient: 'agent', + audioPath: '/saved.wav', + ); + await mount(tester); + final surface = tester.widget( + find.byType(BestieTranscriptionSurface), + ); + store.deletion = Completer(); + final discard = surface.discardPending(); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + await tester.pump(); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await surface.retry(); + expect(speech.transcriptions, 0); + expect(relay.events, isEmpty); + store.deletion!.complete(); + await discard; + await tester.pumpAndSettle(); + expect(store.saved, isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets('retry reserves Home recovery while the destination opens', ( + tester, + ) async { + reset(); + store.saved = BestieTranscriptDraft( + id: 'one', + recipient: 'a' * 64, + audioPath: '/saved.wav', + text: 'Retained text', + ); + await mount(tester); + final surface = tester.widget( + find.byType(BestieTranscriptionSurface), + ); + actions.opening = Completer(); + final retry = surface.retry(); + await tester.pump(); + await surface.discardPending(); + expect(store.saved, isNotNull); + expect(relay.events, isEmpty); + actions.opening!.complete(); + await retry; + await tester.pumpAndSettle(); + expect(relay.events.single.content, 'Retained text'); + expect(store.saved, isNull); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets( + 'unsupported file recognition fails before opening the microphone', + (tester) async { + reset(); + speech.preparationFailure = StateError( + 'Transcribing saved recordings is not available on Android yet.', + ); + await mount(tester); + final gesture = await tester.startGesture( + tester.getCenter(find.text('Bestie')), + ); + await tester.pump(const Duration(milliseconds: 600)); + await gesture.up(); + await tester.pumpAndSettle(); + expect(recorder.starts, 0); + expect(speech.transcriptions, 0); + expect(relay.events, isEmpty); + expect(find.textContaining('not available on Android'), findsWidgets); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets( + 'release retains original recipient and transcribes the saved audio', + (tester) async { + reset(); + await mount(tester); + final gesture = await hold(tester); + expect(find.byType(VoiceNoteWaveform), findsOneWidget); + recorder.amplitudes.add(.8); + await tester.pump(); + store.retention = Completer(); + await gesture.up(); + await tester.pump(); + // Finish the pill collapse while the processing spinner keeps animating. + await tester.pump(const Duration(milliseconds: 220)); + expect(find.byTooltip('Discard transcript'), findsNothing); + expect(find.byType(BestieTranscriptionLoadingIndicator), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect( + tester + .widget( + find.byKey(const ValueKey('default-agent-voice-pill')), + ) + .constraints + ?.maxWidth, + 56, + ); + store.retention!.complete(); + await tester.pump(); + expect(recorder.stops, 1); + expect(store.saved?.recipient, 'a' * 64); + expect(speech.transcriptions, 1); + expect(pane.selectedId, isNull); + await tester.pump(); + expect(find.text('Transcribing…'), findsNothing); + expect(find.byTooltip('Discard transcript'), findsNothing); + expect(find.byType(BestieTranscriptionLoadingIndicator), findsOneWidget); + expect( + tester + .widget( + find.byKey(const ValueKey('default-agent-voice-pill')), + ) + .constraints + ?.maxWidth, + 56, + ); + speech.result.complete(''); + await tester.pumpAndSettle(); + expect(store.saved, isNotNull); + expect(find.text('Retry'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }, + ); + Future expectRetainedAfterInterruption( + WidgetTester tester, { + required Future Function() interrupt, + required Future Function() resume, + bool failAfterJournal = false, + }) async { + reset(); + await mount(tester); + final gesture = await hold(tester); + store.retention = Completer(); + await gesture.up(); + await tester.pump(); + expect(recorder.stops, 1); + await interrupt(); + // Let cancellation's stream teardown settle outside the fake clock. + await tester.runAsync(() => Future(() {})); + await resume(); + await tester.pump(); + // The slow save still owns the slot, so a second hold cannot start. + final second = await tester.startGesture( + tester.getCenter(find.byType(BestieTranscriptionSurface)), + ); + await tester.pump(const Duration(milliseconds: 600)); + await second.up(); + await tester.pump(); + expect(recorder.stops, 1); + expect( + tester + .widget( + find.byType(BestieTranscriptionSurface), + ) + .finalizing, + isTrue, + ); + if (failAfterJournal) store.retentionFailure = StateError('disk'); + store.retention!.complete(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + final surface = tester.widget( + find.byType(BestieTranscriptionSurface), + ); + expect(store.saved, isNotNull); + expect(speech.transcriptions, 0); + expect(surface.hasPending, isTrue); + expect(find.text('Retry transcript'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + if (!speech.result.isCompleted) speech.result.complete(''); + await tester.pumpAndSettle(); + } + + testWidgets( + 'pausing during retention still exposes the saved utterance on resume', + (tester) async { + await expectRetainedAfterInterruption( + tester, + interrupt: () async { + tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.paused, + ); + await tester.pump(); + }, + resume: () async => tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.resumed, + ), + ); + }, + ); + testWidgets( + 'a save that fails after journaling during a pause still offers Retry', + (tester) async { + await expectRetainedAfterInterruption( + tester, + failAfterJournal: true, + interrupt: () async { + tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.paused, + ); + await tester.pump(); + }, + resume: () async => tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.resumed, + ), + ); + }, + ); + testWidgets( + 'pushing a route during retention still exposes the saved utterance on return', + (tester) async { + await expectRetainedAfterInterruption( + tester, + interrupt: () async { + unawaited( + tester + .state(find.byType(Navigator)) + .push( + MaterialPageRoute(builder: (_) => const SizedBox()), + ), + ); + await tester.pump(); + }, + resume: () async => + tester.state(find.byType(Navigator)).pop(), + ); + }, + ); + testWidgets( + 'slide up cancels without transcribing or retaining a recording', + (tester) async { + reset(); + await mount(tester); + final gesture = await hold(tester); + await gesture.moveBy(const Offset(0, -90)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(recorder.cancelled, isTrue); + expect(recorder.stops, 0); + expect(speech.transcriptions, 0); + expect(store.saved, isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + testWidgets( + 'release during model preparation cannot later open the microphone', + (tester) async { + reset(); + speech.preparation = Completer(); + await mount(tester); + final gesture = await hold(tester); + expect(find.text('Preparing speech…'), findsOneWidget); + expect(find.byTooltip('Send transcript'), findsNothing); + expect(find.byType(VoiceNoteWaveform), findsNothing); + await gesture.up(); + await tester.pump(); + expect(recorder.starts, 0); + speech.preparation!.complete(); + await tester.pumpAndSettle(); + expect(speech.cancelled, isTrue); + expect(find.textContaining('Speech was not ready'), findsWidgets); + expect(recorder.stops, 0); + expect(find.byType(VoiceNoteWaveform), findsNothing); + await tester.pumpWidget(const SizedBox()); + }, + ); + testWidgets('disposing the account scope prevents late transcript delivery', ( + tester, + ) async { + reset(); + await mount(tester); + final gesture = await hold(tester); + await gesture.up(); + await tester.pump(); + expect(speech.transcriptions, 1); + await tester.pumpWidget(const SizedBox()); + speech.result.complete('Must remain saved'); + await tester.pumpAndSettle(); + expect(relay.events, isEmpty); + expect(store.saved, isNotNull); + expect(speech.cancelled, isTrue); + expect(tester.takeException(), isNull); + }); + testWidgets( + 'leaving Home during processing sends without reopening the conversation', + (tester) async { + reset(); + await mount(tester); + final gesture = await hold(tester); + await gesture.up(); + await tester.pump(); + showControl.value = false; + await tester.pump(); + speech.result.complete('Finish in the background'); + await tester.pumpAndSettle(); + expect(relay.events.single.content, 'Finish in the background'); + expect(store.saved, isNull); + expect(pane.selectedId, isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets( + 'Home keeps the Bestie loader until successful delivery then opens chat', + (tester) async { + reset(); + await mount(tester); + final gesture = await hold(tester); + await gesture.up(); + await tester.pump(); + expect(speech.transcriptions, 1); + expect(pane.selectedId, isNull); + await tester.pump(); + expect(find.text('Transcribing…'), findsNothing); + expect(find.byTooltip('Discard transcript'), findsNothing); + expect(find.byType(BestieTranscriptionLoadingIndicator), findsOneWidget); + expect( + tester + .widget( + find.byKey(const ValueKey('default-agent-voice-pill')), + ) + .constraints + ?.maxWidth, + 56, + ); + speech.result.complete('Send this in the opened chat'); + await tester.pumpAndSettle(); + expect(relay.events.single.content, 'Send this in the opened chat'); + expect(pane.selectedId, '11111111-1111-4111-8111-111111111111'); + expect(find.byType(BestieTranscriptionLoadingIndicator), findsNothing); + expect(store.saved, isNull); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); +} + +class _NoChannels extends ChannelsNotifier { + @override + Future> build() async => []; +} + +class _Actions implements ChannelActions { + Completer? opening; + @override + Future openDm({ + required List pubkeys, + bool waitForChannelList = true, + }) async { + await opening?.future; + return Channel( + id: '11111111-1111-4111-8111-111111111111', + name: 'Bestie', + channelType: 'dm', + visibility: 'private', + description: '', + createdBy: 'a' * 64, + createdAt: DateTime(2026), + memberCount: 2, + participantPubkeys: pubkeys, + isMember: true, + ); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} diff --git a/mobile/test/features/channels/bestie_transcription_draft_test.dart b/mobile/test/features/channels/bestie_transcription_draft_test.dart new file mode 100644 index 0000000000..fe86dc1704 --- /dev/null +++ b/mobile/test/features/channels/bestie_transcription_draft_test.dart @@ -0,0 +1,128 @@ +import 'dart:async'; +import 'dart:io'; +import 'package:buzz/features/channels/bestie_transcription_draft.dart'; +import 'package:buzz/features/channels/voice_note_recording.dart'; +import 'package:buzz/shared/relay/relay.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:image_picker/image_picker.dart'; + +void main() { + late Directory directory; + late BestieTranscriptStore store; + setUp(() async { + directory = await Directory.systemTemp.createTemp('bestie-transcript-test'); + store = BestieTranscriptStore('account:community', () async => directory); + }); + tearDown(() async { + await directory.delete(recursive: true); + }); + Future recording() async { + final file = await File( + '${directory.path}/capture.wav', + ).writeAsBytes([1, 2, 3]); + return VoiceNoteRecording( + file: XFile(file.path), + duration: const Duration(seconds: 1), + waveform: [.4], + ); + } + + test( + 'finalization reserves recovery across remounts and preserves signed text', + () async { + final completion = Completer(); + final retaining = store.retain(completion.future, 'original-bestie'); + final remounted = BestieTranscriptStore( + 'account:community', + () async => directory, + ); + final recovered = remounted.read(); + completion.complete(await recording()); + final draft = await retaining; + expect((await recovered)?.recipient, 'original-bestie'); + final event = NostrEvent( + id: 'event', + pubkey: 'author', + createdAt: 1, + kind: 9, + tags: [ + ['h', 'conversation'], + ], + content: 'A normal text message', + sig: 'signature', + ); + await store.update(draft, text: event.content, event: event); + final reopened = (await remounted.read())!; + expect(reopened.text, event.content); + expect(reopened.event?.toJson(), event.toJson()); + expect(await File(reopened.audioPath).readAsBytes(), [1, 2, 3]); + expect( + await BestieTranscriptStore( + 'different:community', + () async => directory, + ).read(), + isNull, + ); + await store.clear(id: draft.id); + expect(await remounted.read(), isNull); + expect(await File(reopened.audioPath).exists(), isFalse); + }, + ); + test( + 'a failed audio promotion keeps the original recording recoverable', + () async { + final first = await store.retain(recording(), 'first'); + await store.clear(id: first.id); + // Make promotion fail like a storage error without filling the disk. + await Directory(first.audioPath).create(); + await expectLater( + store.retain(recording(), 'bestie'), + throwsA(isA()), + ); + await Directory(first.audioPath).delete(); + final reopened = (await store.read())!; + expect(reopened.audioPath, '${directory.path}/capture.wav'); + expect(await File(reopened.audioPath).exists(), isTrue); + await store.clear(id: reopened.id); + expect(await File(reopened.audioPath).exists(), isFalse); + expect(await store.read(), isNull); + }, + ); + for (final contents in ['{not json', '[]', '{"source": 1}']) { + test('discard removes a journal that cannot be read: $contents', () async { + final draft = await store.retain(recording(), 'bestie'); + final journal = File(draft.audioPath.replaceFirst(RegExp(r'\.wav$'), '')); + await journal.writeAsString(contents); + await store.clear(); + expect(await journal.exists(), isFalse); + expect(await File(draft.audioPath).exists(), isFalse); + }); + } + test( + 'native failure is observed while directory lookup is still pending', + () async { + final location = Completer(); + final delayed = BestieTranscriptStore('delayed', () => location.future); + final capture = Completer(); + final retaining = delayed.retain(capture.future, 'bestie'); + final observed = expectLater(retaining, throwsStateError); + capture.completeError(StateError('Interrupted capture')); + // Cross an event-loop turn while disk lookup remains deliberately blocked. + await Future(() {}); + location.complete(directory); + await observed; + expect(await delayed.read(), isNull); + }, + ); + test( + 'stale completion cannot clear or overwrite a replacement draft', + () async { + final old = await store.retain(recording(), 'old'); + await store.clear(); + final next = await store.retain(recording(), 'new'); + await store.clear(id: old.id); + await expectLater(store.update(old, text: 'stale'), throwsStateError); + expect((await store.read())?.id, next.id); + }, + ); +} diff --git a/mobile/test/features/channels/channel_detail_page_test.dart b/mobile/test/features/channels/channel_detail_page_test.dart index 3afa61cdda..9e7a7db61c 100644 --- a/mobile/test/features/channels/channel_detail_page_test.dart +++ b/mobile/test/features/channels/channel_detail_page_test.dart @@ -22059,6 +22059,8 @@ class _RecordingOrdinarySender implements SendMessage { List? mentionPubkeys, Channel? channel, List> mediaTags = const [], + FutureOr Function(NostrEvent)? beforePublish, + void Function()? validateDelivery, Future Function()? mayPublish, }) async { sent.add(content); diff --git a/mobile/test/features/channels/notification_reply_test.dart b/mobile/test/features/channels/notification_reply_test.dart index 74a3fa403b..872f6b9c07 100644 --- a/mobile/test/features/channels/notification_reply_test.dart +++ b/mobile/test/features/channels/notification_reply_test.dart @@ -478,6 +478,8 @@ class _RecordingSender implements SendMessage { List? mentionPubkeys, Channel? channel, List> mediaTags = const [], + FutureOr Function(NostrEvent)? beforePublish, + void Function()? validateDelivery, Future Function()? mayPublish, }) async { if (mayPublish != null && !await mayPublish()) { diff --git a/mobile/test/features/home/home_page_test.dart b/mobile/test/features/home/home_page_test.dart index f2bd5c0f4f..3be3662af3 100644 --- a/mobile/test/features/home/home_page_test.dart +++ b/mobile/test/features/home/home_page_test.dart @@ -367,30 +367,26 @@ void main() { await tester.pumpAndSettle(); expect( tester - .widget( - find - .ancestor( - of: find.byTooltip('Search'), - matching: find.byType(IgnorePointer), - ) - .first, + .widgetList( + find.ancestor( + of: find.byTooltip('Search'), + matching: find.byType(IgnorePointer), + ), ) - .ignoring, + .any((widget) => widget.ignoring), isTrue, ); create.onMenuVisibilityChanged!(false); await tester.pumpAndSettle(); expect( tester - .widget( - find - .ancestor( - of: find.byTooltip('Search'), - matching: find.byType(IgnorePointer), - ) - .first, + .widgetList( + find.ancestor( + of: find.byTooltip('Search'), + matching: find.byType(IgnorePointer), + ), ) - .ignoring, + .any((widget) => widget.ignoring), isFalse, ); @@ -503,6 +499,27 @@ void main() { (tester) async { await tester.pumpWidget(await buildHome()); await tester.pumpAndSettle(); + final navigation = find.byType(MessagesNavigationBar); + final mountedNavigation = tester.element(navigation); + final focus = find.byKey(const ValueKey('voice-recording-focus')); + expect(tester.widget(focus).enabled, isFalse); + tester.widget(navigation).onRecordingChanged!( + true, + ); + await tester.pump(); + expect(tester.widget(focus).enabled, isTrue); + expect( + tester + .widget(find.byType(MessagesFilters)) + .useNativeGlass, + isFalse, + ); + expect(tester.element(navigation), same(mountedNavigation)); + tester.widget(navigation).onRecordingChanged!( + false, + ); + await tester.pump(); + expect(tester.widget(focus).enabled, isFalse); expect(find.byTooltip('Messages'), findsNothing); expect(find.byTooltip('Solo'), findsNothing); expect(find.text('Personal workspace'), findsOneWidget);