Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(calls): stop Android call crashes and match the iOS call experience (#8501)
Peter Chinman8654e0d5e98e
diff --git a/apps/web/src/features/channel/Call/FullScreenCallPrompt.tsx b/apps/web/src/features/channel/Call/FullScreenCallPrompt.tsxnew file mode 100644index 0000000000..cdda890526--- /dev/null+++ b/apps/web/src/features/channel/Call/FullScreenCallPrompt.tsx@@ -0,0 +1,150 @@+import { makePersistedState } from '@app/lib/persistence';+import { toast } from '@core/component/Toast/Toast';+import { useTutorialCompleted } from '@core/context/user';+import { fireAndForget } from '@core/util/fireAndForget';+import { isPlatform } from '@core/util/platform';+import { catchToResult } from '@core/util/result';+import { Telemetry } from '@macro-inc/observability';+import { useNotificationSettings } from '@notifications/notification-settings';+import PhoneIncoming from '@phosphor/phone-incoming.svg';+import { useIsAuthenticated } from '@queries/auth';+import { invoke } from '@tauri-apps/api/core';+import { createMemo, createSignal, onCleanup, onMount, Show } from 'solid-js';+import { z } from 'zod';+import { isNativeCallEnabled } from './native-call-platform';++// Device-wide: the setting belongs to the device, not the signed-in account.+const DISMISSED_KEY = 'full-screen-call-prompt-dismissed';+const dismissedValue = z.literal('true');+const fullScreenIntentState = z.object({ allowed: z.boolean() });++async function canUseFullScreenIntent(): Promise<boolean> {+ return Telemetry.span('call.full_screen_intent.check', async (span) => {+ const result = await catchToResult(() =>+ invoke<unknown>('plugin:call-kit|can_use_full_screen_intent')+ );+ if (result.isErr()) {+ // Builds before this command can't report it; don't prompt there.+ console.error(+ '[callkit] failed to read full-screen intent access',+ result.error+ );+ span.setAttr('call.full_screen_intent.outcome', 'unavailable');+ return true;+ }+ const allowed =+ fullScreenIntentState.safeParse(result.value).data?.allowed ?? true;+ span.setAttr('call.full_screen_intent.outcome', 'checked');+ span.setAttr('call.full_screen_intent.allowed', allowed);+ return allowed;+ });+}++async function openFullScreenIntentSettings(): Promise<void> {+ await Telemetry.span(+ 'call.full_screen_intent.open_settings',+ async (span) => {+ const result = await catchToResult(() =>+ invoke('plugin:call-kit|open_full_screen_intent_settings')+ );+ span.setAttr(+ 'call.full_screen_intent.outcome',+ result.isOk() ? 'opened' : 'failed'+ );+ if (result.isErr())+ console.error(+ '[callkit] failed to open full-screen intent settings',+ result.error+ );+ }+ );+}++/**+ * Android 14+ revokes full-screen notifications by default, so a ringing call+ * can't open over the lock screen until the user allows them.+ */+export function FullScreenCallPrompt() {+ if (!isPlatform('android') || !isNativeCallEnabled()) return null;++ const settings = useNotificationSettings();+ const isAuthenticated = useIsAuthenticated();+ const tutorialCompleted = useTutorialCompleted();+ const [blocked, setBlocked] = createSignal(false);+ const [dismissed, setDismissed] = makePersistedState(createSignal(false), {+ storages: {+ restore: () =>+ dismissedValue.safeParse(localStorage.getItem(DISMISSED_KEY)).success+ ? true+ : undefined,+ write: (value) => {+ if (value) localStorage.setItem(DISMISSED_KEY, 'true');+ },+ },+ });++ const checkBlocked = async () =>+ setBlocked(!(await canUseFullScreenIntent()));+ onMount(() => fireAndForget(checkBlocked(), 'channel-call'));++ // Calls only ring once notifications are on; that prompt comes first.+ const shouldShow = createMemo(+ () =>+ blocked() &&+ !dismissed() &&+ isAuthenticated() &&+ !!tutorialCompleted() &&+ settings.isSupported &&+ settings.isEnabled()+ );++ // The toast stays up while the user is in Settings; returning rechecks+ // access, and granting it unmounts the toast.+ const recheckOnReturn = () => {+ if (shouldShow()) fireAndForget(checkBlocked(), 'channel-call');+ };+ window.addEventListener('focus', recheckOnReturn);+ onCleanup(() => window.removeEventListener('focus', recheckOnReturn));++ return (+ <Show when={shouldShow()}>+ <FullScreenCallToastTrigger onHide={() => setDismissed(true)} />+ </Show>+ );+}++function FullScreenCallToastTrigger(props: { onHide: () => void }) {+ onMount(() => {+ const toastId = toast.custom(+ {+ title: 'Show Calls on Your Lock Screen',+ icon: PhoneIncoming,+ color: 'var(--color-accent)',+ content: () => (+ <div class="text-xs text-ink-extra-muted">+ Allow full-screen notifications so incoming calls open even when+ your phone is locked.+ </div>+ ),+ actions: [+ {+ label: 'Hide',+ onClick: () => {+ props.onHide();+ toast.dismiss(toastId);+ },+ },+ {+ label: 'Allow',+ onClick: () =>+ fireAndForget(openFullScreenIntentSettings(), 'channel-call'),+ },+ ],+ },+ { persistent: true }+ );+ onCleanup(() => toast.dismiss(toastId));+ });++ return null;+}diff --git a/apps/web/src/features/channel/Call/tests/fake-toast.tsx b/apps/web/src/features/channel/Call/tests/fake-toast.tsxnew file mode 100644index 0000000000..8e290b1787--- /dev/null+++ b/apps/web/src/features/channel/Call/tests/fake-toast.tsx@@ -0,0 +1,36 @@+import type { CustomToastConfig } from '@core/component/Toast/Toast';+import { createSignal, For } from 'solid-js';++/** Stands in for `@core/component/Toast/Toast` so tests can see and press custom toasts. */+type OpenToast = { id: number; config: CustomToastConfig };++const [open, setOpen] = createSignal<OpenToast[]>([]);+let nextId = 0;++export const toast = {+ custom(config: CustomToastConfig) {+ const id = ++nextId;+ setOpen((toasts) => [...toasts, { id, config }]);+ return id;+ },+ dismiss(id: number) {+ setOpen((toasts) => toasts.filter((toast) => toast.id !== id));+ },+};++export function FakeToaster() {+ return (+ <For each={open()}>+ {(toast) => (+ <div role="status">+ <p>{toast.config.title}</p>+ <For each={toast.config.actions}>+ {(action) => (+ <button onClick={action.onClick}>{action.label}</button>+ )}+ </For>+ </div>+ )}+ </For>+ );+}diff --git a/apps/web/src/features/channel/Call/tests/full-screen-call-prompt.test.tsx b/apps/web/src/features/channel/Call/tests/full-screen-call-prompt.test.tsxnew file mode 100644index 0000000000..550619aeed--- /dev/null+++ b/apps/web/src/features/channel/Call/tests/full-screen-call-prompt.test.tsx@@ -0,0 +1,104 @@+/**+ * @vitest-environment jsdom+ */++import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { FullScreenCallPrompt } from '../FullScreenCallPrompt';+import { FakeToaster } from './fake-toast';++const native = vi.hoisted(() => ({+ allowed: false as boolean | 'unavailable',+ invoke: vi.fn(),+}));++vi.mock('@core/component/Toast/Toast', () => import('./fake-toast'));+vi.mock('@core/util/platform', () => ({+ isPlatform: (platform: string) => platform === 'android',+}));+vi.mock('../native-call-platform', () => ({ isNativeCallEnabled: () => true }));+vi.mock('@core/context/user', () => ({+ useTutorialCompleted: () => () => true,+}));+vi.mock('@queries/auth', () => ({ useIsAuthenticated: () => () => true }));+vi.mock('@notifications/notification-settings', () => ({+ useNotificationSettings: () => ({ isSupported: true, isEnabled: () => true }),+}));+vi.mock('@tauri-apps/api/core', () => ({ invoke: native.invoke }));++const title = 'Show Calls on Your Lock Screen';++function renderPrompt() {+ return render(() => (+ <>+ <FakeToaster />+ <FullScreenCallPrompt />+ </>+ ));+}++function accessChecks() {+ return native.invoke.mock.calls.filter(+ ([command]) => command === 'plugin:call-kit|can_use_full_screen_intent'+ ).length;+}++/** Waits for the mount check to reach native and its result to land. */+async function settleAccessCheck() {+ await waitFor(() => expect(accessChecks()).toBeGreaterThan(0));+ await new Promise((resolve) => setTimeout(resolve, 0));+}++describe('full-screen call prompt', () => {+ beforeEach(() => {+ localStorage.clear();+ native.allowed = false;+ native.invoke.mockReset();+ native.invoke.mockImplementation(async (command: string) => {+ if (command !== 'plugin:call-kit|can_use_full_screen_intent') return;+ if (native.allowed === 'unavailable') throw new Error('unknown command');+ return { allowed: native.allowed };+ });+ });++ it('stays through a trip to Settings until access is granted', async () => {+ renderPrompt();+ fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));+ expect(native.invoke).toHaveBeenCalledWith(+ 'plugin:call-kit|open_full_screen_intent_settings'+ );++ // Back from Settings without allowing it.+ const checks = accessChecks();+ fireEvent.focus(window);+ await waitFor(() => expect(accessChecks()).toBe(checks + 1));+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(screen.getByText(title)).toBeTruthy();++ native.allowed = true;+ fireEvent.focus(window);+ await waitFor(() => expect(screen.queryByText(title)).toBeNull());+ });++ it('stays hidden on this device once dismissed', async () => {+ const first = renderPrompt();+ fireEvent.click(await screen.findByRole('button', { name: 'Hide' }));+ expect(screen.queryByText(title)).toBeNull();+ first.unmount();++ native.invoke.mockClear();+ renderPrompt();+ await settleAccessCheck();+ expect(screen.queryByText(title)).toBeNull();+ });++ it('never prompts on builds without the access command', async () => {+ native.allowed = 'unavailable';+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});+ renderPrompt();+ await settleAccessCheck();+ expect(screen.queryByText(title)).toBeNull();+ expect(logged).toHaveBeenCalled();+ logged.mockRestore();+ });+});diff --git a/apps/web/src/features/channel/Call/use-callkit-theme-sync.ts b/apps/web/src/features/channel/Call/use-callkit-theme-sync.tsindex 26f3ec1d0e..f925aecb4d 100644--- a/apps/web/src/features/channel/Call/use-callkit-theme-sync.ts+++ b/apps/web/src/features/channel/Call/use-callkit-theme-sync.ts@@ -1,6 +1,4 @@-import { ENABLE_CALLKIT } from '@core/constant/featureFlags';import { fireAndForget } from '@core/util/fireAndForget';-import { isPlatform, isTauri } from '@core/util/platform';import { createEffect, createMemo } from 'solid-js';import { setNativeCallKitDrawerTheme } from './callkit-drawer-theme';import { useNativeCallState } from './native-call-state';@@ -16,9 +14,8 @@ async function syncDrawerTheme(}export function useCallKitThemeSync() {+ // CallKitSync mounts this only where native calls run (iOS and Android).const nativeCall = useNativeCallState();- if (!ENABLE_CALLKIT || !isTauri() || !isPlatform('ios')) return null;-const theme = createMemo(nativeCall.drawerTheme);createEffect(() => {fireAndForget(syncDrawerTheme(theme()), 'channel-call');diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsxindex 993296c60e..7fb40e606d 100644--- a/apps/web/src/routes/Root.tsx+++ b/apps/web/src/routes/Root.tsx@@ -12,6 +12,7 @@ import { setHotkeyRoot } from '@app/signal/hotkeyRoot';import { IncomingCallEvents } from '@block-call/sidebar/incoming-calls';import { CallProvider } from '@channel/Call/CallContext';import { CallStartedNotifier } from '@channel/Call/CallStartedNotifier';+import { FullScreenCallPrompt } from '@channel/Call/FullScreenCallPrompt';import { CallKitSync } from '@channel/Call/use-callkit';import { dismissBootShell } from '@components/app/boot-shell';import { RootFrame } from '@components/app/Layout';@@ -216,6 +217,7 @@ export function Root() {<UserContextProvider><EmailLinksContextProvider><BrowserNotificationModal />+ <FullScreenCallPrompt /><IosPushNotificationModal /><IpadUnsupportedDialog /><GlobalShareInboxConflictDialog />diff --git a/apps/web/tauri/callkit_plugin/android/build.gradle.kts b/apps/web/tauri/callkit_plugin/android/build.gradle.ktsindex a2914308c4..3e175190bb 100644--- a/apps/web/tauri/callkit_plugin/android/build.gradle.kts+++ b/apps/web/tauri/callkit_plugin/android/build.gradle.kts@@ -20,6 +20,8 @@ dependencies {implementation(project(":tauri-android"))implementation("androidx.core:core-ktx:1.15.0")implementation("androidx.appcompat:appcompat:1.7.1")+ // The in-app call window listens for user-leave hints (OnUserLeaveHintProvider, activity 1.9+).+ implementation("androidx.activity:activity:1.10.1")implementation("io.livekit:livekit-android:2.29.0")implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")testImplementation("junit:junit:4.13.2")@@ -27,4 +29,5 @@ dependencies {testImplementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")androidTestImplementation("androidx.test:runner:1.6.2")androidTestImplementation("androidx.test.ext:junit:1.2.1")+ androidTestImplementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")}diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/AndroidManifest.xml b/apps/web/tauri/callkit_plugin/android/src/androidTest/AndroidManifest.xmlindex a1fb1c4e3b..7ca845c094 100644--- a/apps/web/tauri/callkit_plugin/android/src/androidTest/AndroidManifest.xml+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/AndroidManifest.xml@@ -1,4 +1,7 @@<manifest xmlns:android="http://schemas.android.com/apk/res/android"><!-- Only the instrumentation APK may connect to the local development server. -->- <application android:usesCleartextTraffic="true" />+ <application android:usesCleartextTraffic="true">+ <!-- Stands in for Macro's main activity so the plugin's in-app call window runs as in the app. -->+ <activity android:name="com.macro.call.MiniWindowHostActivity" android:exported="false" android:theme="@style/Theme.AppCompat.Light.NoActionBar" android:supportsPictureInPicture="true" android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout" />+ </application></manifest>diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/CallTestSupport.kt b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/CallTestSupport.ktnew file mode 100644index 0000000000..1b475c09a0--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/CallTestSupport.kt@@ -0,0 +1,46 @@+package com.macro.call++import android.app.Instrumentation+import android.util.Base64+import org.json.JSONObject+import org.junit.Assert.fail+import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec++/** A token for LiveKit's isolated `--dev` server (devkey/secret), used by the optional media tests. */+internal fun liveKitToken(identity: String, room: String, kind: String? = null): String {+ fun encode(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)+ val header = encode("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".toByteArray())+ val payload = encode(JSONObject().apply {+ put("iss", "devkey"); put("sub", identity); kind?.let { put("kind", it) }+ put("exp", System.currentTimeMillis() / 1000 + 300)+ put("video", JSONObject().apply { put("roomJoin", true); put("room", room); put("canPublish", true); put("canSubscribe", true) })+ }.toString().toByteArray())+ val body = "$header.$payload"+ val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec("secret".toByteArray(), "HmacSHA256")) }+ return "$body.${encode(mac.doFinal(body.toByteArray()))}"+}++internal fun Instrumentation.awaitCondition(message: String, condition: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 30_000+ while (System.currentTimeMillis() < deadline) {+ var ready = false+ runOnMainSync { ready = condition() }+ if (ready) return+ Thread.sleep(100)+ }+ fail(message)+}++internal fun Instrumentation.screenshot(name: String) {+ waitForIdleSync()+ // Idle messages can complete before SurfaceFlinger presents the next frame.+ Thread.sleep(300)+ uiAutomation.takeScreenshot().let { bitmap ->+ val file = java.io.File(targetContext.getExternalFilesDir(null), name)+ file.outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }+ bitmap.recycle()+ // Gradle removes test app data after the run; retain synthetic UI evidence.+ uiAutomation.executeShellCommand("cp ${file.absolutePath} /sdcard/Download/$name").close()+ }+}diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallTest.kt b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallTest.ktindex 8578c57312..4ba60f2b56 100644--- a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallTest.kt+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallTest.kt@@ -33,6 +33,23 @@ class IncomingCallTest {context.getSharedPreferences("macro_push", Context.MODE_PRIVATE).edit().clear().commit()}+ @Test fun unchangedParticipantsAreNotReemittedToJs() {+ // JS answers each identities event by resending every display name; repeats once flooded the bridge until the app crashed.+ val sent = mutableListOf<String>()+ fun channel(id: Long) = app.tauri.plugin.Channel(id, { sent.add(it) }, com.fasterxml.jackson.databind.ObjectMapper())+ try {+ instrumentation.runOnMainSync {+ Calls.watch("participants", channel(1))+ Calls.publish(); Calls.publish()+ }+ assertEquals(1, sent.size)+ instrumentation.runOnMainSync { Calls.watch("participants", channel(2)); Calls.publish() }+ assertEquals("A reloaded WebView must receive the current identities", 2, sent.size)+ } finally {+ instrumentation.runOnMainSync { Calls.unwatch() }+ }+ }+private fun data(id: String, recipient: String = "call-test-user") = mapOf("recipientId" to recipient,"payload" to JSONObject().apply {diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MediaLifecycleTest.kt b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MediaLifecycleTest.ktindex 6310e89627..ab53bd7bcd 100644--- a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MediaLifecycleTest.kt+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MediaLifecycleTest.kt@@ -3,20 +3,16 @@ package com.macro.callimport android.Manifestimport android.content.Intentimport android.content.pm.PackageManager-import android.util.Base64import io.livekit.android.LiveKitimport io.livekit.android.room.track.VideoTrackimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport kotlinx.coroutines.launch-import org.json.JSONObjectimport org.junit.Assert.*import org.junit.Assume.assumeNotNullimport org.junit.Testimport org.junit.runner.RunWithimport java.util.UUID-import javax.crypto.Mac-import javax.crypto.spec.SecretKeySpec/** Optional integration test against LiveKit's isolated --dev server. */@RunWith(AndroidJUnit4::class)@@ -24,38 +20,14 @@ class MediaLifecycleTest {private val instrumentation = InstrumentationRegistry.getInstrumentation()private val context = instrumentation.targetContext- private fun token(identity: String = "android-emulator-test"): String {- fun encode(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)- val header = encode("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".toByteArray())- val payload = encode(JSONObject().apply {- put("iss", "devkey"); put("sub", identity)- put("exp", System.currentTimeMillis() / 1000 + 300)- put("video", JSONObject().apply { put("roomJoin", true); put("room", "android-call-test"); put("canPublish", true); put("canSubscribe", true) })- }.toString().toByteArray())- val body = "$header.$payload"- val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec("secret".toByteArray(), "HmacSHA256")) }- return "$body.${encode(mac.doFinal(body.toByteArray()))}"- }-- private fun awaitCondition(message: String, condition: () -> Boolean) {- val deadline = System.currentTimeMillis() + 30_000- while (System.currentTimeMillis() < deadline) {- var ready = false- instrumentation.runOnMainSync { ready = condition() }- if (ready) return- Thread.sleep(100)- }- fail(message)- }-@Test fun nativeRoomSurvivesDuplicateStartAndReleasesCapture() {val url = InstrumentationRegistry.getArguments().getString("livekitUrl")assumeNotNull(url)for (permission in listOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA)) {instrumentation.uiAutomation.executeShellCommand("pm grant ${context.packageName} $permission").close()- awaitCondition("Capture permission was not granted") { context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED }+ instrumentation.awaitCondition("Capture permission was not granted") { context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED }}- val offer = CallOffer(UUID.randomUUID().toString(), "media-test", "Emulator media", url!!, token())+ val offer = CallOffer(UUID.randomUUID().toString(), "media-test", "Emulator media", url!!, liveKitToken("android-emulator-test", "android-call-test"))val previousTheme = Calls.drawerThemeval lightTheme = CallTheme(android.graphics.Color.WHITE, android.graphics.Color.rgb(30,30,30), android.graphics.Color.rgb(245,245,245),0x66000000, android.graphics.Color.rgb(230,230,230), android.graphics.Color.rgb(205,205,205), android.graphics.Color.DKGRAY,@@ -65,6 +37,7 @@ class MediaLifecycleTest {Calls.drawerTheme = lightThemeval observer = LiveKit.create(context)val extraObservers = List(3) { LiveKit.create(context) }+ val agent = LiveKit.create(context)val monitor = instrumentation.addMonitor(CallActivity::class.java.name, null, false)try {instrumentation.runOnMainSync {@@ -73,13 +46,14 @@ class MediaLifecycleTest {}val activity = instrumentation.waitForMonitorWithTimeout(monitor, 5000)assertNotNull("Native call controls did not open", activity)- awaitCondition("Native room did not connect") { Calls.state == "connected" }- instrumentation.runOnMainSync { Calls.scope.launch { observer.connect(url, token("media-observer")) } }- awaitCondition("Remote participant did not join") { Calls.room?.remoteParticipants?.isNotEmpty() == true }+ instrumentation.awaitCondition("Native room did not connect") { Calls.state == "connected" }+ instrumentation.runOnMainSync { Calls.scope.launch { observer.connect(url, liveKitToken("media-observer", "android-call-test")) } }+ instrumentation.awaitCondition("Remote participant did not join") { Calls.room?.remoteParticipants?.isNotEmpty() == true }instrumentation.runOnMainSync {- extraObservers.forEachIndexed { index, extra -> Calls.scope.launch { extra.connect(url, token("tile-observer-$index")) } }+ extraObservers.forEachIndexed { index, extra -> Calls.scope.launch { extra.connect(url, liveKitToken("tile-observer-$index", "android-call-test")) } }+ Calls.scope.launch { agent.connect(url, liveKitToken("agent-transcriber", "android-call-test", kind = "agent")) }}- awaitCondition("Participant strip test peers did not join") { Calls.room?.remoteParticipants?.size == 4 }+ instrumentation.awaitCondition("Participant strip test peers did not join") { Calls.room?.remoteParticipants?.size == 5 }val root = activity!!.findViewById<android.view.ViewGroup>(android.R.id.content).getChildAt(0) as android.widget.FrameLayoutfun assertDrawer(expectedTheme: CallTheme) {val drawer = root.findViewWithTag<android.widget.LinearLayout>("call-drawer")@@ -93,6 +67,10 @@ class MediaLifecycleTest {assertTrue("Controls must stay above Android navigation insets",position[1] + controls.height <= rootPosition[1] + root.height - root.paddingBottom)assertEquals(3, (controls as android.view.ViewGroup).childCount)+ val agentViews = arrayListOf<android.view.View>()+ root.findViewsWithText(agentViews, "agent-transcriber", android.view.View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION)+ assertTrue("Agents such as the transcriber must not appear as call participants", agentViews.isEmpty())+ assertFalse(Calls.snapshot()!!.getJSONArray("participantIdentities").toString().contains("agent-transcriber"))assertTrue(root.findViewWithTag<android.view.View>("call-primary").height > root.findViewWithTag<android.view.View>("call-participant-strip").height)}instrumentation.waitForIdleSync()@@ -103,24 +81,12 @@ class MediaLifecycleTest {strip.scrollTo(100, 0)assertTrue(strip.scrollX > 0)}- fun screenshot(name: String) {- instrumentation.waitForIdleSync()- // Idle messages can complete before SurfaceFlinger presents the next frame.- Thread.sleep(300)- instrumentation.uiAutomation.takeScreenshot().let { bitmap ->- val file = java.io.File(context.getExternalFilesDir(null), name)- file.outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }- bitmap.recycle()- // Gradle removes test app data after the run; retain synthetic UI evidence.- instrumentation.uiAutomation.executeShellCommand("cp ${file.absolutePath} /sdcard/Download/$name").close()- }- }- screenshot("call-drawer-light.png")+ instrumentation.screenshot("call-drawer-light.png")instrumentation.runOnMainSync { Calls.drawerTheme = darkTheme; Calls.publish() }instrumentation.waitForIdleSync()instrumentation.runOnMainSync { assertDrawer(darkTheme) }- screenshot("call-drawer-dark.png")- awaitCondition("Audio foreground service did not start") { CallService.instance != null }+ instrumentation.screenshot("call-drawer-dark.png")+ instrumentation.awaitCondition("Audio foreground service did not start") { CallService.instance != null }instrumentation.runOnMainSync {Calls.showIncoming(context)assertTrue("Late Telecom notification must retain microphone support",@@ -140,7 +106,7 @@ class MediaLifecycleTest {assertEquals(offer.callId, Calls.offer?.callId)assertNotNull(CallService.instance)}- awaitCondition("Failed camera promotion must preserve the ongoing notification") {+ instrumentation.awaitCondition("Failed camera promotion must preserve the ongoing notification") {context.getSystemService(android.app.NotificationManager::class.java).activeNotifications.any { it.id == CallService.NOTIFICATION_ID }}@@ -151,9 +117,9 @@ class MediaLifecycleTest {assertSame("Duplicate start must retain the media room", room, Calls.room)root.findViewWithTag<android.view.View>("call-control-mic").performClick()}- awaitCondition("Native microphone did not mute") { Calls.muted }+ instrumentation.awaitCondition("Native microphone did not mute") { Calls.muted }instrumentation.runOnMainSync { root.findViewWithTag<android.view.View>("call-control-video").performClick() }- awaitCondition("Native camera did not start") { Calls.video }+ instrumentation.awaitCondition("Native camera did not start") { Calls.video }instrumentation.runOnMainSync {val room = Calls.roomCalls.showIncoming(context)@@ -165,7 +131,7 @@ class MediaLifecycleTest {assertSame(room, Calls.room)assertTrue(Calls.video)}- awaitCondition("Remote participant did not receive video") {+ instrumentation.awaitCondition("Remote participant did not receive video") {observer.remoteParticipants.values.any { participant -> participant.trackPublications.values.any { it.track is VideoTrack } }}instrumentation.runOnMainSync {@@ -176,47 +142,38 @@ class MediaLifecycleTest {assertEquals("Selecting a chip must replace the primary participant", "You", root.findViewWithTag<android.view.View>("call-primary").contentDescription)assertNotNull(root.findViewWithTag<android.view.View>("call-control-switch"))}- screenshot("call-drawer-video.png")+ instrumentation.screenshot("call-drawer-video.png")instrumentation.runOnMainSync { root.findViewWithTag<android.view.View>("call-control-video").performClick() }- awaitCondition("Native camera did not stop") { !Calls.video }+ instrumentation.awaitCondition("Native camera did not stop") { !Calls.video }instrumentation.uiAutomation.executeShellCommand("svc wifi disable").close()instrumentation.uiAutomation.executeShellCommand("svc data disable").close()try {- awaitCondition("Native room did not report network interruption") { Calls.state == "reconnecting" }+ instrumentation.awaitCondition("Native room did not report network interruption") { Calls.state == "reconnecting" }} finally {instrumentation.uiAutomation.executeShellCommand("svc wifi enable").close()instrumentation.uiAutomation.executeShellCommand("svc data enable").close()}- awaitCondition("Native room did not reconnect") { Calls.state == "connected" }+ instrumentation.awaitCondition("Native room did not reconnect") { Calls.state == "connected" }instrumentation.runOnMainSync { Calls.scope.launch { Calls.camera(context, true) } }- awaitCondition("Native camera did not restart before PiP") { Calls.video }+ instrumentation.awaitCondition("Native camera did not restart before PiP") { Calls.video }val expandedWidth = root.width- instrumentation.runOnMainSync {- val handle = root.findViewWithTag<android.view.View>("call-drawer-handle")- val down = android.view.MotionEvent.obtain(0, 0, android.view.MotionEvent.ACTION_DOWN, 10f, 10f, 0)- val up = android.view.MotionEvent.obtain(0, 100, android.view.MotionEvent.ACTION_UP, 10f, 200f, 0)- handle.dispatchTouchEvent(down); handle.dispatchTouchEvent(up)- down.recycle(); up.recycle()- }- awaitCondition("Call controls did not enter picture in picture") { activity!!.isInPictureInPictureMode }- awaitCondition("PiP transition did not resize the activity") { root.width < expandedWidth }+ // Leaving the app from the drawer continues the call in PiP.+ instrumentation.uiAutomation.executeShellCommand("input keyevent 3").close()+ instrumentation.awaitCondition("Call controls did not enter picture in picture") { activity!!.isInPictureInPictureMode }+ instrumentation.awaitCondition("PiP transition did not resize the activity") { root.width < expandedWidth }// Mode callbacks precede completion of Android's pinned-task animation.Thread.sleep(1_000)- instrumentation.runOnMainSync {- context.startActivity(Intent(context, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))- }- awaitCondition("Reopening call controls did not expand the drawer") { !activity.isInPictureInPictureMode }- awaitCondition("Expanded drawer did not regain focus") { activity.hasWindowFocus() }- instrumentation.uiAutomation.executeShellCommand("input keyevent 4").close()- awaitCondition("Android Back must dismiss the drawer into PiP") { activity.isInPictureInPictureMode }- instrumentation.waitForIdleSync()+ instrumentation.screenshot("call-pip.png")instrumentation.runOnMainSync {assertTrue("Entering PiP must retain camera capture", Calls.video)assertEquals("connected", Calls.state)assertNotNull("Navigation must retain the media room", Calls.room)- activity!!.finish()+ context.startActivity(Intent(context, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))}- awaitCondition("Leaving the visible call surface must stop the camera") { !Calls.video }+ instrumentation.awaitCondition("Reopening call controls did not expand the drawer") { !activity.isInPictureInPictureMode }+ instrumentation.awaitCondition("Expanded drawer did not regain focus") { activity.hasWindowFocus() }+ instrumentation.runOnMainSync { activity.finish() }+ instrumentation.awaitCondition("Leaving the visible call surface must stop the camera") { !Calls.video }instrumentation.runOnMainSync {assertEquals("Background audio must remain connected", "connected", Calls.state)Calls.end(context, offer.callId)@@ -230,6 +187,7 @@ class MediaLifecycleTest {instrumentation.removeMonitor(monitor)instrumentation.runOnMainSync {extraObservers.forEach { it.disconnect(); it.release() }+ agent.disconnect(); agent.release()observer.disconnect(); observer.release(); Calls.end(context, offer.callId)Calls.drawerTheme = previousTheme}diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MiniWindowHostActivity.kt b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MiniWindowHostActivity.ktnew file mode 100644index 0000000000..c2c83b6ef1--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MiniWindowHostActivity.kt@@ -0,0 +1,20 @@+package com.macro.call++import android.os.Bundle+import android.webkit.WebView+import android.widget.FrameLayout+import androidx.appcompat.app.AppCompatActivity++/** Forwards the lifecycle callbacks Tauri delivers to [CallPlugin] in the app. */+class MiniWindowHostActivity : AppCompatActivity() {+ private lateinit var plugin: CallPlugin+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ setContentView(FrameLayout(this))+ plugin = CallPlugin(this)+ plugin.load(WebView(this))+ }+ override fun onResume() { super.onResume(); plugin.onResume(this) }+ override fun onStop() { super.onStop(); plugin.onStop(this) }+ override fun onDestroy() { plugin.onDestroy(this); super.onDestroy() }+}diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MiniWindowTest.kt b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MiniWindowTest.ktnew file mode 100644index 0000000000..fc56d6db64--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MiniWindowTest.kt@@ -0,0 +1,129 @@+package com.macro.call++import android.Manifest+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build+import android.view.MotionEvent+import android.view.View+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry+import androidx.test.runner.lifecycle.Stage+import io.livekit.android.LiveKit+import kotlinx.coroutines.launch+import org.junit.Assert.*+import org.junit.Assume.assumeNotNull+import org.junit.Assume.assumeTrue+import org.junit.Test+import org.junit.runner.RunWith+import java.util.UUID++/** Optional integration test of the iOS-style in-app call window against LiveKit's isolated --dev server. */+@RunWith(AndroidJUnit4::class)+class MiniWindowTest {+ private val instrumentation = InstrumentationRegistry.getInstrumentation()+ private val context = instrumentation.targetContext+ private val room = "android-mini-window-test"++ @Test fun drawerMinimizesInAppAndLeavingTheAppContinuesInPictureInPicture() {+ val url = InstrumentationRegistry.getArguments().getString("livekitUrl")+ assumeNotNull(url)+ assumeTrue("Auto-entering PiP requires Android 12", Build.VERSION.SDK_INT >= 31)+ for (permission in listOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA)) {+ instrumentation.uiAutomation.executeShellCommand("pm grant ${context.packageName} $permission").close()+ instrumentation.awaitCondition("Capture permission was not granted") { context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED }+ }+ val offer = CallOffer(UUID.randomUUID().toString(), "mini-window-test", "Mini window", url!!, liveKitToken("mini-window-test", room))+ val observer = LiveKit.create(context)+ val host = instrumentation.startActivitySync(Intent(context, MiniWindowHostActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ val hostRoot = host.findViewById<android.view.ViewGroup>(android.R.id.content)+ fun thumbnail() = hostRoot.findViewWithTag<View>("call-mini-window")+ fun edgeTab() = hostRoot.findViewWithTag<View>("call-edge-tab")+ fun returnToApp() = context.startActivity(Intent(context, MiniWindowHostActivity::class.java)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))+ // The live drawer, whether open or in PiP; call on the main thread.+ fun drawer() = listOf(Stage.RESUMED, Stage.PAUSED).flatMap { ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(it) }+ .filterIsInstance<CallActivity>().firstOrNull { !it.isFinishing }+ try {+ instrumentation.runOnMainSync { Calls.outgoing(context, offer) }+ instrumentation.awaitCondition("Native room did not connect") { Calls.state == "connected" }+ instrumentation.runOnMainSync { Calls.scope.launch { observer.connect(url, liveKitToken("mini-window-observer", room)) } }+ instrumentation.awaitCondition("Remote participant did not join") { Calls.room?.remoteParticipants?.isNotEmpty() == true }+ instrumentation.awaitCondition("Connecting must open the drawer") { Calls.overlay == "expanded" && drawer()?.hasWindowFocus() == true }+ instrumentation.runOnMainSync { Calls.scope.launch { Calls.camera(context, true) } }+ instrumentation.awaitCondition("Native camera did not start") { Calls.video }++ instrumentation.uiAutomation.executeShellCommand("input keyevent 4").close()+ instrumentation.awaitCondition("Back must shrink the drawer to the in-app thumbnail") {+ Calls.overlay == "minimized" && !CallActivity.isOpen && thumbnail().visibility == View.VISIBLE+ }+ instrumentation.screenshot("call-mini-window.png")+ instrumentation.runOnMainSync { assertTrue("The thumbnail keeps showing the camera", Calls.video) }++ instrumentation.runOnMainSync { thumbnail().performClick() }+ instrumentation.awaitCondition("Tapping the thumbnail must reopen the drawer") {+ Calls.overlay == "expanded" && thumbnail().visibility == View.GONE && drawer()?.hasWindowFocus() == true+ }+ instrumentation.uiAutomation.executeShellCommand("input keyevent 4").close()+ instrumentation.awaitCondition("Back must minimize again") { Calls.overlay == "minimized" && !CallActivity.isOpen }++ // Leaving the app from the thumbnail turns Macro's own window into the call's PiP.+ instrumentation.uiAutomation.executeShellCommand("input keyevent 3").close()+ instrumentation.awaitCondition("Leaving the app must continue the call in PiP") { host.isInPictureInPictureMode }+ // Mode callbacks precede completion of Android's pinned-task animation.+ Thread.sleep(1_000)+ instrumentation.screenshot("call-pip-from-mini-window.png")+ instrumentation.runOnMainSync {+ assertNotNull(hostRoot.findViewWithTag<View>("call-pip"))+ assertTrue("PiP keeps the camera", Calls.video)+ }++ returnToApp()+ instrumentation.awaitCondition("Expanding PiP must open the drawer, as iOS restores") {+ !host.isInPictureInPictureMode && Calls.overlay == "expanded" && drawer()?.hasWindowFocus() == true+ }++ // From the drawer, the drawer itself becomes PiP, and returning to the app reopens it.+ instrumentation.uiAutomation.executeShellCommand("input keyevent 3").close()+ instrumentation.awaitCondition("The drawer did not enter PiP") { drawer()?.isInPictureInPictureMode == true && Calls.overlay == "minimized" }+ returnToApp()+ instrumentation.awaitCondition("Returning to the app must reopen the drawer from its PiP") {+ drawer()?.isInPictureInPictureMode == false && drawer()?.hasWindowFocus() == true && Calls.overlay == "expanded"+ }+ instrumentation.uiAutomation.executeShellCommand("input keyevent 4").close()+ instrumentation.awaitCondition("Back must minimize the restored drawer") { thumbnail().visibility == View.VISIBLE && !CallActivity.isOpen }+ instrumentation.runOnMainSync { assertTrue("The thumbnail keeps the camera", Calls.video) }++ instrumentation.runOnMainSync {+ // Drag the thumbnail past the right edge, as on iOS, to tuck the call away.+ val view = thumbnail()+ val start = MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0f, 0f, 0)+ val move = MotionEvent.obtain(0, 50, MotionEvent.ACTION_MOVE, hostRoot.width.toFloat(), 0f, 0)+ val end = MotionEvent.obtain(0, 100, MotionEvent.ACTION_UP, hostRoot.width.toFloat(), 0f, 0)+ listOf(start, move, end).forEach { view.dispatchTouchEvent(it); it.recycle() }+ }+ instrumentation.awaitCondition("Dragging past the edge must leave an edge tab") {+ Calls.overlay == "hidden" && thumbnail().visibility == View.GONE && edgeTab().visibility == View.VISIBLE+ }+ instrumentation.runOnMainSync { edgeTab().performClick() }+ instrumentation.awaitCondition("The edge tab must restore the thumbnail") { Calls.overlay == "minimized" && thumbnail().visibility == View.VISIBLE }++ instrumentation.uiAutomation.executeShellCommand("input keyevent 3").close()+ instrumentation.awaitCondition("The call did not enter PiP again") { host.isInPictureInPictureMode }+ // Remove the pinned task, as closing PiP does; the activity stops without expanding.+ instrumentation.uiAutomation.executeShellCommand("am stack remove ${host.taskId}").use { android.os.ParcelFileDescriptor.AutoCloseInputStream(it).readBytes() }+ instrumentation.awaitCondition("Closing PiP must stop the camera") { !Calls.video }+ instrumentation.runOnMainSync {+ assertFalse("Closing PiP must not open the drawer", CallActivity.isOpen)+ assertEquals("Background audio must remain connected", "connected", Calls.state)+ Calls.end(context, offer.callId)+ }+ } finally {+ instrumentation.runOnMainSync {+ observer.disconnect(); observer.release(); Calls.end(context, offer.callId)+ host.finish()+ }+ }+ }+}diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallActivity.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallActivity.ktindex cc324f8961..429f45a637 100644--- a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallActivity.kt+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallActivity.kt@@ -2,13 +2,13 @@ package com.macro.callimport android.Manifestimport android.app.Activity-import android.app.PictureInPictureParams+import android.app.KeyguardManagerimport android.content.Intentimport android.content.pm.PackageManager+import android.content.res.ColorStateListimport android.os.Buildimport android.os.Bundleimport android.telecom.CallAudioState-import android.util.Rationalimport android.view.Viewimport android.view.WindowManagerimport androidx.core.view.ViewCompat@@ -21,9 +21,10 @@ import android.view.Gravityimport android.view.MotionEventimport android.widget.*import io.livekit.android.renderer.SurfaceViewRenderer-import io.livekit.android.room.track.Trackimport io.livekit.android.room.track.VideoTrackimport kotlinx.coroutines.launch+import livekit.org.webrtc.RendererCommon+import java.lang.ref.WeakReference/** Native media UI also owns PiP: navigating/reloading the WebView never owns the room. */class CallActivity : Activity() {@@ -31,6 +32,8 @@ class CallActivity : Activity() {private var backCallback: android.window.OnBackInvokedCallback? = nullprivate var pipRequested = falseprivate var primaryId: String? = null+ // Set when the call moves to the in-app mini-window, which keeps showing the camera.+ private var keepCamera = falseprivate var swipeY = 0fprivate var stripScroll = 0private var participantStrip: HorizontalScrollView? = null@@ -43,6 +46,7 @@ class CallActivity : Activity() {private val callback: () -> Unit = { render() }override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)+ current = WeakReference(this)if (Build.VERSION.SDK_INT >= 33) {backCallback = android.window.OnBackInvokedCallback { dismissDrawer() }onBackInvokedDispatcher.registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT, backCallback!!)@@ -53,7 +57,8 @@ class CallActivity : Activity() {window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(Color.TRANSPARENT))layout = FrameLayout(this)layout.addOnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->- if (right - left != oldRight - oldLeft || bottom - top != oldBottom - oldTop) { rendered = null; render() }+ // Views added during a layout pass stay unmeasured until another pass, which never comes after PiP shrinks the window.+ if (right - left != oldRight - oldLeft || bottom - top != oldBottom - oldTop) layout.post { rendered = null; render() }}ViewCompat.setOnApplyWindowInsetsListener(layout) { view, insets ->val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout())@@ -120,28 +125,28 @@ class CallActivity : Activity() {setPadding(dp(16), 0, dp(16), 0); minimumHeight = dp(48)isClickable = true; isFocusable = true; setOnClickListener { action() }}- private fun icon(kind: String, name: String, active: Boolean = false, off: Boolean = false, action: () -> Unit) = ImageButton(this).apply {- setImageDrawable(CallControlIcon(kind, theme!!.text, off)); scaleType = ImageView.ScaleType.CENTER_INSIDE- setPadding(dp(14), dp(14), dp(14), dp(14)); background = background(if (active) theme!!.edgeMuted else theme!!.drawer, 12, theme!!.edge)+ private fun icon(drawable: Int, kind: String, name: String, active: Boolean = false, action: () -> Unit) = ImageButton(this).apply {+ setImageResource(drawable); imageTintList = ColorStateList.valueOf(theme!!.text); scaleType = ImageView.ScaleType.CENTER+ background = background(if (active) theme!!.edgeMuted else theme!!.drawer, 12, theme!!.edge)tag = "call-control-$kind"contentDescription = name; isSelected = active; setOnClickListener { action() }}private fun detach() { renderers.forEach { (track, renderer) -> track.removeRenderer(renderer); renderer.release() }; renderers.clear() }+ private fun video(track: VideoTrack, mirror: Boolean) = SurfaceViewRenderer(this).also { renderer ->+ renderer.setZOrderMediaOverlay(true)+ renderer.setMirror(mirror)+ Calls.room?.initVideoRenderer(renderer); track.addRenderer(renderer)+ renderers.add(track to renderer)+ }private fun tile(participant: ParticipantTile?, large: Boolean): FrameLayout = FrameLayout(this).apply {background = background(theme!!.tile, 16); clipToOutline = truetag = if (large) "call-primary" else "call-participant"val name = participant?.name ?: "Waiting for others"contentDescription = nameparticipant?.track?.let { track ->- val renderer = SurfaceViewRenderer(this@CallActivity)- renderer.setZOrderMediaOverlay(true)- renderer.setMirror(participant.local)- Calls.room?.initVideoRenderer(renderer); track.addRenderer(renderer)- renderers.add(track to renderer)- addView(renderer, FrameLayout.LayoutParams(-1, -1))+ addView(video(track, participant.local), FrameLayout.LayoutParams(-1, -1))} ?: run {- val initials = participant?.name?.split(' ')?.filter { it.isNotBlank() }?.take(2)?.joinToString("") { it.take(1).uppercase() } ?: ""- val avatar = label(initials, if (large) 32f else 18f).apply {+ val avatar = label(participant?.name?.let(Calls::initials).orEmpty(), if (large) 32f else 18f).apply {gravity = Gravity.CENTER; background = background(theme!!.edgeMuted, 100)}val size = dp(if (large) 88 else 40)@@ -152,7 +157,7 @@ class CallActivity : Activity() {background = background(theme!!.edgeMuted, 8)}, FrameLayout.LayoutParams(-2, -2, Gravity.BOTTOM or Gravity.START).apply { bottomMargin = dp(10); leftMargin = dp(10); rightMargin = dp(10) })if (participant != null && !large) setOnClickListener { primaryId = participant.id; stripScroll = participantStrip?.scrollX ?: 0; rendered = null; render() }- if (participant?.local == true && Calls.video && large) addView(icon("switch", "Switch camera") { Calls.switchCamera() },+ if (participant?.local == true && Calls.video && large) addView(icon(R.drawable.macro_call_camera_rotate, "switch", "Switch camera") { Calls.switchCamera() },FrameLayout.LayoutParams(dp(48), dp(48), Gravity.TOP or Gravity.END).apply { topMargin = dp(8); rightMargin = dp(8) })}private fun render() {@@ -163,28 +168,27 @@ class CallActivity : Activity() {isAppearanceLightNavigationBars = light; isAppearanceLightStatusBars = light}val media = Calls.room- fun video(participant: io.livekit.android.room.participant.Participant): VideoTrack? {- val publication = participant.getTrackPublication(Track.Source.CAMERA)- return publication?.takeUnless { it.muted }?.track as? VideoTrack- }- val remote = media?.remoteParticipants?.values?.map { participant ->- val id = participant.identity?.value ?: participant.sid.value- ParticipantTile(id, Calls.displayNames[id] ?: participant.name?.takeIf { it.isNotBlank() } ?: id.substringAfter('|'), video(participant))- }.orEmpty()- val local = media?.localParticipant?.let { ParticipantTile(it.identity?.value ?: "local", "You", if (Calls.video) video(it) else null, true) }+ val remote = media?.let { Calls.remoteHumans(it) }?.map { ParticipantTile(Calls.participantId(it), Calls.displayName(it), Calls.cameraTrack(it)) }.orEmpty()+ val local = media?.localParticipant?.let { ParticipantTile(Calls.participantId(it), "You", if (Calls.video) Calls.cameraTrack(it) else null, true) }val participants = remote + listOfNotNull(local)val primary = participants.firstOrNull { it.id == primaryId } ?: remote.firstOrNull()primaryId = primary?.id+ val speaker = media?.let { Calls.spotlight(it) }?.let { spotlight -> remote.firstOrNull { it.id == Calls.participantId(spotlight) } }+ val pipState = if (isInPictureInPictureMode) listOf(speaker, media?.let { Calls.localName(it) }) else nullval nextRender = listOf(call.callId, Calls.title, Calls.state, Calls.error, Calls.muted, Calls.video, Calls.audioRoute,- isInPictureInPictureMode, participants, primaryId, theme, layout.width, layout.height, layout.paddingBottom)+ pipState, participants, primaryId, theme, layout.width, layout.height, layout.paddingBottom)if (rendered == nextRender) returnrendered = nextRender+ if (media != null) setPictureInPictureParams(CallPictureInPicture.params(this))stripScroll = participantStrip?.scrollX ?: stripScrollparticipantStrip = nulldetach(); layout.removeAllViews()- layout.setBackgroundColor(if (isInPictureInPictureMode) theme!!.tile else theme!!.scrim)+ layout.setBackgroundColor(theme!!.scrim)if (isInPictureInPictureMode) {- layout.addView(tile(primary ?: local, true), FrameLayout.LayoutParams(-1, -1))+ val pip = CallPictureInPicture.view(this, media?.let { Calls.localName(it) } ?: "You", local?.track, speaker?.name, speaker?.track) { track, mirror ->+ video(track, mirror).apply { setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FILL) }+ }+ layout.addView(pip, FrameLayout.LayoutParams(-1, -1))return}layout.setOnClickListener { dismissDrawer() }@@ -230,20 +234,22 @@ class CallActivity : Activity() {}, LinearLayout.LayoutParams(dp(160), dp(52)))else {fun control(button: ImageButton, name: String) {- val column = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER }+ val column = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL }column.addView(button, LinearLayout.LayoutParams(dp(56), dp(52)))- column.addView(label(name, 11f, theme!!.muted).apply { gravity = Gravity.START or Gravity.CENTER_VERTICAL }, LinearLayout.LayoutParams(dp(56), dp(24)))+ column.addView(label(name, 12f).apply { gravity = Gravity.CENTER }, LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(6) })controls.addView(column, LinearLayout.LayoutParams(dp(88), -2))}- val speaker = icon("speaker", "Speaker mode", Calls.audioRoute == "Speakerphone") {+ val speaker = icon(R.drawable.macro_call_speaker_high, "speaker", "Speaker mode", Calls.audioRoute == "Speakerphone") {Calls.route(if (Calls.audioRoute == "Speakerphone") CallAudioState.ROUTE_EARPIECE else CallAudioState.ROUTE_SPEAKER)}speaker.setOnLongClickListener { audioRoutes(); true }control(speaker, "Speaker")- control(icon("mic", if (Calls.muted) "Unmute" else "Mute", Calls.muted, Calls.muted) {+ control(icon(if (Calls.muted) R.drawable.macro_call_microphone_slash else R.drawable.macro_call_microphone,+ "mic", if (Calls.muted) "Unmute" else "Mute", Calls.muted) {Calls.scope.launch { runCatching { Calls.microphone(Calls.muted) }.onSuccess { Calls.error = null; render() }.onFailure { Calls.error = "Could not change microphone"; render() } }}, if (Calls.muted) "Unmute" else "Mute")- control(icon("video", if (Calls.video) "Video off" else "Video on", Calls.video, !Calls.video) {+ control(icon(if (Calls.video) R.drawable.macro_call_video_camera else R.drawable.macro_call_video_camera_slash,+ "video", if (Calls.video) "Video off" else "Video on", Calls.video) {val cameraRoom = media ?: return@iconval enabled = !Calls.videopermission(Manifest.permission.CAMERA) { Calls.scope.launch { runCatching { Calls.camera(this@CallActivity, enabled, expectedRoom = cameraRoom) }.onSuccess { Calls.error = null; render() }.onFailure { Calls.error = "Could not change camera"; render() } } }@@ -261,21 +267,33 @@ class CallActivity : Activity() {}.show()}private fun dismissDrawer() {- if (!pip()) {- packageManager.getLaunchIntentForPackage(packageName)?.let { startActivity(it) }- finish()- }+ // Macro can't show over the lock screen, so the call stays in PiP there.+ if (getSystemService(KeyguardManager::class.java).isKeyguardLocked && pip()) return+ // As on iOS, the call shrinks to a thumbnail over Macro; PiP starts once the user leaves the app.+ keepCamera = true+ Calls.setOverlay("minimized")+ // Not a user leave: without the flag, onUserLeaveHint would put the closing drawer into PiP.+ packageManager.getLaunchIntentForPackage(packageName)?.let { startActivity(it.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION)) }+ finish()}@Deprecated("Deprecated in Android") override fun onBackPressed() { dismissDrawer() }private fun pip(): Boolean {- if (Calls.room == null || !packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false+ if (isFinishing || Calls.room == null || !packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return falsepipRequested = true- return runCatching { enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(16, 9)).build()) }+ return runCatching { enterPictureInPictureMode(CallPictureInPicture.params(this)) }.getOrDefault(false).also { if (!it) pipRequested = false }}override fun onUserLeaveHint() { pip() }+ override fun onResume() {+ super.onResume()+ if (!isInPictureInPictureMode) Calls.setOverlay("expanded")+ }override fun onPictureInPictureModeChanged(inPip: Boolean, config: android.content.res.Configuration) {- super.onPictureInPictureModeChanged(inPip, config); pipRequested = inPip; render()+ super.onPictureInPictureModeChanged(inPip, config); pipRequested = inPip+ // If this PiP is closed, Macro shows the thumbnail when the user comes back.+ // The callback can trail a quick return to Macro that already expanded PiP again.+ if (inPip && isInPictureInPictureMode) Calls.setOverlay("minimized")+ render()}override fun onStop() {super.onStop()@@ -284,11 +302,8 @@ class CallActivity : Activity() {if (isFinishing || (!pipRequested && !isInPictureInPictureMode)) stopCameraIfOwned()}private fun stopCameraIfOwned() {- if (isChangingConfigurations || Calls.changed !== callback || !Calls.video) return- val media = Calls.room ?: return- Calls.scope.launch {- if (Calls.room === media) runCatching { Calls.camera(this@CallActivity, false, media) }- }+ if (keepCamera || isChangingConfigurations || Calls.changed !== callback) return+ Calls.stopCamera(this)}override fun onDestroy() {if (Build.VERSION.SDK_INT >= 33) backCallback?.let { onBackInvokedDispatcher.unregisterOnBackInvokedCallback(it) }@@ -297,6 +312,14 @@ class CallActivity : Activity() {permissionCallId = null; permissionAction = nullstopCameraIfOwned()if (Calls.changed === callback) Calls.changed = null+ if (current?.get() === this) current = null+ // The mini-window may start offering PiP now that the drawer is gone.+ Calls.refresh()detach(); super.onDestroy()}+ companion object {+ private var current: WeakReference<CallActivity>? = null+ val isOpen get() = current?.get() != null+ val inPictureInPicture get() = current?.get()?.isInPictureInPictureMode == true+ }}diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallControlIcon.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallControlIcon.ktdeleted file mode 100644index 0d1534143f..0000000000--- a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallControlIcon.kt+++ /dev/null@@ -1,41 +0,0 @@-package com.macro.call--import android.graphics.*-import android.graphics.drawable.Drawable--/** Small monochrome call controls, independent of the platform's button theme. */-internal class CallControlIcon(private val kind: String, color: Int, private val off: Boolean = false) : Drawable() {- private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeWidth = 1.8f; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }- override fun draw(canvas: Canvas) {- canvas.save()- canvas.translate(bounds.left.toFloat(), bounds.top.toFloat())- canvas.scale(bounds.width() / 24f, bounds.height() / 24f)- when (kind) {- "speaker" -> {- canvas.drawPath(Path().apply { moveTo(3f,9f); lineTo(7f,9f); lineTo(12f,5f); lineTo(12f,19f); lineTo(7f,15f); lineTo(3f,15f); close() }, paint)- canvas.drawArc(11f,7f,19f,17f,-60f,120f,false,paint)- canvas.drawArc(9f,3f,23f,21f,-50f,100f,false,paint)- }- "mic" -> {- canvas.drawRoundRect(9f,3f,15f,14f,3f,3f,paint)- canvas.drawArc(6f,7f,18f,18f,0f,180f,false,paint)- canvas.drawLine(12f,18f,12f,21f,paint); canvas.drawLine(9f,21f,15f,21f,paint)- }- "video" -> {- canvas.drawRoundRect(3f,6f,16f,18f,2f,2f,paint)- canvas.drawPath(Path().apply { moveTo(16f,10f); lineTo(21f,7f); lineTo(21f,17f); lineTo(16f,14f) },paint)- }- "switch" -> {- canvas.drawArc(4f,4f,20f,20f,30f,140f,false,paint)- canvas.drawArc(4f,4f,20f,20f,210f,140f,false,paint)- canvas.drawLine(4f,12f,4f,17f,paint); canvas.drawLine(4f,17f,9f,17f,paint)- canvas.drawLine(20f,12f,20f,7f,paint); canvas.drawLine(20f,7f,15f,7f,paint)- }- }- if (off) canvas.drawLine(3f,3f,21f,21f,paint)- canvas.restore()- }- override fun setAlpha(alpha: Int) { paint.alpha = alpha; invalidateSelf() }- override fun setColorFilter(filter: ColorFilter?) { paint.colorFilter = filter; invalidateSelf() }- @Deprecated("Deprecated in Android") override fun getOpacity(): Int = PixelFormat.TRANSLUCENT-}diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallMiniWindow.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallMiniWindow.ktnew file mode 100644index 0000000000..0d6622f055--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallMiniWindow.kt@@ -0,0 +1,214 @@+package com.macro.call++import android.app.Activity+import android.content.pm.PackageManager+import android.graphics.Rect+import android.graphics.Typeface+import android.graphics.drawable.GradientDrawable+import android.os.Build+import android.view.Gravity+import android.view.MotionEvent+import android.view.View+import android.view.ViewConfiguration+import android.widget.FrameLayout+import android.widget.LinearLayout+import android.widget.TextView+import androidx.core.app.OnPictureInPictureModeChangedProvider+import androidx.core.app.OnUserLeaveHintProvider+import androidx.core.app.PictureInPictureModeChangedInfo+import androidx.core.graphics.Insets+import androidx.core.util.Consumer+import androidx.core.view.ViewCompat+import androidx.core.view.WindowInsetsCompat+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleOwner+import io.livekit.android.renderer.TextureViewRenderer+import io.livekit.android.room.track.VideoTrack+import livekit.org.webrtc.RendererCommon+import kotlin.math.hypot++/**+ * The iOS call thumbnail over Macro's WebView: tap reopens the drawer, drag snaps it to a corner, and+ * dragging it past a side tucks it into an edge tab. Leaving Macro turns this activity into the call's+ * PiP window, the Android counterpart of iOS starting PiP from the inline thumbnail.+ */+internal class CallMiniWindow(private val activity: Activity, private val webView: View) {+ private val root: FrameLayout = activity.findViewById(android.R.id.content)+ private val thumbnail = FrameLayout(activity).apply {+ tag = "call-mini-window"; contentDescription = "Return to call"; clipToOutline = true; visibility = View.GONE+ }+ private val edgeTab = TextView(activity).apply {+ tag = "call-edge-tab"; contentDescription = "Show call"; text = "‹"; textSize = 18f+ typeface = Typeface.DEFAULT_BOLD; gravity = Gravity.CENTER; visibility = View.GONE+ }+ private val pip = FrameLayout(activity).apply { visibility = View.GONE }+ private val renderers = mutableListOf<Pair<VideoTrack, TextureViewRenderer>>()+ private var rendered: List<Any?>? = null+ private var left = false+ private var top = true+ private var dragging = false+ private var inPictureInPicture = false+ private val callback: () -> Unit = { render() }+ private val layoutListener = View.OnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->+ if (!dragging && (right - left != oldRight - oldLeft || bottom - top != oldBottom - oldTop)) place()+ }+ // Android 12+ enters PiP from the auto-enter params; older versions need the leave hint.+ private val leaveHint = Runnable {+ if (Build.VERSION.SDK_INT < 31 && pictureInPictureAllowed()) runCatching { activity.enterPictureInPictureMode(CallPictureInPicture.params(activity)) }+ }+ private val pictureInPictureListener = Consumer<PictureInPictureModeChangedInfo> { info -> pictureInPictureChanged(info.isInPictureInPictureMode) }++ init {+ root.addView(thumbnail, FrameLayout.LayoutParams(dp(160), dp(112), Gravity.TOP or Gravity.START))+ root.addView(edgeTab, FrameLayout.LayoutParams(dp(34), dp(72), Gravity.END or Gravity.CENTER_VERTICAL))+ root.addView(pip, FrameLayout.LayoutParams(-1, -1))+ root.addOnLayoutChangeListener(layoutListener)+ thumbnail.setOnClickListener { Calls.openDrawer(activity) }+ edgeTab.setOnClickListener { Calls.setOverlay("minimized") }+ val slop = ViewConfiguration.get(activity).scaledTouchSlop+ var downX = 0f; var downY = 0f; var startX = 0f; var startY = 0f+ thumbnail.setOnTouchListener { view, event ->+ when (event.actionMasked) {+ MotionEvent.ACTION_DOWN -> { downX = event.rawX; downY = event.rawY; startX = view.x; startY = view.y; dragging = false; view.animate().cancel() }+ MotionEvent.ACTION_MOVE -> {+ if (!dragging && hypot(event.rawX - downX, event.rawY - downY) > slop) dragging = true+ if (dragging) { view.x = startX + event.rawX - downX; view.y = startY + event.rawY - downY }+ }+ MotionEvent.ACTION_UP -> if (dragging) settle() else view.performClick()+ MotionEvent.ACTION_CANCEL -> if (dragging) settle()+ }+ true+ }+ (activity as? OnUserLeaveHintProvider)?.addOnUserLeaveHintListener(leaveHint)+ (activity as? OnPictureInPictureModeChangedProvider)?.addOnPictureInPictureModeChangedListener(pictureInPictureListener)+ Calls.miniWindowChanged = callback+ render()+ }++ private fun dp(value: Int) = (value * activity.resources.displayMetrics.density).toInt()++ private fun pictureInPictureAllowed() = Calls.room != null && Calls.overlay == "minimized" && !CallActivity.isOpen &&+ activity.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)++ private fun pictureInPictureChanged(active: Boolean) {+ inPictureInPicture = active+ // Hidden, the WebView keeps its size instead of re-laying out Macro at PiP size.+ webView.visibility = if (active) View.GONE else View.VISIBLE+ rendered = null+ render()+ // Expanding PiP opens the drawer, as iOS does when restoring; closing PiP leaves the activity stopped.+ val expanded = (activity as? LifecycleOwner)?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.STARTED) == true+ if (!active && expanded) Calls.openDrawer(activity)+ }++ // Auto-enter PiP only while the thumbnail is showing, animating from its bounds.+ private fun updatePictureInPicture() {+ if (Build.VERSION.SDK_INT < 31 || inPictureInPicture) return+ val allowed = pictureInPictureAllowed() && thumbnail.isShown+ val source = Rect().takeIf { allowed && thumbnail.getGlobalVisibleRect(it) }+ // Builds whose main activity can't enter PiP reject the params.+ runCatching { activity.setPictureInPictureParams(CallPictureInPicture.params(activity, source, autoEnter = allowed)) }+ }++ private fun settle() {+ dragging = false+ val centerX = thumbnail.x + thumbnail.width / 2+ if (centerX > root.width + dp(24) || centerX < -dp(24)) {+ Calls.setOverlay("hidden")+ return+ }+ left = centerX < root.width / 2+ top = thumbnail.y + thumbnail.height / 2 < root.height / 2+ place(animate = true)+ }++ // iOS geometry: under the status bar at the top, clear of the bottom navigation at the bottom.+ private fun place(animate: Boolean = false) {+ if (root.width == 0) return+ val bars = ViewCompat.getRootWindowInsets(root)?.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()) ?: Insets.NONE+ val x = if (left) bars.left + dp(8) else root.width - bars.right - dp(8) - dp(160)+ val y = if (top) bars.top else root.height - bars.bottom - dp(8) - dp(112) - dp(88)+ if (animate) thumbnail.animate().x(x.toFloat()).y(y.toFloat()).setDuration(200).withEndAction { updatePictureInPicture() }.start()+ else { thumbnail.x = x.toFloat(); thumbnail.y = y.toFloat(); thumbnail.post(::updatePictureInPicture) }+ }++ private fun video(track: VideoTrack, mirror: Boolean) = TextureViewRenderer(activity).also { renderer ->+ Calls.room?.initVideoRenderer(renderer)+ renderer.setMirror(mirror)+ renderer.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FILL)+ track.addRenderer(renderer)+ renderers.add(track to renderer)+ }++ private fun detach() {+ renderers.forEach { (track, renderer) -> track.removeRenderer(renderer); renderer.release() }+ renderers.clear()+ }++ private fun half(title: String?, track: VideoTrack?, mirror: Boolean, theme: CallTheme) = FrameLayout(activity).apply {+ if (track != null) {+ addView(video(track, mirror), FrameLayout.LayoutParams(-1, -1))+ return@apply+ }+ val label = TextView(activity).apply { setTextColor(theme.text); gravity = Gravity.CENTER; typeface = Typeface.DEFAULT_BOLD }+ if (title == null) {+ label.text = "No one\nelse is here"; label.textSize = 11f+ addView(label, FrameLayout.LayoutParams(-1, -2, Gravity.CENTER).apply { leftMargin = dp(8); rightMargin = dp(8) })+ } else {+ label.text = Calls.initials(title); label.textSize = 18f+ label.background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(theme.edgeMuted) }+ addView(label, FrameLayout.LayoutParams(dp(44), dp(44), Gravity.CENTER))+ }+ }++ fun render() {+ val media = Calls.room+ if (media == null && inPictureInPicture) {+ // The call ended in PiP; there is nothing left to show.+ activity.moveTaskToBack(false)+ return+ }+ val theme = Calls.drawerTheme ?: CallTheme.load(activity)+ val spotlight = media?.let { Calls.spotlight(it) }+ val showThumbnail = media != null && Calls.overlay == "minimized" && !inPictureInPicture+ // iOS offers the edge tab only once someone else is in the call.+ val showTab = media != null && Calls.overlay == "hidden" && spotlight != null && !inPictureInPicture+ val localTrack = if (Calls.video) media?.localParticipant?.let { Calls.cameraTrack(it) } else null+ val next = listOf(showThumbnail, showTab, inPictureInPicture, theme, media?.let { Calls.localName(it) }, localTrack,+ spotlight?.let { Calls.displayName(it) }, spotlight?.let { Calls.cameraTrack(it) }, Calls.muted, CallActivity.isOpen)+ if (next == rendered) return+ rendered = next+ detach(); thumbnail.removeAllViews(); pip.removeAllViews()+ edgeTab.visibility = if (showTab) View.VISIBLE else View.GONE+ edgeTab.setTextColor(theme.text)+ edgeTab.background = GradientDrawable().apply { setColor(theme.edgeMuted); cornerRadius = dp(10).toFloat() }+ if (showTab) edgeTab.bringToFront()+ pip.visibility = if (inPictureInPicture) View.VISIBLE else View.GONE+ if (inPictureInPicture && media != null) {+ activity.setPictureInPictureParams(CallPictureInPicture.params(activity))+ pip.addView(CallPictureInPicture.view(activity, Calls.localName(media), localTrack, spotlight?.let { Calls.displayName(it) },+ spotlight?.let { Calls.cameraTrack(it) }, ::video), FrameLayout.LayoutParams(-1, -1))+ pip.bringToFront()+ }+ if (!showThumbnail) { thumbnail.visibility = View.GONE; updatePictureInPicture(); return }+ thumbnail.background = GradientDrawable().apply { setColor(theme.tile); cornerRadius = dp(12).toFloat(); setStroke(dp(1), theme.edge) }+ val halves = LinearLayout(activity)+ halves.addView(half(media?.let { Calls.localName(it) }, localTrack, true, theme), LinearLayout.LayoutParams(0, -1, 1f))+ halves.addView(View(activity).apply { setBackgroundColor(theme.edge) }, LinearLayout.LayoutParams(dp(1), -1))+ halves.addView(half(spotlight?.let { Calls.displayName(it) }, spotlight?.let { Calls.cameraTrack(it) }, false, theme), LinearLayout.LayoutParams(0, -1, 1f))+ thumbnail.addView(halves, FrameLayout.LayoutParams(-1, -1))+ thumbnail.visibility = View.VISIBLE+ thumbnail.bringToFront()+ // A speaker change mid-drag must not snap the thumbnail out from under the finger.+ if (!dragging) place()+ }++ fun release() {+ if (Calls.miniWindowChanged === callback) Calls.miniWindowChanged = null+ (activity as? OnUserLeaveHintProvider)?.removeOnUserLeaveHintListener(leaveHint)+ (activity as? OnPictureInPictureModeChangedProvider)?.removeOnPictureInPictureModeChangedListener(pictureInPictureListener)+ root.removeOnLayoutChangeListener(layoutListener)+ detach()+ root.removeView(thumbnail); root.removeView(edgeTab); root.removeView(pip)+ }+}diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPictureInPicture.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPictureInPicture.ktnew file mode 100644index 0000000000..4c4a9dc19c--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPictureInPicture.kt@@ -0,0 +1,66 @@+package com.macro.call++import android.app.PictureInPictureParams+import android.app.RemoteAction+import android.content.Context+import android.graphics.Color+import android.graphics.Rect+import android.graphics.Typeface+import android.graphics.drawable.GradientDrawable+import android.graphics.drawable.Icon+import android.os.Build+import android.util.Rational+import android.view.Gravity+import android.view.View+import android.widget.FrameLayout+import android.widget.LinearLayout+import android.widget.TextView+import io.livekit.android.room.track.VideoTrack++/** Shared by the drawer's PiP (CallActivity) and the mini-window's PiP (Macro's main activity). */+internal object CallPictureInPicture {+ private val dark = Color.rgb(15, 15, 15)++ // System PiP shows these instead of the call service's media-session transport controls.+ fun params(ctx: Context, sourceRect: Rect? = null, autoEnter: Boolean = false): PictureInPictureParams {+ val id = Calls.offer?.callId.orEmpty()+ val mute = if (Calls.muted) "Unmute" else "Mute"+ val actions = listOf(+ RemoteAction(Icon.createWithResource(ctx, if (Calls.muted) R.drawable.macro_call_microphone_slash else R.drawable.macro_call_microphone),+ mute, mute, CallService.action(ctx, "mute", id)),+ RemoteAction(Icon.createWithResource(ctx, R.drawable.macro_call_phone_disconnect), "Leave", "Leave call", CallService.action(ctx, "end", id)),+ )+ val builder = PictureInPictureParams.Builder().setAspectRatio(Rational(32, 15)).setActions(actions).setSourceRectHint(sourceRect)+ if (Build.VERSION.SDK_INT >= 31) builder.setAutoEnterEnabled(autoEnter)+ return builder.build()+ }++ /** Matches iOS: you on the left and the active speaker on the right, video or initials over the name. */+ fun view(ctx: Context, localTitle: String, localTrack: VideoTrack?, remoteTitle: String?, remoteTrack: VideoTrack?,+ video: (VideoTrack, Boolean) -> View): View = LinearLayout(ctx).apply {+ tag = "call-pip"+ setBackgroundColor(dark)+ val density = ctx.resources.displayMetrics.density+ fun dp(value: Int) = (value * density).toInt()+ fun tile(title: String, track: VideoTrack?, mirror: Boolean) = FrameLayout(ctx).apply {+ setBackgroundColor(dark)+ if (track != null) {+ addView(video(track, mirror), FrameLayout.LayoutParams(-1, -1))+ return@apply+ }+ val placeholder = LinearLayout(ctx).apply { orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL }+ placeholder.addView(TextView(ctx).apply {+ text = Calls.initials(title); textSize = 20f; typeface = Typeface.DEFAULT_BOLD; setTextColor(Color.WHITE); gravity = Gravity.CENTER+ background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(Color.rgb(46, 46, 46)) }+ }, LinearLayout.LayoutParams(dp(44), dp(44)))+ placeholder.addView(TextView(ctx).apply {+ text = title; textSize = 10f; setTextColor(Color.argb(224, 255, 255, 255)); gravity = Gravity.CENTER+ maxLines = 2; ellipsize = android.text.TextUtils.TruncateAt.END+ }, LinearLayout.LayoutParams(-2, -2).apply { topMargin = dp(5) })+ addView(placeholder, FrameLayout.LayoutParams(-1, -2, Gravity.CENTER).apply { leftMargin = dp(8); rightMargin = dp(8) })+ }+ addView(tile(localTitle, localTrack, true), LinearLayout.LayoutParams(0, -1, 1f))+ addView(View(ctx).apply { setBackgroundColor(Color.argb(46, 255, 255, 255)) }, LinearLayout.LayoutParams(dp(1), -1))+ addView(tile(remoteTitle ?: "No one else is here", remoteTrack, false), LinearLayout.LayoutParams(0, -1, 1f))+ }+}diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPlugin.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPlugin.ktindex ba9f0ed5bb..62d4bdf9f3 100644--- a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPlugin.kt+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPlugin.kt@@ -3,8 +3,12 @@ package com.macro.callimport android.Manifestimport android.app.Activityimport android.content.Intent+import android.app.NotificationManagerimport android.content.pm.PackageManager+import android.net.Uriimport android.os.Build+import android.provider.Settings+import android.webkit.WebViewimport androidx.appcompat.app.AppCompatActivityimport app.tauri.annotation.*import app.tauri.plugin.*@@ -41,6 +45,12 @@ internal class ModeArgs { var mode = "hidden" }@TauriPlugin(permissions = [Permission(strings = [Manifest.permission.RECORD_AUDIO], alias = "microphone"), Permission(strings = [Manifest.permission.CAMERA], alias = "camera")])class CallPlugin(private val activity: Activity) : Plugin(activity) {private var preparePermissionCallId: String? = null+ private var miniWindow: CallMiniWindow? = null+ override fun load(webView: WebView) { miniWindow = CallMiniWindow(activity, webView) }+ // Back in Macro, a drawer left in PiP opens again, as iOS returns to PiP's source.+ override fun onResume(activity: AppCompatActivity) { if (CallActivity.inPictureInPicture) Calls.openDrawer(activity) }+ // Once Macro is out of sight (PiP closed, phone locked) nothing shows the camera.+ override fun onStop(activity: AppCompatActivity) { if (!CallActivity.isOpen) Calls.stopCamera(activity) }private fun finishPreparePermission() {preparePermissionCallId?.let { Calls.finishMicrophonePermission(it) }preparePermissionCallId = null@@ -116,12 +126,8 @@ class CallPlugin(private val activity: Activity) : Plugin(activity) {@Command fun setVideoOverlayMode(invoke: Invoke) {val mode = invoke.parseArgs(ModeArgs::class.java).modeif (mode !in listOf("hidden", "expanded", "minimized")) { invoke.reject("Invalid call surface mode"); return }- Calls.overlay = mode- if (mode != "hidden" && Calls.offer != null) {- activity.startActivity(Intent(activity, CallActivity::class.java))- Calls.offer?.let { Calls.emit("drawer", JSObject().apply { put("channelId", it.channelId) }) }- }- Calls.publish(); invoke.resolve()+ if (mode == "expanded") Calls.openDrawer(activity) else Calls.setOverlay(mode)+ invoke.resolve()}@Command fun switchCamera(invoke: Invoke) { Calls.switchCamera(); invoke.resolve() }@Command fun setCallDrawerTheme(invoke: Invoke) {@@ -141,9 +147,29 @@ class CallPlugin(private val activity: Activity) : Plugin(activity) {@Command fun setParticipantDisplayName(invoke: Invoke) {val args = invoke.parseArgs(NameArgs::class.java)val name = args.displayName?.trim()?.takeIf { it.isNotEmpty() }- if (name == null) Calls.displayNames.remove(args.identity) else Calls.displayNames[args.identity] = name- Calls.publish(); invoke.resolve()+ // Names only change native UI. Publishing would re-emit identities, which makes JS resend every name.+ if (Calls.displayNames[args.identity] != name) {+ if (name == null) Calls.displayNames.remove(args.identity) else Calls.displayNames[args.identity] = name+ Calls.refresh()+ }+ invoke.resolve()}@Command fun getVoipToken(invoke: Invoke) { invoke.resolve(JSObject().apply { put("token", org.json.JSONObject.NULL) }) }- override fun onDestroy(activity: AppCompatActivity) { finishPreparePermission(); Calls.abortPendingJoin(activity); Calls.unwatch() }+ // Android 14+ revokes full-screen intents unless the user (or a Play declaration) allows them,+ // so incoming calls can't take over the lock screen.+ @Command fun canUseFullScreenIntent(invoke: Invoke) {+ val allowed = Build.VERSION.SDK_INT < 34 || activity.getSystemService(NotificationManager::class.java).canUseFullScreenIntent()+ invoke.resolve(JSObject().apply { put("allowed", allowed) })+ }+ @Command fun openFullScreenIntentSettings(invoke: Invoke) {+ if (Build.VERSION.SDK_INT >= 34) {+ runCatching { activity.startActivity(Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, Uri.parse("package:${activity.packageName}"))) }+ .onFailure { invoke.reject("Unable to open full-screen notification settings"); return }+ }+ invoke.resolve()+ }+ override fun onDestroy(activity: AppCompatActivity) {+ finishPreparePermission(); Calls.abortPendingJoin(activity); Calls.unwatch()+ miniWindow?.release(); miniWindow = null+ }}diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallReceiver.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallReceiver.ktindex c6548fceb6..e2f74711f6 100644--- a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallReceiver.kt+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallReceiver.kt@@ -20,6 +20,7 @@ class CallReceiver : BroadcastReceiver() {"com.macro.call.RESET" -> Calls.resetRecipient(context.applicationContext, intent.getStringExtra("previousRecipient"))"answer" -> intent.getStringExtra("callId")?.let { Calls.answer(context.applicationContext, it) }"end" -> intent.getStringExtra("callId")?.let { Calls.end(context.applicationContext, it) }+ "mute" -> if (intent.getStringExtra("callId") == Calls.offer?.callId) runCatching { Calls.microphone(Calls.muted) }}} finally { pending.finish() }}diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallService.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallService.ktindex aad1b86581..525f19d1e5 100644--- a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallService.kt+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallService.kt@@ -112,7 +112,8 @@ class CallService : Service() {.setSmallIcon(android.R.drawable.sym_call_incoming).setContentTitle(Calls.title ?: call?.title ?: "Macro call").setCategory(NotificationCompat.CATEGORY_CALL).setOngoing(true).setOnlyAlertOnce(true).setSilent(!ringing)- .setContentIntent(screen(this)).setVisibility(NotificationCompat.VISIBILITY_PRIVATE)+ // Like the system dialer and CallKit, show who is calling and the call controls on the lock screen.+ .setContentIntent(screen(this)).setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setFullScreenIntent(if (ringing) screen(this) else null, ringing)if (call != null) {val person = Person.Builder().setName((Calls.title ?: call.title).ifBlank { "Macro call" }).setImportant(true).build()diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/Calls.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/Calls.ktindex 2fff41c04e..ba1d6cd92b 100644--- a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/Calls.kt+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/Calls.kt@@ -13,13 +13,17 @@ import android.telecom.*import androidx.core.content.ContextCompatimport app.tauri.plugin.Channelimport app.tauri.plugin.JSObject+import com.twilio.audioswitch.AudioDeviceimport io.livekit.android.LiveKitimport io.livekit.android.events.RoomEventimport io.livekit.android.events.collectimport io.livekit.android.room.Room+import io.livekit.android.room.participant.Participant+import io.livekit.android.room.participant.RemoteParticipantimport io.livekit.android.room.track.LocalVideoTrackimport io.livekit.android.room.track.RemoteAudioTrackimport io.livekit.android.room.track.Track+import io.livekit.android.room.track.VideoTrackimport kotlinx.coroutines.*import kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock@@ -43,9 +47,13 @@ internal object Calls {var video = falseprivate setvar error: String? = null+ /** Where the call UI is, as on iOS: the drawer (expanded), the in-app thumbnail (minimized), or an edge tab (hidden). */var overlay = "hidden"+ private setvar pendingAnswered: String? = nullvar changed: (() -> Unit)? = null+ var miniWindowChanged: (() -> Unit)? = null+ private var spotlightId: String? = nullprivate var session: Job? = nullprivate var poller: Job? = nullprivate var held = false@@ -60,6 +68,8 @@ internal object Calls {private var telecomMuted = falseprivate var telecomFocusLost = falseprivate var desiredAudioType: String? = null+ private var remoteAudioSilenced = false+ private var publishedIdentities: String? = nullprivate val audioMutex = Mutex()private val videoMutex = Mutex()var recipient: String? = null@@ -80,8 +90,53 @@ internal object Calls {)return handle}- fun watch(name: String, channel: Channel) { watchers[name] = channel }+ fun watch(name: String, channel: Channel) { watchers[name] = channel; publishedIdentities = null }fun unwatch() { watchers.clear() }+ // Agents such as the transcriber join the room but are not call participants.+ fun remoteHumans(media: Room): List<RemoteParticipant> =+ media.remoteParticipants.values.filter { it.kind != Participant.Kind.AGENT }+ fun participantId(participant: Participant) = participant.identity?.value ?: participant.sid.value+ fun displayName(participant: Participant): String {+ val id = participantId(participant)+ return displayNames[id] ?: participant.name?.takeIf { it.isNotBlank() } ?: id.substringAfter('|')+ }+ // Same rule as the iOS call UI, so fallback identities don't render as "M" for "macro|...".+ fun initials(name: String) = name.split(' ', '@', '.', '|').filter { it.isNotBlank() && !it.equals("macro", true) }+ .take(2).joinToString("") { it.take(1).uppercase() }.ifEmpty { "?" }+ fun localName(media: Room) = displayNames[participantId(media.localParticipant)] ?: "You"+ fun cameraTrack(participant: Participant): VideoTrack? =+ participant.getTrackPublication(Track.Source.CAMERA)?.takeUnless { it.muted }?.track as? VideoTrack+ /** PiP and the mini-window show the active speaker, keeping the last one through pauses. */+ fun spotlight(media: Room): RemoteParticipant? {+ val humans = remoteHumans(media)+ val speaking = media.activeSpeakers.map(::participantId).firstNotNullOfOrNull { id -> humans.firstOrNull { participantId(it) == id } }+ return (speaking ?: humans.firstOrNull { participantId(it) == spotlightId } ?: humans.firstOrNull())+ .also { spotlightId = it?.let(::participantId) }+ }+ fun setOverlay(mode: String) {+ if (overlay == mode) return+ overlay = mode+ publish()+ }+ fun openDrawer(ctx: Context) {+ val call = offer ?: return+ setOverlay("expanded")+ ctx.startActivity(Intent(ctx, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ emit("drawer", JSObject().apply { put("channelId", call.channelId) })+ }+ /** Re-renders native call surfaces without notifying JS. */+ fun refresh() {+ changed?.invoke()+ miniWindowChanged?.invoke()+ }+ // Release builds obfuscate audioswitch class names, so match device types.+ private fun audioType(device: AudioDevice?): String? = when (device) {+ is AudioDevice.BluetoothHeadset -> "BluetoothHeadset"+ is AudioDevice.WiredHeadset -> "WiredHeadset"+ is AudioDevice.Earpiece -> "Earpiece"+ is AudioDevice.Speakerphone -> "Speakerphone"+ null -> null+ }fun emit(name: String, payload: JSObject) { watchers[name]?.send(payload) }fun snapshot(): JSObject? = offer?.takeIf { accepted }?.let {JSObject().apply {@@ -92,13 +147,17 @@ internal object Calls {}private fun identities(): JSONArray = JSONArray().apply {room?.localParticipant?.identity?.value?.let { put(it) }- room?.remoteParticipants?.values?.forEach { it.identity?.value?.let { id -> put(id) } }+ room?.let { remoteHumans(it).forEach { participant -> participant.identity?.value?.let { id -> put(id) } } }}private fun interrupted(): Boolean = held || focusLost || telecomFocusLostprivate fun syncRemoteAudio() {+ // setVolume blocks on LiveKit's RTC thread; only touch tracks while silencing or restoring.+ val silence = interrupted()+ if (!silence && !remoteAudioSilenced) return+ remoteAudioSilenced = silenceroom?.remoteParticipants?.values?.forEach { participant ->participant.trackPublications.values.forEach { publication ->- (publication.track as? RemoteAudioTrack)?.setVolume(if (interrupted()) 0.0 else 1.0)+ (publication.track as? RemoteAudioTrack)?.setVolume(if (silence) 0.0 else 1.0)}}}@@ -107,8 +166,13 @@ internal object Calls {val payload = snapshot() ?: JSObject()payload.put("state", if (accepted) state else "disconnected")emit("connection", payload)- emit("participants", JSObject().apply { put("identities", identities()) })- changed?.invoke()+ // JS re-sends every display name when identities arrive; repeating unchanged ones floods the bridge.+ val identities = identities()+ if (identities.toString() != publishedIdentities) {+ publishedIdentities = identities.toString()+ emit("participants", JSObject().apply { put("identities", identities) })+ }+ refresh()}fun prepareJoin(ctx: Context, channelId: String): String {check(joinLease == null) { "A call join is already pending" }@@ -149,11 +213,18 @@ internal object Calls {}fun receive(ctx: Context, data: Map<String, String>, sentTime: Long) {if (android.os.Build.VERSION.SDK_INT < 26) return- if (data["recipientId"] != ctx.getSharedPreferences("macro_push", Context.MODE_PRIVATE).getString("recipient", null)) return- val next = runCatching { CallOffer.parse(data["payload"] ?: return, sentTime) }.getOrNull() ?: return- if (!CallOffer.fresh(sentTime, System.currentTimeMillis())) return- if (ctx.getSharedPreferences("macro_calls", Context.MODE_PRIVATE).getLong(next.callId, 0) > System.currentTimeMillis() - 120_000) return- if (offer != null) return+ val next = runCatching { CallOffer.parse(data["payload"].orEmpty(), sentTime) }.getOrNull()+ val now = System.currentTimeMillis()+ // Log only the reason: payloads carry LiveKit credentials.+ val ignored = when {+ data["recipientId"] != ctx.getSharedPreferences("macro_push", Context.MODE_PRIVATE).getString("recipient", null) -> "another account"+ next == null -> "invalid payload"+ !CallOffer.fresh(sentTime, now) -> "stale, sent ${now - sentTime}ms ago"+ ctx.getSharedPreferences("macro_calls", Context.MODE_PRIVATE).getLong(next.callId, 0) > now - 120_000 -> "call recently ended"+ offer != null -> "another call is ringing or active"+ else -> null+ }+ if (ignored != null || next == null) { android.util.Log.i("MacroCall", "Ignored call push: $ignored"); return }recipient = ctx.getSharedPreferences("macro_push", Context.MODE_PRIVATE).getString("recipient", null)title = next.titleoffer = next; state = "ringing"; accepted = false@@ -173,7 +244,10 @@ internal object Calls {delay(1000)}}- } catch (_: Exception) { end(ctx, next.callId) }+ } catch (error: Exception) {+ android.util.Log.w("MacroCall", "Incoming call failed: ${error.javaClass.simpleName}")+ end(ctx, next.callId)+ }}private suspend fun ringStatus(next: CallOffer): String? = withContext(Dispatchers.IO) {runCatching {@@ -218,7 +292,11 @@ internal object Calls {}fun showIncoming(ctx: Context) {try { CallService.start(ctx); publish() }- catch (_: Exception) { end(ctx) }+ catch (error: Exception) {+ // Background starts can be denied, e.g. when FCM delivered the push without high priority.+ android.util.Log.w("MacroCall", "Incoming call UI failed: ${error.javaClass.simpleName}")+ end(ctx)+ }}fun answer(ctx: Context, id: String, verify: suspend (CallOffer) -> String? = ::ringStatus) {val next = offer ?: return@@ -260,10 +338,10 @@ internal object Calls {media.audioSwitchHandler?.registerAudioDeviceChangeListener { devices, selected ->scope.launch {if (room !== media) return@launch- audioRoute = selected?.javaClass?.simpleName+ audioRoute = audioType(selected)publish()- if (selected?.javaClass?.simpleName != desiredAudioType) {- devices.firstOrNull { it.javaClass.simpleName == desiredAudioType }?.let { media.audioSwitchHandler?.selectDevice(it) }+ if (audioRoute != desiredAudioType) {+ devices.firstOrNull { audioType(it) == desiredAudioType }?.let { media.audioSwitchHandler?.selectDevice(it) }}}}@@ -293,7 +371,7 @@ internal object Calls {media.connect(next.serverUrl, next.token)if (room !== media) return@launchmedia.localParticipant.setMicrophoneEnabled(!muted && !interrupted())- state = "connected"; connection?.setActive(); publish()+ state = "connected"; connection?.setActive(); overlay = "expanded"; publish()ctx.startActivity(Intent(ctx, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))} catch (_: CancellationException) {// end() already owns teardown.@@ -331,11 +409,17 @@ internal object Calls {media.localParticipant.setCameraEnabled(enabled)if (room === media) { video = enabled; CallService.start(ctx, media = true, camera = enabled); publish() }}+ /** Stops capture once no call surface (drawer, PiP or mini-window) is visible. */+ fun stopCamera(ctx: Context) {+ val media = room ?: return+ if (!video) return+ scope.launch { if (room === media) runCatching { camera(ctx, false, media) } }+ }fun switchCamera() { (room?.localParticipant?.getTrackPublication(Track.Source.CAMERA)?.track as? LocalVideoTrack)?.switchCamera() }private fun selectAudio(type: String) {desiredAudioType = typeval handler = room?.audioSwitchHandler ?: return- handler.availableAudioDevices.firstOrNull { it.javaClass.simpleName == type }?.let { handler.selectDevice(it) }+ handler.availableAudioDevices.firstOrNull { audioType(it) == type }?.let { handler.selectDevice(it) }}fun telecomAudio(audio: CallAudioState) {scope.launch {@@ -388,7 +472,7 @@ internal object Calls {session?.cancel(); session = nullval media = room; room = nullval telecomConnection = connection; connection = null- offer = null; pendingAnswered = null; state = "disconnected"; title = null; recipient = null; displayNames.clear(); error = null; muted = false; video = false; held = false; answering = false; accepted = false; focusLost = false; telecomMuted = false; telecomFocusLost = false; desiredAudioType = null; audioRoute = null; overlay = "hidden"+ offer = null; pendingAnswered = null; state = "disconnected"; title = null; recipient = null; displayNames.clear(); error = null; muted = false; video = false; held = false; answering = false; accepted = false; focusLost = false; telecomMuted = false; telecomFocusLost = false; desiredAudioType = null; remoteAudioSilenced = false; audioRoute = null; overlay = "hidden"; spotlightId = null// Native/SDK callbacks may fail or reenter; no resource owns the cleared session.// Release each resource independently so one failure cannot leave a phantom call.runCatching { media?.disconnect() }diff --git a/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_camera_rotate.xml b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_camera_rotate.xmlnew file mode 100644index 0000000000..72dbc374ac--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_camera_rotate.xml@@ -0,0 +1,10 @@+<!-- Phosphor camera-rotate (regular), MIT: https://phosphoricons.com -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="256"+ android:viewportHeight="256">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M208,56H180.28L166.65,35.56A8,8,0,0,0,160,32H96a8,8,0,0,0-6.65,3.56L75.71,56H48A24,24,0,0,0,24,80V192a24,24,0,0,0,24,24H208a24,24,0,0,0,24-24V80A24,24,0,0,0,208,56Zm8,136a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V80a8,8,0,0,1,8-8H80a8,8,0,0,0,6.66-3.56L100.28,48h55.43l13.63,20.44A8,8,0,0,0,176,72h32a8,8,0,0,1,8,8ZM176,96v24a8,8,0,0,1-8,8H144a8,8,0,0,1,0-16h5.15a32.12,32.12,0,0,0-40.34-1.61A8,8,0,0,1,99.19,97.6,48.21,48.21,0,0,1,160,100.23V96a8,8,0,0,1,16,0Zm-17.61,59.2a8,8,0,0,1-1.58,11.2A48.21,48.21,0,0,1,96,163.77V168a8,8,0,0,1-16,0V144a8,8,0,0,1,8-8h24a8,8,0,0,1,0,16h-5.15a32.12,32.12,0,0,0,40.34,1.61A8,8,0,0,1,158.39,155.2Z" />+</vector>diff --git a/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_microphone.xml b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_microphone.xmlnew file mode 100644index 0000000000..c871b71b14--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_microphone.xml@@ -0,0 +1,10 @@+<!-- Phosphor microphone (regular), MIT: https://phosphoricons.com -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="256"+ android:viewportHeight="256">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M128,176a48.05,48.05,0,0,0,48-48V64a48,48,0,0,0-96,0v64A48.05,48.05,0,0,0,128,176ZM96,64a32,32,0,0,1,64,0v64a32,32,0,0,1-64,0Zm40,143.6V240a8,8,0,0,1-16,0V207.6A80.11,80.11,0,0,1,48,128a8,8,0,0,1,16,0,64,64,0,0,0,128,0,8,8,0,0,1,16,0A80.11,80.11,0,0,1,136,207.6Z" />+</vector>diff --git a/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_microphone_slash.xml b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_microphone_slash.xmlnew file mode 100644index 0000000000..7d003f0e75--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_microphone_slash.xml@@ -0,0 +1,10 @@+<!-- Phosphor microphone-slash (regular), MIT: https://phosphoricons.com -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="256"+ android:viewportHeight="256">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M213.92,218.62l-160-176A8,8,0,0,0,42.08,53.38L80,95.09V128a48,48,0,0,0,69.11,43.12l11.1,12.2A63.41,63.41,0,0,1,128,192a64.07,64.07,0,0,1-64-64,8,8,0,0,0-16,0,80.11,80.11,0,0,0,72,79.6V240a8,8,0,0,0,16,0V207.59a78.83,78.83,0,0,0,35.16-12.22l30.92,34a8,8,0,1,0,11.84-10.76ZM128,160a32,32,0,0,1-32-32V112.69l41.66,45.82A32,32,0,0,1,128,160Zm57.52-3.91A63.32,63.32,0,0,0,192,128a8,8,0,0,1,16,0,79.16,79.16,0,0,1-8.11,35.12,8,8,0,0,1-7.19,4.49,7.88,7.88,0,0,1-3.51-.82A8,8,0,0,1,185.52,156.09ZM84,44.87A48,48,0,0,1,176,64v64a49.19,49.19,0,0,1-.26,5,8,8,0,0,1-8,7.17,8.13,8.13,0,0,1-.84,0,8,8,0,0,1-7.12-8.79c.11-1.1.17-2.24.17-3.36V64A32,32,0,0,0,98.64,51.25,8,8,0,1,1,84,44.87Z" />+</vector>diff --git a/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_phone_disconnect.xml b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_phone_disconnect.xmlnew file mode 100644index 0000000000..b7409a851b--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_phone_disconnect.xml@@ -0,0 +1,10 @@+<!-- Phosphor phone-disconnect (regular), MIT: https://phosphoricons.com -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="256"+ android:viewportHeight="256">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M231.59,90.13h0C175.44,34,80.56,34,24.41,90.13c-20,20-21.92,49.49-4.69,71.71A16,16,0,0,0,32.35,168a15.8,15.8,0,0,0,5.75-1.08l49-17.37.29-.11a16,16,0,0,0,9.75-11.73l5.9-29.52a76.52,76.52,0,0,1,49.68-.11h0l6.21,29.75a16,16,0,0,0,9.72,11.59l.29.11,49,17.39a16,16,0,0,0,18.38-5.06C253.51,139.62,251.58,110.13,231.59,90.13ZM223.67,152l-.3-.12-48.82-17.33-6.21-29.74A16,16,0,0,0,158,93a92.56,92.56,0,0,0-60.34.13,16,16,0,0,0-10.32,12l-5.9,29.51L32.63,151.86c-.1,0-.17.13-.27.17-12.33-15.91-11-36.23,3.36-50.58,25-25,58.65-37.53,92.28-37.53s67.27,12.51,92.28,37.53C234.61,115.8,236,136.12,223.67,152Zm.32,48a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16H216A8,8,0,0,1,224,200Z" />+</vector>diff --git a/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_speaker_high.xml b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_speaker_high.xmlnew file mode 100644index 0000000000..a908ac4082--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_speaker_high.xml@@ -0,0 +1,10 @@+<!-- Phosphor speaker-high (regular), MIT: https://phosphoricons.com -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="256"+ android:viewportHeight="256">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M155.51,24.81a8,8,0,0,0-8.42.88L77.25,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H77.25l69.84,54.31A8,8,0,0,0,160,224V32A8,8,0,0,0,155.51,24.81ZM32,96H72v64H32ZM144,207.64,88,164.09V91.91l56-43.55Zm54-106.08a40,40,0,0,1,0,52.88,8,8,0,0,1-12-10.58,24,24,0,0,0,0-31.72,8,8,0,0,1,12-10.58ZM248,128a79.9,79.9,0,0,1-20.37,53.34,8,8,0,0,1-11.92-10.67,64,64,0,0,0,0-85.33,8,8,0,1,1,11.92-10.67A79.83,79.83,0,0,1,248,128Z" />+</vector>diff --git a/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_video_camera.xml b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_video_camera.xmlnew file mode 100644index 0000000000..07acee8113--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_video_camera.xml@@ -0,0 +1,10 @@+<!-- Phosphor video-camera (regular), MIT: https://phosphoricons.com -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="256"+ android:viewportHeight="256">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M251.77,73a8,8,0,0,0-8.21.39L208,97.05V72a16,16,0,0,0-16-16H32A16,16,0,0,0,16,72V184a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V159l35.56,23.71A8,8,0,0,0,248,184a8,8,0,0,0,8-8V80A8,8,0,0,0,251.77,73ZM192,184H32V72H192V184Zm48-22.95-32-21.33V116.28L240,95Z" />+</vector>diff --git a/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_video_camera_slash.xml b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_video_camera_slash.xmlnew file mode 100644index 0000000000..fdbe1abe0b--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/res/drawable/macro_call_video_camera_slash.xml@@ -0,0 +1,10 @@+<!-- Phosphor video-camera-slash (regular), MIT: https://phosphoricons.com -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="256"+ android:viewportHeight="256">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M251.77,73a8,8,0,0,0-8.21.39L208,97.05V72a16,16,0,0,0-16-16H113.06a8,8,0,0,0,0,16H192v87.63a8,8,0,0,0,16,0V159l35.56,23.71A8,8,0,0,0,248,184a8,8,0,0,0,8-8V80A8,8,0,0,0,251.77,73ZM240,161.05l-32-21.33V116.28L240,95ZM53.92,34.62A8,8,0,1,0,42.08,45.38L51.73,56H32A16,16,0,0,0,16,72V184a16,16,0,0,0,16,16H182.64l19.44,21.38a8,8,0,1,0,11.84-10.76ZM32,184V72H66.28L168.1,184Z" />+</vector>diff --git a/apps/web/tauri/callkit_plugin/build.rs b/apps/web/tauri/callkit_plugin/build.rsindex a093e11ff0..3e990ca45b 100644--- a/apps/web/tauri/callkit_plugin/build.rs+++ b/apps/web/tauri/callkit_plugin/build.rs@@ -24,6 +24,8 @@ const COMMANDS: &[&str] = &["set_call_drawer_theme","set_participant_display_name","switch_camera",+ "can_use_full_screen_intent",+ "open_full_screen_intent_settings",];struct BuildEnv {diff --git a/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/can_use_full_screen_intent.toml b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/can_use_full_screen_intent.tomlnew file mode 100644index 0000000000..eb0a9b5894--- /dev/null+++ b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/can_use_full_screen_intent.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-can-use-full-screen-intent"+description = "Enables the can_use_full_screen_intent command without any pre-configured scope."+commands.allow = ["can_use_full_screen_intent"]++[[permission]]+identifier = "deny-can-use-full-screen-intent"+description = "Denies the can_use_full_screen_intent command without any pre-configured scope."+commands.deny = ["can_use_full_screen_intent"]diff --git a/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/open_full_screen_intent_settings.toml b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/open_full_screen_intent_settings.tomlnew file mode 100644index 0000000000..08419bf034--- /dev/null+++ b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/open_full_screen_intent_settings.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-open-full-screen-intent-settings"+description = "Enables the open_full_screen_intent_settings command without any pre-configured scope."+commands.allow = ["open_full_screen_intent_settings"]++[[permission]]+identifier = "deny-open-full-screen-intent-settings"+description = "Denies the open_full_screen_intent_settings command without any pre-configured scope."+commands.deny = ["open_full_screen_intent_settings"]diff --git a/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.mdindex 67194124bc..a6ef19a7ec 100644--- a/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md+++ b/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md@@ -36,6 +36,32 @@ Denies the abort_join command without any pre-configured scope.<tr><td>+`call-kit:allow-can-use-full-screen-intent`++</td>+<td>++Enables the can_use_full_screen_intent command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-can-use-full-screen-intent`++</td>+<td>++Denies the can_use_full_screen_intent command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`call-kit:allow-end-active-call`</td>@@ -140,6 +166,32 @@ Denies the get_voip_token command without any pre-configured scope.<tr><td>+`call-kit:allow-open-full-screen-intent-settings`++</td>+<td>++Enables the open_full_screen_intent_settings command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-open-full-screen-intent-settings`++</td>+<td>++Denies the open_full_screen_intent_settings command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`call-kit:allow-prepare-join`</td>diff --git a/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json b/apps/web/tauri/callkit_plugin/permissions/schemas/schema.jsonindex 5a6d055330..c221ed058f 100644--- a/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json+++ b/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json@@ -306,6 +306,18 @@"const": "deny-abort-join","markdownDescription": "Denies the abort_join command without any pre-configured scope."},+ {+ "description": "Enables the can_use_full_screen_intent command without any pre-configured scope.",+ "type": "string",+ "const": "allow-can-use-full-screen-intent",+ "markdownDescription": "Enables the can_use_full_screen_intent command without any pre-configured scope."+ },+ {+ "description": "Denies the can_use_full_screen_intent command without any pre-configured scope.",+ "type": "string",+ "const": "deny-can-use-full-screen-intent",+ "markdownDescription": "Denies the can_use_full_screen_intent command without any pre-configured scope."+ },{"description": "Enables the end_active_call command without any pre-configured scope.","type": "string",@@ -354,6 +366,18 @@"const": "deny-get-voip-token","markdownDescription": "Denies the get_voip_token command without any pre-configured scope."},+ {+ "description": "Enables the open_full_screen_intent_settings command without any pre-configured scope.",+ "type": "string",+ "const": "allow-open-full-screen-intent-settings",+ "markdownDescription": "Enables the open_full_screen_intent_settings command without any pre-configured scope."+ },+ {+ "description": "Denies the open_full_screen_intent_settings command without any pre-configured scope.",+ "type": "string",+ "const": "deny-open-full-screen-intent-settings",+ "markdownDescription": "Denies the open_full_screen_intent_settings command without any pre-configured scope."+ },{"description": "Enables the prepare_join command without any pre-configured scope.","type": "string",diff --git a/apps/web/tauri/callkit_plugin/src/android.rs b/apps/web/tauri/callkit_plugin/src/android.rsindex e9aad7bc09..3a63f7704a 100644--- a/apps/web/tauri/callkit_plugin/src/android.rs+++ b/apps/web/tauri/callkit_plugin/src/android.rs@@ -21,6 +21,11 @@ command!(end_active_call, "endActiveCall");command!(get_pending_answered_call, "getPendingAnsweredCall");command!(get_active_call_state, "getActiveCallState");command!(switch_camera, "switchCamera");+command!(can_use_full_screen_intent, "canUseFullScreenIntent");+command!(+ open_full_screen_intent_settings,+ "openFullScreenIntentSettings"+);#[derive(Serialize)]struct WatchArgs {diff --git a/apps/web/tauri/callkit_plugin/src/lib.rs b/apps/web/tauri/callkit_plugin/src/lib.rsindex 88fa29f1d2..5629259d0a 100644--- a/apps/web/tauri/callkit_plugin/src/lib.rs+++ b/apps/web/tauri/callkit_plugin/src/lib.rs@@ -43,7 +43,9 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {android::set_call_drawer_channel_title,android::set_call_drawer_theme,android::set_participant_display_name,- android::switch_camera+ android::switch_camera,+ android::can_use_full_screen_intent,+ android::open_full_screen_intent_settings]).js_init_script(include_str!("android-init.js"));builderdiff --git a/apps/web/tauri/src-tauri/capabilities/android.json b/apps/web/tauri/src-tauri/capabilities/android.jsonindex 66ba40024a..d61b46f04f 100644--- a/apps/web/tauri/src-tauri/capabilities/android.json+++ b/apps/web/tauri/src-tauri/capabilities/android.json@@ -27,6 +27,8 @@"call-kit:allow-set-call-drawer-theme","call-kit:allow-set-participant-display-name","call-kit:allow-switch-camera",+ "call-kit:allow-can-use-full-screen-intent",+ "call-kit:allow-open-full-screen-intent-settings","network-status:allow-watch-status"]}diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xmlindex aa7a1fe2dd..42dd4b079d 100644--- a/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml@@ -24,6 +24,7 @@android:name=".MainActivity"android:exported="true"android:windowSoftInputMode="adjustResize"+ android:supportsPictureInPicture="true"android:enableOnBackInvokedCallback="true"><intent-filter><action android:name="android.intent.action.MAIN" />diff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.jsonindex f6bd31cc11..2962ae39a6 100644--- a/apps/web/tauri/src-tauri/tauri.android.conf.json+++ b/apps/web/tauri/src-tauri/tauri.android.conf.json@@ -2,7 +2,7 @@"version": "2.5.0","bundle": {"android": {- "versionCode": 14+ "versionCode": 15}},"$schema": "https://schema.tauri.app/config/2",diff --git a/docs/agent-guide/calls.md b/docs/agent-guide/calls.mdindex eb050c6fed..66091b73fc 100644--- a/docs/agent-guide/calls.md+++ b/docs/agent-guide/calls.md@@ -244,12 +244,17 @@ joining a standalone call never makes its content available to the wider team.Android channel calls use a native call activity rather than browser media.After joining, the themed drawer shows a large participant tile and a horizontally-scrolling participant strip; tap a strip tile to make it primary. Speaker toggles+scrolling participant strip without the transcription agent; tap a strip tile to make it primary. Speaker togglesspeaker mode (hold it for headset/Bluetooth routing), Mute and Video control capture, and **Leave** ends the call.The local primary video tile exposes Switch camera. Swipe the drawer handle down,-tap outside the drawer, or use Back to enter PiP on supported devices; **Open call-controls** in the web call controls restores the native surface. Leaving the channel does-not end the call. Incoming calls expose Answer/Decline in the **Calls** notification-channel, including while locked/backgrounded. PiP is a native, device-dependent+tap outside the drawer, or use Back to shrink it to a thumbnail over Macro, as on+iOS: tap it to reopen the drawer, drag it to another corner, or drag it past a side+to tuck it away (an edge tab brings it back once someone else is in the call). Leaving the app continues the call in system PiP (you and the+active speaker); tapping PiP shows Android's menu with Mute, **Leave** and expand,+which reopens the drawer. **Open call controls** in the web call controls also+reopens the drawer. Leaving the channel does not end the call. Incoming calls+expose Answer/Decline in the **Calls** notification channel, including while+locked/backgrounded; while Android 14+ blocks full-screen notifications, a toast+offers **Allow** (system setting) or **Hide**. PiP is a native, device-dependentflow. Browser-only tests cannot validate Telecom, FCM wakeup or background media;follow the hardware matrix in [Android development](../development/android.md#native-calling).diff --git a/docs/development/android.md b/docs/development/android.mdindex 3c21626ec3..0457fced3c 100644--- a/docs/development/android.md+++ b/docs/development/android.md@@ -857,6 +857,8 @@ receive its fallback alert.Call pushes are data-only, high priority, have a 60-second TTL, and include a recipient-specificLiveKit token and HTTPS ring-status URL. The receiver checks the registeredaccount and message age. Tokens are kept in memory and never logged or persisted.+A dropped call push logs its reason under the `MacroCall` logcat tag (another+account, invalid payload, stale, recently ended, or another call active).While ringing, the native coordinator polls the existing ring-status endpoint;answering rechecks it before connecting. Answered-elsewhere, cancelled, expired,and invalid-token rings are dismissed. Transient verification failures allow a@@ -866,7 +868,14 @@ The **Calls** notification channel presents Answer/Decline and an ongoing Endcall action. Telecom handles headset/system actions and coordinates interruptions.Android's full-screen-intent setting controls whether a locked phone opens thecall activity automatically; when unavailable, the call notification remains the-entry point. Test both permission states. Microphone access is required to join;+entry point. Android 14+ revokes it by default for Play installs unless the Play+Console's full-screen intent declaration names calling as core functionality;+check with `adb shell appops get <package> USE_FULL_SCREEN_INTENT`. Once+notifications are on, Macro shows a toast while the setting is off; **Allow**+opens Android's per-app setting, and the toast stays until returning to Macro+finds access granted; **Hide** stops the prompt on that device. The+call notification is public, so the lock screen shows the call and its actions.+Test both permission states. Microphone access is required to join;camera access is requested when enabling video, and Bluetooth access when selectingthat route on Android 12 or newer. A denied permission does not silently enablecapture.@@ -874,14 +883,25 @@ capture.The native call activity presents a themed drawer at approximately 92% of thesafe screen height, above navigation bars/cutouts. A large participant tile sitsabove a horizontally scrolling participant strip; tapping a strip tile selects-it as primary. Speaker, Mute and Video form a compact control row, with Leave-in the header and camera switching on the primary local video tile. Hold Speaker-to select headset/Bluetooth routing. Back,-tapping the scrim, or swiping the handle down enters PiP on supported devices.-Without PiP support, dismissal returns to Macro while retaining audio. Audio continues in the-foreground service while backgrounded. Camera capture stops when the call activity-is backgrounded outside PiP. PiP uses native renderers and requires device support.-The web call controls can reopen the native activity after returning to Macro.+it as primary. Agent participants such as the transcriber are hidden. Speaker,+Mute and Video form a labelled control row of Phosphor icons, with Leave in the+header and camera switching on the primary local video tile. Hold Speaker to+select headset/Bluetooth routing.++As on iOS, Back, tapping the scrim, or swiping the handle down shrinks the drawer+to a thumbnail over Macro (you on the left, the active speaker on the right).+Tapping it reopens the drawer, dragging snaps it to a corner, and dragging it+past a side tucks it away; once someone else is in the call an edge tab brings+it back, and **Open call controls** reopens the drawer. On a locked phone the drawer+goes straight to PiP where the device supports it. Leaving Macro continues the call in system PiP:+from the thumbnail, Macro's main activity enters PiP (auto-enter on Android 12+,+which needs `android:supportsPictureInPicture` on `MainActivity`) and hides the+WebView so it keeps its size; from the drawer, the drawer enters PiP and+reopens when Macro returns. PiP uses the same layout as iOS, its menu offers+Mute and Leave, and expanding it reopens the drawer. A tap on a system PiP+always shows Android's menu first. Audio continues in the foreground service+while backgrounded; camera capture stops once neither the drawer, the thumbnail+nor PiP is visible. The web call controls can also reopen the drawer.After a debug build generates Tauri's Gradle includes, run the plugin unit testsfrom `tauri/src-tauri/gen/android` with@@ -898,10 +918,11 @@ For isolated native media testing, run a local LiveKit server in `--dev` modebound to `0.0.0.0`, then add`-Pandroid.testInstrumentationRunnerArguments.livekitUrl=ws://10.0.2.2:7880`to the connected-test command on the standard Android emulator. The optional-media test uses LiveKit's development credentials, a second native participant,+media tests use LiveKit's development credentials, a second native participant,and emulator microphone/camera permissions to verify video subscription, mute,-camera start/stop, duplicate start, network interruption/reconnect, navigation/PiP-and resource cleanup. Cleartext+camera start/stop, duplicate start, network interruption/reconnect, navigation/PiP,+the in-app thumbnail and its PiP handoff (`MiniWindowTest`, Android 12+), and+resource cleanup. Cleartextaccess is enabled only in the instrumentation APK. This test does not validateproduction FCM delivery or hardware audio quality.@@ -916,6 +937,7 @@ record Android version, APK revision, permissions, route/accessory and results:| Audio | Microphone denied/revoked, earpiece/speaker, wired headset, Bluetooth connect/disconnect, cellular-call interruption || Lifecycle | Wi-Fi/cellular transitions, temporary offline/reconnect, navigation, WebView reload, foreground resume, no duplicate participant || Video | Camera denial, front/back switch, remote video, supported PiP, PiP dismissal, background without PiP, end and reopen; granting camera permission for an ended call must not enable video on a replacement call |+| In-app thumbnail | Drawer to thumbnail and back, drag to each corner, edge tab, leave the app into PiP (Android 12+ and older), expand PiP to the drawer, close PiP, call ending in PiP |A local build or JVM/shared-state test does not prove this hardware matrix. Playinstallation/distribution regression belongs to release workstream 07.