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.

21.4 KB
Raw Blame
import CodyncKit
import CodyncUI
import SwiftUI
import Observation
import UserNotifications
import WidgetKit

@main
struct CodyncApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) private var delegate
    @State private var app = AppStore.shared
    /// What the App Store has: greys out an update it doesn't have yet, reminds of newer ones.
    @State private var updates = AppUpdates()
    @Environment(\.scenePhase) private var scenePhase
    @AppStorage(Appearance.storageKey) private var appearance = Appearance.system
    @AppStorage("onboardingCompleted") private var onboardingCompleted = false
    @AppStorage(AppLanguage.storageKey, store: AppLanguage.defaults) private var appLanguageRaw = AppLanguage.system.rawValue
    /// Cold launch with a computer to reach: the splash covers its connect and catch-up. Not over the sign-in
    /// screen, where signed-out computers wait to move into the account.
    @State private var launching = !AppStore.shared.accounts.computers.isEmpty
        && (AppStore.shared.accounts.accountId != nil || !AppStore.shared.account.isConfigured)
    init() {
        // A tapped widget bot arrives as an intent, not a URL.
        OpenBotIntent.open = { AppStore.shared.open($0) }
        MuteCallIntent.run = { CallActivity.toggleMute(botId: $0) }
        EndCallIntent.run = { CallActivity.hangUp(botId: $0) }
    }

    var body: some Scene {
        WindowGroup {
            RootView()
                .id("\(app.contextID)#\(app.generation)")
                .environment(app)
                .environment(app.accounts)
                .environment(app.account)
                .environment(\.customIconAccount, CustomIconAccount(
                    signedIn: app.account.isSignedIn, loading: app.account.isBusy || !app.account.isReady,
                    error: app.account.errorMessage,
                    signIn: { provider in Task { await app.account.signIn(provider: provider) } }))
                // A computer needs a newer app: its App Store page has the Update button.
                .environment(\.appUpdate, AppUpdateAction {
                    Analytics.shared.capture(.linkOpened(.appStore))
                    UIApplication.shared.open(AppStoreRelease.page)
                })
                .environment(updates)
                .tint(Palette.accent)
                .background(AppearanceWindow(appearance: appearance).frame(width: 0, height: 0))
                .environment(\.locale, AppLanguage.locale(
                    preference: AppLanguage(rawValue: appLanguageRaw) ?? .system,
                    systemIsChinese: AppLanguage.systemIsChinese()))
                .onChange(of: appLanguageRaw) { _, _ in WidgetCenter.shared.reloadAllTimelines() }
                // No scroll indicators anywhere in the app.
                .scrollIndicators(.never)
                .codyncSheet(isPresented: Binding(
                    get: { (onboardingCompleted || app.account.isSignedIn) && app.account.showSwitcher },
                    set: { app.account.showSwitcher = $0 }
                )) {
                    AccountSwitcherView()
                        .environment(app)
                        .environment(app.accounts)
                        .environment(app.account)
                        .tint(Palette.accent)
                }
                .onChange(of: app.account.userID, initial: true) { _, userID in
                    app.switchAccount(to: userID)
                }
                .overlay {
                    if launching {
                        LaunchSplash(stores: app.accounts.computers.compactMap { app.accounts.store(for: $0.id) }) {
                            withAnimation(.easeOut(duration: 0.35)) { launching = false }
                        }
                    }
                }
                .onOpenURL { url in app.open(url) }
                .onChange(of: scenePhase, initial: true) { _, phase in
                    switch phase {
                    case .active: Analytics.shared.becameActive()
                    case .background: BackgroundTime.run("Analytics") { await Analytics.shared.enteredBackground() }
                    default: break
                    }
                    // Only leaving for the background disconnects; `.inactive` (Control Center,
                    // app switcher, system prompts) comes and goes too often to drop the link.
                    app.accounts.setActive(phase != .background)
                    // Back in the app: a computer may have joined the account meanwhile.
                    if phase == .active {
                        Task { await app.accounts.refreshCloud() }
                        Task { await updates.refresh() }
                    }
                }
                #if DEBUG
                .task {
                    // Simulator/UI-test pairing: SIMCTL_CHILD_CODYNC_PAIR_URL=codync://pair?...
                    if let s = ProcessInfo.processInfo.environment["CODYNC_PAIR_URL"], let p = Pairing(string: s) {
                        _ = try? await app.pair(p, via: .link)
                    }
                    if ProcessInfo.processInfo.environment["CODYNC_OPEN_USAGE"] != nil { app.tab = .state; app.showUsage = true }
                    if ProcessInfo.processInfo.environment["CODYNC_STATE_SURFACE"] != nil { app.tab = .state }
                    // Screenshots: CODYNC_OPEN_URL=codync://bot/<botId>?scope=local&computer=<id>, without the system prompt.
                    if let s = ProcessInfo.processInfo.environment["CODYNC_OPEN_URL"], let url = URL(string: s) {
                        try? await Task.sleep(for: .seconds(1))
                        app.open(url)
                    }
                    await LiveActivities.shared.previewIfRequested()
                    if ProcessInfo.processInfo.environment["CODYNC_OPEN_SCREEN"] != nil {
                        try? await Task.sleep(for: .seconds(2))
                        app.currentStore?.screenRequest = ScreenRequest()
                    }
                }
                #endif
        }
    }
}

