Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions mobile/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down Expand Up @@ -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",
],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<application>
<service
android:name="app.botkins.audio.BotkinsVoiceService"
android:exported="false"
android:foregroundServiceType="microphone" />
</application>
</manifest>
Original file line number Diff line number Diff line change
@@ -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<String> = 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()
}
}
}
Original file line number Diff line number Diff line change
@@ -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.
}
}
}
}
4 changes: 2 additions & 2 deletions mobile/modules/botkins-audio/expo-module.config.json
Original file line number Diff line number Diff line change
@@ -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"] }
}
30 changes: 30 additions & 0 deletions mobile/modules/botkins-audio/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;
update(options: VoicePiPUpdateOptions): void;
enter?(): Promise<void>;
stop(): Promise<void>;
addListener(name: "action", listener: (event: VoicePiPAction) => void): EventSubscription;
};

export const callRoutes = requireOptionalNativeModule<CallRoutes>("BotkinsCallRoutes");

export const DuplexAudio = requireOptionalNativeModule<Native>("BotkinsAudio");

export const voicePiP = requireOptionalNativeModule<VoicePiPModule>("BotkinsVoicePiP");
Loading
Loading