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(android): improve incoming calls and trace native call handling (#9142)
Peter Chinmanccc415308cc0
diff --git a/Cargo.lock b/Cargo.lockindex cfd11d826a..51de83d2ea 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -13674,6 +13674,8 @@ dependencies = ["model_user","models_pagination","notification_state",+ "opentelemetry",+ "opentelemetry_sdk","rate_limit","rdkafka","redis",@@ -13692,6 +13694,8 @@ dependencies = ["tokio-util","tower 0.5.3","tracing",+ "tracing-opentelemetry",+ "tracing-subscriber","url","utoipa","uuid",diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 363236cc2e..68823b04a0 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -530,6 +530,15 @@ manual export when a distribution certificate path is supplied.## Native notification navigation+Android incoming calls use an opaque full-screen call screen, with the standard+Calls notification as the fallback when full-screen access is unavailable.+Keep notification Answer intents pointed directly at the call activity and scoped+to the offered call; active calls retain the drawer and PiP controls. See+`docs/development/android.md#native-calling` at the repository root.+Native call tracing retains the browser telemetry gate and exporter for cold+calls; propagate W3C context through push payloads, notification intents and+ring-status requests, and keep caller names, tokens and URLs out of spans.+Read iOS's durable pending tap before mounting the router, then choose itsdestination only after the authenticated account matches `recipientId`. Keepthe native receipt pending until the destination route is applied; release thediff --git a/apps/web/src/observability/browser.ts b/apps/web/src/observability/browser.tsindex 8be393d0c6..d41f946980 100644--- a/apps/web/src/observability/browser.ts+++ b/apps/web/src/observability/browser.ts@@ -13,6 +13,7 @@ import {} from './desktop';import { startDocumentLifecycle } from './document-lifecycle';import { frontendInstanceId } from './frontend-instance';+import { configureNativeCallTracing } from './native-call-tracing';import { startNativeDiagnostics } from './native-diagnostics';import { recordNativeWebviewStart } from './native-lifecycle';import { initializeUiOperationTelemetry } from './ui-operation';@@ -108,6 +109,11 @@ export async function initializeBrowserObservability(): Promise<void> {tracingProvider: (resource, getUserId) =>createWebTracingProvider(telemetryConfig, resource, getUserId),});+ await configureNativeCallTracing({+ enabled: browserEnabled,+ tracesUrl,+ environment: telemetryConfig.environment,+ }).catch(() => Telemetry.warn('Native call tracing configuration failed'));if (isTauri()) recordNativeWebviewStart(desktop, lifecycle?.attributes);if (recording && desktop) {recording.accept(desktop);diff --git a/apps/web/src/observability/native-call-tracing.test.ts b/apps/web/src/observability/native-call-tracing.test.tsnew file mode 100644index 0000000000..b5e7420c1b--- /dev/null+++ b/apps/web/src/observability/native-call-tracing.test.ts@@ -0,0 +1,45 @@+import { invoke } from '@tauri-apps/api/core';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { configureNativeCallTracing } from './native-call-tracing';++vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() }));++beforeEach(() => vi.clearAllMocks());+afterEach(() => {+ delete window.__MACRO_ANDROID_CALL_TRACING__;+});++it('does not invoke unsupported installed binaries', async () => {+ await configureNativeCallTracing({+ enabled: true,+ tracesUrl: 'https://example.com/v1/traces',+ environment: 'dev',+ });+ expect(invoke).not.toHaveBeenCalled();+});++it('clears native telemetry when the existing telemetry gate is disabled', async () => {+ window.__MACRO_ANDROID_CALL_TRACING__ = true;+ await configureNativeCallTracing({+ enabled: false,+ tracesUrl: 'https://example.com/v1/traces',+ environment: 'dev',+ });+ expect(invoke).toHaveBeenCalledWith('plugin:call-kit|configure_tracing', {+ tracesUrl: null,+ environment: 'dev',+ });+});++it('uses the resolved exporter for supported binaries', async () => {+ window.__MACRO_ANDROID_CALL_TRACING__ = true;+ await configureNativeCallTracing({+ enabled: true,+ tracesUrl: 'http://localhost:4318/v1/traces',+ environment: 'dev',+ });+ expect(invoke).toHaveBeenCalledWith('plugin:call-kit|configure_tracing', {+ tracesUrl: 'http://localhost:4318/v1/traces',+ environment: 'dev',+ });+});diff --git a/apps/web/src/observability/native-call-tracing.ts b/apps/web/src/observability/native-call-tracing.tsnew file mode 100644index 0000000000..de774ce783--- /dev/null+++ b/apps/web/src/observability/native-call-tracing.ts@@ -0,0 +1,21 @@+import { invoke } from '@tauri-apps/api/core';++declare global {+ interface Window {+ __MACRO_ANDROID_CALL_TRACING__?: boolean;+ }+}++/** Retain the existing telemetry gate and exporter for native calls without a running WebView. */+export async function configureNativeCallTracing(config: {+ enabled: boolean;+ tracesUrl?: string;+ environment: string;+}): Promise<void> {+ // New web bundles also run on installed binaries that predate this command.+ if (window.__MACRO_ANDROID_CALL_TRACING__ !== true) return;+ await invoke('plugin:call-kit|configure_tracing', {+ tracesUrl: config.enabled ? (config.tracesUrl ?? null) : null,+ environment: config.environment,+ });+}diff --git a/apps/web/tauri/callkit_plugin/android/build.gradle.kts b/apps/web/tauri/callkit_plugin/android/build.gradle.ktsindex 3e175190bb..e73d9ca569 100644--- a/apps/web/tauri/callkit_plugin/android/build.gradle.kts+++ b/apps/web/tauri/callkit_plugin/android/build.gradle.kts@@ -8,15 +8,31 @@ android {defaultConfig {minSdk = 24targetSdk = 36+ consumerProguardFiles("consumer-rules.pro")testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"}compileOptions {+ isCoreLibraryDesugaringEnabled = truesourceCompatibility = JavaVersion.VERSION_1_8targetCompatibility = JavaVersion.VERSION_1_8}kotlinOptions { jvmTarget = "1.8" }}dependencies {+ coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")+ implementation(platform("io.opentelemetry:opentelemetry-bom:1.67.0"))+ implementation("io.opentelemetry:opentelemetry-sdk")+ // Supply the SDK's optional interfaces and annotation types for release shrinking.+ implementation("io.opentelemetry:opentelemetry-api-incubator:1.67.0-alpha")+ implementation("io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi")+ implementation("com.google.auto.value:auto-value-annotations:1.11.0")+ implementation("com.google.errorprone:error_prone_annotations:2.30.0")+ // Share LiveKit's Android-compatible OkHttp transport instead of pulling in OkHttp 5's newer SDK/Kotlin floor.+ implementation("io.opentelemetry:opentelemetry-exporter-otlp") { exclude(group = "com.squareup.okhttp3") }+ implementation("com.squareup.okhttp3:okhttp:4.12.0")+ testImplementation("io.opentelemetry:opentelemetry-sdk-testing")+ androidTestImplementation("io.opentelemetry:opentelemetry-sdk-testing")+ androidTestImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")implementation(project(":tauri-android"))implementation("androidx.core:core-ktx:1.15.0")implementation("androidx.appcompat:appcompat:1.7.1")diff --git a/apps/web/tauri/callkit_plugin/android/consumer-rules.pro b/apps/web/tauri/callkit_plugin/android/consumer-rules.pronew file mode 100644index 0000000000..312d3e566b--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/consumer-rules.pro@@ -0,0 +1,2 @@+# OTLP discovers its HTTP transport through META-INF/services at runtime.+-keep class io.opentelemetry.exporter.sender.okhttp.internal.OkHttpHttpSenderProvider { *; }diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/CallTracingTest.kt b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/CallTracingTest.ktnew file mode 100644index 0000000000..4c12c4c074--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/CallTracingTest.kt@@ -0,0 +1,204 @@+package com.macro.call++import android.Manifest+import android.app.NotificationManager+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build+import android.os.ParcelFileDescriptor+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import io.opentelemetry.api.common.Attributes+import io.opentelemetry.api.trace.Span+import io.opentelemetry.api.trace.SpanKind+import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter+import io.opentelemetry.sdk.resources.Resource+import io.opentelemetry.sdk.trace.SdkTracerProvider+import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor+import okhttp3.mockwebserver.Dispatcher+import okhttp3.mockwebserver.MockResponse+import okhttp3.mockwebserver.MockWebServer+import okhttp3.mockwebserver.RecordedRequest+import org.json.JSONObject+import org.junit.Assert.*+import org.junit.Test+import org.junit.runner.RunWith+import java.net.HttpURLConnection+import java.net.URL+import java.util.UUID+import java.util.concurrent.LinkedBlockingQueue+import java.util.concurrent.TimeUnit++/** Exports actual protobuf over HTTP, including a backend parent and a downstream status request. */+@RunWith(AndroidJUnit4::class)+class CallTracingTest {+ private val instrumentation = InstrumentationRegistry.getInstrumentation()+ private val context = instrumentation.targetContext+ private fun shell(command: String) = ParcelFileDescriptor.AutoCloseInputStream(+ instrumentation.uiAutomation.executeShellCommand(command)).bufferedReader().use { it.readText() }++ @Test fun notificationAnswerAndStatusRequestExportOneConnectedTrace() {+ val exported = LinkedBlockingQueue<ByteArray>()+ val forwardUrl = InstrumentationRegistry.getArguments().getString("tracesUrl")+ val collector = MockWebServer().apply {+ dispatcher = object : Dispatcher() {+ override fun dispatch(request: RecordedRequest): MockResponse {+ val bytes = request.body.readByteArray()+ // Optional local Tempo intake; no real call credentials or push delivery are involved.+ if (forwardUrl != null) {+ val http = URL(forwardUrl).openConnection() as HttpURLConnection+ try {+ http.requestMethod = "POST"; http.doOutput = true+ http.connectTimeout = 5_000; http.readTimeout = 5_000+ http.setRequestProperty("Content-Type", "application/x-protobuf")+ http.outputStream.use { it.write(bytes) }+ assertEquals(200, http.responseCode)+ } finally { http.disconnect() }+ }+ exported.put(bytes)+ return MockResponse().setResponseCode(200)+ }+ }+ start()+ }+ val endpoint = collector.url("/v1/traces").toString()+ val backend = SdkTracerProvider.builder()+ .setResource(Resource.create(Attributes.builder().put("service.name", "call-tracing-test-backend").build()))+ .addSpanProcessor(SimpleSpanProcessor.create(OtlpHttpSpanExporter.builder().setEndpoint(endpoint).build())).build()+ val tracer = backend.get("test-backend")+ val producer = tracer.spanBuilder("call.push.send").startSpan()+ val parent = io.opentelemetry.context.Context.root().with(producer)+ val headers = CallTracing.inject(parent)+ val traceId = producer.spanContext.traceId+ val status = MockWebServer().apply {+ dispatcher = object : Dispatcher() {+ override fun dispatch(request: RecordedRequest): MockResponse {+ val remote = CallTracing.extract(mapOf("traceparent" to request.getHeader("traceparent").orEmpty(),+ "tracestate" to request.getHeader("tracestate").orEmpty()))+ tracer.spanBuilder("call.ring_status.server").setParent(remote).setSpanKind(SpanKind.SERVER)+ .startSpan().end()+ return MockResponse().setBody("{\"status\":\"ended\"}")+ }+ }+ start()+ }+ try {+ val id = UUID.randomUUID().toString()+ val microphoneGranted = context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED+ context.getSharedPreferences("macro_push", Context.MODE_PRIVATE).edit().putString("recipient", "trace-test-recipient").commit()+ if (Build.VERSION.SDK_INT >= 33) shell("pm grant ${context.packageName} android.permission.POST_NOTIFICATIONS")+ if (Build.VERSION.SDK_INT >= 34) shell("appops set ${context.packageName} USE_FULL_SCREEN_INTENT deny")+ instrumentation.runOnMainSync {+ Calls.end(context)+ CallTracing.configure(context, endpoint, "test")+ val payload = JSONObject().apply {+ put("callId", id); put("channelId", "trace-test-channel")+ put("channelName", "Private channel marker"); put("callerName", "Private caller marker")+ put("livekitServerUrl", "wss://unused.invalid"); put("livekitToken", "secret-token-marker")+ put("ringStatusUrl", "https://unavailable-call-test.macro.com/status")+ headers.forEach { (key, value) -> put(key, value) }+ }+ Calls.receive(context, mapOf("recipientId" to "trace-test-recipient", "payload" to payload.toString()), System.currentTimeMillis())+ }+ producer.end()+ instrumentation.awaitCondition("Call notification was not posted") {+ context.getSystemService(NotificationManager::class.java).activeNotifications.any { it.id == CallService.NOTIFICATION_ID }+ }+ val activity = instrumentation.startActivitySync(Intent(context, CallActivity::class.java)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as CallActivity+ instrumentation.runOnMainSync {+ assertEquals(traceId, Span.fromContext(Calls.trace!!.context).spanContext.traceId)+ // The foreground activity receives the real notification PendingIntent through onNewIntent.+ CallService.screen(context, Calls.offer!!.callId, answer = true).send()+ }+ instrumentation.awaitCondition("Notification Answer did not reach the activity") { activity.intent.getStringExtra("answer") == id }+ if (microphoneGranted) {+ instrumentation.awaitCondition("The initial answer verification did not finish") { Calls.error != null }+ }+ instrumentation.runOnMainSync {+ activity.onRequestPermissionsResult(4, arrayOf(Manifest.permission.RECORD_AUDIO), intArrayOf(PackageManager.PERMISSION_DENIED))+ val next = Calls.offer!!.copy(ringUrl = status.url("/ring-status").toString())+ Calls.answer(context, next.callId) { Calls.ringStatus(next) }+ }+ instrumentation.awaitCondition("The verified ended call was not resolved") { Calls.offer == null }+ val request = status.takeRequest(10, TimeUnit.SECONDS)+ assertNotNull(request)+ assertTrue(request!!.getHeader("traceparent")!!.startsWith("00-$traceId-"))+ assertFalse(request.getHeader("traceparent") == headers["traceparent"])++ var payload = ""+ while (!payload.contains("call.incoming")) {+ val bytes = exported.poll(10, TimeUnit.SECONDS)+ assertNotNull("Native spans were not exported", bytes)+ payload += bytes!!.toString(Charsets.UTF_8)+ }+ val remaining = mutableListOf<ByteArray>()+ exported.drainTo(remaining)+ payload += remaining.joinToString("") { it.toString(Charsets.UTF_8) }+ for (name in listOf("call.push.receive", "call.notification", "call.activity", "call.answer", "call.ring_status")) {+ assertTrue("Missing exported phase $name", payload.contains(name))+ }+ assertTrue(payload.contains(if (microphoneGranted) "already_granted" else "denied"))+ for (privateValue in listOf("Private caller marker", "Private channel marker", "secret-token-marker", "Authorization")) {+ assertFalse("Telemetry must exclude call content and credentials", payload.contains(privateValue))+ }+ // Disabling tracing while a permission phase is open must leave the ring alive,+ // close its trace, and stop propagating the old context on subsequent HTTP requests.+ instrumentation.runOnMainSync {+ val nextId = UUID.randomUUID().toString()+ val nextPayload = JSONObject().apply {+ put("callId", nextId); put("channelId", "trace-test-channel")+ put("channelName", "Private channel marker"); put("livekitServerUrl", "wss://unused.invalid")+ put("livekitToken", "secret-token-marker"); put("ringStatusUrl", "https://unavailable-call-test.macro.com/status")+ headers.forEach { (key, value) -> put(key, value) }+ }+ Calls.receive(context, mapOf("recipientId" to "trace-test-recipient", "payload" to nextPayload.toString()), System.currentTimeMillis())+ val permission = Calls.trace!!.phase("call.permission.microphone")+ CallTracing.configure(context, null, "test")+ assertNull(Calls.trace)+ assertEquals("Changing telemetry must not dismiss the call", nextId, Calls.offer?.callId)+ permission.end("granted")+ val next = Calls.offer!!.copy(ringUrl = status.url("/ring-status").toString())+ Calls.answer(context, next.callId) { Calls.ringStatus(next) }+ }+ instrumentation.awaitCondition("The call must still resolve with telemetry disabled") { Calls.offer == null }+ assertNull("Opt-out must detach the previous trace from HTTP", status.takeRequest(10, TimeUnit.SECONDS)!!.getHeader("traceparent"))+ // Re-enable the same exporter and exercise a real native media connection failure.+ shell("pm grant ${context.packageName} android.permission.RECORD_AUDIO")+ instrumentation.runOnMainSync {+ CallTracing.configure(context, endpoint, "test")+ val nextPayload = JSONObject().apply {+ put("callId", UUID.randomUUID().toString()); put("channelId", "trace-test-channel")+ put("livekitServerUrl", "wss://unused.invalid"); put("livekitToken", "secret-token-marker")+ put("ringStatusUrl", "https://unavailable-call-test.macro.com/status")+ headers.forEach { (key, value) -> put(key, value) }+ }+ Calls.receive(context, mapOf("recipientId" to "trace-test-recipient", "payload" to nextPayload.toString()), System.currentTimeMillis())+ }+ instrumentation.startActivitySync(Intent(context, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ instrumentation.runOnMainSync { Calls.answer(context, Calls.offer!!.callId) { "ringing" } }+ instrumentation.awaitCondition("The failed media connection must resolve") { Calls.offer == null }+ var failurePayload = ""+ while (!failurePayload.contains("call.connect")) {+ val bytes = exported.poll(10, TimeUnit.SECONDS)+ assertNotNull("Connection failure spans were not exported", bytes)+ failurePayload += bytes!!.toString(Charsets.UTF_8)+ }+ assertTrue(failurePayload.contains("connection_error"))+ assertFalse(failurePayload.contains("secret-token-marker"))+ java.io.File(context.getExternalFilesDir(null), "native-call-trace-id.txt").writeText(traceId)+ shell("cp ${context.getExternalFilesDir(null)}/native-call-trace-id.txt /sdcard/Download/native-call-trace-id.txt")+ instrumentation.runOnMainSync {+ CallTracing.configure(context, null, "test")+ val offer = CallOffer(UUID.randomUUID().toString(), "channel", "Test", "wss://unused.invalid", "token")+ assertNull("Telemetry opt-out must also disable cold native calls", CallTracing.start(context, offer))+ }+ } finally {+ instrumentation.runOnMainSync { Calls.end(context); CallTracing.configure(context, null, "test") }+ if (Build.VERSION.SDK_INT >= 34) shell("appops set ${context.packageName} USE_FULL_SCREEN_INTENT default")+ context.getSharedPreferences("macro_push", Context.MODE_PRIVATE).edit().clear().commit()+ status.close(); backend.close(); collector.close()+ }+ }+}diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallPresentationTest.kt b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallPresentationTest.ktnew file mode 100644index 0000000000..707ab09d65--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallPresentationTest.kt@@ -0,0 +1,177 @@+package com.macro.call++import android.Manifest+import android.accessibilityservice.AccessibilityService+import android.accessibilityservice.AccessibilityServiceInfo+import android.app.Notification+import android.app.NotificationManager+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build+import android.os.ParcelFileDescriptor+import android.view.accessibility.AccessibilityNodeInfo+import android.view.accessibility.AccessibilityEvent+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.json.JSONObject+import org.junit.After+import org.junit.Assert.*+import org.junit.Assume.assumeTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import java.util.UUID++/** Real notification actions and activity lifecycle, without a backend or media credentials. */+@RunWith(AndroidJUnit4::class)+class IncomingCallPresentationTest {+ private val instrumentation = InstrumentationRegistry.getInstrumentation()+ private val context = instrumentation.targetContext+ private val manager = context.getSystemService(NotificationManager::class.java)++ private fun shell(command: String): String = ParcelFileDescriptor.AutoCloseInputStream(+ instrumentation.uiAutomation.executeShellCommand(command)).bufferedReader().use { it.readText() }++ @Before fun setup() {+ context.getSharedPreferences("macro_push", Context.MODE_PRIVATE).edit().putString("recipient", "call-test-user").commit()+ if (Build.VERSION.SDK_INT >= 33) shell("pm grant ${context.packageName} android.permission.POST_NOTIFICATIONS")+ instrumentation.runOnMainSync { Calls.end(context) }+ }++ @After fun cleanup() {+ instrumentation.runOnMainSync { Calls.end(context) }+ if (Build.VERSION.SDK_INT >= 34) shell("appops set ${context.packageName} USE_FULL_SCREEN_INTENT default")+ shell("input keyevent 224")+ shell("input keyevent 4")+ context.getSharedPreferences("macro_push", Context.MODE_PRIVATE).edit().clear().commit()+ }++ private fun receive(id: String) {+ val payload = JSONObject().apply {+ put("callId", id); put("channelId", "call-preview-channel")+ put("channelName", "Design team"); put("callerName", "Test caller")+ put("livekitServerUrl", "wss://unused.invalid"); put("livekitToken", "test-token")+ put("ringStatusUrl", "https://unavailable-call-test.macro.com/status")+ }+ instrumentation.runOnMainSync {+ Calls.receive(context, mapOf("recipientId" to "call-test-user", "payload" to payload.toString()), System.currentTimeMillis())+ }+ instrumentation.awaitCondition("Incoming notification was not posted") {+ manager.activeNotifications.any { it.id == CallService.NOTIFICATION_ID }+ }+ }++ private fun notification(): Notification = manager.activeNotifications.single { it.id == CallService.NOTIFICATION_ID }.notification++ private fun answerNode(root: AccessibilityNodeInfo?): AccessibilityNodeInfo? {+ if (root == null) return null+ if (root.text?.contains("Answer") == true || root.contentDescription?.contains("Answer") == true) {+ var action: AccessibilityNodeInfo = root+ while (!action.isClickable) action = action.parent ?: return null+ return action+ }+ for (index in 0 until root.childCount) answerNode(root.getChild(index))?.let { return it }+ return null+ }++ @Test fun lockedIncomingCallOpensFullScreenAndBackKeepsTheRing() {+ assumeTrue(Build.VERSION.SDK_INT >= 34)+ shell("appops set ${context.packageName} USE_FULL_SCREEN_INTENT allow")+ shell("input keyevent 223")+ val monitor = instrumentation.addMonitor(CallActivity::class.java.name, null, false)+ try {+ val id = UUID.randomUUID().toString()+ receive(id)+ val activity = monitor.waitForActivityWithTimeout(10_000) as? CallActivity+ assertNotNull("A locked screen with full-screen access must open the incoming activity", activity)+ instrumentation.waitForIdleSync()+ instrumentation.uiAutomation.waitForIdle(500, 5_000)+ instrumentation.screenshot("incoming-call-full-screen.png")+ instrumentation.runOnMainSync {+ assertNull(Calls.room)+ assertEquals(id, Calls.offer?.callId)+ activity!!.onBackPressed()+ }+ instrumentation.awaitCondition("Back did not close the incoming screen") { !CallActivity.isOpen }+ assertNotNull(notification().contentIntent)+ assertTrue(notification().actions.size >= 2)+ instrumentation.runOnMainSync {+ assertEquals("Back must leave the ring answerable", id, Calls.offer?.callId)+ Calls.end(context, id)+ }+ instrumentation.awaitCondition("Ending the ring left its notification") { manager.activeNotifications.isEmpty() }+ } finally { instrumentation.removeMonitor(monitor) }+ }++ @Test fun deniedFullScreenAccessKeepsAnswerAndMicrophonePermissionReachable() {+ assumeTrue(Build.VERSION.SDK_INT >= 34)+ assumeTrue(context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED)+ shell("appops set ${context.packageName} USE_FULL_SCREEN_INTENT deny")+ shell("input keyevent 223")+ val id = UUID.randomUUID().toString()+ receive(id)+ assertFalse(manager.canUseFullScreenIntent())+ instrumentation.runOnMainSync {+ assertFalse("Denied full-screen access must leave presentation to Android's notification", CallActivity.isOpen)+ assertNull(Calls.room)+ }+ val incoming = notification()+ val answer = incoming.actions.single { it.actionIntent.isActivity }+ assertTrue("Answer must open the activity directly, without a notification trampoline", answer.actionIntent.isActivity)+ shell("input keyevent 224")+ instrumentation.uiAutomation.waitForIdle(500, 5_000)+ instrumentation.uiAutomation.executeAndWaitForEvent({+ assertTrue(instrumentation.uiAutomation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS))+ }, { event -> event.packageName == "com.android.systemui" &&+ event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED }, 5_000)+ instrumentation.uiAutomation.waitForIdle(500, 5_000)+ instrumentation.screenshot("incoming-call-notification-fallback.png")+ instrumentation.uiAutomation.serviceInfo = instrumentation.uiAutomation.serviceInfo.apply {+ flags = flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS+ }+ val monitor = instrumentation.addMonitor(CallActivity::class.java.name, null, false)+ try {+ val answerNode = instrumentation.uiAutomation.windows.firstNotNullOfOrNull { answerNode(it.root) }+ assertNotNull("The system notification must offer an Answer action", answerNode)+ assertTrue(answerNode!!.performAction(AccessibilityNodeInfo.ACTION_CLICK))+ val activity = monitor.waitForActivityWithTimeout(10_000) as? CallActivity+ assertNotNull("Notification Answer must reach the call screen", activity)+ instrumentation.waitForIdleSync()+ instrumentation.runOnMainSync {+ assertEquals(id, activity!!.intent.getStringExtra("answer"))+ val field = CallActivity::class.java.getDeclaredField("permissionCallId").apply { isAccessible = true }+ assertEquals("Answer must request microphone access for this ring", id, field.get(activity))+ assertNull(Calls.room)+ }+ instrumentation.uiAutomation.waitForIdle(500, 5_000)+ assertTrue("Microphone permission must be visible after notification Answer",+ instrumentation.uiAutomation.windows.any { it.root?.packageName?.toString()?.endsWith(".permissioncontroller") == true })+ instrumentation.screenshot("incoming-call-microphone-permission.png")+ } finally { instrumentation.removeMonitor(monitor) }+ }++ @Test fun staleNotificationActionsCannotAnswerOrDeclineAReplacementCall() {+ val old = UUID.randomUUID().toString()+ val next = UUID.randomUUID().toString()+ val staleAnswer = CallService.screen(context, old, answer = true)+ val staleDecline = CallService.action(context, "end", old)+ receive(next)+ val currentAnswer = CallService.screen(context, next, answer = true)+ val currentDecline = CallService.action(context, "end", next)+ assertNotEquals("Pending intents must retain their original call identity", staleAnswer, currentAnswer)+ assertNotEquals(staleDecline, currentDecline)+ val activity = instrumentation.startActivitySync(Intent(context, CallActivity::class.java)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("answer", old)) as CallActivity+ instrumentation.waitForIdleSync()+ staleDecline.send()+ instrumentation.waitForIdleSync()+ instrumentation.runOnMainSync {+ assertTrue("A stale Answer must close without requesting microphone access", activity.isFinishing || activity.isDestroyed)+ assertEquals(next, Calls.offer?.callId)+ assertNull(Calls.room)+ }+ currentDecline.send()+ instrumentation.awaitCondition("The current notification must still decline its call") { Calls.offer == null }+ }+}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 429f45a637..0cbff5682c 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@@ -42,10 +42,13 @@ class CallActivity : Activity() {private val renderers = mutableListOf<Pair<VideoTrack, SurfaceViewRenderer>>()private var permissionAction: (() -> Unit)? = nullprivate var permissionCallId: String? = null+ private var permissionTrace: CallTrace.Phase? = nullprivate var rendered: List<Any?>? = nullprivate val callback: () -> Unit = { render() }override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)+ if (!matchesCall(intent)) { finish(); return }+ val receipt = Calls.trace?.activity(intent)current = WeakReference(this)if (Build.VERSION.SDK_INT >= 33) {backCallback = android.window.OnBackInvokedCallback { dismissDrawer() }@@ -73,12 +76,20 @@ class CallActivity : Activity() {permission(Manifest.permission.RECORD_AUDIO, id) { Calls.answer(this, id) }}render()+ receipt?.end("shown")}override fun onNewIntent(intent: Intent) {super.onNewIntent(intent)+ if (!matchesCall(intent)) return+ val receipt = Calls.trace?.activity(intent)setIntent(intent)intent.getStringExtra("answer")?.let { id -> permission(Manifest.permission.RECORD_AUDIO, id) { Calls.answer(this, id) } }render()+ receipt?.end("shown")+ }+ private fun matchesCall(intent: Intent): Boolean {+ val id = intent.getStringExtra("callId") ?: intent.getStringExtra("answer")+ return Calls.offer != null && (id == null || id == Calls.offer?.callId)}private fun permission(name: String, callId: String? = null, action: () -> Unit) {if (permissionAction != null) {@@ -86,6 +97,7 @@ class CallActivity : Activity() {return}if (checkSelfPermission(name) == PackageManager.PERMISSION_GRANTED) {+ if (callId != null) Calls.trace?.takeIf { it.callId == callId }?.phase("call.permission.microphone")?.end("already_granted")callId?.let { Calls.finishMicrophonePermission(it) }action()return@@ -93,8 +105,10 @@ class CallActivity : Activity() {if (callId != null && !Calls.beginMicrophonePermission(callId)) returnpermissionCallId = callIdpermissionAction = action+ if (callId != null) permissionTrace = Calls.trace?.takeIf { it.callId == callId }?.phase("call.permission.microphone")try { requestPermissions(arrayOf(name), 4) }catch (_: Exception) {+ permissionTrace?.end("request_error", failed = true); permissionTrace = nullpermissionCallId?.let { Calls.finishMicrophonePermission(it) }permissionCallId = null; permissionAction = nullCalls.error = "Could not request permission. Try again."; render()@@ -105,9 +119,11 @@ class CallActivity : Activity() {if (code != 4 || permissionAction == null) returnval action = permissionActionval callId = permissionCallId+ val granted = grants.firstOrNull() == PackageManager.PERMISSION_GRANTED+ permissionTrace?.end(if (granted) "granted" else "denied"); permissionTrace = nullpermissionAction = null; permissionCallId = nullcallId?.let { Calls.finishMicrophonePermission(it) }- if (grants.firstOrNull() == PackageManager.PERMISSION_GRANTED) action?.invoke()+ if (granted) action?.invoke()else { Calls.error = "Permission denied. Enable it in Android settings to use this control."; render() }}private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()@@ -160,6 +176,48 @@ class CallActivity : Activity() {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 incoming(call: CallOffer) {+ val colors = theme!!+ // Cover the whole lock screen; the translucent drawer theme is only for an active call.+ window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(colors.drawer))+ layout.setBackgroundColor(colors.drawer)+ layout.setOnClickListener(null)+ val content = LinearLayout(this).apply {+ orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL+ setPadding(dp(24), dp(24), dp(24), dp(24)); tag = "incoming-call"+ }+ layout.addView(content, FrameLayout.LayoutParams(-1, -1))+ content.addView(label("Incoming Macro call", 14f, colors.muted).apply { gravity = Gravity.CENTER },+ LinearLayout.LayoutParams(-1, -2))+ val identity = LinearLayout(this).apply {+ orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER+ setPadding(0, dp(24), 0, dp(24))+ }+ val name = call.callerName ?: Calls.title ?: call.title+ identity.addView(label(Calls.initials(name), 36f).apply {+ gravity = Gravity.CENTER; background = background(colors.edgeMuted, 100)+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO+ }, LinearLayout.LayoutParams(dp(112), dp(112)))+ identity.addView(label(name, 28f).apply { gravity = Gravity.CENTER; maxLines = 3 },+ LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(24) })+ if (call.callerName != null) identity.addView(label(Calls.title ?: call.title, 16f, colors.muted).apply {+ gravity = Gravity.CENTER; maxLines = 2+ }, LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(8) })+ content.addView(ScrollView(this).apply {+ isFillViewport = true; addView(identity, FrameLayout.LayoutParams(-1, -1))+ }, LinearLayout.LayoutParams(-1, 0, 1f))+ Calls.error?.let { message ->+ content.addView(label(message, 14f, colors.muted).apply { gravity = Gravity.CENTER; maxLines = 3 },+ LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = dp(16) })+ }+ val actions = LinearLayout(this).apply { gravity = Gravity.CENTER }+ actions.addView(actionButton("Decline", colors.failure) { Calls.end(this, call.callId, outcome = "declined") },+ LinearLayout.LayoutParams(0, dp(64), 1f).apply { marginEnd = dp(8) })+ actions.addView(actionButton("Answer", colors.success) {+ permission(Manifest.permission.RECORD_AUDIO, call.callId) { Calls.answer(this, call.callId) }+ }, LinearLayout.LayoutParams(0, dp(64), 1f).apply { marginStart = dp(8) })+ content.addView(actions, LinearLayout.LayoutParams(-1, -2))+ }private fun render() {val call = Calls.offer ?: run { finish(); return }theme = Calls.drawerTheme ?: theme ?: CallTheme.load(this)@@ -183,6 +241,8 @@ class CallActivity : Activity() {stripScroll = participantStrip?.scrollX ?: stripScrollparticipantStrip = nulldetach(); layout.removeAllViews()+ if (Calls.state == "ringing") { incoming(call); return }+ window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(Color.TRANSPARENT))layout.setBackgroundColor(theme!!.scrim)if (isInPictureInPictureMode) {val pip = CallPictureInPicture.view(this, media?.let { Calls.localName(it) } ?: "You", local?.track, speaker?.name, speaker?.track) { track, mirror ->@@ -267,6 +327,8 @@ class CallActivity : Activity() {}.show()}private fun dismissDrawer() {+ // Back hides an unanswered call; its notification remains available to answer or decline.+ if (Calls.state == "ringing") { finish(); return }// 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.@@ -286,7 +348,7 @@ class CallActivity : Activity() {override fun onUserLeaveHint() { pip() }override fun onResume() {super.onResume()- if (!isInPictureInPictureMode) Calls.setOverlay("expanded")+ if (!isFinishing && !isInPictureInPictureMode) Calls.setOverlay("expanded")}override fun onPictureInPictureModeChanged(inPip: Boolean, config: android.content.res.Configuration) {super.onPictureInPictureModeChanged(inPip, config); pipRequested = inPip@@ -306,6 +368,7 @@ class CallActivity : Activity() {Calls.stopCamera(this)}override fun onDestroy() {+ permissionTrace?.end("activity_destroyed"); permissionTrace = nullif (Build.VERSION.SDK_INT >= 33) backCallback?.let { onBackInvokedDispatcher.unregisterOnBackInvokedCallback(it) }backCallback = nullpermissionCallId?.let { Calls.finishMicrophonePermission(it) }diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallOffer.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallOffer.ktindex 3c35326017..ef0e1b2920 100644--- a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallOffer.kt+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallOffer.kt@@ -13,6 +13,9 @@ internal data class CallOffer(val token: String,val ringUrl: String? = null,val sentTime: Long = System.currentTimeMillis(),+ val callerName: String? = null,+ val traceparent: String? = null,+ val tracestate: String? = null,) {companion object {fun fresh(sentTime: Long, now: Long): Boolean = RingPolicy.fresh(sentTime, now)@@ -24,7 +27,10 @@ internal data class CallOffer(val ring = data.getString("ringStatusUrl")require(URI(ring).let { it.scheme == "https" && (it.host == "macro.com" || it.host?.endsWith(".macro.com") == true) && it.userInfo == null })return CallOffer(id, data.getString("channelId"), data.optString("channelName", "Macro call"), server,- data.getString("livekitToken"), ring, sentTime).also {+ data.getString("livekitToken"), ring, sentTime,+ data.optString("callerName").takeIf { !data.isNull("callerName") && it.isNotBlank() },+ data.optString("traceparent").takeIf { !data.isNull("traceparent") && it.isNotBlank() },+ data.optString("tracestate").takeIf { !data.isNull("tracestate") && it.isNotBlank() }).also {require(it.channelId.isNotBlank() && it.token.isNotBlank())}}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 62d4bdf9f3..4dbf681d88 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@@ -41,9 +41,18 @@ internal class NameArgs { lateinit var identity: String; var displayName: Stringinternal class ThemeArgs { var theme: Map<String, Map<String, Double>> = emptyMap() }@InvokeArginternal class ModeArgs { var mode = "hidden" }+@InvokeArg+internal class TracingArgs { var tracesUrl: String? = null; var environment = "" }@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) {+ @Command fun configureTracing(invoke: Invoke) {+ try {+ val args = invoke.parseArgs(TracingArgs::class.java)+ CallTracing.configure(activity, args.tracesUrl, args.environment)+ invoke.resolve()+ } catch (_: Exception) { invoke.reject("Unable to configure native call tracing") }+ }private var preparePermissionCallId: String? = nullprivate var miniWindow: CallMiniWindow? = nulloverride fun load(webView: WebView) { miniWindow = CallMiniWindow(activity, webView) }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 525f19d1e5..eb8642f0fd 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@@ -6,6 +6,7 @@ import android.content.Intentimport android.content.pm.ServiceInfoimport android.os.Buildimport android.os.IBinder+import android.net.Uriimport androidx.core.app.NotificationCompatimport androidx.core.app.Personimport androidx.core.content.ContextCompat@@ -31,11 +32,17 @@ class CallService : Service() {service.stopSelf()}fun action(ctx: Context, name: String, id: String): PendingIntent = PendingIntent.getBroadcast(- ctx, name.hashCode(), Intent(ctx, CallReceiver::class.java).setAction(name).putExtra("callId", id),+ ctx, name.hashCode(), Intent(ctx, CallReceiver::class.java).setAction(name)+ .setData(Uri.parse("macro-call:$id/$name")).putExtra("callId", id),PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)- fun screen(ctx: Context): PendingIntent = PendingIntent.getActivity(ctx, 0,- Intent(ctx, CallActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)+ fun screen(ctx: Context, id: String?, answer: Boolean = false): PendingIntent = PendingIntent.getActivity(ctx, if (answer) 1 else 0,+ Intent(ctx, CallActivity::class.java).setData(Uri.parse("macro-call:$id/${if (answer) "answer" else "screen"}"))+ .putExtra("callId", id).apply {+ if (answer) putExtra("answer", id)+ Calls.trace?.takeIf { it.callId == id }?.write(this)+ },+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)}private var foregroundTypes = 0private var callId: String? = null@@ -108,25 +115,41 @@ class CallService : Service() {enableVibration(true)})val ringing = call != null && Calls.room == null- val builder = NotificationCompat.Builder(this, CHANNEL)- .setSmallIcon(android.R.drawable.sym_call_incoming).setContentTitle(Calls.title ?: call?.title ?: "Macro call")- .setCategory(NotificationCompat.CATEGORY_CALL).setOngoing(true).setOnlyAlertOnce(true)- .setSilent(!ringing)- // 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()- builder.setStyle(if (ringing) NotificationCompat.CallStyle.forIncomingCall(person,- action(this, "end", call.callId), action(this, "answer", call.callId))- else NotificationCompat.CallStyle.forOngoingCall(person, action(this, "end", call.callId)))+ val presentation = if (ringing) Calls.trace?.phase("call.notification") else null+ presentation?.attribute("android.full_screen.allowed", Build.VERSION.SDK_INT < 34 || manager.canUseFullScreenIntent())+ presentation?.attribute("android.keyguard.locked", getSystemService(KeyguardManager::class.java).isKeyguardLocked)+ try {+ val title = Calls.title ?: call?.title ?: "Macro call"+ val caller = call?.callerName ?: title+ val builder = NotificationCompat.Builder(this, CHANNEL)+ .setSmallIcon(android.R.drawable.sym_call_incoming).setContentTitle(if (ringing) caller else title)+ .setContentText(if (ringing && call?.callerName != null) "Incoming Macro call · $title"+ else if (ringing) "Incoming Macro call" else "Call in progress")+ .setPriority(NotificationCompat.PRIORITY_MAX)+ .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)+ .setCategory(NotificationCompat.CATEGORY_CALL).setOngoing(true).setOnlyAlertOnce(true)+ .setSilent(!ringing)+ // Like the system dialer and CallKit, show who is calling and the call controls on the lock screen.+ .setContentIntent(screen(this, call?.callId)).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)+ // Android downgrades this to a heads-up call notification when full-screen access is denied.+ .setFullScreenIntent(if (ringing) screen(this, call?.callId) else null, ringing)+ if (call != null) {+ val person = Person.Builder().setName((if (ringing) caller else title).ifBlank { "Macro call" }).setImportant(true).build()+ builder.setStyle(if (ringing) NotificationCompat.CallStyle.forIncomingCall(person,+ action(this, "end", call.callId), screen(this, call.callId, answer = true))+ else NotificationCompat.CallStyle.forOngoingCall(person, action(this, "end", call.callId)))+ }+ val notification = builder.build().apply { if (ringing) this.flags = this.flags or Notification.FLAG_INSISTENT }+ var types = ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL+ if (media || Calls.room != null) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE+ if (camera || Calls.video) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA+ promote(notification, types)+ foregroundTypes = types+ presentation?.end("posted")+ } catch (error: Exception) {+ presentation?.end("notification_error", failed = true, error = error)+ throw error}- val notification = builder.build().apply { if (ringing) this.flags = this.flags or Notification.FLAG_INSISTENT }- var types = ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL- if (media || Calls.room != null) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE- if (camera || Calls.video) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA- promote(notification, types)- foregroundTypes = types}override fun onDestroy() {if (instance === this) instance = nulldiff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallTracing.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallTracing.ktnew file mode 100644index 0000000000..57bb0196f0--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallTracing.kt@@ -0,0 +1,139 @@+package com.macro.call++import android.content.Context+import android.content.Intent+import android.content.pm.ApplicationInfo+import io.opentelemetry.api.common.Attributes+import io.opentelemetry.api.trace.Span+import io.opentelemetry.api.trace.SpanKind+import io.opentelemetry.api.trace.StatusCode+import io.opentelemetry.api.trace.Tracer+import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator+import io.opentelemetry.context.Context as TraceContext+import io.opentelemetry.context.propagation.TextMapGetter+import io.opentelemetry.context.propagation.TextMapSetter+import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter+import io.opentelemetry.sdk.resources.Resource+import io.opentelemetry.sdk.trace.SdkTracerProvider+import io.opentelemetry.sdk.trace.export.BatchSpanProcessor+import java.net.URI+import java.util.concurrent.TimeUnit++/** Native spans use the same exporter and enablement decision as browser telemetry, retained for cold calls. */+internal object CallTracing {+ private var provider: SdkTracerProvider? = null+ private var initialized = false+ private val propagator = W3CTraceContextPropagator.getInstance()+ private val getter = object : TextMapGetter<Map<String, String>> {+ override fun keys(carrier: Map<String, String>) = carrier.keys+ override fun get(carrier: Map<String, String>?, key: String) = carrier?.get(key)+ }+ private val setter = TextMapSetter<MutableMap<String, String>> { carrier, key, value -> carrier?.put(key, value); Unit }++ @Synchronized fun configure(context: Context, tracesUrl: String?, environment: String) {+ if (tracesUrl != null) {+ val uri = URI(tracesUrl)+ val cleartextDebug = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0 && uri.scheme == "http"+ require((uri.scheme == "https" || cleartextDebug) && uri.host != null && uri.userInfo == null && uri.fragment == null)+ require(uri.path.endsWith("/v1/traces") && environment.isNotBlank())+ }+ val settings = context.getSharedPreferences("macro_call_tracing", Context.MODE_PRIVATE)+ if (settings.getString("url", null) == tracesUrl && settings.getString("environment", null) == environment) return+ Calls.stopTracing(if (tracesUrl == null) "telemetry_disabled" else "telemetry_reconfigured")+ settings.edit()+ .putString("url", tracesUrl).putString("environment", environment).apply()+ provider?.shutdown()+ provider = null; initialized = false+ }++ @Synchronized fun start(context: Context, offer: CallOffer): CallTrace? {+ if (!initialized) {+ initialized = true+ val settings = context.getSharedPreferences("macro_call_tracing", Context.MODE_PRIVATE)+ val url = settings.getString("url", null) ?: return null+ val environment = settings.getString("environment", null) ?: return null+ provider = runCatching {+ val exporter = OtlpHttpSpanExporter.builder().setEndpoint(url).setTimeout(3, TimeUnit.SECONDS).build()+ SdkTracerProvider.builder().setResource(Resource.getDefault().merge(Resource.create(Attributes.builder()+ .put("service.name", "android-calls")+ .put("deployment.environment", environment)+ .put("service.version", context.packageManager.getPackageInfo(context.packageName, 0).versionName.orEmpty())+ .put("app.platform", "android").build())))+ .addSpanProcessor(BatchSpanProcessor.builder(exporter).setScheduleDelay(1, TimeUnit.SECONDS)+ .setMaxQueueSize(512).build()).build()+ }.getOrElse {+ android.util.Log.w("MacroCall", "Native call tracing initialization failed: ${it.javaClass.simpleName}")+ null+ }+ }+ val active = provider ?: return null+ return CallTrace(active.get("macro.calls"), offer.callId,+ extract(mapOf("traceparent" to offer.traceparent.orEmpty(), "tracestate" to offer.tracestate.orEmpty()))) {+ active.forceFlush()+ }+ }++ fun extract(carrier: Map<String, String>): TraceContext =+ propagator.extract(TraceContext.root(), carrier, getter)++ fun inject(context: TraceContext): Map<String, String> = mutableMapOf<String, String>().also {+ propagator.inject(context, it, setter)+ }+}++/** One incoming-call trace; explicit contexts avoid leaking an ambient scope across coroutine threads. */+internal class CallTrace(tracer: Tracer, val callId: String, parent: TraceContext, private val flush: () -> Unit = {}) {+ private val tracer = tracer+ private val root = tracer.spanBuilder("call.incoming").setParent(parent).setSpanKind(SpanKind.CONSUMER)+ .setAttribute("call.id", callId).startSpan()+ val context: TraceContext = TraceContext.root().with(root)+ private var finished = false+ private val phases = mutableSetOf<Phase>()++ @Synchronized fun phase(name: String, parent: TraceContext = context, kind: SpanKind = SpanKind.INTERNAL): Phase {+ // A late completion stays a no-op after the call has resolved.+ val span = if (finished) Span.getInvalid() else tracer.spanBuilder(name).setParent(parent)+ .setSpanKind(kind).setAttribute("call.id", callId).startSpan()+ return Phase(span).also { if (!finished) phases.add(it) }+ }++ fun write(intent: Intent) {+ CallTracing.inject(context).forEach { (key, value) -> intent.putExtra(key, value) }+ }++ fun activity(intent: Intent): Phase {+ val parent = CallTracing.extract(mapOf("traceparent" to intent.getStringExtra("traceparent").orEmpty(),+ "tracestate" to intent.getStringExtra("tracestate").orEmpty()))+ val matching = Span.fromContext(parent).spanContext.traceId == root.spanContext.traceId+ return phase("call.activity", if (matching) parent else context)+ }++ @Synchronized fun finish(outcome: String, failed: Boolean = false) {+ if (finished) return+ finished = true+ phases.toList().forEach { it.end(outcome, failed) }+ root.setAttribute("call.outcome", outcome)+ if (failed) root.setStatus(StatusCode.ERROR)+ root.end()+ flush()+ }++ inner class Phase internal constructor(private val span: Span) {+ val context: TraceContext = TraceContext.root().with(span)+ private var ended = false+ fun attribute(key: String, value: String) { synchronized(this@CallTrace) { if (!ended) span.setAttribute(key, value) } }+ fun attribute(key: String, value: Boolean) { synchronized(this@CallTrace) { if (!ended) span.setAttribute(key, value) } }+ fun attribute(key: String, value: Long) { synchronized(this@CallTrace) { if (!ended) span.setAttribute(key, value) } }+ // Exceptions can contain LiveKit URLs/JWTs; record only the exception class.+ fun end(outcome: String, failed: Boolean = false, error: Throwable? = null) {+ synchronized(this@CallTrace) {+ if (ended) return+ ended = true+ span.setAttribute("call.outcome", outcome)+ error?.let { span.setAttribute("error.type", it.javaClass.simpleName) }+ if (failed) span.setStatus(StatusCode.ERROR)+ span.end(); phases.remove(this)+ }+ }+ }+}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 ba1d6cd92b..f3eacccd08 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@@ -31,9 +31,18 @@ import org.json.JSONArrayimport org.json.JSONObjectimport java.net.HttpURLConnectionimport java.net.URL+import io.opentelemetry.api.trace.SpanKind+import io.opentelemetry.context.Context as TraceContext/** Main-thread owner shared by Telecom, FCM, service, Activity and the WebView. */internal object Calls {+ var trace: CallTrace? = null+ private set+ fun stopTracing(outcome: String) {+ val previous = trace+ trace = null+ previous?.finish(outcome)+ }val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)var offer: CallOffer? = nullprivate set@@ -214,17 +223,25 @@ internal object Calls {fun receive(ctx: Context, data: Map<String, String>, sentTime: Long) {if (android.os.Build.VERSION.SDK_INT < 26) returnval next = runCatching { CallOffer.parse(data["payload"].orEmpty(), sentTime) }.getOrNull()+ val incomingTrace = next?.let { CallTracing.start(ctx, it) }+ val receipt = incomingTrace?.phase("call.push.receive")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"+ data["recipientId"] != ctx.getSharedPreferences("macro_push", Context.MODE_PRIVATE).getString("recipient", null) -> "another_account"+ next == null -> "invalid_payload"+ !CallOffer.fresh(sentTime, now) -> "stale"+ ctx.getSharedPreferences("macro_calls", Context.MODE_PRIVATE).getLong(next.callId, 0) > now - 120_000 -> "recently_ended"+ offer != null -> "duplicate_or_busy"else -> null}- if (ignored != null || next == null) { android.util.Log.i("MacroCall", "Ignored call push: $ignored"); return }+ if (ignored != null || next == null) {+ val outcome = ignored ?: "invalid_payload"+ receipt?.end(outcome); incomingTrace?.finish(outcome)+ android.util.Log.i("MacroCall", "Ignored call push: $outcome"); return+ }+ receipt?.end("accepted")+ trace = incomingTracerecipient = ctx.getSharedPreferences("macro_push", Context.MODE_PRIVATE).getString("recipient", null)title = next.titleoffer = next; state = "ringing"; accepted = false@@ -237,32 +254,45 @@ internal object Calls {}poller = scope.launch {while (offer === next && room == null) {- if (!CallOffer.fresh(next.sentTime, ringTime())) { end(ctx, next.callId); break }+ if (!CallOffer.fresh(next.sentTime, ringTime())) { end(ctx, next.callId, outcome = "expired"); break }val status = ringStatus(next)if (offer !== next || joinLease?.channelId == next.channelId) break- if (RingPolicy.decide(next.sentTime, ringTime(), status) == RingPolicy.Decision.RESOLVE) { end(ctx, next.callId); break }+ if (RingPolicy.decide(next.sentTime, ringTime(), status) == RingPolicy.Decision.RESOLVE) {+ end(ctx, next.callId, outcome = when (status) { "answered" -> "answered_elsewhere"; "invalid" -> "invalid"; else -> "ended_remotely" }); break+ }delay(1000)}}} catch (error: Exception) {android.util.Log.w("MacroCall", "Incoming call failed: ${error.javaClass.simpleName}")- end(ctx, next.callId)+ end(ctx, next.callId, outcome = "telecom_error", failed = true)}}- private suspend fun ringStatus(next: CallOffer): String? = withContext(Dispatchers.IO) {- runCatching {+ internal suspend fun ringStatus(next: CallOffer, parent: TraceContext? = null): String? = withContext(Dispatchers.IO) {+ val owner = trace?.takeIf { it.callId == next.callId }+ val phase = owner?.phase("call.ring_status", parent ?: owner.context, SpanKind.CLIENT)+ phase?.attribute("http.request.method", "GET")+ try {val http = URL(next.ringUrl ?: return@withContext null).openConnection() as HttpURLConnectiontry {http.instanceFollowRedirects = falsehttp.connectTimeout = 5000; http.readTimeout = 5000http.setRequestProperty("Authorization", "Bearer ${next.token}")- when (http.responseCode) {+ phase?.let { CallTracing.inject(it.context).forEach { (key, value) -> http.setRequestProperty(key, value) } }+ val code = http.responseCode+ phase?.attribute("http.response.status_code", code.toLong())+ val status = when (code) {200 -> JSONObject(http.inputStream.bufferedReader().use { it.readText() }).getString("status")401, 403, 404 -> "invalid"else -> null}+ phase?.end(when (status) { "ringing", "answered", "ended", "invalid" -> status; else -> "retry" }, code >= 500)+ status} finally { http.disconnect() }- }.getOrNull()+ } catch (error: Exception) {+ phase?.end("network_error", failed = true, error = error)+ null+ } finally { phase?.end("unavailable") }}fun outgoing(ctx: Context, next: CallOffer, leaseId: String? = null) {if (leaseId != null) check(joinLease?.let { it.id == leaseId && it.channelId == next.channelId } == true) { "Call join was cancelled" }@@ -295,44 +325,62 @@ internal object Calls {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)+ end(ctx, outcome = "notification_error", failed = true)}}- fun answer(ctx: Context, id: String, verify: suspend (CallOffer) -> String? = ::ringStatus) {+ fun answer(ctx: Context, id: String, verify: (suspend (CallOffer) -> String?)? = null) {val next = offer ?: returnif (next.callId != id || room != null || answering) return+ val attempt = trace?.phase("call.answer")answering = truescope.launch {- // Recheck immediately before answer to close the answered-elsewhere race.- val status = verify(next)- if (offer !== next) return@launch- answering = false- if (joinLease?.channelId == next.channelId) return@launch- if (room != null || accepted) return@launch- when (RingPolicy.decide(next.sentTime, ringTime(), status)) {- RingPolicy.Decision.RESOLVE -> { end(ctx, id); return@launch }- RingPolicy.Decision.RETRY -> { error = "Could not verify this call. Check your connection and try again."; publish(); return@launch }- RingPolicy.Decision.RING -> error = null- }- if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {- if (!beginMicrophonePermission(id)) return@launch- runCatching {- ctx.startActivity(Intent(ctx, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("answer", id))- }.onFailure { finishMicrophonePermission(id) }- return@launch- }- poller?.cancel(); poller = null- accepted = true; state = "connecting"- pendingAnswered = next.channelId- connect(ctx)- emit("answered", JSObject().apply { put("channelId", next.channelId); put("nativeMedia", true) })+ try {+ // Recheck immediately before answer to close the answered-elsewhere race.+ val status = if (verify == null) ringStatus(next, attempt?.context) else verify(next)+ if (offer !== next) return@launch+ answering = false+ if (joinLease?.channelId == next.channelId) return@launch+ if (room != null || accepted) return@launch+ when (RingPolicy.decide(next.sentTime, ringTime(), status)) {+ RingPolicy.Decision.RESOLVE -> { attempt?.end("resolved"); end(ctx, id, outcome = "resolved_before_answer"); return@launch }+ RingPolicy.Decision.RETRY -> { attempt?.end("verification_unavailable", failed = true); error = "Could not verify this call. Check your connection and try again."; publish(); return@launch }+ RingPolicy.Decision.RING -> error = null+ }+ if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {+ if (!beginMicrophonePermission(id)) return@launch+ runCatching {+ val intent = Intent(ctx, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("answer", id)+ trace?.write(intent)+ ctx.startActivity(intent)+ }.onFailure { attempt?.end("permission_activity_error", failed = true, error = it); finishMicrophonePermission(id) }+ attempt?.end("permission_required")+ return@launch+ }+ poller?.cancel(); poller = null+ accepted = true; state = "connecting"+ pendingAnswered = next.channelId+ attempt?.end("accepted")+ connect(ctx)+ emit("answered", JSObject().apply { put("channelId", next.channelId); put("nativeMedia", true) })+ } catch (error: CancellationException) {+ attempt?.end("cancelled")+ throw error+ } catch (error: Exception) {+ attempt?.end("answer_error", failed = true, error = error)+ throw error+ } finally { attempt?.end("superseded") }}}fun connect(ctx: Context) {val next = offer ?: returnif (room != null) returnif (ContextCompat.checkSelfPermission(ctx, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { end(ctx, next.callId); return }- val media = LiveKit.create(ctx.applicationContext)+ val connecting = trace?.phase("call.connect", kind = SpanKind.CLIENT)+ val media = try { LiveKit.create(ctx.applicationContext) } catch (error: Exception) {+ connecting?.end("initialization_error", failed = true, error = error)+ end(ctx, next.callId, outcome = "connection_error", failed = true)+ return+ }room = mediamedia.audioSwitchHandler?.loggingEnabled = falsemedia.audioSwitchHandler?.registerAudioDeviceChangeListener { devices, selected ->@@ -371,18 +419,22 @@ internal object Calls {media.connect(next.serverUrl, next.token)if (room !== media) return@launchmedia.localParticipant.setMicrophoneEnabled(!muted && !interrupted())+ connecting?.end("connected")+ trace?.takeIf { it.callId == next.callId }?.finish("connected")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.+ connecting?.end("cancelled")} catch (error: Exception) {+ connecting?.end("connection_error", failed = true, error = error)// Exception messages can contain the signaling URL/token; log types only.android.util.Log.w("MacroCall", "Native media failed: ${error.javaClass.simpleName}; cause=${error.cause?.javaClass?.simpleName}")if (offer === next) {android.widget.Toast.makeText(ctx, "Could not connect the call. Please try again.", android.widget.Toast.LENGTH_LONG).show()- end(ctx, next.callId)+ end(ctx, next.callId, outcome = "connection_error", failed = true)}- }+ } finally { connecting?.end("superseded") }}}suspend fun microphone(enabled: Boolean) = audioMutex.withLock {@@ -452,10 +504,11 @@ internal object Calls {})}fun route(route: Int) { (connection as? TelecomService.MacroConnection)?.route(route) }- fun end(ctx: Context, id: String? = offer?.callId,+ fun end(ctx: Context, id: String? = offer?.callId, outcome: String = "ended", failed: Boolean = false,disconnectConnection: (Connection) -> Unit = { it.setDisconnected(DisconnectCause(DisconnectCause.LOCAL)) }) {val next = offer ?: returnif (next.callId != id) return+ trace?.finish(outcome, failed); trace = nullval preferences = ctx.getSharedPreferences("macro_calls", Context.MODE_PRIVATE)val now = System.currentTimeMillis()runCatching {diff --git a/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallOfferTest.kt b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallOfferTest.ktindex acc2590810..52cfa8f531 100644--- a/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallOfferTest.kt+++ b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallOfferTest.kt@@ -19,6 +19,23 @@ class CallOfferTest {assertEquals("channel-1", parsed.channelId)assertEquals("recipient-scoped-token", parsed.token)assertEquals(1000L, parsed.sentTime)+ assertEquals("Alice", parsed.callerName)+ }+ @Test fun missingCallerNamesKeepTheChannelIdentity() {+ val json = offer()+ json.remove("callerName")+ assertNull(CallOffer.parse(json.toString(), 1000).callerName)+ for (name in listOf("", " ", JSONObject.NULL)) {+ assertNull(CallOffer.parse(json.put("callerName", name).toString(), 1000).callerName)+ }+ }+ @Test fun traceContextIsOptionalAtTheDeployedPushBoundary() {+ val old = CallOffer.parse(offer().toString(), 1000)+ assertNull(old.traceparent)+ val next = CallOffer.parse(offer().put("traceparent", "00-11111111111111111111111111111111-2222222222222222-01")+ .put("tracestate", "test=value").toString(), 1000)+ assertEquals("00-11111111111111111111111111111111-2222222222222222-01", next.traceparent)+ assertEquals("test=value", next.tracestate)}@Test fun refusesToSendBearerTokensToUntrustedOrInsecureRingEndpoints() {for (url in listOf("http://dev.macro.com/ring", "https://macro.com.evil.example/ring", "https://evil.example/ring", "https://[email protected]/ring")) {diff --git a/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallTraceTest.kt b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallTraceTest.ktnew file mode 100644index 0000000000..3bfcfffba1--- /dev/null+++ b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallTraceTest.kt@@ -0,0 +1,66 @@+package com.macro.call++import io.opentelemetry.api.common.AttributeKey+import io.opentelemetry.api.trace.SpanKind+import io.opentelemetry.api.trace.StatusCode+import io.opentelemetry.context.Context+import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter+import io.opentelemetry.sdk.trace.SdkTracerProvider+import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor+import org.junit.Assert.*+import org.junit.Test++class CallTraceTest {+ @Test fun phasesPreserveRemoteParentsAndRedactExceptions() {+ val exporter = InMemorySpanExporter.create()+ SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build().use { provider ->+ val parent = CallTracing.extract(mapOf("traceparent" to "00-11111111111111111111111111111111-2222222222222222-01"))+ val call = CallTrace(provider.get("test"), "test-call", parent)+ val answer = call.phase("call.answer")+ val request = call.phase("call.ring_status", answer.context, SpanKind.CLIENT)+ val headers = CallTracing.inject(request.context)+ assertTrue(headers.getValue("traceparent").startsWith("00-11111111111111111111111111111111-"))+ request.end("network_error", failed = true, error = IllegalStateException("secret-token-and-caller-name"))+ answer.end("retry")+ call.finish("cancelled")++ val spans = exporter.finishedSpanItems+ val incoming = spans.single { it.name == "call.incoming" }+ val attempt = spans.single { it.name == "call.answer" }+ val http = spans.single { it.name == "call.ring_status" }+ assertEquals("2222222222222222", incoming.parentSpanId)+ assertEquals(incoming.spanId, attempt.parentSpanId)+ assertEquals(attempt.spanId, http.parentSpanId)+ assertEquals(StatusCode.ERROR, http.status.statusCode)+ assertEquals("IllegalStateException", http.attributes.get(AttributeKey.stringKey("error.type")))+ assertTrue(spans.all { it.traceId == incoming.traceId && it.endEpochNanos >= it.startEpochNanos })+ assertTrue(spans.all { !it.attributes.toString().contains("secret-token-and-caller-name") && it.events.isEmpty() })+ }+ }++ @Test fun resolvingTheCallClosesPendingPhasesExactlyOnce() {+ val exporter = InMemorySpanExporter.create()+ SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build().use { provider ->+ val call = CallTrace(provider.get("test"), "test-call", Context.root())+ val permission = call.phase("call.permission.microphone")+ call.finish("answered_elsewhere")+ permission.end("granted")+ call.finish("connected")+ call.phase("late-callback").end("done")+ assertEquals(2, exporter.finishedSpanItems.size)+ assertTrue(exporter.finishedSpanItems.all {+ it.attributes.get(AttributeKey.stringKey("call.outcome")) == "answered_elsewhere"+ })+ }+ }++ @Test fun malformedPushContextStartsANewTrace() {+ val exporter = InMemorySpanExporter.create()+ SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build().use { provider ->+ val call = CallTrace(provider.get("test"), "test-call", CallTracing.extract(mapOf("traceparent" to "invalid")))+ call.finish("declined")+ assertEquals("0000000000000000", exporter.finishedSpanItems.single().parentSpanId)+ assertNotEquals("00000000000000000000000000000000", exporter.finishedSpanItems.single().traceId)+ }+ }+}diff --git a/apps/web/tauri/callkit_plugin/build.rs b/apps/web/tauri/callkit_plugin/build.rsindex 3e990ca45b..4a9aed7b15 100644--- a/apps/web/tauri/callkit_plugin/build.rs+++ b/apps/web/tauri/callkit_plugin/build.rs@@ -4,6 +4,7 @@ use std::{};const COMMANDS: &[&str] = &[+ "configure_tracing","register_listener","remove_listener","get_voip_token",diff --git a/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/configure_tracing.toml b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/configure_tracing.tomlnew file mode 100644index 0000000000..d4c9841dd4--- /dev/null+++ b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/configure_tracing.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-configure-tracing"+description = "Enables the configure_tracing command without any pre-configured scope."+commands.allow = ["configure_tracing"]++[[permission]]+identifier = "deny-configure-tracing"+description = "Denies the configure_tracing command without any pre-configured scope."+commands.deny = ["configure_tracing"]diff --git a/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.mdindex a6ef19a7ec..fcbdc7809a 100644--- a/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md+++ b/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md@@ -62,6 +62,32 @@ Denies the can_use_full_screen_intent command without any pre-configured scope.<tr><td>+`call-kit:allow-configure-tracing`++</td>+<td>++Enables the configure_tracing command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-configure-tracing`++</td>+<td>++Denies the configure_tracing command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`call-kit:allow-end-active-call`</td>diff --git a/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json b/apps/web/tauri/callkit_plugin/permissions/schemas/schema.jsonindex c221ed058f..1c046d3f28 100644--- a/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json+++ b/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json@@ -318,6 +318,18 @@"const": "deny-can-use-full-screen-intent","markdownDescription": "Denies the can_use_full_screen_intent command without any pre-configured scope."},+ {+ "description": "Enables the configure_tracing command without any pre-configured scope.",+ "type": "string",+ "const": "allow-configure-tracing",+ "markdownDescription": "Enables the configure_tracing command without any pre-configured scope."+ },+ {+ "description": "Denies the configure_tracing command without any pre-configured scope.",+ "type": "string",+ "const": "deny-configure-tracing",+ "markdownDescription": "Denies the configure_tracing command without any pre-configured scope."+ },{"description": "Enables the end_active_call command without any pre-configured scope.","type": "string",diff --git a/apps/web/tauri/callkit_plugin/src/android-init.js b/apps/web/tauri/callkit_plugin/src/android-init.jsindex 3be204444c..13ad52a165 100644--- a/apps/web/tauri/callkit_plugin/src/android-init.js+++ b/apps/web/tauri/callkit_plugin/src/android-init.js@@ -1 +1,4 @@Object.defineProperty(window, '__MACRO_ANDROID_CALL_KIT__', { value: true });+Object.defineProperty(window, '__MACRO_ANDROID_CALL_TRACING__', {+ value: true,+});diff --git a/apps/web/tauri/callkit_plugin/src/android.rs b/apps/web/tauri/callkit_plugin/src/android.rsindex 3a63f7704a..cb8f6154a1 100644--- a/apps/web/tauri/callkit_plugin/src/android.rs+++ b/apps/web/tauri/callkit_plugin/src/android.rs@@ -4,6 +4,32 @@ use tauri::{AppHandle, Manager, Runtime, ipc::Channel, plugin::PluginHandle};pub(crate) struct Calls<R: Runtime>(pub PluginHandle<R>);+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct TracingArgs {+ traces_url: Option<String>,+ environment: String,+}++#[tauri::command]+pub(crate) async fn configure_tracing<R: Runtime>(+ app: AppHandle<R>,+ traces_url: Option<String>,+ environment: String,+) -> Result<(), String> {+ app.state::<Calls<R>>()+ .0+ .run_mobile_plugin_async(+ "configureTracing",+ TracingArgs {+ traces_url,+ environment,+ },+ )+ .await+ .map_err(|e| e.to_string())+}+macro_rules! command {($name:ident, $native:literal) => {#[tauri::command]diff --git a/apps/web/tauri/callkit_plugin/src/lib.rs b/apps/web/tauri/callkit_plugin/src/lib.rsindex 5629259d0a..65a3ebe7d9 100644--- a/apps/web/tauri/callkit_plugin/src/lib.rs+++ b/apps/web/tauri/callkit_plugin/src/lib.rs@@ -26,6 +26,7 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {#[cfg(target_os = "android")]let builder = builder.invoke_handler(tauri::generate_handler![+ android::configure_tracing,android::get_voip_token,android::end_active_call,android::get_pending_answered_call,diff --git a/apps/web/tauri/src-tauri/capabilities/android.json b/apps/web/tauri/src-tauri/capabilities/android.jsonindex d61b46f04f..a9958fe1de 100644--- a/apps/web/tauri/src-tauri/capabilities/android.json+++ b/apps/web/tauri/src-tauri/capabilities/android.json@@ -10,6 +10,7 @@"android-auth:allow-authenticate","android-mobile:default","android-push:default",+ "call-kit:allow-configure-tracing","call-kit:allow-end-active-call","call-kit:allow-get-pending-answered-call","call-kit:allow-watch-call-answered",diff --git a/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts b/apps/web/tauri/src-tauri/gen/android/app/build.gradle.ktsindex 7fb480d9d1..a8cc6f2686 100644--- a/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts+++ b/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts@@ -50,6 +50,11 @@ val tauriProperties = Properties().apply {}android {+ compileOptions {+ isCoreLibraryDesugaringEnabled = true+ sourceCompatibility = JavaVersion.VERSION_1_8+ targetCompatibility = JavaVersion.VERSION_1_8+ }compileSdk = 36namespace = "com.macro.workspace.mobile"defaultConfig {@@ -106,6 +111,7 @@ rust {}dependencies {+ coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")implementation("androidx.webkit:webkit:1.14.0")implementation("androidx.appcompat:appcompat:1.7.1")implementation("androidx.activity:activity-ktx:1.10.1")diff --git a/crates/notification/AGENTS.md b/crates/notification/AGENTS.mdindex 3352faa609..9f1155d3c7 100644--- a/crates/notification/AGENTS.md+++ b/crates/notification/AGENTS.md@@ -89,6 +89,8 @@ through the same service.stale/unknown measurements from zero; they are not client-delivery ACKs.- Notification payloads must not be logged on tracing spans (see the`fix(notification): stop recording notification payloads` history).+- Android call pushes carry W3C trace context inside their existing JSON offer;+ keep propagation in the outbound SNS adapter, with no baggage or payload logging.- iOS egress binds `recipientId` to each receiving account; channel pushes carryan optional typed `navigation` destination, with `threadId: null` for a rootmessage. Preserve older payloads that omit these fields.diff --git a/crates/notification/Cargo.toml b/crates/notification/Cargo.tomlindex f1dea09804..19082ad173 100644--- a/crates/notification/Cargo.toml+++ b/crates/notification/Cargo.toml@@ -64,6 +64,7 @@ model-error-response = { path = "../model-error-response", optional = true }model_user = { path = "../model_user", optional = true }models_pagination = { path = "../models_pagination" }notification_state = { path = "../notification_state", features = ["postgres"] }+opentelemetry = { workspace = true, features = ["trace"] }rate_limit = { path = "../rate_limit" }rdkafka = { workspace = true, optional = true }redis = { workspace = true, features = [@@ -85,12 +86,15 @@ tokio = { workspace = true, features = ["time"] }tokio-retry = { workspace = true }tokio-util = { workspace = true, features = ["rt"] }tracing = { workspace = true }+tracing-opentelemetry = { workspace = true }url = { workspace = true }utoipa = { workspace = true, optional = true }uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+opentelemetry_sdk = { workspace = true, features = ["trace", "testing"] }+tracing-subscriber = { workspace = true }http-body-util = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }rate_limit = { path = "../rate_limit", features = ["testing"] }diff --git a/crates/notification/src/outbound/mobile.rs b/crates/notification/src/outbound/mobile.rsindex 3ede4cacf9..ae664c6167 100644--- a/crates/notification/src/outbound/mobile.rs+++ b/crates/notification/src/outbound/mobile.rs@@ -122,7 +122,7 @@ impl<P: MobilePushOps + Send + Sync + 'static> MobilePushAdapter<P> {/// Bypasses the normal notification pipeline — sent immediately without/// DB persistence. Wakes the app via PushKit so CallKit can report an/// incoming call.- #[tracing::instrument(err, skip(self, recipient_id, payload))]+ #[tracing::instrument(name = "call.push.send", err, skip_all, fields(call.id = %payload.call_id, otel.kind = "producer"))]pub async fn send_voip_push(&self,endpoint_arn: &str,diff --git a/crates/notification/src/outbound/mobile/payload.rs b/crates/notification/src/outbound/mobile/payload.rsindex c97e3e9164..a21799ecc2 100644--- a/crates/notification/src/outbound/mobile/payload.rs+++ b/crates/notification/src/outbound/mobile/payload.rs@@ -5,6 +5,7 @@ use crate::domain::models::{apple::{APNSPushNotification, Alert, VoipPushPayload},};use serde::{Serialize, Serializer};+use tracing_opentelemetry::OpenTelemetrySpanExt;#[cfg(test)]mod test;@@ -140,8 +141,8 @@ impl<T> SnsTarget<'_, T> {}}- fn as_payload(&self) -> SnsPayload<'_, T> {- match self {+ fn as_payload(&self) -> Result<SnsPayload<'_, T>, serde_json::Error> {+ Ok(match self {SnsTarget::Ios(apnspush_notification) => SnsPayload::Ios {default: self.default_string(),apns: apnspush_notification,@@ -152,25 +153,38 @@ impl<T> SnsTarget<'_, T> {apns_voip: payload,apns_voip_sandbox: payload,},- SnsTarget::AndroidCall(payload, recipient) => SnsPayload::AndroidCall {- default: self.default_string(),- gcm: serde_json::json!({"fcmV1Message": {"message": {- "android": {"priority": "high", "ttl": "60s"},- "data": {"type": "call", "recipientId": recipient,- "payload": serde_json::to_string(payload).expect("call payload serializes")}- }}}),- },+ SnsTarget::AndroidCall(payload, recipient) => {+ let mut offer = serde_json::to_value(payload)?;+ let mut context = std::collections::HashMap::new();+ opentelemetry::global::get_text_map_propagator(|propagator| {+ propagator.inject_context(&tracing::Span::current().context(), &mut context);+ });+ // Only W3C trace context crosses the push boundary; never forward baggage.+ for key in ["traceparent", "tracestate"] {+ if let Some(value) = context.remove(key) {+ offer[key] = serde_json::Value::String(value);+ }+ }+ SnsPayload::AndroidCall {+ default: self.default_string(),+ gcm: serde_json::json!({"fcmV1Message": {"message": {+ "android": {"priority": "high", "ttl": "60s"},+ "data": {"type": "call", "recipientId": recipient,+ "payload": offer.to_string()}+ }}}),+ }+ }SnsTarget::Android(fcmmessage) => SnsPayload::Android {default: self.default_string(),gcm: fcmmessage,},- }+ })}}impl<T: Serialize> SnsTarget<'_, T> {/// Serialize the target to JSON for SNS.pub fn as_json(&self) -> Result<String, serde_json::Error> {- self.as_payload().as_json()+ self.as_payload()?.as_json()}}diff --git a/crates/notification/src/outbound/mobile/payload/test.rs b/crates/notification/src/outbound/mobile/payload/test.rsindex b4f79080db..eac7444f48 100644--- a/crates/notification/src/outbound/mobile/payload/test.rs+++ b/crates/notification/src/outbound/mobile/payload/test.rs@@ -127,3 +127,57 @@ fn android_call_push_is_short_lived_data_only_and_recipient_scoped() {assert_eq!(offer["livekitToken"], "recipient-token");assert_eq!(offer["callId"], payload.call_id);}++#[test]+fn android_call_push_carries_the_producing_span_context() {+ use opentelemetry::baggage::BaggageExt;+ use opentelemetry::trace::{TraceContextExt, TracerProvider};+ use tracing_subscriber::prelude::*;++ opentelemetry::global::set_text_map_propagator(+ opentelemetry::propagation::TextMapCompositePropagator::new(vec![+ Box::new(opentelemetry_sdk::propagation::TraceContextPropagator::new()),+ Box::new(opentelemetry_sdk::propagation::BaggagePropagator::new()),+ ]),+ );+ let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder().build();+ let subscriber = tracing_subscriber::registry()+ .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("call-test")));+ tracing::subscriber::with_default(subscriber, || {+ let span = tracing::info_span!("call.push.send");+ span.set_parent(opentelemetry::Context::new().with_baggage([+ opentelemetry::KeyValue::new("private", "private-context-marker"),+ ]))+ .unwrap();+ let _guard = span.enter();+ let payload = VoipPushPayload {+ aps: Default::default(),+ call_id: Uuid::now_v7().to_string(),+ channel_id: "test-channel".into(),+ channel_name: "Test channel".into(),+ caller_name: "Test caller".into(),+ livekit_server_url: None,+ livekit_token: None,+ ring_status_url: None,+ };+ let target: SnsTarget<'_, ()> = SnsTarget::AndroidCall(&payload, "test-recipient");+ let sns: Value = serde_json::from_str(&target.as_json().unwrap()).unwrap();+ let fcm: Value = serde_json::from_str(sns["GCM"].as_str().unwrap()).unwrap();+ let offer: Value = serde_json::from_str(+ fcm["fcmV1Message"]["message"]["data"]["payload"]+ .as_str()+ .unwrap(),+ )+ .unwrap();+ let context = span.context();+ let source = context.span();+ let expected = source.span_context();+ assert!(expected.is_valid());+ assert_eq!(+ offer["traceparent"],+ format!("00-{}-{}-01", expected.trace_id(), expected.span_id())+ );+ assert!(offer.get("baggage").is_none());+ assert!(!offer.to_string().contains("private-context-marker"));+ });+}diff --git a/deny.toml b/deny.tomlindex eeb671aadf..edd1d6ddbd 100644--- a/deny.toml+++ b/deny.toml@@ -242,6 +242,7 @@ deny = ["macro_authorization", # Credential-redaction span tests only"macro_tower_layers", # OpenTelemetry layer tests"native_app_server", # Dev tooling only+ "notification", # Call-push trace propagation and baggage-redaction tests only"notification_sandbox", # This is not production code its just tooling"opentelemetry-appender-tracing", # OpenTelemetry tracing-to-OTLP log bridge requires tracing-subscriber"projects", # Dev logging onlydiff --git a/docs/agent-guide/calls.md b/docs/agent-guide/calls.mdindex 9935b2f0f9..6cfec9c83c 100644--- a/docs/agent-guide/calls.md+++ b/docs/agent-guide/calls.md@@ -296,9 +296,27 @@ iOS: tap it to reopen the drawer, drag it to another corner, or drag it past a sto 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 theactive 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+reopens the drawer. Leaving the channel does not end the call. While ringing,+a locked phone opens a full-screen incoming-call screen when permitted, with+caller initials/name, channel context and large Answer/Decline controls. Back+hides this screen and leaves the call available in its notification. Incoming calls+also expose Answer/Decline in the **Calls** notification channel, including while+locked/backgrounded. When full-screen access is unavailable, the notification+remains usable; Answer opens the call screen directly for microphone permission+and retry errors. Verify allowed/denied full-screen access, missing microphone+permission, cancellation/expiry and stale notification actions after a replacement+call arrives. While Android 14+ blocks full-screen notifications, a toastoffers **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).++Synthetic emulator captures: [incoming screen](media/calls/android-incoming-call.png),+[notification fallback](media/calls/android-call-notification.png), and+[microphone permission after Answer](media/calls/android-call-microphone-permission.png).++Native Android call spans use service `android-calls` and the opaque `call.id`.+The existing telemetry gate also controls cold calls. W3C context connects the+push producer, notification/activity, permission and answer phases, and status+HTTP requests; connection and cancellation outcomes end the incoming trace.+For local collector verification and the exporter fixture, see+[native call tracing](../development/android.md#native-call-tracing).diff --git a/docs/agent-guide/media/calls/android-call-microphone-permission.png b/docs/agent-guide/media/calls/android-call-microphone-permission.pngnew file mode 100644index 0000000000..6448ac04fdBinary files /dev/null and b/docs/agent-guide/media/calls/android-call-microphone-permission.png differdiff --git a/docs/agent-guide/media/calls/android-call-notification.png b/docs/agent-guide/media/calls/android-call-notification.pngnew file mode 100644index 0000000000..ef37cf4a9fBinary files /dev/null and b/docs/agent-guide/media/calls/android-call-notification.png differdiff --git a/docs/agent-guide/media/calls/android-incoming-call.png b/docs/agent-guide/media/calls/android-incoming-call.pngnew file mode 100644index 0000000000..4e6ad7a722Binary files /dev/null and b/docs/agent-guide/media/calls/android-incoming-call.png differdiff --git a/docs/development/android.md b/docs/development/android.mdindex 79768bfb24..d9f9c3c65e 100644--- a/docs/development/android.md+++ b/docs/development/android.md@@ -885,9 +885,14 @@ retry but cannot authorize an answer. Logout/account switching ends native callsThe **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 the-call activity automatically; when unavailable, the call notification remains the-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;+incoming-call screen automatically; when unavailable, Android keeps a heads-up+call notification with Answer/Decline. Answer opens the call activity directly,+so microphone permission requests and verification errors remain accessible+without a background receiver launching an activity. Content, Answer, and+Decline intents are bound to the offered call; stale notification actions cannot+act on a replacement call. Android 14+ revokes full-screen access 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`. Oncenotifications 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@@ -898,8 +903,59 @@ camera access is requested when enabling video, and Bluetooth access when selectthat route on Android 12 or newer. A denied permission does not silently enablecapture.-The native call activity presents a themed drawer at approximately 92% of the-safe screen height, above navigation bars/cutouts. A large participant tile sits+While ringing, the native call activity fills the screen with an opaque themed+background, caller initials and name (or channel name when unavailable), channel+context, and large Answer/Decline controls. It has no drawer handle or participant+tiles. Back hides the screen while leaving the notification available; cancellation,+expiry and answering elsewhere dismiss it. A full-screen intent lets Android+choose this screen while locked or a notification while the phone is in use.+Test full-screen access allowed/denied, including notification Answer with+microphone permission missing and a stale action after another call arrives.++### Native call tracing++The Kotlin call plugin uses OpenTelemetry to export through the same OTLP endpoint+and enablement decision as browser telemetry. The guarded `configure_tracing`+command persists only the endpoint and environment, so incoming calls can export+without starting the WebView. Older binaries without the capability flag skip+this command. Reapplying an unchanged configuration preserves an active trace;+changing the endpoint or disabling telemetry closes and detaches it before shutting+down the provider, without ending the call. Disabled calls do not propagate the+old trace context in subsequent requests.++The outbound notification adapter adds `traceparent`/`tracestate` to the existing+Android call offer under `call.push.send`; older consumers ignore them. Native+`call.incoming` adopts that producer context. Children cover `call.push.receive`,+`call.notification`, `call.activity`, `call.permission.microphone`, `call.answer`,+`call.ring_status` and `call.connect`. Notification intents carry W3C context;+status requests inject it into HTTP headers so the backend request joins the+trace. Older pushes without valid context start a native root. Search by+`resource.service.name="android-calls"` and the opaque `call.id`; `call.outcome`+records permission, retry, cancellation and connection outcomes. Durations come+from span boundaries. Only exception classes are recorded: never caller/channel+names, JWTs, authorization headers or connection URLs.++The SDK uses a bounded 512-span queue and a three-second exporter timeout. It+shares the native media stack's OkHttp 4 transport and enables core library+desugaring, preserving the existing Android/Kotlin baseline. Consumer R8 rules+retain the HTTP transport provider, and optional SDK interfaces and annotation+types are present for release shrinking. Debug builds permit HTTP exporters for+local device testing; releases require HTTPS. Export is best effort when the+device is offline or terminated.++Run `CallTracingTest` with the native connected-test command below. It uses local+HTTP fixtures to verify producer context, real notification intents, permission+outcomes, downstream headers, protobuf export, mid-call telemetry changes and+connection failure without sending real pushes. With local Tempo on port 4318,+add `-Pandroid.testInstrumentationRunnerArguments.tracesUrl=http://10.0.2.2:4318/v1/traces`.+The synthetic trace ID is saved to `/sdcard/Download/native-call-trace-id.txt`;+fetch it from Tempo at `http://localhost:3200/api/traces/<trace-id>` to inspect+the connected backend producer, native phases and status-request server span.++### Active call controls++After answering, the native call activity presents a themed drawer at approximately+92% of the safe screen height, above navigation bars/cutouts. A large participant tile sitsabove a horizontally scrolling participant strip; tapping a strip tile selectsit 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