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: send crash and error reports with usage analytics

leepokaiae2ac162af76
diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.ts
index 7a10d931..be05989c 100644
--- a/apps/desktop/electron.vite.config.ts
+++ b/apps/desktop/electron.vite.config.ts
@@ -14,5 +14,7 @@ export default defineConfig({
renderer: {
resolve: { alias: { '@shared': resolve('src/shared') } },
plugins: [react()],
+ // Readable function names in error reports; the files are local, so size doesn't matter.
+ build: { minify: false },
},
})
diff --git a/apps/desktop/src/main/error-reports.ts b/apps/desktop/src/main/error-reports.ts
new file mode 100644
index 00000000..e37419e9
--- /dev/null
+++ b/apps/desktop/src/main/error-reports.ts
@@ -0,0 +1,26 @@
+import { app, ipcMain } from 'electron'
+import { errorReport, type ErrorReport } from '../shared/error-report'
+import type { HostController } from './host-controller'
+
+/**
+ * Error tracking: uncaught errors in the main process and the windows, and windows or helpers
+ * that crashed, go to the host's loopback `reportError` (shared/error-report.ts).
+ */
+export function registerErrorReports(host: HostController) {
+ const send = (report: ErrorReport) => {
+ host.call('reportError', report).catch(() => {})
+ }
+ // The monitor only watches: Electron still handles the error as before.
+ process.on('uncaughtExceptionMonitor', (error) => send(errorReport(error, 'desktop-main', 'uncaught')))
+ process.on('unhandledRejection', (reason) => {
+ console.error('Unhandled rejection in the main process:', reason)
+ send(errorReport(reason, 'desktop-main', 'unhandledrejection'))
+ })
+ ipcMain.on('app:reportError', (_e, report: ErrorReport) => send({ ...report, process: 'desktop-renderer' }))
+ app.on('render-process-gone', (_e, _contents, details) => {
+ if (details.reason !== 'clean-exit') send({ process: 'desktop-main', type: 'RendererGone', mechanism: 'render-process-gone', value: details.reason, frames: [] })
+ })
+ app.on('child-process-gone', (_e, details) => {
+ if (details.reason !== 'clean-exit') send({ process: 'desktop-main', type: `${details.type}Gone`, mechanism: 'child-process-gone', value: details.reason, frames: [] })
+ })
+}
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index e3e6e0f8..c3dead1a 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -19,6 +19,7 @@ import { registerCloud } from './cloud'
import { registerSSH } from './ssh'
import { QuitLifecycle } from './quit-lifecycle'
import { Island } from './island'
+import { registerErrorReports } from './error-reports'
/** macOS's user-facing computer name, else the host name. */
function computerName() {
@@ -34,6 +35,7 @@ function computerName() {
if (!app.isPackaged && process.env.CODYNC_REMOTE_DEBUG) app.commandLine.appendSwitch('remote-debugging-port', process.env.CODYNC_REMOTE_DEBUG)
const host = new HostController()
+registerErrorReports(host)
const account = new AccountService()
const updates = new Updates(host)
let chat: BrowserWindow | null = null
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index ab7d2fe8..9b431041 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -99,6 +99,7 @@ const bridge: CodyncBridge = {
cancel: (id) => ipcRenderer.invoke('files:cancel', id),
},
app: {
+ reportError: (report) => ipcRenderer.send('app:reportError', report),
openExternal: (url) => ipcRenderer.send('app:openExternal', url),
copy: (text) => ipcRenderer.send('app:copy', text),
pickFiles: () => ipcRenderer.invoke('app:pickFiles'),
diff --git a/apps/desktop/src/renderer/components/Controls.tsx b/apps/desktop/src/renderer/components/Controls.tsx
index 28040867..da183793 100644
--- a/apps/desktop/src/renderer/components/Controls.tsx
+++ b/apps/desktop/src/renderer/components/Controls.tsx
@@ -38,9 +38,10 @@ export function Spinner({ size = 14 }: { size?: number }) {
}
/** On/off switch: label on the left, a flat capsule track on the right. */
-export function Switch({ on, onChange, children, disabled, style }: { on: boolean; onChange: (on: boolean) => void; children?: ReactNode; disabled?: boolean; style?: CSSProperties }) {
+/** `label` names a switch whose visible label sits outside it (beside an info button, say). */
+export function Switch({ on, onChange, children, label, disabled, style }: { on: boolean; onChange: (on: boolean) => void; children?: ReactNode; label?: string; disabled?: boolean; style?: CSSProperties }) {
return (
- <button className="switch" role="switch" aria-checked={on} disabled={disabled} onClick={() => onChange(!on)} style={style}>
+ <button className="switch" role="switch" aria-checked={on} aria-label={label} disabled={disabled} onClick={() => onChange(!on)} style={style}>
{children !== undefined ? <span className="switch-label">{children}</span> : null}
<span className={`switch-track ${on ? 'on' : ''}`}>
<span className="switch-knob" />
diff --git a/apps/desktop/src/renderer/demo/bridge.ts b/apps/desktop/src/renderer/demo/bridge.ts
index c423d3cc..429d050b 100644
--- a/apps/desktop/src/renderer/demo/bridge.ts
+++ b/apps/desktop/src/renderer/demo/bridge.ts
@@ -90,6 +90,7 @@ const bridge: CodyncBridge = {
updates: { state: async () => updates, onChange: none, check() {}, setAutoCheck() {}, setAutoDownload() {} },
files: { begin: unavailable, write: async () => {}, finish: async () => {}, cancel: async () => {} },
app: {
+ reportError() {},
openExternal: (url) => void window.open(url, '_blank', 'noopener'),
copy: (text) => void navigator.clipboard?.writeText(text).catch(() => {}),
pickFiles: async () => [],
diff --git a/apps/desktop/src/renderer/main.tsx b/apps/desktop/src/renderer/main.tsx
index 9cfcf27d..6432affc 100644
--- a/apps/desktop/src/renderer/main.tsx
+++ b/apps/desktop/src/renderer/main.tsx
@@ -8,6 +8,12 @@ import { AppModel } from './store/app-model'
import { AppContext } from './store/context'
import { applyTextSize, prefs } from './lib/prefs'
import { account } from './store/account'
+import { errorReport } from '@shared/error-report'
+
+// Error tracking: this window's uncaught errors go to the host (shared/error-report.ts).
+const report = (error: unknown, mechanism: string) => window.codync.app.reportError(errorReport(error, 'desktop-renderer', mechanism))
+window.addEventListener('error', (e) => report(e.error, 'onerror'))
+window.addEventListener('unhandledrejection', (e) => report(e.reason, 'unhandledrejection'))
const page = new URLSearchParams(location.search).get('window') ?? 'chat'
document.title = window.codync.appName
diff --git a/apps/desktop/src/renderer/views/settings/AnalyticsSheet.tsx b/apps/desktop/src/renderer/views/settings/AnalyticsSheet.tsx
new file mode 100644
index 00000000..531ac569
--- /dev/null
+++ b/apps/desktop/src/renderer/views/settings/AnalyticsSheet.tsx
@@ -0,0 +1,46 @@
+import { CardForm, CardSection } from '../../components/Controls'
+import { Icon } from '../../components/Icon'
+import { ModalHeader } from '../../components/Overlay'
+import { font } from '../../lib/fonts'
+
+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: '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." },
+ { icon: 'eye.slash', title: 'Never shared', detail: 'Your messages, prompts, code, files, file names or paths, bot names, credentials, or anything your agents produce.' },
+ { icon: 'lock.shield', title: "How it's used", detail: 'Only to spot bugs sooner and see which features work and where people get stuck. Never sold, never used for ads or to track you across other apps and websites.' },
+ { icon: 'power', title: 'Your choice', detail: 'Each iPhone and each computer has its own switch. Turning it off stops sending right away and drops anything not sent yet.' },
+]
+
+/** Settings → Privacy's info button: everything Share usage analytics covers. */
+export function AnalyticsSheet() {
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--background)' }}>
+ <ModalHeader title="Usage analytics" />
+ <CardForm>
+ <CardSection>
+ {details.map((d) => (
+ <div key={d.title} className="settings-row" style={{ alignItems: 'flex-start' }}>
+ <span style={{ width: 20, display: 'flex', justifyContent: 'center', paddingTop: 2 }}>
+ <Icon name={d.icon} size={15} color="var(--secondary)" />
+ </span>
+ <div className="settings-stack" style={{ flex: 1, gap: 2 }}>
+ <span>{d.title}</span>
+ <span style={{ ...font('footnote'), color: 'var(--secondary)' }}>{d.detail}</span>
+ </div>
+ </div>
+ ))}
+ </CardSection>
+ <CardSection>
+ <button className="press" style={{ ...font('body'), color: 'var(--text)', alignSelf: 'flex-start' }} onClick={() => window.codync.app.openExternal(PRIVACY_POLICY)}>
+ Privacy Policy
+ </button>
+ </CardSection>
+ </CardForm>
+ </div>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/settings/SettingsView.tsx b/apps/desktop/src/renderer/views/settings/SettingsView.tsx
index 8738c90c..c7daa067 100644
--- a/apps/desktop/src/renderer/views/settings/SettingsView.tsx
+++ b/apps/desktop/src/renderer/views/settings/SettingsView.tsx
@@ -15,6 +15,8 @@ import { errorText, isMac, thisMac } from './parts'
import { UsageLimits } from './UsageLimits'
import { VoiceChatSettingsView } from './VoiceChatSettingsView'
import { ComputerAccessView } from '../computer-access/ComputerAccessView'
+import { FormSheet } from '../marketplace/pieces'
+import { AnalyticsSheet } from './AnalyticsSheet'
/** The chat window's Settings: pages in a sidebar, ChatGPT's settings layout. */
export type SettingsPage = 'general' | 'computers' | 'access' | 'voice' | 'usage' | 'updates'
@@ -177,13 +179,21 @@ function PrivacySettings() {
const app = useApp()
const local = useModel(app.local)
const running = local !== null && local.connection.kind === 'online'
+ const [about, setAbout] = useState(false)
const setShared = (on: boolean) => void local?.setAnalytics(on).catch((e: unknown) => app.setError(errorText(e)))
return (
- <CardSection title="Privacy" footer="Which features you use, never your messages, code or files. Helps us spot bugs sooner and make Codync better for you.">
- <Switch on={local?.analytics === true} onChange={setShared} disabled={!running}>
- Share usage analytics
- </Switch>
- </CardSection>
+ <>
+ <CardSection title="Privacy" footer="Which features you use, never your messages, code or files. Helps us spot bugs sooner and make Codync better for you.">
+ <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
+ <span style={{ opacity: running ? 1 : 0.4 }}>Share usage analytics</span>
+ <IconButton title="About usage analytics" icon="info.circle" onClick={() => setAbout(true)} />
+ <Switch on={local?.analytics === true} onChange={setShared} disabled={!running} label="Share usage analytics" style={{ flex: 1, justifyContent: 'flex-end' }} />
+ </div>
+ </CardSection>
+ <FormSheet open={about} onClose={() => setAbout(false)}>
+ <AnalyticsSheet />
+ </FormSheet>
+ </>
)
}
diff --git a/apps/desktop/src/shared/error-report.test.ts b/apps/desktop/src/shared/error-report.test.ts
new file mode 100644
index 00000000..906ccba0
--- /dev/null
+++ b/apps/desktop/src/shared/error-report.test.ts
@@ -0,0 +1,22 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { errorReport, parseStack } from './error-report.ts'
+
+test('a report keeps the error class and its frames, never the message', () => {
+ const error = new TypeError('cannot read /Users/kevin/secret.txt')
+ error.stack = [
+ 'TypeError: cannot read /Users/kevin/secret.txt',
+ ' at loadChat (file:///Applications/Codync.app/Contents/Resources/app.asar/out/renderer/assets/index-a1.js:99:2)',
+ ' at async open (file:///Applications/Codync.app/Contents/Resources/app.asar/out/renderer/assets/index-a1.js:10:4)',
+ ' at file:///Applications/Codync.app/Contents/Resources/app.asar/out/renderer/assets/index-a1.js:5:1',
+ ].join('\n')
+ const report = errorReport(error, 'desktop-renderer', 'onerror')
+ assert.equal(report.type, 'TypeError')
+ assert.ok(!JSON.stringify(report).includes('secret'))
+ assert.deepEqual(report.frames.map((f) => [f.function, f.line]), [['<anonymous>', 5], ['async open', 10], ['loadChat', 99]])
+})
+
+test('a thrown non-error has a type but nothing else', () => {
+ assert.deepEqual(errorReport('hello world', 'desktop-main', 'uncaught'), { process: 'desktop-main', type: 'NonError', mechanism: 'uncaught', frames: [] })
+ assert.deepEqual(parseStack('Error: x\n at node:internal/process/task_queues:105:5'), [{ function: '<anonymous>', file: 'node:internal/process/task_queues', line: 105, column: 5 }])
+})
diff --git a/apps/desktop/src/shared/error-report.ts b/apps/desktop/src/shared/error-report.ts
new file mode 100644
index 00000000..c78e46bb
--- /dev/null
+++ b/apps/desktop/src/shared/error-report.ts
@@ -0,0 +1,41 @@
+// Error tracking: an uncaught error, as the host's loopback `reportError` takes it. The host
+// sends it to PostHog with usage analytics (same switch) after cutting paths down; the
+// message never leaves this computer (docs/features/analytics.md).
+
+export interface ErrorReport {
+ process: 'desktop-main' | 'desktop-renderer'
+ /** The error's class (`TypeError`), or what the platform reports (`RendererGone`). */
+ type: string
+ /** How it was caught: `onerror`, `unhandledrejection`, `uncaught`, `render-process-gone`, … */
+ mechanism: string
+ /** Only a reason Electron names (`oom`); never an error's message. */
+ value?: string
+ /** Oldest call first, the failing one last. */
+ frames: ReportFrame[]
+}
+
+export interface ReportFrame {
+ function: string
+ file?: string
+ line?: number
+ column?: number
+}
+
+/** ` at fn (file:line:col)` or ` at file:line:col` in a V8 stack. */
+const FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/
+
+export function errorReport(error: unknown, process: ErrorReport['process'], mechanism: string): ErrorReport {
+ const type = error instanceof Error ? error.name : 'NonError'
+ const stack = error instanceof Error ? (error.stack ?? '') : ''
+ return { process, type, mechanism, frames: parseStack(stack) }
+}
+
+/** V8 lists the failing call first; the report wants it last. */
+export function parseStack(stack: string): ReportFrame[] {
+ const frames: ReportFrame[] = []
+ for (const line of stack.split('\n')) {
+ const m = FRAME.exec(line)
+ if (m) frames.push({ function: m[1] ?? '<anonymous>', file: m[2], line: Number(m[3]), column: Number(m[4]) })
+ }
+ return frames.reverse()
+}
diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.ts
index 20ebae07..b60a0e41 100644
--- a/apps/desktop/src/shared/ipc.ts
+++ b/apps/desktop/src/shared/ipc.ts
@@ -2,6 +2,7 @@ import type { SharedFile } from './models'
import type { SSHBridge } from './ssh'
import type { ScreenAgentState } from './computer-access'
import type { IslandRect, IslandScreen, IslandSummary } from './island'
+import type { ErrorReport } from './error-report'
// The bridge between the main process (host lifecycle, loopback HTTP, tray, windows)
// and the renderer (stores and UI). Exposed as `window.codync` by the preload script.
@@ -187,6 +188,8 @@ export interface CodyncBridge {
cancel(id: string): Promise<void>
}
app: {
+ /** Error tracking: an uncaught error in this window (shared/error-report.ts). */
+ reportError(report: ErrorReport): void
openExternal(url: string): void
copy(text: string): void
/** Files picked in the system dialog: name and bytes. */
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index b9edfd67..4c4a5a30 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -123,6 +123,7 @@ final class AppStore {
SharedStore.activeAccountID = session.userID
account = session
Analytics.shared.userID = { [session] in session.userID }
+ CrashReports.shared.start()
contextID = storage.id
(accounts, cloud) = Self.makeAccounts(storage, session: session)
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift
index 515b8f7f..46119511 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift
@@ -26,14 +26,17 @@ public final class Analytics {
let properties: [String: Value]
}
- enum Value: Encodable, Equatable {
- case string(String), bool(Bool)
+ enum Value: Encodable, Equatable, Sendable {
+ case string(String), bool(Bool), int(Int), array([Value]), object([String: Value])
func encode(to encoder: Encoder) throws {
var c = encoder.singleValueContainer()
switch self {
case .string(let s): try c.encode(s)
case .bool(let b): try c.encode(b)
+ case .int(let i): try c.encode(i)
+ case .array(let a): try c.encode(a)
+ case .object(let o): try c.encode(o)
}
}
}
@@ -80,8 +83,12 @@ public final class Analytics {
/// `properties` are public names, never content.
public func capture(_ event: AnalyticsEvent, _ properties: [String: String] = [:]) {
+ record(event.rawValue, properties.mapValues(Value.string))
+ }
+
+ /// One event for the signed-in account (merging the install ID into it once), else the install ID.
+ func record(_ name: String, _ extra: [String: Value]) {
guard isEnabled else { return }
- let extra = properties.mapValues(Value.string)
if let user = userID() {
var identified = defaults.stringArray(forKey: Self.identifiedKey) ?? []
if !identified.contains(user) {
@@ -89,9 +96,9 @@ public final class Analytics {
identified.append(user)
defaults.set(identified, forKey: Self.identifiedKey)
}
- enqueue(event.rawValue, user, extra)
+ enqueue(name, user, extra)
} else {
- enqueue(event.rawValue, installID, extra)
+ enqueue(name, installID, extra)
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/CrashReports.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/CrashReports.swift
new file mode 100644
index 00000000..8c1d27b3
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/CrashReports.swift
@@ -0,0 +1,95 @@
+import Foundation
+import MetricKit
+
+/// Crashes as `$exception` events for PostHog Error Tracking. MetricKit hands the app its own
+/// crash reports on the next launch; each becomes one event with the exception and signal names
+/// and binary + offset frames, never a message, reason or memory detail.
+public final class CrashReports: NSObject, MXMetricManagerSubscriber, Sendable {
+ public static let shared = CrashReports()
+ private static let maxFrames = 50
+
+ /// Subscribes once, at app launch (widgets and the notification extension never do).
+ public func start() {
+ MXMetricManager.shared.add(self)
+ }
+
+ public func didReceive(_ payloads: [MXDiagnosticPayload]) {
+ let events = payloads.flatMap { $0.crashDiagnostics ?? [] }.map {
+ Self.properties(callStack: $0.callStackTree.jsonRepresentation(), exceptionType: $0.exceptionType?.intValue,
+ signal: $0.signal?.intValue, appVersion: $0.applicationVersion)
+ }
+ guard !events.isEmpty else { return }
+ Task { @MainActor in
+ events.forEach { Analytics.shared.record("$exception", $0) }
+ Analytics.shared.flush()
+ }
+ }
+
+ /// The `$exception` properties for one crash.
+ static func properties(callStack: Data, exceptionType: Int?, signal: Int?, appVersion: String) -> [String: Analytics.Value] {
+ let exception: [String: Analytics.Value] = [
+ "type": .string(exceptionType.flatMap { machExceptions[$0] } ?? "Crash"),
+ "value": .string(signal.flatMap { signals[$0] } ?? ""),
+ "mechanism": .object(["type": .string("metrickit"), "handled": .bool(false), "synthetic": .bool(false)]),
+ "stacktrace": .object(["type": .string("raw"), "frames": .array(frames(callStack))]),
+ ]
+ return [
+ "$exception_list": .array([.object(exception)]),
+ "$exception_level": .string("fatal"),
+ "process": .string("ios"),
+ "app_version": .string(appVersion),
+ ]
+ }
+
+ /// The crashed thread's frames, oldest first and the crashing frame last (PostHog's order).
+ static func frames(_ callStack: Data) -> [Analytics.Value] {
+ guard let tree = try? JSONDecoder().decode(Tree.self, from: callStack),
+ let stack = tree.callStacks.first(where: { $0.threadAttributed == true }) ?? tree.callStacks.first
+ else { return [] }
+ // Root frame is where it crashed; each first sub-frame is its caller.
+ var walk: [Frame] = []
+ var next = stack.callStackRootFrames.first
+ while let frame = next, walk.count < maxFrames {
+ walk.append(frame)
+ next = frame.subFrames?.first
+ }
+ return walk.reversed().map { frame in
+ let binary = frame.binaryName ?? "???"
+ return .object([
+ "platform": .string("custom"),
+ "lang": .string("swift"),
+ "function": .string("\(binary) + \(frame.offsetIntoBinaryTextSegment ?? 0)"),
+ "module": .string(binary),
+ "resolved": .bool(false),
+ "in_app": .bool(binary.hasPrefix("Codync")),
+ ])
+ }
+ }
+
+ private struct Tree: Decodable {
+ let callStacks: [Stack]
+ }
+
+ private struct Stack: Decodable {
+ let threadAttributed: Bool?
+ let callStackRootFrames: [Frame]
+ }
+
+ private struct Frame: Decodable {
+ let binaryName: String?
+ let offsetIntoBinaryTextSegment: Int?
+ let subFrames: [Frame]?
+ }
+
+ /// `<mach/exception_types.h>`.
+ static let machExceptions: [Int: String] = [
+ 1: "EXC_BAD_ACCESS", 2: "EXC_BAD_INSTRUCTION", 3: "EXC_ARITHMETIC", 4: "EXC_EMULATION",
+ 5: "EXC_SOFTWARE", 6: "EXC_BREAKPOINT", 7: "EXC_SYSCALL", 8: "EXC_MACH_SYSCALL",
+ 9: "EXC_RPC_ALERT", 10: "EXC_CRASH", 11: "EXC_RESOURCE", 12: "EXC_GUARD", 13: "EXC_CORPSE_NOTIFY",
+ ]
+
+ static let signals: [Int: String] = [
+ 1: "SIGHUP", 2: "SIGINT", 3: "SIGQUIT", 4: "SIGILL", 5: "SIGTRAP", 6: "SIGABRT", 7: "SIGEMT",
+ 8: "SIGFPE", 9: "SIGKILL", 10: "SIGBUS", 11: "SIGSEGV", 12: "SIGSYS", 13: "SIGPIPE", 14: "SIGALRM", 15: "SIGTERM",
+ ]
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/AnalyticsSheet.swift b/apps/ios/Kit/Sources/CodyncUI/AnalyticsSheet.swift
new file mode 100644
index 00000000..cb391b63
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/AnalyticsSheet.swift
@@ -0,0 +1,50 @@
+import CodyncKit
+import SwiftUI
+
+/// Settings' info button beside Share usage analytics: everything it covers. The same text as the
+/// desktop app's and the terminal UI's, true to the privacy policy.
+public struct AnalyticsSheet: View {
+ @Environment(\.openURL) private var openURL
+
+ private static let details: [(icon: String, title: String, detail: String)] = [
+ ("chart.bar", "Features you use", "Opening the app, creating or deleting a bot, sending a message (how many attachments, never the files), running a routine or a voice call, installing a connector. Each comes with the app version, the platform, and the bot's agent and model."),
+ ("exclamationmark.triangle", "Crashes and errors", "When Codync crashes or an agent fails to answer: the kind of error and where in Codync's own code it happened. Never the error's message; file paths are cut down to Codync's own files."),
+ ("globe", "Approximate location", "Country and city, looked up from your IP address. The IP address itself is never stored."),
+ ("person.crop.circle", "Who it belongs to", "Your Codync account when you're signed in, otherwise a random ID made on this device."),
+ ("eye.slash", "Never shared", "Your messages, prompts, code, files, file names or paths, bot names, credentials, or anything your agents produce."),
+ ("lock.shield", "How it's used", "Only to spot bugs sooner and see which features work and where people get stuck. Never sold, never used for ads or to track you across other apps and websites."),
+ ("power", "Your choice", "Each iPhone and each computer has its own switch. Turning it off stops sending right away and drops anything not sent yet."),
+ ]
+
+ public init() {}
+
+ public var body: some View {
+ VStack(spacing: 0) {
+ ModalHeader("Usage analytics")
+ CardForm {
+ CardSection {
+ ForEach(Self.details, id: \.title) { item in
+ HStack(alignment: .firstTextBaseline, spacing: 12) {
+ Image(systemName: item.icon)
+ .foregroundStyle(Palette.secondary)
+ .frame(width: 22)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(item.title)
+ Text(item.detail)
+ .font(.footnote)
+ .foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ }
+ CardSection {
+ Button("Privacy Policy") { openURL(URL(string: "https://codync.dev/privacy")!) }
+ .buttonStyle(.plain)
+ .foregroundStyle(Palette.text)
+ }
+ }
+ }
+ .background(Palette.background)
+ }
+}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
index 768eae57..89e30339 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
@@ -45,3 +45,53 @@ import Testing
analytics.setEnabled(false)
#expect(analytics.pending.isEmpty)
}
+
+@MainActor
+@Test func crashReportsSendNamesAndFramesButNoMessage() throws {
+ // MetricKit's call-stack JSON: the root frame crashed, each first sub-frame is its caller.
+ func frame(_ binary: String, _ offset: Int, _ caller: String = "") -> String {
+ #"{"binaryName":"\#(binary)","offsetIntoBinaryTextSegment":\#(offset),"binaryUUID":"U","address":1,"sampleCount":1\#(caller.isEmpty ? "" : #","subFrames":[\#(caller)]"#)}"#
+ }
+ let crashed = frame("CodyncKit", 3, frame("SwiftUI", 2, frame("Codync", 1)))
+ let json = #"{"callStackPerThread":true,"callStacks":[{"threadAttributed":false,"callStackRootFrames":[\#(frame("libsystem_kernel.dylib", 9))]},{"threadAttributed":true,"callStackRootFrames":[\#(crashed)]}]}"#
+ let p = CrashReports.properties(callStack: Data(json.utf8), exceptionType: 1, signal: 11, appVersion: "2.14.1")
+
+ #expect(p["$exception_level"] == .string("fatal"))
+ #expect(p["process"] == .string("ios"))
+ #expect(p["app_version"] == .string("2.14.1"))
+ guard case .array(let list) = p["$exception_list"], case .object(let exception) = list.first,
+ case .object(let stack) = exception["stacktrace"], case .array(let frames) = stack["frames"] else {
+ Issue.record("no exception")
+ return
+ }
+ #expect(exception["type"] == .string("EXC_BAD_ACCESS"))
+ #expect(exception["value"] == .string("SIGSEGV"))
+ // The attributed thread, oldest first: the crashing frame is last.
+ let functions = frames.compactMap { if case .object(let f) = $0 { f["function"] } else { nil } }
+ #expect(functions == [.string("Codync + 1"), .string("SwiftUI + 2"), .string("CodyncKit + 3")])
+ let inApp = frames.compactMap { if case .object(let f) = $0 { f["in_app"] } else { nil } }
+ #expect(inApp == [.bool(true), .bool(false), .bool(true)])
+
+ // Unknown numbers fall back to generic names; nothing but names and offsets is sent.
+ let unknown = CrashReports.properties(callStack: Data("{}".utf8), exceptionType: 99, signal: nil, appVersion: "1")
+ let encoded = String(decoding: try JSONEncoder().encode(unknown), as: UTF8.self)
+ #expect(encoded.contains(#""type":"Crash""#) && encoded.contains(#""frames":[]"#))
+
+ // A runaway stack keeps the 50 frames nearest the crash.
+ var deep = frame("Codync", 0)
+ for i in 1...80 { deep = frame("Codync", i, deep) }
+ let capped = CrashReports.frames(Data(#"{"callStacks":[{"callStackRootFrames":[\#(deep)]}]}"#.utf8))
+ #expect(capped.count == 50)
+ #expect(capped.last == .object(["platform": .string("custom"), "lang": .string("swift"), "function": .string("Codync + 80"),
+ "module": .string("Codync"), "resolved": .bool(false), "in_app": .bool(true)]))
+
+ // Recorded like any other event: off records nothing.
+ let defaults = try #require(UserDefaults(suiteName: "CrashReportsTests-\(UUID())"))
+ let analytics = Analytics(defaults: defaults) { _ in false }
+ analytics.record("$exception", p)
+ #expect(analytics.pending.first?.properties["process"] == .string("ios"))
+ #expect(analytics.pending.first?.properties["$lib"] == .string("codync-ios"))
+ analytics.setEnabled(false)
+ analytics.record("$exception", p)
+ #expect(analytics.pending.isEmpty)
+}
diff --git a/apps/ios/Resources/PrivacyInfo.xcprivacy b/apps/ios/Resources/PrivacyInfo.xcprivacy
index 421e3e6b..cc2e3f63 100644
--- a/apps/ios/Resources/PrivacyInfo.xcprivacy
+++ b/apps/ios/Resources/PrivacyInfo.xcprivacy
@@ -21,6 +21,19 @@
<string>NSPrivacyCollectedDataTypePurposeAnalytics</string>
</array>
</dict>
+ <!-- Crash reports (exception and signal names, binary + offset frames, no message) sent with usage analytics. -->
+ <dict>
+ <key>NSPrivacyCollectedDataType</key>
+ <string>NSPrivacyCollectedDataTypeCrashData</string>
+ <key>NSPrivacyCollectedDataTypeLinked</key>
+ <true/>
+ <key>NSPrivacyCollectedDataTypeTracking</key>
+ <false/>
+ <key>NSPrivacyCollectedDataTypePurposes</key>
+ <array>
+ <string>NSPrivacyCollectedDataTypePurposeAnalytics</string>
+ </array>
+ </dict>
<!-- Approximate location (country, city) that the analytics service looks up from the IP, which it then discards. -->
<dict>
<key>NSPrivacyCollectedDataType</key>
diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swift
index 159b2fe3..2c3cc465 100644
--- a/apps/ios/Views/SettingsView.swift
+++ b/apps/ios/Views/SettingsView.swift
@@ -21,6 +21,7 @@ struct SettingsView: View {
@State private var confirmStartOver = false
@State private var confirmRemoveCopy: CloudComputer?
@State private var voice: VoiceTarget?
+ @State private var aboutAnalytics = false
var body: some View {
CardForm {
@@ -78,9 +79,13 @@ struct SettingsView: View {
}
CardSection(footer: "Which features you use, never your messages, code or files. Helps us spot bugs sooner and make Codync better for you.") {
- Toggle("Share usage analytics", isOn: Binding(get: { analyticsEnabled },
- set: { Analytics.shared.setEnabled($0) }))
- .toggleStyle(.codync)
+ HStack(spacing: 4) {
+ Text("Share usage analytics").lineLimit(1).layoutPriority(1)
+ IconButton("About usage analytics", systemImage: "info.circle") { aboutAnalytics = true }
+ Toggle(isOn: Binding(get: { analyticsEnabled }, set: { Analytics.shared.setEnabled($0) })) { EmptyView() }
+ .toggleStyle(.codync)
+ .accessibilityLabel("Share usage analytics")
+ }
}
if !hiddenBots.isEmpty {
@@ -136,6 +141,7 @@ struct SettingsView: View {
PairingView(inModal: true)
}
.codyncSheet(item: $voice) { target in VoiceChatSettingsView().environment(target.store) }
+ .codyncSheet(isPresented: $aboutAnalytics) { AnalyticsSheet() }
.codyncSheet(item: $access) { target in
AccessRequestView(computer: target.computer, pending: accounts.pendingAccess[target.id] != nil)
}
diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md
index 9b91d121..ec0d3092 100644
--- a/docs/architecture/desktop-app.md
+++ b/docs/architecture/desktop-app.md
@@ -24,7 +24,7 @@ determines when there are no earlier messages.
| Path | |
|---|---|
-| `src/main/` | Main process: host service (`host-controller.ts`), loopback HTTP/SSE proxy (`host-proxy.ts`), menu bar/tray, windows, account sign-in (Clerk Frontend API, `account.ts`), cloud API and device key (`cloud.ts`), updates (`updates.ts`), SSH tunnels (`ssh.ts`), Codync Screen agent (`screen.ts`), on-device speech (`speech.ts`), browser sign-in callbacks (`auth.ts`), the [notch island](../features/notch-island.md) window (`island.ts`) |
+| `src/main/` | Main process: host service (`host-controller.ts`), loopback HTTP/SSE proxy (`host-proxy.ts`), menu bar/tray, windows, account sign-in (Clerk Frontend API, `account.ts`), cloud API and device key (`cloud.ts`), updates (`updates.ts`), SSH tunnels (`ssh.ts`), Codync Screen agent (`screen.ts`), on-device speech (`speech.ts`), browser sign-in callbacks (`auth.ts`), the [notch island](../features/notch-island.md) window (`island.ts`), [error tracking](../features/analytics.md#error-tracking) (`error-reports.ts`) |
| `src/preload/` | The `window.codync` bridge (types in `src/shared/ipc.ts`) |
| `src/renderer/store/` | `BotStore` (port of kit's; `bot-store.ts` actions over `bot-sync.ts` events stream and `bot-mirror.ts` state), `AppModel` (window state, approvals), `CloudModel` (claims, cloud default), `AccountSession` |
| `src/renderer/components/` | Design system: controls, overlays (sheets, dialogs, menus), SF Symbol icons, character avatars, thinking orbs |
diff --git a/docs/features/analytics.md b/docs/features/analytics.md
index 7d50d03e..487ffca2 100644
--- a/docs/features/analytics.md
+++ b/docs/features/analytics.md
@@ -3,13 +3,17 @@
Product analytics in PostHog (US Cloud, project "Codync App", id 649427), on by default on
every device; *Share usage analytics* in Settings turns it off. It exists to spot bugs sooner
(failed or stopped turns per agent and platform) and to serve users better. The public promise
-lives in `web/app/privacy/page.tsx`: keep it true.
+lives in `web/app/privacy/page.tsx`: keep it true. The info button beside the switch (terminal
+UI: *About usage analytics…*) shows the same promise in the app, in one text per client
+(desktop `views/settings/AnalyticsSheet.tsx`, `CodyncUI/AnalyticsSheet.swift`,
+`host/src/tui/view/analytics.rs`): change all three with the policy.
## Rules
- **Only feature use, never content.** No message text, prompts, code, file names, paths,
bot names, credentials or agent output. Properties are counts, booleans and public
catalog names (agent, model, connector catalog name; a custom connector is just `custom`).
+ Errors are categories and code locations, never an error's message (see *Error tracking*).
- **Setting per device.** The computer's owner decides for that computer (host kv
`analytics_enabled`, on unless `0`); each iPhone decides for itself (`UserDefaults`
`analyticsEnabled`, on unless `false`). Turning it off drops anything still queued. A
@@ -52,13 +56,42 @@ Besides `env`, `app_version`, `$os`, `$lib`:
|---|---|
| `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` |
+| `turn_finished` | `agent`, `outcome` (`done`/`stopped`/`failed`/`incomplete`), `stop_reason` (ACP's, else `other`), `source` (`user`/`routine`/`group`/`bot`), `seconds`; when failed, `error` (`not_installed`/`sign_in`/`timeout`/`exited`/`agent_error`/`io`/`other`) and, for `agent_error`, the agent's JSON-RPC `rpc_code` |
| `voice_call_finished` | `seconds` |
| `connector_installed` | `connector` (catalog name or `custom`) |
| `skill_installed` | `custom` |
| `computer_paired` | `via` (`qr`/`account`), `computer` |
| every host event | `client` (`local`/`remote`), `computer`, `arch` |
+## Error tracking
+
+Crashes and uncaught errors go to PostHog Error Tracking as `$exception` events with the same
+switch, identity and common properties as everything else, plus `process`. No SDK: each client
+builds PostHog's generic `custom` frames (oldest first, the failing one last).
+
+- **Host** (`host/src/analytics/errors.rs`): its own panics (a panic hook queues them for the
+ analytics task), and `reportError`, loopback only, for the computer's apps. Process `host`.
+- **Terminal UI**: its panics, through `reportError` from the panic hook. Process `tui`.
+- **Desktop** (`apps/desktop/src/main/error-reports.ts`, `shared/error-report.ts`): uncaught
+ errors and rejections in the main process and every window, and windows or helpers that
+ crashed (`RendererGone`, `GPUGone`, … with Electron's reason), through `reportError`.
+ Processes `desktop-main`, `desktop-renderer`. The renderer is built unminified so function
+ names stay readable.
+- **iPhone** (`CodyncKit` `CrashReports`): MetricKit's crash diagnostics, delivered on the next
+ launch, straight to PostHog with the version that crashed. Frames are `binary + offset`
+ (unsymbolicated; Xcode Organizer has the symbolicated crash). Process `ios`.
+
+What leaves the device: the error's type (`Panic`, `TypeError`, `EXC_BAD_ACCESS`), how it was
+caught, function names, and file names and line numbers inside Codync's code; an absolute path
+keeps only its file name. Never the error's message: only a panic message written as a literal
+in the code, an Electron crash reason or a signal name. Release host builds are stripped, so a
+host panic is its location only.
+
+Alerts email the owner, from insights on the *Codync users* dashboard (production only): *Any
+crash or error in a day* (`$exception` > 0, checked daily) and *Failed agent turns over 15 in an
+hour* (`turn_finished` with `outcome = failed`, checked hourly; a normal hour has a few). Error
+tracking's own issue alerts (new, reopened, spiking) need a Slack or Discord destination.
+
## Metrics
Shared filters: `env = 'main'`, internal accounts excluded, UTC days. A *user* is a PostHog
diff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rs
index c02f4965..c5701e8d 100644
--- a/host/src/agent/acp.rs
+++ b/host/src/agent/acp.rs
@@ -3,7 +3,7 @@
//! newer adapter adding a variant never breaks parsing.
use crate::LockExt;
-use anyhow::{Context, Result, bail};
+use anyhow::{Context, Result};
use serde_json::{Value, json};
use std::collections::{HashMap, VecDeque};
use std::process::Stdio;
@@ -43,9 +43,49 @@ impl std::fmt::Display for RpcError {
impl std::error::Error for RpcError {}
+/// Whether an agent's error asks for signing in: ACP's code, or adapters that only say so.
+pub fn needs_sign_in(e: &anyhow::Error) -> bool {
+ let rpc = |c: &(dyn std::error::Error + 'static)| {
+ c.downcast_ref::<RpcError>()
+ .is_some_and(|r| r.code == AUTH_REQUIRED || r.message.to_lowercase().contains("auth"))
+ };
+ e.chain().any(rpc) || e.to_string().to_lowercase().contains("auth")
+}
+
+/// A way an agent fails that the host itself recognizes, kept as a type so usage
+/// analytics can count it (`turn_finished.error`) without its text.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum FailureKind {
+ /// No way to start the agent on this computer.
+ NotSetUp,
+ /// The agent stopped answering.
+ Timeout,
+ /// The agent process went away mid-request.
+ Exited,
+}
+
+#[derive(Debug)]
+pub struct Failure {
+ pub kind: FailureKind,
+ message: String,
+}
+
+impl Failure {
+ pub fn error(kind: FailureKind, message: impl Into<String>) -> anyhow::Error {
+ Self { kind, message: message.into() }.into()
+ }
+}
+
+impl std::fmt::Display for Failure {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.message)
+ }
+}
+
+impl std::error::Error for Failure {}
+
/// A request already written to the agent, waiting for its response.
pub struct Answer {
- method: String,
rx: oneshot::Receiver<std::result::Result<Value, Value>>,
}
@@ -61,7 +101,8 @@ impl Answer {
};
Err(RpcError { code: e["code"].as_i64().unwrap_or_default(), message }.into())
}
- Err(_) => bail!("{}: connection closed", self.method),
+ // The reader drops every waiter when the process goes away.
+ Err(_) => Err(Failure::error(FailureKind::Exited, "agent process exited")),
}
}
}
@@ -148,10 +189,8 @@ impl Acp {
_ => {}
}
}
- // Process gone: fail everyone still waiting.
- for (_, w) in pending.locked().drain() {
- let _ = w.send(Err(json!({"message": "agent process exited"})));
- }
+ // Process gone: dropping the waiters fails them as `FailureKind::Exited`.
+ pending.locked().clear();
let stderr_tail = tail.locked().iter().cloned().collect::<Vec<_>>().join("\n");
let _ = tx.send(Incoming::Closed { stderr_tail });
});
@@ -186,7 +225,7 @@ impl Acp {
let (tx, rx) = oneshot::channel();
self.pending.locked().insert(id, tx);
self.write(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})).await?;
- Ok(Answer { method: method.to_owned(), rx })
+ Ok(Answer { rx })
}
pub async fn notify(&self, method: &str, params: Value) -> Result<()> {
diff --git a/host/src/agent/backends.rs b/host/src/agent/backends.rs
index 034c72a4..a87d465e 100644
--- a/host/src/agent/backends.rs
+++ b/host/src/agent/backends.rs
@@ -7,7 +7,7 @@
//! back to the official ACP registry build (npx / uvx / downloaded binary).
use crate::LockExt;
-use crate::agent::{node, registry};
+use crate::agent::{acp, node, registry};
use crate::shell;
use serde_json::{Value, json};
use std::collections::HashSet;
@@ -687,7 +687,11 @@ pub async fn launch_candidates(id: &str, progress: impl Fn(&str)) -> anyhow::Res
}
if out.is_empty() {
let hint = h.map_or("Check that it's installed on this computer.", |h| h.setup);
- anyhow::bail!("{} isn't set up on this computer. {hint}", h.map_or(id, |h| h.name));
+ let name = h.map_or(id, |h| h.name);
+ return Err(acp::Failure::error(
+ acp::FailureKind::NotSetUp,
+ format!("{name} isn't set up on this computer. {hint}"),
+ ));
}
Ok(out)
}
diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rs
index 5310c9c2..d7fd7530 100644
--- a/host/src/agent/bot/queue.rs
+++ b/host/src/agent/bot/queue.rs
@@ -230,14 +230,14 @@ 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.report_turn(false, Some(e), "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:#}")));
// `{:#}` keeps the reason ("starting `npx …`: EACCES"), not just "agent process exited".
let mut msg = format!("Couldn't start the agent: {e:#}");
- if e.to_string().to_lowercase().contains("auth")
+ if crate::agent::acp::needs_sign_in(e)
&& let Some(h) = crate::agent::backends::harness(&self.cfg.backend)
{
msg = format!("{0} needs you to sign in. Open {0} in Marketplace to sign in.", h.name);
diff --git a/host/src/agent/bot/session.rs b/host/src/agent/bot/session.rs
index 2971cccf..4e91b6ab 100644
--- a/host/src/agent/bot/session.rs
+++ b/host/src/agent/bot/session.rs
@@ -300,7 +300,8 @@ impl Actor {
if let Some(c) = self.conn.take() {
c.acp.kill().await;
}
- bail!("the agent didn't answer {method} within {}s", SESSION_TIMEOUT.as_secs())
+ let message = format!("the agent didn't answer {method} within {}s", SESSION_TIMEOUT.as_secs());
+ Err(acp::Failure::error(acp::FailureKind::Timeout, message))
}
/// Memory failed to start: said once per actor, then the bot works without it.
@@ -411,7 +412,8 @@ pub(crate) async fn start_agent(command: &str, cwd: &str, env: &[(String, String
}
Err(_) => {
acp.kill().await;
- return Err(anyhow!("the agent didn't answer the ACP handshake within {}s", budget.as_secs()));
+ let message = format!("the agent didn't answer the ACP handshake within {}s", budget.as_secs());
+ return Err(acp::Failure::error(acp::FailureKind::Timeout, message));
}
};
let sessions = SessionCaps {
diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rs
index 6717d0e6..7c5e7ec5 100644
--- a/host/src/agent/bot/turn.rs
+++ b/host/src/agent/bot/turn.rs
@@ -245,8 +245,9 @@ impl Actor {
(_, "refusal") => self.notice("The agent declined to continue.", NoticeStyle::Info),
_ => {}
}
- let failed = done.is_err() && !self.stop_requested;
- self.report_turn(stopped, failed, &stop_reason);
+ let failure = done.as_ref().err().filter(|_| !self.stop_requested);
+ let failed = failure.is_some();
+ self.report_turn(stopped, failure, &stop_reason);
let reply = if stopped {
Err(anyhow!("recipient was stopped; partial work may have happened"))
} else if stop_reason != "end_turn" {
@@ -330,10 +331,10 @@ 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) {
+ pub(super) fn report_turn(&self, stopped: bool, failure: Option<&anyhow::Error>, stop_reason: &str) {
let outcome = if stopped {
TurnOutcome::Stopped
- } else if failed {
+ } else if failure.is_some() {
TurnOutcome::Failed
} else if stop_reason == "end_turn" {
TurnOutcome::Done
@@ -350,7 +351,8 @@ impl Actor {
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);
+ let ms = now_ms() - started;
+ analytics::turn_finished(&self.hub, &self.cfg.backend, outcome, stop_reason, failure, source, ms);
}
}
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index edae1c9c..9f54e64a 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -14,6 +14,8 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
+pub mod errors;
+
const KV_ENABLED: &str = "analytics_enabled";
/// The account the install id was last merged into (one `$identify` per account).
const KV_IDENTIFIED: &str = "analytics_identified";
@@ -48,6 +50,8 @@ pub enum Event {
RemoteScreenOpened,
ConnectorInstalled,
SkillInstalled,
+ /// Error tracking (`errors`): a panic or an uncaught error.
+ Exception,
}
impl Event {
@@ -73,6 +77,7 @@ impl Event {
Self::RemoteScreenOpened => "remote_screen_opened",
Self::ConnectorInstalled => "connector_installed",
Self::SkillInstalled => "skill_installed",
+ Self::Exception => "$exception",
}
}
@@ -90,6 +95,8 @@ pub struct Analytics {
enum Msg {
Event(Value),
+ /// A panic, captured off the panicking thread (`errors::report_panics`).
+ Report(errors::Report),
/// Send what's queued now and answer when done.
Flush(oneshot::Sender<()>),
}
@@ -194,8 +201,17 @@ pub enum TurnSource {
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) {
+/// `turn_finished`: the agent, how the turn ended, why it failed and how long it ran;
+/// never its text or the error's.
+pub fn turn_finished(
+ hub: &Hub,
+ agent: &str,
+ outcome: TurnOutcome,
+ stop_reason: &str,
+ failure: Option<&anyhow::Error>,
+ source: TurnSource,
+ ms: i64,
+) {
let outcome = match outcome {
TurnOutcome::Done => "done",
TurnOutcome::Stopped => "stopped",
@@ -215,10 +231,43 @@ pub fn turn_finished(hub: &Hub, agent: &str, outcome: TurnOutcome, stop_reason:
TurnSource::Group => "group",
TurnSource::Bot => "bot",
};
- let p = json!({"agent": agent, "outcome": outcome, "stop_reason": stop_reason, "source": source, "seconds": ms.max(0) / 1000});
+ let mut p = json!({"agent": agent, "outcome": outcome, "stop_reason": stop_reason, "source": source, "seconds": ms.max(0) / 1000});
+ if let Some(e) = failure {
+ let (kind, rpc_code) = failure_kind(e);
+ p["error"] = kind.into();
+ if let Some(code) = rpc_code {
+ p["rpc_code"] = code.into();
+ }
+ }
capture(hub, Event::TurnFinished, p.as_object().cloned().unwrap_or_default());
}
+/// Why a turn failed, as a category (plus the agent's JSON-RPC code): never the error's text,
+/// which can hold paths and agent output.
+fn failure_kind(e: &anyhow::Error) -> (&'static str, Option<i64>) {
+ use crate::agent::acp::{Failure, FailureKind, RpcError};
+ if let Some(f) = e.chain().find_map(|c| c.downcast_ref::<Failure>()) {
+ let kind = match f.kind {
+ FailureKind::NotSetUp => "not_installed",
+ FailureKind::Timeout => "timeout",
+ FailureKind::Exited => "exited",
+ };
+ return (kind, None);
+ }
+ if crate::agent::acp::needs_sign_in(e) {
+ return ("sign_in", None);
+ }
+ for cause in e.chain() {
+ if let Some(r) = cause.downcast_ref::<RpcError>() {
+ return ("agent_error", Some(r.code));
+ }
+ if let Some(io) = cause.downcast_ref::<std::io::Error>() {
+ return (if io.kind() == std::io::ErrorKind::NotFound { "not_installed" } else { "io" }, None);
+ }
+ }
+ ("other", None)
+}
+
/// `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>)> {
@@ -296,6 +345,7 @@ pub fn computer_tag(computer_id: &str) -> String {
/// Sends queued events in batches every `FLUSH_EVERY`; turning analytics off drops them.
pub fn start(hub: &Arc<Hub>) {
let Some(mut rx) = hub.analytics.rx.locked().take() else { return };
+ errors::report_panics(hub);
let hub = hub.clone();
tokio::spawn(async move {
let mut pending: Vec<Value> = Vec::new();
@@ -304,6 +354,7 @@ pub fn start(hub: &Arc<Hub>) {
tokio::select! {
msg = rx.recv() => match msg {
Some(Msg::Event(e)) => pending.push(e),
+ Some(Msg::Report(r)) => errors::capture_report(&hub, r),
Some(Msg::Flush(done)) => {
flush(&hub, &mut pending).await;
let _ = done.send(());
@@ -414,6 +465,24 @@ mod tests {
assert_eq!(computer_tag("AAECAwQFBgcICQoLDA0ODw"), "2d6878bee20aba04");
}
+ #[test]
+ fn a_failed_turn_names_its_kind_not_its_text() {
+ use crate::agent::acp::{Failure, FailureKind, RpcError};
+ use anyhow::Context as _;
+ let setup = Failure::error(FailureKind::NotSetUp, "Codex isn't set up on this computer.");
+ assert_eq!(failure_kind(&setup), ("not_installed", None));
+ let hung = Err::<(), _>(Failure::error(FailureKind::Timeout, "no answer")).context("starting");
+ assert_eq!(failure_kind(&hung.expect_err("failed")), ("timeout", None));
+ let missing = std::io::Error::new(std::io::ErrorKind::NotFound, "/Users/me/bin/agent");
+ let spawn = Err::<(), _>(missing).context("starting `/Users/me/bin/agent`");
+ assert_eq!(failure_kind(&spawn.expect_err("failed")), ("not_installed", None));
+ let auth = anyhow::Error::new(RpcError { code: -32000, message: "Authentication required".into() });
+ assert_eq!(failure_kind(&auth), ("sign_in", None));
+ let rpc = anyhow::Error::new(RpcError { code: -32603, message: "Internal error: /Users/me".into() });
+ assert_eq!(failure_kind(&rpc), ("agent_error", Some(-32603)));
+ assert_eq!(failure_kind(&anyhow::anyhow!("something else")), ("other", None));
+ }
+
#[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/analytics/errors.rs b/host/src/analytics/errors.rs
new file mode 100644
index 00000000..791d0a4e
--- /dev/null
+++ b/host/src/analytics/errors.rs
@@ -0,0 +1,237 @@
+//! Error tracking: panics and uncaught client errors as `PostHog` `$exception` events, sent with
+//! usage analytics (same switch, same identity). Never content: an error's message is dropped
+//! (a panic keeps only a literal written in the code), and a file path keeps only what lies
+//! inside the code base. What is collected: docs/features/analytics.md.
+
+use super::{Event, Msg, capture};
+use crate::hub::Hub;
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+use std::sync::Arc;
+
+/// Frames kept per exception, the ones nearest the error.
+const MAX_FRAMES: usize = 50;
+
+/// One exception: what `reportError` takes, and what goes out as `$exception`.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Report {
+ pub process: Process,
+ /// The error's type: `Panic`, `TypeError`, `RendererGone`, …
+ #[serde(rename = "type")]
+ pub kind: String,
+ /// How it was caught: `panic`, `onerror`, `unhandledrejection`, `render-process-gone`, …
+ pub mechanism: String,
+ /// A panic's literal message, or a reason the platform names (`oom`); never an error's text.
+ #[serde(default)]
+ pub value: String,
+ /// Oldest call first, the failing one last.
+ #[serde(default)]
+ pub frames: Vec<Frame>,
+}
+
+/// Where the exception happened.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Process {
+ Host,
+ Tui,
+ DesktopMain,
+ DesktopRenderer,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Frame {
+ pub function: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub file: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub line: Option<u32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub column: Option<u32>,
+}
+
+impl Report {
+ /// A panic at its location. Its message only when the code wrote it as a literal:
+ /// `unwrap` on an error or a formatted `expect` can carry runtime data.
+ // ponytail: no backtrace, release builds are stripped; upload debug symbols with
+ // `posthog-cli` and send instruction addresses if the panic site isn't enough.
+ pub fn panic(info: &std::panic::PanicHookInfo<'_>, process: Process) -> Self {
+ let value = info.payload().downcast_ref::<&'static str>().map(|s| (*s).to_owned()).unwrap_or_default();
+ let frames = info
+ .location()
+ .map(|l| Frame {
+ function: "panic".into(),
+ file: Some(l.file().into()),
+ line: Some(l.line()),
+ column: Some(l.column()),
+ })
+ .into_iter()
+ .collect();
+ Self { process, kind: "Panic".into(), mechanism: "panic".into(), value, frames }
+ }
+
+ /// The `$exception` properties (`PostHog`'s generic `custom` frames), with paths cut down.
+ fn properties(self) -> Map<String, Value> {
+ let lang = match self.process {
+ Process::Host | Process::Tui => "rust",
+ Process::DesktopMain | Process::DesktopRenderer => "javascript",
+ };
+ let skip = self.frames.len().saturating_sub(MAX_FRAMES);
+ let frames: Vec<Value> = self
+ .frames
+ .into_iter()
+ .skip(skip)
+ .map(|f| {
+ json!({
+ "platform": "custom",
+ "lang": lang,
+ "function": clip(&f.function, 200),
+ "filename": f.file.as_deref().map(code_path),
+ "lineno": f.line,
+ "colno": f.column,
+ "resolved": true,
+ "in_app": f.file.as_deref().is_some_and(in_app),
+ })
+ })
+ .collect();
+ let exception = json!({
+ "type": token(&self.kind, "Error"),
+ "value": clip(&self.value, 300),
+ "mechanism": {"type": token(&self.mechanism, "generic"), "handled": false, "synthetic": false},
+ "stacktrace": {"type": "raw", "frames": frames},
+ });
+ let level = if self.kind == "Panic" { "fatal" } else { "error" };
+ let process = serde_json::to_value(self.process).unwrap_or_default();
+ let p = json!({"$exception_list": [exception], "$exception_level": level, "process": process});
+ p.as_object().cloned().unwrap_or_default()
+ }
+}
+
+/// `reportError`: an exception this computer's own app or terminal UI caught.
+pub fn report(hub: &Hub, body: &Value) -> anyhow::Result<()> {
+ let report = Report::deserialize(body)?;
+ anyhow::ensure!(report.process != Process::Host, "unknown process");
+ capture(hub, Event::Exception, report.properties());
+ Ok(())
+}
+
+/// Reports the host's own panics: a panicking task or thread doesn't stop the host, so this
+/// is often the only sign of one.
+// ponytail: a panic that ends the process (the main thread) is lost with the queue; persist
+// it and send it on the next start if that ever shows up.
+pub fn report_panics(hub: &Arc<Hub>) {
+ let hub = Arc::downgrade(hub);
+ let previous = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ if let Some(hub) = hub.upgrade() {
+ // Captured by the analytics task: here it could wait on a lock the panic site holds.
+ let _ = hub.analytics.tx.send(Msg::Report(Report::panic(info, Process::Host)));
+ }
+ previous(info);
+ }));
+}
+
+/// Captures what `report_panics` queued.
+pub(super) fn capture_report(hub: &Hub, report: Report) {
+ capture(hub, Event::Exception, report.properties());
+}
+
+/// A frame's file without anything outside the code base: an absolute path (a home folder,
+/// an install location) keeps only its file name.
+fn code_path(file: &str) -> &str {
+ let path = file.split_once("://").map_or(file, |(_, rest)| rest);
+ let absolute = path.starts_with(['/', '\\']) || path.as_bytes().get(1) == Some(&b':');
+ if absolute { path.rsplit(['/', '\\']).next().unwrap_or(path) } else { path }
+}
+
+/// Codync's own code, not a dependency's or the runtime's.
+fn in_app(file: &str) -> bool {
+ let path = file.split_once("://").map_or(file, |(_, rest)| rest);
+ !(path.contains("node_modules") || file.starts_with("node:") || path.contains(".cargo") || path.contains("/rustc/"))
+}
+
+/// A type or mechanism name: identifier characters only.
+fn token(s: &str, fallback: &str) -> String {
+ let t: String = s.chars().filter(|c| c.is_ascii_alphanumeric() || "_.:-$".contains(*c)).take(80).collect();
+ if t.is_empty() { fallback.into() } else { t }
+}
+
+fn clip(s: &str, max: usize) -> String {
+ s.chars().take(max).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn paths_keep_only_the_code_base() {
+ assert_eq!(code_path("src/agent/acp.rs"), "src/agent/acp.rs");
+ assert_eq!(code_path("/Users/kevin/.cargo/registry/src/x/tokio-1.0/src/lib.rs"), "lib.rs");
+ assert_eq!(
+ code_path("file:///Users/kevin/Codync.app/Contents/Resources/app.asar/out/renderer/assets/index-a1.js"),
+ "index-a1.js"
+ );
+ assert_eq!(code_path(r"C:\Users\kevin\AppData\Local\Codync\resources\app.asar\out\main\index.js"), "index.js");
+ assert_eq!(code_path("file:///C:/Users/kevin/app.asar/out/renderer/index.js"), "index.js");
+ assert!(in_app("src/agent/acp.rs"));
+ assert!(!in_app("/Users/kevin/.cargo/registry/src/x/tokio-1.0/src/lib.rs"));
+ assert!(!in_app("node:internal/process/task_queues"));
+ }
+
+ #[test]
+ fn a_report_carries_no_content() {
+ let body = json!({
+ "process": "desktop-renderer",
+ "type": "TypeError <script>",
+ "mechanism": "onerror",
+ "frames": [
+ {"function": "render", "file": "file:///home/kevin/.mount_Codync/resources/app.asar/out/renderer/assets/index-a1.js", "line": 10, "column": 4},
+ {"function": "loadChat", "file": "file:///home/kevin/.mount_Codync/resources/app.asar/out/renderer/assets/index-a1.js", "line": 99, "column": 2},
+ ],
+ });
+ let p = Report::deserialize(&body).expect("a renderer report").properties();
+ let text = Value::Object(p.clone()).to_string();
+ assert!(!text.contains("kevin"), "{text}");
+ let e = &p["$exception_list"][0];
+ assert_eq!(e["type"], "TypeErrorscript");
+ assert_eq!(e["value"], "");
+ assert_eq!(e["stacktrace"]["frames"][1]["function"], "loadChat", "the failing frame stays last");
+ assert_eq!(e["stacktrace"]["frames"][1]["lang"], "javascript");
+ assert_eq!(p["process"], "desktop-renderer");
+ assert_eq!(p["$exception_level"], "error");
+ }
+
+ #[test]
+ fn only_the_host_reports_its_own_panics() {
+ assert!(Report::deserialize(&json!({"process": "host", "type": "Panic", "mechanism": "panic"})).is_ok());
+ assert!(Report::deserialize(&json!({"process": "phone", "type": "Panic", "mechanism": "panic"})).is_err());
+ }
+
+ #[test]
+ fn a_panic_keeps_its_site_and_only_a_literal_message() {
+ let caught = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let sink = caught.clone();
+ let previous = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ if let Ok(mut c) = sink.lock() {
+ c.push(Report::panic(info, Process::Tui));
+ }
+ }));
+ let secret = "/Users/kevin/secret.txt";
+ let _ = std::panic::catch_unwind(|| panic!("literal"));
+ let _ = std::panic::catch_unwind(|| panic!("formatted {secret}"));
+ std::panic::set_hook(previous);
+ let mut reports = std::mem::take(&mut *caught.lock().expect("not poisoned"));
+ // Other tests panic in parallel; only this file's panics are ours.
+ reports.retain(|r| r.frames.first().and_then(|f| f.file.as_deref()) == Some(file!()));
+ assert_eq!(reports.len(), 2);
+ assert_eq!(reports[0].value, "literal");
+ assert_eq!(reports[1].value, "", "a formatted message can carry runtime data");
+ let p = reports.into_iter().nth(1).expect("two reports").properties();
+ let frame = &p["$exception_list"][0]["stacktrace"]["frames"][0];
+ assert_eq!(frame["filename"], file!());
+ assert_eq!((frame["lang"].as_str(), frame["in_app"].as_bool()), (Some("rust"), Some(true)));
+ assert_eq!(p["$exception_level"], "fatal");
+ }
+}
diff --git a/host/src/api/devices.rs b/host/src/api/devices.rs
index a1985d05..76ebfdc9 100644
--- a/host/src/api/devices.rs
+++ b/host/src/api/devices.rs
@@ -39,6 +39,7 @@ const LOCAL_ONLY: &[&str] = &[
// Analytics is the computer owner's choice; phones decide only for themselves.
"setAnalytics",
"track",
+ "reportError",
// Voice keys are entered on the computer itself; phones only use them.
"setVoiceKey",
"pairing",
diff --git a/host/src/api/host.rs b/host/src/api/host.rs
index e18f527d..b62a0c95 100644
--- a/host/src/api/host.rs
+++ b/host/src/api/host.rs
@@ -162,6 +162,10 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
crate::analytics::track(hub, &b)?;
json!({})
}
+ "reportError" => {
+ crate::analytics::errors::report(hub, &b)?;
+ json!({})
+ }
"setScreenEnabled" => {
hub.screen.set_enabled(&hub.store, b["enabled"].as_bool().unwrap_or(false)).await?;
hub.screen.state()
diff --git a/host/src/remote/channel.rs b/host/src/remote/channel.rs
index dcbea32a..4e14cf14 100644
--- a/host/src/remote/channel.rs
+++ b/host/src/remote/channel.rs
@@ -755,6 +755,7 @@ mod tests {
"setScreenEnabled",
"setAnalytics",
"track",
+ "reportError",
"pairing",
"devices",
"revokeDevice",
diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rs
index ffb664e6..1bfa6b12 100644
--- a/host/src/tui/app/overlay_keys.rs
+++ b/host/src/tui/app/overlay_keys.rs
@@ -3,7 +3,7 @@
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::{Value, json};
-use super::super::manage::Reply;
+use super::super::manage::{AnalyticsSheet, Reply};
use super::{
ACTIONS, Action, After, AgentPicker, App, Bot, ConfirmAct, Dir, Editor, FILTERS, FolderPicker, Goto, GotoItem,
NEW_GROUP, Overlay, contains, fuzzy,
@@ -55,6 +55,7 @@ impl App {
Action::Usage => self.overlays.push(Overlay::Usage),
Action::CheckUpdate => self.call("checkHostUpdate", json!({}), After::Update),
Action::Analytics => self.toggle_analytics(),
+ Action::AboutAnalytics => self.overlays.push(Overlay::Analytics(AnalyticsSheet::default())),
Action::Keys => self.overlays.push(Overlay::Help(Editor::default())),
}
}
@@ -109,6 +110,7 @@ impl App {
Overlay::Agent(a) => self.agent_key(a, k),
Overlay::Fields(f) => self.fields_key(f, k),
Overlay::Skill(s) => self.skill_key(s, k),
+ Overlay::Analytics(s) => s.key(k),
o @ (Overlay::Usage | Overlay::Pair(_)) => {
if matches!(k.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q' | 'U' | 'P')) {
None
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index 08c8f2b7..87b39d9b 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -5,7 +5,7 @@ use std::collections::BTreeMap;
use std::time::Instant;
use super::super::manage::{
- AgentSetup, BotChatSheet, Fields, Market, MemorySheet, RoutineForm, RoutineList, SkillSheet,
+ AgentSetup, AnalyticsSheet, BotChatSheet, Fields, Market, MemorySheet, RoutineForm, RoutineList, SkillSheet,
};
use super::{Editor, Mark};
@@ -56,12 +56,13 @@ pub enum Action {
Usage,
CheckUpdate,
Analytics,
+ AboutAnalytics,
Keys,
}
pub const NEW_GROUP: &str = "New group chat";
-pub const ACTIONS: [(&str, &str, Action); 11] = [
+pub const ACTIONS: [(&str, &str, Action); 12] = [
("New bot…", "n", Action::NewBot),
("New group chat…", "m", Action::NewGroup),
("Extensions: agents, connectors, skills…", "A", Action::Market),
@@ -72,6 +73,7 @@ pub const ACTIONS: [(&str, &str, Action); 11] = [
("Usage", "U", Action::Usage),
("Check for updates", "", Action::CheckUpdate),
("Share usage analytics", "", Action::Analytics),
+ ("About usage analytics…", "", Action::AboutAnalytics),
("Keys", "?", Action::Keys),
];
@@ -258,6 +260,7 @@ pub enum Overlay {
Agent(AgentSetup),
Fields(Box<Fields>),
Skill(SkillSheet),
+ Analytics(AnalyticsSheet),
}
pub struct Toast {
diff --git a/host/src/tui/manage/analytics.rs b/host/src/tui/manage/analytics.rs
new file mode 100644
index 00000000..ea598156
--- /dev/null
+++ b/host/src/tui/manage/analytics.rs
@@ -0,0 +1,34 @@
+//! What sharing usage analytics covers: a read-only sheet beside the palette's switch.
+
+use std::cell::Cell;
+
+use crossterm::event::{KeyCode, KeyEvent};
+
+use super::super::app::Overlay;
+use super::ctrl;
+
+/// Scrolled from the top; the last draw sets the bounds.
+#[derive(Default)]
+pub struct AnalyticsSheet {
+ pub scroll: usize,
+ pub max_scroll: Cell<usize>,
+ pub page: Cell<usize>,
+}
+
+impl AnalyticsSheet {
+ pub(in crate::tui) fn key(mut self, k: KeyEvent) -> Option<Overlay> {
+ let max = self.max_scroll.get();
+ let half = (self.page.get() / 2).max(1);
+ match k.code {
+ KeyCode::Esc | KeyCode::Char('q') | KeyCode::Enter => return None,
+ KeyCode::Down | KeyCode::Char('j') => self.scroll = (self.scroll + 1).min(max),
+ KeyCode::Up | KeyCode::Char('k') => self.scroll = self.scroll.saturating_sub(1),
+ KeyCode::PageDown => self.scroll = (self.scroll + half).min(max),
+ KeyCode::PageUp => self.scroll = self.scroll.saturating_sub(half),
+ KeyCode::Char('d') if ctrl(k) => self.scroll = (self.scroll + half).min(max),
+ KeyCode::Char('u') if ctrl(k) => self.scroll = self.scroll.saturating_sub(half),
+ _ => {}
+ }
+ Some(Overlay::Analytics(self))
+ }
+}
diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rs
index 2203b1a1..1f98ef15 100644
--- a/host/src/tui/manage/mod.rs
+++ b/host/src/tui/manage/mod.rs
@@ -6,6 +6,7 @@
#![allow(clippy::many_single_char_names)]
mod agent;
+mod analytics;
mod bot_chat;
mod fields;
mod market;
@@ -14,6 +15,7 @@ mod replies;
mod routines;
mod skill;
+pub use analytics::AnalyticsSheet;
pub use memory::{MemoryMode, MemorySheet};
pub use routines::local_zone;
pub use skill::SkillSheet;
diff --git a/host/src/tui/mod.rs b/host/src/tui/mod.rs
index 478d4ad6..bd69c1a3 100644
--- a/host/src/tui/mod.rs
+++ b/host/src/tui/mod.rs
@@ -67,8 +67,10 @@ pub async fn run(url: String, token: Option<String>) -> Result<()> {
&& execute!(out, PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)).is_ok();
let _restore = Restore { enhanced };
let hook = std::panic::take_hook();
+ let reporter = client.clone();
std::panic::set_hook(Box::new(move |info| {
restore(enhanced);
+ reporter.report_panic(info);
hook(info);
}));
let mut term = Terminal::new(CrosstermBackend::new(out))?;
diff --git a/host/src/tui/net.rs b/host/src/tui/net.rs
index bcd28133..4c3ce8b7 100644
--- a/host/src/tui/net.rs
+++ b/host/src/tui/net.rs
@@ -88,6 +88,23 @@ impl Client {
if ok { Ok(v) } else { Err(v["error"].as_str().unwrap_or("The host refused that.").to_owned()) }
}
+ /// Sends a panic of this terminal UI to the host (`reportError`) before the process ends:
+ /// from a thread and runtime of its own, since the panicking thread may be driving this one.
+ pub fn report_panic(&self, info: &std::panic::PanicHookInfo<'_>) {
+ use crate::analytics::errors::{Process, Report};
+ let (Some(token), Ok(body)) = (self.token(), serde_json::to_value(Report::panic(info, Process::Tui))) else {
+ return;
+ };
+ let url = format!("{}/api/reportError", self.base);
+ let _ = std::thread::spawn(move || {
+ let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else { return };
+ let sent =
+ reqwest::Client::new().post(url).bearer_auth(token).json(&body).timeout(Duration::from_secs(3)).send();
+ let _ = rt.block_on(sent);
+ })
+ .join();
+ }
+
/// Runs a command in the background; the reply comes back as `Msg::Reply`.
pub fn spawn_call(&self, method: &'static str, body: Value, after: After, tx: UnboundedSender<Msg>) {
let c = self.clone();
diff --git a/host/src/tui/view/analytics.rs b/host/src/tui/view/analytics.rs
new file mode 100644
index 00000000..9f69d03c
--- /dev/null
+++ b/host/src/tui/view/analytics.rs
@@ -0,0 +1,68 @@
+//! The usage analytics sheet.
+
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::text::{Line, Span};
+
+use super::super::manage::AnalyticsSheet;
+use super::super::md;
+use super::buffer::{centered, frame_box, hline, put, put_line, u};
+use super::style::theme;
+
+/// What sharing usage analytics sends; the same text as the desktop app's and the iPhone's,
+/// true to the privacy policy.
+const DETAILS: [(&str, &str); 7] = [
+ (
+ "Features you use",
+ "Opening the app, creating or deleting a bot, sending a message (how many attachments, never the files), running a routine or a voice call, installing a connector. Each comes with the app version, the platform, and the bot's agent and model.",
+ ),
+ (
+ "Crashes and errors",
+ "When Codync crashes or an agent fails to answer: the kind of error and where in Codync's own code it happened. Never the error's message; file paths are cut down to Codync's own files.",
+ ),
+ (
+ "Approximate location",
+ "Country and city, looked up from your IP address. The IP address itself is never stored.",
+ ),
+ ("Who it belongs to", "Your Codync account when you're signed in, otherwise a random ID made on this device."),
+ (
+ "Never shared",
+ "Your messages, prompts, code, files, file names or paths, bot names, credentials, or anything your agents produce.",
+ ),
+ (
+ "How it's used",
+ "Only to spot bugs sooner and see which features work and where people get stuck. Never sold, never used for ads or to track you across other apps and websites.",
+ ),
+ (
+ "Your choice",
+ "Each iPhone and each computer has its own switch. Turning it off stops sending right away and drops anything not sent yet.",
+ ),
+];
+
+pub(super) fn analytics(buf: &mut Buffer, area: Rect, s: &AnalyticsSheet) {
+ let t = theme();
+ let r = centered(area, 72, area.height.saturating_sub(4).min(44));
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Usage analytics", t.text)));
+ if inner.height < 5 {
+ return;
+ }
+ hline(buf, inner.x, inner.bottom() - 2, inner.width, t.dim.patch(t.panel));
+ put(buf, inner.x, inner.bottom() - 1, inner.width, " ↑↓ scroll · esc close", t.dim.patch(t.panel));
+
+ let body = Rect::new(inner.x, inner.y, inner.width, inner.height - 2);
+ let width = usize::from(body.width);
+ let mut lines = Vec::new();
+ for (title, detail) in DETAILS {
+ lines.push(Line::from(Span::styled(format!(" {title}"), t.bold)));
+ lines.extend(md::wrap(&[Span::styled(detail, t.secondary)], width, &[Span::raw(" ")], &[Span::raw(" ")]));
+ lines.push(Line::default());
+ }
+ lines.push(Line::from(Span::styled(" Privacy policy: https://codync.dev/privacy", t.dim)));
+ let h = usize::from(body.height);
+ let max = lines.len().saturating_sub(h);
+ s.max_scroll.set(max);
+ s.page.set(h);
+ for (i, l) in lines.iter().skip(s.scroll.min(max)).take(h).enumerate() {
+ put_line(buf, body.x, body.y + u(i), body.width, l);
+ }
+}
diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rs
index 8f86fdc7..f1f0bf0d 100644
--- a/host/src/tui/view/help.rs
+++ b/host/src/tui/view/help.rs
@@ -9,7 +9,7 @@ use super::buffer::{centered, frame_box, put, u};
use super::overlay::field_line;
use super::style::theme;
-const HELP: [(&str, &str, &str); 55] = [
+const HELP: [(&str, &str, &str); 56] = [
("MOVE", "j k ↑ ↓", "next / previous bot"),
("MOVE", "[ ]", "previous / next bot"),
("MOVE", "1…9", "jump to bot 1–9"),
@@ -61,6 +61,7 @@ const HELP: [(&str, &str, &str); 55] = [
("VIEW", "U", "usage"),
("VIEW", "P", "pair a phone"),
("VIEW", "^k share", "share usage analytics on / off"),
+ ("VIEW", "^k about", "what usage analytics include"),
("VIEW", "esc", "close / go back"),
("VIEW", "q", "quit; bots keep going"),
("MOUSE", "click", "open, press a button"),
diff --git a/host/src/tui/view/mod.rs b/host/src/tui/view/mod.rs
index 5b4fd137..fe81fad1 100644
--- a/host/src/tui/view/mod.rs
+++ b/host/src/tui/view/mod.rs
@@ -6,6 +6,7 @@
// Drawing code reads best with x / y / w / t (theme) / r (rect).
#![allow(clippy::many_single_char_names, clippy::similar_names)]
+mod analytics;
mod bot_chat;
mod buffer;
mod chat;
diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rs
index 892a9cdd..bc6f7344 100644
--- a/host/src/tui/view/overlay.rs
+++ b/host/src/tui/view/overlay.rs
@@ -196,6 +196,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay
Overlay::Agent(a) => super::super::sheets::agent(buf, area, app, a),
Overlay::Fields(f) => super::super::sheets::fields(buf, area, f),
Overlay::Skill(s) => super::skill::skill(buf, area, app, s),
+ Overlay::Analytics(s) => super::analytics::analytics(buf, area, s),
}
}
diff --git a/web/app/privacy/page.tsx b/web/app/privacy/page.tsx
index 4f4242cb..d25b9143 100644
--- a/web/app/privacy/page.tsx
+++ b/web/app/privacy/page.tsx
@@ -33,6 +33,7 @@ export default function Privacy() {
</p>
<ul className="list-disc pl-5 space-y-2">
<li><strong>What we record:</strong> which features you use, such as opening the app, creating or deleting a bot, sending a message (with the number of attachments, not the files), starting a routine or a voice call, and installing a connector from the catalog. Each event carries the app version, the platform and the agent and model a bot uses.</li>
+ <li><strong>Crash and error reports:</strong> when an app crashes or hits an unexpected error, or an agent fails to answer, we record what kind of error it was and where in Codync&apos;s own code it happened (type, function names and line numbers). The error&apos;s message is never sent, and file paths are cut down to Codync&apos;s own files.</li>
<li><strong>What we never record:</strong> your messages, prompts, code, files, file names or paths, bot names, credentials or anything your agents produce. We don&apos;t store your IP address: it is only used to look up your approximate location (country and city), which is kept with the events.</li>
<li><strong>Who it&apos;s linked to:</strong> your Codync account when you&apos;re signed in; otherwise a random ID created on that device.</li>
<li><strong>Why:</strong> to spot bugs sooner and serve you better, by seeing which features work and where people get stuck. It is never sold, never shared for advertising and never used to track you across other apps or websites.</li>