Skip to content

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.

fix: stop sending account merges that analytics always refuses

leepokai0434a5bffd8c
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AnalyticsIdentityTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AnalyticsIdentityTest.kt
new file mode 100644
index 00000000..32016e37
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AnalyticsIdentityTest.kt
@@ -0,0 +1,46 @@
+package com.codync.android
+
+import android.content.Context
+import androidx.test.platform.app.InstrumentationRegistry
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class AnalyticsIdentityTest {
+ private fun JsonObject.text(key: String) = getValue(key).jsonPrimitive.content
+
+ /** Turning analytics off drops the queue, so nothing from this test reaches PostHog. */
+ private fun dropQueue() {
+ Analytics.setEnabled(false)
+ Analytics.setEnabled(true)
+ }
+
+ // The iPhone's analyticsIsOnByDefaultAndIdentifiesOnlyTheFirstAccount, on real SharedPreferences.
+ @Test fun theInstallIdMergesIntoTheFirstAccountOnly() {
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ val context = instrumentation.targetContext
+ val stored = context.getSharedPreferences("codync-analytics", Context.MODE_PRIVATE)
+ var events = emptyList<JsonObject>()
+ instrumentation.runOnMainSync {
+ Analytics.start(context)
+ dropQueue()
+ stored.edit().remove("identified").commit()
+ val userId = Analytics.userId
+ for (user in listOf("user_1", "user_2")) {
+ Analytics.userId = { user }
+ Analytics.record("signed_in", emptyMap())
+ }
+ events = Analytics.pending.toList()
+ dropQueue()
+ Analytics.userId = userId
+ stored.edit().remove("identified").commit()
+ }
+ assertEquals(
+ listOf("\$identify" to "user_1", "signed_in" to "user_1", "signed_in" to "user_2"),
+ events.map { it.text("event") to it.text("distinct_id") },
+ )
+ assertEquals(stored.getString("install", null), events[0].getValue("properties").jsonObject.text("\$anon_distinct_id"))
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt b/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt
index 7e1839b4..13cfb064 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
@@ -58,7 +58,7 @@ internal object Analytics {
private var prefs: SharedPreferences? = null
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val http by lazy { OkHttpClient() }
- private val pending = mutableListOf<JsonObject>()
+ internal val pending = mutableListOf<JsonObject>()
private var timer: Job? = null
private var sending = false
private var foreground = false
@@ -82,16 +82,18 @@ internal object Analytics {
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. */
+ /**
+ * One event for the signed-in account, else the install ID. The install ID merges into the first
+ * account only: PostHog refuses a second, so a later account on this phone starts its own profile.
+ */
fun record(name: String, extra: Map<String, JsonElement>) {
val stored = prefs ?: return
if (!enabled) return
val user = userId()
if (user != null) {
- val identified = stored.getStringSet("identified", emptySet()).orEmpty()
- if (user !in identified) {
+ if (!stored.contains("identified")) {
enqueue("\$identify", user, mapOf("\$anon_distinct_id" to JsonPrimitive(installId(stored))))
- stored.edit().putStringSet("identified", identified + user).apply()
+ stored.edit().putStringSet("identified", setOf(user)).apply()
}
enqueue(name, user, extra)
} else enqueue(name, installId(stored), extra)
diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift
index 71afc601..d1bee8ea 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift
@@ -97,14 +97,13 @@ public final class Analytics {
record("$exception", properties, sessionID: lastLaunchSession)
}
- /// One event for the signed-in account (merging the install ID into it once), else the install ID.
+ /// One event for the signed-in account, else the install ID. The install ID merges into the first
+ /// account only: PostHog refuses a second, so a later account on this phone starts its own profile.
private func record(_ name: String, _ extra: [String: Value], sessionID: String?) {
if let user = userID() {
- var identified = defaults.stringArray(forKey: Self.identifiedKey) ?? []
- if !identified.contains(user) {
+ if defaults.object(forKey: Self.identifiedKey) == nil {
enqueue("$identify", user, ["$anon_distinct_id": .string(installID)], sessionID)
- identified.append(user)
- defaults.set(identified, forKey: Self.identifiedKey)
+ defaults.set([user], forKey: Self.identifiedKey)
}
enqueue(name, user, extra, sessionID)
} else {
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
index e332f280..11c102b2 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
@@ -3,7 +3,7 @@ import Testing
@testable import CodyncKit
@MainActor
-@Test func analyticsIsOnByDefaultAndIdentifiesAccountsOnce() throws {
+@Test func analyticsIsOnByDefaultAndIdentifiesOnlyTheFirstAccount() throws {
let defaults = try #require(UserDefaults(suiteName: "AnalyticsTests-\(UUID())"))
let analytics = Analytics(defaults: defaults) { _ in false }
@@ -39,6 +39,12 @@ import Testing
#expect(identify.properties["$anon_distinct_id"] == .string(anon.distinct_id))
#expect(analytics.pending[2].properties["$process_person_profile"] == .bool(true))
+ // Another account on this phone: the install ID already joined the first, so no second $identify.
+ analytics.userID = { "user_2" }
+ analytics.capture(.signedIn(.apple))
+ #expect(analytics.pending.last?.distinct_id == "user_2")
+ #expect(analytics.pending.filter { $0.event == "$identify" }.count == 1)
+
// The computer key matches the host's (host/src/analytics.rs `computer_tag_matches_the_iphone`).
#expect(Analytics.computerTag("AAECAwQFBgcICQoLDA0ODw") == "2d6878bee20aba04")
diff --git a/docs/features/analytics.md b/docs/features/analytics.md
index beda9c4b..ab3b37a2 100644
--- a/docs/features/analytics.md
+++ b/docs/features/analytics.md
@@ -31,8 +31,9 @@ UI: *About usage analytics…*) shows the same promise in the app, in one text p
packages have no install step that could ask.
- **Identity.** Every device gets a person profile. Signed in to a Codync account: the Clerk
user id. Otherwise a random install id (the host id on a computer, a UUID on the iPhone).
- The first signed-in event sends `$identify` with `$anon_distinct_id` so earlier events join
- the account.
+ A device's first signed-in event sends `$identify` with `$anon_distinct_id` so earlier events
+ join the account. Only once per device: PostHog refuses to merge an id into a second account
+ (`cannot_merge_already_identified`), so a later account on that device starts its own profile.
- **Sessions.** Every event carries a `$session_id` (a UUIDv7) that changes after 30 minutes
without events or 24 hours in all, as in PostHog's own SDKs, and on each launch of an app or
start of the host (host `analytics/session.rs`, `AnalyticsSession` on the iPhone and Android),
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index d246cad9..c6ab3d76 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -27,7 +27,8 @@ pub use reported::track;
pub use turns::{Steer, TurnOutcome, TurnSource, agent_fell_back, message_steered, turn_finished};
const KV_ENABLED: &str = "analytics_enabled";
-/// The account the install id was last merged into (one `$identify` per account).
+/// The account the install id was merged into. An id merges into one account and a second is
+/// refused, so a later account on this computer starts its own profile.
const KV_IDENTIFIED: &str = "analytics_identified";
/// Write-only project token: safe to ship in public builds.
const TOKEN: &str = "phc_rQHvxdSFKnMquPfMjmiMhXhM4tqJ5qCYsWuVEoFxCCWX";
@@ -294,7 +295,7 @@ pub fn capture(hub: &Hub, event: Event, mut properties: Map<String, Value>) {
}
let account = hub.cloud.status().owner.map(|o| o.user_id);
if let Some(user) = &account
- && hub.store.kv_get(KV_IDENTIFIED).as_deref() != Some(user.as_str())
+ && hub.store.kv_get(KV_IDENTIFIED).is_none()
{
// Merges this install's earlier, anonymous events into the account.
let identify = json!({"$anon_distinct_id": hub.host_id, "$process_person_profile": true});
@@ -424,4 +425,32 @@ mod tests {
// Same vector as the iPhone's AnalyticsTests.
assert_eq!(computer_tag("AAECAwQFBgcICQoLDA0ODw"), "2d6878bee20aba04");
}
+
+ #[test]
+ fn the_install_id_merges_into_the_first_account_only() {
+ use crate::remote::cloud::{Owner, update_status};
+ let dir = std::env::temp_dir().join(format!("codync-analytics-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();
+ let identity = crate::remote::identity::Identity::load_or_create(&dir).unwrap();
+ let hub = Hub::new(store, "h".into(), identity, "t".into(), 0);
+
+ for user in ["user_1", "user_2"] {
+ update_status(&hub, |s| s.owner = Some(Owner { user_id: user.into(), email: None }));
+ capture(&hub, Event::AppOpened, Map::new());
+ }
+
+ let mut rx = hub.analytics.rx.locked().take().unwrap();
+ let mut sent = Vec::new();
+ while let Ok(Msg::Event(event)) = rx.try_recv() {
+ sent.push(event);
+ }
+ assert_eq!(
+ sent.iter().map(|e| (e["event"].as_str().unwrap(), e["distinct_id"].as_str().unwrap())).collect::<Vec<_>>(),
+ [("$identify", "user_1"), ("app_opened", "user_1"), ("app_opened", "user_2")]
+ );
+ assert_eq!(sent[0]["properties"]["$anon_distinct_id"], "h");
+ assert_eq!(hub.store.kv_get(KV_IDENTIFIED).as_deref(), Some("user_1"));
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
}