From 5d7ff271f1b144f2462bf5a401496410f2dedc99 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:21:04 -0600 Subject: [PATCH] Keep voice mode active in background with floating PiP avatar Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- mobile/app.config.ts | 6 +- .../android/src/main/AndroidManifest.xml | 8 + .../botkins/audio/BotkinsVoicePiPModule.kt | 133 +++ .../app/botkins/audio/BotkinsVoiceService.kt | 169 +++ .../botkins-audio/expo-module.config.json | 4 +- mobile/modules/botkins-audio/index.ts | 30 + .../ios/BotkinsAudioModule.swift | 20 + .../ios/BotkinsCallRoutesModule.swift | 3 +- .../ios/BotkinsVoicePiPModule.swift | 968 ++++++++++++++++++ mobile/plugins/withBackgroundVoice.js | 81 ++ mobile/src/features/voice/pip.ts | 197 ++++ mobile/src/features/voice/tts.ts | 2 +- mobile/src/features/voice/useLiveSession.ts | 51 +- mobile/tests/voice-background.test.ts | 314 ++++++ 14 files changed, 1957 insertions(+), 29 deletions(-) create mode 100644 mobile/modules/botkins-audio/android/src/main/java/app/botkins/audio/BotkinsVoicePiPModule.kt create mode 100644 mobile/modules/botkins-audio/android/src/main/java/app/botkins/audio/BotkinsVoiceService.kt create mode 100644 mobile/modules/botkins-audio/ios/BotkinsVoicePiPModule.swift create mode 100644 mobile/plugins/withBackgroundVoice.js create mode 100644 mobile/src/features/voice/pip.ts create mode 100644 mobile/tests/voice-background.test.ts diff --git a/mobile/app.config.ts b/mobile/app.config.ts index 9d3c7849..8dc680b6 100644 --- a/mobile/app.config.ts +++ b/mobile/app.config.ts @@ -31,7 +31,7 @@ const config: ExpoConfig = { ITSAppUsesNonExemptEncryption: false, NSLocalNetworkUsageDescription: "Botkins finds and connects to your computer on your local network.", NSAppleMusicUsageDescription: "Botkins lets your bots search, play, and change Apple Music only when you turn on Music under Device access.", - // A Watch-owned live voice session keeps the iPhone bridge alive while the Watch is in front. + // Supports phone-owned background live voice + Picture-in-Picture and Watch-owned voice sessions. UIBackgroundModes: ["audio"], // What the app may look for on the network: the desktop app's own announcement. NSBonjourServices: ["_botkins._tcp"], @@ -142,12 +142,14 @@ const config: ExpoConfig = { ["@kingstinct/react-native-healthkit", { NSHealthShareUsageDescription: "Botkins reads your Health data for your bots, when you turn on Health under Device access.", NSHealthUpdateUsageDescription: "Botkins writes the Health records you ask a bot to log.", background: false }], // Voice: dictation, reading replies aloud, and live voice. These come after the camera and photo // plugins above, which leave the microphone out, so the microphone's reason is the one set here. - ["expo-audio", { microphonePermission: "Botkins uses the microphone when you dictate a message or talk with a bot.", enableBackgroundRecording: false, enableBackgroundPlayback: true }], + ["expo-audio", { microphonePermission: "Botkins uses the microphone when you dictate a message or talk with a bot.", enableBackgroundRecording: true, enableBackgroundPlayback: true }], ["expo-speech-recognition", { microphonePermission: "Botkins uses the microphone when you dictate a message or talk with a bot.", speechRecognitionPermission: "Botkins turns what you say into the text of a message." }], ["@config-plugins/react-native-webrtc", { cameraPermission: "Botkins uses the camera to scan the pairing code and to take a photo for a message.", microphonePermission: "Botkins uses the microphone when you dictate a message or talk with a bot." }], // The Watch app, Live Activities/widgets, and notification extensions (targets/). "@bacons/apple-targets", "./plugins/withShortcuts.js", + // Background live voice foreground service and Picture-in-Picture config on Android. + "./plugins/withBackgroundVoice.js", // Android release signing with the Play upload key (plugins/withAndroidRelease.js). "./plugins/withAndroidRelease.js", ], diff --git a/mobile/modules/botkins-audio/android/src/main/AndroidManifest.xml b/mobile/modules/botkins-audio/android/src/main/AndroidManifest.xml index 8eb0ea2d..1d20a834 100644 --- a/mobile/modules/botkins-audio/android/src/main/AndroidManifest.xml +++ b/mobile/modules/botkins-audio/android/src/main/AndroidManifest.xml @@ -1,4 +1,12 @@ + + + + + diff --git a/mobile/modules/botkins-audio/android/src/main/java/app/botkins/audio/BotkinsVoicePiPModule.kt b/mobile/modules/botkins-audio/android/src/main/java/app/botkins/audio/BotkinsVoicePiPModule.kt new file mode 100644 index 00000000..f54670c9 --- /dev/null +++ b/mobile/modules/botkins-audio/android/src/main/java/app/botkins/audio/BotkinsVoicePiPModule.kt @@ -0,0 +1,133 @@ +package app.botkins.audio + +import android.app.PictureInPictureParams +import android.content.pm.PackageManager +import android.os.Build +import android.util.Rational +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition +import expo.modules.kotlin.records.Field +import expo.modules.kotlin.records.Record + +class PiPStartOptions : Record { + @Field val name: String = "Botkin" + @Field val status: String = "connecting" + @Field val muted: Boolean = false + @Field val dark: Boolean = false + @Field val colors: List = emptyList() +} + +class PiPUpdateOptions : Record { + @Field val status: String = "listening" + @Field val muted: Boolean = false + @Field val level: Double = 0.0 +} + +class BotkinsVoicePiPModule : Module() { + private var active = false + private var botName = "Botkin" + private var lastStatusText = "" + + private fun isPiPSupported(): Boolean { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return false + val context = appContext.reactContext ?: return false + return context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE) + } + + private fun statusLabel(status: String, muted: Boolean): String { + if (muted) return "Muted" + return when (status) { + "connecting" -> "Connecting…" + "listening" -> "Listening" + "thinking" -> "Thinking…" + "talking" -> "Speaking" + else -> "Live voice" + } + } + + private fun configurePiP(autoEnter: Boolean) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val activity = appContext.currentActivity ?: return + activity.runOnUiThread { + try { + val builder = PictureInPictureParams.Builder().setAspectRatio(Rational(1, 1)) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + builder.setAutoEnterEnabled(autoEnter) + } + activity.setPictureInPictureParams(builder.build()) + } catch (_: Throwable) { + // Device or activity state rejected PiP params. + } + } + } + + private fun enterPiP() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val activity = appContext.currentActivity ?: return + activity.runOnUiThread { + try { + val builder = PictureInPictureParams.Builder().setAspectRatio(Rational(1, 1)) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + builder.setAutoEnterEnabled(true) + } + activity.enterPictureInPictureMode(builder.build()) + } catch (_: Throwable) { + // Ignore if PiP is unavailable in current activity state. + } + } + } + + private fun stopSession() { + if (!active) return + active = false + lastStatusText = "" + appContext.reactContext?.let { BotkinsVoiceService.stop(it) } + configurePiP(autoEnter = false) + } + + override fun definition() = ModuleDefinition { + Name("BotkinsVoicePiP") + + Events("action") + + Function("isSupported") { + isPiPSupported() + } + + AsyncFunction("start") { options: PiPStartOptions -> + val context = appContext.reactContext ?: return@AsyncFunction + botName = options.name.ifBlank { "Botkin" } + val label = statusLabel(options.status, options.muted) + active = true + lastStatusText = label + BotkinsVoiceService.start(context, botName, label) + configurePiP(autoEnter = true) + } + + Function("update") { options: PiPUpdateOptions -> + if (!active) return@Function + val label = statusLabel(options.status, options.muted) + if (label == lastStatusText) return@Function + lastStatusText = label + appContext.reactContext?.let { BotkinsVoiceService.update(it, botName, label) } + } + + AsyncFunction("enter") { + if (active) enterPiP() + } + + AsyncFunction("stop") { + stopSession() + } + + OnUserLeavesActivity { + if (active && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { + enterPiP() + } + } + + OnDestroy { + stopSession() + } + } +} diff --git a/mobile/modules/botkins-audio/android/src/main/java/app/botkins/audio/BotkinsVoiceService.kt b/mobile/modules/botkins-audio/android/src/main/java/app/botkins/audio/BotkinsVoiceService.kt new file mode 100644 index 00000000..c8561cac --- /dev/null +++ b/mobile/modules/botkins-audio/android/src/main/java/app/botkins/audio/BotkinsVoiceService.kt @@ -0,0 +1,169 @@ +package app.botkins.audio + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder + +/** + * Lightweight microphone foreground service that keeps Android audio capture alive while a live + * voice call runs in the background or inside a Picture-in-Picture window. + */ +class BotkinsVoiceService : Service() { + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + ACTION_STOP -> { + running = false + stopForegroundCompat() + stopSelf() + return START_NOT_STICKY + } + ACTION_UPDATE -> { + val name = intent.getStringExtra(EXTRA_NAME) ?: "Botkin" + val status = intent.getStringExtra(EXTRA_STATUS) ?: "Live voice" + val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.notify(NOTIFICATION_ID, buildNotification(this, name, status)) + return START_STICKY + } + else -> { + val name = intent?.getStringExtra(EXTRA_NAME) ?: "Botkin" + val status = intent?.getStringExtra(EXTRA_STATUS) ?: "Live voice" + ensureChannel(this) + val notification = buildNotification(this, name, status) + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + } else { + startForeground(NOTIFICATION_ID, notification) + } + running = true + } catch (_: Throwable) { + // If the system blocks foreground start (e.g. missing mic grant), fail silently without crashing. + running = false + stopSelf() + } + return START_STICKY + } + } + } + + override fun onDestroy() { + running = false + stopForegroundCompat() + super.onDestroy() + } + + private fun stopForegroundCompat() { + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + stopForeground(STOP_FOREGROUND_REMOVE) + } else { + @Suppress("DEPRECATION") + stopForeground(true) + } + } catch (_: Throwable) { + // Already stopped. + } + } + + companion object { + private const val CHANNEL_ID = "botkins_voice_live" + private const val NOTIFICATION_ID = 4107 + private const val ACTION_START = "app.botkins.audio.VOICE_START" + private const val ACTION_UPDATE = "app.botkins.audio.VOICE_UPDATE" + private const val ACTION_STOP = "app.botkins.audio.VOICE_STOP" + private const val EXTRA_NAME = "name" + private const val EXTRA_STATUS = "status" + + @Volatile + private var running = false + + private fun ensureChannel(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + if (manager.getNotificationChannel(CHANNEL_ID) != null) return + val channel = NotificationChannel( + CHANNEL_ID, + "Live voice", + NotificationManager.IMPORTANCE_LOW + ).apply { + description = "Keeps live voice calls active in the background." + setSound(null, null) + enableVibration(false) + setShowBadge(false) + } + manager.createNotificationChannel(channel) + } + + private fun buildNotification(context: Context, name: String, status: String): Notification { + val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply { + flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP + } + val contentIntent = launchIntent?.let { + val pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT or + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0 + PendingIntent.getActivity(context, 0, it, pendingFlags) + } + val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + Notification.Builder(context, CHANNEL_ID) + } else { + @Suppress("DEPRECATION") + Notification.Builder(context) + } + val smallIcon = context.applicationInfo.icon.takeIf { it != 0 } ?: android.R.drawable.ic_btn_speak_now + builder + .setSmallIcon(smallIcon) + .setContentTitle("Live voice with $name") + .setContentText(status) + .setOngoing(true) + .setCategory(Notification.CATEGORY_CALL) + if (contentIntent != null) builder.setContentIntent(contentIntent) + return builder.build() + } + + fun start(context: Context, name: String, status: String) { + val intent = Intent(context, BotkinsVoiceService::class.java).apply { + action = ACTION_START + putExtra(EXTRA_NAME, name) + putExtra(EXTRA_STATUS, status) + } + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + context.startForegroundService(intent) + } else { + context.startService(intent) + } + } catch (_: Throwable) { + // Best effort when background restrictions apply. + } + } + + fun update(context: Context, name: String, status: String) { + if (!running) return + try { + ensureChannel(context) + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.notify(NOTIFICATION_ID, buildNotification(context, name, status)) + } catch (_: Throwable) { + // Ignore if notification updates are unavailable. + } + } + + fun stop(context: Context) { + running = false + try { + context.stopService(Intent(context, BotkinsVoiceService::class.java)) + } catch (_: Throwable) { + // Already stopped. + } + } + } +} diff --git a/mobile/modules/botkins-audio/expo-module.config.json b/mobile/modules/botkins-audio/expo-module.config.json index 2cd8c9c0..7c86f4c5 100644 --- a/mobile/modules/botkins-audio/expo-module.config.json +++ b/mobile/modules/botkins-audio/expo-module.config.json @@ -1,5 +1,5 @@ { "platforms": ["apple", "android"], - "apple": { "modules": ["BotkinsAudioModule", "BotkinsCallRoutesModule"] }, - "android": { "modules": ["app.botkins.audio.BotkinsCallRoutesModule"] } + "apple": { "modules": ["BotkinsAudioModule", "BotkinsCallRoutesModule", "BotkinsVoicePiPModule"] }, + "android": { "modules": ["app.botkins.audio.BotkinsCallRoutesModule", "app.botkins.audio.BotkinsVoicePiPModule"] } } diff --git a/mobile/modules/botkins-audio/index.ts b/mobile/modules/botkins-audio/index.ts index 163d5ab5..a9b586b9 100644 --- a/mobile/modules/botkins-audio/index.ts +++ b/mobile/modules/botkins-audio/index.ts @@ -46,6 +46,36 @@ type CallRoutes = { endCall?(): void; }; +export type VoicePiPAction = { + type: "toggleMute" | "closed" | "restored" | "started"; + muted?: boolean; +}; + +export type VoicePiPStartOptions = { + name: string; + status: string; + muted: boolean; + dark: boolean; + colors: [string, string, string, string]; +}; + +export type VoicePiPUpdateOptions = { + status: string; + muted: boolean; + level: number; +}; + +export type VoicePiPModule = { + isSupported(): boolean; + start(options: VoicePiPStartOptions): Promise; + update(options: VoicePiPUpdateOptions): void; + enter?(): Promise; + stop(): Promise; + addListener(name: "action", listener: (event: VoicePiPAction) => void): EventSubscription; +}; + export const callRoutes = requireOptionalNativeModule("BotkinsCallRoutes"); export const DuplexAudio = requireOptionalNativeModule("BotkinsAudio"); + +export const voicePiP = requireOptionalNativeModule("BotkinsVoicePiP"); diff --git a/mobile/modules/botkins-audio/ios/BotkinsAudioModule.swift b/mobile/modules/botkins-audio/ios/BotkinsAudioModule.swift index 732ac4b9..189b4ae2 100644 --- a/mobile/modules/botkins-audio/ios/BotkinsAudioModule.swift +++ b/mobile/modules/botkins-audio/ios/BotkinsAudioModule.swift @@ -223,6 +223,26 @@ public final class BotkinsAudioModule: Module { do { try self.wire() } catch { self.fail() } } }) + // If iOS resets media services (e.g. while backgrounded), the existing AVAudioEngine and + // AVAudioSession state are invalidated; rebuild from scratch or fail cleanly. + observers.append(center.addObserver(forName: AVAudioSession.mediaServicesWereResetNotification, object: nil, queue: nil) { [weak self] _ in + self?.queue.async { + guard let self, self.running else { return } + let now = Date() + self.restarts = self.restarts.filter { now.timeIntervalSince($0) < 10 } + guard self.restarts.count < 2 else { return self.fail() } + self.restarts.append(now) + let wasMuted = self.muted + let savedRestarts = self.restarts + do { + try self.begin() + self.muted = wasMuted + self.restarts = savedRestarts + } catch { + self.fail() + } + } + }) } /// A piece of microphone sound as 16-bit mono PCM at the wire rate. diff --git a/mobile/modules/botkins-audio/ios/BotkinsCallRoutesModule.swift b/mobile/modules/botkins-audio/ios/BotkinsCallRoutesModule.swift index 1a45fd8a..852c1bb9 100644 --- a/mobile/modules/botkins-audio/ios/BotkinsCallRoutesModule.swift +++ b/mobile/modules/botkins-audio/ios/BotkinsCallRoutesModule.swift @@ -21,12 +21,13 @@ public final class BotkinsCallRoutesModule: Module { }?.uid } - // WebRTC owns the audio engine. Select the port without touching its taps or activation. + // WebRTC owns the audio engine. Select the port and ensure the session stays active in background. Function("setSpeaker") { (speaker: Bool) in let session = AVAudioSession.sharedInstance() var options: AVAudioSession.CategoryOptions = [.allowBluetooth] if speaker { options.insert(.defaultToSpeaker) } try session.setCategory(.playAndRecord, mode: .voiceChat, options: options) + try? session.setActive(true) try session.overrideOutputAudioPort(speaker ? .speaker : .none) } diff --git a/mobile/modules/botkins-audio/ios/BotkinsVoicePiPModule.swift b/mobile/modules/botkins-audio/ios/BotkinsVoicePiPModule.swift new file mode 100644 index 00000000..92fdbf75 --- /dev/null +++ b/mobile/modules/botkins-audio/ios/BotkinsVoicePiPModule.swift @@ -0,0 +1,968 @@ +// Floating Picture-in-Picture animated avatar window for background live voice on iOS. +// +// Uses AVPictureInPictureController with an AVSampleBufferDisplayLayer (iOS 15+, requires only +// UIBackgroundModes: ["audio"] — no CallKit or VoIP entitlements). While a live voice session is +// active, a 1x1 invisible host view feeds crisp 360x360 animated CoreGraphics frames of the bot's +// Bloub character with audio-reactive glow rings, natural eye blinks, and live status pill. +// Swiping home or switching apps automatically pops the floating square avatar window into PiP. +// +// isSupported() -> Bool +// start({ name, status, muted, dark, colors }) +// update({ status, muted, level }) +// enter() +// stop() +// events: action { type: "toggleMute" | "closed" | "restored" | "started", muted?: Bool } +import AVFoundation +import AVKit +import CoreGraphics +import CoreMedia +import CoreVideo +import ExpoModulesCore +import UIKit + +struct PiPStartOptions: Record { + @Field var name: String = "Botkin" + @Field var status: String = "connecting" + @Field var muted: Bool = false + @Field var dark: Bool = false + @Field var colors: [String] = [] +} + +struct PiPUpdateOptions: Record { + @Field var status: String = "listening" + @Field var muted: Bool = false + @Field var level: Double = 0 +} + +public final class BotkinsVoicePiPModule: Module { + private var controller: AnyObject? + + public func definition() -> ModuleDefinition { + Name("BotkinsVoicePiP") + + Events("action") + + Function("isSupported") { () -> Bool in + if #available(iOS 15.0, *) { + return AVPictureInPictureController.isPictureInPictureSupported() + } + return false + } + + AsyncFunction("start") { (options: PiPStartOptions, promise: Promise) in + DispatchQueue.main.async { [weak self] in + guard let self else { + promise.resolve(nil) + return + } + guard #available(iOS 15.0, *), AVPictureInPictureController.isPictureInPictureSupported() else { + promise.resolve(nil) + return + } + let pip = (self.controller as? VoicePiPController) ?? { + let created = VoicePiPController { [weak self] payload in + self?.sendEvent("action", payload) + } + self.controller = created + return created + }() + pip.start(options: options) + promise.resolve(nil) + } + } + + Function("update") { (options: PiPUpdateOptions) in + if #available(iOS 15.0, *) { + (self.controller as? VoicePiPController)?.update(options: options) + } + } + + AsyncFunction("enter") { (promise: Promise) in + DispatchQueue.main.async { [weak self] in + if #available(iOS 15.0, *) { + (self?.controller as? VoicePiPController)?.enter() + } + promise.resolve(nil) + } + } + + AsyncFunction("stop") { (promise: Promise) in + DispatchQueue.main.async { [weak self] in + if #available(iOS 15.0, *) { + (self?.controller as? VoicePiPController)?.stop() + } + self?.controller = nil + promise.resolve(nil) + } + } + + OnDestroy { + let existing = self.controller + self.controller = nil + DispatchQueue.main.async { + if #available(iOS 15.0, *) { + (existing as? VoicePiPController)?.stop() + } + } + } + } +} + +private final class SampleBufferHostView: UIView { + override class var layerClass: AnyClass { AVSampleBufferDisplayLayer.self } + var displayLayer: AVSampleBufferDisplayLayer { layer as! AVSampleBufferDisplayLayer } +} + +private struct RGBA { + let r: CGFloat + let g: CGFloat + let b: CGFloat + let a: CGFloat + + init(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat = 1) { + self.r = r + self.g = g + self.b = b + self.a = a + } + + func alpha(_ a: CGFloat) -> RGBA { RGBA(r, g, b, a) } + + func cgColor(_ space: CGColorSpace) -> CGColor { + CGColor(colorSpace: space, components: [r, g, b, a]) ?? UIColor(red: r, green: g, blue: b, alpha: a).cgColor + } + + func uiColor() -> UIColor { + UIColor(red: r, green: g, blue: b, alpha: a) + } + + func mixed(with other: RGBA, amount: CGFloat) -> RGBA { + let t = max(0, min(1, amount)) + return RGBA( + r + (other.r - r) * t, + g + (other.g - g) * t, + b + (other.b - b) * t, + a + (other.a - a) * t + ) + } + + static func hex(_ value: String, fallback: RGBA) -> RGBA { + var raw = value.trimmingCharacters(in: .whitespacesAndNewlines) + if raw.hasPrefix("#") { raw.removeFirst() } + guard raw.count == 6, let parsed = UInt32(raw, radix: 16) else { return fallback } + return RGBA( + CGFloat((parsed >> 16) & 0xFF) / 255.0, + CGFloat((parsed >> 8) & 0xFF) / 255.0, + CGFloat(parsed & 0xFF) / 255.0 + ) + } +} + +private struct PiPRenderState { + var name: String = "Botkin" + var status: String = "connecting" + var muted: Bool = false + var dark: Bool = false + var shell: RGBA = RGBA(0.78, 0.37, 0.21) // #c75e35 + var accent: RGBA = RGBA(0.47, 0.52, 0.29) // #788449 + var faceplate: RGBA = RGBA(1.0, 0.90, 0.72) // #ffe5b7 + var eyes: RGBA = RGBA(0.31, 0.18, 0.12) // #502e1e + var targetLevel: Double = 0 +} + +@available(iOS 15.0, *) +private final class VoicePiPController: NSObject, AVPictureInPictureControllerDelegate, AVPictureInPictureSampleBufferPlaybackDelegate { + private static let frameSize = 360 + private static let fps = 15 + + private let onAction: ([String: Any]) -> Void + private let renderQueue = DispatchQueue(label: "app.botkins.voice.pip.render", qos: .userInteractive) + private let colorSpace = CGColorSpaceCreateDeviceRGB() + private let stateLock = NSLock() + + private var state = PiPRenderState() + // Main-thread owned UIKit/PiP objects + private var hostView: SampleBufferHostView? + private var pipController: AVPictureInPictureController? + private var timer: DispatchSourceTimer? + private var isRunning = false + private var isPiPActive = false + private var restoring = false + + // renderQueue-owned rendering state (never touched from main thread directly) + private var renderLayer: AVSampleBufferDisplayLayer? + private var renderTimebase: CMTimebase? + private var pixelBufferPool: CVPixelBufferPool? + private var startTime: CFAbsoluteTime = 0 + private var smoothedLevel: Double = 0 + + init(onAction: @escaping ([String: Any]) -> Void) { + self.onAction = onAction + super.init() + } + + // Called on main thread. + func start(options: PiPStartOptions) { + stop() + guard let window = Self.keyWindow() else { return } + + let palette = Self.parsePalette(options.colors) + stateLock.lock() + state = PiPRenderState( + name: options.name.isEmpty ? "Botkin" : options.name, + status: options.status, + muted: options.muted, + dark: options.dark, + shell: palette.0, + accent: palette.1, + faceplate: palette.2, + eyes: palette.3, + targetLevel: 0 + ) + stateLock.unlock() + + // Keep alpha slightly above zero and not hidden so iOS considers the inline layer visible + // and allows automatic PiP entry when backgrounded. + let host = SampleBufferHostView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) + host.backgroundColor = .clear + host.alpha = 0.01 + host.isUserInteractionEnabled = false + host.clipsToBounds = true + window.addSubview(host) + + let displayLayer = host.displayLayer + displayLayer.videoGravity = .resizeAspect + displayLayer.isOpaque = true + + var tb: CMTimebase? + if CMTimebaseCreateWithSourceClock( + allocator: kCFAllocatorDefault, + sourceClock: CMClockGetHostTimeClock(), + timebaseOut: &tb + ) == noErr, let tb { + CMTimebaseSetTime(tb, time: .zero) + CMTimebaseSetRate(tb, rate: 1.0) + displayLayer.controlTimebase = tb + } + + let contentSource = AVPictureInPictureController.ContentSource( + sampleBufferDisplayLayer: displayLayer, + playbackDelegate: self + ) + let pip = AVPictureInPictureController(contentSource: contentSource) + pip.delegate = self + pip.canStartPictureInPictureAutomaticallyFromInline = true + pip.requiresLinearPlayback = true + + self.hostView = host + self.pipController = pip + self.isRunning = true + self.isPiPActive = false + self.restoring = false + + let createdTimebase = tb + // Establish 1:1 aspect ratio immediately before backgrounding. + renderQueue.async { [weak self] in + guard let self else { return } + self.renderLayer = displayLayer + self.renderTimebase = createdTimebase + self.startTime = CFAbsoluteTimeGetCurrent() + self.smoothedLevel = 0 + self.ensurePixelBufferPool() + self.renderFrame() + } + startRenderTimer() + } + + func update(options: PiPUpdateOptions) { + stateLock.lock() + let mutedChanged = state.muted != options.muted + state.status = options.status + state.muted = options.muted + state.targetLevel = max(0, min(1, options.level)) + stateLock.unlock() + + if mutedChanged { + DispatchQueue.main.async { [weak self] in + self?.pipController?.invalidatePlaybackState() + } + renderQueue.async { [weak self] in + self?.renderFrame() + } + } + } + + // Called on main thread. + func enter() { + guard isRunning, let pip = pipController, !pip.isPictureInPictureActive else { return } + pip.startPictureInPicture() + } + + // Called on main thread. + func stop() { + isRunning = false + restoring = false + isPiPActive = false + + stopRenderTimer() + + if let pip = pipController { + pip.canStartPictureInPictureAutomaticallyFromInline = false + if pip.isPictureInPictureActive { + pip.stopPictureInPicture() + } + pip.delegate = nil + } + pipController = nil + + if let host = hostView { + let layer = host.displayLayer + if #available(iOS 17.0, *) { + layer.sampleBufferRenderer.flush() + } else { + layer.flushAndRemoveImage() + } + host.removeFromSuperview() + } + hostView = nil + + renderQueue.async { [weak self] in + self?.renderLayer = nil + self?.renderTimebase = nil + self?.pixelBufferPool = nil + self?.smoothedLevel = 0 + } + } + + private func startRenderTimer() { + stopRenderTimer() + let source = DispatchSource.makeTimerSource(queue: renderQueue) + let intervalMs = 1000 / Self.fps + source.schedule(deadline: .now() + .milliseconds(intervalMs), repeating: .milliseconds(intervalMs), leeway: .milliseconds(16)) + source.setEventHandler { [weak self] in + self?.renderFrame() + } + timer = source + source.resume() + } + + private func stopRenderTimer() { + timer?.cancel() + timer = nil + } + + // MARK: - AVPictureInPictureControllerDelegate + + func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { + isPiPActive = true + restoring = false + onAction(["type": "started"]) + renderQueue.async { [weak self] in + self?.renderFrame() + } + } + + func pictureInPictureController( + _ pictureInPictureController: AVPictureInPictureController, + restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void + ) { + restoring = true + onAction(["type": "restored"]) + completionHandler(true) + } + + func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { + let wasRestoring = restoring + restoring = false + isPiPActive = false + if !wasRestoring && isRunning { + onAction(["type": "closed"]) + } + } + + func pictureInPictureController( + _ pictureInPictureController: AVPictureInPictureController, + failedToStartPictureInPictureWithError error: Error + ) { + isPiPActive = false + } + + // MARK: - AVPictureInPictureSampleBufferPlaybackDelegate + + func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, setPlaying playing: Bool) { + let nextMuted = !playing + stateLock.lock() + state.muted = nextMuted + stateLock.unlock() + pictureInPictureController.invalidatePlaybackState() + onAction(["type": "toggleMute", "muted": nextMuted]) + renderQueue.async { [weak self] in + self?.renderFrame() + } + } + + func pictureInPictureControllerTimeRangeForPlayback(_ pictureInPictureController: AVPictureInPictureController) -> CMTimeRange { + CMTimeRange(start: .zero, duration: .positiveInfinity) + } + + func pictureInPictureControllerIsPlaybackPaused(_ pictureInPictureController: AVPictureInPictureController) -> Bool { + stateLock.lock() + let muted = state.muted + stateLock.unlock() + return muted + } + + func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, didTransitionToRenderSize newRenderSize: CMVideoDimensions) {} + + func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, skipByInterval skipInterval: CMTime, completion completionHandler: @escaping () -> Void) { + completionHandler() + } + + // MARK: - Frame Rendering (renderQueue) + + private func ensurePixelBufferPool() { + guard pixelBufferPool == nil else { return } + let attributes: [CFString: Any] = [ + kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA, + kCVPixelBufferWidthKey: Self.frameSize, + kCVPixelBufferHeightKey: Self.frameSize, + kCVPixelBufferCGImageCompatibilityKey: true, + kCVPixelBufferCGBitmapContextCompatibilityKey: true, + kCVPixelBufferIOSurfacePropertiesKey: [:] as [String: Any], + ] + var pool: CVPixelBufferPool? + CVPixelBufferPoolCreate(kCFAllocatorDefault, nil, attributes as CFDictionary, &pool) + pixelBufferPool = pool + } + + private func renderFrame() { + guard let displayLayer = renderLayer, let pool = pixelBufferPool else { return } + + if #available(iOS 17.0, *) { + if displayLayer.sampleBufferRenderer.status == .failed { + displayLayer.sampleBufferRenderer.flush() + } + guard displayLayer.sampleBufferRenderer.isReadyForMoreMediaData else { return } + } else { + if displayLayer.status == .failed { + displayLayer.flush() + } + guard displayLayer.isReadyForMoreMediaData else { return } + } + + var pixelBuffer: CVPixelBuffer? + guard CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool, &pixelBuffer) == kCVReturnSuccess, + let buffer = pixelBuffer else { return } + + stateLock.lock() + let snapshot = state + stateLock.unlock() + + let elapsed = max(0, CFAbsoluteTimeGetCurrent() - startTime) + let activeTarget = snapshot.muted ? 0 : snapshot.targetLevel + smoothedLevel += (activeTarget - smoothedLevel) * 0.35 + + drawAvatarFrame(into: buffer, state: snapshot, elapsed: elapsed, level: smoothedLevel) + + guard let sampleBuffer = makeSampleBuffer(from: buffer, elapsed: elapsed) else { return } + if #available(iOS 17.0, *) { + displayLayer.sampleBufferRenderer.enqueue(sampleBuffer) + } else { + displayLayer.enqueue(sampleBuffer) + } + } + + private func makeSampleBuffer(from pixelBuffer: CVPixelBuffer, elapsed: Double) -> CMSampleBuffer? { + var formatDescription: CMVideoFormatDescription? + guard CMVideoFormatDescriptionCreateForImageBuffer( + allocator: kCFAllocatorDefault, + imageBuffer: pixelBuffer, + formatDescriptionOut: &formatDescription + ) == noErr, let format = formatDescription else { return nil } + + let pts = renderTimebase.map { CMTimebaseGetTime($0) } ?? CMTime(seconds: elapsed, preferredTimescale: 600) + var timing = CMSampleTimingInfo( + duration: CMTime(value: 1, timescale: CMTimeScale(Self.fps)), + presentationTimeStamp: pts, + decodeTimeStamp: .invalid + ) + var sampleBuffer: CMSampleBuffer? + guard CMSampleBufferCreateForImageBuffer( + allocator: kCFAllocatorDefault, + imageBuffer: pixelBuffer, + dataReady: true, + makeDataReadyCallback: nil, + refcon: nil, + formatDescription: format, + sampleTiming: &timing, + sampleBufferOut: &sampleBuffer + ) == noErr, let sample = sampleBuffer else { return nil } + + if let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: true), + CFArrayGetCount(attachments) > 0, + let raw = CFArrayGetValueAtIndex(attachments, 0) { + let dict = unsafeBitCast(raw, to: CFMutableDictionary.self) + CFDictionarySetValue( + dict, + Unmanaged.passUnretained(kCMSampleAttachmentKey_DisplayImmediately).toOpaque(), + Unmanaged.passUnretained(kCFBooleanTrue).toOpaque() + ) + } + return sample + } + + private func drawAvatarFrame(into pixelBuffer: CVPixelBuffer, state: PiPRenderState, elapsed: Double, level: Double) { + CVPixelBufferLockBaseAddress(pixelBuffer, []) + defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, []) } + + guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { return } + let size = Self.frameSize + let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer) + let bitmapInfo = CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue + guard let ctx = CGContext( + data: baseAddress, + width: size, + height: size, + bitsPerComponent: 8, + bytesPerRow: bytesPerRow, + space: colorSpace, + bitmapInfo: bitmapInfo + ) else { return } + + // Flip to top-left origin so geometry and UIKit text drawing share the same coordinate space. + ctx.translateBy(x: 0, y: CGFloat(size)) + ctx.scaleBy(x: 1, y: -1) + ctx.setAllowsAntialiasing(true) + ctx.setShouldAntialias(true) + + let rect = CGRect(x: 0, y: 0, width: size, height: size) + let center = CGPoint(x: 180, y: 150) + let t = CGFloat(elapsed) + let lvl = CGFloat(max(0, min(1, level))) + let effectiveStatus = state.muted ? "muted" : state.status + + // 1. Background gradient card + let bgTop = state.dark ? RGBA(0.125, 0.106, 0.094) : RGBA(0.984, 0.945, 0.871) + let bgBottom = state.dark ? RGBA(0.078, 0.067, 0.059) : RGBA(0.945, 0.890, 0.796) + if let bgGradient = CGGradient( + colorsSpace: colorSpace, + colors: [bgTop.cgColor(colorSpace), bgBottom.cgColor(colorSpace)] as CFArray, + locations: [0, 1] + ) { + ctx.drawLinearGradient(bgGradient, start: CGPoint(x: 180, y: 0), end: CGPoint(x: 180, y: 360), options: []) + } + + // Soft radial aura behind the Bloub character + let auraColor = effectiveStatus == "listening" ? state.accent : state.shell + let auraAlpha: CGFloat = effectiveStatus == "muted" ? 0.08 : (state.dark ? 0.24 + lvl * 0.14 : 0.15 + lvl * 0.12) + if let aura = CGGradient( + colorsSpace: colorSpace, + colors: [auraColor.alpha(auraAlpha).cgColor(colorSpace), auraColor.alpha(0).cgColor(colorSpace)] as CFArray, + locations: [0, 1] + ) { + ctx.drawRadialGradient( + aura, + startCenter: center, + startRadius: 20, + endCenter: center, + endRadius: 155, + options: [] + ) + } + + // 2. State-driven glow rings + drawStatusRings(ctx: ctx, center: center, state: state, effectiveStatus: effectiveStatus, t: t, level: lvl) + + // 3. Animated Bloub character + let bobAmp: CGFloat = effectiveStatus == "talking" ? 4.5 + lvl * 4.5 : (effectiveStatus == "listening" ? 3.2 : 2.0) + let bobY = sin(t * (effectiveStatus == "talking" ? 4.2 : 2.2)) * bobAmp + let headCenter = CGPoint(x: center.x, y: center.y + bobY) + let scalePulse: CGFloat = effectiveStatus == "talking" ? 1.0 + lvl * 0.045 : 1.0 + sin(t * 2.2) * 0.012 + + drawBloubCharacter( + ctx: ctx, + center: headCenter, + scale: scalePulse, + state: state, + effectiveStatus: effectiveStatus, + t: t, + level: lvl + ) + + // 4. Muted microphone pill badge in top-right corner + if state.muted { + drawMutedBadge(ctx: ctx, dark: state.dark) + } + + // 5. Bottom name + live status pill + drawStatusPill(ctx: ctx, state: state, effectiveStatus: effectiveStatus, t: t, level: lvl) + + // Subtle inner frame border + ctx.setStrokeColor((state.dark ? RGBA(1, 1, 1, 0.08) : RGBA(0.26, 0.16, 0.12, 0.08)).cgColor(colorSpace)) + ctx.setLineWidth(2) + ctx.stroke(rect.insetBy(dx: 1, dy: 1)) + } + + private func drawStatusRings( + ctx: CGContext, + center: CGPoint, + state: PiPRenderState, + effectiveStatus: String, + t: CGFloat, + level: CGFloat + ) { + ctx.saveGState() + defer { ctx.restoreGState() } + + let listenGreen = RGBA(0.30, 0.69, 0.44) + switch effectiveStatus { + case "talking": + let r1 = 92 + level * 22 + sin(t * 5.0) * 3 + let r2 = 108 + level * 32 + cos(t * 4.0) * 3 + ctx.setStrokeColor(state.shell.alpha(0.55 + level * 0.30).cgColor(colorSpace)) + ctx.setLineWidth(4.5) + ctx.strokeEllipse(in: CGRect(x: center.x - r1, y: center.y - r1, width: r1 * 2, height: r1 * 2)) + + ctx.setStrokeColor(state.accent.alpha(0.26 + level * 0.28).cgColor(colorSpace)) + ctx.setLineWidth(3.0) + ctx.strokeEllipse(in: CGRect(x: center.x - r2, y: center.y - r2, width: r2 * 2, height: r2 * 2)) + + case "listening": + let breath = (sin(t * 2.5) + 1) * 0.5 + let r1 = 93 + breath * 6 + level * 18 + let r2 = 109 + breath * 8 + level * 24 + ctx.setStrokeColor(listenGreen.alpha(0.42 + level * 0.35).cgColor(colorSpace)) + ctx.setLineWidth(4.0) + ctx.strokeEllipse(in: CGRect(x: center.x - r1, y: center.y - r1, width: r1 * 2, height: r1 * 2)) + + ctx.setStrokeColor(state.accent.alpha(0.18 + breath * 0.16 + level * 0.22).cgColor(colorSpace)) + ctx.setLineWidth(2.5) + ctx.strokeEllipse(in: CGRect(x: center.x - r2, y: center.y - r2, width: r2 * 2, height: r2 * 2)) + + case "connecting", "thinking": + let orbitR: CGFloat = 100 + ctx.translateBy(x: center.x, y: center.y) + ctx.rotate(by: t * 1.45) + ctx.setStrokeColor(state.accent.alpha(0.45).cgColor(colorSpace)) + ctx.setLineWidth(3.5) + ctx.setLineCap(.round) + ctx.setLineDash(phase: 0, lengths: [16, 14]) + ctx.strokeEllipse(in: CGRect(x: -orbitR, y: -orbitR, width: orbitR * 2, height: orbitR * 2)) + ctx.setLineDash(phase: 0, lengths: []) + + // Two orbiting sparkles + ctx.setFillColor(state.shell.alpha(0.9).cgColor(colorSpace)) + ctx.fillEllipse(in: CGRect(x: orbitR - 6, y: -6, width: 12, height: 12)) + ctx.setFillColor(state.accent.alpha(0.85).cgColor(colorSpace)) + ctx.fillEllipse(in: CGRect(x: -orbitR - 5, y: -5, width: 10, height: 10)) + + default: + // Muted: calm dimmed ring + let r: CGFloat = 92 + let mutedRing = state.dark ? RGBA(0.65, 0.60, 0.56, 0.22) : RGBA(0.40, 0.32, 0.28, 0.18) + ctx.setStrokeColor(mutedRing.cgColor(colorSpace)) + ctx.setLineWidth(3.0) + ctx.strokeEllipse(in: CGRect(x: center.x - r, y: center.y - r, width: r * 2, height: r * 2)) + } + } + + private func drawBloubCharacter( + ctx: CGContext, + center: CGPoint, + scale: CGFloat, + state: PiPRenderState, + effectiveStatus: String, + t: CGFloat, + level: CGFloat + ) { + ctx.saveGState() + defer { ctx.restoreGState() } + + ctx.translateBy(x: center.x, y: center.y) + ctx.scaleBy(x: scale, y: scale) + + // Soft ground shadow + ctx.setFillColor((state.dark ? RGBA(0, 0, 0, 0.38) : RGBA(0.26, 0.16, 0.12, 0.14)).cgColor(colorSpace)) + ctx.fillEllipse(in: CGRect(x: -60, y: 66, width: 120, height: 22)) + + // Top-side Bloub ear / sprout accents + ctx.saveGState() + ctx.setFillColor(state.accent.cgColor(colorSpace)) + ctx.fillEllipse(in: CGRect(x: -66, y: -68, width: 32, height: 32)) + ctx.fillEllipse(in: CGRect(x: 34, y: -68, width: 32, height: 32)) + // Top crest nub + let nubTilt = sin(t * 2.6) * 0.10 + ctx.rotate(by: nubTilt) + ctx.fillEllipse(in: CGRect(x: -14, y: -88, width: 28, height: 26)) + ctx.restoreGState() + + // Main rounded Bloub shell body + let shellRect = CGRect(x: -74, y: -68, width: 148, height: 138) + let shellPath = UIBezierPath(roundedRect: shellRect, cornerRadius: 62).cgPath + ctx.saveGState() + ctx.addPath(shellPath) + ctx.clip() + + let shellLight = state.shell.mixed(with: RGBA(1, 1, 1), amount: 0.18) + let shellDark = state.shell.mixed(with: RGBA(0.12, 0.07, 0.05), amount: 0.22) + if let shellGrad = CGGradient( + colorsSpace: colorSpace, + colors: [shellLight.cgColor(colorSpace), state.shell.cgColor(colorSpace), shellDark.cgColor(colorSpace)] as CFArray, + locations: [0, 0.55, 1] + ) { + ctx.drawLinearGradient(shellGrad, start: CGPoint(x: -20, y: -74), end: CGPoint(x: 24, y: 74), options: []) + } + + // Subtle specular sheen on upper-left of shell + ctx.setFillColor(RGBA(1, 1, 1, 0.16).cgColor(colorSpace)) + ctx.fillEllipse(in: CGRect(x: -54, y: -56, width: 52, height: 24)) + ctx.restoreGState() + + // Warm faceplate oval + let faceRect = CGRect(x: -54, y: -38, width: 108, height: 84) + let facePath = UIBezierPath(roundedRect: faceRect, cornerRadius: 40).cgPath + ctx.saveGState() + ctx.addPath(facePath) + ctx.setFillColor(state.faceplate.cgColor(colorSpace)) + ctx.fillPath() + ctx.addPath(facePath) + ctx.setStrokeColor(state.eyes.alpha(0.12).cgColor(colorSpace)) + ctx.setLineWidth(2.0) + ctx.strokePath() + ctx.restoreGState() + + // Natural periodic blink (~every 3.5 seconds, lasting ~160ms) + let blinkCycle = t.truncatingRemainder(dividingBy: 3.5) + let blinkAmount: CGFloat + if blinkCycle > 3.34 { + let progress = (blinkCycle - 3.34) / 0.16 + blinkAmount = sin(progress * .pi) + } else { + blinkAmount = 0 + } + + // Subtle horizontal gaze shift when thinking/connecting + let gazeX: CGFloat = (effectiveStatus == "thinking" || effectiveStatus == "connecting") ? sin(t * 1.8) * 5.0 : 0 + let gazeY: CGFloat = (effectiveStatus == "thinking" || effectiveStatus == "connecting") ? -3.0 : 0 + + // Eyes + let eyeBaseW: CGFloat = 14 + let eyeBaseH: CGFloat = effectiveStatus == "muted" ? 11 : 18 + let eyeH = max(2.5, eyeBaseH * (1 - blinkAmount * 0.88)) + let eyeY: CGFloat = -6 + gazeY + let leftX: CGFloat = -22 + gazeX + let rightX: CGFloat = 22 + gazeX + + ctx.setFillColor(state.eyes.cgColor(colorSpace)) + if effectiveStatus == "talking" && level > 0.45 && blinkAmount < 0.2 { + // Expressive happy talking eyes (curved arcs) + ctx.setStrokeColor(state.eyes.cgColor(colorSpace)) + ctx.setLineWidth(4.5) + ctx.setLineCap(.round) + for ex in [leftX, rightX] { + ctx.beginPath() + ctx.move(to: CGPoint(x: ex - 8, y: eyeY + 2)) + ctx.addQuadCurve(to: CGPoint(x: ex + 8, y: eyeY + 2), control: CGPoint(x: ex, y: eyeY - 9)) + ctx.strokePath() + } + } else { + for ex in [leftX, rightX] { + ctx.fillEllipse(in: CGRect(x: ex - eyeBaseW / 2, y: eyeY - eyeH / 2, width: eyeBaseW, height: eyeH)) + if eyeH > 8 { + // Tiny highlight glint + ctx.setFillColor(RGBA(1, 1, 1, 0.72).cgColor(colorSpace)) + ctx.fillEllipse(in: CGRect(x: ex - 3.5, y: eyeY - eyeH / 2 + 2.5, width: 4.5, height: 4.5)) + ctx.setFillColor(state.eyes.cgColor(colorSpace)) + } + } + } + + // Soft rosy cheek dots + let cheekColor = state.shell.alpha(0.22) + ctx.setFillColor(cheekColor.cgColor(colorSpace)) + ctx.fillEllipse(in: CGRect(x: -44, y: 6, width: 14, height: 9)) + ctx.fillEllipse(in: CGRect(x: 30, y: 6, width: 14, height: 9)) + + // Expressive mouth + let mouthY: CGFloat = 20 + ctx.setStrokeColor(state.eyes.cgColor(colorSpace)) + ctx.setFillColor(state.eyes.cgColor(colorSpace)) + ctx.setLineWidth(3.8) + ctx.setLineCap(.round) + + switch effectiveStatus { + case "talking": + let openH = 6 + level * 15 + abs(sin(t * 11.0)) * (2 + level * 5) + let openW = 14 + level * 10 + let mouthRect = CGRect(x: -openW / 2, y: mouthY - openH / 2 + 1, width: openW, height: openH) + let path = UIBezierPath(roundedRect: mouthRect, cornerRadius: openH / 2).cgPath + ctx.addPath(path) + ctx.fillPath() + // Warm accent tongue hint when wide open + if openH > 12 { + ctx.setFillColor(state.shell.mixed(with: RGBA(1, 0.65, 0.6), amount: 0.45).cgColor(colorSpace)) + ctx.fillEllipse(in: CGRect(x: -openW * 0.28, y: mouthY + openH * 0.08, width: openW * 0.56, height: openH * 0.34)) + } + + case "connecting", "thinking": + let shift = sin(t * 2.4) * 2.0 + ctx.fillEllipse(in: CGRect(x: -5.5 + shift, y: mouthY - 4, width: 11, height: 8)) + + case "muted": + ctx.beginPath() + ctx.move(to: CGPoint(x: -10, y: mouthY + 1)) + ctx.addLine(to: CGPoint(x: 10, y: mouthY + 1)) + ctx.strokePath() + + default: + // Listening: friendly warm smile + ctx.beginPath() + ctx.move(to: CGPoint(x: -13, y: mouthY - 1)) + ctx.addQuadCurve(to: CGPoint(x: 13, y: mouthY - 1), control: CGPoint(x: 0, y: mouthY + 10)) + ctx.strokePath() + } + } + + private func drawMutedBadge(ctx: CGContext, dark: Bool) { + ctx.saveGState() + defer { ctx.restoreGState() } + + let badgeRect = CGRect(x: 292, y: 20, width: 48, height: 48) + let bg = dark ? RGBA(0.82, 0.27, 0.25, 0.92) : RGBA(0.78, 0.24, 0.22, 0.95) + ctx.setFillColor(bg.cgColor(colorSpace)) + ctx.fillEllipse(in: badgeRect) + + // Minimal mic + diagonal slash glyph in white + let cx = badgeRect.midX + let cy = badgeRect.midY + ctx.setStrokeColor(RGBA(1, 1, 1, 0.96).cgColor(colorSpace)) + ctx.setFillColor(RGBA(1, 1, 1, 0.96).cgColor(colorSpace)) + ctx.setLineWidth(2.8) + ctx.setLineCap(.round) + + let micBody = UIBezierPath(roundedRect: CGRect(x: cx - 5, y: cy - 11, width: 10, height: 15), cornerRadius: 5).cgPath + ctx.addPath(micBody) + ctx.fillPath() + + ctx.beginPath() + ctx.addArc(center: CGPoint(x: cx, y: cy - 1), radius: 9.5, startAngle: 0.15, endAngle: .pi - 0.15, clockwise: false) + ctx.strokePath() + + ctx.beginPath() + ctx.move(to: CGPoint(x: cx, y: cy + 8.5)) + ctx.addLine(to: CGPoint(x: cx, y: cy + 13)) + ctx.strokePath() + + // Diagonal slash + ctx.setLineWidth(3.2) + ctx.beginPath() + ctx.move(to: CGPoint(x: cx - 12, y: cy - 12)) + ctx.addLine(to: CGPoint(x: cx + 12, y: cy + 12)) + ctx.strokePath() + } + + private func drawStatusPill( + ctx: CGContext, + state: PiPRenderState, + effectiveStatus: String, + t: CGFloat, + level: CGFloat + ) { + let statusLabel: String + let dotColor: RGBA + switch effectiveStatus { + case "listening": + statusLabel = "Listening" + dotColor = RGBA(0.30, 0.72, 0.45) + case "talking": + statusLabel = "Speaking" + dotColor = state.shell + case "thinking": + statusLabel = "Thinking" + dotColor = RGBA(0.91, 0.66, 0.27) + case "connecting": + statusLabel = "Connecting" + dotColor = RGBA(0.91, 0.66, 0.27) + case "muted": + statusLabel = "Muted" + dotColor = RGBA(0.84, 0.31, 0.29) + default: + statusLabel = "Live" + dotColor = state.accent + } + + let trimmedName = state.name.count > 14 ? String(state.name.prefix(13)) + "…" : state.name + let title = "\(trimmedName) · \(statusLabel)" + let textColor = state.dark ? RGBA(0.96, 0.94, 0.90).uiColor() : RGBA(0.24, 0.16, 0.12).uiColor() + let font = UIFont.systemFont(ofSize: 18, weight: .semibold) + let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: textColor] + let attributed = NSAttributedString(string: title, attributes: attrs) + let textSize = attributed.size() + + let dotDiameter: CGFloat = 10 + let padX: CGFloat = 18 + let gap: CGFloat = 9 + let pillHeight: CGFloat = 42 + let pillWidth = min(332, ceil(textSize.width) + padX * 2 + dotDiameter + gap) + let pillRect = CGRect(x: (360 - pillWidth) / 2, y: 294, width: pillWidth, height: pillHeight) + let pillPath = UIBezierPath(roundedRect: pillRect, cornerRadius: pillHeight / 2).cgPath + + ctx.saveGState() + let pillBg = state.dark ? RGBA(0.18, 0.16, 0.14, 0.90) : RGBA(1.0, 0.985, 0.955, 0.92) + let pillBorder = state.dark ? RGBA(1, 1, 1, 0.12) : RGBA(0.26, 0.16, 0.12, 0.12) + ctx.addPath(pillPath) + ctx.setFillColor(pillBg.cgColor(colorSpace)) + ctx.fillPath() + ctx.addPath(pillPath) + ctx.setStrokeColor(pillBorder.cgColor(colorSpace)) + ctx.setLineWidth(1.5) + ctx.strokePath() + + // Live status dot + let dotPulse: CGFloat = effectiveStatus == "muted" ? 0.9 : (0.65 + 0.35 * ((sin(t * 3.5) + 1) * 0.5) + level * 0.15) + ctx.setFillColor(dotColor.alpha(min(1, dotPulse)).cgColor(colorSpace)) + let dotX = pillRect.minX + padX + let dotY = pillRect.midY - dotDiameter / 2 + ctx.fillEllipse(in: CGRect(x: dotX, y: dotY, width: dotDiameter, height: dotDiameter)) + ctx.restoreGState() + + // Draw label text + UIGraphicsPushContext(ctx) + defer { UIGraphicsPopContext() } + let textX = dotX + dotDiameter + gap + let maxTextWidth = max(40, pillRect.maxX - padX - textX) + let textRect = CGRect( + x: textX, + y: pillRect.midY - textSize.height / 2, + width: maxTextWidth, + height: textSize.height + ) + attributed.draw(in: textRect) + } + + private static func parsePalette(_ colors: [String]) -> (RGBA, RGBA, RGBA, RGBA) { + let defaultShell = RGBA(0.78, 0.37, 0.21) // #c75e35 + let defaultAccent = RGBA(0.47, 0.52, 0.29) // #788449 + let defaultFace = RGBA(1.0, 0.90, 0.72) // #ffe5b7 + let defaultEyes = RGBA(0.31, 0.18, 0.12) // #502e1e + guard colors.count >= 4 else { + return (defaultShell, defaultAccent, defaultFace, defaultEyes) + } + return ( + RGBA.hex(colors[0], fallback: defaultShell), + RGBA.hex(colors[1], fallback: defaultAccent), + RGBA.hex(colors[2], fallback: defaultFace), + RGBA.hex(colors[3], fallback: defaultEyes) + ) + } + + private static func keyWindow() -> UIWindow? { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + let foreground = scenes.filter { + $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive + } + return foreground.flatMap(\.windows).first(where: \.isKeyWindow) + ?? foreground.flatMap(\.windows).first + ?? scenes.flatMap(\.windows).first + } +} diff --git a/mobile/plugins/withBackgroundVoice.js b/mobile/plugins/withBackgroundVoice.js new file mode 100644 index 00000000..a7b257e1 --- /dev/null +++ b/mobile/plugins/withBackgroundVoice.js @@ -0,0 +1,81 @@ +// Configures Android for background live voice and Picture-in-Picture: +// - MainActivity supports PiP and handles PiP layout config changes without restarting +// - Registers foreground-service permissions and BotkinsVoiceService (microphone type) +const { AndroidConfig, withAndroidManifest } = require("expo/config-plugins"); + +const SERVICE_NAME = "app.botkins.audio.BotkinsVoiceService"; +const PIP_CONFIG_CHANGES = ["screenSize", "smallestScreenSize", "screenLayout", "orientation"]; +const REQUIRED_PERMISSIONS = [ + "android.permission.FOREGROUND_SERVICE", + "android.permission.FOREGROUND_SERVICE_MICROPHONE", +]; + +function ensurePermissions(manifest) { + manifest["uses-permission"] ??= []; + const existing = new Set( + manifest["uses-permission"].map((entry) => entry.$?.["android:name"]).filter(Boolean), + ); + for (const name of REQUIRED_PERMISSIONS) { + if (!existing.has(name)) { + manifest["uses-permission"].push({ $: { "android:name": name } }); + } + } +} + +function ensureMainActivityPiP(application) { + const activities = application.activity ?? []; + const main = + activities.find((activity) => activity.$?.["android:name"] === ".MainActivity") ?? + activities.find((activity) => + (activity["intent-filter"] ?? []).some((filter) => + (filter.action ?? []).some((action) => action.$?.["android:name"] === "android.intent.action.MAIN"), + ), + ); + if (!main) return; + main.$ ??= {}; + main.$["android:supportsPictureInPicture"] = "true"; + const current = String(main.$["android:configChanges"] ?? "") + .split("|") + .map((part) => part.trim()) + .filter(Boolean); + for (const flag of PIP_CONFIG_CHANGES) { + if (!current.includes(flag)) current.push(flag); + } + main.$["android:configChanges"] = current.join("|"); +} + +function ensureVoiceService(application) { + application.service ??= []; + const existing = application.service.find((service) => service.$?.["android:name"] === SERVICE_NAME); + if (existing) { + existing.$["android:exported"] = "false"; + existing.$["android:foregroundServiceType"] = "microphone"; + return; + } + application.service.push({ + $: { + "android:name": SERVICE_NAME, + "android:exported": "false", + "android:foregroundServiceType": "microphone", + }, + }); +} + +function patchAndroidManifest(modResults) { + const manifest = modResults.manifest; + ensurePermissions(manifest); + const application = AndroidConfig.Manifest.getMainApplicationOrThrow(modResults); + ensureMainActivityPiP(application); + ensureVoiceService(application); + return modResults; +} + +function withBackgroundVoice(config) { + return withAndroidManifest(config, (mod) => { + patchAndroidManifest(mod.modResults); + return mod; + }); +} + +withBackgroundVoice.patchAndroidManifest = patchAndroidManifest; +module.exports = withBackgroundVoice; diff --git a/mobile/src/features/voice/pip.ts b/mobile/src/features/voice/pip.ts new file mode 100644 index 00000000..6c97bf95 --- /dev/null +++ b/mobile/src/features/voice/pip.ts @@ -0,0 +1,197 @@ +// Coordinator for the native floating Picture-in-Picture (PiP) voice avatar window. +// Pure TypeScript (no React Native or image asset imports) so it can be unit-tested directly. +import { type FourColors, parseHex, TEMPLATES } from "@/data/lookTemplates"; +import type { BotkinLook } from "@/link/types"; +import type { VoicePiPAction, VoicePiPStartOptions, VoicePiPUpdateOptions } from "../../../modules/botkins-audio"; +import type { LiveStatus } from "./live/types"; + +/** Warm Botkins default [shell, accent, faceplate, eyes] when no look or palette matches. */ +export const DEFAULT_PIP_COLORS: FourColors = ["#c75e35", "#788449", "#ffe5b7", "#502e1e"]; + +/** Kit palette colors mirrored from botkins.generated.ts (without .webp asset requires). */ +const KIT_PALETTE_COLORS: Record = { + terracotta: ["#c75e35", "#788449", "#ffe5b7", "#502e1e"], + honey: ["#dfa12e", "#a65c39", "#ffebc5", "#553819"], + fern: ["#748848", "#dfae52", "#f4e8c4", "#373722"], + tidepool: ["#518477", "#dfad58", "#f6e7c7", "#303b30"], + bluebell: ["#738da4", "#bf8061", "#f8e5cf", "#32303c"], + fig: ["#946079", "#b99655", "#f7e1cf", "#482d39"], +}; + +const TEMPLATE_COLORS = new Map( + TEMPLATES.map((template) => [template.id.toLowerCase(), template.colors]), +); + +function normalizeFourColors(values: readonly string[] | null | undefined): FourColors | null { + if (!Array.isArray(values) || values.length < 4) return null; + const parsed: string[] = []; + for (let i = 0; i < 4; i++) { + const hex = typeof values[i] === "string" ? parseHex(values[i]!) : null; + if (!hex) return null; + parsed.push(hex); + } + return parsed as FourColors; +} + +/** + * Resolves a bot's look into the 4 hex colors [shell, accent, faceplate, eyes] drawn inside + * the floating PiP avatar card. Prefers custom look.colors, then named kit/template palettes, + * then character-specific own colors (for "original"), and finally warm Botkins defaults. + */ +export function resolveBotPiPColors( + look?: Pick | null, + headOwnColors?: readonly string[] | null, +): FourColors { + const custom = normalizeFourColors(look?.colors); + if (custom) return custom; + + const paletteId = look?.palette?.trim().toLowerCase(); + if (paletteId && paletteId !== "original" && paletteId !== "custom") { + const kit = KIT_PALETTE_COLORS[paletteId]; + if (kit) return [...kit]; + const template = TEMPLATE_COLORS.get(paletteId); + if (template) return [...template]; + } + + const own = normalizeFourColors(headOwnColors); + if (own) return own; + + return [...DEFAULT_PIP_COLORS]; +} + +export type VoicePiPLike = { + isSupported(): boolean; + start(options: VoicePiPStartOptions): Promise | void; + update(options: VoicePiPUpdateOptions): void; + stop(): Promise | void; + addListener(name: "action", listener: (event: VoicePiPAction) => void): { remove(): void }; +}; + +export type VoicePiPBridgeOptions = { + native: VoicePiPLike | null | undefined; + name: string; + dark: boolean; + colors: FourColors; + onToggleMute(): void; + onClose(): void; + onRestore?(): void; + /** Minimum interval in ms between audio-level-only updates (status/mute changes send immediately). */ + levelThrottleMs?: number; + now?: () => number; +}; + +export type VoicePiPBridge = { + start(initial: { status: LiveStatus; muted: boolean }): void; + update(next: { status: LiveStatus; muted: boolean; level: number }): void; + stop(): void; + readonly active: boolean; +}; + +/** + * Bridges a live voice session to the native Picture-in-Picture controller: + * - starts/stops PiP cleanly with the call lifecycle + * - throttles audio-level updates while sending status and mute changes immediately + * - routes PiP controls back into the call (mute toggle, restore keeps call alive, close ends call) + */ +export function createVoicePiPBridge(options: VoicePiPBridgeOptions): VoicePiPBridge { + const { native, name, dark, colors, onToggleMute, onClose, onRestore } = options; + const throttleMs = options.levelThrottleMs ?? 80; + const now = options.now ?? Date.now; + + let active = false; + let subscription: { remove(): void } | null = null; + let lastStatus: LiveStatus | null = null; + let lastMuted: boolean | null = null; + let lastLevel = 0; + let lastSentAt = 0; + + const supported = () => { + if (!native) return false; + try { + return native.isSupported(); + } catch { + return false; + } + }; + + function stop() { + if (!active) return; + active = false; + lastStatus = null; + lastMuted = null; + lastLevel = 0; + try { + subscription?.remove(); + } catch { + // Listener already removed. + } + subscription = null; + try { + void Promise.resolve(native?.stop()).catch(() => {}); + } catch { + // Best effort cleanup. + } + } + + return { + get active() { + return active; + }, + start(initial) { + if (active || !native || !supported()) return; + active = true; + lastStatus = initial.status; + lastMuted = initial.muted; + lastLevel = 0; + lastSentAt = now(); + try { + subscription = native.addListener("action", (event) => { + if (!active) return; + if (event.type === "toggleMute") onToggleMute(); + else if (event.type === "closed") onClose(); + else if (event.type === "restored") onRestore?.(); + }); + } catch { + subscription = null; + } + try { + void Promise.resolve( + native.start({ + name: name.trim() || "Botkin", + status: initial.status, + muted: initial.muted, + dark, + colors, + }), + ).catch(() => {}); + } catch { + // Native module unavailable. + } + }, + update(next) { + if (!active || !native) return; + if (next.status === "ended") { + stop(); + return; + } + const clamped = Number.isFinite(next.level) ? Math.max(0, Math.min(1, next.level)) : 0; + const stateChanged = next.status !== lastStatus || next.muted !== lastMuted; + const current = now(); + if (!stateChanged) { + if (current - lastSentAt < throttleMs) return; + const delta = Math.abs(clamped - lastLevel); + if (delta < 0.02 && !(clamped === 0 && lastLevel > 0)) return; + } + lastStatus = next.status; + lastMuted = next.muted; + lastLevel = clamped; + lastSentAt = current; + try { + native.update({ status: next.status, muted: next.muted, level: clamped }); + } catch { + // Ignore transient native update error. + } + }, + stop, + }; +} diff --git a/mobile/src/features/voice/tts.ts b/mobile/src/features/voice/tts.ts index 657e19fc..5648db22 100644 --- a/mobile/src/features/voice/tts.ts +++ b/mobile/src/features/voice/tts.ts @@ -51,7 +51,7 @@ const waiting: Job[] = []; /** Sound plays with the ring switch off, and other apps' sound dips while a reply is read. */ async function playbackSession() { try { - await audioModule()?.setAudioModeAsync({ playsInSilentMode: true, allowsRecording: false, interruptionMode: "duckOthers", shouldPlayInBackground: false }); + await audioModule()?.setAudioModeAsync({ playsInSilentMode: true, allowsRecording: false, interruptionMode: "duckOthers", shouldPlayInBackground: true }); } catch { // The phone keeps its current session. } diff --git a/mobile/src/features/voice/useLiveSession.ts b/mobile/src/features/voice/useLiveSession.ts index 59aa2e43..74844025 100644 --- a/mobile/src/features/voice/useLiveSession.ts +++ b/mobile/src/features/voice/useLiveSession.ts @@ -1,23 +1,24 @@ // React adapter for the shared live-voice controller. The Watch companion uses the same controller // with a WatchConnectivity audio endpoint instead of this phone's native duplex endpoint. import { useEffect, useRef, useState } from "react"; -import { Animated, AppState } from "react-native"; +import { Animated } from "react-native"; +import { colorsOf, lookOf } from "@/data/botLook"; import { type AvatarState, useCapability } from "@/state/hooks"; import { trackResource } from "@/state/ledger"; import { showToast, useApp } from "@/state/store"; -import { haptic } from "@/ui"; +import { useAppActive } from "@/state/useAppActive"; +import { haptic, useTheme } from "@/ui"; import { useReducedMotion } from "@/ui/BotAvatar"; import { endLiveCall } from "./liveCall"; import { LiveSessionController, type LiveSessionState, phoneLiveKit } from "./live/session"; import type { LiveStatus } from "./live/types"; import { effectiveLive } from "./botVoice"; -import { callRoutes } from "../../../modules/botkins-audio"; +import { createVoicePiPBridge, resolveBotPiPColors } from "./pip"; +import { callRoutes, voicePiP } from "../../../modules/botkins-audio"; import { audioModule, keepAwakeModule } from "./native"; import { useVoiceSupported, useVoiceSettings } from "./state"; const UPDATE_APP = "Update the app to use this live voice."; -/** How long an iPhone-owned call may sit in the background. A Watch-owned call uses reachability. */ -const BACKGROUND_LIMIT = 30_000; const AVATAR: Record = { connecting: "pending", @@ -60,15 +61,19 @@ const display = (state: LiveSessionState) => ({ export function useLiveSession({ chatId, botId, computer }: { chatId: string; botId: string; computer?: string }) { const supported = useVoiceSupported(); const voice = useVoiceSettings(); - const own = useApp((state) => state.parts.bots?.find((bot) => bot.id === botId)?.voice?.live); + const bot = useApp((state) => state.parts.bots?.find((item) => item.id === botId)); + const own = bot?.voice?.live; const provider = voice ? effectiveLive(voice.live, own).provider : null; const savesTurns = useCapability("voice-turns-v1"); const savesHistory = useCapability("voice-history-v1"); const request = useApp((state) => state.parts.live?.requests.find((item) => item.chatId === chatId)); + const { dark } = useTheme(); const [state, setState] = useState(() => display({ ...INITIAL, savesTurns, savesHistory })); const [levels, setLevels] = useState(false); const [level] = useState(() => new Animated.Value(0)); const controller = useRef(null); + const pipMeta = useRef({ name: bot?.name ?? "Botkin", look: bot?.look, dark }); + pipMeta.current = { name: bot?.name ?? "Botkin", look: bot?.look, dark }; const still = useReducedMotion(); const stillNow = useRef(true); useEffect(() => { @@ -88,8 +93,23 @@ export function useLiveSession({ chatId, botId, computer }: { chatId: string; bo }); const next = new LiveSessionController({ chatId, botId, computer, provider, kit, savesTurns, savesHistory }); controller.current = next; + const { name, look, dark: isDark } = pipMeta.current; + const pip = createVoicePiPBridge({ + native: voicePiP, + name, + dark: isDark, + colors: resolveBotPiPColors(look, colorsOf(lookOf(look ? { id: botId, look } : { id: botId }))), + onToggleMute: () => { + if (controller.current === next) next.toggleMute(); + }, + onClose: () => { + if (controller.current === next) endLiveCall(); + }, + }); + pip.start({ status: INITIAL.status, muted: INITIAL.muted }); let old = display(INITIAL); const off = next.subscribe((value) => { + pip.update({ status: value.status, muted: value.muted, level: value.level }); if (value.metered && !stillNow.current) { setLevels(true); Animated.timing(level, { @@ -108,6 +128,7 @@ export function useLiveSession({ chatId, botId, computer }: { chatId: string; bo const micHandle = trackResource("mic", "useLiveSession", `live-voice:${provider}`, computer); void next.start(); return () => { + pip.stop(); micHandle.release(); off(); controller.current = null; @@ -116,7 +137,7 @@ export function useLiveSession({ chatId, botId, computer }: { chatId: string; bo }; }, [ready, chatId, botId, provider, savesHistory, savesTurns, computer, level]); - const keepAwake = ready && state.started && state.status !== "ended"; + const keepAwake = useAppActive(ready && state.started && state.status !== "ended"); useEffect(() => { if (!keepAwake) return; const awakeHandle = trackResource("keep-awake", "useLiveSession", "live-voice", computer ?? undefined); @@ -128,22 +149,6 @@ export function useLiveSession({ chatId, botId, computer }: { chatId: string; bo }; }, [keepAwake, computer]); - useEffect(() => { - let timer: ReturnType | null = null; - const subscription = AppState.addEventListener("change", (next) => { - if (next === "active") { - if (timer) clearTimeout(timer); - timer = null; - } else if (!timer) { - timer = setTimeout(endLiveCall, BACKGROUND_LIMIT); - } - }); - return () => { - if (timer) clearTimeout(timer); - subscription.remove(); - }; - }, []); - const blocked = !supported ? UPDATE_APP + "." : state.problem; const failed = !!blocked && (state.status === "ended" || state.status === "connecting" || !controller.current); const live = !failed && !!controller.current && state.status !== "connecting" && state.status !== "ended"; diff --git a/mobile/tests/voice-background.test.ts b/mobile/tests/voice-background.test.ts new file mode 100644 index 00000000..9886f02c --- /dev/null +++ b/mobile/tests/voice-background.test.ts @@ -0,0 +1,314 @@ +// Background live voice & floating Picture-in-Picture (PiP) avatar tests. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { test } from "node:test"; +import type { VoicePiPAction, VoicePiPStartOptions, VoicePiPUpdateOptions } from "../modules/botkins-audio"; +import { + createVoicePiPBridge, + DEFAULT_PIP_COLORS, + resolveBotPiPColors, + type VoicePiPLike, +} from "../src/features/voice/pip"; +import { createBackgroundController } from "../src/state/backgroundRelay"; +import { createRequire } from "node:module"; + +const require = createRequire(import.meta.url); + +class FakeVoicePiP implements VoicePiPLike { + supported = true; + starts: VoicePiPStartOptions[] = []; + updates: VoicePiPUpdateOptions[] = []; + stops = 0; + listeners = new Set<(event: VoicePiPAction) => void>(); + + isSupported() { + return this.supported; + } + start(options: VoicePiPStartOptions) { + this.starts.push(options); + } + update(options: VoicePiPUpdateOptions) { + this.updates.push(options); + } + stop() { + this.stops++; + } + addListener(_name: "action", listener: (event: VoicePiPAction) => void) { + this.listeners.add(listener); + return { remove: () => this.listeners.delete(listener) }; + } + emit(event: VoicePiPAction) { + for (const listener of [...this.listeners]) listener(event); + } +} + +// ---- resolveBotPiPColors + +test("resolveBotPiPColors prefers custom look.colors and normalizes hex values", () => { + assert.deepEqual( + resolveBotPiPColors({ palette: "honey", colors: ["#abc", "#112233", "445566", "#778899"] }), + ["#aabbcc", "#112233", "#445566", "#778899"], + ); +}); + +test("resolveBotPiPColors resolves named kit and template palettes", () => { + assert.deepEqual(resolveBotPiPColors({ palette: "tidepool" }), [ + "#518477", + "#dfad58", + "#f6e7c7", + "#303b30", + ]); + assert.deepEqual(resolveBotPiPColors({ palette: "FIG" }), [ + "#946079", + "#b99655", + "#f7e1cf", + "#482d39", + ]); + assert.deepEqual(resolveBotPiPColors({ palette: "midnight" }), [ + "#3e4f86", + "#e0b354", + "#e8ecf6", + "#151a2e", + ]); +}); + +test("resolveBotPiPColors uses head own colors for original palette and falls back cleanly", () => { + const headOwn = ["#123456", "#654321", "#fedcba", "#101010"]; + assert.deepEqual(resolveBotPiPColors({ palette: "original" }, headOwn), headOwn); + assert.deepEqual(resolveBotPiPColors({ palette: "unknown", colors: ["bad"] }, headOwn), headOwn); + assert.deepEqual(resolveBotPiPColors(undefined, undefined), DEFAULT_PIP_COLORS); +}); + +// ---- createVoicePiPBridge + +test("createVoicePiPBridge starts, updates, throttles audio levels, and stops cleanly", () => { + const native = new FakeVoicePiP(); + let clock = 1000; + let toggles = 0; + let closes = 0; + let restores = 0; + + const bridge = createVoicePiPBridge({ + native, + name: "Alfie", + dark: true, + colors: ["#c75e35", "#788449", "#ffe5b7", "#502e1e"], + onToggleMute: () => { toggles++; }, + onClose: () => { closes++; }, + onRestore: () => { restores++; }, + levelThrottleMs: 80, + now: () => clock, + }); + + bridge.start({ status: "connecting", muted: false }); + assert.equal(bridge.active, true); + assert.equal(native.starts.length, 1); + assert.deepEqual(native.starts[0], { + name: "Alfie", + status: "connecting", + muted: false, + dark: true, + colors: ["#c75e35", "#788449", "#ffe5b7", "#502e1e"], + }); + + // Status change flushes immediately even inside the throttle window. + clock += 10; + bridge.update({ status: "listening", muted: false, level: 0.25 }); + assert.equal(native.updates.length, 1); + assert.deepEqual(native.updates[0], { status: "listening", muted: false, level: 0.25 }); + + // Rapid level-only update inside throttle window is skipped. + clock += 30; + bridge.update({ status: "listening", muted: false, level: 0.6 }); + assert.equal(native.updates.length, 1); + + // Level update after throttle window is forwarded and clamped. + clock += 60; + bridge.update({ status: "listening", muted: false, level: 1.5 }); + assert.equal(native.updates.length, 2); + assert.deepEqual(native.updates[1], { status: "listening", muted: false, level: 1 }); + + // Mute change flushes immediately even inside the throttle window. + clock += 5; + bridge.update({ status: "listening", muted: true, level: 0 }); + assert.equal(native.updates.length, 3); + assert.deepEqual(native.updates[2], { status: "listening", muted: true, level: 0 }); + + // Native PiP controls: toggleMute toggles mute, restored keeps call alive, closed ends call. + native.emit({ type: "toggleMute", muted: false }); + assert.equal(toggles, 1); + assert.equal(closes, 0); + + native.emit({ type: "restored" }); + assert.equal(restores, 1); + assert.equal(closes, 0); + assert.equal(bridge.active, true, "restoring the app keeps PiP bridge active until call ends"); + + native.emit({ type: "closed" }); + assert.equal(closes, 1); + + // Stopping cleans up listener and is idempotent. + bridge.stop(); + bridge.stop(); + assert.equal(bridge.active, false); + assert.equal(native.stops, 1); + assert.equal(native.listeners.size, 0); + + // Events after stop are ignored. + native.emit({ type: "toggleMute" }); + native.emit({ type: "closed" }); + assert.equal(toggles, 1); + assert.equal(closes, 1); +}); + +test("createVoicePiPBridge stops automatically when session status reaches ended", () => { + const native = new FakeVoicePiP(); + const bridge = createVoicePiPBridge({ + native, + name: "Alfie", + dark: false, + colors: DEFAULT_PIP_COLORS, + onToggleMute() {}, + onClose() {}, + }); + + bridge.start({ status: "listening", muted: false }); + assert.equal(bridge.active, true); + + bridge.update({ status: "ended", muted: false, level: 0 }); + assert.equal(bridge.active, false); + assert.equal(native.stops, 1); +}); + +test("createVoicePiPBridge is a safe no-op when unsupported or native module is absent", () => { + const unsupported = new FakeVoicePiP(); + unsupported.supported = false; + + const b1 = createVoicePiPBridge({ + native: unsupported, + name: "Alfie", + dark: false, + colors: DEFAULT_PIP_COLORS, + onToggleMute() {}, + onClose() {}, + }); + b1.start({ status: "connecting", muted: false }); + b1.update({ status: "listening", muted: false, level: 0.5 }); + b1.stop(); + assert.equal(b1.active, false); + assert.equal(unsupported.starts.length, 0); + assert.equal(unsupported.updates.length, 0); + assert.equal(unsupported.stops, 0); + + const b2 = createVoicePiPBridge({ + native: null, + name: "Alfie", + dark: false, + colors: DEFAULT_PIP_COLORS, + onToggleMute() {}, + onClose() {}, + }); + b2.start({ status: "connecting", muted: false }); + b2.stop(); + assert.equal(b2.active, false); +}); + +// ---- Background voice hold & config invariants + +test("background voice hold keeps link awake across background transitions until released", () => { + let sleeps = 0; + let scheduled: (() => void) | null = null; + const ctrl = createBackgroundController({ + graceMs: 3000, + onSleep: () => { sleeps++; }, + onWake() {}, + setTimeout: ((fn: () => void) => { + scheduled = fn; + return 1 as unknown as ReturnType; + }) as typeof setTimeout, + clearTimeout: (() => { scheduled = null; }) as typeof clearTimeout, + }); + + const releaseVoice = ctrl.hold("voice"); + ctrl.setAppState("background"); + assert.equal(ctrl.sleeping, false); + assert.equal(scheduled, null, "voice hold prevents scheduling background sleep"); + + releaseVoice(); + assert.ok(scheduled, "releasing voice hold while backgrounded schedules grace sleep"); + scheduled!(); + assert.equal(sleeps, 1); + assert.equal(ctrl.sleeping, true); +}); + +test("useLiveSession has no 30-second background hangup timeout and app config enables background audio/PiP", () => { + const mobileRoot = resolve(import.meta.dirname, ".."); + const useLiveSessionSrc = readFileSync(resolve(mobileRoot, "src/features/voice/useLiveSession.ts"), "utf8"); + const appConfigSrc = readFileSync(resolve(mobileRoot, "app.config.ts"), "utf8"); + const ttsSrc = readFileSync(resolve(mobileRoot, "src/features/voice/tts.ts"), "utf8"); + + assert.equal(useLiveSessionSrc.includes("BACKGROUND_LIMIT"), false, "30s background timeout must be removed"); + assert.ok(useLiveSessionSrc.includes("createVoicePiPBridge"), "useLiveSession wires the PiP bridge"); + assert.ok(appConfigSrc.includes("enableBackgroundRecording: true"), "expo-audio enables background recording"); + assert.ok(appConfigSrc.includes("./plugins/withBackgroundVoice.js"), "app.config registers Android background voice plugin"); + assert.ok(ttsSrc.includes("shouldPlayInBackground: true"), "Read Aloud enables background playback"); +}); + +test("withBackgroundVoice Android plugin configures PiP activity flags and microphone foreground service idempotently", () => { + const { patchAndroidManifest } = require("../plugins/withBackgroundVoice.js") as { + patchAndroidManifest(manifest: Record): Record; + }; + + const manifest = { + manifest: { + $: { "xmlns:android": "http://schemas.android.com/apk/res/android" }, + "uses-permission": [], + application: [ + { + $: { "android:name": ".MainApplication" }, + activity: [ + { + $: { + "android:name": ".MainActivity", + "android:configChanges": "keyboard|keyboardHidden|orientation|screenSize", + }, + }, + ], + service: [], + }, + ], + }, + }; + + patchAndroidManifest(manifest); + patchAndroidManifest(manifest); // idempotent on second run + + const root = manifest.manifest as { + "uses-permission": { $: Record }[]; + application: { + activity: { $: Record }[]; + service: { $: Record }[]; + }[]; + }; + + const perms = root["uses-permission"].map((p) => p.$["android:name"]); + assert.deepEqual(perms, [ + "android.permission.FOREGROUND_SERVICE", + "android.permission.FOREGROUND_SERVICE_MICROPHONE", + ]); + + const activity = root.application[0]!.activity[0]!.$; + assert.equal(activity["android:supportsPictureInPicture"], "true"); + const configParts = new Set((activity["android:configChanges"] ?? "").split("|")); + for (const needed of ["screenSize", "smallestScreenSize", "screenLayout", "orientation"]) { + assert.ok(configParts.has(needed), `missing configChanges token: ${needed}`); + } + + assert.equal(root.application[0]!.service.length, 1); + assert.deepEqual(root.application[0]!.service[0]!.$, { + "android:name": "app.botkins.audio.BotkinsVoiceService", + "android:exported": "false", + "android:foregroundServiceType": "microphone", + }); +});