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.

feat(desktop): count every onboarding step, even before the host is up

leepokai330723521557
diff --git a/apps/desktop/src/main/account.ts b/apps/desktop/src/main/account.ts
index f0825319..1b17a29b 100644
--- a/apps/desktop/src/main/account.ts
+++ b/apps/desktop/src/main/account.ts
@@ -2,8 +2,9 @@ import { EventEmitter } from 'node:events'
import { promises as fs } from 'node:fs'
import { join } from 'node:path'
import { app, ipcMain, safeStorage, type BrowserWindow } from 'electron'
+import type { SignInFailure, SignInProvider } from '../shared/analytics'
import type { AccountState } from '../shared/ipc'
-import { authenticate } from './auth'
+import { authenticate, AuthenticationEnded } from './auth'
import { buildConfig, identity } from './environment'
/**
@@ -103,7 +104,7 @@ export class AccountService extends EventEmitter {
register(windows: () => BrowserWindow[]) {
ipcMain.handle('account:state', () => this.state)
- ipcMain.handle('account:signIn', (_e, provider: 'apple' | 'google') => this.signIn(provider))
+ ipcMain.handle('account:signIn', (_e, provider: SignInProvider) => this.signIn(provider))
ipcMain.handle('account:signOut', () => this.signOut())
ipcMain.handle('account:token', () => this.sessionToken())
this.on('change', () => {
@@ -186,10 +187,15 @@ export class AccountService extends EventEmitter {
this.applyClient(client)
}
- async signIn(provider: 'apple' | 'google') {
- if (this.state.busy) return
- if (!this.base) return this.set({ error: "Sign-in setup isn't finished yet. You can continue using local pairing." })
+ /** Why it ended without an account (`sign_in_failed`); null once signed in. */
+ async signIn(provider: SignInProvider): Promise<SignInFailure | null> {
+ if (this.state.busy) return null
+ if (!this.base) {
+ this.set({ error: "Sign-in setup isn't finished yet. You can continue using local pairing." })
+ return 'error'
+ }
const name = provider === 'apple' ? 'Apple' : 'Google'
+ let failure: SignInFailure | null = null
this.set({ busy: true, error: null })
try {
const strategy = `oauth_${provider}`
@@ -204,19 +210,27 @@ export class AccountService extends EventEmitter {
if (!nonce && transferable) {
// A new account: Clerk's transfer flow turns the sign-in into a sign-up.
const signUp = await this.request<{ status: string }>('POST', '/v1/client/sign_ups', { transfer: true })
- if (signUp.status !== 'complete') this.set({ error: `${name} sign-up needs additional account information. Your account is not signed in yet.` })
+ if (signUp.status !== 'complete') {
+ failure = 'verification'
+ this.set({ error: `${name} sign-up needs additional account information. Your account is not signed in yet.` })
+ }
} else if (signIn.status !== 'complete') {
const error = signIn.first_factor_verification?.error
if (error) throw new ClerkError(0, error.long_message ?? error.message ?? 'Sign-in failed.')
+ failure = 'verification'
this.set({ error: `${name} sign-in needs additional verification. Your account is not signed in yet.` })
}
await this.refreshClient()
} catch (error) {
- const message = error instanceof Error ? error.message : ''
- if (!/timed out|Another sign-in/.test(message)) this.set({ error: "Couldn't sign in. Check your connection and try again." })
+ if (error instanceof AuthenticationEnded) failure = error.reason
+ else {
+ failure = 'error'
+ this.set({ error: "Couldn't sign in. Check your connection and try again." })
+ }
} finally {
this.set({ busy: false })
}
+ return failure
}
async signOut() {
diff --git a/apps/desktop/src/main/analytics.ts b/apps/desktop/src/main/analytics.ts
new file mode 100644
index 00000000..f682c311
--- /dev/null
+++ b/apps/desktop/src/main/analytics.ts
@@ -0,0 +1,74 @@
+import { randomUUID } from 'node:crypto'
+import { existsSync } from 'node:fs'
+import { join } from 'node:path'
+import { app } from 'electron'
+import { maySendSetupFailure } from '../shared/analytics'
+import { identity } from './environment'
+import { baseURL, dataDir, prefs } from './host-controller'
+
+// `host_setup_failed`: the one event the desktop app sends to PostHog itself, since without a
+// working host there's nothing to report through. Everything else goes through the host
+// (docs/features/analytics.md).
+
+/** Where getting a working host failed. */
+export type HostSetupStage = 'missing_binary' | 'install' | 'verify' | 'not_responding' | 'environment'
+
+/** Write-only project token, the host's (host/src/analytics.rs): safe to ship in public builds. */
+const TOKEN = 'phc_rQHvxdSFKnMquPfMjmiMhXhM4tqJ5qCYsWuVEoFxCCWX'
+const BATCH_URL = 'https://us.i.posthog.com/batch/'
+/** The host's `$os` names. */
+const OS: Partial<Record<NodeJS.Platform, string>> = { darwin: 'macos', win32: 'windows', linux: 'linux' }
+const ENABLED = 'analyticsEnabled'
+const INSTALL_ID = 'analyticsInstallId'
+
+const reported = new Set<HostSetupStage>()
+
+/** The computer owner's choice, as its host last answered it (`hello`, `setAnalytics`); unknown until then. */
+export function noteAnalyticsSetting(url: string, method: string, value: unknown) {
+ // Not an SSH computer's host: those reach the window through loopback tunnels too.
+ if (url !== baseURL) return
+ const answer = value as { analytics?: unknown; enabled?: unknown } | null
+ let on: unknown
+ if (method === 'hello') on = answer?.analytics
+ else if (method === 'setAnalytics') on = answer?.enabled
+ if (typeof on === 'boolean' && prefs.get(ENABLED) !== on) prefs.set(ENABLED, on)
+}
+
+/** Once per stage per launch; never from a development run, nor when the owner may have turned analytics off. */
+export function reportHostSetupFailure(stage: HostSetupStage) {
+ if (!app.isPackaged || reported.has(stage)) return
+ if (!maySendSetupFailure(prefs.get(ENABLED), existsSync(join(dataDir, 'codync.db')))) return
+ reported.add(stage)
+ const event = {
+ event: 'host_setup_failed',
+ distinct_id: installId(),
+ timestamp: new Date().toISOString(),
+ uuid: randomUUID(),
+ properties: {
+ $lib: 'codync-desktop',
+ app_version: app.getVersion(),
+ env: identity.environment,
+ $os: OS[process.platform] ?? process.platform,
+ $process_person_profile: true,
+ stage,
+ },
+ }
+ void fetch(BATCH_URL, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ api_key: TOKEN, batch: [event] }),
+ signal: AbortSignal.timeout(10_000),
+ }).then(
+ (res) => { if (!res.ok) console.warn(`host_setup_failed: PostHog answered ${res.status}`) },
+ (error: unknown) => console.warn('host_setup_failed not sent', error),
+ )
+}
+
+/** A random id for this install, kept in the app's preferences. */
+function installId() {
+ const saved = prefs.get(INSTALL_ID)
+ if (typeof saved === 'string') return saved
+ const id = randomUUID()
+ prefs.set(INSTALL_ID, id)
+ return id
+}
diff --git a/apps/desktop/src/main/auth.ts b/apps/desktop/src/main/auth.ts
index 9eb23eeb..ae743bcc 100644
--- a/apps/desktop/src/main/auth.ts
+++ b/apps/desktop/src/main/auth.ts
@@ -15,6 +15,13 @@ interface Pending {
let pending: Pending | null = null
+/** The browser never came back: another sign-in took its place, or it ran out of time. */
+export class AuthenticationEnded extends Error {
+ constructor(readonly reason: 'cancelled' | 'timeout', message: string) {
+ super(message)
+ }
+}
+
export function registerSchemes() {
for (const scheme of SCHEMES) {
if (process.defaultApp && process.argv[1]) app.setAsDefaultProtocolClient(scheme, process.execPath, [process.argv[1]])
@@ -44,7 +51,7 @@ export function urlFromArgv(argv: string[]) {
/** Opens `url` in the browser and waits (up to 10 minutes) for the return on `scheme`. */
export function authenticate(url: string, scheme: string): Promise<string> {
if (!/^https:\/\//.test(url)) return Promise.reject(new Error('Sign-in needs an https address.'))
- pending?.reject(new Error('Another sign-in started.'))
+ pending?.reject(new AuthenticationEnded('cancelled', 'Another sign-in started.'))
return new Promise((resolve, reject) => {
pending = {
scheme,
@@ -52,7 +59,7 @@ export function authenticate(url: string, scheme: string): Promise<string> {
reject,
timer: setTimeout(() => {
pending = null
- reject(new Error('Sign-in timed out.'))
+ reject(new AuthenticationEnded('timeout', 'Sign-in timed out.'))
}, 10 * 60_000),
}
void shell.openExternal(url)
diff --git a/apps/desktop/src/main/host-controller.ts b/apps/desktop/src/main/host-controller.ts
index c3cc6508..7fd2c5c7 100644
--- a/apps/desktop/src/main/host-controller.ts
+++ b/apps/desktop/src/main/host-controller.ts
@@ -9,6 +9,7 @@ import type { HostState, LocalHost } from '../shared/ipc'
import { unregisterScreenAgent } from './screen'
import { identity } from './environment'
import { hostEnvironmentError } from '../shared/environment'
+import type { HostSetupStage } from './analytics'
/** `CODYNC_PORT` / `CODYNC_HOME` point the app at a dev host started with `codync-host serve`. */
export const devPort = process.env.CODYNC_PORT ? Number(process.env.CODYNC_PORT) : null
@@ -72,9 +73,17 @@ function serviceDefinition(): string | null {
const serviceInstalled = () => serviceDefinition() !== null
+/** A failed check of the host binary, and the `host_setup_failed` stage it counts as. */
+class SetupError extends Error {
+ constructor(readonly stage: HostSetupStage, message: string) {
+ super(message)
+ }
+}
+
/**
* Manages the local codync-host (binary, background service, health): bundled with the app,
- * else a Homebrew / cargo install.
+ * else a Homebrew / cargo install. Emits `change`, and `setupFailed` (a `HostSetupStage`) when
+ * it couldn't get a working host.
*/
export class HostController extends EventEmitter {
state: HostState = { kind: 'starting' }
@@ -116,6 +125,11 @@ export class HostController extends EventEmitter {
this.emit('change')
}
+ private setupFailed(stage: HostSetupStage, state: HostState) {
+ this.emit('setupFailed', stage)
+ this.setState(state)
+ }
+
private setLocal(local: LocalHost | null) {
this.local = local
this.emit('change')
@@ -131,7 +145,7 @@ export class HostController extends EventEmitter {
async refresh() {
if (this.preparingForUpdate) return
- if (!this.binary && devPort === null) return this.setState({ kind: 'missingBinary' })
+ if (!this.binary && devPort === null) return this.setupFailed('missing_binary', { kind: 'missingBinary' })
if (devPort === null && prefs.get('hostRestartAfterAppUpdate') === true && serviceInstalled()) return this.install()
if (devPort === null && !serviceInstalled()) {
// The app is the way to run the host: set it up right away, unless the user took it out.
@@ -146,10 +160,10 @@ export class HostController extends EventEmitter {
private async verifyBinary(bin: string) {
const result = await run(bin, ['compat'])
- if (result.status !== 0) throw new Error(result.output || 'Cannot verify the host environment.')
+ if (result.status !== 0) throw new SetupError('verify', result.output || 'Cannot verify the host environment.')
const info = JSON.parse(result.output) as { environment?: string }
const mismatch = hostEnvironmentError(identity.environment, info.environment)
- if (mismatch) throw new Error(mismatch)
+ if (mismatch) throw new SetupError('environment', mismatch)
}
/** A service operation must never invoke the other environment's binary. */
@@ -164,13 +178,14 @@ export class HostController extends EventEmitter {
await this.verifyBinary(bin)
const result = await run(bin, ['install', '--port', String(port)])
if (result.status !== 0) {
- this.setState({ kind: 'failed', message: result.output || 'Install failed' })
+ this.setupFailed('install', { kind: 'failed', message: result.output || 'Install failed' })
} else {
await sleep(1000)
this.connect()
}
} catch (error) {
- this.setState({ kind: 'failed', message: error instanceof Error ? error.message : String(error) })
+ // Only the binary's checks throw here (unreadable `compat` output too).
+ this.setupFailed(error instanceof SetupError ? error.stage : 'verify', { kind: 'failed', message: error instanceof Error ? error.message : String(error) })
} finally {
this.installing = false
}
@@ -271,7 +286,7 @@ export class HostController extends EventEmitter {
if (devPort === null && prefs.get('hostRestartAfterAppUpdate') === true) prefs.set('hostRestartAfterAppUpdate', false)
} else {
this.failures++
- if (this.failures > 5) this.setState({ kind: 'failed', message: "The host isn't responding. See the log for details." })
+ if (this.failures > 5) this.setupFailed('not_responding', { kind: 'failed', message: "The host isn't responding. See the log for details." })
else if (this.state.kind !== 'running') this.setState({ kind: 'starting' })
}
if (generation === this.generation) this.loop = setTimeout(tick, 5000)
@@ -289,7 +304,7 @@ export class HostController extends EventEmitter {
if (!health?.computerId) return false
const mismatch = hostEnvironmentError(identity.environment, health.environment)
if (mismatch) {
- this.setState({ kind: 'failed', message: mismatch })
+ this.setupFailed('environment', { kind: 'failed', message: mismatch })
return false
}
const token = await readToken()
diff --git a/apps/desktop/src/main/host-proxy.ts b/apps/desktop/src/main/host-proxy.ts
index 362350f6..e46331b0 100644
--- a/apps/desktop/src/main/host-proxy.ts
+++ b/apps/desktop/src/main/host-proxy.ts
@@ -1,5 +1,6 @@
import { ipcMain, type WebContents } from 'electron'
import type { CallError } from '../shared/ipc'
+import { noteAnalyticsSetting } from './analytics'
// Loopback HTTP + SSE for the renderer. The host has no CORS (it's a loopback API for local
// apps), so requests leave from the main process.
@@ -36,7 +37,10 @@ async function call(baseURL: string, token: string, method: string, body: unknow
} catch {}
throw { status: res.status, message } satisfies CallError
}
- return text ? JSON.parse(text) : {}
+ const value: unknown = text ? JSON.parse(text) : {}
+ // The main process keeps the analytics setting for when there's no host (`host_setup_failed`).
+ noteAnalyticsSetting(baseURL, method, value)
+ return value
}
function stream(sender: WebContents, id: string, url: string, token: string) {
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 7f5d88de..d0745e4f 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -20,6 +20,8 @@ import { registerSSH } from './ssh'
import { QuitLifecycle } from './quit-lifecycle'
import { Island } from './island'
import { registerErrorReports } from './error-reports'
+import { reportHostSetupFailure } from './analytics'
+import { launchAtLogin, openedAtLogin, setLaunchAtLogin, updateLoginItem } from './login-item'
/** macOS's user-facing computer name, else the host name. */
function computerName() {
@@ -36,6 +38,7 @@ if (!app.isPackaged && process.env.CODYNC_REMOTE_DEBUG) app.commandLine.appendSw
const host = new HostController()
registerErrorReports(host)
+host.on('setupFailed', reportHostSetupFailure)
const account = new AccountService()
const updates = new Updates(host)
let chat: BrowserWindow | null = null
@@ -58,6 +61,8 @@ function snapshot(): HostSnapshot {
/** The chat window: roster on the left, the conversation on the right (Grok Bot's desktop layout). */
function openChat() {
if (chat) {
+ // Shown again after being hidden (closed to the background): the launch itself is `app_opened`.
+ if (!chat.isVisible() && !chat.webContents.isLoading()) chat.webContents.send('app:command', { kind: 'windowOpened' } satisfies WindowCommand)
chat.show()
chat.focus()
return chat
@@ -148,6 +153,7 @@ function registerIPC(tray: Tray) {
registerFileSaves()
ipcMain.on('app:version', (e) => (e.returnValue = app.getVersion()))
ipcMain.on('app:computerName', (e) => (e.returnValue = computerName()))
+ ipcMain.on('app:openedAtLogin', (e) => (e.returnValue = openedAtLogin()))
ipcMain.on('app:debugOpen', (e) => (e.returnValue = app.isPackaged ? null : (process.env.CODYNC_DEBUG_OPEN ?? null)))
ipcMain.handle('host:snapshot', () => snapshot())
ipcMain.on('host:install', () => void host.install())
@@ -180,11 +186,8 @@ function registerIPC(tray: Tray) {
tray.hostChanged()
return visible
})
- ipcMain.handle('app:launchAtLogin', () => app.getLoginItemSettings().openAtLogin)
- ipcMain.handle('app:setLaunchAtLogin', (_e, on: boolean) => {
- app.setLoginItemSettings({ openAtLogin: on })
- return app.getLoginItemSettings().openAtLogin
- })
+ ipcMain.handle('app:launchAtLogin', () => launchAtLogin())
+ ipcMain.handle('app:setLaunchAtLogin', (_e, on: boolean) => setLaunchAtLogin(on))
ipcMain.handle('app:resetAllData', async () => {
// Tell paired devices first: connected ones see "No access" at once, and the account drops
// this computer instead of keeping an unreachable older copy of it.
@@ -222,6 +225,7 @@ if (!app.requestSingleInstanceLock()) {
// would otherwise show Electron's.
if (isMac && !app.isPackaged) app.dock?.setIcon(join(__dirname, '../../resources/icon.png'))
applyDockVisibility()
+ updateLoginItem()
const island = new Island({ url: rendererURL('island'), preload: join(__dirname, '../preload/index.js'), send, openApp: openChat, changed: () => tray.hostChanged() })
const tray = new Tray({ openChat, openPairing, send, host, updates, island })
updates.on('change', () => tray.hostChanged())
diff --git a/apps/desktop/src/main/login-item.ts b/apps/desktop/src/main/login-item.ts
new file mode 100644
index 00000000..281c8433
--- /dev/null
+++ b/apps/desktop/src/main/login-item.ts
@@ -0,0 +1,25 @@
+import { app } from 'electron'
+
+// Open at login (macOS and Windows; Electron has no login item on Linux). Windows starts the
+// login item with a flag so that launch can tell itself apart; macOS says so itself.
+
+const LOGIN_FLAG = '--opened-at-login'
+const options = process.platform === 'win32' ? { args: [LOGIN_FLAG] } : {}
+
+export const launchAtLogin = () => app.getLoginItemSettings(options).openAtLogin
+
+export function setLaunchAtLogin(on: boolean) {
+ app.setLoginItemSettings({ ...options, openAtLogin: on })
+ return launchAtLogin()
+}
+
+/** This launch came from the login item (`app_opened`'s `at_login`). */
+export const openedAtLogin = () =>
+ process.platform === 'darwin' ? app.getLoginItemSettings().wasOpenedAtLogin : process.argv.includes(LOGIN_FLAG)
+
+/** Windows: a login item registered without the flag gets it, so its sign-in launches count. */
+export function updateLoginItem() {
+ if (process.platform !== 'win32' || launchAtLogin()) return
+ // Quoted: Electron splits its own unquoted path at the first space ("Codync Dev.exe"), so the entry never matches.
+ if (app.getLoginItemSettings({ path: `"${process.execPath}"` }).executableWillLaunchAtLogin) setLaunchAtLogin(true)
+}
diff --git a/apps/desktop/src/main/tray.ts b/apps/desktop/src/main/tray.ts
index 28a28902..2a3935a5 100644
--- a/apps/desktop/src/main/tray.ts
+++ b/apps/desktop/src/main/tray.ts
@@ -8,6 +8,7 @@ import { setShowInDock, showInDock } from './dock'
import { identity } from './environment'
import { islandSupported, type Island } from './island'
import { islandLabel } from '../shared/island'
+import { launchAtLogin, setLaunchAtLogin } from './login-item'
interface Deps {
openChat: () => unknown
@@ -25,7 +26,7 @@ const TEXT_SIZES = [11, 12, 13, 14, 15, 16, 18]
export class Tray {
private tray: ElectronTray
private summary: TraySummary | null = null
- private launchAtLogin = app.getLoginItemSettings().openAtLogin
+ private launchAtLogin = launchAtLogin()
constructor(private deps: Deps) {
this.tray = new ElectronTray(this.icon(false))
@@ -200,8 +201,7 @@ export class Tray {
type: 'checkbox',
checked: this.launchAtLogin,
click: () => {
- app.setLoginItemSettings({ openAtLogin: !this.launchAtLogin })
- this.launchAtLogin = app.getLoginItemSettings().openAtLogin
+ this.launchAtLogin = setLaunchAtLogin(!this.launchAtLogin)
this.rebuild()
},
},
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 77ed6144..8b4eb844 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -25,6 +25,7 @@ const bridge: CodyncBridge = {
hostPort: ipcRenderer.sendSync('app:hostPort') as number,
appVersion: ipcRenderer.sendSync('app:version') as string,
computerName: ipcRenderer.sendSync('app:computerName') as string,
+ openedAtLogin: ipcRenderer.sendSync('app:openedAtLogin') as boolean,
debugOpen: ipcRenderer.sendSync('app:debugOpen') as string | null,
host: {
snapshot: () => ipcRenderer.invoke('host:snapshot') as Promise<HostSnapshot>,
diff --git a/apps/desktop/src/renderer/demo/bridge.ts b/apps/desktop/src/renderer/demo/bridge.ts
index 538c4ebe..d4c93f5e 100644
--- a/apps/desktop/src/renderer/demo/bridge.ts
+++ b/apps/desktop/src/renderer/demo/bridge.ts
@@ -29,6 +29,7 @@ const bridge: CodyncBridge = {
hostPort: 19222,
appVersion: version,
computerName: HOST_NAME,
+ openedAtLogin: false,
// Opens the group at launch, like the website's screenshot.
debugOpen: 'Ship room',
host: {
diff --git a/apps/desktop/src/renderer/lib/analytics-queue.test.ts b/apps/desktop/src/renderer/lib/analytics-queue.test.ts
new file mode 100644
index 00000000..78cc0368
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/analytics-queue.test.ts
@@ -0,0 +1,52 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { trackBody, type AnalyticsEvent } from '../../shared/analytics.ts'
+import { AnalyticsQueue } from './analytics-queue.ts'
+
+const settle = () => new Promise((r) => setImmediate(r))
+
+test('events from before the host answers go out once it does, in order', async () => {
+ const queue = new AnalyticsQueue()
+ const sent: AnalyticsEvent[] = []
+ queue.track({ event: 'app_opened', at_login: false })
+ queue.track({ event: 'onboarding_completed', signed_in: true })
+ await settle()
+ queue.connect(async (e) => void sent.push(e))
+ queue.track({ event: 'screen_viewed', screen: 'chat' })
+ await settle()
+ assert.deepEqual(sent.map((e) => e.event), ['app_opened', 'onboarding_completed', 'screen_viewed'])
+})
+
+test('an unreachable host keeps the event for the next try; a gone host holds them again', async () => {
+ const queue = new AnalyticsQueue()
+ const sent: string[] = []
+ queue.connect(async () => {
+ throw new Error('unreachable')
+ })
+ queue.track({ event: 'window_opened' })
+ await settle()
+ assert.equal(sent.length, 0)
+ queue.connect(async (e) => void sent.push(e.event))
+ await settle()
+ assert.deepEqual(sent, ['window_opened'])
+ queue.connect(null)
+ queue.track({ event: 'signed_out' })
+ await settle()
+ assert.deepEqual(sent, ['window_opened'])
+})
+
+test('only the newest events wait past the limit', async () => {
+ const queue = new AnalyticsQueue(2)
+ const sent: string[] = []
+ for (const link of ['docs', 'issues', 'privacy'] as const) queue.track({ event: 'link_opened', link })
+ queue.connect(async (e) => void sent.push(e.event === 'link_opened' ? e.link : e.event))
+ await settle()
+ assert.deepEqual(sent, ['issues', 'privacy'])
+})
+
+test('track sends the event name and its properties, from the desktop app', () => {
+ assert.deepEqual(trackBody({ event: 'sign_in_failed', provider: 'google', reason: 'timeout' }), {
+ event: 'sign_in_failed', provider: 'google', reason: 'timeout', app: 'desktop',
+ })
+ assert.deepEqual(trackBody({ event: 'window_opened' }), { event: 'window_opened', app: 'desktop' })
+})
diff --git a/apps/desktop/src/renderer/lib/analytics-queue.ts b/apps/desktop/src/renderer/lib/analytics-queue.ts
new file mode 100644
index 00000000..f45359d2
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/analytics-queue.ts
@@ -0,0 +1,47 @@
+import type { AnalyticsEvent } from '@shared/analytics'
+
+/** Sends one event; rejects when the host can't be reached, so the event waits for the next try. */
+export type AnalyticsSender = (event: AnalyticsEvent) => Promise<void>
+
+/**
+ * App-level events held until this computer's host answers, then sent one at a time in the order
+ * they happened. Past `limit` waiting, the oldest go.
+ */
+export class AnalyticsQueue {
+ private pending: AnalyticsEvent[] = []
+ private sender: AnalyticsSender | null = null
+ private sending = false
+ private readonly limit: number
+
+ constructor(limit = 100) {
+ this.limit = limit
+ }
+
+ track(event: AnalyticsEvent) {
+ this.pending.push(event)
+ if (this.pending.length > this.limit) this.pending.shift()
+ void this.flush()
+ }
+
+ /** The host answered (how to reach it), or is gone (null). */
+ connect(sender: AnalyticsSender | null) {
+ this.sender = sender
+ void this.flush()
+ }
+
+ private async flush() {
+ if (this.sending) return
+ this.sending = true
+ try {
+ for (let next = this.pending[0]; next && this.sender; next = this.pending[0]) {
+ await this.sender(next)
+ // Unless the limit already dropped it while it was on its way.
+ if (this.pending[0] === next) this.pending.shift()
+ }
+ } catch {
+ // The host can't be reached: the event stays first in line for the next connect or event.
+ } finally {
+ this.sending = false
+ }
+ }
+}
diff --git a/apps/desktop/src/renderer/store/account.ts b/apps/desktop/src/renderer/store/account.ts
index 200e30fd..2349e102 100644
--- a/apps/desktop/src/renderer/store/account.ts
+++ b/apps/desktop/src/renderer/store/account.ts
@@ -1,6 +1,6 @@
+import type { SignInProvider } from '@shared/analytics'
import { Observable, useModel } from '../lib/observable'
-
-export type SignInProvider = 'apple' | 'google'
+import { analytics } from './analytics'
export interface AccountInfo {
userId: string
@@ -19,6 +19,8 @@ export class AccountSession extends Observable {
errorMessage: string | null = null
user: AccountInfo | null = null
cloudURL: string | null = null
+ /** The last sign-in started here, for `signed_in`. */
+ provider: SignInProvider | null = null
get isSignedIn() {
return this.user !== null
@@ -41,7 +43,10 @@ export class AccountSession extends Observable {
}
async signIn(provider: SignInProvider) {
- await window.codync.account.signIn(provider)
+ this.provider = provider
+ analytics.track({ event: 'sign_in_started', provider })
+ const reason = await window.codync.account.signIn(provider)
+ if (reason) analytics.track({ event: 'sign_in_failed', provider, reason })
}
async signOut() {
diff --git a/apps/desktop/src/renderer/store/analytics.ts b/apps/desktop/src/renderer/store/analytics.ts
new file mode 100644
index 00000000..8cbad90a
--- /dev/null
+++ b/apps/desktop/src/renderer/store/analytics.ts
@@ -0,0 +1,19 @@
+import { useEffect } from 'react'
+import type { Link, Screen } from '@shared/analytics'
+import { AnalyticsQueue } from '../lib/analytics-queue'
+
+/** This window's app-level analytics; `AppModel` connects it to this computer's host once it answers. */
+export const analytics = new AnalyticsQueue()
+
+/** A screen, sheet or tab is shown: once when it appears, and again when `key` changes. */
+export function useScreenViewed(screen: Screen | null, key: unknown = null) {
+ useEffect(() => {
+ if (screen) analytics.track({ event: 'screen_viewed', screen })
+ }, [screen, key])
+}
+
+/** Opens an outbound link in the browser, counted by what it leads to. */
+export function openLink(url: string, link: Link) {
+ analytics.track({ event: 'link_opened', link })
+ window.codync.app.openExternal(url)
+}
diff --git a/apps/desktop/src/renderer/store/app-model.ts b/apps/desktop/src/renderer/store/app-model.ts
index 97eb6404..31ff010e 100644
--- a/apps/desktop/src/renderer/store/app-model.ts
+++ b/apps/desktop/src/renderer/store/app-model.ts
@@ -1,8 +1,10 @@
-import type { HostSnapshot } from '@shared/ipc'
+import { trackBody } from '@shared/analytics'
+import type { HostSnapshot, LocalHost } from '@shared/ipc'
import type { AccessRequest, Bot, Computer } from '@shared/models'
-import { LoopbackTransport } from '../client/host-client'
+import { HostError, LoopbackTransport } from '../client/host-client'
import { Observable } from '../lib/observable'
import { account } from './account'
+import { analytics } from './analytics'
import { BotStore } from './bot-store'
import { CloudModel } from './cloud'
import { DeviceComputerOrder } from './computer-order'
@@ -49,7 +51,6 @@ export class AppModel extends Observable {
screenNeedsApproval = false
screenError: string | null = null
private screenSynced = false
- private opened = false
/** Whether the account was signed in when last seen; null until its state first arrives. */
private signedIn: boolean | null = null
/** Approvals closed with "later"; they come back when the request changes (its code arrives). */
@@ -76,6 +77,11 @@ export class AppModel extends Observable {
async start() {
window.codync.host.onChange((s) => this.setHost(s))
+ if (this.mirrors) {
+ // Once per launch; it goes out when this computer's host first answers.
+ analytics.track({ event: 'app_opened', at_login: window.codync.openedAtLogin })
+ window.codync.app.onCommand((c) => c.kind === 'windowOpened' && analytics.track({ event: 'window_opened' }))
+ }
this.setHost(await window.codync.host.snapshot())
}
@@ -83,6 +89,7 @@ export class AppModel extends Observable {
const old = this.host.local
this.host = snapshot
const local = snapshot.local
+ this.connectAnalytics(local)
if (!this.mirrors) return this.changed()
if (local && (old?.computerId !== local.computerId || old.token !== local.token || !this.stores.has(local.computerId))) {
if (old && old.computerId !== local.computerId) this.detach(old.computerId)
@@ -90,10 +97,7 @@ export class AppModel extends Observable {
const computer: Computer = cached ?? { id: local.computerId, name: 'This computer', signKey: '', urls: [] }
const store = new BotStore(computer, true, () => new LoopbackTransport(local.baseURL, local.token))
this.attach(computer, store)
- store.subscribe(() => {
- this.syncScreen(store)
- this.noteOpened(store)
- })
+ store.subscribe(() => this.syncScreen(store))
} else if (!local && old) {
this.detach(old.computerId)
}
@@ -239,18 +243,26 @@ export class AppModel extends Observable {
})
}
- /** `app_opened` once per launch, when this computer's host first answers. */
- private noteOpened(store: BotStore) {
- if (this.opened || !store.hello) return
- this.opened = true
- store.track('app_opened')
+ /** App-level analytics go out through this computer's host (`track`) once it answers; null holds them. */
+ private connectAnalytics(local: LocalHost | null) {
+ if (!local) return analytics.connect(null)
+ const transport = new LoopbackTransport(local.baseURL, local.token)
+ analytics.connect(async (event) => {
+ try {
+ await transport.call('track', trackBody(event), 10_000)
+ } catch (error) {
+ // Unreachable: kept for the next try. Refused (a host without this event): dropped.
+ if (error instanceof HostError && error.isTransient) throw error
+ console.warn(`track ${event.event} failed`, error)
+ }
+ })
}
/** Sign-in and sign-out, not the state restored at launch. */
private noteAccount() {
if (!account.isReady) return
const now = account.isSignedIn
- if (this.signedIn !== null && now !== this.signedIn) this.local?.track(now ? 'signed_in' : 'signed_out')
+ if (this.signedIn !== null && now !== this.signedIn) analytics.track(now ? { event: 'signed_in', provider: account.provider ?? undefined } : { event: 'signed_out' })
this.signedIn = now
}
diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.ts
index 95ed5b5a..2ebbf8c4 100644
--- a/apps/desktop/src/renderer/store/bot-store.ts
+++ b/apps/desktop/src/renderer/store/bot-store.ts
@@ -1,7 +1,6 @@
import {
isWorking,
needsInput,
- type AnalyticsEvent,
type Bot,
type BotDraft,
type DirListing,
@@ -157,11 +156,6 @@ export class BotStore extends BotSync {
this.changed()
}
- /** 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))
- }
-
/** Toggles the user's reaction; shown at once, then replaced by the host's copy. */
react(entry: Entry, emoji: string) {
const list = this.entries.get(entry.botId)
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 122ee79c..6b03f952 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -10,6 +10,8 @@ import { Text } from '../components/Text'
import { useModels } from '../lib/observable'
import { prefs, stepTextSize, usePref, DEFAULT_TEXT_SIZE } from '../lib/prefs'
import { useApp, StoreContext } from '../store/context'
+import { account } from '../store/account'
+import { analytics } from '../store/analytics'
import { refKey, sameRef, parseRef, type BotRef } from '../store/app-model'
import type { BotStore } from '../store/bot-store'
import { useComputerRoster } from '../store/computer-roster'
@@ -48,6 +50,10 @@ export function ChatWindow() {
useSSHAttachments(app)
const ssh = useSSH()
const showsChat = shouldShowChat(app.host.state.kind, app.computers.length, ssh.state)
+ const finishAccess = (ready: boolean, onboarding: boolean) => {
+ setAccessSetup(ready ? 'ready' : 'later')
+ analytics.track({ event: 'computer_access_finished', ready, onboarding })
+ }
useEffect(
() =>
@@ -103,7 +109,7 @@ export function ChatWindow() {
<Summaries />
{onboarded ? (
accessSetup === null ? (
- <ComputerAccessView onContinue={(ready) => setAccessSetup(ready ? 'ready' : 'later')} />
+ <ComputerAccessView onContinue={(ready) => finishAccess(ready, true)} />
) : showsChat ? (
<ChatSplitView />
) : (
@@ -113,7 +119,7 @@ export function ChatWindow() {
<AccountWelcomeView
onContinue={() => {
setOnboarded(true)
- app.local?.track('onboarding_completed')
+ analytics.track({ event: 'onboarding_completed', signed_in: account.isSignedIn })
}}
/>
)}
@@ -121,7 +127,7 @@ export function ChatWindow() {
{onboarded && accessSetup !== null ? <StarPrompt /> : null}
<Sheet open={showAccess} onClose={() => setShowAccess(false)} width={660} height={Math.min(820, window.innerHeight - 80)}>
<ModalHeader icon="hand.raised" title="Computer access" />
- <ComputerAccessView onContinue={(ready) => { setAccessSetup(ready ? 'ready' : 'later'); setShowAccess(false) }} />
+ <ComputerAccessView onContinue={(ready) => { finishAccess(ready, false); setShowAccess(false) }} />
</Sheet>
<Dialog
open={confirmReset}
diff --git a/apps/desktop/src/renderer/views/PairingWindow.tsx b/apps/desktop/src/renderer/views/PairingWindow.tsx
index b911e2cf..433ac10b 100644
--- a/apps/desktop/src/renderer/views/PairingWindow.tsx
+++ b/apps/desktop/src/renderer/views/PairingWindow.tsx
@@ -5,6 +5,7 @@ import { IconButton, Spinner } from '../components/Controls'
import { HStack, VStack } from '../components/Stack'
import { Text } from '../components/Text'
import { LoopbackTransport } from '../client/host-client'
+import { analytics, useScreenViewed } from '../store/analytics'
import { useApp } from '../store/context'
import './pairing-window.css'
@@ -17,6 +18,7 @@ export function PairingWindow() {
const [cloud, setCloud] = useState<CloudStatus | null>(null)
const [name, setName] = useState('this computer')
const [error, setError] = useState<string | null>(null)
+ useScreenViewed('pairing')
const load = useCallback(async () => {
if (!local) return setError("This computer's host isn't connected.")
@@ -37,10 +39,14 @@ export function PairingWindow() {
}
}, [local])
- // A new code each time "Pair iPhone…" is chosen (the window stays open between uses)…
+ // A new code each time "Pair iPhone…" is chosen (the window stays open between uses, so it's shown again)…
useEffect(() => {
void load()
- return window.codync.app.onCommand((c) => c.kind === 'reviewApprovals' && void load())
+ return window.codync.app.onCommand((c) => {
+ if (c.kind !== 'reviewApprovals') return
+ analytics.track({ event: 'screen_viewed', screen: 'pairing' })
+ void load()
+ })
}, [load])
// …and a fresh one when this code expires while it's on screen.
diff --git a/apps/desktop/src/renderer/views/PanelMenus.tsx b/apps/desktop/src/renderer/views/PanelMenus.tsx
index 119ec79a..368a8026 100644
--- a/apps/desktop/src/renderer/views/PanelMenus.tsx
+++ b/apps/desktop/src/renderer/views/PanelMenus.tsx
@@ -4,7 +4,9 @@ import { Icon } from '../components/Icon'
import type { MenuItem } from '../components/Overlay'
import { HStack, IconSlot, VStack } from '../components/Stack'
import { Text } from '../components/Text'
+import type { Link } from '@shared/analytics'
import { account, useAccount } from '../store/account'
+import { openLink, useScreenViewed } from '../store/analytics'
import googleLogo from '../assets/google.svg'
// The chat window's floating panels: the account menu (with its profile avatar) and the roster's
@@ -50,6 +52,7 @@ export function AccountPanelLayer({ compact, approvals, onDismiss, onUsage, onSe
}) {
const [page, setPage] = useState<'main' | 'support'>('main')
const { user, isBusy, errorMessage } = useAccount()
+ useScreenViewed('account')
const signedIn = user !== null
const auth: PanelItem[] = signedIn
? [{ title: isBusy ? 'Please wait…' : 'Sign out', icon: 'rectangle.portrait.and.arrow.right', disabled: isBusy, action: () => { onDismiss(); void account.signOut() } }]
@@ -57,20 +60,20 @@ export function AccountPanelLayer({ compact, approvals, onDismiss, onUsage, onSe
{ title: 'Continue with Apple', icon: 'apple.logo', disabled: isBusy, action: () => { onDismiss(); void account.signIn('apple') } },
{ title: 'Continue with Google', icon: 'person.crop.circle.badge.plus', image: googleLogo, disabled: isBusy, action: () => { onDismiss(); void account.signIn('google') } },
]
- const open = (url: string) => {
+ const open = (url: string, link: Link) => {
onDismiss()
- window.codync.app.openExternal(url)
+ openLink(url, link)
}
const items: PanelItem[] =
page === 'support'
? [
{ title: 'Support', icon: 'chevron.left', action: () => setPage('main') },
- { title: 'Help & documentation', icon: 'book', chevron: true, action: () => open('https://github.com/leepokai/codync#readme') },
- { title: 'Report an issue', icon: 'bubble.left', chevron: true, action: () => open('https://github.com/leepokai/codync/issues') },
+ { title: 'Help & documentation', icon: 'book', chevron: true, action: () => open('https://github.com/leepokai/codync#readme', 'docs') },
+ { title: 'Report an issue', icon: 'bubble.left', chevron: true, action: () => open('https://github.com/leepokai/codync/issues', 'issues') },
]
: [
{ title: 'Usage', icon: 'gauge.with.dots.needle.33percent', chevron: true, action: onUsage },
- { title: 'Get Codync for mobile', icon: 'iphone', action: () => open('https://apps.apple.com/app/id6760984418') },
+ { title: 'Get Codync for mobile', icon: 'iphone', action: () => open('https://apps.apple.com/app/id6760984418', 'app_store') },
{ title: 'Support', icon: 'book.closed', chevron: true, action: () => setPage('support') },
{ title: 'Settings', icon: 'gearshape', detail: approvals > 0 ? String(approvals) : null, action: onSettings },
...auth,
diff --git a/apps/desktop/src/renderer/views/StarPrompt.tsx b/apps/desktop/src/renderer/views/StarPrompt.tsx
index 0d7fec62..647366e0 100644
--- a/apps/desktop/src/renderer/views/StarPrompt.tsx
+++ b/apps/desktop/src/renderer/views/StarPrompt.tsx
@@ -9,6 +9,7 @@ import { useModel } from '../lib/observable'
import { prefs, usePref } from '../lib/prefs'
import { afterStarAsk, dueStarAsk } from '../lib/star-ask'
import { useApp } from '../store/context'
+import { analytics } from '../store/analytics'
const [OWNER, NAME] = ['leepokai', 'Codync']
const REPO = `https://github.com/${OWNER}/${NAME}`
@@ -38,9 +39,11 @@ export function StarPrompt() {
const open = due !== null && onboarded && !closed && local?.connection.kind === 'online'
const finish = (starred: boolean) => {
- if (closed) return
+ if (closed || !due) return
setClosed(true)
setState(afterStarAsk(state, starred, Date.now()))
+ // Covers the GitHub link too: it opens only on a star.
+ analytics.track({ event: 'star_prompt_answered', ask: due, starred })
if (starred) window.codync.app.openExternal(REPO)
}
diff --git a/apps/desktop/src/renderer/views/bots/MemoryView.tsx b/apps/desktop/src/renderer/views/bots/MemoryView.tsx
index 57015235..8f3b6121 100644
--- a/apps/desktop/src/renderer/views/bots/MemoryView.tsx
+++ b/apps/desktop/src/renderer/views/bots/MemoryView.tsx
@@ -5,6 +5,7 @@ import { Dialog, ModalHeader, Sheet } from '../../components/Overlay'
import { HStack } from '../../components/Stack'
import { useModel } from '../../lib/observable'
import { useStore } from '../../store/context'
+import { useScreenViewed } from '../../store/analytics'
import { MemoryStore, authorLabel, type MemoryEntry } from '../../store/memory-store'
import { FormSheet } from '../marketplace/pieces'
import { relativeTime } from '../thread/chat-items'
@@ -18,6 +19,7 @@ type Section = 'yours' | 'bot' | 'dreams' | 'harness'
export function MemoryCard({ botId }: { botId: string }) {
const host = useStore()
const memory = useModel(useMemo(() => new MemoryStore(botId, () => host.ready()), [botId, host]))
+ useScreenViewed('memory')
const bot = host.bots.get(botId)
const [section, setSection] = useState<Section>('bot')
const [draft, setDraft] = useState<{ id?: number; text: string } | null>(null)
diff --git a/apps/desktop/src/renderer/views/call/CallView.tsx b/apps/desktop/src/renderer/views/call/CallView.tsx
index 73fd4885..5b21b23e 100644
--- a/apps/desktop/src/renderer/views/call/CallView.tsx
+++ b/apps/desktop/src/renderer/views/call/CallView.tsx
@@ -1,3 +1,4 @@
+import type { VoiceCallEngine } from '@shared/analytics'
import { isWorking } from '@shared/models'
import { createContext, useContext, useEffect, useRef, useState } from 'react'
import { BotAvatar } from '../../components/Avatar'
@@ -6,6 +7,7 @@ import { Sheet } from '../../components/Overlay'
import { Text } from '../../components/Text'
import { useModel } from '../../lib/observable'
import { avatarColor, useDark, usePixelRatio, useReduceMotion, withAlpha } from '../../lib/theme'
+import { analytics } from '../../store/analytics'
import { useStore } from '../../store/context'
import { VoiceChatSettingsView } from '../settings/VoiceChatSettingsView'
import { CallOperator } from './call-operator'
@@ -47,6 +49,9 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {
/** When the current cloud engine started, for this month's minutes. */
const cloudStartedAt = useRef<number | null>(null)
const closed = useRef(false)
+ /** What carries the current engine's audio, and whether the call has been counted (once its first engine runs). */
+ const engineName = useRef<VoiceCallEngine>('on_device')
+ const counted = useRef(false)
const bot = store.bots.get(botId)
const color = bot ? avatarColor(bot.avatarColor) : null
@@ -84,6 +89,7 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {
send,
})
cloudStartedAt.current = Date.now()
+ engineName.current = 'cloud'
} else if (provider) {
const model = VoiceSettings.model(provider)
const voice = VoiceSettings.voice(provider)
@@ -92,8 +98,10 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {
? new OpenAIRealtimeEngine(credential(provider, model, voice), op)
: new GeminiLiveEngine(model, voice, credential(provider, model, voice), op)
cloudStartedAt.current = Date.now()
+ engineName.current = provider
} else {
next = new OnDeviceEngine(send)
+ engineName.current = 'on_device'
}
// Picks up the computer's newest models for the next call; this one starts right away.
if (provider) void rememberStatus()
@@ -151,6 +159,10 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {
if (!session) return
onSpeaking(phase === 'speaking')
interrupt.current = phase === 'speaking' ? () => session.interrupt() : null
+ if (session.isActive && !counted.current) {
+ counted.current = true
+ analytics.track({ event: 'voice_call_started', engine: engineName.current })
+ }
// A cloud engine that can't start or drops mid-call hands over to on-device voice.
if (phase === 'failed' && session.provider && onDeviceAvailable()) {
countCloudMinutes()
diff --git a/apps/desktop/src/renderer/views/computer-access/ComputerAccessView.tsx b/apps/desktop/src/renderer/views/computer-access/ComputerAccessView.tsx
index a89c9ea8..f1d31821 100644
--- a/apps/desktop/src/renderer/views/computer-access/ComputerAccessView.tsx
+++ b/apps/desktop/src/renderer/views/computer-access/ComputerAccessView.tsx
@@ -1,6 +1,7 @@
import type { ReactNode } from 'react'
import { Button, IconButton, Spinner } from '../../components/Controls'
import { Icon } from '../../components/Icon'
+import { useScreenViewed } from '../../store/analytics'
import { useComputerAccess } from './use-computer-access'
import appIcon from '../../../../resources/icon.png'
import './computer-access.css'
@@ -8,6 +9,7 @@ import './computer-access.css'
/** Shared by onboarding and Settings. Permission requests remain explicit and local. */
export function ComputerAccessView({ onContinue }: { onContinue?: (ready: boolean) => void }) {
const access = useComputerAccess()
+ useScreenViewed('computer_access')
const { screen, step, busy } = access
const mac = window.codync.platform === 'darwin'
const windows = window.codync.platform === 'win32'
diff --git a/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx b/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx
index 2aeb37e8..61dc1436 100644
--- a/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx
@@ -6,6 +6,7 @@ import { Dialog, SheetPage, useDismiss } from '../../components/Overlay'
import { HStack, Spacer, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useStore } from '../../store/context'
+import { useScreenViewed } from '../../store/analytics'
import { ComputerBadge } from '../ComputerBadge'
import { AgentSheet, AgentTile, NodeNotice } from './AgentSheet'
import { ComposioSection } from './ComposioViews'
@@ -32,6 +33,7 @@ export function MarketplaceView({ computers, computer, onComputer, appsFirst = f
const store = useStore()
const plugins = usePlugins(store)
const dismiss = useDismiss()
+ useScreenViewed('marketplace')
const [search, setSearch] = useState('')
/** Bumped on each submitted search, so every section searches again. */
const [searchToken, setSearchToken] = useState(0)
diff --git a/apps/desktop/src/renderer/views/routines/RoutinesView.tsx b/apps/desktop/src/renderer/views/routines/RoutinesView.tsx
index 81da77b7..58ded9f5 100644
--- a/apps/desktop/src/renderer/views/routines/RoutinesView.tsx
+++ b/apps/desktop/src/renderer/views/routines/RoutinesView.tsx
@@ -3,6 +3,7 @@ import { IconButton, Switch } from '../../components/Controls'
import { Sheet } from '../../components/Overlay'
import { HStack, Spacer, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
+import { useScreenViewed } from '../../store/analytics'
import { useStore } from '../../store/context'
import { errorText, isActiveRun, type Routine, type RoutineListing, type RoutineRun } from './routine'
import { RoutineEditorView } from './RoutineEditorView'
@@ -47,6 +48,8 @@ export function RoutinesView({ botId, initialId, onClose }: { botId: string; ini
current.current = botId
const open = (routineId: string | null) => setEditing({ id: crypto.randomUUID(), routineId })
+ // The list is part of the details panel; a routine's editor is the routines screen.
+ useScreenViewed(editing ? 'routines' : null, editing?.id)
const load = async () => {
const asked = botId
diff --git a/apps/desktop/src/renderer/views/settings/AnalyticsSheet.tsx b/apps/desktop/src/renderer/views/settings/AnalyticsSheet.tsx
index 7b9ffca1..fccca9c3 100644
--- a/apps/desktop/src/renderer/views/settings/AnalyticsSheet.tsx
+++ b/apps/desktop/src/renderer/views/settings/AnalyticsSheet.tsx
@@ -3,12 +3,13 @@ import { Icon } from '../../components/Icon'
import { ModalHeader, SheetPage } from '../../components/Overlay'
import { HStack, IconSlot, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
+import { openLink } from '../../store/analytics'
const PRIVACY_POLICY = 'https://codync.dev/privacy'
/** What sharing usage analytics sends; the same text as the kit's and the terminal UI's, true to the privacy policy. */
const details = [
- { icon: 'chart.bar', title: 'Features you use', detail: "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." },
+ { icon: 'chart.bar', title: 'Features you use', detail: "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." },
{ icon: 'exclamationmark.triangle', title: 'Crashes and errors', detail: "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." },
{ icon: 'globe', title: 'Approximate location', detail: 'Country and city, looked up from your IP address. The IP address itself is never stored.' },
{ icon: 'person.crop.circle', title: 'Who it belongs to', detail: "Your Codync account when you're signed in, otherwise a random ID made on this device." },
@@ -27,7 +28,7 @@ export function AnalyticsSheet() {
footer={
<>
See the{' '}
- <button className="settings-link" onClick={() => window.codync.app.openExternal(PRIVACY_POLICY)}>
+ <button className="settings-link" onClick={() => openLink(PRIVACY_POLICY, 'privacy')}>
Privacy Policy
</button>{' '}
for details.
diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
index 0120e98e..bc84f4a8 100644
--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx
+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
@@ -10,6 +10,7 @@ import { Text } from '../../components/Text'
import { useModel } from '../../lib/observable'
import { useAccount } from '../../store/account'
import type { BotStore } from '../../store/bot-store'
+import { useScreenViewed } from '../../store/analytics'
import { StoreContext, useApp } from '../../store/context'
import { ComputerBadge } from '../ComputerBadge'
import { deviceIcon, errorText, liveClient, relativeDay, Reveal, SectionHeader, statusText, thisMac } from './parts'
@@ -317,6 +318,7 @@ function deviceDetail(device: AuthorizedDevice) {
/** A one-time pairing QR (v3) from a computer this app manages: its keys, a code, and how to reach it. */
function PairingPanel({ store }: { store: BotStore }) {
useModel(store)
+ useScreenViewed('pairing')
const [info, setInfo] = useState<PairingInfo | null>(null)
const [qr, setQr] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
diff --git a/apps/desktop/src/renderer/views/settings/SSHRow.tsx b/apps/desktop/src/renderer/views/settings/SSHRow.tsx
index c3f77537..69825b28 100644
--- a/apps/desktop/src/renderer/views/settings/SSHRow.tsx
+++ b/apps/desktop/src/renderer/views/settings/SSHRow.tsx
@@ -3,6 +3,7 @@ import { Button, IconButton } from '../../components/Controls'
import { Icon } from '../../components/Icon'
import { HStack, IconSlot, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
+import { analytics } from '../../store/analytics'
import { Reveal } from './parts'
import { sshStatusDetail } from '@shared/ssh-startup'
@@ -68,7 +69,7 @@ export function SSHRow({ profile, status, edit, attached = true }: { profile: SS
<Reveal show={status.kind === 'notInstalled' && !dev}>
<HStack gap={6} className="settings-row">
<span className="settings-code selectable">{SSH_INSTALL_COMMAND}</span>
- <IconButton title="Copy install command" icon="doc.on.doc" onClick={() => window.codync.app.copy(SSH_INSTALL_COMMAND)} />
+ <IconButton title="Copy install command" icon="doc.on.doc" onClick={() => { analytics.track({ event: 'link_opened', link: 'install_command' }); window.codync.app.copy(SSH_INSTALL_COMMAND) }} />
</HStack>
</Reveal>
</div>
diff --git a/apps/desktop/src/renderer/views/settings/SettingsView.tsx b/apps/desktop/src/renderer/views/settings/SettingsView.tsx
index 30e66e7e..834055ff 100644
--- a/apps/desktop/src/renderer/views/settings/SettingsView.tsx
+++ b/apps/desktop/src/renderer/views/settings/SettingsView.tsx
@@ -1,4 +1,5 @@
import { Fragment, useEffect, useState } from 'react'
+import type { Screen } from '@shared/analytics'
import { islandLabel } from '@shared/island'
import { Button, CardForm, CardSection, ChoicePicker, IconButton, ProgressBar, Switch, ValueRow } from '../../components/Controls'
import { Icon } from '../../components/Icon'
@@ -8,6 +9,7 @@ import { Text } from '../../components/Text'
import { useModel } from '../../lib/observable'
import { DEFAULT_TEXT_SIZE, prefs, TEXT_SIZES, usePref } from '../../lib/prefs'
import { useAccount } from '../../store/account'
+import { useScreenViewed } from '../../store/analytics'
import { StoreContext, useApp } from '../../store/context'
import { ComputerBadge } from '../ComputerBadge'
import { UpdateButton, useUpdates } from '../UpdateButton'
@@ -32,12 +34,16 @@ const pages: { id: SettingsPage; title: string; label?: string; group: string; i
{ id: 'updates', title: 'Updates', group: thisComputer, icon: 'arrow.down.circle' },
]
+/** Each page as `screen_viewed` names it; Computer access and Voice chat report themselves. */
+const pageScreens: Record<SettingsPage, Screen | null> = { general: 'settings', updates: 'settings', computers: 'computers', usage: 'usage', access: null, voice: null }
+
export function SettingsView({ page: initial }: { page: SettingsPage }) {
// Kept here: the sheet's content doesn't follow the window's state once shown.
const [page, setPage] = useState(initial)
const app = useApp()
const dismiss = useDismiss()
const current = pages.find((p) => p.id === page)!
+ useScreenViewed(pageScreens[page])
return (
<div className="settings">
<nav className="settings-sidebar">
diff --git a/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx b/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx
index 372685c7..99a69ffb 100644
--- a/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx
+++ b/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx
@@ -8,6 +8,7 @@ import { HStack, Spacer, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { usePref } from '../../lib/prefs'
import { useStore } from '../../store/context'
+import { useScreenViewed } from '../../store/analytics'
import { errorText, liveClient, Reveal } from './parts'
import * as voice from './voice-settings'
import type { VoiceModels, VoiceProvider } from './voice-settings'
@@ -18,6 +19,7 @@ import type { VoiceModels, VoiceProvider } from './voice-settings'
* in `StoreContext`. `showsHeader` is false inside Settings, which titles the page itself.
*/
export function VoiceChatSettingsView({ showsHeader = true }: { showsHeader?: boolean }) {
+ useScreenViewed('voice_settings')
const [engine, setEngine] = usePref(voice.engine)
const [rate, setRate] = usePref(voice.rate)
const [language, setLanguage] = usePref(voice.language)
diff --git a/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx b/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx
index 2de6a960..1f55d2ba 100644
--- a/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx
+++ b/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx
@@ -6,6 +6,7 @@ import { Icon } from '../../components/Icon'
import { HStack, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useStore } from '../../store/context'
+import { useScreenViewed } from '../../store/analytics'
import { BotSettingsPanel } from '../bots/BotEditorView'
import { MemoryCard } from '../bots/MemoryView'
import { RoutinesView } from '../routines/RoutinesView'
@@ -34,6 +35,7 @@ export function DetailsPanel({ botId, routineId, tab, setTab, editGroup, share,
const store = useStore()
const bot = store.bots.get(botId) ?? null
const group = !!bot && isGroup(bot)
+ useScreenViewed('bot_details')
return (
<div className="details-panel">
<div className="details-drag" />
diff --git a/apps/desktop/src/renderer/views/thread/RepliesView.tsx b/apps/desktop/src/renderer/views/thread/RepliesView.tsx
index 5d1e690a..60104f86 100644
--- a/apps/desktop/src/renderer/views/thread/RepliesView.tsx
+++ b/apps/desktop/src/renderer/views/thread/RepliesView.tsx
@@ -5,6 +5,7 @@ import { ModalHeader, Sheet, SheetPage } from '../../components/Overlay'
import { HStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useStore } from '../../store/context'
+import { useScreenViewed } from '../../store/analytics'
import { UpdateNeededCard } from '../UpdateNeededCard'
import { buildChat, rowIn, useArrivals } from './chat-items'
import { ChatRow, WorkingIndicator } from './ChatRows'
@@ -20,6 +21,7 @@ import { useReading } from './reading'
export function RepliesView({ botId, rootId, close }: { botId: string; rootId: string; close: () => void }) {
const store = useStore()
const chat = store.bots.get(botId) ?? null
+ useScreenViewed('thread')
const root = store.allEntries(botId).find((e) => e.id === rootId)
const replies = store.replies(botId, rootId)
const live = !!chat && isWorkingIn(chat, botId, rootId) && !store.isOffline
diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsx
index 9187ca0c..c754368a 100644
--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx
+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx
@@ -7,6 +7,7 @@ import { Sheet, usePresence } from '../../components/Overlay'
import { HStack, IconSlot, Spacer } from '../../components/Stack'
import { Text } from '../../components/Text'
import { prefs, usePref } from '../../lib/prefs'
+import { useScreenViewed } from '../../store/analytics'
import { useStore } from '../../store/context'
import { UpdateNeededCard } from '../UpdateNeededCard'
import { buildChat, rowIn, useArrivals, type ChatItem } from './chat-items'
@@ -60,6 +61,8 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })
const [detailsWidth, setDetailsWidth] = usePref(prefs.detailsPanelWidth)
const [repliesWidth, setRepliesWidth] = usePref(prefs.repliesPanelWidth)
useReading(store, botId, null)
+ // The chat window remounts this per conversation (`key`), so each one opened counts.
+ useScreenViewed('chat')
useLayoutEffect(() => {
const el = root.current
diff --git a/apps/desktop/src/renderer/views/thread/TraceView.tsx b/apps/desktop/src/renderer/views/thread/TraceView.tsx
index d339bfe9..5f0ba436 100644
--- a/apps/desktop/src/renderer/views/thread/TraceView.tsx
+++ b/apps/desktop/src/renderer/views/thread/TraceView.tsx
@@ -8,6 +8,7 @@ import { Text, type Tone } from '../../components/Text'
import { ThinkingOrb, type OrbState } from '../../components/ThinkingOrb'
import type { Weight } from '../../lib/fonts'
import { useStore } from '../../store/context'
+import { useScreenViewed } from '../../store/analytics'
import { MarkdownText } from './Markdown'
import { CodeBox, DiffView } from './PermissionCard'
import './trace.css'
@@ -18,6 +19,7 @@ import './trace.css'
*/
export function TraceView({ botId, thread = null }: { botId: string; thread?: string | null }) {
const store = useStore()
+ useScreenViewed('trace')
const turns = new Map<number, Entry[]>()
for (const e of store.allEntries(botId)) {
if ((e.threadId ?? null) !== thread) continue
diff --git a/apps/desktop/src/shared/analytics.test.ts b/apps/desktop/src/shared/analytics.test.ts
new file mode 100644
index 00000000..3e9989e6
--- /dev/null
+++ b/apps/desktop/src/shared/analytics.test.ts
@@ -0,0 +1,11 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { maySendSetupFailure } from './analytics.ts'
+
+test('a host setup failure is sent only when the owner can’t have turned analytics off', () => {
+ assert.equal(maySendSetupFailure(true, true), true)
+ assert.equal(maySendSetupFailure(undefined, false), true, 'a first install: nothing stored yet, so on')
+ assert.equal(maySendSetupFailure(false, false), false)
+ assert.equal(maySendSetupFailure(false, true), false)
+ assert.equal(maySendSetupFailure(undefined, true), false, 'an older app never kept the host’s setting')
+})
diff --git a/apps/desktop/src/shared/analytics.ts b/apps/desktop/src/shared/analytics.ts
new file mode 100644
index 00000000..b5f950c1
--- /dev/null
+++ b/apps/desktop/src/shared/analytics.ts
@@ -0,0 +1,55 @@
+// App-level events the desktop app reports through the host's loopback `track`. The host accepts
+// only the catalog's events and properties (docs/reference/analytics-events.md): feature use,
+// never content.
+
+/** Screens, sheets and tabs, named the same on every client. */
+export type Screen =
+ | 'chat'
+ | 'thread'
+ | 'trace'
+ | 'bot_details'
+ | 'memory'
+ | 'routines'
+ | 'marketplace'
+ | 'settings'
+ | 'computers'
+ | 'usage'
+ | 'account'
+ | 'pairing'
+ | 'voice_settings'
+ | 'computer_access'
+
+/** Outbound links, by what they lead to. */
+export type Link = 'github' | 'docs' | 'issues' | 'discord' | 'app_store' | 'demo' | 'tailscale' | 'privacy' | 'support' | 'install_command'
+
+export type SignInProvider = 'apple' | 'google'
+
+/** Why a sign-in ended without an account. */
+export type SignInFailure = 'cancelled' | 'timeout' | 'verification' | 'error'
+
+/** What carried a voice call: on-device speech, a realtime model, or cloud transcription and speech. */
+export type VoiceCallEngine = 'on_device' | 'openai' | 'gemini' | 'cloud'
+
+export type AnalyticsEvent =
+ | { event: 'app_opened'; at_login: boolean }
+ | { event: 'window_opened' }
+ | { event: 'onboarding_completed'; signed_in: boolean }
+ | { event: 'computer_access_finished'; ready: boolean; onboarding: boolean }
+ | { event: 'sign_in_started'; provider: SignInProvider }
+ | { event: 'sign_in_failed'; provider: SignInProvider; reason: SignInFailure }
+ | { event: 'signed_in'; provider?: SignInProvider }
+ | { event: 'signed_out' }
+ | { event: 'star_prompt_answered'; ask: 'first' | 'second'; starred: boolean }
+ | { event: 'link_opened'; link: Link }
+ | { event: 'screen_viewed'; screen: Screen }
+ | { event: 'voice_call_started'; engine: VoiceCallEngine }
+
+/** `track`'s body: the event with its properties, from the desktop app. */
+export const trackBody = (event: AnalyticsEvent) => ({ ...event, app: 'desktop' as const })
+
+/**
+ * Whether the app may send `host_setup_failed` itself (`host` is the owner's analytics setting as
+ * its host last answered it): when it's on, or still unknown on a computer whose host never stored
+ * one, so an owner who turned analytics off is never reported.
+ */
+export const maySendSetupFailure = (host: unknown, hostHasData: boolean) => host === true || (host === undefined && !hostHasData)
diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.ts
index cbe3b074..5aa625e3 100644
--- a/apps/desktop/src/shared/ipc.ts
+++ b/apps/desktop/src/shared/ipc.ts
@@ -1,3 +1,4 @@
+import type { SignInFailure, SignInProvider } from './analytics'
import type { SharedFile } from './models'
import type { SSHBridge } from './ssh'
import type { ScreenAgentState } from './computer-access'
@@ -70,6 +71,8 @@ export type WindowCommand =
| { kind: 'refresh' }
| { kind: 'respondPermission'; ref: string; entryId: string; optionId: string }
| { kind: 'sendMessage'; ref: string; text: string }
+ /** The chat window was shown again after being hidden (`window_opened`). */
+ | { kind: 'windowOpened' }
/** The app's own updates (electron-updater, release builds only). */
export interface UpdateState {
@@ -114,6 +117,8 @@ export interface CodyncBridge {
appVersion: string
/** The computer's name ("Kevin's MacBook Pro"). */
computerName: string
+ /** This launch was started by the login item (Open at login). */
+ openedAtLogin: boolean
/** Screenshot/UI checks: CODYNC_DEBUG_OPEN=compose | group | plugins | computers | <bot name>. */
debugOpen: string | null
host: {
@@ -129,7 +134,8 @@ export interface CodyncBridge {
account: {
state(): Promise<AccountState>
onChange(cb: (s: AccountState) => void): () => void
- signIn(provider: 'apple' | 'google'): Promise<void>
+ /** Why it ended without an account; null once signed in (or while another sign-in runs). */
+ signIn(provider: SignInProvider): Promise<SignInFailure | null>
signOut(): Promise<void>
/** The signed-in session's JWT for the Codync cloud. */
token(): Promise<string>
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index aec97e00..db9e552b 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -369,9 +369,6 @@ export interface Hello {
analytics?: boolean
}
-/** Events only the desktop app knows about; the host records everything else from API calls. */
-export type AnalyticsEvent = 'app_opened' | 'onboarding_completed' | 'signed_in' | 'signed_out'
-
export interface PairingInfo {
pairingUrl: string
urls: string[]