Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(android): count setup steps, pairing, screens and notification answers
leepokaif78f3c7a36da
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AlertNotificationTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AlertNotificationTest.ktindex e3b1fec5..5b8c8a65 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/AlertNotificationTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AlertNotificationTest.kt@@ -34,7 +34,7 @@ class AlertNotificationTest {private fun show(bot: String, alert: String): Notification {val tag = "$scope/$computer/$bot"posted += tag- NotificationDisplay.alert(context, scope, computer, bot, PushAlert.decode(alert))+ NotificationDisplay.alert(context, scope, computer, bot, PushAlert.decode(alert), "done")val deadline = SystemClock.elapsedRealtime() + 3000while (manager.activeNotifications.none { it.tag == tag } && SystemClock.elapsedRealtime() < deadline) SystemClock.sleep(10)return manager.activeNotifications.single { it.tag == tag }.notificationdiff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.ktindex 4794c791..aa9377d0 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt@@ -50,11 +50,7 @@ private enum class AccessPhase { Asking, Code, Approved, Ended }if (asking) asked = trueelse if (asked && !approved) { ended = state.error ?: "${computer.name} didn't approve this request."; store.clearError(); asked = false }}- LaunchedEffect(approved) {- if (!approved) return@LaunchedEffect- Analytics.capture(AnalyticsEvent.ComputerPaired, mapOf("via" to "account", "computer" to Analytics.computerTag(computer.computerId)))- delay(1000); dismiss()- }+ LaunchedEffect(approved) { if (approved) { delay(1000); dismiss() } }val phase = when {approved -> AccessPhase.Approvedticket != null -> AccessPhase.Codediff --git a/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt b/apps/android/app/src/main/kotlin/com/codync/android/Analytics.ktindex 717725f7..c0a038fa 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt@@ -3,9 +3,12 @@ package com.codync.androidimport android.content.Contextimport android.content.SharedPreferencesimport android.os.Build+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValue+import androidx.compose.ui.platform.UriHandlerimport java.security.MessageDigestimport java.time.Instantimport java.util.UUID@@ -27,10 +30,13 @@ import okhttp3.OkHttpClientimport okhttp3.Requestimport okhttp3.RequestBody.Companion.toRequestBody-/** What the phone reports (iOS `AnalyticsEvent`). Bot and message events come from the computer's host instead. */-internal enum class AnalyticsEvent(val wire: String) {- AppOpened("app_opened"), OnboardingCompleted("onboarding_completed"), ComputerPaired("computer_paired"),- SignedIn("signed_in"), SignedOut("signed_out"), VoiceCallStarted("voice_call_started"),+/** Reports a screen, sheet or onboarding step each time it appears. */+@Composable internal fun AnalyticsOnAppear(event: AnalyticsEvent) = LaunchedEffect(event) { Analytics.capture(event) }++/** Opens an outbound link, counted by what it leads to (desktop `openLink`). */+internal fun UriHandler.open(url: String, link: OutboundLink) {+ openUri(url)+ Analytics.capture(AnalyticsEvent.LinkOpened(link))}/**@@ -74,9 +80,7 @@ internal object Analytics {pending.clear(); timer?.cancel(); timer = null}- /** `properties` are public names, never content. */- fun capture(event: AnalyticsEvent, properties: Map<String, String> = emptyMap()) =- record(event.wire, properties.mapValues { JsonPrimitive(it.value) })+ fun capture(event: AnalyticsEvent) = record(event.name, event.properties)/** One event for the signed-in account (merging the install ID into it once), else the install ID. */fun record(name: String, extra: Map<String, JsonElement>) {@@ -93,8 +97,19 @@ internal object Analytics {} else enqueue(name, installId(stored), extra)}+ /** `onboarding_completed`, once per phone until Start over (iOS: its `onboardingCompleted` default), whichever account. */+ fun completeOnboarding(via: OnboardingVia) {+ val stored = prefs ?: return+ if (stored.getBoolean("onboarded", false)) return+ stored.edit().putBoolean("onboarded", true).apply()+ capture(AnalyticsEvent.OnboardingCompleted(via))+ }++ /** Start over: the next setup is onboarding again. */+ fun forgetOnboarding() { prefs?.edit()?.remove("onboarded")?.apply() }+/** `app_opened` once per trip to the foreground. */- fun becameActive() { if (!foreground) { foreground = true; capture(AnalyticsEvent.AppOpened) } }+ fun becameActive(context: Context) { if (!foreground) { foreground = true; capture(AnalyticsEvent.AppOpened.of(context)) } }fun enteredBackground() { foreground = false; flush() }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.ktnew file mode 100644index 00000000..4ad82dbd--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt@@ -0,0 +1,163 @@+package com.codync.android++import android.content.Context+import android.os.Build+import com.codync.android.core.HostError+import com.codync.android.core.PairingProblem+import java.io.IOException+import java.io.InterruptedIOException+import kotlinx.coroutines.TimeoutCancellationException+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonPrimitive++/**+ * What the phone reports (iOS `AnalyticsEvent`; every event and value: docs/reference/analytics-events.md).+ * Properties are typed: counts, booleans and the catalog's values, never content. Bot and message events+ * come from the computer's host instead.+ */+internal sealed class AnalyticsEvent(val name: String) {+ open val properties: Map<String, JsonElement> get() = emptyMap()++ /** `widgets` is null when the launcher can't say how many are installed. */+ data class AppOpened(val notifications: NotificationAccess, val widgets: Int?) : AnalyticsEvent("app_opened") {+ override val properties get() = mapOf("notifications" to notifications.json) + listOfNotNull(widgets?.let { "widgets" to JsonPrimitive(it) })++ companion object {+ fun of(context: Context) = AppOpened(NotificationAccess.of(context), runCatching { CodyncWidgets.installed(context) }.getOrNull())+ }+ }+ data class OnboardingStepViewed(val step: OnboardingStep) : AnalyticsEvent("onboarding_step_viewed") {+ override val properties get() = mapOf("step" to step.json)+ }+ data class OnboardingCompleted(val via: OnboardingVia) : AnalyticsEvent("onboarding_completed") {+ override val properties get() = mapOf("via" to via.json)+ }+ data class SignInStarted(val provider: SignInProvider) : AnalyticsEvent("sign_in_started") {+ override val properties get() = mapOf("provider" to provider.json)+ }+ data class SignInFailed(val provider: SignInProvider, val reason: SignInFailure) : AnalyticsEvent("sign_in_failed") {+ override val properties get() = mapOf("provider" to provider.json, "reason" to reason.json)+ }+ data class SignedIn(val provider: SignInProvider) : AnalyticsEvent("signed_in") {+ override val properties get() = mapOf("provider" to provider.json)+ }+ data object SignedOut : AnalyticsEvent("signed_out")+ data class PairingFailed(val reason: PairingFailure) : AnalyticsEvent("pairing_failed") {+ override val properties get() = mapOf("reason" to reason.json)+ }+ /** Sends the computer's analytics key (`Analytics.computerTag`), never its id. */+ data class ComputerPaired(val via: PairedVia, val computerId: String) : AnalyticsEvent("computer_paired") {+ override val properties get() = mapOf("via" to via.json, "computer" to JsonPrimitive(Analytics.computerTag(computerId)))+ }+ data object AccessRequested : AnalyticsEvent("access_requested")+ data class AccessRequestFailed(val reason: AccessFailure) : AnalyticsEvent("access_request_failed") {+ override val properties get() = mapOf("reason" to reason.json)+ }+ data class NotificationsAnswered(val granted: Boolean, val source: PromptSource) : AnalyticsEvent("notifications_answered") {+ override val properties get() = mapOf("granted" to JsonPrimitive(granted), "source" to source.json)+ }+ data class NotificationOpened(val kind: NotificationKind) : AnalyticsEvent("notification_opened") {+ override val properties get() = mapOf("kind" to kind.json)+ }+ data class SettingChanged(val setting: PhoneSetting, val on: Boolean) : AnalyticsEvent("setting_changed") {+ override val properties get() = mapOf("setting" to setting.json, "on" to JsonPrimitive(on))+ }+ data class LinkOpened(val link: OutboundLink) : AnalyticsEvent("link_opened") {+ override val properties get() = mapOf("link" to link.json)+ }+ data class VoiceCallStarted(val engine: VoiceEngineKind) : AnalyticsEvent("voice_call_started") {+ override val properties get() = mapOf("engine" to engine.json)+ }+ data class ScreenViewed(val screen: AnalyticsScreen) : AnalyticsEvent("screen_viewed") {+ override val properties get() = mapOf("screen" to screen.json)+ }+}++/** One of a property's catalog values, as sent. */+internal interface CatalogValue { val wire: String }++private val CatalogValue.json get() = JsonPrimitive(wire)++internal enum class NotificationAccess(override val wire: String) : CatalogValue {+ Allowed("allowed"), Denied("denied"), NotAsked("not_asked");++ companion object {+ /** Android 13+ asks; before that, notifications are on until turned off. */+ fun of(context: Context) = when {+ notificationsAllowed(context) -> Allowed+ Build.VERSION.SDK_INT >= 33 && !PushPreferences.asked(context) -> NotAsked+ else -> Denied+ }+ }+}++internal enum class OnboardingStep(override val wire: String) : CatalogValue { Welcome("welcome"), Install("install"), Scan("scan") }++internal enum class OnboardingVia(override val wire: String) : CatalogValue { Paired("paired"), Account("account"), Skipped("skipped") }++internal enum class SignInProvider(override val wire: String) : CatalogValue { Apple("apple"), Google("google"), Hosted("hosted") }++internal enum class SignInFailure(override val wire: String) : CatalogValue {+ Cancelled("cancelled"), Timeout("timeout"), Verification("verification"), Error("error")+}++internal enum class PairingFailure(override val wire: String) : CatalogValue {+ NotPairingLink("not_pairing_link"), OutdatedHost("outdated_host"), Invalid("invalid"), Expired("expired"), Unauthorized("unauthorized"),+ Unreachable("unreachable"), Timeout("timeout"), UpgradeRequired("upgrade_required"), Other("other");++ companion object {+ fun of(error: Throwable): PairingFailure = when {+ error is PairingProblem -> when (error.kind) {+ PairingProblem.Kind.NotPairingLink -> NotPairingLink+ PairingProblem.Kind.OutdatedHost -> OutdatedHost+ PairingProblem.Kind.Invalid -> Invalid+ }+ // 400: a host from before Android phones turns the platform down; 403: the code expired or was used.+ error is HostError -> when (error.status) { 400 -> OutdatedHost; 403 -> Expired; 426 -> UpgradeRequired; else -> Other }+ // The computer's keys don't match the code's.+ error is SecurityException -> Unauthorized+ error.isTimeout -> Timeout+ error is IOException -> Unreachable+ else -> Other+ }+ }+}++/** A deadline or a socket timeout anywhere in the chain. */+internal val Throwable.isTimeout: Boolean+ get() = generateSequence(this) { it.cause }.any { it is InterruptedIOException || it is TimeoutCancellationException }++internal enum class PairedVia(override val wire: String) : CatalogValue { Qr("qr"), Link("link"), Account("account") }++internal enum class AccessFailure(override val wire: String) : CatalogValue { Denied("denied"), Expired("expired"), Cancelled("cancelled") }++internal enum class PromptSource(override val wire: String) : CatalogValue { Settings("settings"), Widgets("widgets"), Automatic("automatic") }++/** An alert's kind; `category` is the host's `AlertKind` the push carries. */+internal enum class NotificationKind(override val wire: String, val category: String) : CatalogValue {+ Done("done", "done"), NeedsInput("needs_input", "needsInput"), Failed("failed", "failed");++ companion object {+ fun of(category: String): NotificationKind? = entries.firstOrNull { it.category == category }+ }+}++internal enum class PhoneSetting(override val wire: String) : CatalogValue { Push("push"), LiveActivities("live_activities") }++/** What an outbound link leads to (`install_command`: an install command copied). */+internal enum class OutboundLink(override val wire: String) : CatalogValue {+ Github("github"), Demo("demo"), Tailscale("tailscale"), Privacy("privacy"), InstallCommand("install_command"),+}++internal enum class VoiceEngineKind(override val wire: String) : CatalogValue {+ OnDevice("on_device"), OpenAI("openai"), Gemini("gemini"),+ /** A provider's speech-to-text and text-to-speech (`CloudSpeechEngine`), not its realtime model. */+ Cloud("cloud"),+}++/** `screen_viewed` values (the catalog's *Screens* table, iOS/Android column). */+internal enum class AnalyticsScreen(override val wire: String) : CatalogValue {+ Bots("bots"), State("state"), Chat("chat"), Thread("thread"), Trace("trace"), BotDetails("bot_details"), Memory("memory"),+ Routines("routines"), Marketplace("marketplace"), Settings("settings"), Computers("computers"), Usage("usage"),+ Account("account"), Pairing("pairing"), VoiceSettings("voice_settings"), RemoteScreen("remote_screen"),+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSheet.kt b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSheet.ktindex 0fdb9e6d..5235528b 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSheet.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSheet.kt@@ -17,7 +17,7 @@ import androidx.compose.ui.unit.dpimport com.codync.android.design.*private val DETAILS = listOf(- Triple("chart.bar", "Features you use", "Opening the app, creating or deleting a bot, sending a message (how many attachments, never the files), running a routine or a voice call, installing a connector. Each comes with the app version, the platform, and the bot's agent and model."),+ Triple("chart.bar", "Features you use", "Opening the app and its screens, setting up and pairing (and whether you allow notifications), creating or deleting a bot, sending a message (how many attachments, never the files), running a routine or a voice call, installing a connector. Each comes with the app version, the platform, and the bot's agent and model."),Triple("exclamationmark.triangle", "Crashes and errors", "When Codync crashes or an agent fails to answer: the kind of error and where in Codync's own code it happened. Never the error's message; file paths are cut down to Codync's own files."),Triple("globe", "Approximate location", "Country and city, looked up from your IP address. The IP address itself is never stored."),Triple("person.crop.circle", "Who it belongs to", "Your Codync account when you're signed in, otherwise a random ID made on this device."),@@ -46,7 +46,7 @@ private val DETAILS = listOf(Row(Modifier.padding(horizontal = 2.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {Text("See the", style = Type.caption, color = Palette.secondary)LinkButton("Privacy Policy", style = Type.caption.copy(textDecoration = androidx.compose.ui.text.style.TextDecoration.Underline),- color = Palette.text) { uri.openUri("https://codync.dev/privacy") }+ color = Palette.text) { uri.open("https://codync.dev/privacy", OutboundLink.Privacy) }Text("for details.", style = Type.caption, color = Palette.secondary)}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.ktindex 1f253034..4354b01f 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt@@ -12,13 +12,24 @@ import kotlinx.serialization.json.*// Accounts, account computers and starting over: what the account sheet and Computers & settings ask for.-fun AppStore.signIn(apple: Boolean = false, hosted: Boolean = false) = sessionAction {- if (hosted) NativeAccounts.hostedSignIn() else NativeAccounts.signIn(apple)+internal fun AppStore.signIn(provider: SignInProvider) = sessionAction {+ Analytics.capture(AnalyticsEvent.SignInStarted(provider))+ try {+ if (provider == SignInProvider.Hosted) NativeAccounts.hostedSignIn() else NativeAccounts.signIn(apple = provider == SignInProvider.Apple)+ } catch (error: CancellationException) { throw error }+ catch (error: Exception) {+ Analytics.capture(AnalyticsEvent.SignInFailed(provider, (error as? SignInError)?.reason ?: SignInFailure.Error))+ throw error+ }+ // Clerk holds the new session already, so this counts toward the account.+ Analytics.capture(AnalyticsEvent.SignedIn(provider))}fun AppStore.switchAccount(account: SavedAccount) = sessionAction { NativeAccounts.switch(account) }fun AppStore.retryAccounts() { NativeAccounts.retry() }fun AppStore.signOut() = sessionAction {val old = state.value.account.accounts.firstOrNull { it.userId == state.value.account.userId } ?: return@sessionAction+ // Sent first so it still counts toward the account.+ Analytics.capture(AnalyticsEvent.SignedOut)NativeAccounts.signOut(old.sessionId)transitions.withLock {// The SDK updates its session synchronously; its observer may be queued behind us.@@ -39,6 +50,8 @@ fun AppStore.refreshCloud() = action("cloud") {client.registerDevice(Build.MODEL.take(100))val computers = client.computers()mutableState.update { it.copy(cloudComputers = computers) }+ // Signed in to an account with computers, before pairing any (iOS: the same moment).+ if (computers.isNotEmpty() && state.value.computers.isEmpty()) Analytics.completeOnboarding(OnboardingVia.Account)// Online computers this phone has no grant on yet; a granted one needs Revoke before asking again.val target = computers.firstOrNull { remote -> state.value.computers.isEmpty() && remote.online == true &&remote.access != "granted" && remote.computerId !in asked }@@ -54,6 +67,7 @@ fun AppStore.requestAccess(target: CloudComputer) = action("access") {require(state.value.computers.isEmpty() || state.value.computers.first().id == target.computerId) { "Forget the current computer before connecting a different one." }asked.add(target.computerId)val ticket = client.requestAccess(target.computerId, target.signKey)+ Analytics.capture(AnalyticsEvent.AccessRequested)mutableState.update { it.copy(access = ticket) }try {while (currentCoroutineContext().isActive) {@@ -70,12 +84,19 @@ fun AppStore.requestAccess(target: CloudComputer) = action("access") {computer.validate()withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }mutableState.update { it.copy(computers = listOf(computer), setupComplete = true) }+ Analytics.capture(AnalyticsEvent.ComputerPaired(PairedVia.Account, computer.id))openMirror(); connect(); return@action}- "denied" -> throw IOException("${target.name} declined the request.")+ "denied" -> {+ Analytics.capture(AnalyticsEvent.AccessRequestFailed(AccessFailure.Denied))+ throw IOException("${target.name} declined the request.")+ }else -> throw CloudError(410, "requestExpired")}}+ } catch (error: CloudError) {+ if (error.code == "requestExpired") Analytics.capture(AnalyticsEvent.AccessRequestFailed(AccessFailure.Expired))+ throw error} finally { mutableState.update { it.copy(access = null) } }}@@ -83,6 +104,7 @@ fun AppStore.cancelAccess() {val ticket = state.value.accessval client = cloudval request = actions["access"]+ if (ticket != null) Analytics.capture(AnalyticsEvent.AccessRequestFailed(AccessFailure.Cancelled))action("cancelAccess") {request?.cancelAndJoin()if (ticket != null && client != null) client.cancelAccess(ticket.requestId)@@ -129,6 +151,7 @@ fun AppStore.forgetComputer() = sessionAction {fun AppStore.skipSetup() = action("setup") {withContext(Dispatchers.IO) { local.completeSetup() }mutableState.update { it.copy(setupComplete = true) }+ Analytics.completeOnboarding(OnboardingVia.Skipped)}fun AppStore.clearError() { mutableState.update { it.copy(error = null) } }@@ -146,6 +169,7 @@ fun AppStore.startOver() = sessionAction {File(cache, "shared-attachments").deleteRecursively()cache.listFiles()?.filter { it.name.startsWith("codync-images") }?.forEach { it.deleteRecursively() }}+ Analytics.forgetOnboarding()mutableState.update { it.copy(account = AccountState(ready = true), error = null) }loadContext(null)}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.ktindex c699f335..03c905f9 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt@@ -48,7 +48,8 @@ fun AppStore.setForeground(active: Boolean) {}}-fun AppStore.pair(text: String) {+/** Pairs with the computer in a `codync://pair` link: scanned or pasted ([PairedVia.Qr]) or opened from outside ([PairedVia.Link]). */+internal fun AppStore.pair(text: String, via: PairedVia) {if (pairingJob?.isActive == true) returnpairingJob = contextScope.launch {state.first { !it.loading }@@ -62,10 +63,15 @@ fun AppStore.pair(text: String) {val computer = HostConnector.pair(pairing, identity, Build.MODEL.take(100)).copy(color = old?.color)withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }mutableState.update { it.copy(computers = listOf(computer), setupComplete = true) }+ Analytics.capture(AnalyticsEvent.ComputerPaired(via, computer.id))+ Analytics.completeOnboarding(OnboardingVia.Paired)if (database == null) openMirror()connect()} catch (error: CancellationException) { throw error }- catch (error: Exception) { showError(error) }+ catch (error: Exception) {+ Analytics.capture(AnalyticsEvent.PairingFailed(PairingFailure.of(error)))+ showError(error)+ }finally { mutableState.update { it.copy(pairing = false) } }}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.ktindex dac28b4f..6e29dd83 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt@@ -19,12 +19,14 @@ fun AppStore.syncPush() = action("push") {fun AppStore.notifications(enabled: Boolean) = action("notificationSettings") {PushPreferences.enabled(getApplication(), enabled)mutableState.update { it.copy(notifications = enabled) }+ Analytics.capture(AnalyticsEvent.SettingChanged(PhoneSetting.Push, enabled))if (!enabled) NotificationDisplay.cancel(getApplication(), 1)syncPush(); PushDelivery.schedule(getApplication())}fun AppStore.taskNotifications(enabled: Boolean) = action("taskSettings") {PushPreferences.tasks(getApplication(), enabled)mutableState.update { it.copy(tasks = enabled) }+ Analytics.capture(AnalyticsEvent.SettingChanged(PhoneSetting.LiveActivities, enabled))if (!enabled) NotificationDisplay.cancel(getApplication(), 2)syncPush(); PushDelivery.schedule(getApplication())}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.ktindex 5ab406a4..468fea55 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt@@ -22,6 +22,8 @@ internal class VoiceBinding(val id: String, val botId: String, val generation: Ivar recording: () -> Int? = { null }/** What the voice service sees: the current engine, never the failure it fell back from. */val state = MutableStateFlow(VoiceState())+ /** `voice_call_started` went out: once per call, with the engine that got it going. */+ var reported = false}private val voiceHttp by lazy { OkHttpClient() }@@ -67,6 +69,12 @@ private fun AppStore.begin(call: VoiceBinding, provider: VoiceProvider?) {override fun respond(entry: Entry, optionId: String) = [email protected](entry, optionId)})call.recording = { null }+ val kind = when {+ provider == null -> VoiceEngineKind.OnDevice+ choices.speechMode(provider) -> VoiceEngineKind.Cloud+ provider == VoiceProvider.OpenAI -> VoiceEngineKind.OpenAI+ else -> VoiceEngineKind.Gemini+ }val engine: VoiceEngine = if (provider == null) {val audio = LocalVoiceAudio(getApplication(), VoicePreferences.language(getApplication()))call.recording = { audio.recordingSessionId }@@ -98,7 +106,14 @@ private fun AppStore.begin(call: VoiceBinding, provider: VoiceProvider?) {val last = engine.state.first { status ->val current = voiceBinding === call && call.engine === engineval fallingBack = provider != null && status.phase == VoicePhase.Failed- if (current && !fallingBack) publish(call, status)+ if (current && !fallingBack) {+ publish(call, status)+ // Live once it listens or talks; a cloud engine that failed first is reported as the one that took over.+ if (!call.reported && (status.phase == VoicePhase.Listening || status.phase == VoicePhase.Speaking)) {+ call.reported = true+ Analytics.capture(AnalyticsEvent.VoiceCallStarted(kind))+ }+ }!current || fallingBack || status.phase == VoicePhase.Ended}if (provider == null || last.phase != VoicePhase.Failed || voiceBinding !== call) return@launchdiff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.ktindex e44d590e..afa8ed54 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt@@ -69,6 +69,7 @@ import com.kyant.shapes.Capsule}@Composable private fun ThreadView(bot: Bot, state: AppState, store: AppStore, edit: (Bot) -> Unit) {+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Chat))val context = LocalContext.currentvar confirmNewSession by remember { mutableStateOf(false) }var confirmDelete by remember { mutableStateOf(false) }@@ -127,9 +128,18 @@ import com.kyant.shapes.CapsulelistOf(DialogAction("Open settings") { openAppSettings(context) })}// A thread over the chat, and "Full conversation" over either.- CodyncSheet(state.thread, { store.openBot(bot.id) }) { root -> RepliesView(bot, root, state, store, connect) }- CodyncSheet(state.trace, { store.showTrace(false) }) { TraceView(bot, state.thread, state) }- CodyncSheet(routines, { routines = false }) { RoutinesScreen(bot, state, store, routineId) }+ CodyncSheet(state.thread, { store.openBot(bot.id) }) { root ->+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Thread))+ RepliesView(bot, root, state, store, connect)+ }+ CodyncSheet(state.trace, { store.showTrace(false) }) {+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Trace))+ TraceView(bot, state.thread, state)+ }+ CodyncSheet(routines, { routines = false }) {+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Routines))+ RoutinesScreen(bot, state, store, routineId)+ }CodyncSheet(peer, { peer = null }) { BotConversationView(bot, it, state, store) }CodyncSheet(app, { app = null; setupEntry = null }) { ComposioConnectSheet(it, state, store, setupEntry) { store.refreshPlugins() } }CodyncSheet(connector, { connector = null; setupEntry = null }) { InstallConnectorSheet(it, state, store, setupEntry) }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.ktindex 1b235dba..a0bec399 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt@@ -61,12 +61,8 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }}}val signedIn = state.account.userId != null- AnalyticsMilestones(state)+ // Signed in, setup counts as complete (`loadContext`): the account's computers ask for access on their own.val onboarding = !state.setupComplete && state.computers.isEmpty() && state.cloudComputers.isEmpty()- // Signing in to an account that has computers completes setup, as pairing or skipping does.- LaunchedEffect(state.cloudComputers.isNotEmpty(), state.loading) {- if (!state.loading && !state.setupComplete && state.cloudComputers.isNotEmpty()) store.skipSetup()- }val root = when {state.loading -> Root.Loadingonboarding && !welcomed && !signedIn -> Root.Welcome@@ -101,22 +97,37 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }}// The account sheet holds its own push (Computers & settings), as the iOS sheet's NavigationStack.CodyncSheet(showAccount && (state.setupComplete || signedIn) && !state.loading, { showAccount = false; accountSettings = false }) {+ // Counted by the top page, outside NavStack: it composes the page below again while sliding.+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(if (accountSettings) AnalyticsScreen.Settings else AnalyticsScreen.Account))NavStack(listOfNotNull("account", "settings".takeIf { accountSettings }), key = { it }, pop = { accountSettings = false }) { page ->if (page == "account") AccountSwitcherView(state, store, { accountSettings = true }) { showPairing = true }else SettingsView(state, store, { accountSettings = false }, { showPairing = true }, { access = it }, openMarketplace)}}CodyncSheet(showComputers && !state.loading, { showComputers = false }) {+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Computers))SettingsView(state, store, null, { showPairing = true }, { access = it }, openMarketplace)}CodyncSheet(access, { access = null }) { AccessRequestView(state, store, it) }- CodyncSheet(showPairing && !state.loading, { showPairing = false }) { PairingView(state, store, inModal = true) }- CodyncSheet(showUsage && !state.loading, { showUsage = false }) { UsageScreen(state, store::refreshUsage, store::reloadUsage) }- CodyncSheet(showMarketplace && root == Root.Tabs, { showMarketplace = false }) { MarketplaceView(state, store) }+ CodyncSheet(showPairing && !state.loading, { showPairing = false }) {+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Pairing))+ PairingView(state, store, inModal = true)+ }+ CodyncSheet(showUsage && !state.loading, { showUsage = false }) {+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Usage))+ UsageScreen(state, store::refreshUsage, store::reloadUsage)+ }+ CodyncSheet(showMarketplace && root == Root.Tabs, { showMarketplace = false }) {+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Marketplace))+ MarketplaceView(state, store)+ }+ // An existing bot or group's editor is its details; a new one's isn't.CodyncSheet(groupEditor.takeIf { !state.loading }, { groupEditor = null }) { draft ->+ if (draft.id != null) AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))key(state.contextId, state.generation, draft.id) { GroupEditor(state, draft, store) }}CodyncSheet(editor.takeIf { !state.loading }, { editor = null }) { draft ->+ if (draft.id != null) AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))key(state.contextId, state.generation, draft.id) { BotEditor(state, draft, store) }}// The remote screen opens over the app once its sheets have slid away.@@ -134,25 +145,8 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }if (!visible.currentState && !visible.targetState) returnOverlay {AnimatedVisibility(visible, enter = fadeIn(Motion.layout()), exit = fadeOut(Motion.fade())) {+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.RemoteScreen))ScreenView(state, store, state.screenRequest?.watching, store::closeScreen)}}}--/** The app-level analytics events (iOS reports the same): setup finished, signed in, signed out. */-@Composable private fun AnalyticsMilestones(state: AppState) {- var setup by remember { mutableStateOf<Boolean?>(null) }- var user by remember { mutableStateOf<String?>(null) }- var known by remember { mutableStateOf(false) }- LaunchedEffect(state.loading, state.setupComplete) {- if (state.loading) return@LaunchedEffect- if (setup == false && state.setupComplete) Analytics.capture(AnalyticsEvent.OnboardingCompleted)- setup = state.setupComplete- }- LaunchedEffect(state.account.ready, state.account.userId) {- if (!state.account.ready) return@LaunchedEffect- val now = state.account.userId- if (known && now != user) Analytics.capture(if (now != null) AnalyticsEvent.SignedIn else AnalyticsEvent.SignedOut)- user = now; known = true- }-}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.ktindex 2e078dc1..edd8718b 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt@@ -30,17 +30,22 @@ class MainActivity : ComponentActivity() {super.onCreate(savedInstanceState)NativeAccounts.initialize(this)Analytics.start(applicationContext)- Analytics.userId = { store.state.value.account.userId }+ // Clerk's session, not the UI's copy of it: right as sign-in and sign-out happen.+ Analytics.userId = NativeAccounts::activeUserIdNotificationDisplay.channels(this)if (savedInstanceState == null) lifecycleScope.launch { CodyncWidgets.publishPreviews(applicationContext) }enableEdgeToEdge()setContent {val state by store.state.collectAsStateWithLifecycle()- val notifications = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { store.syncPush() }+ val notifications = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ notificationsAnswered(applicationContext, granted, PromptSource.Automatic)+ store.syncPush()+ }LaunchedEffect(state.computers.isNotEmpty(), state.contextId) {if (BuildConfig.PUSH_CONFIGURED && state.computers.isNotEmpty() && android.os.Build.VERSION.SDK_INT >= 33 && !PushPreferences.asked(applicationContext)) {PushPreferences.markAsked(applicationContext)- notifications.launch(android.Manifest.permission.POST_NOTIFICATIONS)+ // Already allowed (in Android settings): no prompt to answer.+ if (!notificationsAllowed(applicationContext)) notifications.launch(android.Manifest.permission.POST_NOTIFICATIONS)}}val images = remember(state.contextId, state.generation) { AccountImages.open(applicationContext, state.contextId) }@@ -63,7 +68,7 @@ class MainActivity : ComponentActivity() {setIntent(intent)handle(intent)}- override fun onStart() { super.onStart(); store.setForeground(true); Analytics.becameActive() }+ override fun onStart() { super.onStart(); store.setForeground(true); Analytics.becameActive(applicationContext) }override fun onStop() {store.setForeground(false)// A rotation isn't a trip to the background.@@ -72,9 +77,13 @@ class MainActivity : ComponentActivity() {}private fun handle(intent: Intent?) {val uri = intent?.data ?: return+ intent.getStringExtra(NotificationDisplay.ALERT_KIND)?.let { category ->+ intent.removeExtra(NotificationDisplay.ALERT_KIND)+ NotificationKind.of(category)?.let { Analytics.capture(AnalyticsEvent.NotificationOpened(it)) }+ }if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "pair") {intent.data = null- store.pair(uri.toString())+ store.pair(uri.toString(), PairedVia.Link)}// Retain the scoped, non-secret destination for Activity/process restoration.if (uri.scheme == BuildConfig.URL_SCHEME && uri.host in setOf("bot", "usage")) store.openLink(uri)diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt b/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.ktindex e044c27c..951e9f9e 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt@@ -38,6 +38,7 @@ private enum class AppTab { Bots, State }var tab by rememberSaveable { mutableStateOf(AppTab.Bots) }// Opening a bot (notification, widget, link) always lands on the Bots tab.if (state.selectedBot != null && tab != AppTab.Bots) tab = AppTab.Bots+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(if (tab == AppTab.Bots) AnalyticsScreen.Bots else AnalyticsScreen.State))val bottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()val barSpace = bottom + 62.dp + 24.dpGlassStage(Modifier.fillMaxSize(), chrome = {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.ktindex 66bfad9a..ca4c051e 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt@@ -23,6 +23,7 @@ import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.ui.layout.onVisibilityChangedimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp@@ -44,7 +45,12 @@ private enum class Backup { Export, Import }var backup by remember { mutableStateOf<Backup?>(null) }var confirmClear by remember { mutableStateOf(false) }LaunchedEffect(botId) { memory.load() }- CardSection("Memory", accessory = {+ // At the end of bot details: viewed once it scrolls into sight, once per opening.+ var viewed by remember(botId) { mutableStateOf(false) }+ val seen = Modifier.onVisibilityChanged(minFractionVisible = 0f) { visible ->+ if (visible && !viewed) { viewed = true; Analytics.capture(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Memory)) }+ }+ CardSection("Memory", modifier = seen, accessory = {IconButton("Add memory", "plus", enabled = !memory.busy) { editor = MemoryDraft.of(botId, null) }DropdownMenu({ listOf(MenuItem("Refresh", icon = "arrow.clockwise") { memory.refresh() },diff --git a/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt b/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.ktindex 53e2057e..7ff0b029 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt@@ -3,10 +3,12 @@ package com.codync.androidimport android.app.Activityimport com.clerk.api.Clerkimport com.clerk.api.ClerkConfigurationOptions+import com.clerk.api.hostedauth.HostedAuthCancellationExceptionimport com.clerk.api.network.serialization.ClerkResultimport com.clerk.api.network.serialization.errorMessageimport com.clerk.api.session.Sessionimport com.clerk.api.sso.OAuthProvider+import com.clerk.api.sso.SSOCancellationExceptionimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.flow.combine@@ -14,6 +16,9 @@ import kotlinx.coroutines.flow.collectimport kotlinx.coroutines.launchimport java.io.IOException+/** A sign-in that ended without an account, and why. */+internal class SignInError(val reason: SignInFailure, message: String, cause: Throwable? = null) : IOException(message, cause)+data class SavedAccount(val userId: String, val sessionId: String, val email: String, val avatar: String?)data class AccountState(val ready: Boolean = false, val configured: Boolean = NativeAccounts.configured,val userId: String? = null, val accounts: List<SavedAccount> = emptyList(),@@ -36,20 +41,24 @@ object NativeAccounts {.mapNotNull { session -> session.user?.let { user -> SavedAccount(user.id, session.id,user.primaryEmailAddress?.emailAddress ?: "Codync account", user.imageUrl.takeIf { it.startsWith("https://") }) } }.distinctBy(SavedAccount::userId)- val selectedId = selected?.takeIf { it.status == Session.SessionStatus.ACTIVE && it.expireAt > System.currentTimeMillis() }?.user?.id- AccountState(ready, true, selectedId, accounts, multiple,+ AccountState(ready, true, selected?.usableUserId(), accounts, multiple,if (error != null && !ready) "Couldn't restore sign-in. Check your connection and retry." else null)}.collect { update(it) }}+ /** The signed-in account right now; `observe` reports the same once its flows catch up. */+ fun activeUserId(): String? = if (configured) Clerk.activeSession?.usableUserId() else null++ private fun Session.usableUserId(): String? = takeIf { it.status == Session.SessionStatus.ACTIVE && it.expireAt > System.currentTimeMillis() }?.user?.id+suspend fun signIn(apple: Boolean) {require(Clerk.isInitialized.value) { "Wait for sign-in to finish loading." }val result = Clerk.auth.signInWithOAuth(if (apple) OAuthProvider.APPLE else OAuthProvider.GOOGLE)when (result) {- is ClerkResult.Failure -> throw IOException(result.errorMessage)+ is ClerkResult.Failure -> throw signInError(result)is ClerkResult.Success -> {val sessionId = result.value.signIn?.createdSessionId ?: result.value.signUp?.createdSessionId- require(sessionId != null) { "Sign-in needs additional verification. Continue using the other sign-in options." }+ ?: throw SignInError(SignInFailure.Verification, "Sign-in needs additional verification. Continue using the other sign-in options.")val activated = Clerk.auth.setActive(sessionId)requireSuccess(activated)}@@ -58,7 +67,17 @@ object NativeAccounts {suspend fun hostedSignIn() {val result = Clerk.auth.startHostedAuth()- requireSuccess(result)+ if (result is ClerkResult.Failure) throw signInError(result)+ }++ private fun signInError(failure: ClerkResult.Failure<com.clerk.api.network.model.error.ClerkErrorResponse>): SignInError {+ val cause = failure.throwable+ val reason = when {+ cause is SSOCancellationException || cause is HostedAuthCancellationException -> SignInFailure.Cancelled+ cause?.isTimeout == true -> SignInFailure.Timeout+ else -> SignInFailure.Error+ }+ return SignInError(reason, failure.errorMessage, cause)}suspend fun switch(account: SavedAccount) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.ktindex dd6309c0..08d1c19e 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt@@ -80,6 +80,8 @@ private enum class ComputerOS { Mac, Linux }var step by rememberSaveable { mutableStateOf(Step.Install) }var os by rememberSaveable { mutableStateOf(ComputerOS.Mac) }val dismiss = LocalDismissModal.current+ // In a sheet it's the Pairing screen (reported where it opens); otherwise first-run steps.+ if (!inModal) AnalyticsOnAppear(AnalyticsEvent.OnboardingStepViewed(if (step == Step.Install) OnboardingStep.Install else OnboardingStep.Scan))BackHandler(step == Step.Scan) { step = Step.Install }Column(Modifier.fillMaxSize().background(Palette.background)) {ScreenHeader({ if (step == Step.Scan) BackButton { step = Step.Install } else leading() }, {@@ -128,19 +130,19 @@ private enum class ComputerOS { Mac, Linux }Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {if (shown == ComputerOS.Mac) {Hint("Install with Homebrew")- CommandBlock("brew install --cask leepokai/codync/codync")+ CommandBlock("brew install --cask leepokai/codync/codync", records = OutboundLink.InstallCommand)Hint("or download the Mac app")- CommandBlock("https://github.com/leepokai/Codync/releases/latest/download/codync-macos.dmg")+ CommandBlock("https://github.com/leepokai/Codync/releases/latest/download/codync-macos.dmg", records = OutboundLink.InstallCommand)} else {Hint("Run the installer")- CommandBlock("curl -fsSL https://raw.githubusercontent.com/leepokai/Codync/main/packaging/install.sh | sh\ncodync-host install")+ CommandBlock("curl -fsSL https://raw.githubusercontent.com/leepokai/Codync/main/packaging/install.sh | sh\ncodync-host install", records = OutboundLink.InstallCommand)Hint("or install with Homebrew")- CommandBlock("brew install leepokai/codync/codync-host\ncodync-host install")+ CommandBlock("brew install leepokai/codync/codync-host\ncodync-host install", records = OutboundLink.InstallCommand)}Text(if (shown == ComputerOS.Mac) "Open Codync and it sets up the host on its own."else "codync-host install keeps it running in the background.", style = Type.subheadline, color = Palette.secondary)Hint("Every install option")- CommandBlock("https://www.codync.dev/#install")+ CommandBlock("https://www.codync.dev/#install", records = OutboundLink.InstallCommand)}}DemoButton()@@ -166,8 +168,8 @@ private enum class ComputerOS { Mac, Linux }/** A small label above a `CommandBlock`. */@Composable private fun Hint(text: String) = Text(text, style = Type.footnote, color = Palette.secondary)-/** A terminal command with a copy button. */-@Composable private fun CommandBlock(command: String) {+/** A terminal command with a copy button; copying it counts as opening `records`. */+@Composable private fun CommandBlock(command: String, records: OutboundLink? = null) {val clipboard = LocalClipboard.currentval scope = rememberCoroutineScope()var copied by remember { mutableStateOf(false) }@@ -180,6 +182,7 @@ private enum class ComputerOS { Mac, Linux }IconButton(if (done) "Copied" else "Copy", if (done) "checkmark" else "doc.on.doc") {scope.launch {clipboard.setClipEntry(ClipEntry(ClipData.newPlainText("Command", command)))+ records?.let { Analytics.capture(AnalyticsEvent.LinkOpened(it)) }copied = true; delay(1500); copied = false}}@@ -200,17 +203,14 @@ private enum class ComputerOS { Mac, Linux }fun pair(text: String) {if (state.pairing || text.isBlank()) returnerror = null; started = true- store.pair(text.trim())+ store.pair(text.trim(), PairedVia.Qr)}// The store pairs in the background: its finish (and its error) belong to this page.LaunchedEffect(state.pairing, state.error) {if (!started || state.pairing) return@LaunchedEffectstarted = falseval failure = state.error- if (failure == null) {- state.computers.firstOrNull()?.let { Analytics.capture(AnalyticsEvent.ComputerPaired, mapOf("via" to "qr", "computer" to Analytics.computerTag(it.id))) }- pasted = ""; paired()- }+ if (failure == null) { pasted = ""; paired() }else { error = failure; attempt++; store.clearError() }}Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 24.dp).padding(bottom = 24.dp),@@ -250,7 +250,7 @@ private enum class ComputerOS { Mac, Linux }IconLabel("Connects on Wi-Fi, over Tailscale, or from anywhere through Cloudflare, on its own. End-to-end encrypted.", "lock.fill")if (tailscale) IconLabel("Tailscale is on: Codync connects over it directly.", "checkmark.circle.fill")else IconLabel("Use Tailscale? Direct and faster away from home.", "arrow.up.right",- modifier = Modifier.plainButton { uri.openUri("https://tailscale.com/download") })+ modifier = Modifier.plainButton { uri.open("https://tailscale.com/download", OutboundLink.Tailscale) })}}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt b/apps/android/app/src/main/kotlin/com/codync/android/PushService.ktindex 977a7c8d..1579b757 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt@@ -188,7 +188,7 @@ class PushService : FirebaseMessagingService() {alert = PushAlert.decode(local.identity().openPush(sealed, computerId).toString(Charsets.UTF_8))}} catch (_: Exception) { /* Locked/unavailable key: show only a generic fallback. */ }- NotificationDisplay.alert(context, scope, computerId, botId, alert)+ NotificationDisplay.alert(context, scope, computerId, botId, alert, data["category"])} catch (_: Exception) { /* A malformed push cannot crash the Firebase service. */ }}}@@ -198,6 +198,8 @@ class PushService : FirebaseMessagingService() {internal object NotificationDisplay {const val ALERTS = "codync-alerts"const val TASKS = "codync-tasks"+ /** The tapped alert's kind (the host's `AlertKind`), for `notification_opened`. */+ const val ALERT_KIND = "codync:alertKind"fun channels(context: Context) {val manager = context.getSystemService(NotificationManager::class.java)manager.createNotificationChannel(NotificationChannel(ALERTS, "Bot updates", NotificationManager.IMPORTANCE_HIGH))@@ -207,18 +209,20 @@ internal object NotificationDisplay {val url = Uri.Builder().scheme(BuildConfig.URL_SCHEME).authority("bot").appendPath(bot).appendQueryParameter("scope", scope).appendQueryParameter("computer", computer).build()return Intent(context, MainActivity::class.java).setAction(Intent.ACTION_VIEW).setData(url)}- private fun builder(context: Context, scope: String, computer: String, bot: String, channel: String): NotificationCompat.Builder {- val pending = PendingIntent.getActivity(context, 0, open(context, scope, computer, bot), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)+ /** An alert's tap carries its kind; its own request code keeps it apart from the same bot's task. */+ private fun builder(context: Context, scope: String, computer: String, bot: String, channel: String, alertKind: String? = null): NotificationCompat.Builder {+ val intent = open(context, scope, computer, bot).apply { alertKind?.let { putExtra(ALERT_KIND, it) } }+ val pending = PendingIntent.getActivity(context, if (alertKind != null) 1 else 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)val generic = NotificationCompat.Builder(context, channel).setSmallIcon(R.drawable.ic_notification).setContentTitle(context.getString(R.string.app_name)).setContentText("A bot has an update.").build()return NotificationCompat.Builder(context, channel).setSmallIcon(R.drawable.ic_notification).setContentIntent(pending).setVisibility(NotificationCompat.VISIBILITY_PRIVATE).setPublicVersion(generic).setGroup("$scope/$computer")}/** The alert's title, what happened and its text; with the chat's face, a conversation from the bot. */- fun alert(context: Context, scope: String, computer: String, bot: String, alert: PushAlert) {+ fun alert(context: Context, scope: String, computer: String, bot: String, alert: PushAlert, kind: String?) {channels(context)val tag = "$scope/$computer/$bot"- val builder = builder(context, scope, computer, bot, ALERTS).setContentTitle(alert.title).setContentText(alert.body)+ val builder = builder(context, scope, computer, bot, ALERTS, kind.orEmpty()).setContentTitle(alert.title).setContentText(alert.body).setSubText(alert.subtitle).setStyle(NotificationCompat.BigTextStyle().bigText(alert.body)).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_MESSAGE)alert.conversation(bot)?.let { conversation ->diff --git a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.ktindex 0cf59ca5..85196241 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt@@ -122,7 +122,7 @@ import kotlinx.serialization.json.put}CardSection {row { ValueRow("App version", BuildConfig.VERSION_NAME) }- row { LinkButton("Source code") { uri.openUri("https://github.com/leepokai/Codync") } }+ row { LinkButton("Source code") { uri.open("https://github.com/leepokai/Codync", OutboundLink.Github) } }}CardSection {row {@@ -160,7 +160,9 @@ import kotlinx.serialization.json.put@Composable private fun NotificationsSection(state: AppState, store: AppStore) {val context = LocalContext.currentvar asked by remember { mutableStateOf(false) }- val request = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { asked = true }+ val request = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ notificationsAnswered(context, granted, PromptSource.Settings); asked = true+ }val allowed = rememberOnResume { notificationsAllowed(context) } || asked && notificationsAllowed(context)CardSection("Notifications", "Get a result summary, a request for input, or a failure notice. Notification previews follow your Android settings.") {if (BuildConfig.PUSH_CONFIGURED) row { SwitchRow("Push notifications", isOn = state.notifications, onChange = store::notifications) }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.ktindex 070ba2d8..31f25900 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt@@ -105,6 +105,12 @@ private enum class Surface { Widget, LiveUpdate, StatusBar }internal fun notificationsAllowed(context: Context) = context.getSystemService(NotificationManager::class.java).areNotificationsEnabled()+/** Android's notification prompt was answered: never asked on its own again, and reported. */+internal fun notificationsAnswered(context: Context, granted: Boolean, source: PromptSource) {+ PushPreferences.markAsked(context)+ Analytics.capture(AnalyticsEvent.NotificationsAnswered(granted, source))+}+internal fun openNotificationSettings(context: Context) = context.startActivity(Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))@@ -114,7 +120,9 @@ internal fun openNotificationSettings(context: Context) = context.startActivity(val installed = rememberOnResume { runCatching { CodyncWidgets.installed(context) }.getOrNull() }var asked by remember { mutableIntStateOf(0) }val allowed = rememberOnResume { notificationsAllowed(context) } || asked > 0 && notificationsAllowed(context)- val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { asked++; store?.syncPush() }+ val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ notificationsAnswered(context, granted, PromptSource.Widgets); asked++; store?.syncPush()+ }var kind by rememberSaveable { mutableStateOf("usage") }var provider by rememberSaveable { mutableStateOf("claude") }var sizeChoice by rememberSaveable { mutableStateOf("medium") }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/VoiceChatSettings.kt b/apps/android/app/src/main/kotlin/com/codync/android/VoiceChatSettings.ktindex fddb90aa..ce8ed9bd 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/VoiceChatSettings.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/VoiceChatSettings.kt@@ -22,6 +22,7 @@ import kotlinx.coroutines.launch* Opened from a call's gear and from Settings.*/@Composable internal fun VoiceChatSettings(state: AppState, store: AppStore) {+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.VoiceSettings))val context = LocalContext.currentval choices = remember { store.voiceChoices() }var engine by remember { mutableStateOf(choices.provider) }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.kt b/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.ktindex e89b679f..48997d87 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.kt@@ -67,7 +67,6 @@ internal fun openAppSettings(context: android.content.Context) =val color = bot?.let { AvatarPalette.tint(it.avatarColor) } ?: Palette.accentvar settings by remember { mutableStateOf(false) }val speaking = voice.phase == VoicePhase.Speaking- LaunchedEffect(call.id) { Analytics.capture(AnalyticsEvent.VoiceCallStarted) }Column(Modifier.padding(horizontal = 12.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) {Row(Modifier.fillMaxWidth().glass(Capsule()).padding(start = 14.dp, end = 7.dp, top = 7.dp, bottom = 7.dp),verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt b/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.ktindex 026160c7..0bebe2d1 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt@@ -55,6 +55,7 @@ import kotlin.math.sin/** First launch, before any setup: who the bots are, a glimpse of talking to one, one way forward (iOS `WelcomeView`). */@Composable internal fun WelcomeView(state: AppState, store: AppStore, start: () -> Unit) {+ AnalyticsOnAppear(AnalyticsEvent.OnboardingStepViewed(OnboardingStep.Welcome))val still = reduceMotion()// 0 = nothing yet … 4 = everything shown. Each beat enters in turn.var beat by remember { mutableIntStateOf(if (still) 4 else 0) }@@ -149,7 +150,7 @@ private val CREW = listOf(/** Opens a short recording of the app in use on YouTube, for anyone who can't pair a computer yet. */@Composable internal fun DemoButton(modifier: Modifier = Modifier) {val uri = LocalUriHandler.current- Row(modifier.plainButton { uri.openUri("https://youtube.com/shorts/xtZ5WeyOewU") }, verticalAlignment = Alignment.CenterVertically,+ Row(modifier.plainButton { uri.open("https://youtube.com/shorts/xtZ5WeyOewU", OutboundLink.Demo) }, verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.spacedBy(6.dp)) {Symbol("play.circle.fill", size = 17.dp, tint = Palette.text)Text("Watch the demo", style = Type.subheadline.medium, color = Palette.text)@@ -161,16 +162,16 @@ private val CREW = listOf(val busy = "session" in state.busyval enabled = state.account.ready && !busyColumn(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {- WideButton(enabled = enabled, busy = busy, action = { store.signIn(apple = true) }) {+ WideButton(enabled = enabled, busy = busy, action = { store.signIn(SignInProvider.Apple) }) {Symbol("apple.logo", size = 20.dp, tint = Palette.onAccent)Text("Continue with Apple")}- WideButton(primary = false, enabled = enabled, busy = busy, action = { store.signIn(apple = false) }) {+ WideButton(primary = false, enabled = enabled, busy = busy, action = { store.signIn(SignInProvider.Google) }) {Image(painterResource(R.drawable.google_logo), null, Modifier.size(20.dp))Text("Continue with Google")}// Clerk's own page covers the sign-ins that need another step (email codes, verification).- LinkButton("Other sign-in options", enabled = enabled, color = Palette.secondary, style = Type.footnote) { store.signIn(hosted = true) }+ LinkButton("Other sign-in options", enabled = enabled, color = Palette.secondary, style = Type.footnote) { store.signIn(SignInProvider.Hosted) }}}diff --git a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.ktindex eeb09a9f..b7a69ac9 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt@@ -1,5 +1,9 @@package com.codync.android+import com.codync.android.core.HostError+import com.codync.android.core.PairingProblem+import java.io.IOException+import kotlinx.serialization.json.JsonObjectimport org.junit.Assert.assertEqualsimport org.junit.Test@@ -9,6 +13,26 @@ class AnalyticsTest {assertEquals("fbfcd4f4fe9f876c", Analytics.computerTag("tZ1WMzsVltt-fj7mUDwZsg"))}+ @Test fun `event properties encode as JSON booleans numbers and catalog strings`() {+ fun json(event: AnalyticsEvent) = JsonObject(event.properties).toString()+ assertEquals("""{"granted":true,"source":"automatic"}""", json(AnalyticsEvent.NotificationsAnswered(true, PromptSource.Automatic)))+ assertEquals("""{"notifications":"not_asked","widgets":2}""", json(AnalyticsEvent.AppOpened(NotificationAccess.NotAsked, 2)))+ // A widget count the launcher couldn't give is left out, not sent as null.+ assertEquals("""{"notifications":"allowed"}""", json(AnalyticsEvent.AppOpened(NotificationAccess.Allowed, null)))+ assertEquals("""{"setting":"live_activities","on":false}""", json(AnalyticsEvent.SettingChanged(PhoneSetting.LiveActivities, false)))+ assertEquals("""{"via":"link","computer":"fbfcd4f4fe9f876c"}""", json(AnalyticsEvent.ComputerPaired(PairedVia.Link, "tZ1WMzsVltt-fj7mUDwZsg")))+ assertEquals("{}", json(AnalyticsEvent.SignedOut))+ }++ @Test fun `pairing failures map to the catalog's reasons`() {+ assertEquals(PairingFailure.NotPairingLink, PairingFailure.of(PairingProblem(PairingProblem.Kind.NotPairingLink)))+ assertEquals(PairingFailure.UpgradeRequired, PairingFailure.of(HostError(426, "Update")))+ assertEquals(PairingFailure.Expired, PairingFailure.of(HostError(403, "Expired code")))+ assertEquals(PairingFailure.Timeout, PairingFailure.of(IOException("Late", java.net.SocketTimeoutException())))+ assertEquals(PairingFailure.Unreachable, PairingFailure.of(IOException("Offline")))+ assertEquals(PairingFailure.Other, PairingFailure.of(IllegalArgumentException("Use Start over")))+ }+@Test fun `a crash keeps its type and Codync frames but never its message`() {val error = IllegalStateException("secret prompt text")val properties = CrashReports.properties(error).toString()diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.ktindex 9f7d1029..a8e797f9 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt@@ -3,17 +3,27 @@ package com.codync.android.coreimport java.net.URIimport java.net.URLDecoder+/** Why a pairing link can't be used (iOS `Pairing.Problem`). */+class PairingProblem(val kind: Kind, cause: Throwable? = null) : IllegalArgumentException(kind.message, cause) {+ enum class Kind(val message: String) {+ NotPairingLink("That isn't a Codync pairing code."),+ /** The computer runs a Codync that speaks another protocol version. */+ OutdatedHost("Update Codync on your computer, then show a new pairing code."),+ Invalid("This pairing code is damaged. Show a new one on your computer."),+ }+}+/** A short-lived pairing URL. Only the resulting Computer may be persisted. */data class Pairing(val computer: Computer, val code: String) {internal val offerId: String get() = RelayCrypto.offerId(code.decodeBase64Url(16))companion object {fun parse(text: String, scheme: String): Pairing {- require(text.length <= 16 * 1024) { "This pairing code is damaged. Show a new one on your computer." }+ if (text.length > 16 * 1024) throw PairingProblem(PairingProblem.Kind.Invalid)val url = try { URI(text.trim()) } catch (error: Exception) {- throw IllegalArgumentException("That isn't a Codync pairing code.", error)+ throw PairingProblem(PairingProblem.Kind.NotPairingLink, error)}- require(url.scheme == scheme && url.host == "pair" && url.rawQuery != null) { "That isn't a Codync pairing code." }+ if (url.scheme != scheme || url.host != "pair" || url.rawQuery == null) throw PairingProblem(PairingProblem.Kind.NotPairingLink)val params = linkedMapOf<String, String>()try {url.rawQuery.split('&').forEach { part ->@@ -36,8 +46,7 @@ data class Pairing(val computer: Computer, val code: String) {require(computer.urls.isNotEmpty() || computer.cloud != null) { "No valid computer address" }return Pairing(computer, code)} catch (error: IllegalArgumentException) {- if (params["v"] != "3") throw IllegalArgumentException("Update Codync on your computer, then show a new pairing code.", error)- throw IllegalArgumentException("This pairing code is damaged. Show a new one on your computer.", error)+ throw PairingProblem(if (params["v"] != "3") PairingProblem.Kind.OutdatedHost else PairingProblem.Kind.Invalid, error)}}}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.ktindex 91e06e26..5c2b694f 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt@@ -42,6 +42,13 @@ class PairingTest {assertFails<IllegalArgumentException> { Pairing.parse("https://example.test/?v=3", "codync") }}+ @Test fun `a rejected link says why`() {+ fun kind(text: String) = assertFails<PairingProblem> { Pairing.parse(text, "codync") }.kind+ assertEquals(PairingProblem.Kind.NotPairingLink, kind("https://example.test/?v=3"))+ assertEquals(PairingProblem.Kind.OutdatedHost, kind(link(params + ("v" to "2"))))+ assertEquals(PairingProblem.Kind.Invalid, kind(link(params + ("sk" to "invalid"))))+ }+@Test fun `unsafe direct endpoints are removed and at least one route must remain`() {val pairing = Pairing.parse(link(params + ("urls" to "javascript:alert(1),http://user:[email protected]")), "codync")assertEquals(emptyList<String>(), pairing.computer.urls)