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
fix: make usage analytics accurate
leepokaia8eeb5399036
diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex b642f8f5..cf3ccfad 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -161,7 +161,7 @@ export class BotStore extends BotSync {this.changed()}- /** Fire-and-forget; the host drops it unless analytics is on. */+ /** Fire-and-forget; the host holds it until this computer answers and drops it on a no. */track(event: AnalyticsEvent) {void this.withLink((c) => c.call('track', { event })).catch((error: unknown) => console.warn(`track ${event} failed`, error))}diff --git a/apps/desktop/src/renderer/views/AnalyticsPrompt.tsx b/apps/desktop/src/renderer/views/AnalyticsPrompt.tsxindex 3cff6c98..15959733 100644--- a/apps/desktop/src/renderer/views/AnalyticsPrompt.tsx+++ b/apps/desktop/src/renderer/views/AnalyticsPrompt.tsx@@ -15,9 +15,6 @@ const points: [icon: string, text: string][] = [['lock.shield', "Never sold or used for ads. Linked to your Codync account when you're signed in"],['gearshape', 'Turn it off anytime in Settings'],]-/** Read at launch: a welcome screen finished later was this launch's onboarding. */-const onboardedAtLaunch = prefs.onboardingDone.get()-/*** Asks this computer's owner once whether to share product analytics: after the welcome screen,* or on the first launch after updating. Closing without choosing asks again next launch.@@ -34,7 +31,6 @@ export function AnalyticsPrompt() {if (!local) returntry {await local.setAnalytics(share)- if (share && !onboardedAtLaunch) local.track('onboarding_completed')} catch (e) {app.setError(errorText(e))}diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsxindex 78e19a0a..3ec092ed 100644--- a/apps/desktop/src/renderer/views/ChatWindow.tsx+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx@@ -96,7 +96,12 @@ export function ChatWindow() {<HostStateView />)) : (- <AccountWelcomeView onContinue={() => setOnboarded(true)} />+ <AccountWelcomeView+ onContinue={() => {+ setOnboarded(true)+ app.local?.track('onboarding_completed')+ }}+ />)}{onboarded && accessSetup !== null ? <><AnalyticsPrompt /><StarPrompt /></> : null}<Sheet open={showAccess} onClose={() => setShowAccess(false)} width={660} height={Math.min(820, window.innerHeight - 80)}>diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swiftindex 1f6494ba..e17bd2e8 100644--- a/apps/ios/App/CodyncApp.swift+++ b/apps/ios/App/CodyncApp.swift@@ -17,9 +17,6 @@ struct CodyncApp: App {@State private var launching = !AppStore.shared.accounts.computers.isEmpty/// nil until this iPhone answers "Help improve Codync".@AppStorage(Analytics.enabledKey) private var analyticsEnabled: Bool?- /// Setup finished during this launch: a yes to analytics also reports `onboarding_completed`.- @State private var onboardedNow = false-init() {// A tapped widget bot arrives as an intent, not a URL.OpenBotIntent.open = { AppStore.shared.open($0) }@@ -52,11 +49,15 @@ struct CodyncApp: App {// Asked once per iPhone after setup, once the splash and the account sheet are gone..codyncDialog("Help improve Codync", isPresented: Binding(get: { onboardingCompleted && analyticsEnabled == nil && !launching && !app.account.showSwitcher },- set: { shown in if !shown && analyticsEnabled == nil { Analytics.shared.setEnabled(false) } }+ // Closing without choosing is a no. The dialog closes before a button's action+ // runs, so this waits for it: a yes must not first drop the waiting events.+ set: { shown in+ guard !shown else { return }+ Task { @MainActor in if Analytics.shared.isEnabled == nil { Analytics.shared.setEnabled(false) } }+ }), message: Self.analyticsQuestion, cancel: "Don't share", inPlace: true) {[DialogAction("Share usage") {Analytics.shared.setEnabled(true)- if onboardedNow { Analytics.shared.capture(.onboardingCompleted) }}]}.onChange(of: app.account.userID, initial: true) { _, userID in@@ -70,7 +71,8 @@ struct CodyncApp: App {}}.onOpenURL { url in app.open(url) }- .onChange(of: onboardingCompleted) { _, done in if done { onboardedNow = true } }+ // Waits for the analytics answer, which is asked right after setup.+ .onChange(of: onboardingCompleted) { _, done in if done { Analytics.shared.capture(.onboardingCompleted) } }.onChange(of: scenePhase, initial: true) { _, phase inswitch phase {case .active: Analytics.shared.becameActive()@@ -216,7 +218,7 @@ final class AppStore {func pair(_ pairing: Pairing) async throws -> Computer {let computer = try await accounts.pair(pairing, deviceName: UIDevice.current.name, platform: "ios")- Analytics.shared.capture(.computerPaired)+ Analytics.shared.capture(.computerPaired, ["via": "qr"])return computer}diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swiftindex db656e8d..0a4ada5f 100644--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift@@ -69,27 +69,31 @@ public final class Analytics {/// nil until this iPhone answers the question.public var isEnabled: Bool? { defaults.object(forKey: Self.enabledKey) as? Bool }- /// Turning it off (or back to "not asked") drops everything not yet sent.+ /// A yes sends what waited for the answer; turning it off (or back to "not asked") drops+ /// everything not yet sent.public func setEnabled(_ enabled: Bool?) {defaults.set(enabled, forKey: Self.enabledKey)- guard enabled != true else { return }+ guard enabled != true else { return flush() }pending = []timer?.cancel()timer = nil}- public func capture(_ event: AnalyticsEvent) {- guard isEnabled == true else { return }+ /// Until this iPhone answers, events wait in memory (setup and pairing come before the+ /// question) and leave only after a yes. `properties` are public names, never content.+ public func capture(_ event: AnalyticsEvent, _ properties: [String: String] = [:]) {+ guard isEnabled != false else { return }+ let extra = properties.mapValues(Value.string)if let user = userID() {var identified = defaults.stringArray(forKey: Self.identifiedKey) ?? []- if !identified.contains(user) {+ if isEnabled == true, !identified.contains(user) {enqueue("$identify", user, ["$anon_distinct_id": .string(installID)])identified.append(user)defaults.set(identified, forKey: Self.identifiedKey)}- enqueue(event.rawValue, user, [:])+ enqueue(event.rawValue, user, extra)} else {- enqueue(event.rawValue, installID, [:])+ enqueue(event.rawValue, installID, extra)}}@@ -148,10 +152,11 @@ public final class Analytics {static let common: [String: Value] = {let os = ProcessInfo.processInfo.operatingSystemVersion+ // The Codync Dev app is a release build too: its environment, not DEBUG, says which.#if DEBUGlet env = "dev"#else- let env = "main"+ let env = AppEnvironment.current == .main ? "main" : "dev"#endifreturn ["$lib": .string("codync-ios"),diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swiftindex c1d680b0..6168c5ab 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift@@ -265,6 +265,7 @@ public final class AccountStore {cloud: cloud.baseURL, device: target.device)save(computer)open(computer)+ Analytics.shared.capture(.computerPaired, ["via": "account"])await refreshCloud()returncase .denied, .expired, .cancelled:diff --git a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swiftindex 4d43d04e..9661c9e4 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift@@ -7,17 +7,19 @@ import Testinglet defaults = try #require(UserDefaults(suiteName: "AnalyticsTests-\(UUID())"))let analytics = Analytics(defaults: defaults) { _ in false }- // Not asked yet, then declined: nothing recorded.+ // Not asked yet: held until the answer. Declined: dropped, and nothing more recorded.analytics.capture(.appOpened)+ #expect(analytics.pending.map(\.event) == ["app_opened"])analytics.setEnabled(false)analytics.capture(.appOpened)#expect(analytics.pending.isEmpty)// Anonymous: the install ID, no person profile, the common properties.analytics.setEnabled(true)- analytics.capture(.computerPaired)+ analytics.capture(.computerPaired, ["via": "qr"])let anon = try #require(analytics.pending.first)#expect(anon.event == "computer_paired")+ #expect(anon.properties["via"] == .string("qr"))#expect(anon.properties["$process_person_profile"] == .bool(false))#expect(anon.properties["$lib"] == .string("codync-ios"))#expect(anon.properties["$os"] == .string("iOS"))diff --git a/docs/features/analytics.md b/docs/features/analytics.mdindex 5552b5c8..491baa5d 100644--- a/docs/features/analytics.md+++ b/docs/features/analytics.md@@ -22,17 +22,59 @@ Settings anytime. The public promise lives in `web/app/privacy/page.tsx`: keep i## Where events come from- **Host** (`host/src/analytics.rs`): `api::dispatch` maps successful API calls to events- (`analytics::observe`), so every client is covered once: `bot_created`, `bot_updated`,+ (`analytics::observe_call`), so every client is covered once: `bot_created`, `bot_updated`,`bots_reordered`, `bot_deleted`, `message_sent`, `turn_stopped`, `session_reset`, `permission_answered`,`routine_saved`, `routine_deleted`, `routine_run`, `voice_call_finished`,- `remote_screen_opened`, `connector_installed`, `skill_installed`. `client` is `local`- (desktop app, terminal UI) or `remote` (phones). Batches go to `/batch/` every 30 s.-- **Desktop and terminal UI** report app-level events through the loopback-only `track`- method (`app_opened`, `onboarding_completed`, `signed_in`, `signed_out`) and set consent- with `setAnalytics`; `hello` carries `analytics: true | false | null`.+ `remote_screen_opened`, `connector_installed`, `skill_installed`. A resent message (same+ `clientNonce`, e.g. a phone replaying after a reconnect) is not counted again. Bot actors+ report `turn_finished` when an agent's turn ends. `client` is `local` (desktop app, terminal UI)+ or `remote` (phones). Each event carries its own `timestamp` and `uuid` (a resent batch counts+ once) and the computer's `host_id`; batches go to `/batch/` every 30 s and once more when the+ host stops.+- **Desktop** reports app-level events through the loopback-only `track` method+ (`app_opened`, `onboarding_completed` when the welcome screen is finished, `signed_in`,+ `signed_out`) and sets consent with `setAnalytics`; `hello` carries `analytics: true | false | null`.+ The **terminal UI** reports only `app_opened` (it has no welcome screen or sign-in).- **iPhone** (`CodyncKit` analytics client, no SDK) sends its own app-level events(`app_opened`, `onboarding_completed`, `computer_paired`, `signed_in`, `signed_out`,`voice_call_started`) straight to PostHog. Widgets and the notification extension never send.+- **Before the answer**: setup and pairing come before the question, so every client holds+ events in memory until the device answers; a yes sends them, a no drops them. Nothing leaves+ the device before a yes.++## Event properties++Besides `env`, `app_version`, `$os`, `$lib`:++| Event | Properties |+|---|---|+| `bot_created` | `kind` (`bot`/`group`), `agent`, `model` or `members` (count) |+| `message_sent` | `kind`, `agent`, `in_thread`, `attachments` (count) |+| `turn_finished` | `agent`, `outcome` (`done`/`stopped`/`failed`/`incomplete`), `stop_reason` (ACP's, else `other`), `source` (`user`/`routine`/`group`/`bot`), `seconds` |+| `voice_call_finished` | `seconds` |+| `connector_installed` | `connector` (catalog name or `custom`) |+| `skill_installed` | `custom` |+| `computer_paired` | `via` (`qr`/`account`) |+| every host event | `client` (`local`/`remote`), `host_id`, `arch` |++## Metrics++Shared filters: `env = 'main'`, internal accounts excluded, UTC days. A *user* is a PostHog+person: the account when signed in, otherwise one install, so an anonymous iPhone and an+anonymous computer are two users until both sign in. Messages are recorded by the computer,+so an anonymous iPhone's chats count for its computer.++| Metric | Definition |+|---|---|+| Active user (DAU/WAU/MAU) | Sent ≥1 `message_sent` in the period. Any event at all counts as *present*, not active (`app_opened` on the iPhone fires on every return to the foreground). |+| New user | First event of any kind in the period (the first event after the device said yes, not the install). |+| Activated | Sent ≥1 message from a phone (`message_sent`, `client = remote`) within 7 days of first seen. In the first week of data, 4 of 5 such users came back after 24 h and none of the 6 computer-only ones did. |+| Successful turn rate | `turn_finished` with `outcome = done` ÷ all `turn_finished` with `source = user`, per agent and per `$os`. |+| Frustration rate | (`turn_stopped` + `session_reset`) ÷ `message_sent`, per `$os`. |+| Retained (D1, D7) | Active again on day 1 / any of days 7–13 after their first active day (PostHog retention, `message_sent` both ways). |+| Power user | Active on ≥4 of the last 7 days (stickiness). |+| Feature adoption | Share of WAU with ≥1 of: `voice_call_finished`, `remote_screen_opened`, `connector_installed`, `routine_saved`, `bot_created` with `kind = group`. |+| Up to date | Share of computers active in the period whose last `app_version` is the latest release. |## Askingdiff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex 51264ee2..e937096d 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -228,6 +228,9 @@ impl Actor {}pub(super) fn start_failed(&mut self, e: &anyhow::Error) {+ if self.turn.is_some() {+ self.report_turn(false, true, "start_failed");+ }self.finish_routine(crate::routines::Status::Failed, Some(format!("Could not start routine: {e:#}")), None);self.complete_request(Err(anyhow!("couldn't start recipient: {e:#}")), false);self.complete_group(Err(anyhow!("couldn't start: {e:#}")));diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 0ad7086c..6717d0e6 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -2,6 +2,7 @@use super::{Actor, Done, NoticeStyle, Queued, Seg};use crate::agent::acp::{self, Incoming};+use crate::analytics::{self, TurnOutcome, TurnSource};use crate::chat::context::{self, Snapshot};use crate::chat::memory;use crate::hub::BotStatus;@@ -245,6 +246,7 @@ impl Actor {_ => {}}let failed = done.is_err() && !self.stop_requested;+ self.report_turn(stopped, failed, &stop_reason);let reply = if stopped {Err(anyhow!("recipient was stopped; partial work may have happened"))} else if stop_reason != "end_turn" {@@ -326,6 +328,32 @@ impl Actor {}}+impl Actor {+ /// `turn_finished`, while the turn's start time is still in the runtime.+ pub(super) fn report_turn(&self, stopped: bool, failed: bool, stop_reason: &str) {+ let outcome = if stopped {+ TurnOutcome::Stopped+ } else if failed {+ TurnOutcome::Failed+ } else if stop_reason == "end_turn" {+ TurnOutcome::Done+ } else {+ TurnOutcome::Incomplete+ };+ let source = if self.active_routine.is_some() {+ TurnSource::Routine+ } else if self.active_group.is_some() {+ TurnSource::Group+ } else if self.active_request.is_some() {+ TurnSource::Bot+ } else {+ TurnSource::User+ };+ let started = self.hub.runtime(&self.id()).started_at.unwrap_or_else(now_ms);+ analytics::turn_finished(&self.hub, &self.cfg.backend, outcome, stop_reason, source, now_ms() - started);+ }+}+/// A finished turn alerts once the user's work is done: not while their next message/// is already queued. A turn that ended short of `end_turn` always reports the failure.fn turn_alert(failed: bool, stop_reason: &str, more: bool) -> Option<AlertKind> {diff --git a/host/src/analytics.rs b/host/src/analytics.rsindex 49b6cb13..38af12b4 100644--- a/host/src/analytics.rs+++ b/host/src/analytics.rs@@ -12,7 +12,7 @@ use serde::Deserialize;use serde_json::{Map, Value, json};use std::sync::{Arc, Mutex};use std::time::Duration;-use tokio::sync::mpsc;+use tokio::sync::{mpsc, oneshot};const KV_ENABLED: &str = "analytics_enabled";/// The account the install id was last merged into (one `$identify` per account).@@ -38,6 +38,7 @@ pub enum Event {BotDeleted,MessageSent,TurnStopped,+ TurnFinished,SessionReset,PermissionAnswered,RoutineSaved,@@ -62,6 +63,7 @@ impl Event {Self::BotDeleted => "bot_deleted",Self::MessageSent => "message_sent",Self::TurnStopped => "turn_stopped",+ Self::TurnFinished => "turn_finished",Self::SessionReset => "session_reset",Self::PermissionAnswered => "permission_answered",Self::RoutineSaved => "routine_saved",@@ -83,8 +85,14 @@ impl Event {pub struct Analytics {/// `None` until the owner has chosen.enabled: Mutex<Option<bool>>,- tx: mpsc::UnboundedSender<Value>,- rx: Mutex<Option<mpsc::UnboundedReceiver<Value>>>,+ tx: mpsc::UnboundedSender<Msg>,+ rx: Mutex<Option<mpsc::UnboundedReceiver<Msg>>>,+}++enum Msg {+ Event(Value),+ /// Send what's queued now and answer when done.+ Flush(oneshot::Sender<()>),}impl Analytics {@@ -108,10 +116,6 @@ impl Analytics {*self.enabled.locked() = Some(on);Ok(())}-- fn enabled(&self) -> bool {- self.state() == Some(true)- }}/// `track`: an event the computer's own app reports (app opened, signed in, …).@@ -174,14 +178,84 @@ pub fn observe(caller: &Caller, method: &str, b: &Value) -> Option<(Event, Map<SSome((event, p))}-/// Queues one event when the owner said yes. Signed in to a Codync account, events are+/// How an agent's turn ended (`turn_finished`).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TurnOutcome {+ /// `end_turn`: the agent finished.+ Done,+ /// The user stopped it.+ Stopped,+ /// The agent process or connection failed.+ Failed,+ /// It ended short of `end_turn` (output or step limit, refusal).+ Incomplete,+}++/// What started the turn.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TurnSource {+ User,+ Routine,+ Group,+ Bot,+}++/// `turn_finished`: the agent, how the turn ended and how long it ran; never its text or error.+pub fn turn_finished(hub: &Hub, agent: &str, outcome: TurnOutcome, stop_reason: &str, source: TurnSource, ms: i64) {+ let outcome = match outcome {+ TurnOutcome::Done => "done",+ TurnOutcome::Stopped => "stopped",+ TurnOutcome::Failed => "failed",+ TurnOutcome::Incomplete => "incomplete",+ };+ // ACP's stop reasons plus ours; anything else an adapter invents is just `other`.+ let stop_reason = match stop_reason {+ "end_turn" | "cancelled" | "max_tokens" | "max_turn_requests" | "refusal" | "error" | "start_failed" => {+ stop_reason+ }+ _ => "other",+ };+ let source = match source {+ TurnSource::User => "user",+ TurnSource::Routine => "routine",+ TurnSource::Group => "group",+ TurnSource::Bot => "bot",+ };+ let p = json!({"agent": agent, "outcome": outcome, "stop_reason": stop_reason, "source": source, "seconds": ms.max(0) / 1000});+ capture(hub, Event::TurnFinished, p.as_object().cloned().unwrap_or_default());+}++/// `observe` plus what only the store knows: a resent message (same `clientNonce`) is+/// not a new one, and a message names its bot's agent.+pub fn observe_call(hub: &Hub, caller: &Caller, method: &str, b: &Value) -> Option<(Event, Map<String, Value>)> {+ let (event, mut p) = observe(caller, method, b)?;+ if event == Event::MessageSent {+ let bot = b["botId"].as_str().unwrap_or_default();+ let nonce = b["clientNonce"].as_str().unwrap_or_default();+ if !nonce.is_empty() && hub.store.find_by_nonce(bot, nonce).is_some() {+ return None;+ }+ if let Ok(Some(row)) = hub.store.bot(bot) {+ p.insert("kind".into(), (if row.config.is_group() { "group" } else { "bot" }).into());+ if !row.config.is_group() {+ p.insert("agent".into(), row.config.backend.into());+ }+ }+ }+ Some((event, p))+}++/// Queues one event unless the owner said no. Until they answer, events wait in memory+/// and leave only after a yes (see `start`). Signed in to a Codync account, events are/// linked to that account; otherwise to this install's random id, with no person profile.pub fn capture(hub: &Hub, event: Event, mut properties: Map<String, Value>) {- if !hub.analytics.enabled() {+ let consent = hub.analytics.state();+ if consent == Some(false) {return;}let account = hub.cloud.status().owner.map(|o| o.user_id);- if let Some(user) = &account+ if consent == Some(true)+ && let Some(user) = &account&& hub.store.kv_get(KV_IDENTIFIED).as_deref() != Some(user.as_str()){// Merges this install's earlier, anonymous events into the account.@@ -203,11 +277,21 @@ fn queue(hub: &Hub, event: &str, distinct_id: &str, mut properties: Map<String,("$os".into(), std::env::consts::OS.into()),("arch".into(), std::env::consts::ARCH.into()),("$geoip_disable".into(), true.into()),+ // Joins this computer's events across accounts and with its phones' `computer_paired`.+ ("host_id".into(), hub.host_id.clone().into()),]);- let _ = hub.analytics.tx.send(json!({"event": event, "distinct_id": distinct_id, "properties": properties}));+ let _ = hub.analytics.tx.send(Msg::Event(json!({+ "event": event,+ "distinct_id": distinct_id,+ // When it happened, not when its batch left; the uuid makes a resent batch count once.+ "timestamp": chrono::Utc::now().to_rfc3339(),+ "uuid": uuid::Uuid::new_v4().to_string(),+ "properties": properties,+ })));}-/// Sends queued events in batches every `FLUSH_EVERY`; turning analytics off drops them.+/// Sends queued events in batches every `FLUSH_EVERY`; until the owner answers they wait,+/// and a no drops them.pub fn start(hub: &Arc<Hub>) {let Some(mut rx) = hub.analytics.rx.locked().take() else { return };let hub = hub.clone();@@ -216,16 +300,15 @@ pub fn start(hub: &Arc<Hub>) {let mut tick = tokio::time::interval(FLUSH_EVERY);loop {tokio::select! {- event = rx.recv() => match event {- Some(e) => pending.push(e),+ msg = rx.recv() => match msg {+ Some(Msg::Event(e)) => pending.push(e),+ Some(Msg::Flush(done)) => {+ flush(&hub, &mut pending).await;+ let _ = done.send(());+ }None => return,},- _ = tick.tick() => {- let sent = hub.analytics.enabled() && !pending.is_empty() && send(&pending).await;- if sent || !hub.analytics.enabled() {- pending.clear();- }- }+ _ = tick.tick() => flush(&hub, &mut pending).await,}if pending.len() > MAX_PENDING {pending.drain(..pending.len() - MAX_PENDING);@@ -234,6 +317,22 @@ pub fn start(hub: &Arc<Hub>) {});}+async fn flush(hub: &Hub, pending: &mut Vec<Value>) {+ let consent = hub.analytics.state();+ let sent = consent == Some(true) && !pending.is_empty() && send(pending).await;+ if sent || consent == Some(false) {+ pending.clear();+ }+}++/// Sends what's queued before the host exits, so a restart or update loses nothing.+pub async fn flush_before_exit(hub: &Hub) {+ let (tx, rx) = oneshot::channel();+ if hub.analytics.tx.send(Msg::Flush(tx)).is_ok() {+ let _ = tokio::time::timeout(Duration::from_secs(3), rx).await;+ }+}+async fn send(batch: &[Value]) -> bool {let body = json!({"api_key": TOKEN, "batch": batch});match crate::http().post(BATCH_URL).json(&body).timeout(Duration::from_secs(15)).send().await {@@ -268,6 +367,32 @@ mod tests {assert!(observe(&Caller::Local, "history", &json!({})).is_none());}+ #[tokio::test]+ async fn a_resent_message_counts_once_and_names_its_agent() {+ 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 hub = Hub::new(+ store,+ "h".into(),+ crate::remote::identity::Identity::load_or_create(&dir).unwrap(),+ "t".into(),+ 0,+ );+ let cfg = serde_json::from_value(json!({"id": "b1", "name": "b", "backend": "codex", "cwd": "/tmp"})).unwrap();+ hub.store.save_bot(&cfg).unwrap();+ let send = json!({"botId": "b1", "text": "hi", "clientNonce": "n1"});++ let (_, p) = observe_call(&hub, &Caller::Local, "send", &send).expect("a new message is tracked");+ assert_eq!((p["agent"].as_str(), p["kind"].as_str()), (Some("codex"), Some("bot")));+ let lane = crate::store::Lane::main("b1");+ hub.store+ .insert_entry(&lane, crate::store::EntryKind::User, 1, &json!({"text": "hi", "clientNonce": "n1"}))+ .unwrap();+ assert!(observe_call(&hub, &Caller::Local, "send", &send).is_none(), "a replay is the same message");+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn only_app_events_can_be_tracked_directly() {assert!(Event::deserialize(&json!("app_opened")).is_ok_and(Event::client_reported));diff --git a/host/src/api/mod.rs b/host/src/api/mod.rsindex 4807d514..0dc3362b 100644--- a/host/src/api/mod.rs+++ b/host/src/api/mod.rs@@ -56,7 +56,7 @@ fn str_arg<'a>(b: &'a Value, k: &str) -> Result<&'a str> {/// Runs one API method for `caller` (permissions per spec §6.6).pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -> Result<Value> {devices::permit(caller, method)?;- let observed = crate::analytics::observe(caller, method, &b);+ let observed = crate::analytics::observe_call(hub, caller, method, &b);let result = route(hub, caller, method, b).await;if result.is_ok()&& let Some((event, properties)) = observeddiff --git a/host/src/main.rs b/host/src/main.rsindex 59e81626..6ff00d45 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -533,6 +533,7 @@ async fn serve(bind: &str, port: u16) -> Result<()> {() = shutdown_signal() => {},}hub.shutdown().await;+ analytics::flush_before_exit(&hub).await;tracing::info!("codync-host stopped");Ok(())}