enum AppTab: Hashable { case bots, state, settings }

/// One `AccountStore` per account context: switching accounts retires the old one so
/// in-flight work can't land on another user's screen or storage.
@MainActor
@Observable
final class AppStore {
    static let shared = AppStore()
    let account: AccountSession
    private(set) var accounts: AccountStore
    /// The signed-in account's cloud; nil when signed out or the build has no cloud.
    private(set) var cloud: CloudClient?
    private(set) var contextID: String
    /// Bumped by Start over so the whole UI is rebuilt, even though the local context keeps its id.
    private(set) var generation = 0
    var tab = AppTab.bots
    var showComputers = false
    /// The usage limits sheet over the State tab.
    var showUsage = false
    /// The computer whose marketplace is open.
    var marketplace: ComputerID?
    /// While an account is being left: its stores stay open until its computers have been told.
    var leaving = false

    private init() {
        let session = AccountSession()
        // Keep the selected context while Clerk restores: background intents have no scene observer yet.
        let storage = SharedStore.Context(accountID: session.isReady ? session.userID : SharedStore.activeAccountID)
        SharedStore.activeAccountID = storage.accountID
        account = session
        Analytics.shared.userID = { [session] in session.userID }
        Analytics.shared.foregroundState = {
            let allowed = await PushRegistrar.shared.isAllowed()
            // Unreadable (WidgetKit's error carries nothing to act on): `app_opened` leaves the count out.
            let widgets = try? await WidgetCenter.shared.currentConfigurations().count
            return (allowed.map { $0 ? .allowed : .denied } ?? .notAsked, widgets)
        }
        CrashReports.shared.start()
        contextID = storage.id
        let rescan = Self.adoptSignedOutPairings(into: storage)
        // Accounts Clerk hasn't restored by launch keep their computers' push on.
        SharedStore.Context.splitPushSwitch(from: .standard,
                                            into: Set([nil, storage.accountID] + session.accounts.map(\.id)).map { SharedStore.Context(accountID: $0) })
        (accounts, cloud) = Self.makeAccounts(storage, session: session)
        if rescan { accounts.lastError = Self.scanAgain }
    }

    var storage: SharedStore.Context { accounts.storage }

    /// The computer the Usage tab, widgets and "open screen" links act on: the last active one.
    var currentStore: BotStore? {
        accounts.storage.lastComputerId.flatMap(accounts.store(for:)) ?? accounts.computers.first.flatMap { accounts.store(for: $0.id) }
    }

    func switchAccount(to userID: String?) {
        let storage = SharedStore.Context(accountID: userID)
        guard storage.id != contextID, !leaving else { return }
        accounts.retire()
        PushRegistrar.shared.deactivate()
        LiveActivities.shared.endAll()
        let rescan = Self.adoptSignedOutPairings(into: storage)
        SharedStore.activeAccountID = userID
        storage.bots = []
        contextID = storage.id
        tab = .bots
        showComputers = false
        marketplace = nil
        (accounts, cloud) = Self.makeAccounts(storage, session: account)
        if rescan { accounts.lastError = Self.scanAgain }
        BotsWidgetFeed.reset()
        WidgetCenter.shared.reloadAllTimelines()
    }

    /// Settings → Start over: signs out of every account and forgets every computer, key and cache
    /// on this iPhone, then shows the welcome again. The computers keep their bots and chats.
    func startOver() async {
        // The open account's computers and cloud drop this iPhone; every account's keys go regardless, those signed
        // out here too (signing out keeps them).
        await handBack(cloud: cloud)
        await account.signOutAll()
        accounts.retire()
        PushRegistrar.shared.deactivate()
        LiveActivities.shared.endAll()
        SharedStore.eraseAll()
        let storage = SharedStore.Context(accountID: nil)
        storage.bots = []
        SharedStore.activeAccountID = nil
        UserDefaults.standard.set(false, forKey: "onboardingCompleted")
        UserDefaults.standard.set(false, forKey: "withoutAccount")
        showComputers = false
        account.showSwitcher = false
        marketplace = nil
        tab = .bots
        contextID = storage.id
        (accounts, cloud) = Self.makeAccounts(storage, session: account)
        generation += 1
        BotsWidgetFeed.reset()
        WidgetCenter.shared.reloadAllTimelines()
    }

