Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat: readable iPhone crash reports and the steps before each error
leepokai47d5603df92a
diff --git a/.github/workflows/ios-dsyms.yml b/.github/workflows/ios-dsyms.ymlnew file mode 100644index 00000000..83e3442c--- /dev/null+++ b/.github/workflows/ios-dsyms.yml@@ -0,0 +1,45 @@+name: iOS dSYMs++# After Submit iOS, uploads the dSYMs from that release's Xcode Cloud archive to PostHog, so iPhone+# crash reports show function, file and line (tools/upload-dsyms.py). By hand: any version.+on:+ workflow_run:+ workflows: ["Submit iOS"]+ types: [completed]+ workflow_dispatch:+ inputs:+ version:+ description: "Version whose dSYMs to upload, e.g. 2.19.2"+ required: true++permissions:+ contents: read++jobs:+ upload:+ # A manual Submit iOS ran on a branch, not the release commit: run this by hand after it.+ if: github.event_name == 'workflow_dispatch' || github.event.workflow_run.event == 'push'+ # posthog-cli reads dSYMs with Xcode's dwarfdump.+ runs-on: macos-latest+ timeout-minutes: 150+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0+ - uses: actions/setup-python@v5+ with:+ python-version: "3.12"+ - run: pip install pyjwt cryptography+ - run: npm install -g @posthog/[email protected]+ - name: Upload dSYMs+ env:+ ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }}+ ASC_ISSUER_ID: ${{ secrets.ASC_ISSUER_ID }}+ ASC_PRIVATE_KEY: ${{ secrets.ASC_PRIVATE_KEY }}+ POSTHOG_CLI_API_KEY: ${{ secrets.POSTHOG_CLI_API_KEY }}+ POSTHOG_CLI_PROJECT_ID: "649427"+ VERSION: ${{ inputs.version }}+ RELEASE_SHA: ${{ github.event.workflow_run.head_sha }}+ run: |+ if [[ -n "$VERSION" ]]; then REF="v${VERSION#v}"; else REF="$RELEASE_SHA"; fi+ python3 tools/upload-dsyms.py "$REF"diff --git a/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt b/apps/android/app/src/main/kotlin/com/codync/android/Analytics.ktindex c3e82f62..717725f7 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt@@ -56,6 +56,7 @@ internal object Analytics {private var timer: Job? = nullprivate var sending = falseprivate var foreground = false+ private val session = AnalyticsSession()fun start(context: Context) {if (prefs != null) return@@ -114,8 +115,11 @@ internal object Analytics {private fun installId(stored: SharedPreferences): String = stored.getString("install", null)?: UUID.randomUUID().toString().also { stored.edit().putString("install", it).apply() }+ /** The current `$session_id`; a crash written down on another thread takes it along to the next launch. */+ fun sessionId(): String = session.id(System.currentTimeMillis())+private fun enqueue(name: String, distinctId: String, extra: Map<String, JsonElement>) {- pending += event(name, distinctId, Instant.now().toString(), extra)+ pending += event(name, distinctId, Instant.now().toString(), mapOf("\$session_id" to JsonPrimitive(sessionId())) + extra)if (pending.size > MAX_PENDING) repeat(pending.size - MAX_PENDING) { pending.removeAt(0) }if (pending.size >= BATCH_SIZE) flush() else scheduleFlush()}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSession.kt b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSession.ktnew file mode 100644index 00000000..7616b70e--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSession.kt@@ -0,0 +1,36 @@+package com.codync.android++import java.util.UUID++/**+ * `$session_id` (iOS `AnalyticsSession`): one id for a stretch of use, so an error's page in PostHog shows the+ * events that led up to it. A new one after 30 minutes without events or 24 hours in all, as PostHog's own SDKs do.+ */+internal class AnalyticsSession {+ private var id: String? = null+ private var started = 0L+ private var last = 0L++ /** The id for an event at [now] (ms); the first event after the last session ran out starts a new one. Any thread. */+ @Synchronized fun id(now: Long): String {+ val current = id+ if (current != null && now - last <= IDLE && now - started <= LONGEST) {+ last = now+ return current+ }+ return uuidV7(now).also { id = it; started = now; last = now }+ }++ companion object {+ private const val IDLE = 30 * 60 * 1000L+ private const val LONGEST = 24 * 60 * 60 * 1000L++ /** PostHog reads a session's start from its UUIDv7: milliseconds since 1970 in the first 48 bits. */+ private fun uuidV7(ms: Long): String {+ val random = UUID.randomUUID()+ val high = (ms shl 16) or 0x7000L or (random.mostSignificantBits and 0x0FFFL)+ val low = (random.leastSignificantBits and 0x3FFF_FFFF_FFFF_FFFFL) or Long.MIN_VALUE+ return UUID(high, low).toString()+ }+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CrashReports.kt b/apps/android/app/src/main/kotlin/com/codync/android/CrashReports.ktindex fa3542eb..ab702622 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/CrashReports.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/CrashReports.kt@@ -13,8 +13,8 @@ import kotlinx.serialization.json.put/*** Crashes as `$exception` events for PostHog Error Tracking (iOS `CrashReports`): an uncaught- * exception is written down as it happens and sent on the next launch, with the exception's type- * and frames but never its message.+ * exception is written down as it happens, with its session, and sent on the next launch, with the+ * exception's type and frames but never its message.*/internal object CrashReports {private const val MAX_FRAMES = 50@@ -29,7 +29,12 @@ internal object CrashReports {}val previous = Thread.getDefaultUncaughtExceptionHandler()Thread.setDefaultUncaughtExceptionHandler { thread, error ->- runCatching { if (Analytics.enabled) file.writeText(JsonObject(properties(error)).toString()) }+ runCatching {+ if (Analytics.enabled) {+ val session = "\$session_id" to JsonPrimitive(Analytics.sessionId())+ file.writeText(JsonObject(properties(error) + session).toString())+ }+ }previous?.uncaughtException(thread, error)}}diff --git a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.ktindex dd910baa..eeb09a9f 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt@@ -15,4 +15,21 @@ class AnalyticsTest {assert("IllegalStateException" in properties)assert("secret prompt text" !in properties)}++ @Test fun `a session ends after half an hour idle or a day in all`() {+ val session = AnalyticsSession()+ val t0 = 1_800_000_000_000L+ val minute = 60_000L+ val first = session.id(t0)+ // A UUIDv7 whose first 48 bits are its start in milliseconds.+ assertEquals("%012x".format(t0) + "7", first.replace("-", "").take(13))+ assertEquals(first, session.id(t0 + 29 * minute))+ val start = t0 + 60 * minute+ val second = session.id(start)+ assert(second != first) { "idle for 31 minutes" }+ // Busy without a break: a new one once it has run for a day.+ var t = start+ while (t <= start + 24 * 60 * minute) { assertEquals(second, session.id(t)); t += 20 * minute }+ assert(session.id(t) != second)+ }}diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swiftindex 46119511..cc72f63a 100644--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/Analytics.swift@@ -52,6 +52,7 @@ public final class Analytics {public static let enabledKey = "analyticsEnabled"private static let installKey = "analyticsInstallID"private static let identifiedKey = "analyticsIdentifiedUsers"+ private static let sessionKey = "analyticsSession"private static let batchSize = 20private static let maxPending = 500private static let flushDelay = Duration.seconds(30)@@ -64,10 +65,14 @@ public final class Analytics {private var timer: Task<Void, Never>?private var sending = falseprivate var foreground = false+ private var session = AnalyticsSession()+ /// The session the last launch ended in: where a crash MetricKit reports now happened.+ private let lastLaunchSession: String?init(defaults: UserDefaults = .standard, upload: @escaping @Sendable (Data) async -> Bool = Analytics.post) {self.defaults = defaultsself.upload = upload+ lastLaunchSession = defaults.string(forKey: Self.sessionKey)}public var isEnabled: Bool { defaults.object(forKey: Self.enabledKey) as? Bool ?? true }@@ -86,19 +91,29 @@ public final class Analytics {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 }+ record(name, extra, sessionID: currentSession())+ }++ /// A crash MetricKit reported from the last launch, in the session that launch ended in.+ func recordCrash(_ properties: [String: Value]) {+ guard isEnabled else { return }+ record("$exception", properties, sessionID: lastLaunchSession)+ }++ /// One event for the signed-in account (merging the install ID into it once), else the install ID.+ private func record(_ name: String, _ extra: [String: Value], sessionID: String?) {if let user = userID() {var identified = defaults.stringArray(forKey: Self.identifiedKey) ?? []if !identified.contains(user) {- enqueue("$identify", user, ["$anon_distinct_id": .string(installID)])+ enqueue("$identify", user, ["$anon_distinct_id": .string(installID)], sessionID)identified.append(user)defaults.set(identified, forKey: Self.identifiedKey)}- enqueue(name, user, extra)+ enqueue(name, user, extra, sessionID)} else {- enqueue(name, installID, extra)+ enqueue(name, installID, extra, sessionID)}}@@ -142,9 +157,17 @@ public final class Analytics {return id}- private func enqueue(_ name: String, _ distinctID: String, _ extra: [String: Value]) {+ /// Kept for the next launch, whose crash reports belong to it.+ private func currentSession() -> String {+ let id = session.id(at: .now)+ defaults.set(id, forKey: Self.sessionKey)+ return id+ }++ private func enqueue(_ name: String, _ distinctID: String, _ extra: [String: Value], _ sessionID: String?) {var properties = Self.common.merging(extra) { $1 }properties["$process_person_profile"] = .bool(true)+ properties["$session_id"] = sessionID.map(Value.string)pending.append(Event(event: name, distinct_id: distinctID,timestamp: Date.now.ISO8601Format(), properties: properties))if pending.count > Self.maxPending { pending.removeFirst(pending.count - Self.maxPending) }diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsSession.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsSession.swiftnew file mode 100644index 00000000..fcc80e45--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsSession.swift@@ -0,0 +1,33 @@+import Foundation++/// `$session_id`: one id for a stretch of use, so an error's page in PostHog shows the events+/// that led up to it. A new one after 30 minutes without events or 24 hours in all, as PostHog's+/// own SDKs do (the host's `analytics/session.rs`).+struct AnalyticsSession {+ private static let idle: TimeInterval = 30 * 60+ private static let longest: TimeInterval = 24 * 60 * 60+ private var current: (id: String, started: Date, last: Date)?++ /// The id for an event at `now`; the first event after the last session ran out starts a new one.+ mutating func id(at now: Date) -> String {+ if let s = current, now.timeIntervalSince(s.last) <= Self.idle, now.timeIntervalSince(s.started) <= Self.longest {+ current?.last = now+ return s.id+ }+ let id = Self.uuidV7(now).uuidString.lowercased()+ current = (id, now, now)+ return id+ }++ /// PostHog reads a session's start from its UUIDv7: milliseconds since 1970 in the first 48 bits.+ private static func uuidV7(_ date: Date) -> UUID {+ let ms = UInt64(date.timeIntervalSince1970 * 1000)+ var bytes = UUID().uuid+ withUnsafeMutableBytes(of: &bytes) { b in+ for i in 0..<6 { b[i] = UInt8(truncatingIfNeeded: ms >> (40 - 8 * i)) }+ b[6] = 0x70 | (b[6] & 0x0F)+ b[8] = 0x80 | (b[8] & 0x3F)+ }+ return UUID(uuid: bytes)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/CrashReports.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/CrashReports.swiftindex bfc6445c..e87cb63f 100644--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/CrashReports.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/CrashReports.swift@@ -3,7 +3,7 @@ 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.+/// and code addresses, never a message, reason or memory detail.public final class CrashReports: NSObject, MXMetricManagerSubscriber, Sendable {public static let shared = CrashReports()/// A SwiftUI update alone runs dozens of frames deep: fewer would cut off the app's own.@@ -21,50 +21,74 @@ public final class CrashReports: NSObject, MXMetricManagerSubscriber, Sendable {}guard !events.isEmpty else { return }Task { @MainActor in- events.forEach { Analytics.shared.record("$exception", $0) }+ events.forEach { Analytics.shared.recordCrash($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 (frames, images) = stack(callStack)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))]),+ "stacktrace": .object(["type": .string("raw"), "frames": .array(frames)]),]- return [+ var properties: [String: Analytics.Value] = ["$exception_list": .array([.object(exception)]),"$exception_level": .string("fatal"),"process": .string("ios"),"app_version": .string(appVersion),]+ if !images.isEmpty { properties["$debug_images"] = .array(images) }+ return properties}- /// The crashed thread's frames, oldest first and the crashing frame last (PostHog's order).- static func frames(_ callStack: Data) -> [Analytics.Value] {+ /// The crashed thread's frames as PostHog `apple` frames, oldest first and the crashing frame+ /// last (PostHog's order), and the binaries they ran in. PostHog symbolicates them with the+ /// dSYMs each release uploads (tools/upload-dsyms.py); a frame it can't resolve (the system's)+ /// keeps its `binary + offset` name.+ static func stack(_ callStack: Data) -> (frames: [Analytics.Value], images: [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 [] }+ let thread = 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+ var next = thread.callStackRootFrames.firstwhile let frame = next, walk.count < maxFrames {walk.append(frame)next = frame.subFrames?.first}- return walk.reversed().map { frame in+ var frames: [Analytics.Value] = []+ var images: [Analytics.Value] = []+ var loaded: Set<UInt64> = []+ for frame in walk.reversed() {let binary = frame.binaryName ?? "???"- return .object([- "platform": .string("custom"),- "lang": .string("swift"),- "function": .string("\(binary) + \(frame.offsetIntoBinaryTextSegment ?? 0)"),+ let offset = frame.offsetIntoBinaryTextSegment ?? 0+ var apple: [String: Analytics.Value] = [+ "platform": .string("apple"),+ "function": .string("\(binary) + \(offset)"),"module": .string(binary),- "resolved": .bool(false),"in_app": .bool(binary.hasPrefix("Codync")),- ])+ ]+ // Pointer authentication bits off (arm64e); the binary was loaded at address - offset.+ if let address = frame.address.map({ $0 & 0xF_FFFF_FFFF }), offset <= address {+ let base = address - offset+ apple["instruction_addr"] = .string(hex(address))+ apple["image_addr"] = .string(hex(base))+ // PostHog matches the dSYM by its UUID in this exact form (uppercase, dashed).+ if let uuid = frame.binaryUUID.flatMap(UUID.init(uuidString:)), loaded.insert(base).inserted {+ images.append(.object(["type": .string("macho"), "debug_id": .string(uuid.uuidString), "image_addr": .string(hex(base))]))+ }+ }+ frames.append(.object(apple))}+ return (frames, images)+ }++ private static func hex(_ address: UInt64) -> String {+ "0x" + String(address, radix: 16)}private struct Tree: Decodable {@@ -78,7 +102,9 @@ public final class CrashReports: NSObject, MXMetricManagerSubscriber, Sendable {private struct Frame: Decodable {let binaryName: String?- let offsetIntoBinaryTextSegment: Int?+ let binaryUUID: String?+ let address: UInt64?+ let offsetIntoBinaryTextSegment: UInt64?let subFrames: [Frame]?}diff --git a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swiftindex bd9bfa2a..5d17c7ec 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift@@ -49,8 +49,12 @@ import Testing@MainActor@Test func crashReportsSendNamesAndFramesButNoMessage() throws {// MetricKit's call-stack JSON: the root frame crashed, each first sub-frame is its caller.+ let loadedAt = ["Codync": 0x1_0480_0000, "SwiftUI": 0x1_8a00_0000, "CodyncKit": 0x1_0600_0000]+ let uuids = ["Codync": "d97c7f78-3fcc-389d-9047-deafc1d7bdc3", "SwiftUI": "11111111-2222-3333-4444-555555555555",+ "CodyncKit": "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"]func frame(_ binary: String, _ offset: Int, _ caller: String = "") -> String {- #"{"binaryName":"\#(binary)","offsetIntoBinaryTextSegment":\#(offset),"binaryUUID":"U","address":1,"sampleCount":1\#(caller.isEmpty ? "" : #","subFrames":[\#(caller)]"#)}"#+ let address = (loadedAt[binary] ?? 0) + offset+ return #"{"binaryName":"\#(binary)","offsetIntoBinaryTextSegment":\#(offset),"binaryUUID":"\#(uuids[binary] ?? "")","address":\#(address),"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)]}]}"#@@ -71,19 +75,27 @@ import Testing#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)])+ // PostHog symbolicates an address with the dSYM of the binary loaded at `image_addr`.+ #expect(frames.last == .object(["platform": .string("apple"), "function": .string("CodyncKit + 3"), "module": .string("CodyncKit"),+ "in_app": .bool(true), "instruction_addr": .string("0x106000003"), "image_addr": .string("0x106000000")]))+ // The binary's UUID as posthog-cli uploads it: uppercase.+ let image = { (name: String, at: String) in+ Analytics.Value.object(["type": .string("macho"), "debug_id": .string(uuids[name, default: ""].uppercased()), "image_addr": .string(at)])+ }+ #expect(p["$debug_images"] == .array([image("Codync", "0x104800000"), image("SwiftUI", "0x18a000000"), image("CodyncKit", "0x106000000")]))- // Unknown numbers fall back to generic names; nothing but names and offsets is sent.+ // Unknown numbers fall back to generic names; nothing but names and addresses 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":[]"#))+ #expect(encoded.contains(#""type":"Crash""#) && encoded.contains(#""frames":[]"#) && unknown["$debug_images"] == nil)- // A runaway stack keeps the 200 frames nearest the crash.+ // A runaway stack keeps the 200 frames nearest the crash, all in one binary.var deep = frame("Codync", 0)for i in 1...250 { deep = frame("Codync", i, deep) }- let capped = CrashReports.frames(Data(#"{"callStacks":[{"callStackRootFrames":[\#(deep)]}]}"#.utf8))- #expect(capped.count == 200)- #expect(capped.last == .object(["platform": .string("custom"), "lang": .string("swift"), "function": .string("Codync + 250"),- "module": .string("Codync"), "resolved": .bool(false), "in_app": .bool(true)]))+ let capped = CrashReports.stack(Data(#"{"callStacks":[{"callStackRootFrames":[\#(deep)]}]}"#.utf8))+ #expect(capped.frames.count == 200 && capped.images.count == 1)+ #expect(capped.frames.last == .object(["platform": .string("apple"), "function": .string("Codync + 250"), "module": .string("Codync"),+ "in_app": .bool(true), "instruction_addr": .string("0x1048000fa"), "image_addr": .string("0x104800000")]))// Recorded like any other event: off records nothing.let defaults = try #require(UserDefaults(suiteName: "CrashReportsTests-\(UUID())"))@@ -95,3 +107,43 @@ import Testinganalytics.record("$exception", p)#expect(analytics.pending.isEmpty)}++@MainActor+@Test func eventsShareASessionAndACrashGoesToTheLaunchItEnded() throws {+ let defaults = try #require(UserDefaults(suiteName: "AnalyticsSessionTests-\(UUID())"))+ // The first launch ever has no session to put a crash in.+ let first = Analytics(defaults: defaults) { _ in false }+ first.recordCrash([:])+ first.capture(.appOpened)+ first.capture(.voiceCallStarted)+ let sessions = first.pending.map { $0.properties["$session_id"] }+ #expect(sessions[0] == nil && sessions[1] != nil && sessions[1] == sessions[2])++ // The next launch starts its own session; a crash MetricKit reports then belongs to the last one.+ let next = Analytics(defaults: defaults) { _ in false }+ next.recordCrash([:])+ next.capture(.appOpened)+ #expect(next.pending[0].properties["$session_id"] == sessions[1])+ #expect(next.pending[1].properties["$session_id"] != sessions[1])+}++@Test func aSessionEndsAfterHalfAnHourIdleOrADayInAll() {+ var session = AnalyticsSession()+ let t0 = Date(timeIntervalSince1970: 1_800_000_000)+ let first = session.id(at: t0)+ // A UUIDv7 whose first 48 bits are its start in milliseconds.+ let hex = first.replacingOccurrences(of: "-", with: "")+ #expect(hex.prefix(12) == String(format: "%012llx", UInt64(1_800_000_000_000)) && Array(hex)[12] == "7")+ #expect(session.id(at: t0 + 29 * 60) == first)+ let start = t0 + 60 * 60+ let second = session.id(at: start)+ #expect(second != first, "idle for 31 minutes")++ // Busy without a break: a new one once it has run for a day.+ var t = start+ while t <= start + 24 * 3600 {+ #expect(session.id(at: t) == second)+ t += 20 * 60+ }+ #expect(session.id(at: t) != second)+}diff --git a/apps/ios/Resources/PrivacyInfo.xcprivacy b/apps/ios/Resources/PrivacyInfo.xcprivacyindex cc2e3f63..0cdac6b2 100644--- a/apps/ios/Resources/PrivacyInfo.xcprivacy+++ b/apps/ios/Resources/PrivacyInfo.xcprivacy@@ -21,7 +21,7 @@<string>NSPrivacyCollectedDataTypePurposeAnalytics</string></array></dict>- <!-- Crash reports (exception and signal names, binary + offset frames, no message) sent with usage analytics. -->+ <!-- Crash reports (exception and signal names, code addresses, no message) sent with usage analytics. --><dict><key>NSPrivacyCollectedDataType</key><string>NSPrivacyCollectedDataTypeCrashData</string>diff --git a/docs/README.md b/docs/README.mdindex ed1c3623..3bfa459b 100644--- a/docs/README.md+++ b/docs/README.md@@ -50,7 +50,7 @@ Source review, a passing build, local integration tests and production acceptanc- [Android parity and acceptance](plans/android-app.md)- [Harness memory](plans/harness-memory.md) (the switch that keeps a harness's own memory on; a choice of it instead of Codync's, planned)-- [Error tracking detail](plans/error-tracking-detail.md) (proposal: symbolicated iPhone crashes, sessions, consented problem reports)+- [Error tracking detail](plans/error-tracking-detail.md) (symbolicated iPhone crashes and sessions, built; consented problem reports, proposed)## Investigationsdiff --git a/docs/features/analytics.md b/docs/features/analytics.mdindex 5e0f61bd..6b9b1f29 100644--- a/docs/features/analytics.md+++ b/docs/features/analytics.md@@ -22,6 +22,12 @@ UI: *About usage analytics…*) shows the same promise in the app, in one text puser id. Otherwise a random install id (the host id on a computer, a UUID on the iPhone).The first signed-in event sends `$identify` with `$anon_distinct_id` so earlier events jointhe account.+- **Sessions.** Every event carries a `$session_id` (a UUIDv7) that changes after 30 minutes+ without events or 24 hours in all, as in PostHog's own SDKs, and on each launch of an app or+ start of the host (host `analytics/session.rs`, `AnalyticsSession` on the iPhone and Android),+ so an error's page shows the events that led up to it. Nothing is recorded for it beyond the+ events themselves. A crash reported on the next launch keeps the session it happened in, with+ the time it was reported.- **Location, never the IP.** The project's GeoIP transformation turns the sender's IP into anapproximate location (`$geoip_country_name`, `$geoip_city_name`, …), then the project's*Discard client IP data* drops the IP before storage.@@ -69,7 +75,8 @@ Besides `env`, `app_version`, `$os`, `$lib`:Crashes and uncaught errors go to PostHog Error Tracking as `$exception` events with the sameswitch, 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).+builds PostHog frames itself (oldest first, the failing one last): generic `custom` frames, or+`apple` frames on the iPhone.- **Host** (`host/src/analytics/errors.rs`): its own panics (a panic hook queues them for theanalytics task), and `reportError`, loopback only, for the computer's apps. Process `host`.@@ -83,16 +90,21 @@ builds PostHog's generic `custom` frames (oldest first, the failing one last).Processes `desktop-main`, `desktop-renderer`. The renderer is built unminified so functionnames 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`.+ launch, straight to PostHog with the version that crashed and the session it ended. Frames are+ code addresses with the binaries they ran in (`$debug_images`: each binary's UUID and load+ address). PostHog symbolicates them with the release's dSYMs, which the *iOS dSYMs* workflow+ uploads from its Xcode Cloud archive after *Submit iOS* (`tools/upload-dsyms.py`, secret+ `POSTHOG_CLI_API_KEY`: a personal API key with *error tracking write* on this project). A frame+ it can't resolve, such as the system's, shows `binary + offset`. Process `ios`.- **Android** (`CrashReports.kt`): an uncaught exception is written down as it happens and senton the next launch: its type and frames (class, method, file name, line), never the message.Process `android`.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+caught, function names, and file names and line numbers inside Codync's code (on the iPhone,+code addresses and binary UUIDs instead); 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 ahost panic is its location only.Alerts email the owner, from insights on the *Codync users* dashboard (production only): *Anydiff --git a/docs/guides/development.md b/docs/guides/development.mdindex 81401dfd..8eca6096 100644--- a/docs/guides/development.md+++ b/docs/guides/development.md@@ -126,4 +126,4 @@ To bump, set `version` in `host/crates/memory/Cargo.toml` (patch for fixes, mino## iOS releases (Xcode Cloud)-The Xcode Cloud workflow "Release" on the product "iOS" has no automatic start condition (its own tag trigger never fired); it only runs when started through the API, and it archives the `iOS` scheme in Release with deployment preparation **TestFlight and App Store** (the "Internal Testing Only" option produces builds App Review can't take) and uploads it to App Store Connect. Xcode Cloud overrides the build number with its own counter (`CI_BUILD_NUMBER`, configured under Xcode Cloud settings → Build Number in App Store Connect), so `CURRENT_PROJECT_VERSION` in `project.yml` is only the local default. The checked-in `apps/Codync.xcodeproj` is what the cloud builds: regenerate it whenever `project.yml` changes, and commit `apps/Codync.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved` whenever a package version changes (Xcode Cloud never resolves packages itself; copy `apps/ios/Kit/Package.resolved` there if Xcode wrote it to `apps/ios/Kit/`). Xcode Cloud reads public package repositories without any connection. The `Submit iOS` GitHub workflow (`.github/workflows/ios-submit.yml` → `tools/asc-submit.py`, secrets `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_PRIVATE_KEY`) runs on every `v*` tag (the tags Auto Tag pushes after a version bump on `main`). It compares the tag with the last version sent to the App Store: when nothing the iPhone app is built from changed (`apps/ios/` including `apps/ios/Kit/`, `apps/shared/`, the package pins, or `apps/project.yml` beyond its version lines), iOS skips that release, so host- or desktop-only releases neither build nor touch a version in review. Otherwise it starts the Xcode Cloud archive on the tag, waits for that build to finish processing and submits it for App Review, released automatically after approval. The latest version wins: a version still *Waiting for Review* is pulled back, renamed and resubmitted with the new build; one already *In Review* or approved is left alone (rerun the workflow with the version once it is out). *What's New* comes from the version's `## <version>` section in `apps/ios/WhatsNew.md` (one `### <locale>` per App Store language, written in the version bump); without one, the `### zh-Hant` / `### en-US` bullets under `## What's New` in the PR template are collected from every PR merged since the last App Store version (changes pushed to `main` without a PR add nothing); with neither, empty fields get a generic "Bug fixes and improvements" line. Running `Submit iOS` by hand with a version ships it even without iPhone changes. `python3 tools/asc-submit-test.py` checks the PR parsing and the change detection. `DRY_RUN=1 tools/asc-submit.py <version>` prints the writes without making them.+The Xcode Cloud workflow "Release" on the product "iOS" has no automatic start condition (its own tag trigger never fired); it only runs when started through the API, and it archives the `iOS` scheme in Release with deployment preparation **TestFlight and App Store** (the "Internal Testing Only" option produces builds App Review can't take) and uploads it to App Store Connect. Xcode Cloud overrides the build number with its own counter (`CI_BUILD_NUMBER`, configured under Xcode Cloud settings → Build Number in App Store Connect), so `CURRENT_PROJECT_VERSION` in `project.yml` is only the local default. The checked-in `apps/Codync.xcodeproj` is what the cloud builds: regenerate it whenever `project.yml` changes, and commit `apps/Codync.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved` whenever a package version changes (Xcode Cloud never resolves packages itself; copy `apps/ios/Kit/Package.resolved` there if Xcode wrote it to `apps/ios/Kit/`). Xcode Cloud reads public package repositories without any connection. The `Submit iOS` GitHub workflow (`.github/workflows/ios-submit.yml` → `tools/asc-submit.py`, secrets `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_PRIVATE_KEY`) runs on every `v*` tag (the tags Auto Tag pushes after a version bump on `main`). It compares the tag with the last version sent to the App Store: when nothing the iPhone app is built from changed (`apps/ios/` including `apps/ios/Kit/`, `apps/shared/`, the package pins, or `apps/project.yml` beyond its version lines), iOS skips that release, so host- or desktop-only releases neither build nor touch a version in review. Otherwise it starts the Xcode Cloud archive on the tag, waits for that build to finish processing and submits it for App Review, released automatically after approval. The latest version wins: a version still *Waiting for Review* is pulled back, renamed and resubmitted with the new build; one already *In Review* or approved is left alone (rerun the workflow with the version once it is out). *What's New* comes from the version's `## <version>` section in `apps/ios/WhatsNew.md` (one `### <locale>` per App Store language, written in the version bump); without one, the `### zh-Hant` / `### en-US` bullets under `## What's New` in the PR template are collected from every PR merged since the last App Store version (changes pushed to `main` without a PR add nothing); with neither, empty fields get a generic "Bug fixes and improvements" line. Running `Submit iOS` by hand with a version ships it even without iPhone changes. After each `Submit iOS` run, the `iOS dSYMs` workflow (`.github/workflows/ios-dsyms.yml` → `tools/upload-dsyms.py`, on macOS) downloads that release's archive from Xcode Cloud and uploads its dSYMs to PostHog (secret `POSTHOG_CLI_API_KEY`), so iPhone crash reports are symbolicated; run it by hand with a version after a manual `Submit iOS` or to upload an older one. `python3 tools/asc-submit-test.py` checks the PR parsing and the change detection. `DRY_RUN=1 tools/asc-submit.py <version>` prints the writes without making them.diff --git a/docs/investigations/posthog-errors-2026-10-19.md b/docs/investigations/posthog-errors-2026-10-19.mdindex 62581483..2729c4dd 100644--- a/docs/investigations/posthog-errors-2026-10-19.md+++ b/docs/investigations/posthog-errors-2026-10-19.md@@ -55,4 +55,5 @@ frames from `localhost:5173`) reports into the project with `env = main`. Its `d## Open- 10 and 11 need more detail than the reports carry; see [error tracking detail](../plans/error-tracking-detail.md).+ From 2.19.2 PostHog symbolicates iPhone crashes itself and every error carries its session.- 7: watch `agent_reason` and `rpc_code` on failed Claude turns after 2.19.1; bursts that remain with `rate_limit` or `overloaded` are the provider, not Codync.diff --git a/docs/plans/error-tracking-detail.md b/docs/plans/error-tracking-detail.mdindex 2adb53a1..e8037791 100644--- a/docs/plans/error-tracking-detail.md+++ b/docs/plans/error-tracking-detail.md@@ -1,7 +1,8 @@# Error tracking detail-Proposal, not built. What PostHog could record so a production error can be acted on without-asking the user, and what each step costs in privacy. Today's rules and payloads:+What PostHog could record so a production error can be acted on without asking the user, and+what each step costs in privacy. A1 and A2 are built (2.19.2); the rest is a proposal. Today's+rules and payloads:[usage analytics](../features/analytics.md#error-tracking). The 2026-10-19 triage that promptedthis: [PostHog error triage](../investigations/posthog-errors-2026-10-19.md) (two of its elevenfindings stayed unexplained for lack of detail).@@ -12,25 +13,31 @@ findings stayed unexplained for lack of detail).|---|---|---|| Host | Panic location (file and line) and a literal panic message; release builds are stripped, so no frames | Which code path led there; a formatted panic message (`failed printing to stderr: …`) is dropped || Desktop | Type, mechanism and readable frames (the renderer is built unminified) | A `DOMException` or a rejection has no stack, and no message is sent, so `NotFoundError` can't be placed |-| iPhone | MetricKit type, signal and `binary + offset` frames | Frames need a manual dSYM lookup per version |+| iPhone | MetricKit type, signal and code addresses, symbolicated by PostHog (A1) | — || Android | Type and frames (class, method, file, line) | — |-| All | Each error stands alone | No session: PostHog can't show what the person did just before (error tracking shows 0 sessions) |+| All | The session it happened in (A2) | — |The public promise (`web/app/privacy/page.tsx`, *Crash and error reports*) says an error's messageis never sent and paths are cut down to Codync's own files. Options A keep it; B and C change it.## A. More detail without changing the promise-1. **iPhone frames symbolicated by PostHog.** Send MetricKit frames as PostHog `apple` frames- (`instruction_addr`, `image_addr` = `address − offsetIntoBinaryTextSegment`, `module`, `in_app`)+1. **iPhone frames symbolicated by PostHog** (built, 2.19.2). Send MetricKit frames as PostHog+ `apple` frames (`instruction_addr`, `image_addr` = `address − offsetIntoBinaryTextSegment`,+ `module`, `in_app`)with an event-level `$debug_images` list (`debug_id` = the frame's `binaryUUID`, `image_addr`,- `type: macho`, `arch: arm64`). Upload each release's dSYMs from Xcode Cloud- (`ci_scripts/ci_post_xcodebuild.sh`, `posthog-cli` 0.7.7 or later, a personal API key with- *error tracking write* as an Xcode Cloud secret). PostHog then shows function, file and line- for every iPhone crash. Only addresses and binary UUIDs leave the device.-2. **A session per launch.** A `$session_id` (UUIDv7, new on each app launch and host start) on- every event lets PostHog's error page show the feature events that led up to an exception.- Those events are already sent; nothing new is recorded.+ `type: macho`). Each release's dSYMs are uploaded from its Xcode Cloud archive by the *iOS+ dSYMs* GitHub workflow after *Submit iOS* (`tools/upload-dsyms.py`, `posthog-cli` on macOS,+ a personal API key with *error tracking write* as the `POSTHOG_CLI_API_KEY` secret), rather+ than from an Xcode Cloud script: the secret stays in GitHub and an older version can be+ uploaded by hand. PostHog then shows function, file and line for every iPhone crash. Only+ addresses and binary UUIDs leave the device. The new frames group iPhone crashes into new+ issues from 2.19.2 on.+2. **Sessions** (built, 2.19.2). A `$session_id` (UUIDv7, new after 30 minutes without events or+ 24 hours, and on each launch of an app or start of the host) on every event lets PostHog's+ error page show the feature events that led up to an exception; an iPhone crash, reported on+ the next launch, goes in the session the crashed launch ended in. Those events are already+ sent; nothing new is recorded.3. **Context properties on `$exception`.** The screen or sheet that was open, the call engine, theconnection (direct or relay), the agent of the bot involved: catalog names, as other events carry.4. **Host frames.** The same server-side symbolication for the host: capture instruction addresses@@ -52,5 +59,5 @@ but UI in every client.## Recommendation-A1 and A2 first: the largest gain (readable iPhone crashes, the steps before every error) with no-change to the promise. Then C if a bug needs a message to be understood. Avoid B.+A1 and A2 first (done): the largest gain (readable iPhone crashes, the steps before every error)+with no change to the promise. Then C if a bug needs a message to be understood. Avoid B.diff --git a/host/Cargo.toml b/host/Cargo.tomlindex 2ec7e439..6880d2d9 100644--- a/host/Cargo.toml+++ b/host/Cargo.toml@@ -51,7 +51,7 @@ tokio-tungstenite = { version = "0.29", features = ["rustls-tls-webpki-roots"] }tracing = "0.1.44"tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }unicode-width = "0.2"-uuid = { version = "1.26.1", features = ["v4"] }+uuid = { version = "1.26.1", features = ["v4", "v7"] }x25519-dalek = { version = "3.0.0", features = ["static_secrets"] }zeroize = "1"diff --git a/host/src/analytics.rs b/host/src/analytics.rsindex f4989e68..d9b3f61d 100644--- a/host/src/analytics.rs+++ b/host/src/analytics.rs@@ -11,10 +11,11 @@ use anyhow::Result;use serde::Deserialize;use serde_json::{Map, Value, json};use std::sync::{Arc, Mutex};-use std::time::Duration;+use std::time::{Duration, SystemTime};use tokio::sync::{mpsc, oneshot};pub mod errors;+mod session;mod turns;pub use turns::{TurnOutcome, TurnSource, turn_finished};@@ -94,6 +95,7 @@ pub struct Analytics {enabled: Mutex<bool>,tx: mpsc::UnboundedSender<Msg>,rx: Mutex<Option<mpsc::UnboundedReceiver<Msg>>>,+ session: Mutex<session::Session>,}enum Msg {@@ -108,7 +110,7 @@ impl Analytics {pub fn load(store: &Store) -> Self {let enabled = store.kv_get(KV_ENABLED).as_deref() != Some("0");let (tx, rx) = mpsc::unbounded_channel();- Self { enabled: Mutex::new(enabled), tx, rx: Mutex::new(Some(rx)) }+ Self { enabled: Mutex::new(enabled), tx, rx: Mutex::new(Some(rx)), session: Mutex::default() }}pub fn state(&self) -> bool {@@ -233,6 +235,7 @@ fn queue(hub: &Hub, event: &str, distinct_id: &str, mut properties: Map<String,("arch".into(), std::env::consts::ARCH.into()),// Joins this computer's events across accounts and with its phones' `computer_paired`.("computer".into(), computer_tag(&hub.identity.computer_id()).into()),+ ("$session_id".into(), hub.analytics.session.locked().id(SystemTime::now()).to_string().into()),]);let _ = hub.analytics.tx.send(Msg::Event(json!({"event": event,diff --git a/host/src/analytics/session.rs b/host/src/analytics/session.rsnew file mode 100644index 00000000..08620df1--- /dev/null+++ b/host/src/analytics/session.rs@@ -0,0 +1,61 @@+//! `$session_id`: one id for a stretch of activity, so an error's page in `PostHog` shows the+//! events that led up to it. A new one after 30 minutes without events or 24 hours in all,+//! as `PostHog`'s own SDKs do, and on each start of the host.++use std::time::{Duration, SystemTime};+use uuid::Uuid;++const IDLE: Duration = Duration::from_secs(30 * 60);+const LONGEST: Duration = Duration::from_secs(24 * 60 * 60);++#[derive(Default)]+pub struct Session {+ /// The id, when it started and its last event. Wall-clock time, unlike `Instant`, also+ /// counts the hours a computer sleeps.+ current: Option<(Uuid, SystemTime, SystemTime)>,+}++impl Session {+ /// The id for an event at `now`; the first event after the last session ran out starts a new one.+ pub fn id(&mut self, now: SystemTime) -> Uuid {+ let since = |t: SystemTime| now.duration_since(t).unwrap_or_default();+ match &mut self.current {+ Some((id, started, last)) if since(*last) <= IDLE && since(*started) <= LONGEST => {+ *last = now;+ *id+ }+ _ => {+ // PostHog reads a session's start from its UUIDv7.+ let id = Uuid::now_v7();+ self.current = Some((id, now, now));+ id+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_session_ends_after_half_an_hour_idle_or_a_day_in_all() {+ let mut s = Session::default();+ let t0 = SystemTime::now();+ let first = s.id(t0);+ assert_eq!(first.get_version_num(), 7);+ let minutes = |m: u64| Duration::from_secs(m * 60);+ assert_eq!(s.id(t0 + minutes(29)), first, "still active");+ let start = t0 + minutes(60);+ let second = s.id(start);+ assert_ne!(second, first, "idle for 31 minutes");++ // Busy without a break: a new one once it has run for a day.+ let mut t = start;+ while t <= start + minutes(24 * 60) {+ assert_eq!(s.id(t), second);+ t += minutes(20);+ }+ assert_ne!(s.id(t), second);+ }+}diff --git a/tools/upload-dsyms.py b/tools/upload-dsyms.pynew file mode 100755index 00000000..11b57883--- /dev/null+++ b/tools/upload-dsyms.py@@ -0,0 +1,75 @@+#!/usr/bin/env python3+"""Upload an iPhone release's dSYMs to PostHog, so its crash reports show function, file and line.++Usage: upload-dsyms.py v2.19.2 (a release tag or its commit)+Env: ASC_KEY_ID, ASC_ISSUER_ID, ASC_PRIVATE_KEY (as asc-submit.py); POSTHOG_CLI_API_KEY (a personal+API key with error tracking write) and POSTHOG_CLI_PROJECT_ID for posthog-cli, which must be on PATH.+macOS only: posthog-cli reads dSYMs with Xcode's dwarfdump. Runs in a checkout with the release tags.++Finds the Xcode Cloud "Release" run on that commit, waits for it, downloads its archive and uploads+the dSYMs inside. A release that didn't build the iPhone app has no run and nothing to upload.+"""++import importlib.util+import subprocess+import sys+import tempfile+import urllib.request+import zipfile+from pathlib import Path++spec = importlib.util.spec_from_file_location("asc_submit", Path(__file__).with_name("asc-submit.py"))+asc = importlib.util.module_from_spec(spec)+spec.loader.exec_module(asc)+++def release_run(sha):+ """The newest Xcode Cloud "Release" run on `sha`, or None."""+ runs = asc.call("GET", f"/ciWorkflows/{asc.WORKFLOW_ID}/buildRuns?sort=-number&limit=30"+ "&fields[ciBuildRuns]=number,sourceCommit,executionProgress,completionStatus")["data"]+ return next((r for r in runs if (r["attributes"].get("sourceCommit") or {}).get("commitSha") == sha), None)+++def archive_url(run_id):+ """Where the run's .xcarchive (zipped) can be downloaded."""+ for action in asc.call("GET", f"/ciBuildRuns/{run_id}/actions")["data"]:+ for artifact in asc.call("GET", f"/ciBuildActions/{action['id']}/artifacts")["data"]:+ if artifact["attributes"]["fileType"] == "ARCHIVE":+ return asc.call("GET", f"/ciArtifacts/{artifact['id']}")["data"]["attributes"]["downloadUrl"]+ sys.exit(f"Xcode Cloud run {run_id} has no archive")+++def main(ref):+ sha = asc.git("rev-list", "-n", "1", ref)+ if not sha:+ sys.exit(f"{ref} isn't a commit in this checkout")+ run = release_run(sha)+ if not run:+ print(f"no Xcode Cloud archive of {ref} among the latest 30; nothing to upload")+ return+ number = run["attributes"]["number"]++ def finished():+ attributes = asc.call("GET", f"/ciBuildRuns/{run['id']}")["data"]["attributes"]+ return attributes if attributes["executionProgress"] == "COMPLETE" else None++ status = asc.wait_for(f"Xcode Cloud build {number}", finished, 120)["completionStatus"]+ if status != "SUCCEEDED":+ sys.exit(f"Xcode Cloud build {number} {status.lower()}; no dSYMs to upload")++ with tempfile.TemporaryDirectory() as tmp:+ archive = Path(tmp, "archive.zip")+ urllib.request.urlretrieve(archive_url(run["id"]), archive)+ dsyms = Path(tmp, "dSYMs")+ with zipfile.ZipFile(archive) as z:+ z.extractall(dsyms, [n for n in z.namelist() if ".dSYM/" in n])+ names = sorted(p.name for p in dsyms.rglob("*.dSYM"))+ if not names:+ sys.exit(f"Xcode Cloud build {number}'s archive has no dSYMs")+ print(f"uploading the dSYMs of {ref} (Xcode Cloud build {number}): {', '.join(names)}", flush=True)+ # posthog-cli finds every .dSYM bundle under the directory.+ subprocess.run(["posthog-cli", "dsym", "upload", "--directory", str(dsyms)], check=True)+++if __name__ == "__main__":+ main(sys.argv[1])