    /// A scanned, pasted or opened pairing link, or a short code typed from the computer, which the cloud
    /// turns into its link; one that can't be read is recorded before it's shown.
    func pairing(from text: String) async throws -> Pairing {
        do {
            guard let code = Pairing.shortCode(text) else { return try Pairing.parse(text) }
            guard let cloud else { throw AccountStore.signInForShortCode }
            return try Pairing.parse(try await cloud.pairingLink(code: code))
        } catch {
            throw pairingFailed(error)
        }
    }

    /// `via`: `qr` scanned or pasted here, `link` opened from the Camera app.
    func pair(_ pairing: Pairing, via: AnalyticsEvent.PairVia) async throws -> Computer {
        do {
            let computer = try await accounts.pair(pairing, deviceName: UIDevice.current.name, platform: "ios")
            Analytics.shared.capture(.computerPaired(via: via, computer: computer.id))
            return computer
        } catch {
            throw pairingFailed(error)
        }
    }

    /// Records why pairing failed (nothing when it was called off) and hands the error on.
    private func pairingFailed(_ error: any Error) -> any Error {
        if let reason = AnalyticsEvent.PairingFailure(error) { Analytics.shared.capture(.pairingFailed(reason)) }
        return error
    }

    func open(_ url: URL) {
        if url.scheme == Bundle.main.bundleIdentifier {
            Task { await account.handle(url) }
            return
        }
        guard url.scheme == AppEnvironment.current.urlScheme else { return }
        switch url.host() {
        case "pair":
            // Scanned with the Camera app: pair right away.
            let accounts = accounts
            Task {
                do { _ = try await pair(try await pairing(from: url.absoluteString), via: .link) } catch { accounts.lastError = error.localizedDescription }
            }
        case "bot":
            guard let ref = storage.reference(from: url), accounts.store(for: ref.computerId) != nil else { return }
            tab = .bots
            accounts.selection = ref
        case "plugins":
            accounts.selection = nil
            tab = .bots
            marketplace = currentStore?.computer.id
        case "usage":
            accounts.selection = nil
            tab = .state
            showUsage = true
        case "computers":
            accounts.selection = nil
            tab = .bots
            showComputers = true
        case "screen":
            currentStore?.screenRequest = ScreenRequest()
        default:
            break
        }
    }

    private static func makeAccounts(_ storage: SharedStore.Context, session: AccountSession) -> (AccountStore, CloudClient?) {
        let identity = storage.accountID == nil ? nil : try? DeviceIdentity.load(context: storage)
        let cloud = session.cloudClient(for: storage.accountID, identity: identity)
        let accounts = AccountStore(storage: storage, cloud: cloud)
        accounts.onConnected = { store in
            PushRegistrar.shared.syncDevice(with: store)
            store.onUsageChanged = { _, _ in WidgetCenter.shared.reloadTimelines(ofKind: "CodyncUsage") }
        }
        accounts.onBotUpdated = { ref, bot in LiveActivities.shared.update(ref, bot: bot) }
        accounts.onRosterChanged = { roster in
            BotsWidgetFeed.update(roster, storage: storage)
            if roster.isEmpty {
                LiveActivities.shared.endAll()
                WidgetCenter.shared.reloadAllTimelines()
            }
        }
        accounts.onSent = { [weak accounts] ref, bot, progress in
            guard let store = accounts?.store(for: ref.computerId) else { return }
            LiveActivities.shared.sent(ref, bot: bot, progress: progress, store: store)
        }
        // Signed in: make this iPhone known to the account, then list its computers.
        if cloud != nil { Task { [weak accounts] in await accounts?.refreshCloud() } }
        return (accounts, cloud)
    }

    /// Takes back this iPhone's account access to a computer (its grant), and forgets the computer here.
    /// Also the way out when an earlier install was approved but this one never checked the code.
    func revokeAccess(_ id: ComputerID) async {
        guard let cloud else { return }
        let accounts = accounts
        do {
            try await cloud.revokeDeviceAccess(id)
            accounts.forget(id)
            await accounts.refreshCloud()
        } catch {
            accounts.lastError = error.localizedDescription
        }
    }

    /// Forgets a computer here. Approved through the account, its grant goes too, or it would come
    /// straight back as an account row; a failed revoke (offline) still forgets it, and its error says
    /// why the grant stayed.
    func removeComputer(_ id: ComputerID) async {
        let accounts = accounts
        if accounts.cloudComputers.first(where: { $0.computerId == id })?.isGranted == true { await revokeAccess(id) }
        // A revoke that went through forgot it already.
        if accounts.computers.contains(where: { $0.id == id }) { accounts.forget(id) }
    }

    /// A computer's push switch: saved here, then the computer is told to alert this iPhone or to stop.
    func setNotifications(_ id: ComputerID, _ on: Bool) {
        accounts.setNotifications(id, on)
        if let store = accounts.store(for: id) { PushRegistrar.shared.syncDevice(with: store) }
        Analytics.shared.capture(.settingChanged(.push, on: on))
    }
}

final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        UNUserNotificationCenter.current().delegate = self
        let open = UNNotificationAction(identifier: "openConversation", title: "Open conversation", options: [.foreground])
        let review = UNNotificationAction(identifier: "reviewRequest", title: "Review request", options: [.foreground])
        UNUserNotificationCenter.current().setNotificationCategories([
            UNNotificationCategory(identifier: "done", actions: [open], intentIdentifiers: []),
            UNNotificationCategory(identifier: "needsInput", actions: [review], intentIdentifiers: []),
            UNNotificationCategory(identifier: "failed", actions: [open], intentIdentifiers: []),
        ])
        #if DEBUG
        PushRegistrar.shared.verifyDeliveryIfRequested()
        #endif
        return true
    }

    /// Portrait, except while the screen viewer is open.
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        OrientationLock.mask
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Task { @MainActor in PushRegistrar.shared.didRegister(token: deviceToken) }
    }

    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
                                          withCompletionHandler completionHandler: @escaping @Sendable () -> Void) {
        let info = response.notification.request.content.userInfo
        let ctx = info["ctx"] as? String
        let computerId = info["computerId"] as? String
        let botId = info["botId"] as? String
        let kind = AnalyticsEvent.NotificationKind(category: response.notification.request.content.categoryIdentifier)
        // UIKit saves application state from this completion. The async delegate
        // bridge can complete off the main thread even after MainActor.run.
        Task { @MainActor in
            defer { completionHandler() }
            if let kind { Analytics.shared.capture(.notificationOpened(kind)) }
            guard let ctx, let computerId, let botId else { return }
            // Only open it in the account it was sent to, on a computer that account still has.
            let accounts = AppStore.shared.accounts
            guard ctx == accounts.storage.id, accounts.store(for: computerId) != nil else { return }
            AppStore.shared.tab = .bots
            accounts.selection = BotReference(accountId: accounts.accountId, computerId: computerId, botId: botId)
        }
    }

    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
        // The chat already shows it live.
        []
    }
}

/// Background time for work that has to finish after the app leaves the screen (the analytics
/// batch); without it iOS suspends the app with the work half done.
@MainActor
private final class BackgroundTime {
    private var id = UIBackgroundTaskIdentifier.invalid

    static func run(_ name: String, _ work: @escaping @MainActor @Sendable () async -> Void) {
        let time = BackgroundTime()
        let task = Task { await work() }
        // Out of time: give the work up rather than have iOS end the app for overrunning.
        time.id = UIApplication.shared.beginBackgroundTask(withName: name) { task.cancel(); time.end() }
        Task { await task.value; time.end() }
    }

    private func end() {
        guard id != .invalid else { return }
        UIApplication.shared.endBackgroundTask(id)
        id = .invalid
    }
}

/// Keeps the Bots widget's snapshot current; asks WidgetKit to redraw only when
/// something the widget shows changes (who is working / needs you / unread).
@MainActor
enum BotsWidgetFeed {
    private struct Snapshot: Equatable {
        let computerId: ComputerID
        let id: String
        let name: String
        let shape: String
        let color: String
        let status: String
        let activity: String
        let message: String?
        let lastAt: Int64

        init(_ bot: Bot, computerId: ComputerID) {
            self.computerId = computerId
            id = bot.id; name = bot.name; shape = bot.avatarShape; color = bot.avatarColor
            status = bot.status; activity = bot.activity; message = bot.lastMessage; lastAt = bot.lastAt
        }
    }
    private static var shown: [Snapshot]?
    private static var scope: String?

    static func reset() { shown = nil; scope = nil }

    static func update(_ roster: [RosterItem], storage: SharedStore.Context) {
        guard storage.id == SharedStore.activeContext.id else { return }
        storage.bots = roster.map { BotSnapshot(computerId: $0.ref.computerId, bot: $0.bot) }
        let currentScope = storage.id
        let signature = roster.filter { !$0.bot.hidden }.map { Snapshot($0.bot, computerId: $0.ref.computerId) }
        guard signature != shown || scope != currentScope else { return }
        shown = signature
        scope = currentScope
        WidgetCenter.shared.reloadTimelines(ofKind: "CodyncBots")
        WidgetCenter.shared.reloadTimelines(ofKind: "CodyncTeam")
        ControlCenter.shared.reloadControls(ofKind: "CodyncLeadBot")
    }
}