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.

Rebuild Codync as a bot-based remote for coding agents (2.0)

leepokaiae3458b05d51
diff --git a/.github/workflows/host.yml b/.github/workflows/host.yml
new file mode 100644
index 00000000..71060c27
--- /dev/null
+++ b/.github/workflows/host.yml
@@ -0,0 +1,65 @@
+name: codync-host
+
+on:
+ push:
+ branches: [main, v2]
+ paths: ["host/**", ".github/workflows/host.yml"]
+ tags: ["host-v*"]
+ pull_request:
+ paths: ["host/**"]
+
+jobs:
+ test:
+ strategy:
+ matrix:
+ os: [ubuntu-latest, macos-latest]
+ runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ working-directory: host
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ components: clippy
+ - uses: Swatinem/rust-cache@v2
+ with:
+ workspaces: host
+ - run: cargo clippy -- -D warnings
+ - run: cargo test
+
+ release:
+ if: startsWith(github.ref, 'refs/tags/host-v')
+ needs: test
+ strategy:
+ matrix:
+ include:
+ - { os: ubuntu-latest, target: x86_64-unknown-linux-gnu }
+ - { os: ubuntu-24.04-arm, target: aarch64-unknown-linux-gnu }
+ - { os: macos-latest, target: aarch64-apple-darwin }
+ - { os: macos-latest, target: x86_64-apple-darwin }
+ runs-on: ${{ matrix.os }}
+ permissions:
+ contents: write
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ targets: ${{ matrix.target }}
+ - name: Build
+ working-directory: host
+ run: cargo build --release --target ${{ matrix.target }}
+ - name: Package
+ run: |
+ VERSION=${GITHUB_REF_NAME#host-v}
+ NAME=codync-host-$VERSION-${{ matrix.target }}
+ mkdir $NAME
+ cp host/target/${{ matrix.target }}/release/codync-host $NAME/
+ cp LICENSE $NAME/
+ tar czf $NAME.tar.gz $NAME
+ shasum -a 256 $NAME.tar.gz > $NAME.tar.gz.sha256
+ - uses: softprops/action-gh-release@v2
+ with:
+ files: |
+ codync-host-*.tar.gz
+ codync-host-*.tar.gz.sha256
diff --git a/.github/workflows/release-macos.yml b/.github/workflows/release-macos.yml
index 8c79b8ac..23bad794 100644
--- a/.github/workflows/release-macos.yml
+++ b/.github/workflows/release-macos.yml
@@ -16,20 +16,14 @@ jobs:
- name: Set version from tag
run: echo "VERSION=${GITHUB_REF_NAME#v}" >> $GITHUB_ENV
- - name: Generate APNsSecrets.swift
- run: |
- cat > Codync-macOS/Services/APNsSecrets.swift << 'SWIFT'
- enum APNsSecrets {
- static let workerURL = "${{ secrets.APNS_WORKER_URL }}"
- static let apiSecret = "${{ secrets.APNS_API_SECRET }}"
- }
- SWIFT
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ targets: aarch64-apple-darwin,x86_64-apple-darwin
- name: Install Apple certificate and provisioning profile
env:
APPLE_CERTIFICATE_P12: ${{ secrets.APPLE_CERTIFICATE_P12 }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
- PROVISION_PROFILE: ${{ secrets.DEVELOPER_ID_PROVISION_PROFILE }}
run: |
CERT_FILE=$RUNNER_TEMP/certificate.p12
KEYCHAIN_FILE=$RUNNER_TEMP/app-signing.keychain-db
@@ -52,15 +46,11 @@ jobs:
security list-keychain -d user -s "$KEYCHAIN_FILE"
- mkdir -p ~/Library/Developer/Xcode/UserData/Provisioning\ Profiles
- echo "$PROVISION_PROFILE" | base64 --decode \
- > ~/Library/Developer/Xcode/UserData/Provisioning\ Profiles/codync-devid.provisionprofile
-
- name: Build
run: |
xcodebuild build \
-project Codync.xcodeproj \
- -scheme Codync \
+ -scheme Codync-macOS \
-configuration Release \
-destination 'generic/platform=macOS' \
-derivedDataPath build/derived \
@@ -74,29 +64,11 @@ jobs:
- name: Sign app with Developer ID
run: |
APP_PATH=$(find build/derived -name "Codync.app" -path "*/Release/*" | head -1)
-
- cp ~/Library/Developer/Xcode/UserData/Provisioning\ Profiles/codync-devid.provisionprofile \
- "$APP_PATH/Contents/embedded.provisionprofile"
-
- cat > $RUNNER_TEMP/release.entitlements << 'PLIST'
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
- <plist version="1.0">
- <dict>
- <key>com.apple.developer.icloud-container-environment</key>
- <string>Production</string>
- <key>com.apple.developer.icloud-container-identifiers</key>
- <array><string>iCloud.com.pokai.Codync</string></array>
- <key>com.apple.developer.icloud-services</key>
- <array><string>CloudKit</string></array>
- </dict>
- </plist>
- PLIST
-
- codesign --deep --force --options runtime \
- --sign "Developer ID Application" \
- --entitlements $RUNNER_TEMP/release.entitlements \
- "$APP_PATH"
+ # Nested helper first (the bundled Rust host), then the app itself.
+ codesign --force --options runtime --timestamp \
+ --sign "Developer ID Application" "$APP_PATH/Contents/MacOS/codync-host"
+ codesign --force --options runtime --timestamp \
+ --sign "Developer ID Application" "$APP_PATH"
cp -R "$APP_PATH" "$RUNNER_TEMP/Codync.app"
- name: Notarize and staple
@@ -146,10 +118,11 @@ jobs:
url "https://github.com/leepokai/Codync/releases/download/v#{version}/Codync-macOS.dmg"
name "Codync"
- desc "Real-time Claude Code session monitor for macOS menu bar"
+ desc "Message your coding agents (Claude Code, Codex, OpenCode) from your iPhone"
homepage "https://codync.dev"
app "Codync.app"
+ binary "#{appdir}/Codync.app/Contents/MacOS/codync-host"
zap trash: [
"~/Library/Preferences/com.pokai.Codync.plist",
diff --git a/.gitignore b/.gitignore
index 46239c49..b027b47b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,5 @@
.superpowers/
docs/superpowers/
-project.yml
# Xcode
xcuserdata/
diff --git a/CLAUDE.md b/CLAUDE.md
index 52595d84..c02dcc08 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,39 +1,46 @@
# Codync
+Bot-based remote for coding agents: persistent named bots on your computer, messaged from the iPhone (UI patterns from Grok Bot).
+
## Language & Syntax
- **Swift 6** strict concurrency mode — use latest Swift 6 syntax throughout
-- Prefer SwiftUI lifecycle and modern APIs (e.g., `MenuBarExtra`, `@Observable`, `@State`, `@Environment`)
-- Use structured concurrency (`async/await`, `TaskGroup`) over Combine where possible
+- Prefer SwiftUI lifecycle and modern APIs (`MenuBarExtra`, `@Observable`, `@State`, `@Environment`)
+- Use structured concurrency (`async/await`, `TaskGroup`) over Combine
- Use `sending`, `nonisolated`, `@MainActor` correctly per Swift 6 rules
- Avoid `@unchecked Sendable` — prefer proper `Sendable` conformance
+- Host is Rust 2024 edition; keep `cargo clippy -- -D warnings` clean
## Architecture
-- macOS menu bar app using `NSStatusItem` + `NSPopover`
-- **Hook-driven status detection** — 7 Claude Code hooks (Notification, Stop, UserPromptSubmit, PreToolUse, PostToolUse, SessionStart, SessionEnd) provide instant, accurate state
-- JSONL transcript parsing retained for supplementary data only (model, tokens, cost, tool display)
-- Command hook script (`~/.codync/notify.sh`) reads stdin, POSTs to local server, exits instantly (~20ms)
-- Shell script hook uses `curl --max-time 1 || true` — never blocks Claude Code even if app is not running
-- Shared code in `CodyncShared` Swift Package (macOS 14+ / iOS 17+)
-- **Do NOT register HTTP hooks** — they block Claude Code on ECONNREFUSED when app is down
-- Command hooks for PreToolUse/PostToolUse are safe — script exits in <20ms, imperceptible delay
+- `host/` — **codync-host** (Rust, macOS + Linux). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`bot.rs`) owns the agent process + session and maps `session/update` onto transcript entries.
+- **Thread ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is resumed with `session/load` or replaced by *New session*.
+- **Chat shows only**: user messages, the *final* agent message of each turn (`data.final`), permission cards, notices. Narration, thoughts, tool calls, plans are trace entries (Full conversation sheet).
+- **Sync**: every mutation stamps a global `rev`. Clients call `GET /events?since=<rev>` (catch-up in rev order, then live). Emission happens under `Hub::emit_lock` so events leave in rev order. Clients upsert by id; never skip undecodable events (the iOS app rewinds to rev 0).
+- API: `POST /api/<method>` + SSE, bearer token (`~/.codync/token`). Default port **19222**, binds 0.0.0.0 for Tailscale/LAN.
+- Push: iOS registers its APNs token with `relay/` → gets an AES-GCM ticket → gives it to the host. Only two alert kinds: *needs you* and *done*, suppressed while the iOS app is connected.
+- Usage: host-only reads (Claude statusline ingest + `/api/oauth/usage` with the stored Claude Code token, Codex rollout files). Never refresh or write agent credentials.
+- macOS app is thin: embeds `codync-host` in `Contents/MacOS` (Xcode post-build script runs cargo), installs it as a launchd agent via `codync-host install`, shows status/pairing/usage. Not sandboxed, not Mac App Store (the host must spawn CLIs).
+- Do **not** reintroduce Claude Code hooks or CloudKit — both were removed in 2.0.
+
+## Project generation
+
+- `project.yml` + `xcodegen generate` produce `Codync.xcodeproj`. Edit `project.yml`, not the pbxproj.
## App Store Upload
-- **IMPORTANT**: Every time you archive and upload a new build to App Store Connect, you MUST increment `CURRENT_PROJECT_VERSION` in the Xcode project first. App Store Connect rejects duplicate build numbers.
-- Version numbers are defined in `Codync.xcodeproj/project.pbxproj`, NOT in `Shared.xcconfig` — the pbxproj values take precedence. Always modify `MARKETING_VERSION` and `CURRENT_PROJECT_VERSION` directly in the pbxproj.
+- **IMPORTANT**: Every time you archive and upload a new build to App Store Connect, you MUST increment `CURRENT_PROJECT_VERSION` first (App Store Connect rejects duplicate build numbers).
+- Versions live in `project.yml` (`MARKETING_VERSION`, `CURRENT_PROJECT_VERSION`); regenerate the project after changing them. Keep `host/Cargo.toml` `version` in sync with `MARKETING_VERSION`.
## Versioning
-- **Major version** defines macOS ↔ iOS compatibility: `1.x.x` macOS works with `1.x.x` iOS
-- `2.x.x` macOS is NOT compatible with `1.x.x` iOS (breaking sync/protocol change)
-- Minor/patch bumps are always backward compatible within the same major
-- When bumping major version, both macOS and iOS must ship updated versions
+- **Major version** defines phone ↔ host compatibility: 2.x iOS works with 2.x host/macOS
+- 2.x is NOT compatible with 1.x (1.x was the hooks + CloudKit monitor)
+- Minor/patch bumps are always backward compatible within the same major; the iOS decoder is lenient (`Bot.init(from:)`) so small host additions don't break older apps
## Targets
-- `Codync-macOS` — macOS menu bar app
-- `Codync-iOS` — iOS companion app
-- `CodyncLiveActivity` — iOS Live Activity widget
-- `CodyncShared` — shared models and CloudKit logic
+- `Codync-macOS` — menu bar app + embedded host
+- `Codync-iOS` — iOS app
+- `CodyncWidgets` — usage widget + bot Live Activity (bundle id `com.pokai.Codync.ios.LiveActivity`)
+- `CodyncKit` — shared Swift package (models, host client, theme, avatars)
diff --git a/CloudKit/schema.ckdb b/CloudKit/schema.ckdb
deleted file mode 100644
index 00a1817d..00000000
--- a/CloudKit/schema.ckdb
+++ /dev/null
@@ -1,25 +0,0 @@
-DEFINE SCHEMA
-
- RECORD TYPE SessionState (
- "___createTime" TIMESTAMP,
- "___modTime" TIMESTAMP,
- "___recordID" REFERENCE QUERYABLE,
- sessionId STRING QUERYABLE,
- projectName STRING,
- gitBranch STRING,
- status STRING QUERYABLE,
- model STRING,
- summary STRING,
- currentTask STRING,
- lastEvent STRING,
- waitingReason STRING,
- contextPct INT64,
- costUSD DOUBLE,
- startedAt TIMESTAMP,
- durationSec INT64,
- deviceId STRING,
- updatedAt TIMESTAMP QUERYABLE SORTABLE,
- tasks BYTES,
- GRANT WRITE TO "_creator",
- GRANT READ TO "_creator"
- );
diff --git a/Codync-iOS/App/AppDelegate.swift b/Codync-iOS/App/AppDelegate.swift
deleted file mode 100644
index d94fb194..00000000
--- a/Codync-iOS/App/AppDelegate.swift
+++ /dev/null
@@ -1,137 +0,0 @@
-import UIKit
-import CloudKit
-import UserNotifications
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync.ios", category: "AppDelegate")
-
-final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
- let receiver = CloudKitReceiver()
- let liveActivityManager = LiveActivityManager()
- let primarySessionManager = PrimarySessionManager()
- private var pollTimer: Timer?
-
- func application(
- _ application: UIApplication,
- didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
- ) -> Bool {
- UNUserNotificationCenter.current().delegate = self
- application.registerForRemoteNotifications()
- NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in
- Task { @MainActor in
- guard let self else { return }
- await self.receiver.fetch(source: "did-become-active", force: true)
- self.liveActivityManager.userPrimarySessionId = self.primarySessionManager.primarySessionId
- self.liveActivityManager.updateSessions(self.receiver.sessions)
- }
- }
- Task {
- PremiumManager.shared.configure()
- async let startReceiver: () = receiver.start()
- async let loadPins: () = liveActivityManager.loadPinnedSessions()
- async let loadPref: () = liveActivityManager.loadPreference()
- async let loadPrimary: () = primarySessionManager.load()
- _ = await (startReceiver, loadPins, loadPref, loadPrimary)
-
- liveActivityManager.userPrimarySessionId = primarySessionManager.primarySessionId
- liveActivityManager.updateSessions(receiver.sessions)
- primarySessionManager.autoSelect(from: receiver.sessions)
-
- startForegroundPolling()
- }
- return true
- }
-
- // MARK: - Foreground Polling
-
- func startForegroundPolling() {
- pollTimer?.invalidate()
- pollTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] _ in
- Task { @MainActor in
- guard let self else { return }
- await self.receiver.fetch(source: "poll", force: true)
- self.liveActivityManager.userPrimarySessionId = self.primarySessionManager.primarySessionId
- self.liveActivityManager.updateSessions(self.receiver.sessions)
- self.primarySessionManager.autoSelect(from: self.receiver.sessions)
- }
- }
- RunLoop.main.add(pollTimer!, forMode: .common)
- }
-
- func stopForegroundPolling() {
- pollTimer?.invalidate()
- pollTimer = nil
- }
-
- func application(
- _ application: UIApplication,
- didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
- ) {
- let hex = deviceToken.map { String(format: "%02x", $0) }.joined()
- logger.info("APNs device token registered: \(hex.prefix(8))...")
- // Save device token to CloudKit for alert push (session complete notifications)
- Task {
- let recordID = CKRecord.ID(
- recordName: "device-push-token",
- zoneID: CloudKitManager.zoneID
- )
- do {
- let record: CKRecord
- do {
- record = try await CloudKitManager.shared.database.record(for: recordID)
- } catch {
- record = CKRecord(recordType: "DeviceToken", recordID: recordID)
- }
- record["token"] = hex as CKRecordValue
- record["updatedAt"] = Date() as CKRecordValue
- _ = try await CloudKitManager.shared.database.save(record)
- logger.info("Saved device push token to CloudKit")
- } catch {
- logger.error("Failed to save device push token: \(error.localizedDescription)")
- }
- }
- }
-
- func application(
- _ application: UIApplication,
- didFailToRegisterForRemoteNotificationsWithError error: Error
- ) {
- logger.error("APNs registration failed: \(error.localizedDescription)")
- }
-
- func application(
- _ application: UIApplication,
- didReceiveRemoteNotification userInfo: [AnyHashable: Any]
- ) async -> UIBackgroundFetchResult {
- // Pro users rely on APNs Worker push — skip silent push to isolate testing
- if PremiumManager.shared.isPro {
- logger.info("CloudKit silent push skipped (Pro uses APNs Worker)")
- return .noData
- }
-
- let notification = CKNotification(fromRemoteNotificationDictionary: userInfo)
- let subID = notification?.subscriptionID
- guard subID == "session-zone-changes" || subID == "session-changes" else {
- return .noData
- }
- let fmt = DateFormatter()
- fmt.dateFormat = "HH:mm:ss"
- let ts = fmt.string(from: Date())
- logger.info("[\(ts)] CloudKit push received")
- await receiver.fetch(source: "silent-push", force: true)
- let statuses = receiver.sessions.map { "\($0.projectName):\($0.status.rawValue)" }.joined(separator: ", ")
- logger.info("[\(ts)] → \(statuses)")
- liveActivityManager.updateSessions(receiver.sessions)
- primarySessionManager.autoSelect(from: receiver.sessions)
- return .newData
- }
-
- // Show notifications even when app is in foreground
- nonisolated func userNotificationCenter(
- _ center: UNUserNotificationCenter,
- willPresent notification: UNNotification
- ) async -> UNNotificationPresentationOptions {
- [.banner, .sound]
- }
-}
diff --git a/Codync-iOS/App/AppModel.swift b/Codync-iOS/App/AppModel.swift
new file mode 100644
index 00000000..7292f702
--- /dev/null
+++ b/Codync-iOS/App/AppModel.swift
@@ -0,0 +1,380 @@
+import CodyncKit
+import Foundation
+import Observation
+import UIKit
+import WidgetKit
+import os
+
+private let log = Logger(subsystem: "com.pokai.Codync.ios", category: "AppModel")
+
+/// Single source of truth for the phone: mirrors the host's bots and
+/// transcripts via one SSE stream (catch-up since `rev`, then live).
+@MainActor
+@Observable
+final class AppModel {
+ enum Connection: Equatable {
+ case unpaired
+ case connecting
+ case online
+ case offline(String)
+ }
+
+ private(set) var pairing: Pairing? = SharedStore.pairing
+ private(set) var connection: Connection = .unpaired
+ private(set) var client: HostClient?
+ private(set) var hello: Hello?
+ private(set) var bots: [String: Bot] = [:]
+ private(set) var entries: [String: [Entry]] = [:]
+ private(set) var usage = SharedStore.usage ?? Usage()
+ /// Bots whose older history has been fully paged in.
+ private(set) var historyComplete: Set<String> = []
+ var lastError: String?
+
+ private var rev: Int64 = 0
+ private var hostId: String?
+ private var streamTask: Task<Void, Never>?
+ private var isActive = true
+ private var saveTask: Task<Void, Never>?
+ private var rewound = false
+
+ init() {
+ loadCache()
+ connection = pairing == nil ? .unpaired : .connecting
+ }
+
+ // MARK: derived
+
+ var hostName: String { hello?.name ?? pairing?.name ?? "Computer" }
+
+ /// Roster order: pinned first (manual order not tracked yet), then most recent activity.
+ var roster: [Bot] {
+ bots.values.filter { !$0.hidden }.sorted {
+ if $0.pinned != $1.pinned { return $0.pinned }
+ return $0.lastAt > $1.lastAt
+ }
+ }
+
+ var hiddenBots: [Bot] { bots.values.filter(\.hidden).sorted { $0.name < $1.name } }
+
+ func thread(_ botId: String) -> [Entry] { entries[botId] ?? [] }
+
+ // MARK: pairing
+
+ func pair(_ p: Pairing) {
+ let changedHost = pairing?.token != p.token
+ pairing = p
+ SharedStore.pairing = p
+ SharedStore.preferredURL = nil
+ if changedHost { resetMirror() }
+ connection = .connecting
+ restartStream()
+ PushRegistrar.shared.syncDevice(with: self)
+ }
+
+ func unpair() {
+ streamTask?.cancel()
+ pairing = nil
+ client = nil
+ hello = nil
+ SharedStore.pairing = nil
+ resetMirror()
+ connection = .unpaired
+ }
+
+ private func resetMirror() {
+ bots = [:]
+ entries = [:]
+ rev = 0
+ hostId = nil
+ historyComplete = []
+ saveCache()
+ }
+
+ // MARK: lifecycle
+
+ func setActive(_ active: Bool) {
+ isActive = active
+ if active {
+ restartStream()
+ } else {
+ // Disconnect so the host knows we're gone and sends pushes instead.
+ streamTask?.cancel()
+ streamTask = nil
+ saveCache()
+ }
+ }
+
+ func restartStream() {
+ streamTask?.cancel()
+ guard pairing != nil, isActive else { return }
+ streamTask = Task { [weak self] in await self?.runStream() }
+ }
+
+ private func runStream() async {
+ var backoff: Double = 1
+ while !Task.isCancelled {
+ guard let pairing = SharedStore.orderedPairing else { return }
+ if connection != .online { connection = .connecting }
+ guard let client = await HostClient.resolve(pairing) else {
+ connection = .offline(HostError.unreachable.localizedDescription)
+ try? await Task.sleep(for: .seconds(backoff))
+ backoff = min(backoff * 2, 20)
+ continue
+ }
+ self.client = client
+ SharedStore.preferredURL = client.baseURL.absoluteString
+ do {
+ if hello == nil || hello?.hostId != hostId {
+ let h = try await client.hello()
+ hello = h
+ // Host upgraded since the cache was written: its data may carry new fields.
+ if let stamp = cacheStamp, stamp != "\(Self.appBuild)/\(h.version)" {
+ rev = 0
+ cacheStamp = nil
+ }
+ }
+ for try await event in client.events(since: rev, client: "ios") {
+ connection = .online
+ backoff = 1
+ apply(event)
+ }
+ } catch is CancellationError {
+ return
+ } catch {
+ if Task.isCancelled { return }
+ log.info("stream ended: \(error.localizedDescription)")
+ if case HostError.http(401, _) = error {
+ connection = .offline(error.localizedDescription)
+ return
+ }
+ connection = .offline(error.localizedDescription)
+ }
+ try? await Task.sleep(for: .seconds(backoff))
+ backoff = min(backoff * 2, 20)
+ }
+ }
+
+ private func apply(_ event: HostEvent) {
+ switch event {
+ case let .hello(id, hostRev, newUsage):
+ if let hostId, hostId != id {
+ // Different host database: start over.
+ resetMirror()
+ }
+ hostId = id
+ setUsage(newUsage)
+ if hostRev < rev { rev = 0 }
+ case let .bot(bot):
+ let old = bots[bot.id]
+ bots[bot.id] = bot
+ bump(bot.rev)
+ LiveActivities.shared.update(bot: bot, previous: old)
+ case let .botDeleted(id, r):
+ bots[id] = nil
+ entries[id] = nil
+ bump(r)
+ case let .entry(e):
+ upsert(e)
+ bump(e.rev)
+ case let .usage(u):
+ setUsage(u)
+ case .resync:
+ restartStream()
+ case let .undecodable(type):
+ // Never skip past data we couldn't read: rewind once and fetch everything again.
+ log.error("undecodable \(type) event")
+ if !rewound {
+ rewound = true
+ rev = 0
+ restartStream()
+ }
+ }
+ scheduleSave()
+ }
+
+ private func bump(_ r: Int64) { rev = max(rev, r) }
+
+ private func upsert(_ e: Entry) {
+ var list = entries[e.botId] ?? []
+ if let i = list.firstIndex(where: { $0.id == e.id }) {
+ list[i] = e
+ } else {
+ // Replace the optimistic copy of a message we sent.
+ if e.kind == "user", let nonce = e.data.clientNonce, !nonce.isEmpty {
+ list.removeAll { $0.id == "local-\(nonce)" }
+ }
+ if let last = list.last, last.seq > e.seq, e.seq > 0 {
+ let i = list.firstIndex { $0.seq > e.seq } ?? list.endIndex
+ list.insert(e, at: i)
+ } else {
+ list.append(e)
+ }
+ }
+ entries[e.botId] = list
+ }
+
+ private func setUsage(_ u: Usage) {
+ guard u != usage else { return }
+ usage = u
+ SharedStore.usage = u
+ WidgetCenter.shared.reloadAllTimelines()
+ }
+
+ // MARK: actions
+
+ private func require() throws -> HostClient {
+ guard let client, connection == .online else { throw HostError.unreachable }
+ return client
+ }
+
+ func send(_ text: String, to botId: String) {
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+ let nonce = UUID().uuidString
+ let local = Entry(
+ id: "local-\(nonce)", seq: Int64.max, botId: botId, rev: 0, kind: "user",
+ turn: 0, data: EntryData(text: trimmed, status: "sending", clientNonce: nonce),
+ createdAt: Int64(Date.now.timeIntervalSince1970 * 1000), updatedAt: 0
+ )
+ upsert(local)
+ Task {
+ do {
+ let e = try await require().send(botId: botId, text: trimmed, clientNonce: nonce)
+ upsert(e)
+ if let bot = bots[botId] { LiveActivities.shared.start(for: bot, model: self) }
+ } catch {
+ markLocal(nonce: nonce, botId: botId, status: "failed")
+ }
+ }
+ }
+
+ func retry(_ entry: Entry) {
+ guard let text = entry.data.text else { return }
+ entries[entry.botId]?.removeAll { $0.id == entry.id }
+ send(text, to: entry.botId)
+ }
+
+ func discard(_ entry: Entry) {
+ entries[entry.botId]?.removeAll { $0.id == entry.id }
+ }
+
+ private func markLocal(nonce: String, botId: String, status: String) {
+ guard var list = entries[botId], let i = list.firstIndex(where: { $0.id == "local-\(nonce)" }) else { return }
+ list[i].data.status = status
+ entries[botId] = list
+ }
+
+ func stop(_ botId: String) { perform { try await $0.stop(botId) } }
+ func newSession(_ botId: String) { perform { try await $0.newSession(botId) } }
+
+ func respond(_ entry: Entry, option: String?) {
+ perform { try await $0.respondPermission(entryId: entry.id, optionId: option) }
+ }
+
+ func markRead(_ botId: String) {
+ guard (bots[botId]?.unread ?? 0) > 0 else { return }
+ bots[botId]?.unread = 0
+ perform { try await $0.markRead(botId) }
+ }
+
+ func setPinned(_ bot: Bot, _ pinned: Bool) {
+ var d = BotDraft(bot)
+ d.pinned = pinned
+ bots[bot.id]?.pinned = pinned
+ perform { _ = try await $0.updateBot(d) }
+ }
+
+ func setHidden(_ bot: Bot, _ hidden: Bool) {
+ var d = BotDraft(bot)
+ d.hidden = hidden
+ bots[bot.id]?.hidden = hidden
+ perform { _ = try await $0.updateBot(d) }
+ }
+
+ func delete(_ bot: Bot) {
+ bots[bot.id] = nil
+ entries[bot.id] = nil
+ perform { try await $0.deleteBot(bot.id) }
+ }
+
+ func save(_ draft: BotDraft) async throws -> Bot {
+ let client = try require()
+ let bot = draft.id == nil ? try await client.createBot(draft) : try await client.updateBot(draft)
+ bots[bot.id] = bot
+ return bot
+ }
+
+ func listDirs(_ path: String?) async throws -> DirListing {
+ try await require().listDirs(path)
+ }
+
+ func refreshUsage() async {
+ guard let client else { return }
+ if let u = try? await client.usage(refresh: true) { setUsage(u) }
+ }
+
+ func loadOlder(_ botId: String) async {
+ guard let client, !historyComplete.contains(botId) else { return }
+ let first = thread(botId).first { $0.seq > 0 && $0.seq != Int64.max }?.seq ?? Int64.max
+ guard let older = try? await client.history(botId: botId, beforeSeq: first, limit: 100) else { return }
+ if older.count < 100 { historyComplete.insert(botId) }
+ for e in older { upsert(e) }
+ }
+
+ private func perform(_ op: @escaping @MainActor (HostClient) async throws -> Void) {
+ Task {
+ do {
+ try await op(try require())
+ } catch {
+ lastError = error.localizedDescription
+ }
+ }
+ }
+
+ // MARK: cache (instant launch, offline reading)
+
+ private struct Cache: Codable {
+ /// App build + host version that wrote the cache; any change means refetch everything.
+ var stamp: String?
+ var hostId: String?
+ var rev: Int64
+ var bots: [Bot]
+ var entries: [Entry]
+ }
+
+ private static let appBuild = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"
+ private var cacheStamp: String?
+
+ private static var cacheURL: URL {
+ URL.cachesDirectory.appending(path: "codync-mirror.json")
+ }
+
+ private func loadCache() {
+ guard pairing != nil,
+ let data = try? Data(contentsOf: Self.cacheURL),
+ let cache = try? JSONDecoder().decode(Cache.self, from: data),
+ cache.stamp?.hasPrefix(Self.appBuild + "/") == true else { return }
+ cacheStamp = cache.stamp
+ hostId = cache.hostId
+ rev = cache.rev
+ bots = Dictionary(cache.bots.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
+ entries = Dictionary(grouping: cache.entries, by: \.botId)
+ }
+
+ private func scheduleSave() {
+ saveTask?.cancel()
+ saveTask = Task {
+ try? await Task.sleep(for: .seconds(2))
+ if !Task.isCancelled { saveCache() }
+ }
+ }
+
+ func saveCache() {
+ // Keep the newest 200 entries per bot; older ones page in from the host.
+ let kept = entries.values.flatMap { $0.filter { !$0.id.hasPrefix("local-") }.suffix(200) }
+ let cache = Cache(stamp: "\(Self.appBuild)/\(hello?.version ?? "")", hostId: hostId, rev: rev, bots: Array(bots.values), entries: kept)
+ if let data = try? JSONEncoder().encode(cache) {
+ try? data.write(to: Self.cacheURL, options: .atomic)
+ }
+ }
+}
diff --git a/Codync-iOS/App/CodyncApp.swift b/Codync-iOS/App/CodyncApp.swift
new file mode 100644
index 00000000..7420c79f
--- /dev/null
+++ b/Codync-iOS/App/CodyncApp.swift
@@ -0,0 +1,72 @@
+import CodyncKit
+import SwiftUI
+import UserNotifications
+
+@main
+struct CodyncApp: App {
+ @UIApplicationDelegateAdaptor(AppDelegate.self) private var delegate
+ @State private var model = AppModel()
+ @State private var router = Router.shared
+ @Environment(\.scenePhase) private var scenePhase
+
+ var body: some Scene {
+ WindowGroup {
+ RootView()
+ .environment(model)
+ .environment(router)
+ .tint(Palette.accent)
+ .onOpenURL { url in
+ if let p = Pairing(url: url) {
+ model.pair(p)
+ } else if url.host() == "bot" {
+ router.open(botId: url.lastPathComponent)
+ }
+ }
+ .onChange(of: scenePhase, initial: true) { _, phase in
+ model.setActive(phase == .active)
+ }
+ #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) {
+ model.pair(p)
+ }
+ }
+ #endif
+ }
+ }
+}
+
+@MainActor
+@Observable
+final class Router {
+ static let shared = Router()
+ var path: [String] = []
+
+ func open(botId: String) {
+ path = [botId]
+ }
+}
+
+final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
+ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
+ UNUserNotificationCenter.current().delegate = self
+ return true
+ }
+
+ func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
+ Task { @MainActor in PushRegistrar.shared.didRegister(token: deviceToken) }
+ }
+
+ nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
+ let botId = response.notification.request.content.userInfo["botId"] as? String
+ if let botId {
+ await MainActor.run { Router.shared.open(botId: botId) }
+ }
+ }
+
+ nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
+ // The chat already shows it live.
+ []
+ }
+}
diff --git a/Codync-iOS/App/CodyncIOSApp.swift b/Codync-iOS/App/CodyncIOSApp.swift
deleted file mode 100644
index 94cb23a0..00000000
--- a/Codync-iOS/App/CodyncIOSApp.swift
+++ /dev/null
@@ -1,35 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-@main
-struct CodyncIOSApp: App {
- @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
- @Environment(\.scenePhase) private var scenePhase
-
- var body: some Scene {
- WindowGroup {
- IOSRootView(
- receiver: appDelegate.receiver,
- liveActivityManager: appDelegate.liveActivityManager,
- primarySessionManager: appDelegate.primarySessionManager
- )
- }
- .onChange(of: scenePhase) { _, phase in
- if phase == .active {
- appDelegate.liveActivityManager.ensureTimerRunning()
- appDelegate.liveActivityManager.invalidateCache()
- appDelegate.liveActivityManager.userPrimarySessionId = appDelegate.primarySessionManager.primarySessionId
- appDelegate.liveActivityManager.updateSessions(appDelegate.receiver.sessions)
- // Fetch fresh + start polling while in foreground
- Task {
- await appDelegate.receiver.fetch(source: "foreground-return", force: true)
- appDelegate.liveActivityManager.updateSessions(appDelegate.receiver.sessions)
- appDelegate.primarySessionManager.autoSelect(from: appDelegate.receiver.sessions)
- }
- appDelegate.startForegroundPolling()
- } else if phase == .background {
- appDelegate.stopForegroundPolling()
- }
- }
- }
-}
diff --git a/Codync-iOS/App/Push.swift b/Codync-iOS/App/Push.swift
new file mode 100644
index 00000000..7f3216f4
--- /dev/null
+++ b/Codync-iOS/App/Push.swift
@@ -0,0 +1,120 @@
+import ActivityKit
+import CodyncKit
+import Foundation
+import UIKit
+import UserNotifications
+import os
+
+private let log = Logger(subsystem: "com.pokai.Codync.ios", category: "Push")
+
+private var apnsEnvironment: String {
+ #if DEBUG
+ "sandbox"
+ #else
+ "production"
+ #endif
+}
+
+/// Turns an APNs token into a relay ticket (see relay/src/index.ts).
+private func relayTicket(token: Data, kind: String) async throws -> String {
+ struct Body: Encodable { var token: String; var env: String; var kind: String }
+ struct Res: Decodable { var ticket: String }
+ var req = URLRequest(url: URL(string: "\(SharedStore.relayURL)/register")!)
+ req.httpMethod = "POST"
+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ req.httpBody = try JSONEncoder().encode(Body(token: token.map { String(format: "%02x", $0) }.joined(), env: apnsEnvironment, kind: kind))
+ let (data, _) = try await URLSession.shared.data(for: req)
+ return try JSONDecoder().decode(Res.self, from: data).ticket
+}
+
+/// Registers this phone for "needs you" / "done" alerts with the paired host.
+@MainActor
+final class PushRegistrar {
+ static let shared = PushRegistrar()
+
+ private var deviceToken: Data?
+ private weak var model: AppModel?
+
+ func requestAuthorization() async -> Bool {
+ let granted = (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])) ?? false
+ if granted { UIApplication.shared.registerForRemoteNotifications() }
+ return granted
+ }
+
+ func didRegister(token: Data) {
+ deviceToken = token
+ if let model { syncDevice(with: model) }
+ }
+
+ /// Sends our ticket to the host whenever we have both a token and a pairing.
+ func syncDevice(with model: AppModel) {
+ self.model = model
+ guard let token = deviceToken else {
+ Task {
+ let settings = await UNUserNotificationCenter.current().notificationSettings()
+ if settings.authorizationStatus == .authorized { UIApplication.shared.registerForRemoteNotifications() }
+ }
+ return
+ }
+ Task {
+ do {
+ let ticket = try await relayTicket(token: token, kind: "alert")
+ guard let pairing = SharedStore.orderedPairing, let client = await HostClient.resolve(pairing) else { return }
+ try await client.registerDevice(ticket: ticket, relay: SharedStore.relayURL, name: UIDevice.current.name)
+ log.info("device registered with host")
+ } catch {
+ log.error("device registration failed: \(error.localizedDescription)")
+ }
+ }
+ }
+}
+
+/// One Live Activity per bot the user delegated to from this phone.
+@MainActor
+final class LiveActivities {
+ static let shared = LiveActivities()
+
+ private nonisolated static func find(_ botId: String) -> Activity<BotActivityAttributes>? {
+ Activity<BotActivityAttributes>.activities.first { $0.attributes.botId == botId }
+ }
+
+ func start(for bot: Bot, model: AppModel) {
+ guard ActivityAuthorizationInfo().areActivitiesEnabled, Self.find(bot.id) == nil, let client = model.client else { return }
+ let attributes = BotActivityAttributes(bot: bot)
+ Task.detached { await Self.request(attributes: attributes, client: client) }
+ }
+
+ private nonisolated static func request(attributes: BotActivityAttributes, client: HostClient) async {
+ let state = BotActivityAttributes.ContentState(status: "working", activity: "Starting…", startedAt: .now)
+ do {
+ let activity = try Activity.request(attributes: attributes, content: .init(state: state, staleDate: nil), pushType: .token)
+ for await token in activity.pushTokenUpdates {
+ guard let ticket = try? await relayTicket(token: token, kind: "liveactivity") else { continue }
+ try? await client.registerActivity(botId: attributes.botId, ticket: ticket)
+ }
+ } catch {
+ log.info("live activity not started: \(error.localizedDescription)")
+ }
+ }
+
+ /// Local updates while the app is open; the host pushes them otherwise.
+ func update(bot: Bot, previous: Bot?) {
+ guard Self.find(bot.id) != nil else { return }
+ let state = BotActivityAttributes.ContentState(
+ status: bot.status,
+ activity: bot.activity,
+ startedAt: bot.startedAt.map(Date.init(milliseconds:))
+ )
+ let botId = bot.id, working = bot.isWorking
+ Task.detached { await Self.apply(botId: botId, state: state, end: !working) }
+ }
+
+ private nonisolated static func apply(botId: String, state: BotActivityAttributes.ContentState, end: Bool) async {
+ guard let activity = find(botId) else { return }
+ if end {
+ await activity.end(.init(state: state, staleDate: nil), dismissalPolicy: .after(.now + 60))
+ } else {
+ await activity.update(.init(state: state, staleDate: nil))
+ }
+ }
+}
diff --git a/Codync-iOS/Assets.xcassets/ClaudeIcon.imageset/Contents.json b/Codync-iOS/Assets.xcassets/ClaudeIcon.imageset/Contents.json
deleted file mode 100644
index 9eea8384..00000000
--- a/Codync-iOS/Assets.xcassets/ClaudeIcon.imageset/Contents.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "images" : [
- {
- "filename" : "claude.svg",
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "preserves-vector-representation" : true,
- "template-rendering-intent" : "template"
- }
-}
diff --git a/Codync-iOS/Assets.xcassets/ClaudeIcon.imageset/claude.svg b/Codync-iOS/Assets.xcassets/ClaudeIcon.imageset/claude.svg
deleted file mode 100644
index 8b2e7cbc..00000000
--- a/Codync-iOS/Assets.xcassets/ClaudeIcon.imageset/claude.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg fill="#000000" fill-rule="evenodd" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"/></svg>
diff --git a/Codync-iOS/Assets.xcassets/CodexIcon.imageset/Contents.json b/Codync-iOS/Assets.xcassets/CodexIcon.imageset/Contents.json
deleted file mode 100644
index 4778f324..00000000
--- a/Codync-iOS/Assets.xcassets/CodexIcon.imageset/Contents.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "images" : [
- {
- "filename" : "codex.png",
- "idiom" : "universal",
- "scale" : "1x"
- },
- {
- "filename" : "[email protected]",
- "idiom" : "universal",
- "scale" : "2x"
- },
- {
- "filename" : "[email protected]",
- "idiom" : "universal",
- "scale" : "3x"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "template"
- }
-}
diff --git a/Codync-iOS/Assets.xcassets/CodexIcon.imageset/codex.png b/Codync-iOS/Assets.xcassets/CodexIcon.imageset/codex.png
deleted file mode 100644
index 39888eae..00000000
Binary files a/Codync-iOS/Assets.xcassets/CodexIcon.imageset/codex.png and /dev/null differ
diff --git a/Codync-iOS/Assets.xcassets/CodexIcon.imageset/[email protected] b/Codync-iOS/Assets.xcassets/CodexIcon.imageset/[email protected]
deleted file mode 100644
index 84cbdc58..00000000
Binary files a/Codync-iOS/Assets.xcassets/CodexIcon.imageset/[email protected] and /dev/null differ
diff --git a/Codync-iOS/Assets.xcassets/CodexIcon.imageset/[email protected] b/Codync-iOS/Assets.xcassets/CodexIcon.imageset/[email protected]
deleted file mode 100644
index 35cd30de..00000000
Binary files a/Codync-iOS/Assets.xcassets/CodexIcon.imageset/[email protected] and /dev/null differ
diff --git a/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/Contents.json b/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/Contents.json
deleted file mode 100644
index 61c57327..00000000
--- a/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/Contents.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "images" : [
- {
- "filename" : "image.png",
- "idiom" : "universal",
- "scale" : "1x"
- },
- {
- "filename" : "image 1.png",
- "idiom" : "universal",
- "scale" : "2x"
- },
- {
- "filename" : "image 2.png",
- "idiom" : "universal",
- "scale" : "3x"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "original"
- }
-}
diff --git a/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/image 1.png b/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/image 1.png
deleted file mode 100644
index 7c716818..00000000
Binary files a/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/image 1.png and /dev/null differ
diff --git a/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/image 2.png b/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/image 2.png
deleted file mode 100644
index 7c716818..00000000
Binary files a/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/image 2.png and /dev/null differ
diff --git a/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/image.png b/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/image.png
deleted file mode 100644
index 7c716818..00000000
Binary files a/Codync-iOS/Assets.xcassets/CodyncIcon.imageset/image.png and /dev/null differ
diff --git a/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/Contents.json b/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/Contents.json
deleted file mode 100644
index b08a55f7..00000000
--- a/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/Contents.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "images" : [
- {
- "filename" : "cowork.png",
- "idiom" : "universal",
- "scale" : "1x"
- },
- {
- "filename" : "[email protected]",
- "idiom" : "universal",
- "scale" : "2x"
- },
- {
- "filename" : "[email protected]",
- "idiom" : "universal",
- "scale" : "3x"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "template"
- }
-}
diff --git a/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/cowork.png b/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/cowork.png
deleted file mode 100644
index 7889c800..00000000
Binary files a/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/cowork.png and /dev/null differ
diff --git a/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/[email protected] b/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/[email protected]
deleted file mode 100644
index a3d75ff0..00000000
Binary files a/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/[email protected] and /dev/null differ
diff --git a/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/[email protected] b/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/[email protected]
deleted file mode 100644
index 05540922..00000000
Binary files a/Codync-iOS/Assets.xcassets/CoworkIcon.imageset/[email protected] and /dev/null differ
diff --git a/Codync-iOS/App/Codync-iOS.entitlements b/Codync-iOS/Codync-iOS.entitlements
similarity index 57%
rename from Codync-iOS/App/Codync-iOS.entitlements
rename to Codync-iOS/Codync-iOS.entitlements
index 60f51655..0a770bc1 100644
--- a/Codync-iOS/App/Codync-iOS.entitlements
+++ b/Codync-iOS/Codync-iOS.entitlements
@@ -2,15 +2,11 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
- <key>com.apple.developer.icloud-container-identifiers</key>
- <array>
- <string>iCloud.com.pokai.Codync</string>
- </array>
- <key>com.apple.developer.icloud-services</key>
- <array>
- <string>CloudKit</string>
- </array>
<key>aps-environment</key>
<string>development</string>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>group.com.pokai.Codync</string>
+ </array>
</dict>
</plist>
diff --git a/Codync-iOS/CodyncStore.storekit b/Codync-iOS/CodyncStore.storekit
deleted file mode 100644
index 426e7bc6..00000000
--- a/Codync-iOS/CodyncStore.storekit
+++ /dev/null
@@ -1,55 +0,0 @@
-{
- "identifier" : "CodyncStore",
- "type" : "Default",
- "version" : 2,
- "products" : [
- {
- "displayPrice" : "0.99",
- "familyShareable" : true,
- "internalID" : "1",
- "localizations" : [
- {
- "description" : "Always-on Live Activity updates",
- "displayName" : "Codync Pro",
- "locale" : "en_US"
- }
- ],
- "productID" : "com.pokai.Codync.ios.pro.monthly",
- "referenceName" : "Pro Monthly",
- "subscriptionGroupID" : "21991861",
- "type" : "RecurringSubscription",
- "subscription" : {
- "subscriptionPeriod" : "P1M",
- "groupNumber" : 1,
- "introductoryOffer" : null
- }
- }
- ],
- "subscriptionGroups" : [
- {
- "id" : "21991861",
- "localizations" : [
- {
- "description" : "",
- "displayName" : "Codync Pro",
- "locale" : "en_US"
- }
- ],
- "name" : "Codync Pro"
- }
- ],
- "settings" : {
- "_applicationInternalID" : "6760984418",
- "_developerTeamID" : "DEVELOPMENT_TEAM_REDACTED",
- "_failTransactionsEnabled" : false,
- "_locale" : "en_US",
- "_storefront" : "USA",
- "_storeKitErrors" : [
- {
- "current" : null,
- "enabled" : false,
- "name" : "Load Products"
- }
- ]
- }
-}
diff --git a/Codync-iOS/Info.plist b/Codync-iOS/Info.plist
index ca9a074a..e8eb5cbf 100644
--- a/Codync-iOS/Info.plist
+++ b/Codync-iOS/Info.plist
@@ -6,5 +6,31 @@
<array>
<string>remote-notification</string>
</array>
+ <key>CFBundleURLTypes</key>
+ <array>
+ <dict>
+ <key>CFBundleURLName</key>
+ <string>com.pokai.Codync.ios</string>
+ <key>CFBundleURLSchemes</key>
+ <array>
+ <string>codync</string>
+ </array>
+ </dict>
+ </array>
+ <key>NSAppTransportSecurity</key>
+ <dict>
+ <key>NSAllowsLocalNetworking</key>
+ <true/>
+ <key>NSExceptionDomains</key>
+ <dict>
+ <key>ts.net</key>
+ <dict>
+ <key>NSIncludesSubdomains</key>
+ <true/>
+ <key>NSExceptionAllowsInsecureHTTPLoads</key>
+ <true/>
+ </dict>
+ </dict>
+ </dict>
</dict>
</plist>
diff --git a/Codync-iOS/Services/CloudKitReceiver.swift b/Codync-iOS/Services/CloudKitReceiver.swift
deleted file mode 100644
index 055d9a1b..00000000
--- a/Codync-iOS/Services/CloudKitReceiver.swift
+++ /dev/null
@@ -1,88 +0,0 @@
-import Foundation
-import CloudKit
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync.ios", category: "CloudKitReceiver")
-
-@MainActor
-final class CloudKitReceiver: ObservableObject {
- @Published var sessions: [SessionState] = []
- @Published var syncError: SyncError?
- private var isFetching = false
-
- enum SyncError {
- case quotaExceeded
- case networkUnavailable
- case other(String)
-
- var title: String {
- switch self {
- case .quotaExceeded: "iCloud Storage Full"
- case .networkUnavailable: "No Network"
- case .other: "Sync Error"
- }
- }
- }
-
- private static let cacheURL: URL = {
- let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
- return dir.appendingPathComponent("codync_sessions.json")
- }()
-
- init() {
- // Load cached data synchronously so UI has content immediately
- if let data = try? Data(contentsOf: Self.cacheURL),
- let cached = try? JSONDecoder().decode([SessionState].self, from: data) {
- sessions = cached
- logger.info("Loaded \(cached.count) cached sessions")
- }
- }
-
- func start() async {
- // Ensure custom zone exists before subscribing
- do {
- try await CloudKitManager.shared.ensureZoneExists()
- } catch {
- logger.warning("Zone creation failed: \(error.localizedDescription)")
- }
- do {
- try await CloudKitManager.shared.subscribeToChanges()
- logger.info("CloudKit zone subscription active")
- } catch {
- logger.error("Failed to subscribe to CloudKit: \(error.localizedDescription)")
- }
- await fetch(source: "initial")
- }
-
- func fetch(source: String = "unknown", force: Bool = false) async {
- guard force || !isFetching else { return }
- isFetching = true
- defer { isFetching = false }
- do {
- sessions = try await CloudKitManager.shared.fetchAll()
- syncError = nil
- logger.info("Fetched \(self.sessions.count) sessions (source: \(source))")
- persistCache()
- } catch let error as CKError where error.code == .quotaExceeded {
- syncError = .quotaExceeded
- logger.error("CloudKit quota exceeded")
- } catch let error as CKError where error.code == .networkUnavailable || error.code == .networkFailure {
- syncError = .networkUnavailable
- logger.error("CloudKit network unavailable")
- } catch {
- syncError = .other(error.localizedDescription)
- logger.error("CloudKit fetch failed: \(error.localizedDescription)")
- }
- }
-
- private func persistCache() {
- let snapshot = sessions
- let url = Self.cacheURL
- Task.detached(priority: .utility) {
- if let data = try? JSONEncoder().encode(snapshot) {
- try? data.write(to: url, options: .atomic)
- }
- }
- }
-}
diff --git a/Codync-iOS/Services/LiveActivityManager.swift b/Codync-iOS/Services/LiveActivityManager.swift
deleted file mode 100644
index 7e2ac80a..00000000
--- a/Codync-iOS/Services/LiveActivityManager.swift
+++ /dev/null
@@ -1,630 +0,0 @@
-import ActivityKit
-import CloudKit
-import Foundation
-import SwiftUI
-import UIKit
-import UserNotifications
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync.ios", category: "LiveActivity")
-
-
-@MainActor
-final class LiveActivityManager: ObservableObject {
- @Published private(set) var trackedSessionIds: Set<String> = []
- @Published private(set) var pinnedSessionIds: Set<String> = []
- private var graceTimers: [String: Date] = [:]
- private var activities: [String: Activity<CodyncAttributes>] = [:]
- private var sessionsByID: [String: SessionState] = [:]
- private var previousStatuses: [String: SessionStatus] = [:] // sessionId → last known status
- private var lastPushedState: [String: CodyncAttributes.ContentState] = [:]
- private var previousTasks: [String: String] = [:] // sessionId → last completed tool
- private var secondPreviousTasks: [String: String] = [:] // sessionId → second-last tool
- private var tickTimer: Timer?
- @Published var mode: LiveActivityMode = .overall
- @Published var maxOverallSessions: Int = 4
- var userPrimarySessionId: String?
- private var overallActivity: Activity<OverallAttributes>?
- private var lastOverallState: OverallAttributes.ContentState?
- private var overallTrackedIds: Set<String> = []
- private var pushTokenTasks: [String: Task<Void, Never>] = [:]
- @AppStorage("codync_darkMode") private var isDarkMode = true
-
- private static let maxActivities = 4
-
- init() {
- startTicking()
- // End all stale activities from previous app sessions on launch
- endAllStaleActivities()
- }
-
- /// Clean up any lingering activities from previous app sessions (crash, reinstall, etc.)
- private func endAllStaleActivities() {
- for activity in Activity<CodyncAttributes>.activities
- where activity.activityState == .active || activity.activityState == .stale {
- Task { await activity.end(nil, dismissalPolicy: .immediate) }
- logger.info("Cleaned up stale Individual activity: \(activity.attributes.sessionId)")
- }
- for activity in Activity<OverallAttributes>.activities
- where activity.activityState == .active || activity.activityState == .stale {
- Task { await activity.end(nil, dismissalPolicy: .immediate) }
- logger.info("Cleaned up stale Overall activity")
- }
- }
-
- /// Tick every second to keep durationSec fresh — drives sparkle animation in Dynamic Island.
- /// Timer callback is @Sendable, so we hop back to @MainActor via Task.
- private func startTicking() {
- tickTimer?.invalidate()
- let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
- Task { @MainActor in
- self?.tickActivities()
- }
- }
- // Fire in .common mode so ticking survives scroll tracking
- RunLoop.main.add(timer, forMode: .common)
- tickTimer = timer
- }
-
- /// Re-establish the tick timer after returning from background — iOS can silently
- /// invalidate timers during long suspensions.
- func ensureTimerRunning() {
- if tickTimer == nil || tickTimer?.isValid == false {
- logger.info("Tick timer was dead — restarting")
- startTicking()
- }
- }
-
- /// Clear cached state so the next updateSessions() pushes unconditionally.
- func invalidateCache() {
- lastPushedState.removeAll()
- lastOverallState = nil
- }
-
- private func tickActivities() {
- // Individual mode: tick each tracked activity
- if !activities.isEmpty {
- for sessionId in activities.keys {
- guard let session = sessionsByID[sessionId] else { continue }
- pushUpdateIfChanged(session)
- }
- }
- // Overall mode: detect iOS-ended activity so next updateSessions() recreates it
- if let activity = overallActivity,
- activity.activityState == .ended || activity.activityState == .dismissed {
- logger.info("Tick detected Overall Activity ended by iOS — clearing")
- overallActivity = nil
- lastOverallState = nil
- }
- }
-
- func isTracking(sessionId: String) -> Bool {
- trackedSessionIds.contains(sessionId)
- }
-
- func isPinned(sessionId: String) -> Bool {
- pinnedSessionIds.contains(sessionId)
- }
-
- // MARK: - Pin / Unpin
-
- func togglePin(_ sessionId: String) {
- if pinnedSessionIds.contains(sessionId) {
- pinnedSessionIds.remove(sessionId)
- Task { try? await CloudKitManager.shared.unpinSession(sessionId) }
- } else {
- guard pinnedSessionIds.count < Self.maxActivities else { return }
- pinnedSessionIds.insert(sessionId)
- Task { try? await CloudKitManager.shared.pinSession(sessionId) }
- }
- // Re-evaluate tracking with current sessions
- updateSessions(Array(sessionsByID.values))
- }
-
- func loadPinnedSessions() async {
- do {
- pinnedSessionIds = try await CloudKitManager.shared.fetchPinnedSessionIds()
- } catch {
- // First run or no pins yet — not an error
- }
- }
-
- func loadPreference() async {
- let pref = await CloudKitManager.shared.fetchLiveActivityPreference()
- mode = pref.mode
- maxOverallSessions = pref.maxSessions
- }
-
- func savePreference() async {
- await CloudKitManager.shared.setLiveActivityPreference(mode: mode, maxSessions: maxOverallSessions)
- }
-
- // MARK: - Recovery
-
- /// Recover Activity references that iOS still manages but we lost
- /// (e.g., after app termination + background relaunch).
- private func recoverOrphanedActivities() {
- for activity in Activity<CodyncAttributes>.activities {
- let sid = activity.attributes.sessionId
- guard activity.activityState == .active || activity.activityState == .stale else {
- continue
- }
- if activities[sid] == nil {
- activities[sid] = activity
- trackedSessionIds.insert(sid)
- logger.info("Recovered orphaned Live Activity for \(sid)")
- }
- }
- }
-
- /// Prune activities that iOS has ended/dismissed but we still hold references to.
- private func pruneEndedActivities() {
- for (sid, activity) in activities {
- if activity.activityState == .ended || activity.activityState == .dismissed {
- activities.removeValue(forKey: sid)
- trackedSessionIds.remove(sid)
- lastPushedState.removeValue(forKey: sid)
- logger.info("Pruned ended Live Activity for \(sid)")
- }
- }
- }
-
- // MARK: - Unified Update
-
- func updateSessions(_ sessions: [SessionState]) {
- logger.debug("updateSessions (\(self.mode.rawValue)) primary=\(self.userPrimarySessionId ?? "none") sessions=\(sessions.count)")
- sessionsByID = Dictionary(sessions.map { ($0.sessionId, $0) }, uniquingKeysWith: { _, last in last })
-
- // Notify when primary session transitions from working → idle/completed
- if let primaryId = userPrimarySessionId {
- let session = sessionsByID[primaryId]
- let prevStatus = previousStatuses[primaryId]
- #if DEBUG
- logger.info("ALERT CHECK: primary=\(primaryId.suffix(8)) status=\(session?.status.rawValue ?? "nil") prev=\(prevStatus?.rawValue ?? "nil")")
- #endif
- if let session,
- (session.status == .idle || session.status == .needsInput),
- prevStatus == .working {
- #if DEBUG
- logger.info("ALERT SENDING local notification for \(session.projectName)")
- #endif
- sendCompletionNotification(session)
- }
- }
-
- // Track statuses for next comparison
- for session in sessions {
- previousStatuses[session.sessionId] = session.status
- }
-
- switch mode {
- case .individual: updateIndividual(sessions)
- case .overall: updateOverall(sessions)
- }
- }
-
- private func updateIndividual(_ sessions: [SessionState]) {
- // Recover any activities iOS still has running but we lost track of
- recoverOrphanedActivities()
- // Remove stale references to activities iOS has already ended
- pruneEndedActivities()
-
- // 1. Clean up completed/dead sessions
- let completedIds = trackedSessionIds.filter { id in
- guard let session = sessionsByID[id] else { return true }
- return session.status == .completed
- }
- for sessionId in completedIds {
- stopTracking(sessionId: sessionId)
- pinnedSessionIds.remove(sessionId)
- graceTimers.removeValue(forKey: sessionId)
- }
-
- // Also clean pinned sessions that no longer exist
- let deadPinIds = pinnedSessionIds.filter { sessionsByID[$0] == nil }
- for sessionId in deadPinIds {
- pinnedSessionIds.remove(sessionId)
- }
-
- // 2. Update grace timers for currently tracked sessions
- for sessionId in trackedSessionIds {
- guard let session = sessionsByID[sessionId] else { continue }
- if session.status == .idle {
- // Start grace timer if not already running
- if graceTimers[sessionId] == nil {
- graceTimers[sessionId] = Date()
- }
- } else {
- // Session is active again — remove grace timer
- graceTimers.removeValue(forKey: sessionId)
- }
- }
-
- // 3. Build desired set: auto-fill by priority up to maxOverallSessions
- var desired: [String] = []
-
- let maxSlots = maxOverallSessions
- let candidates = sortedSessions(sessions.filter { $0.status != .completed })
-
- for session in candidates {
- guard desired.count < maxSlots else { break }
- // Skip idle sessions past grace
- if session.status == .idle && !isInGrace(session.sessionId) {
- continue
- }
- desired.append(session.sessionId)
- }
-
- let desiredSet = Set(desired)
-
- // 4. Stop tracking sessions not in desired set
- let toRemove = trackedSessionIds.filter { !desiredSet.contains($0) }
- for sessionId in toRemove {
- stopTracking(sessionId: sessionId)
- graceTimers.removeValue(forKey: sessionId)
- }
-
- // 5. Start/update tracking for desired sessions
- for sessionId in desired {
- guard let session = sessionsByID[sessionId] else { continue }
- if !isTracking(sessionId: sessionId) {
- startTracking(session)
- } else {
- pushUpdateIfChanged(session)
- }
- }
- }
-
- private func updateOverall(_ sessions: [SessionState]) {
- // End orphaned Overall activities that iOS still manages but we lost reference to
- // (e.g., after app reinstall or crash). Don't recover — end them and create fresh.
- for activity in Activity<OverallAttributes>.activities
- where activity.id != overallActivity?.id
- && (activity.activityState == .active || activity.activityState == .stale) {
- Task { await activity.end(nil, dismissalPolicy: .immediate) }
- logger.info("Ended orphaned Overall Live Activity")
- }
-
- // Detect if iOS ended the activity (stale timeout, user dismissed, etc.)
- if let activity = overallActivity,
- activity.activityState == .ended || activity.activityState == .dismissed {
- logger.info("Overall Live Activity was ended by iOS — will recreate")
- overallActivity = nil
- lastOverallState = nil
- }
-
- // Pro: ensure we're observing push token for existing activity
- if let activity = overallActivity, PremiumManager.shared.isPro {
- if activity.pushToken == nil && pushTokenTasks["__overall__"] == nil {
- // Activity exists but wasn't created with pushType: .token — recreate
- logger.info("Pro active but Overall Activity has no push token — recreating")
- Task { await activity.end(nil, dismissalPolicy: .immediate) }
- overallActivity = nil
- lastOverallState = nil
- } else if pushTokenTasks["__overall__"] == nil {
- // Activity has token but we're not observing — start observing + save existing token
- logger.info("Resuming push token observation for existing Overall Activity")
- observeOverallPushToken(activity: activity)
- if let token = activity.pushToken {
- let hex = token.map { String(format: "%02x", $0) }.joined()
- logger.info("Existing Overall push token: \(hex.prefix(8))...")
- Task { await savePushToken(sessionId: "__overall__", tokenHex: hex) }
- }
- }
- }
-
- let active = sortedSessions(sessions.filter { $0.status != .completed })
- .prefix(maxOverallSessions)
-
- let summaries = active.map { session in
- let liveDuration = max(session.durationSec, Int(Date().timeIntervalSince(session.startedAt)))
- return SessionSummary(
- sessionId: session.sessionId,
- projectName: session.projectName,
- status: session.status,
- model: session.model,
- currentTask: session.currentTask,
- costUSD: session.costUSD,
- durationSec: liveDuration,
- completedCount: session.completedTaskCount,
- totalCount: session.totalTaskCount
- )
- }
-
- let totalCost = sessions.reduce(0) { $0 + $1.costUSD }
- // User-selected primary takes precedence, then auto-pick first working
- let resolvedPrimaryId = userPrimarySessionId.flatMap { id in
- active.contains(where: { $0.sessionId == id }) ? id : nil
- } ?? active.first(where: { $0.status == .working })?.sessionId
- ?? active.first?.sessionId
-
- let state = OverallAttributes.ContentState(
- sessions: summaries,
- primarySessionId: resolvedPrimaryId,
- totalCost: totalCost,
- isDark: isDarkMode
- )
-
- logger.debug("Overall state: primary=\(resolvedPrimaryId ?? "nil"), sessions=\(summaries.count)")
- guard state != lastOverallState else { return }
- lastOverallState = state
-
- if overallActivity == nil {
- guard UIApplication.shared.applicationState == .active else { return }
- let isPro = PremiumManager.shared.isPro
- do {
- let activity = try Activity.request(
- attributes: OverallAttributes(),
- content: .init(state: state, staleDate: nil),
- pushType: isPro ? .token : nil
- )
- overallActivity = activity
- if isPro {
- observeOverallPushToken(activity: activity)
- }
- logger.info("Started Overall Live Activity with \(summaries.count) sessions (push: \(isPro))")
- } catch {
- logger.error("Failed to start Overall Live Activity: \(error)")
- }
- } else if let activity = overallActivity {
- let content = ActivityContent(state: state, staleDate: nil, relevanceScore: 100)
- Task {
- await activity.update(content)
- }
- }
-
- // Track sessions seen in Overall mode
- for session in active {
- overallTrackedIds.insert(session.sessionId)
- }
-
- // Clean up completed sessions from overall tracking
- for session in sessions where session.status == .completed {
- overallTrackedIds.remove(session.sessionId)
- }
- }
-
- func switchMode(to newMode: LiveActivityMode) async {
- guard newMode != mode else { return }
- logger.info("Switching Live Activity mode: \(self.mode.rawValue) → \(newMode.rawValue)")
-
- // 1. End current mode's activities with await
- if mode == .individual {
- let snapshot = Array(activities.values)
- activities.removeAll()
- trackedSessionIds.removeAll()
- lastPushedState.removeAll()
- for activity in snapshot {
- await Task { await activity.end(nil, dismissalPolicy: .immediate) }.value
- }
- } else if let activity = overallActivity {
- overallActivity = nil
- lastOverallState = nil
- await Task { await activity.end(nil, dismissalPolicy: .immediate) }.value
- }
-
- // 2. Scan and end ALL orphaned iOS-managed activities (crash recovery)
- for activity in Activity<CodyncAttributes>.activities
- where activity.activityState == .active || activity.activityState == .stale {
- await Task { await activity.end(nil, dismissalPolicy: .immediate) }.value
- }
- for activity in Activity<OverallAttributes>.activities
- where activity.activityState == .active || activity.activityState == .stale {
- await Task { await activity.end(nil, dismissalPolicy: .immediate) }.value
- }
-
- // 3. Safety clear all internal state
- activities.removeAll()
- trackedSessionIds.removeAll()
- previousStatuses.removeAll()
- previousTasks.removeAll()
- secondPreviousTasks.removeAll()
- graceTimers.removeAll()
- lastPushedState.removeAll()
- pushTokenTasks.values.forEach { $0.cancel() }
- pushTokenTasks.removeAll()
- overallActivity = nil
- lastOverallState = nil
- overallTrackedIds.removeAll()
-
- // 4-5. Set new mode and persist
- mode = newMode
- await savePreference()
-
- // 6. Recreate with current data
- updateSessions(Array(sessionsByID.values))
- }
-
- // MARK: - Grace Period Helpers
-
- private func isInGrace(_ sessionId: String) -> Bool {
- guard let start = graceTimers[sessionId] else { return false }
- return Date().timeIntervalSince(start) < 60
- }
-
- /// Unified session sort: primary first, then by status priority.
- func sortedSessions(_ sessions: [SessionState]) -> [SessionState] {
- let pid = userPrimarySessionId
- return sessions.sorted { a, b in
- if a.sessionId == pid { return true }
- if b.sessionId == pid { return false }
- return autoFillPriority(a) < autoFillPriority(b)
- }
- }
-
- private func autoFillPriority(_ session: SessionState) -> Int {
- switch session.status {
- case .working: return 0
- case .needsInput: return 1
- case .compacting: return 2
- case .idle: return isInGrace(session.sessionId) ? 3 : 4
- case .error: return 4
- case .completed: return 5
- }
- }
-
- // MARK: - Core
-
- private func startTracking(_ session: SessionState) {
- guard !isTracking(sessionId: session.sessionId) else { return }
- guard trackedSessionIds.count < Self.maxActivities else { return }
-
- // Can only START Live Activities when app is in foreground
- guard UIApplication.shared.applicationState == .active else {
- logger.debug("Skipping Live Activity start — app in background")
- return
- }
-
- let attributes = CodyncAttributes(
- sessionId: session.sessionId,
- projectName: session.projectName,
- summary: session.summary
- )
- let state = contentState(from: session)
- let isPro = PremiumManager.shared.isPro
- do {
- let activity = try Activity.request(
- attributes: attributes,
- content: .init(state: state, staleDate: nil),
- pushType: isPro ? .token : nil
- )
- activities[session.sessionId] = activity
- lastPushedState[session.sessionId] = state
- trackedSessionIds.insert(session.sessionId)
- if isPro {
- observePushToken(activity: activity, sessionId: session.sessionId)
- }
- logger.info("Started Live Activity for \(session.sessionId) (push: \(isPro))")
- } catch {
- logger.error("Failed to start Live Activity: \(error)")
- }
- }
-
- // MARK: - Push Token Sync (Pro only)
-
- private func observePushToken(activity: Activity<CodyncAttributes>, sessionId: String) {
- pushTokenTasks[sessionId]?.cancel()
- pushTokenTasks[sessionId] = Task {
- for await token in activity.pushTokenUpdates {
- let hex = token.map { String(format: "%02x", $0) }.joined()
- logger.info("Push token for \(sessionId): \(hex.prefix(8))...")
- await savePushToken(sessionId: sessionId, tokenHex: hex)
- }
- }
- }
-
- private func observeOverallPushToken(activity: Activity<OverallAttributes>) {
- pushTokenTasks["__overall__"]?.cancel()
- pushTokenTasks["__overall__"] = Task {
- for await token in activity.pushTokenUpdates {
- let hex = token.map { String(format: "%02x", $0) }.joined()
- logger.info("Overall push token: \(hex.prefix(8))...")
- await savePushToken(sessionId: "__overall__", tokenHex: hex)
- }
- }
- }
-
- private func savePushToken(sessionId: String, tokenHex: String) async {
- let recordID = CKRecord.ID(
- recordName: "pushtoken-\(sessionId)",
- zoneID: CloudKitManager.zoneID
- )
- do {
- // Fetch existing record or create new one (upsert)
- let record: CKRecord
- do {
- record = try await CloudKitManager.shared.database.record(for: recordID)
- } catch {
- record = CKRecord(recordType: "PushToken", recordID: recordID)
- }
- record["sessionId"] = sessionId as CKRecordValue
- record["token"] = tokenHex as CKRecordValue
- record["updatedAt"] = Date() as CKRecordValue
- _ = try await CloudKitManager.shared.database.save(record)
- logger.info("Saved push token to CloudKit for \(sessionId)")
- } catch {
- logger.error("Failed to save push token: \(error.localizedDescription)")
- }
- }
-
- /// Push an activity update only if non-time fields changed.
- /// durationSec changes every second — comparing it would cause constant updates.
- private func pushUpdateIfChanged(_ session: SessionState) {
- guard let activity = activities[session.sessionId] else { return }
- let state = contentState(from: session)
-
- let prev = lastPushedState[session.sessionId]
- let fieldChange = prev == nil
- || prev?.status != state.status
- || prev?.model != state.model
- || prev?.completedCount != state.completedCount
- || prev?.totalCount != state.totalCount
- || prev?.currentTask != state.currentTask
- || prev?.previousTask != state.previousTask
- || prev?.contextPct != state.contextPct
- || prev?.costUSD != state.costUSD
- // Update every 2s for sparkle animation, even without field changes
- let animationTick = prev != nil && (state.durationSec / 2 != prev!.durationSec / 2)
-
- guard fieldChange || animationTick else { return }
-
- if let prev, prev.status != state.status {
- logger.info("[\(session.projectName)] status changed: \(prev.status) → \(state.status)")
- }
- lastPushedState[session.sessionId] = state
- // Pinned sessions get highest relevance → iOS shows them in Dynamic Island
- let score: Double = pinnedSessionIds.contains(session.sessionId) ? 100 : 25
- Task {
- await activity.update(.init(state: state, staleDate: nil, relevanceScore: score))
- }
- }
-
- private func stopTracking(sessionId: String) {
- guard let activity = activities.removeValue(forKey: sessionId) else { return }
- trackedSessionIds.remove(sessionId)
- lastPushedState.removeValue(forKey: sessionId)
- pushTokenTasks.removeValue(forKey: sessionId)?.cancel()
- Task {
- await activity.end(nil, dismissalPolicy: .immediate)
- }
- }
-
- private func contentState(from session: SessionState) -> CodyncAttributes.ContentState {
- // Track tool changes: when currentTask changes, old one becomes previousTask
- let currentTool = session.currentTask
- if let current = currentTool,
- let prev = lastPushedState[session.sessionId]?.currentTask,
- current != prev, !prev.isEmpty {
- // Shift chain: previous → secondPrevious, current → previous
- secondPreviousTasks[session.sessionId] = previousTasks[session.sessionId]
- previousTasks[session.sessionId] = prev
- }
-
- let liveDuration = max(session.durationSec, Int(Date().timeIntervalSince(session.startedAt)))
- return .init(
- status: session.status.rawValue,
- model: session.model,
- tasks: session.truncatedTasks,
- completedCount: session.completedTaskCount,
- totalCount: session.totalTaskCount,
- currentTask: currentTool,
- previousTask: previousTasks[session.sessionId],
- secondPreviousTask: secondPreviousTasks[session.sessionId],
- contextPct: session.contextPct,
- costUSD: session.costUSD,
- durationSec: liveDuration,
- sessionStartDate: session.startedAt,
- isDark: isDarkMode
- )
- }
-
- private func sendCompletionNotification(_ session: SessionState) {
- let content = UNMutableNotificationContent()
- content.title = session.projectName
- content.body = "Session complete"
- content.sound = .default
- let request = UNNotificationRequest(identifier: session.sessionId, content: content, trigger: nil)
- UNUserNotificationCenter.current().add(request)
- }
-}
diff --git a/Codync-iOS/Services/PremiumManager.swift b/Codync-iOS/Services/PremiumManager.swift
deleted file mode 100644
index 116e847c..00000000
--- a/Codync-iOS/Services/PremiumManager.swift
+++ /dev/null
@@ -1,55 +0,0 @@
-import Foundation
-import RevenueCat
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync.ios", category: "Premium")
-
-@MainActor
-@Observable
-final class PremiumManager {
- static let shared = PremiumManager()
-
- fileprivate(set) var isPro = false
- private(set) var isLoaded = false
-
- private init() {}
-
- func configure() {
- Purchases.logLevel = .warn
- Purchases.configure(withAPIKey: RevenueCatSecrets.apiKey)
- Purchases.shared.delegate = RCPurchasesDelegate.shared
- Task { await refreshStatus() }
- }
-
- func refreshStatus() async {
- do {
- let info = try await Purchases.shared.customerInfo()
- isPro = info.entitlements["Codync Pro"]?.isActive == true
- isLoaded = true
- logger.info("Premium status: \(self.isPro ? "Pro" : "Free")")
- } catch {
- logger.warning("Failed to fetch customer info: \(error.localizedDescription)")
- isLoaded = true
- }
- }
-
- func restorePurchases() async throws {
- let info = try await Purchases.shared.restorePurchases()
- isPro = info.entitlements["Codync Pro"]?.isActive == true
- logger.info("Restored purchases: \(self.isPro ? "Pro" : "Free")")
- }
-}
-
-// MARK: - Delegate
-
-private final class RCPurchasesDelegate: NSObject, RevenueCat.PurchasesDelegate, Sendable {
- static let shared = RCPurchasesDelegate()
-
- nonisolated func purchases(_ purchases: Purchases, receivedUpdated customerInfo: CustomerInfo) {
- let isPro = customerInfo.entitlements["Codync Pro"]?.isActive == true
- Task { @MainActor in
- PremiumManager.shared.isPro = isPro
- logger.info("Customer info updated: \(isPro ? "Pro" : "Free")")
- }
- }
-}
diff --git a/Codync-iOS/Services/PrimarySessionManager.swift b/Codync-iOS/Services/PrimarySessionManager.swift
deleted file mode 100644
index 3b672a03..00000000
--- a/Codync-iOS/Services/PrimarySessionManager.swift
+++ /dev/null
@@ -1,76 +0,0 @@
-import Foundation
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync.ios", category: "PrimarySession")
-
-@MainActor
-final class PrimarySessionManager: ObservableObject {
- @Published var primarySessionId: String?
- @Published var isManuallyLocked: Bool = false
-
- func autoSelect(from sessions: [SessionState]) {
- guard isManuallyLocked else {
- // No manual lock — no primary session
- if primarySessionId != nil {
- primarySessionId = nil
- }
- return
- }
- // If locked session disappeared, unlock
- if let lockedId = primarySessionId,
- !sessions.contains(where: { $0.sessionId == lockedId }) {
- logger.info("Locked primary session \(lockedId) no longer exists, unlocking")
- isManuallyLocked = false
- primarySessionId = nil
- }
- }
-
- func manualLock(_ sessionId: String) {
- if primarySessionId == sessionId && isManuallyLocked {
- // Tap again to deselect — let algorithm auto-decide
- isManuallyLocked = false
- primarySessionId = nil
- logger.info("Deselected primary: \(sessionId)")
- Task { await save() }
- return
- }
- primarySessionId = sessionId
- isManuallyLocked = true
- logger.info("Manually locked primary: \(sessionId)")
- Task { await save() }
- }
-
- func unlock() {
- isManuallyLocked = false
- logger.info("Unlocked primary session")
- Task { await save() }
- }
-
- func load() async {
- let result = await CloudKitManager.shared.fetchPrimarySession()
- primarySessionId = result.sessionId
- isManuallyLocked = result.locked
- if let id = result.sessionId {
- logger.info("Loaded primary: \(id), locked: \(result.locked)")
- }
- }
-
- func save() async {
- if let id = primarySessionId {
- await CloudKitManager.shared.setPrimarySession(id, locked: isManuallyLocked)
- } else {
- await CloudKitManager.shared.clearPrimarySession()
- }
- }
-
- private func autoFillPriority(_ s: SessionState) -> Int {
- switch s.status {
- case .working: 5
- case .needsInput: 4
- case .compacting: 3
- case .idle, .error: 2
- case .completed: 0
- }
- }
-}
diff --git a/Codync-iOS/Views/BotEditorView.swift b/Codync-iOS/Views/BotEditorView.swift
new file mode 100644
index 00000000..c4c59ad3
--- /dev/null
+++ b/Codync-iOS/Views/BotEditorView.swift
@@ -0,0 +1,236 @@
+import CodyncKit
+import SwiftUI
+
+struct EditorRequest: Identifiable {
+ let id = UUID()
+ var draft: BotDraft
+
+ init(_ draft: BotDraft) { self.draft = draft }
+}
+
+/// Create or edit a bot: who it is, which agent, which project, how much it may do alone.
+struct BotEditorView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ @State var draft: BotDraft
+ @State private var saving = false
+ @State private var error: String?
+ @State private var pickingFolder = false
+
+ private var isNew: Bool { draft.id == nil }
+
+ var body: some View {
+ Form {
+ Section {
+ VStack(spacing: 14) {
+ CharacterAvatar(shape: draft.avatarShape, color: draft.avatarColor, size: 84, mood: .working)
+ TextField("Name", text: $draft.name)
+ .font(.title3.weight(.semibold))
+ .multilineTextAlignment(.center)
+ AvatarPicker(shape: $draft.avatarShape, color: $draft.avatarColor)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 6)
+ }
+
+ Section {
+ TextField("e.g. Reviews PRs. Never pushes without asking. Answers in Traditional Chinese.", text: $draft.description, axis: .vertical)
+ .lineLimit(3...8)
+ } header: {
+ Text("Standing instructions")
+ } footer: {
+ Text("Rules that always apply. Put task-specific requests in the chat instead.")
+ }
+
+ Section("Agent") {
+ Picker("Runs on", selection: $draft.backend) {
+ ForEach(model.hello?.backends ?? []) { b in
+ Text(b.available ? b.name : "\(b.name) (not installed)").tag(b.id)
+ }
+ Text("Custom command").tag("custom")
+ }
+ if let b = model.hello?.backends.first(where: { $0.id == draft.backend }), !b.available {
+ Text(b.installHint).font(.footnote).foregroundStyle(Palette.warning)
+ }
+ if draft.backend == "custom" {
+ TextField("ACP command, e.g. my-agent --acp", text: Binding(get: { draft.command ?? "" }, set: { draft.command = $0.isEmpty ? nil : $0 }))
+ .font(.callout.monospaced())
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ }
+ TextField("Model (optional)", text: Binding(get: { draft.model ?? "" }, set: { draft.model = $0.isEmpty ? nil : $0 }))
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ }
+
+ Section {
+ Button {
+ pickingFolder = true
+ } label: {
+ LabeledContent("Project folder") {
+ Text(draft.cwd.isEmpty ? "Choose…" : (draft.cwd as NSString).lastPathComponent)
+ .foregroundStyle(draft.cwd.isEmpty ? Palette.accent : Palette.secondary)
+ }
+ .foregroundStyle(Palette.text)
+ }
+ } footer: {
+ if !draft.cwd.isEmpty {
+ Text(draft.cwd).font(.caption.monospaced())
+ }
+ }
+
+ Section {
+ Picker("Permissions", selection: $draft.permission) {
+ Text("Ask me").tag("ask")
+ Text("Approve automatically").tag("auto")
+ }
+ Toggle("Notifications", isOn: Binding(get: { draft.notify ?? true }, set: { draft.notify = $0 }))
+ } footer: {
+ Text(draft.permission == "auto"
+ ? "Tool requests are approved once, automatically. Your agent's own settings (like Claude Code's permission rules) still apply."
+ : "You'll get an approval card and a notification whenever the agent asks.")
+ }
+
+ if let error {
+ Section { Text(error).foregroundStyle(Palette.danger) }
+ }
+ }
+ .scrollContentBackground(.hidden)
+ .background(Palette.background)
+ .navigationTitle(isNew ? "New bot" : "Edit bot")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
+ ToolbarItem(placement: .confirmationAction) {
+ if saving {
+ ProgressView()
+ } else {
+ Button(isNew ? "Create" : "Save") { save() }
+ .disabled(draft.name.trimmingCharacters(in: .whitespaces).isEmpty || draft.cwd.isEmpty)
+ }
+ }
+ }
+ .sheet(isPresented: $pickingFolder) {
+ NavigationStack {
+ FolderPicker(path: draft.cwd.isEmpty ? model.hello?.home : draft.cwd) {
+ draft.cwd = $0
+ pickingFolder = false
+ }
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { pickingFolder = false } }
+ }
+ }
+ }
+ .onAppear {
+ if isNew, draft.backend == "claude", model.hello?.backends.first(where: { $0.id == "claude" })?.available == false,
+ let first = model.hello?.backends.first(where: \.available) {
+ draft.backend = first.id
+ }
+ }
+ }
+
+ private func save() {
+ saving = true
+ error = nil
+ if draft.backend != "custom" { draft.command = nil }
+ Task {
+ do {
+ let bot = try await model.save(draft)
+ dismiss()
+ if isNew { Router.shared.open(botId: bot.id) }
+ } catch {
+ self.error = error.localizedDescription
+ }
+ saving = false
+ }
+ }
+}
+
+struct AvatarPicker: View {
+ @Binding var shape: String
+ @Binding var color: String
+
+ var body: some View {
+ VStack(spacing: 12) {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 10) {
+ ForEach(AvatarPalette.shapes, id: \.self) { s in
+ CharacterAvatar(shape: s, color: color, size: 36)
+ .padding(4)
+ .background(Circle().stroke(s == shape ? Palette.accent : .clear, lineWidth: 2))
+ .onTapGesture { shape = s }
+ .accessibilityLabel("\(s) shape")
+ .accessibilityAddTraits(s == shape ? .isSelected : [])
+ }
+ }
+ .padding(.horizontal, 4)
+ }
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 10) {
+ ForEach(AvatarPalette.colors) { c in
+ Circle()
+ .fill(c.color)
+ .frame(width: 26, height: 26)
+ .padding(3)
+ .background(Circle().stroke(c.id == color ? Palette.accent : .clear, lineWidth: 2))
+ .onTapGesture { color = c.id }
+ .accessibilityLabel(c.label)
+ .accessibilityAddTraits(c.id == color ? .isSelected : [])
+ }
+ }
+ .padding(.horizontal, 4)
+ }
+ }
+ }
+}
+
+/// Browses folders on the host.
+struct FolderPicker: View {
+ let path: String?
+ let onPick: (String) -> Void
+ @Environment(AppModel.self) private var model
+ @State private var listing: DirListing?
+ @State private var error: String?
+ @State private var filter = ""
+
+ var body: some View {
+ List {
+ if let listing {
+ Section {
+ Button {
+ onPick(listing.path)
+ } label: {
+ Label("Use “\((listing.path as NSString).lastPathComponent)”", systemImage: "checkmark.circle.fill")
+ .font(.headline)
+ }
+ } footer: {
+ Text(listing.path).font(.caption.monospaced())
+ }
+ Section {
+ ForEach(listing.dirs.filter { filter.isEmpty || $0.name.localizedCaseInsensitiveContains(filter) }) { dir in
+ NavigationLink {
+ FolderPicker(path: dir.path, onPick: onPick)
+ } label: {
+ Label {
+ Text(dir.name)
+ } icon: {
+ Image(systemName: dir.isGit ? "arrow.triangle.branch" : "folder")
+ .foregroundStyle(dir.isGit ? Palette.accent : Palette.secondary)
+ }
+ }
+ }
+ }
+ } else if let error {
+ Text(error).foregroundStyle(Palette.danger)
+ } else {
+ ProgressView()
+ }
+ }
+ .searchable(text: $filter)
+ .navigationTitle(listing.map { ($0.path as NSString).lastPathComponent } ?? "Folders")
+ .navigationBarTitleDisplayMode(.inline)
+ .task {
+ do { listing = try await model.listDirs(path) } catch { self.error = error.localizedDescription }
+ }
+ }
+}
diff --git a/Codync-iOS/Views/BotListView.swift b/Codync-iOS/Views/BotListView.swift
new file mode 100644
index 00000000..5b1ad815
--- /dev/null
+++ b/Codync-iOS/Views/BotListView.swift
@@ -0,0 +1,206 @@
+import CodyncKit
+import SwiftUI
+
+/// The roster: every bot is a person you can message (Grok Bot sidebar, phone-sized).
+struct BotListView: View {
+ @Environment(AppModel.self) private var model
+ @State private var editing: EditorRequest?
+ @State private var showSettings = false
+ @State private var confirmDelete: Bot?
+
+ var body: some View {
+ let roster = model.roster
+ List {
+ Section {
+ ConnectionBanner()
+ if !model.usage.providers.isEmpty {
+ UsageStrip(usage: model.usage)
+ }
+ }
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16))
+
+ if roster.isEmpty {
+ EmptyRoster { editing = EditorRequest(BotDraft()) }
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ }
+
+ ForEach(roster) { bot in
+ NavigationLink(value: bot.id) {
+ BotRow(bot: bot)
+ }
+ .listRowBackground(Palette.background)
+ .listRowSeparatorTint(Palette.border)
+ .swipeActions(edge: .leading) {
+ Button(bot.pinned ? "Unpin" : "Pin", systemImage: bot.pinned ? "pin.slash" : "pin") {
+ model.setPinned(bot, !bot.pinned)
+ }
+ .tint(Palette.accentDim)
+ }
+ .swipeActions(edge: .trailing) {
+ Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = bot }
+ Button("Hide", systemImage: "eye.slash") { model.setHidden(bot, true) }
+ }
+ .contextMenu {
+ Button(bot.pinned ? "Unpin" : "Pin", systemImage: "pin") { model.setPinned(bot, !bot.pinned) }
+ Button("Edit profile", systemImage: "pencil") { editing = EditorRequest(BotDraft(bot)) }
+ Button("Mark as read", systemImage: "checkmark.message") { model.markRead(bot.id) }
+ Button("Hide from list", systemImage: "eye.slash") { model.setHidden(bot, true) }
+ Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = bot }
+ }
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .background(Palette.background)
+ .navigationTitle(model.hostName)
+ .navigationBarTitleDisplayMode(.large)
+ .toolbar {
+ ToolbarItem(placement: .topBarLeading) {
+ Button("Settings", systemImage: "gearshape") { showSettings = true }
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ Button("New bot", systemImage: "plus") {
+ editing = EditorRequest(BotDraft())
+ }
+ .disabled(model.connection != .online)
+ }
+ }
+ .refreshable {
+ model.restartStream()
+ await model.refreshUsage()
+ }
+ .sheet(item: $editing) { request in
+ NavigationStack { BotEditorView(draft: request.draft) }
+ }
+ .sheet(isPresented: $showSettings) {
+ NavigationStack { SettingsView() }
+ }
+ .confirmationDialog(
+ "Delete \(confirmDelete?.name ?? "")?",
+ isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }),
+ titleVisibility: .visible
+ ) {
+ Button("Delete bot and its conversation", role: .destructive) {
+ if let bot = confirmDelete { model.delete(bot) }
+ }
+ } message: {
+ Text("Files it changed on your computer stay as they are.")
+ }
+ }
+}
+
+struct BotRow: View {
+ let bot: Bot
+
+ var body: some View {
+ HStack(spacing: 12) {
+ AvatarWithStatus(bot: bot, size: 46)
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(alignment: .firstTextBaseline) {
+ if bot.pinned {
+ Image(systemName: "pin.fill").font(.caption2).foregroundStyle(Palette.tertiary)
+ }
+ Text(bot.name)
+ .font(.body.weight(bot.unread > 0 ? .semibold : .medium))
+ .foregroundStyle(Palette.text)
+ .lineLimit(1)
+ Spacer(minLength: 8)
+ Text(RelativeTime.short(Date(milliseconds: bot.lastAt)))
+ .font(.caption)
+ .foregroundStyle(bot.unread > 0 ? Palette.accent : Palette.tertiary)
+ .monospacedDigit()
+ }
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ preview
+ Spacer(minLength: 4)
+ if bot.unread > 0 {
+ Text("\(bot.unread)")
+ .font(.caption2.bold())
+ .foregroundStyle(Palette.onAccent)
+ .padding(.horizontal, 6)
+ .frame(minWidth: 18, minHeight: 18)
+ .background(Palette.accentFill, in: Capsule())
+ }
+ }
+ }
+ }
+ .padding(.vertical, 6)
+ .accessibilityElement(children: .combine)
+ }
+
+ /// Live activity while working, otherwise the last message (Grok Bot row behavior).
+ @ViewBuilder private var preview: some View {
+ if bot.needsInput {
+ Label(bot.activity.isEmpty ? "Needs your approval" : bot.activity, systemImage: "hand.raised.fill")
+ .font(.subheadline)
+ .foregroundStyle(Palette.warning)
+ .lineLimit(1)
+ } else if bot.isWorking {
+ HStack(spacing: 6) {
+ ProgressView().controlSize(.mini)
+ Text(bot.activity.isEmpty ? "Working…" : bot.activity)
+ .lineLimit(1)
+ }
+ .font(.subheadline)
+ .foregroundStyle(Palette.accent)
+ } else if bot.status == "error" {
+ Text(bot.lastMessage ?? "Something went wrong")
+ .font(.subheadline)
+ .foregroundStyle(Palette.danger)
+ .lineLimit(2)
+ } else {
+ Text(bot.lastMessage ?? "\(BackendInfo.name(bot.backend)) · \(bot.folderName)")
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ .lineLimit(2)
+ }
+ }
+}
+
+private struct EmptyRoster: View {
+ let create: () -> Void
+
+ var body: some View {
+ VStack(spacing: 14) {
+ CharacterAvatar(shape: "cloud", color: "green", size: 72)
+ Text("No bots yet").font(.title3.bold()).foregroundStyle(Palette.text)
+ Text("Create a bot for each kind of work — a reviewer, a fixer, a docs writer — and point it at a project.")
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ .multilineTextAlignment(.center)
+ Button("Create your first bot", action: create)
+ .buttonStyle(.borderedProminent)
+ .tint(Palette.accentFill)
+ .foregroundStyle(Palette.onAccent)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 40)
+ }
+}
+
+struct ConnectionBanner: View {
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ switch model.connection {
+ case .online, .unpaired:
+ EmptyView()
+ case .connecting:
+ Label("Connecting to \(model.hostName)…", systemImage: "antenna.radiowaves.left.and.right")
+ .font(.footnote)
+ .foregroundStyle(Palette.secondary)
+ case let .offline(reason):
+ HStack(alignment: .top, spacing: 8) {
+ Image(systemName: "wifi.exclamationmark").foregroundStyle(Palette.warning)
+ Text(reason).font(.footnote).foregroundStyle(Palette.secondary)
+ Spacer()
+ Button("Retry") { model.restartStream() }.font(.footnote.bold())
+ }
+ .padding(10)
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 10))
+ }
+ }
+}
diff --git a/Codync-iOS/Views/ComingSoonView.swift b/Codync-iOS/Views/ComingSoonView.swift
deleted file mode 100644
index 0e7f44c8..00000000
--- a/Codync-iOS/Views/ComingSoonView.swift
+++ /dev/null
@@ -1,41 +0,0 @@
-import SwiftUI
-
-struct ComingSoonView: View {
- let icon: String
- let isSystemImage: Bool
- let title: String
- let description: String
- @Environment(\.theme) private var theme
-
- var body: some View {
- VStack(spacing: 16) {
- if isSystemImage {
- Image(systemName: icon)
- .font(.system(size: 48))
- .foregroundStyle(theme.tertiaryText)
- } else {
- Image(icon)
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 48, height: 48)
- .foregroundStyle(theme.tertiaryText)
- }
- Text(title)
- .font(.title2.bold())
- .foregroundStyle(theme.primaryText)
- Text(description)
- .font(.subheadline)
- .foregroundStyle(theme.secondaryText)
- .multilineTextAlignment(.center)
- .padding(.horizontal, 40)
- Text("Coming Soon")
- .font(.caption.bold())
- .foregroundStyle(theme.tertiaryText)
- .padding(.horizontal, 12)
- .padding(.vertical, 6)
- .background(theme.tertiaryText.opacity(0.1), in: Capsule())
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(theme.background)
- }
-}
diff --git a/Codync-iOS/Views/Components/LiveActivityPreview.swift b/Codync-iOS/Views/Components/LiveActivityPreview.swift
deleted file mode 100644
index adf62725..00000000
--- a/Codync-iOS/Views/Components/LiveActivityPreview.swift
+++ /dev/null
@@ -1,209 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-struct LiveActivityPreview: View {
- let mode: LiveActivityMode
- var sessions: [SessionState]?
- var primarySessionId: String?
- var maxSessions: Int = 4
- @Environment(\.theme) private var theme
-
- private var displaySessions: [SessionState] {
- if let sessions, !sessions.isEmpty { return Array(sessions.prefix(maxSessions)) }
- return Array(Self.mockSessions.prefix(maxSessions))
- }
-
- var body: some View {
- Group {
- if mode == .overall {
- overallPreview
- } else {
- individualPreview
- }
- }
- .transition(.opacity.combined(with: .scale(scale: 0.96)))
- .padding(.horizontal, 12)
- .padding(.vertical, 10)
- .background(
- RoundedRectangle(cornerRadius: 20, style: .continuous)
- .fill(Color.black.opacity(0.6))
- .overlay(
- RoundedRectangle(cornerRadius: 20, style: .continuous)
- .stroke(theme.primaryText.opacity(0.06), lineWidth: 1)
- )
- )
- .animation(.easeInOut(duration: 0.3), value: displaySessions.map(\.sessionId))
- .animation(.easeInOut(duration: 0.3), value: displaySessions.map(\.currentTask))
- }
-
- // MARK: - Overall Preview
-
- @ViewBuilder
- private var overallPreview: some View {
- VStack(alignment: .leading, spacing: 4) {
- ForEach(Array(displaySessions.enumerated()), id: \.element.sessionId) { index, session in
- let isPrimary = primarySessionId != nil
- ? session.sessionId == primarySessionId
- : index == 0
-
- OverallSessionRow(
- projectName: session.projectName,
- model: session.model,
- currentTask: session.currentTask,
- status: session.status,
- isPrimary: isPrimary,
- fg: theme.primaryText,
- completedCount: session.completedTaskCount,
- totalCount: session.totalTaskCount
- )
- .padding(.horizontal, 10)
- .padding(.vertical, 8)
- .background(
- RoundedRectangle(cornerRadius: 10, style: .continuous)
- .fill(isPrimary ? theme.primaryText.opacity(0.06) : .clear)
- )
- }
- }
- }
-
- // MARK: - Individual Preview
-
- @ViewBuilder
- private var individualPreview: some View {
- VStack(spacing: 8) {
- ForEach(Array(displaySessions.enumerated()), id: \.element.sessionId) { index, session in
- let isPrimary = primarySessionId != nil
- ? session.sessionId == primarySessionId
- : index == 0
-
- individualCard(session: session, isPrimary: isPrimary)
- }
- }
- }
-
- @ViewBuilder
- private func individualCard(session: SessionState, isPrimary: Bool) -> some View {
- let currentTool = session.currentTask ?? "Working…"
- let prevTool = session.lastEvent ?? session.summary
-
- VStack(alignment: .leading, spacing: 0) {
- // Header
- HStack(spacing: 6) {
- Image(systemName: "chevron.left.forwardslash.chevron.right")
- .font(.system(size: 7, weight: .bold))
- .foregroundStyle(theme.primaryText.opacity(0.5))
- .frame(width: 15, height: 15)
- .background(Circle().fill(theme.primaryText.opacity(0.08)))
-
- Text(session.projectName)
- .font(.system(size: 12, weight: .semibold))
- .foregroundStyle(theme.primaryText.opacity(0.72))
- .lineLimit(1)
-
- Spacer()
-
- if session.costUSD > 0 {
- Text(String(format: "$%.2f", session.costUSD))
- .font(.system(size: 10))
- .foregroundStyle(theme.primaryText.opacity(0.5))
- .monospacedDigit()
- }
- }
-
- Spacer().frame(height: 6)
-
- // Mini card stack — mirrors widget's TaskCard behavior
- ZStack {
- miniCard(text: prevTool, isBehind: true)
- miniCard(text: currentTool, isBehind: false)
- .id(currentTool)
- .transition(.asymmetric(
- insertion: .offset(y: 80),
- removal: .opacity
- ))
- }
- .frame(height: 36)
- .compositingGroup()
- .clipped()
-
- Spacer().frame(height: 6)
-
- // Footer
- HStack(spacing: 4) {
- Image(systemName: "arrow.turn.down.right")
- .font(.system(size: 8, weight: .semibold))
- .foregroundStyle(theme.primaryText.opacity(0.4))
- .frame(width: 14, height: 14)
- Text(currentTool)
- .font(.system(size: 10, weight: .semibold))
- .foregroundStyle(theme.primaryText)
- .lineLimit(1)
- .id(currentTool)
- .transition(.push(from: .bottom))
-
- Spacer()
-
- Text("02:34")
- .font(.system(size: 10, weight: .semibold))
- .foregroundStyle(theme.primaryText.opacity(0.4))
- .monospacedDigit()
- }
- }
- .padding(10)
- .background(
- RoundedRectangle(cornerRadius: 14, style: .continuous)
- .fill(isPrimary ? theme.primaryText.opacity(0.06) : .clear)
- )
- }
-
- // MARK: - Helpers
-
- @ViewBuilder
- private func miniCard(text: String, isBehind: Bool) -> some View {
- HStack(spacing: 6) {
- Image(systemName: "checkmark")
- .font(.system(size: 8, weight: .semibold))
- .foregroundStyle(theme.primaryText.opacity(0.4))
- .frame(width: 14, height: 14)
- .background(Circle().fill(theme.primaryText.opacity(0.08)))
-
- Text(text)
- .font(.system(size: 10))
- .foregroundStyle(isBehind ? theme.primaryText.opacity(0.4) : theme.primaryText)
- .lineLimit(1)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- .padding(8)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(
- RoundedRectangle(cornerRadius: isBehind ? 6 : 10, style: .continuous)
- .fill(isBehind
- ? theme.primaryText.opacity(0.03)
- : Color(red: 0.14, green: 0.14, blue: 0.16))
- )
- .scaleEffect(isBehind ? 0.92 : 1)
- .offset(y: isBehind ? 6 : 0)
- .opacity(isBehind ? 0.5 : 1)
- .zIndex(isBehind ? 0 : 1)
- }
-
- // MARK: - Mock Data
-
- static let mockSessions: [SessionState] = [
- SessionState(
- sessionId: "mock-1", projectName: "Codync", gitBranch: "main",
- status: .working, model: "claude-opus-4-6", summary: "Building UI",
- currentTask: "Reading file", costUSD: 0.42
- ),
- SessionState(
- sessionId: "mock-2", projectName: "MyApp", gitBranch: "feat/auth",
- status: .idle, model: "claude-sonnet-4-6", summary: "Auth flow",
- currentTask: "Editing code", costUSD: 0.18
- ),
- SessionState(
- sessionId: "mock-3", projectName: "Backend", gitBranch: "main",
- status: .idle, model: "claude-haiku-4-5", summary: "API work",
- costUSD: 0.05
- ),
- ]
-}
diff --git a/Codync-iOS/Views/Components/ModePillToggle.swift b/Codync-iOS/Views/Components/ModePillToggle.swift
deleted file mode 100644
index f15640b1..00000000
--- a/Codync-iOS/Views/Components/ModePillToggle.swift
+++ /dev/null
@@ -1,81 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-struct ModePillToggle: View {
- @Binding var mode: LiveActivityMode
- @Environment(\.theme) private var theme
-
- var body: some View {
- HStack(spacing: 0) {
- pillSegment(
- mode: .overall,
- icon: overallIcon,
- label: "Overall"
- )
- pillSegment(
- mode: .individual,
- icon: individualIcon,
- label: "Individual"
- )
- }
- .padding(3)
- .background(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(theme.primaryText.opacity(0.06))
- )
- }
-
- @ViewBuilder
- private func pillSegment(mode segmentMode: LiveActivityMode, icon: some View, label: String) -> some View {
- let isSelected = mode == segmentMode
-
- Button {
- withAnimation(.spring(duration: 0.35, bounce: 0.15)) {
- mode = segmentMode
- }
- } label: {
- HStack(spacing: 6) {
- icon
- Text(label)
- .font(.system(size: 14, weight: isSelected ? .semibold : .regular))
- }
- .foregroundStyle(isSelected ? theme.primaryText : theme.tertiaryText)
- .padding(.vertical, 10)
- .frame(maxWidth: .infinity)
- .background(
- RoundedRectangle(cornerRadius: 10, style: .continuous)
- .fill(isSelected ? theme.primaryText.opacity(0.1) : .clear)
- )
- }
- .buttonStyle(.plain)
- }
-
- // 3-dot grid for Overall
- private var overallIcon: some View {
- Canvas { context, size in
- let fg = theme.primaryText
- let dotSize: CGFloat = 3.5
- let gap: CGFloat = 1.5
- let positions: [(CGFloat, CGFloat, Double)] = [
- (0, 0, 0.8), (dotSize + gap, 0, 0.5),
- (0, dotSize + gap, 0.3), (dotSize + gap, dotSize + gap, 0.15),
- ]
- for (x, y, opacity) in positions {
- let rect = CGRect(x: x + 1, y: y + 1, width: dotSize, height: dotSize)
- context.opacity = mode == .overall ? opacity : opacity * 0.5
- context.fill(
- RoundedRectangle(cornerRadius: 1).path(in: rect),
- with: .color(fg)
- )
- }
- }
- .frame(width: 12, height: 12)
- }
-
- // Single rect for Individual
- private var individualIcon: some View {
- RoundedRectangle(cornerRadius: 2.5, style: .continuous)
- .stroke(mode == .individual ? theme.primaryText : theme.tertiaryText, lineWidth: 1.5)
- .frame(width: 10, height: 10)
- }
-}
diff --git a/Codync-iOS/Views/FreeWarningSheet.swift b/Codync-iOS/Views/FreeWarningSheet.swift
deleted file mode 100644
index 8b965f9b..00000000
--- a/Codync-iOS/Views/FreeWarningSheet.swift
+++ /dev/null
@@ -1,97 +0,0 @@
-import SwiftUI
-
-struct FreeWarningSheet: View {
- @Environment(\.dismiss) private var dismiss
- @Environment(\.theme) private var theme
- @State private var showPaywall = false
-
- var body: some View {
- ZStack {
- theme.background.ignoresSafeArea()
-
- VStack(spacing: 0) {
- // Close button
- HStack {
- Spacer()
- Button { dismiss() } label: {
- Image(systemName: "xmark")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.tertiaryText)
- .frame(width: 32, height: 32)
- .background(theme.cardBackground, in: Circle())
- }
- }
- .padding(.horizontal, 20)
- .padding(.top, 16)
-
- Spacer()
-
- VStack(spacing: 20) {
- Image(systemName: "exclamationmark.triangle.fill")
- .font(.system(size: 40))
- .foregroundStyle(theme.secondaryText)
-
- Text("Free Plan Limitations")
- .font(.title2.bold())
- .foregroundStyle(theme.primaryText)
-
- VStack(alignment: .leading, spacing: 12) {
- warningRow(
- icon: "clock.arrow.circlepath",
- text: "Updates may be delayed — free plan relies on iCloud polling instead of instant push notifications"
- )
- warningRow(
- icon: "livephoto.slash",
- text: "Live Activities may not update in the background when the app is closed"
- )
- warningRow(
- icon: "bell.slash",
- text: "Session completion alerts may arrive late or not at all"
- )
- }
- .padding(.horizontal, 8)
- }
- .padding(.horizontal, 24)
-
- Spacer()
-
- Button {
- showPaywall = true
- } label: {
- Text("Upgrade to Pro")
- .font(.headline)
- .foregroundStyle(theme.isDark ? .black : .white)
- .frame(maxWidth: .infinity)
- .padding(.vertical, 14)
- .background(theme.primaryText, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
- }
- .padding(.horizontal, 24)
- .padding(.bottom, 8)
-
- Button { dismiss() } label: {
- Text("Maybe Later")
- .font(.subheadline)
- .foregroundStyle(theme.tertiaryText)
- }
- .padding(.bottom, 24)
- }
- }
- .sheet(isPresented: $showPaywall) {
- CodyncPaywallView()
- }
- }
-
- @ViewBuilder
- private func warningRow(icon: String, text: String) -> some View {
- HStack(alignment: .top, spacing: 12) {
- Image(systemName: icon)
- .font(.system(size: 16, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- .frame(width: 24)
- Text(text)
- .font(.subheadline)
- .foregroundStyle(theme.secondaryText)
- .fixedSize(horizontal: false, vertical: true)
- }
- }
-}
diff --git a/Codync-iOS/Views/IOSOnboardingView.swift b/Codync-iOS/Views/IOSOnboardingView.swift
deleted file mode 100644
index 9ca8d436..00000000
--- a/Codync-iOS/Views/IOSOnboardingView.swift
+++ /dev/null
@@ -1,1005 +0,0 @@
-import SwiftUI
-import CloudKit
-import UserNotifications
-import CodyncShared
-
-struct IOSOnboardingView: View {
- @ObservedObject var liveActivityManager: LiveActivityManager
- @Environment(\.theme) private var theme
- @AppStorage("codync_onboardingComplete") private var onboardingComplete = false
- @State private var currentPage = 0
- @State private var iCloudStatus: ICloudStatus = .checking
- @State private var selectedMode: LiveActivityMode = .overall
- @State private var showPaywall = false
- @State private var showDemoVideo = false
-
- private let totalPages = 8
-
- var body: some View {
- ZStack {
- theme.background.ignoresSafeArea()
-
- TabView(selection: $currentPage) {
- welcomePage.tag(0)
- macSetupPage.tag(1)
- iCloudPage.tag(2)
- notificationPage.tag(3)
- modePage.tag(4)
- primarySessionPage.tag(5)
- proPage.tag(6)
- liveActivityPermissionPage.tag(7)
- }
- .tabViewStyle(.page(indexDisplayMode: .never))
- .animation(.easeInOut(duration: 0.3), value: currentPage)
- }
- .task {
- await checkICloudStatus()
- }
- .sheet(isPresented: $showDemoVideo) {
- DemoVideoSheet()
- }
- .sheet(isPresented: $showPaywall) {
- CodyncPaywallView()
- .onDisappear {
- if PremiumManager.shared.isPro {
- withAnimation { currentPage = 7 }
- }
- }
- }
- }
-
- // MARK: - Page 1: Welcome
-
- private var welcomePage: some View {
- OnboardingPage(
- theme: theme,
- content: {
- Spacer()
-
- Image("CodyncIcon")
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 100, height: 100)
- .clipShape(RoundedRectangle(cornerRadius: 24, style: .continuous))
- .shadow(color: .white.opacity(0.05), radius: 20)
-
- Spacer().frame(height: 32)
-
- Text("Welcome to Codync")
- .font(.system(size: 32, weight: .bold))
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 12)
-
- Text("Monitor your Claude Code sessions\nin real time from your iPhone")
- .multilineTextAlignment(.center)
- .font(.system(size: 17))
- .foregroundStyle(theme.secondaryText)
- .lineSpacing(4)
-
- Spacer().frame(height: 24)
-
- Button { showDemoVideo = true } label: {
- HStack(spacing: 6) {
- Image(systemName: "play.rectangle.fill")
- .font(.system(size: 14))
- Text("Watch Demo")
- .font(.system(size: 15, weight: .medium))
- }
- .foregroundStyle(theme.primaryText)
- .padding(.horizontal, 18)
- .padding(.vertical, 10)
- .background(
- RoundedRectangle(cornerRadius: 10, style: .continuous)
- .fill(theme.primaryText.opacity(0.1))
- )
- }
-
- Spacer()
- },
- primaryButton: "Get Started",
- primaryAction: { withAnimation { currentPage = 1 } }
- )
- }
-
- // MARK: - Page 2: Install on Mac
-
- private var macSetupPage: some View {
- OnboardingPage(
- theme: theme,
- content: {
- Spacer()
-
- // Mac mockup with notch — 1:1 replica of macOS menu bar
- VStack(spacing: 0) {
- ZStack(alignment: .top) {
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(Color(white: 0.12))
-
- VStack(spacing: 0) {
- // macOS menu bar
- ZStack(alignment: .top) {
- // Menu bar background — translucent like real macOS
- LinearGradient(
- colors: [
- Color(red: 0.22, green: 0.38, blue: 0.58),
- Color(red: 0.28, green: 0.45, blue: 0.65)
- ],
- startPoint: .leading,
- endPoint: .trailing
- )
- .frame(height: 24)
-
- // Notch with Codync icon inside
- HStack(spacing: 0) {
- Spacer()
- HStack(spacing: 0) {
- Spacer().frame(width: 50)
- Image("CodyncIcon")
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 13, height: 13)
- .foregroundStyle(.white.opacity(0.9))
- .padding(.trailing, 8)
- }
- .frame(height: 20)
- .background(.black)
- .clipShape(
- .rect(
- topLeadingRadius: 0,
- bottomLeadingRadius: 10,
- bottomTrailingRadius: 10,
- topTrailingRadius: 0
- )
- )
- Spacer()
- }
- .frame(height: 24, alignment: .top)
- .offset(x: 15)
- }
- .frame(height: 24)
- .clipShape(
- .rect(
- topLeadingRadius: 12,
- bottomLeadingRadius: 0,
- bottomTrailingRadius: 0,
- topTrailingRadius: 12
- )
- )
-
- Spacer().frame(height: 8)
-
- // Terminal window mockup
- VStack(alignment: .leading, spacing: 4) {
- HStack(spacing: 4) {
- Circle().fill(.red.opacity(0.6)).frame(width: 7, height: 7)
- Circle().fill(.yellow.opacity(0.6)).frame(width: 7, height: 7)
- Circle().fill(.green.opacity(0.6)).frame(width: 7, height: 7)
- Spacer()
- }
- Text("$ claude")
- .font(.system(size: 11, design: .monospaced))
- .foregroundStyle(.white.opacity(0.6))
- }
- .padding(10)
- .background(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .fill(.white.opacity(0.05))
- )
- .padding(.horizontal, 10)
-
- Spacer()
- }
- }
- .frame(height: 140)
- .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
- .overlay(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .stroke(.white.opacity(0.1), lineWidth: 1)
- )
- }
- .padding(.horizontal, 44)
-
- Spacer().frame(height: 36)
-
- Text("Install Codync on Mac")
- .font(.system(size: 32, weight: .bold))
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 12)
-
- Text("Download Codync on your Mac to\nmonitor Claude Code sessions.")
- .multilineTextAlignment(.center)
- .font(.system(size: 17))
- .foregroundStyle(theme.secondaryText)
- .lineSpacing(4)
-
- Spacer().frame(height: 16)
-
- Link(destination: URL(string: "https://codync.dev")!) {
- HStack(spacing: 6) {
- Image(systemName: "arrow.down.circle.fill")
- .font(.system(size: 14))
- Text("codync.dev")
- .font(.system(size: 15, weight: .medium))
- }
- .foregroundStyle(theme.primaryText)
- .padding(.horizontal, 18)
- .padding(.vertical, 10)
- .background(
- RoundedRectangle(cornerRadius: 10, style: .continuous)
- .fill(theme.primaryText.opacity(0.1))
- )
- }
-
- Spacer()
- },
- primaryButton: "Continue",
- primaryAction: { withAnimation { currentPage = 2 } },
- secondaryButton: "Back",
- secondaryAction: { withAnimation { currentPage = 0 } }
- )
- }
-
- // MARK: - Page 3: iCloud
-
- private var iCloudPage: some View {
- OnboardingPage(
- theme: theme,
- content: {
- Spacer()
-
- // Faux iCloud card
- VStack(spacing: 0) {
- RoundedRectangle(cornerRadius: 16, style: .continuous)
- .fill(Color(white: 0.95))
- .frame(height: 200)
- .overlay(
- VStack(spacing: 12) {
- Image(systemName: "icloud.fill")
- .font(.system(size: 40))
- .foregroundStyle(.gray.opacity(0.4))
- HStack(spacing: 8) {
- Circle().fill(.gray.opacity(0.15)).frame(width: 36, height: 36)
- VStack(alignment: .leading, spacing: 4) {
- RoundedRectangle(cornerRadius: 3).fill(.gray.opacity(0.15)).frame(width: 120, height: 10)
- RoundedRectangle(cornerRadius: 3).fill(.gray.opacity(0.1)).frame(width: 80, height: 8)
- }
- Spacer()
- RoundedRectangle(cornerRadius: 6).fill(.gray.opacity(0.12)).frame(width: 50, height: 24)
- }
- .padding(.horizontal, 16)
- }
- )
- .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- }
- .padding(.horizontal, 40)
-
- Spacer().frame(height: 40)
-
- Text("iCloud Sync")
- .font(.system(size: 32, weight: .bold))
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 12)
-
- Text("Session status, tasks, and costs sync\nbetween your Mac and iPhone via iCloud.")
- .multilineTextAlignment(.center)
- .font(.system(size: 17))
- .foregroundStyle(theme.secondaryText)
- .lineSpacing(4)
-
- Spacer().frame(height: 14)
-
- HStack(spacing: 6) {
- Image(systemName: "person.crop.circle")
- .font(.system(size: 13))
- .foregroundStyle(theme.tertiaryText)
- Text("Make sure both devices use the same Apple ID")
- .font(.system(size: 13))
- .foregroundStyle(theme.tertiaryText)
- }
-
- Spacer().frame(height: 14)
-
- // Status badge
- HStack(spacing: 6) {
- if iCloudStatus == .checking {
- ProgressView().scaleEffect(0.7)
- } else if iCloudStatus == .available {
- Image(systemName: "checkmark.circle.fill")
- .foregroundStyle(.white)
- } else {
- Image(systemName: "exclamationmark.circle.fill")
- .foregroundStyle(.white.opacity(0.7))
- }
- Text(iCloudSubtitle)
- .font(.system(size: 14))
- .foregroundStyle(theme.secondaryText)
- }
-
- // Action button for iCloud issues
- if iCloudStatus == .noAccount || iCloudStatus == .restricted {
- Button {
- if let url = URL(string: UIApplication.openSettingsURLString) {
- UIApplication.shared.open(url)
- }
- } label: {
- Text("Open Settings")
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(theme.primaryText)
- .padding(.horizontal, 16)
- .padding(.vertical, 8)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(theme.primaryText.opacity(0.1))
- )
- }
- .padding(.top, 8)
- } else if iCloudStatus == .quotaExceeded {
- Button {
- // Open iCloud storage settings
- if let url = URL(string: "App-Prefs:root=CASTLE&path=STORAGE_AND_BACKUP") {
- UIApplication.shared.open(url)
- }
- } label: {
- Text("Manage iCloud Storage")
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(theme.primaryText)
- .padding(.horizontal, 16)
- .padding(.vertical, 8)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(theme.primaryText.opacity(0.1))
- )
- }
- .padding(.top, 8)
- }
-
- Spacer()
- },
- primaryButton: iCloudStatus.isError ? "Retry" : "Continue",
- primaryAction: {
- if iCloudStatus.isError {
- iCloudStatus = .checking
- Task { await checkICloudStatus() }
- } else {
- withAnimation { currentPage = 3 }
- }
- },
- secondaryButton: iCloudStatus.isError ? "Skip" : "Back",
- secondaryAction: {
- if iCloudStatus.isError {
- withAnimation { currentPage = 3 }
- } else {
- withAnimation { currentPage = 1 }
- }
- }
- )
- }
-
- // MARK: - Page 3: Notifications
-
- private var notificationPage: some View {
- NotificationOnboardingPage(
- theme: theme,
- onContinue: { withAnimation { currentPage = 4 } },
- onSkip: { withAnimation { currentPage = 4 } }
- )
- }
-
- // MARK: - Page 4: Mode Selection
-
- private var modePage: some View {
- OnboardingPage(
- theme: theme,
- content: {
- Spacer()
-
- Text("Live Activity Format")
- .font(.system(size: 32, weight: .bold))
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 12)
-
- Text("Choose how sessions appear\non your Dynamic Island and Lock Screen.")
- .multilineTextAlignment(.center)
- .font(.system(size: 17))
- .foregroundStyle(theme.secondaryText)
- .lineSpacing(4)
-
- Spacer().frame(height: 10)
-
- HStack(spacing: 5) {
- Image(systemName: "clock")
- .font(.system(size: 12))
- Text("Updates may have a slight delay from Mac")
- .font(.system(size: 13))
- }
- .foregroundStyle(theme.tertiaryText)
-
- Spacer().frame(height: 20)
-
- ModePillToggle(mode: $selectedMode)
- .padding(.horizontal, 24)
-
- Spacer().frame(height: 16)
-
- LiveActivityPreview(mode: selectedMode)
- .padding(.horizontal, 24)
-
- Spacer()
- },
- primaryButton: "Continue",
- primaryAction: { withAnimation { currentPage = 5 } },
- secondaryButton: "Back",
- secondaryAction: { withAnimation { currentPage = 3 } }
- )
- }
-
- // MARK: - Page 6: Primary Session
-
- @State private var demoPrimary = 0
-
- private var primarySessionPage: some View {
- OnboardingPage(
- theme: theme,
- content: {
- Spacer()
-
- // Interactive demo list
- let sessions = [
- ("Codync", "Opus"),
- ("MyApp", "Sonnet"),
- ("Backend", "Haiku"),
- ]
- VStack(spacing: 2) {
- ForEach(Array(sessions.enumerated()), id: \.offset) { index, session in
- let isPrimary = index == demoPrimary
- HStack(spacing: 8) {
- Circle()
- .fill(theme.primaryText.opacity(isPrimary ? 1 : 0.35))
- .frame(width: 7, height: 7)
- Text(session.0)
- .font(.system(size: 14, weight: isPrimary ? .semibold : .regular))
- .foregroundStyle(theme.primaryText)
- Text(session.1)
- .font(.system(size: 10, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- .padding(.horizontal, 6)
- .padding(.vertical, 2)
- .background(theme.primaryText.opacity(0.08), in: Capsule())
- Spacer()
- Button {
- withAnimation(.spring(duration: 0.3)) { demoPrimary = index }
- } label: {
- Circle()
- .fill(isPrimary ? theme.primaryText : theme.tertiaryText.opacity(0.3))
- .frame(width: isPrimary ? 8 : 6, height: isPrimary ? 8 : 6)
- .frame(width: 28, height: 28)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- }
- .padding(.horizontal, 10)
- .padding(.vertical, 8)
- .background(
- isPrimary
- ? RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(theme.primaryText.opacity(0.06))
- : nil
- )
- }
- }
- .padding(10)
- .background(
- RoundedRectangle(cornerRadius: 16, style: .continuous)
- .fill(theme.cardBackground)
- .overlay(
- RoundedRectangle(cornerRadius: 16, style: .continuous)
- .stroke(theme.border, lineWidth: 1)
- )
- )
- .padding(.horizontal, 40)
-
- Spacer().frame(height: 36)
-
- Text("Primary Session")
- .font(.system(size: 32, weight: .bold))
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 12)
-
- Text("Tap the circle to pin a session.\nShown first on Dynamic Island and Lock Screen.\nOnly the primary session triggers completion alerts.")
- .multilineTextAlignment(.center)
- .font(.system(size: 16))
- .foregroundStyle(theme.secondaryText)
- .lineSpacing(4)
-
- Spacer()
- },
- primaryButton: "Continue",
- primaryAction: { withAnimation { currentPage = 6 } },
- secondaryButton: "Back",
- secondaryAction: { withAnimation { currentPage = 4 } }
- )
- }
-
- // MARK: - Page 7: Pro Upsell
-
- private var proPage: some View {
- OnboardingPage(
- theme: theme,
- content: {
- Spacer()
-
- Image(systemName: "crown.fill")
- .font(.system(size: 44))
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 20)
-
- HStack(spacing: 8) {
- Text("Codync Pro")
- .font(.system(size: 32, weight: .bold))
- Text("$0.99/mo")
- .font(.system(size: 17, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- }
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 14)
-
- HStack(spacing: 8) {
- Image(systemName: "exclamationmark.triangle.fill")
- .font(.system(size: 15))
- Text("Free: sync stops after the app is closed for a while")
- .font(.system(size: 15, weight: .semibold))
- }
- .foregroundStyle(theme.primaryText)
- .padding(.horizontal, 28)
-
- Spacer().frame(height: 20)
-
- VStack(alignment: .leading, spacing: 14) {
- proFeatureRow("Instant push updates to Live Activity")
- proFeatureRow("Works even when app is closed")
- proFeatureRow("Background completion alerts")
- }
- .padding(.horizontal, 40)
-
- Spacer()
- },
- primaryButton: PremiumManager.shared.isPro ? "Continue" : "Subscribe & Start",
- primaryAction: {
- if PremiumManager.shared.isPro {
- withAnimation { currentPage = 7 }
- } else {
- showPaywall = true
- }
- },
- secondaryButton: PremiumManager.shared.isPro ? "Back" : "Continue Free",
- secondaryAction: {
- withAnimation { currentPage = 7 }
- }
- )
- }
-
- // MARK: - Page 8: Live Activity Permission
-
- private var liveActivityPermissionPage: some View {
- OnboardingPage(
- theme: theme,
- content: {
- Spacer()
-
- // Faux Live Activity permission dialog — mimics real iOS alert
- VStack(spacing: 0) {
- // Session list (dark card) — top portion
- VStack(spacing: 2) {
- fauxLARow(name: "my-project", model: "Opus", task: "Reading file...")
- fauxLARow(name: "backend", model: "Sonnet", task: nil)
- fauxLARow(name: "web-app", model: "Haiku", task: "Editing code")
- }
- .padding(12)
- .frame(maxWidth: .infinity)
- .background(Color(white: 0.13))
-
- // Thin separator between session list and dialog
- Color.white.opacity(0.08)
- .frame(height: 1)
-
- // Permission dialog — bottom portion, slightly lighter
- VStack(spacing: 0) {
- Text("Allow Live Activities\nfrom \u{201C}Codync\u{201D}?")
- .font(.system(size: 16, weight: .medium))
- .foregroundStyle(.white.opacity(0.9))
- .multilineTextAlignment(.center)
- .lineSpacing(3)
- .padding(.top, 18)
- .padding(.bottom, 16)
- .padding(.horizontal, 16)
-
- Divider().overlay(.white.opacity(0.12))
-
- HStack(spacing: 0) {
- Button {} label: {
- Text("Don't Allow")
- .font(.system(size: 16))
- .foregroundStyle(.white.opacity(0.55))
- .frame(maxWidth: .infinity)
- .padding(.vertical, 14)
- }
-
- Divider().overlay(.white.opacity(0.12)).frame(height: 44)
-
- Button {} label: {
- Text("Allow")
- .font(.system(size: 16, weight: .semibold))
- .foregroundStyle(.white.opacity(0.9))
- .frame(maxWidth: .infinity)
- .padding(.vertical, 14)
- }
- }
- }
- .background(Color(white: 0.18))
- }
- .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
- .overlay(
- RoundedRectangle(cornerRadius: 16, style: .continuous)
- .stroke(.white.opacity(0.1), lineWidth: 1)
- )
- .padding(.horizontal, 36)
-
- Spacer().frame(height: 32)
-
- Text("Allow Live Activities")
- .font(.system(size: 32, weight: .bold))
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 12)
-
- Text("This is not a real prompt — just a preview.\nWhen iOS asks you later, tap \u{201C}Allow\u{201D}\nfor real-time Dynamic Island updates.")
- .multilineTextAlignment(.center)
- .font(.system(size: 16))
- .foregroundStyle(theme.secondaryText)
- .lineSpacing(4)
-
- Spacer()
- },
- primaryButton: "Start Monitoring",
- primaryAction: {
- liveActivityManager.mode = selectedMode
- Task { await liveActivityManager.savePreference() }
- onboardingComplete = true
- },
- secondaryButton: "Back",
- secondaryAction: { withAnimation { currentPage = 6 } }
- )
- }
-
- private func fauxLARow(name: String, model: String, task: String?) -> some View {
- HStack(spacing: 8) {
- Circle()
- .fill(.white.opacity(task != nil ? 0.8 : 0.35))
- .frame(width: 7, height: 7)
- Text(name)
- .font(.system(size: 14, weight: .semibold))
- .foregroundStyle(.white)
- Text(model)
- .font(.system(size: 10, weight: .medium))
- .foregroundStyle(.white.opacity(0.4))
- .padding(.horizontal, 5)
- .padding(.vertical, 2)
- .background(.white.opacity(0.08), in: Capsule())
- Spacer()
- if let task {
- Text(task)
- .font(.system(size: 11))
- .foregroundStyle(.white.opacity(0.35))
- .lineLimit(1)
- }
- }
- .padding(.horizontal, 8)
- .padding(.vertical, 6)
- }
-
- private func proFeatureRow(_ text: String) -> some View {
- HStack(spacing: 10) {
- Image(systemName: "checkmark")
- .font(.system(size: 12, weight: .bold))
- .foregroundStyle(theme.primaryText)
- Text(text)
- .font(.system(size: 15))
- .foregroundStyle(theme.secondaryText)
- }
- }
-
- // MARK: - Helpers
-
- private var iCloudSubtitle: String {
- switch iCloudStatus {
- case .checking: return "Checking iCloud status…"
- case .available: return "iCloud is ready"
- case .noAccount: return "Sign in to iCloud in Settings"
- case .restricted: return "iCloud is restricted on this device"
- case .quotaExceeded: return "iCloud storage is full"
- case .error(let msg): return msg
- }
- }
-
- private func checkICloudStatus() async {
- do {
- let status = try await CKContainer.default().accountStatus()
- switch status {
- case .available:
- // Account OK — verify CloudKit zone works (catches quota issues)
- do {
- try await CloudKitManager.shared.ensureZoneExists()
- await MainActor.run { iCloudStatus = .available }
- } catch let error as CKError where error.code == .quotaExceeded {
- await MainActor.run { iCloudStatus = .quotaExceeded }
- } catch {
- // Zone might already exist, still OK
- await MainActor.run { iCloudStatus = .available }
- }
- case .noAccount:
- await MainActor.run { iCloudStatus = .noAccount }
- case .restricted:
- await MainActor.run { iCloudStatus = .restricted }
- default:
- await MainActor.run { iCloudStatus = .error("iCloud unavailable") }
- }
- } catch {
- let nsError = error as NSError
- await MainActor.run {
- if nsError.code == CKError.quotaExceeded.rawValue {
- iCloudStatus = .quotaExceeded
- } else {
- iCloudStatus = .error("iCloud: \(error.localizedDescription)")
- }
- }
- }
- }
-}
-
-// MARK: - Reusable Page Layout
-
-private struct OnboardingPage<Content: View>: View {
- let theme: CodyncTheme
- @ViewBuilder let content: () -> Content
- let primaryButton: String
- let primaryAction: () -> Void
- var secondaryButton: String? = nil
- var secondaryAction: (() -> Void)? = nil
-
- var body: some View {
- VStack(spacing: 0) {
- content()
-
- // Buttons
- VStack(spacing: 12) {
- Button(action: primaryAction) {
- Text(primaryButton)
- .font(.system(size: 17, weight: .semibold))
- .foregroundStyle(theme.isDark ? .black : .white)
- .frame(maxWidth: .infinity)
- .padding(.vertical, 16)
- .background(
- RoundedRectangle(cornerRadius: 14, style: .continuous)
- .fill(theme.primaryText)
- )
- }
-
- if let secondaryButton, let secondaryAction {
- Button(action: secondaryAction) {
- Text(secondaryButton)
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- }
- }
- }
- .padding(.horizontal, 24)
- .padding(.bottom, 50)
- }
- }
-}
-
-// MARK: - Notification Page (animated)
-
-private struct NotificationOnboardingPage: View {
- let theme: CodyncTheme
- let onContinue: () -> Void
- let onSkip: () -> Void
-
- @State private var notificationEnabled = false
- @State private var showBanner = false
- @State private var appeared = false
-
- var body: some View {
- VStack(spacing: 0) {
- Spacer().frame(height: 60)
-
- // Faux iPhone screen
- VStack(spacing: 0) {
- // iPhone frame with notch
- ZStack(alignment: .top) {
- RoundedRectangle(cornerRadius: 28, style: .continuous)
- .fill(Color(white: 0.94))
-
- VStack(spacing: 0) {
- // Top spacer + Notch
- Spacer().frame(height: 8)
-
- RoundedRectangle(cornerRadius: 20, style: .continuous)
- .fill(.black)
- .frame(width: 100, height: 28)
-
- // Status bar
- HStack {
- Text("9:41")
- .font(.system(size: 12, weight: .semibold))
- Spacer()
- HStack(spacing: 3) {
- Image(systemName: "cellularbars")
- Image(systemName: "wifi")
- Image(systemName: "battery.100")
- }
- .font(.system(size: 10))
- }
- .foregroundStyle(.black.opacity(0.35))
- .padding(.horizontal, 20)
- .padding(.top, 6)
-
- Spacer().frame(height: 8)
-
- // Notification banner — slides down from top
- HStack(spacing: 10) {
- Image("CodyncIcon")
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 34, height: 34)
- .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
-
- VStack(alignment: .leading, spacing: 2) {
- HStack {
- Text("Session Complete")
- .font(.system(size: 13, weight: .semibold))
- .foregroundStyle(.black)
- Spacer()
- Text("now")
- .font(.system(size: 11))
- .foregroundStyle(.black.opacity(0.35))
- }
- Text("my-project finished · $0.42")
- .font(.system(size: 12))
- .foregroundStyle(.black.opacity(0.45))
- }
- }
- .padding(10)
- .background(
- RoundedRectangle(cornerRadius: 16, style: .continuous)
- .fill(.white)
- .shadow(color: .black.opacity(0.06), radius: 10, y: 3)
- )
- .padding(.horizontal, 10)
- .offset(y: showBanner ? 0 : -150)
-
- Spacer()
-
- // Faux app grid
- LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 4), spacing: 8) {
- ForEach(0..<8, id: \.self) { _ in
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(.gray.opacity(0.08))
- .aspectRatio(1, contentMode: .fit)
- }
- }
- .padding(.horizontal, 14)
- .padding(.bottom, 12)
- }
- }
- .frame(height: 300)
- .clipShape(RoundedRectangle(cornerRadius: 28, style: .continuous))
- .overlay(
- RoundedRectangle(cornerRadius: 28, style: .continuous)
- .stroke(.white.opacity(0.1), lineWidth: 1)
- )
- }
- .padding(.horizontal, 36)
-
- Spacer().frame(height: 40)
-
- Text("Stay Updated with\nPush Notifications")
- .multilineTextAlignment(.center)
- .font(.system(size: 32, weight: .bold))
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 12)
-
- Text("Get notified when your Claude Code\nsessions complete, even in background.")
- .multilineTextAlignment(.center)
- .font(.system(size: 17))
- .foregroundStyle(theme.secondaryText)
- .lineSpacing(4)
-
- Spacer()
-
- // Buttons
- VStack(spacing: 12) {
- Button {
- if notificationEnabled {
- onContinue()
- } else {
- Task {
- let center = UNUserNotificationCenter.current()
- let granted = (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false
- if granted {
- // Send a test notification
- let content = UNMutableNotificationContent()
- content.title = "You're all set!"
- content.body = "Codync will notify you when sessions complete."
- content.sound = .default
- let request = UNNotificationRequest(identifier: "onboarding-test", content: content, trigger: UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false))
- try? await center.add(request)
- }
- await MainActor.run {
- if granted {
- withAnimation(.spring(duration: 0.4)) {
- notificationEnabled = true
- }
- }
- }
- }
- }
- } label: {
- Text(notificationEnabled ? "Continue" : "Enable Push Notifications")
- .font(.system(size: 17, weight: .semibold))
- .foregroundStyle(theme.isDark ? .black : .white)
- .frame(maxWidth: .infinity)
- .padding(.vertical, 16)
- .background(
- RoundedRectangle(cornerRadius: 14, style: .continuous)
- .fill(theme.primaryText)
- )
- }
-
- Button(action: onSkip) {
- Text("Ask Me Later")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- }
- }
- .padding(.horizontal, 24)
- .padding(.bottom, 50)
- }
- .onAppear {
- guard !appeared else { return }
- appeared = true
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
- withAnimation(.spring(duration: 0.7, bounce: 0.25)) {
- showBanner = true
- }
- }
- }
- .onDisappear {
- showBanner = false
- appeared = false
- }
- }
-}
-
-// MARK: - ICloud Status
-
-private enum ICloudStatus: Equatable {
- case checking, available, noAccount, restricted, quotaExceeded
- case error(String)
-
- var isError: Bool {
- switch self {
- case .noAccount, .restricted, .quotaExceeded, .error: return true
- default: return false
- }
- }
-}
-
diff --git a/Codync-iOS/Views/IOSRootView.swift b/Codync-iOS/Views/IOSRootView.swift
deleted file mode 100644
index a4890d31..00000000
--- a/Codync-iOS/Views/IOSRootView.swift
+++ /dev/null
@@ -1,82 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-struct IOSRootView: View {
- @ObservedObject var receiver: CloudKitReceiver
- @ObservedObject var liveActivityManager: LiveActivityManager
- @ObservedObject var primarySessionManager: PrimarySessionManager
- @AppStorage("codync_onboardingComplete") private var onboardingComplete = false
- @AppStorage("codync_darkMode") private var storedDarkMode = true
- @State private var isDarkMode = true
- @State private var displayedSessions: [SessionState] = []
- @State private var showSplash = true
-
- var body: some View {
- Group {
- if showSplash {
- splashView
- } else if !onboardingComplete {
- NavigationStack {
- IOSOnboardingView(liveActivityManager: liveActivityManager)
- }
- } else {
- TabRootView(
- sessions: displayedSessions,
- syncError: receiver.syncError,
- liveActivityManager: liveActivityManager,
- primarySessionManager: primarySessionManager
- )
- }
- }
- .environment(\.theme, CodyncTheme(isDark: isDarkMode))
- .preferredColorScheme(isDarkMode ? .dark : .light)
- .onAppear { isDarkMode = storedDarkMode }
- .onChange(of: storedDarkMode) { _, newValue in
- withAnimation(.easeInOut(duration: 0.4)) {
- isDarkMode = newValue
- }
- }
- .onChange(of: receiver.sessions) { _, sessions in
- liveActivityManager.userPrimarySessionId = primarySessionManager.primarySessionId
- liveActivityManager.updateSessions(sessions)
- primarySessionManager.autoSelect(from: sessions)
- withAnimation(.spring(duration: 0.5, bounce: 0.1)) {
- displayedSessions = sortSessions(sessions)
- }
- }
- .onChange(of: primarySessionManager.primarySessionId) { _, newId in
- liveActivityManager.userPrimarySessionId = newId
- liveActivityManager.updateSessions(receiver.sessions)
- withAnimation(.spring(duration: 0.5, bounce: 0.1)) {
- displayedSessions = sortSessions(receiver.sessions)
- }
- }
- .task {
- liveActivityManager.userPrimarySessionId = primarySessionManager.primarySessionId
- displayedSessions = sortSessions(receiver.sessions)
- }
- }
-
- private var splashView: some View {
- ZStack {
- Color(red: 0.06, green: 0.06, blue: 0.07)
- .ignoresSafeArea()
- Image("CodyncIcon")
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 80, height: 80)
- .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
- }
- .onAppear {
- DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
- withAnimation(.easeOut(duration: 0.3)) {
- showSplash = false
- }
- }
- }
- }
-
- private func sortSessions(_ sessions: [SessionState]) -> [SessionState] {
- liveActivityManager.sortedSessions(sessions)
- }
-}
diff --git a/Codync-iOS/Views/IOSSessionDetailView.swift b/Codync-iOS/Views/IOSSessionDetailView.swift
deleted file mode 100644
index 3134514a..00000000
--- a/Codync-iOS/Views/IOSSessionDetailView.swift
+++ /dev/null
@@ -1,180 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-// MARK: - Session Detail
-
-struct IOSSessionDetailView: View {
- let session: SessionState
- @Environment(\.theme) private var theme
-
- var body: some View {
- ScrollView {
- VStack(alignment: .leading, spacing: 16) {
- headerSection
- statsCard
- if !session.tasks.isEmpty {
- tasksSection
- }
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 12)
- }
- .background(theme.background)
- .navigationTitle(session.summary)
- .navigationBarTitleDisplayMode(.inline)
- .toolbarColorScheme(.dark, for: .navigationBar)
- }
-
- private var headerSection: some View {
- VStack(alignment: .leading, spacing: 8) {
- HStack(spacing: 8) {
- SessionStatusView(
- status: session.status,
- completedTasks: session.completedTaskCount,
- totalTasks: session.totalTaskCount,
- waitingReason: session.waitingReason
- )
- Text(statusLabel)
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(statusLabelColor)
- Spacer()
- if !session.model.isEmpty {
- SessionTagView(tag: session.model)
- }
- }
- HStack(spacing: 6) {
- Label(session.projectName, systemImage: "folder")
- if !session.gitBranch.isEmpty && session.gitBranch != "unknown" {
- Text("·")
- Text(session.gitBranch)
- }
- }
- .font(.system(size: 13))
- .foregroundStyle(theme.secondaryText)
- }
- }
-
- private var statsCard: some View {
- HStack(spacing: 0) {
- statItem("\(session.contextPct)%", "Context")
- Divider().frame(height: 28).overlay(theme.separator)
- statItem(String(format: "$%.2f", session.costUSD), "Cost")
- Divider().frame(height: 28).overlay(theme.separator)
- statItem(formatDuration(session.durationSec), "Duration")
- }
- .padding(.vertical, 10)
- .background(
- RoundedRectangle(cornerRadius: 10, style: .continuous)
- .fill(theme.cardBackground)
- .overlay(
- RoundedRectangle(cornerRadius: 10, style: .continuous)
- .stroke(theme.border, lineWidth: 1)
- )
- )
- }
-
- private var tasksSection: some View {
- VStack(alignment: .leading, spacing: 12) {
- HStack(spacing: 12) {
- DetailProgressRing(
- completed: session.completedTaskCount,
- total: session.totalTaskCount
- )
- VStack(alignment: .leading, spacing: 2) {
- Text("Tasks")
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(theme.primaryText)
- Text("\(session.completedTaskCount) of \(session.totalTaskCount) completed")
- .font(.system(size: 13))
- .foregroundStyle(theme.secondaryText)
- }
- Spacer()
- }
-
- VStack(alignment: .leading, spacing: 6) {
- ForEach(session.tasks) { task in
- HStack(spacing: 8) {
- taskIcon(task.status)
- Text(task.content)
- .font(.system(size: 14))
- .foregroundStyle(task.status == .pending ? theme.secondaryText : theme.primaryText)
- .lineLimit(2)
- }
- }
- }
- }
- }
-
- private var statusLabel: String {
- guard session.status == .needsInput else { return session.status.label }
- return session.waitingReason?.label ?? "Needs Input"
- }
-
- private var statusLabelColor: Color {
- guard session.status == .needsInput else { return theme.secondaryText }
- return theme.waitingColor(for: session.waitingReason)
- }
-
- private func taskIcon(_ status: TaskStatus) -> some View {
- Group {
- switch status {
- case .completed:
- Image(systemName: "checkmark.circle.fill").foregroundStyle(theme.primaryText.opacity(0.7))
- case .inProgress:
- Image(systemName: "circlebadge.fill").foregroundStyle(theme.accent)
- case .pending:
- Image(systemName: "circle").foregroundStyle(theme.tertiaryText)
- }
- }
- .font(.system(size: 14))
- }
-
- private func statItem(_ value: String, _ label: String) -> some View {
- VStack(spacing: 3) {
- Text(value)
- .font(.system(size: 16, weight: .semibold, design: .monospaced))
- .foregroundStyle(theme.primaryText)
- Text(label)
- .font(.system(size: 11))
- .foregroundStyle(theme.tertiaryText)
- }
- .frame(maxWidth: .infinity)
- }
-
- private func formatDuration(_ seconds: Int) -> String {
- if seconds < 60 { return "\(seconds)s" }
- if seconds < 3600 { return "\(seconds / 60)m" }
- let h = seconds / 3600
- let m = (seconds % 3600) / 60
- return "\(h)h \(m)m"
- }
-}
-
-private struct DetailProgressRing: View {
- let completed: Int
- let total: Int
- @Environment(\.theme) private var theme
- @State private var animatedProgress: Double = 0
-
- private var progress: Double {
- total > 0 ? Double(completed) / Double(total) : 0
- }
-
- var body: some View {
- ZStack {
- Circle().stroke(theme.secondaryText.opacity(0.15), lineWidth: 3.5)
- Circle()
- .trim(from: 0, to: animatedProgress)
- .stroke(theme.primaryText.opacity(0.7), style: StrokeStyle(lineWidth: 3.5, lineCap: .round))
- .rotationEffect(.degrees(-90))
- Text("\(Int(progress * 100))%")
- .font(.system(size: 12, weight: .semibold, design: .monospaced))
- .foregroundStyle(theme.primaryText)
- }
- .frame(width: 44, height: 44)
- .onAppear { withAnimation(.easeOut(duration: 0.6)) { animatedProgress = progress } }
- .onChange(of: progress) { _, newValue in
- withAnimation(.easeOut(duration: 0.4)) { animatedProgress = newValue }
- }
- }
-}
diff --git a/Codync-iOS/Views/IOSSessionListView.swift b/Codync-iOS/Views/IOSSessionListView.swift
deleted file mode 100644
index e2210487..00000000
--- a/Codync-iOS/Views/IOSSessionListView.swift
+++ /dev/null
@@ -1,292 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-struct IOSSessionListView: View {
- let sessions: [SessionState]
- var syncError: CloudKitReceiver.SyncError?
- @ObservedObject var liveActivityManager: LiveActivityManager
- @ObservedObject var primarySessionManager: PrimarySessionManager
- @Environment(\.theme) private var theme
- @State private var showSettings = false
- @State private var showSettingsSheet = false
- @State private var showDemoVideo = false
- @State private var showPrimaryPrompt = false
- @State private var showFreeWarning = false
- @State private var showSyncError = false
- @AppStorage("codync_didPromptPrimary") private var didPromptPrimary = false
- private var premium: PremiumManager { .shared }
-
- var body: some View {
- ScrollView {
- LazyVStack(spacing: 4) {
- // Collapsible settings
- if showSettings {
- modeSection
- }
-
- // Session list
- ForEach(Array(sessions.enumerated()), id: \.element.sessionId) { index, session in
- NavigationLink(destination: IOSSessionDetailView(session: session)) {
- SessionRowContent(
- session: session,
- isPrimary: primarySessionManager.primarySessionId == session.sessionId,
- depth: index,
- onSetPrimary: { primarySessionManager.manualLock(session.sessionId) }
- )
- }
- .buttonStyle(.plain)
- .tint(theme.primaryText)
- }
- }
- }
- .background(theme.background)
- .navigationBarTitleDisplayMode(.inline)
- .toolbar {
- ToolbarItem(placement: .principal) {
- Button {
- withAnimation(.easeInOut(duration: 0.25)) {
- showSettings.toggle()
- }
- } label: {
- HStack(spacing: 5) {
- Image(systemName: showSettings ? "chevron.up" : "chevron.down")
- .font(.system(size: 9, weight: .semibold))
- Text("Preview")
- .font(.system(size: 13, weight: .medium))
- }
- .foregroundStyle(showSettings ? theme.primaryText : theme.secondaryText)
- .padding(.horizontal, 14)
- .padding(.vertical, 6)
- .background(
- Capsule()
- .fill(showSettings ? theme.primaryText.opacity(0.1) : theme.primaryText.opacity(0.05))
- )
- }
- .buttonStyle(.plain)
- }
- }
- .toolbarColorScheme(theme.isDark ? .dark : .light, for: .navigationBar)
- .toolbar {
- ToolbarItem(placement: .topBarLeading) {
- Button { showDemoVideo = true } label: {
- Image(systemName: "play.rectangle")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- }
- }
- ToolbarItem(placement: .topBarLeading) {
- if !premium.isPro {
- Button { showFreeWarning = true } label: {
- Image(systemName: "exclamationmark.triangle.fill")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- }
- }
- }
- ToolbarItem(placement: .topBarTrailing) {
- if syncError != nil {
- Button { showSyncError = true } label: {
- Image(systemName: "icloud.slash")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- }
- }
- }
- ToolbarItem(placement: .topBarTrailing) {
- Button {
- showSettingsSheet = true
- } label: {
- Image(systemName: "gearshape")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- }
- }
- }
- .sheet(isPresented: $showSettingsSheet) {
- SettingsView()
- }
- .sheet(isPresented: $showDemoVideo) {
- DemoVideoSheet()
- }
- .sheet(isPresented: $showFreeWarning) {
- FreeWarningSheet()
- }
- .sheet(isPresented: $showSyncError) {
- SyncErrorSheet(error: syncError)
- }
- .onChange(of: sessions) { _, newSessions in
- if !didPromptPrimary,
- !newSessions.isEmpty,
- primarySessionManager.primarySessionId == nil {
- didPromptPrimary = true
- showPrimaryPrompt = true
- }
- }
- .alert("Select a Primary Session", isPresented: $showPrimaryPrompt) {
- Button("OK") {}
- } message: {
- Text("Tap the circle on the right of a session to pin it as primary. Only the primary session will send completion alerts.")
- }
- }
-
- @ViewBuilder
- private var modeSection: some View {
- VStack(spacing: 14) {
- ModePillToggle(mode: Binding(
- get: { liveActivityManager.mode },
- set: { newMode in
- Task { await liveActivityManager.switchMode(to: newMode) }
- }
- ))
-
- LiveActivityPreview(
- mode: liveActivityManager.mode,
- sessions: sessions.isEmpty ? nil : sessions,
- primarySessionId: primarySessionManager.primarySessionId,
- maxSessions: liveActivityManager.maxOverallSessions
- )
-
- HStack {
- Text("Max Live Activities")
- .font(.caption.bold())
- .foregroundStyle(theme.secondaryText)
- Spacer()
- Picker("Max", selection: Binding(
- get: { liveActivityManager.maxOverallSessions },
- set: { newVal in
- liveActivityManager.maxOverallSessions = newVal
- Task { await liveActivityManager.savePreference() }
- liveActivityManager.updateSessions(sessions)
- }
- )) {
- ForEach(1...4, id: \.self) { n in
- Text("\(n)").tag(n)
- }
- }
- .pickerStyle(.segmented)
- .frame(width: 160)
- }
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 12)
- }
-}
-
-private struct SessionRowContent: View {
- let session: SessionState
- let isPrimary: Bool
- var depth: Int = 0
- let onSetPrimary: () -> Void
- @Environment(\.theme) private var theme
-
- var body: some View {
- HStack(spacing: 10) {
- SessionStatusView(
- status: session.status,
- completedTasks: session.completedTaskCount,
- totalTasks: session.totalTaskCount,
- waitingReason: session.waitingReason
- )
-
- VStack(alignment: .leading, spacing: 2) {
- HStack(spacing: 5) {
- Text(session.projectName)
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.primaryText)
- .lineLimit(1)
- if !session.model.isEmpty {
- SessionTagView(tag: session.model)
- }
- Spacer(minLength: 4)
- if session.statusDescription == nil {
- timestampLabel
- }
- }
- if let desc = session.statusDescription {
- HStack(spacing: 4) {
- Text(desc)
- .font(.system(size: 13))
- .foregroundStyle(subtitleColor)
- .lineLimit(1)
- .id(desc)
- .transition(.push(from: .bottom))
- .animation(.easeInOut(duration: 0.3), value: desc)
- Spacer()
- timestampLabel
- }
- .clipped()
- }
- if !session.tasks.isEmpty {
- MiniProgressBar(tasks: session.tasks)
- }
- }
-
- Button(action: onSetPrimary) {
- Circle()
- .fill(isPrimary ? theme.primaryText : theme.tertiaryText.opacity(0.3))
- .frame(width: isPrimary ? 8 : 6, height: isPrimary ? 8 : 6)
- .frame(width: 28, height: 28)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 8)
- .padding(.vertical, isPrimary ? 4 : 0)
- .background(
- isPrimary
- ? RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(theme.primaryText.opacity(0.06))
- .padding(.horizontal, 8)
- : nil
- )
- .opacity(depth == 0 ? 1.0 : max(0.65, 1.0 - Double(depth) * 0.1))
- .animation(.spring(duration: 0.5, bounce: 0.15), value: isPrimary)
- .animation(.spring(duration: 0.5, bounce: 0.15), value: depth)
- }
-
- private var timestampLabel: some View {
- Text(relativeTime(session.updatedAt))
- .font(.system(size: 12, design: .monospaced))
- .foregroundStyle(theme.tertiaryText)
- }
-
- private var subtitleColor: Color {
- guard session.status == .needsInput else { return theme.secondaryText }
- return theme.waitingColor(for: session.waitingReason)
- }
-
- private func relativeTime(_ date: Date) -> String {
- let seconds = -date.timeIntervalSinceNow
- if seconds < 60 { return "now" }
- if seconds < 3600 { return "\(Int(seconds / 60))m" }
- if seconds < 86400 { return "\(Int(seconds / 3600))h" }
- if seconds < 604800 { return "\(Int(seconds / 86400))d" }
- return "\(Int(seconds / 604800))w"
- }
-}
-
-private struct MiniProgressBar: View {
- let tasks: [TaskItem]
- @Environment(\.theme) private var theme
-
- var body: some View {
- HStack(spacing: 2) {
- ForEach(tasks) { task in
- RoundedRectangle(cornerRadius: 2)
- .fill(color(for: task.status))
- .frame(height: 5)
- }
- }
- .padding(.top, 2)
- }
-
- private func color(for status: TaskStatus) -> Color {
- switch status {
- case .completed: return theme.accent
- case .inProgress: return theme.accent.opacity(0.4)
- case .pending: return theme.secondaryText.opacity(0.15)
- }
- }
-}
-
diff --git a/Codync-iOS/Views/IOSSessionTagView.swift b/Codync-iOS/Views/IOSSessionTagView.swift
deleted file mode 100644
index 1bc9436c..00000000
--- a/Codync-iOS/Views/IOSSessionTagView.swift
+++ /dev/null
@@ -1,18 +0,0 @@
-import SwiftUI
-
-struct SessionTagView: View {
- let tag: String
- @Environment(\.theme) private var theme
-
- var body: some View {
- Text(tag)
- .font(.system(size: 10, weight: .medium, design: .monospaced))
- .foregroundStyle(theme.tertiaryText)
- .padding(.horizontal, 5)
- .padding(.vertical, 2)
- .background(
- RoundedRectangle(cornerRadius: 4, style: .continuous)
- .fill(theme.border)
- )
- }
-}
diff --git a/Codync-iOS/Views/IOSStatusIndicator.swift b/Codync-iOS/Views/IOSStatusIndicator.swift
deleted file mode 100644
index 2cfebe97..00000000
--- a/Codync-iOS/Views/IOSStatusIndicator.swift
+++ /dev/null
@@ -1,99 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-struct SessionStatusView: View {
- let status: SessionStatus
- let completedTasks: Int
- let totalTasks: Int
- var waitingReason: WaitingReason?
- @Environment(\.theme) private var theme
-
- private var hasTasks: Bool { totalTasks > 0 }
-
- var body: some View {
- if hasTasks {
- SegmentedRingView(
- completedCount: completedTasks,
- totalCount: totalTasks,
- isWorking: status == .working,
- fg: theme.primaryText,
- lineWidth: 1.5,
- gapDegrees: 24
- )
- .frame(width: 12, height: 12)
- } else if status == .working {
- ClaudeSparkleView()
- .frame(width: 14, height: 14)
- } else {
- MinimalDotView(status: status, waitingReason: waitingReason)
- }
- }
-}
-
-// MARK: - Minimal Dot
-
-private struct MinimalDotView: View {
- let status: SessionStatus
- var waitingReason: WaitingReason?
- @Environment(\.theme) private var theme
- @State private var isPulsing = false
-
- private var needsPulse: Bool { status == .needsInput || status == .error }
-
- var body: some View {
- ZStack {
- if needsPulse {
- Circle()
- .fill(dotColor.opacity(0.3))
- .frame(width: 16, height: 16)
- .scaleEffect(isPulsing ? 1.4 : 0.8)
- .opacity(isPulsing ? 0 : 0.6)
- }
- Circle()
- .fill(dotColor)
- .frame(width: 9, height: 9)
- .scaleEffect(isPulsing && needsPulse ? 1.15 : 1.0)
- }
- .frame(width: 14, height: 14)
- .animation(
- needsPulse ? .easeInOut(duration: 1.5).repeatForever(autoreverses: true) : .default,
- value: isPulsing
- )
- .onAppear { if needsPulse { isPulsing = true } }
- .onChange(of: status) { _, _ in withAnimation { isPulsing = needsPulse } }
- }
-
- private var dotColor: Color {
- switch status {
- case .needsInput, .error:
- return theme.waitingColor(for: waitingReason)
- case .idle: return theme.tertiaryText
- case .completed: return theme.tertiaryText.opacity(0.7)
- default: return theme.tertiaryText
- }
- }
-}
-
-// MARK: - Claude Sparkle
-
-struct ClaudeSparkleView: View {
- private static let phases: [String] = ["·", "✢", "✶", "✻", "✽"]
- private static let cycle: [String] = phases + phases.dropFirst().dropLast().reversed()
- @Environment(\.theme) private var theme
- @State private var currentIndex = 0
- private let timer = Timer.publish(every: 0.22, on: .main, in: .common).autoconnect()
-
- var body: some View {
- Text(Self.cycle[currentIndex])
- .font(.system(size: 12))
- .foregroundStyle(theme.primaryText.opacity(opacity))
- .onReceive(timer) { _ in
- currentIndex = (currentIndex + 1) % Self.cycle.count
- }
- }
-
- private var opacity: Double {
- let pos = Double(currentIndex) / Double(Self.cycle.count - 1)
- return 0.4 + sin(pos * .pi) * 0.6
- }
-}
diff --git a/Codync-iOS/Views/IOSTheme.swift b/Codync-iOS/Views/IOSTheme.swift
deleted file mode 100644
index 724e7e87..00000000
--- a/Codync-iOS/Views/IOSTheme.swift
+++ /dev/null
@@ -1,80 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-/// Codync iOS design system — Vercel/Cursor inspired, supports dark and light mode.
-/// Pure black background + #ededed foreground with opacity hierarchy in dark mode;
-/// near-white background + near-black foreground in light mode.
-struct CodyncTheme: GlassThemeProvider, Sendable {
- let isDark: Bool
-
- init(isDark: Bool = true) {
- self.isDark = isDark
- }
-
- // Single-source foreground colors
- private static let fgDark = Color(red: 0.93, green: 0.93, blue: 0.93)
- private static let fgLight = Color(red: 0.11, green: 0.11, blue: 0.12)
-
- private var fg: Color { isDark ? Self.fgDark : Self.fgLight }
-
- // MARK: - Backgrounds
-
- var background: Color {
- isDark
- ? Color(red: 0.06, green: 0.06, blue: 0.07)
- : Color(red: 0.96, green: 0.96, blue: 0.97)
- }
-
- var cardBackground: Color {
- isDark ? Color.white.opacity(0.05) : Color.white.opacity(0.70)
- }
-
- var glassBackground: Color {
- isDark ? Color.white.opacity(0.08) : Color.white.opacity(0.60)
- }
-
- var hoverBackground: Color {
- isDark ? Color.white.opacity(0.06) : Color.black.opacity(0.04)
- }
-
- var rowBackground: Color {
- isDark ? Color.white.opacity(0.03) : Color.black.opacity(0.02)
- }
-
- // MARK: - Text hierarchy
-
- var primaryText: Color { fg }
- var secondaryText: Color { fg.opacity(0.55) }
- var tertiaryText: Color { fg.opacity(0.35) }
-
- // MARK: - Borders
-
- var separator: Color {
- isDark ? Color.white.opacity(0.08) : Color.black.opacity(0.08)
- }
-
- var border: Color {
- isDark ? Color.white.opacity(0.08) : Color.black.opacity(0.08)
- }
-
- // MARK: - Semantic
-
- var accent: Color { fg }
- var warning: Color { fg }
- var danger: Color { fg }
-
- func waitingColor(for reason: WaitingReason?) -> Color {
- reason?.isPermission == true ? danger : warning
- }
-}
-
-private struct ThemeKey: EnvironmentKey {
- static let defaultValue = CodyncTheme(isDark: true)
-}
-
-extension EnvironmentValues {
- var theme: CodyncTheme {
- get { self[ThemeKey.self] }
- set { self[ThemeKey.self] = newValue }
- }
-}
diff --git a/Codync-iOS/Views/MarkdownText.swift b/Codync-iOS/Views/MarkdownText.swift
new file mode 100644
index 00000000..cafdf761
--- /dev/null
+++ b/Codync-iOS/Views/MarkdownText.swift
@@ -0,0 +1,120 @@
+import CodyncKit
+import SwiftUI
+
+/// Small block-level Markdown renderer: paragraphs, headings, lists, quotes and
+/// fenced code; inline styling comes from `AttributedString(markdown:)`.
+struct MarkdownText: View {
+ let blocks: [Block]
+
+ init(_ source: String) {
+ blocks = Self.parse(source)
+ }
+
+ enum Block: Hashable {
+ case paragraph(String)
+ case heading(String, level: Int)
+ case bullet(String, marker: String)
+ case quote(String)
+ case code(String, language: String)
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in
+ view(for: block)
+ }
+ }
+ .textSelection(.enabled)
+ }
+
+ @ViewBuilder private func view(for block: Block) -> some View {
+ switch block {
+ case let .paragraph(t):
+ Text(Self.inline(t)).font(.body).foregroundStyle(Palette.text)
+ case let .heading(t, level):
+ Text(Self.inline(t))
+ .font(level == 1 ? .title3.bold() : level == 2 ? .headline : .subheadline.bold())
+ .foregroundStyle(Palette.text)
+ case let .bullet(t, marker):
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text(marker).foregroundStyle(Palette.secondary).monospacedDigit()
+ Text(Self.inline(t)).foregroundStyle(Palette.text)
+ }
+ .font(.body)
+ case let .quote(t):
+ Text(Self.inline(t))
+ .font(.body)
+ .foregroundStyle(Palette.secondary)
+ .padding(.leading, 10)
+ .overlay(alignment: .leading) { Rectangle().fill(Palette.border).frame(width: 3) }
+ case let .code(t, _):
+ ScrollView(.horizontal, showsIndicators: false) {
+ Text(t)
+ .font(.system(.footnote, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .padding(10)
+ }
+ .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(Palette.border))
+ }
+ }
+
+ static func inline(_ s: String) -> AttributedString {
+ (try? AttributedString(markdown: s, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(s)
+ }
+
+ static func parse(_ source: String) -> [Block] {
+ var blocks: [Block] = []
+ var paragraph: [String] = []
+ var code: [String]?
+ var language = ""
+
+ func flush() {
+ if !paragraph.isEmpty {
+ blocks.append(.paragraph(paragraph.joined(separator: "\n")))
+ paragraph = []
+ }
+ }
+
+ for raw in source.components(separatedBy: "\n") {
+ let line = raw.trimmingCharacters(in: .whitespaces)
+ if line.hasPrefix("```") {
+ if let c = code {
+ blocks.append(.code(c.joined(separator: "\n"), language: language))
+ code = nil
+ } else {
+ flush()
+ code = []
+ language = String(line.dropFirst(3))
+ }
+ continue
+ }
+ if code != nil {
+ code?.append(raw)
+ continue
+ }
+ if line.isEmpty {
+ flush()
+ } else if let hashes = line.firstIndex(where: { $0 != "#" }), line.hasPrefix("#"), line[hashes] == " " {
+ flush()
+ let level = line.distance(from: line.startIndex, to: hashes)
+ blocks.append(.heading(String(line[hashes...]).trimmingCharacters(in: .whitespaces), level: level))
+ } else if line.hasPrefix("- ") || line.hasPrefix("* ") || line.hasPrefix("• ") {
+ flush()
+ blocks.append(.bullet(String(line.dropFirst(2)), marker: "•"))
+ } else if let dot = line.firstIndex(of: "."), line[..<dot].allSatisfy(\.isNumber), !line[..<dot].isEmpty,
+ line[line.index(after: dot)...].hasPrefix(" ") {
+ flush()
+ blocks.append(.bullet(String(line[line.index(dot, offsetBy: 2)...]), marker: String(line[...dot])))
+ } else if line.hasPrefix("> ") {
+ flush()
+ blocks.append(.quote(String(line.dropFirst(2))))
+ } else {
+ paragraph.append(raw)
+ }
+ }
+ if let c = code { blocks.append(.code(c.joined(separator: "\n"), language: language)) }
+ flush()
+ return blocks
+ }
+}
diff --git a/Codync-iOS/Views/PairingView.swift b/Codync-iOS/Views/PairingView.swift
new file mode 100644
index 00000000..b1a3cd5f
--- /dev/null
+++ b/Codync-iOS/Views/PairingView.swift
@@ -0,0 +1,162 @@
+import CodyncKit
+import SwiftUI
+import VisionKit
+
+/// First run: explain the model, then pair with a computer running codync-host.
+struct PairingView: View {
+ @Environment(AppModel.self) private var model
+ @State private var scanning = false
+ @State private var pasted = ""
+ @State private var error: String?
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 28) {
+ HStack(spacing: -10) {
+ CharacterAvatar(shape: "blob", color: "blue", size: 64, mood: .working)
+ CharacterAvatar(shape: "squircle", color: "orange", size: 64)
+ CharacterAvatar(shape: "teardrop", color: "violet", size: 64, mood: .working)
+ }
+ .padding(.top, 40)
+
+ VStack(alignment: .leading, spacing: 10) {
+ Text("Your coding agents,\nas teammates.")
+ .font(.system(size: 34, weight: .bold))
+ .foregroundStyle(Palette.text)
+ Text("Give each agent a name, a job and a project. Then just message the right one — it works on your computer while your phone is in your pocket.")
+ .font(.body)
+ .foregroundStyle(Palette.secondary)
+ }
+
+ VStack(alignment: .leading, spacing: 14) {
+ Step(n: 1, title: "Install Codync on your computer", detail: "Mac — then open Codync in the menu bar and click Install host:", code: "brew install --cask leepokai/codync/codync")
+ Step(n: nil, title: "", detail: "Linux:", code: "brew install leepokai/codync/codync-host\ncodync-host install")
+ Step(n: 2, title: "Show the pairing code", detail: "On a Mac, click Codync in the menu bar → Pair iPhone. Or run:", code: "codync-host pair")
+ Step(n: 3, title: "Scan it", detail: "Use the button below, or point the Camera app at the code.", code: nil)
+ }
+
+ VStack(spacing: 12) {
+ Button {
+ scanning = true
+ } label: {
+ Label("Scan pairing code", systemImage: "qrcode.viewfinder")
+ .font(.headline)
+ .frame(maxWidth: .infinity, minHeight: 50)
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Palette.accentFill)
+ .foregroundStyle(Palette.onAccent)
+ .disabled(!DataScannerViewController.isSupported)
+
+ HStack {
+ TextField("…or paste a codync://pair link", text: $pasted)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .font(.callout.monospaced())
+ Button("Pair") { pair(pasted) }
+ .disabled(pasted.isEmpty)
+ }
+ .padding(12)
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.border))
+
+ if let error {
+ Text(error).font(.footnote).foregroundStyle(Palette.danger)
+ }
+ }
+
+ Text("Your phone talks straight to your computer over Tailscale or local Wi-Fi. Codync has no account and no cloud copy of your code or chats.")
+ .font(.footnote)
+ .foregroundStyle(Palette.tertiary)
+ }
+ .padding(24)
+ }
+ .background(Palette.background)
+ .sheet(isPresented: $scanning) {
+ QRScanner { code in
+ scanning = false
+ pair(code)
+ }
+ .ignoresSafeArea()
+ }
+ }
+
+ private func pair(_ text: String) {
+ guard let p = Pairing(string: text) else {
+ error = "That isn't a Codync pairing code."
+ return
+ }
+ error = nil
+ model.pair(p)
+ Task { _ = await PushRegistrar.shared.requestAuthorization() }
+ }
+}
+
+private struct Step: View {
+ let n: Int?
+ let title: String
+ let detail: String
+ let code: String?
+
+ var body: some View {
+ HStack(alignment: .top, spacing: 12) {
+ Text(n.map(String.init) ?? "")
+ .font(.footnote.bold())
+ .frame(width: 24, height: 24)
+ .background(n == nil ? .clear : Palette.accentDim, in: Circle())
+ .foregroundStyle(Palette.text)
+ VStack(alignment: .leading, spacing: 6) {
+ if !title.isEmpty {
+ Text(title).font(.headline).foregroundStyle(Palette.text)
+ }
+ Text(detail).font(.subheadline).foregroundStyle(Palette.secondary)
+ if let code {
+ Text(code)
+ .font(.footnote.monospaced())
+ .textSelection(.enabled)
+ .padding(10)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(Palette.border))
+ }
+ }
+ }
+ }
+}
+
+/// VisionKit live QR scanner.
+struct QRScanner: UIViewControllerRepresentable {
+ let onCode: (String) -> Void
+
+ func makeUIViewController(context: Context) -> DataScannerViewController {
+ let vc = DataScannerViewController(
+ recognizedDataTypes: [.barcode(symbologies: [.qr])],
+ qualityLevel: .fast,
+ isHighlightingEnabled: true
+ )
+ vc.delegate = context.coordinator
+ try? vc.startScanning()
+ return vc
+ }
+
+ func updateUIViewController(_ vc: DataScannerViewController, context: Context) {}
+
+ func makeCoordinator() -> Coordinator { Coordinator(onCode: onCode) }
+
+ final class Coordinator: NSObject, DataScannerViewControllerDelegate {
+ let onCode: (String) -> Void
+ private var done = false
+
+ init(onCode: @escaping (String) -> Void) { self.onCode = onCode }
+
+ func dataScanner(_ scanner: DataScannerViewController, didAdd items: [RecognizedItem], allItems: [RecognizedItem]) {
+ for case let .barcode(code) in items {
+ if let value = code.payloadStringValue, value.hasPrefix("codync://"), !done {
+ done = true
+ scanner.stopScanning()
+ onCode(value)
+ }
+ }
+ }
+ }
+}
diff --git a/Codync-iOS/Views/PaywallView.swift b/Codync-iOS/Views/PaywallView.swift
deleted file mode 100644
index f072cf4f..00000000
--- a/Codync-iOS/Views/PaywallView.swift
+++ /dev/null
@@ -1,241 +0,0 @@
-import SwiftUI
-import RevenueCat
-
-struct CodyncPaywallView: View {
- @Environment(\.dismiss) private var dismiss
- @Environment(\.theme) private var theme
- @State private var offering: Offering?
- @State private var isPurchasing = false
- @State private var errorMessage: String?
-
- var body: some View {
- ZStack {
- theme.background.ignoresSafeArea()
-
- ScrollView {
- VStack(spacing: 0) {
- // Close button
- HStack {
- Spacer()
- Button { dismiss() } label: {
- Image(systemName: "xmark")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.tertiaryText)
- .frame(width: 32, height: 32)
- .background(theme.cardBackground, in: Circle())
- }
- }
- .padding(.horizontal, 20)
- .padding(.top, 16)
-
- Spacer().frame(height: 40)
-
- // Icon
- Image("CodyncIcon")
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 72, height: 72)
- .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
-
- Spacer().frame(height: 20)
-
- // Title
- Text("Codync Pro")
- .font(.system(size: 28, weight: .bold))
- .foregroundStyle(theme.primaryText)
-
- Spacer().frame(height: 8)
-
- Text("Always-on Live Activity")
- .font(.system(size: 15))
- .foregroundStyle(theme.secondaryText)
-
- Spacer().frame(height: 36)
-
- // Features
- VStack(spacing: 0) {
- featureRow(
- icon: "dot.radiowaves.up.forward",
- title: "Background Push Updates",
- subtitle: "Live Activity stays updated even when the app is closed"
- )
- Divider().overlay(theme.separator)
- featureRow(
- icon: "lock.iphone",
- title: "Dynamic Island Always-on",
- subtitle: "Session status persists on your Lock Screen"
- )
- Divider().overlay(theme.separator)
- featureRow(
- icon: "bolt.fill",
- title: "Instant APNs Delivery",
- subtitle: "Direct push via Worker relay, no polling delay"
- )
- }
- .background(
- RoundedRectangle(cornerRadius: 14, style: .continuous)
- .fill(theme.cardBackground)
- .overlay(
- RoundedRectangle(cornerRadius: 14, style: .continuous)
- .stroke(theme.border, lineWidth: 1)
- )
- )
- .padding(.horizontal, 20)
-
- Spacer().frame(height: 32)
-
- // Price
- if let pkg = offering?.monthly {
- Text(pkg.localizedPriceString + " / month")
- .font(.system(size: 17, weight: .semibold))
- .foregroundStyle(theme.primaryText)
- } else {
- Text("$0.99 / month")
- .font(.system(size: 17, weight: .semibold))
- .foregroundStyle(theme.primaryText)
- }
-
- Spacer().frame(height: 16)
-
- // Subscribe button
- Button {
- Task { await purchase() }
- } label: {
- Group {
- if isPurchasing {
- ProgressView()
- .tint(theme.background)
- } else {
- Text("Subscribe")
- .font(.system(size: 16, weight: .semibold))
- }
- }
- .frame(maxWidth: .infinity)
- .frame(height: 50)
- .background(theme.primaryText, in: RoundedRectangle(cornerRadius: 12, style: .continuous))
- .foregroundStyle(theme.background)
- }
- .disabled(isPurchasing)
- .padding(.horizontal, 20)
-
- Spacer().frame(height: 12)
-
- // Restore
- Button {
- Task { await restore() }
- } label: {
- Text("Restore Purchases")
- .font(.system(size: 14))
- .foregroundStyle(theme.tertiaryText)
- }
-
- if let error = errorMessage {
- Spacer().frame(height: 12)
- Text(error)
- .font(.system(size: 13))
- .foregroundStyle(.red.opacity(0.8))
- .multilineTextAlignment(.center)
- .padding(.horizontal, 20)
- }
-
- Spacer().frame(height: 16)
-
- // Legal
- Text("Payment will be charged to your Apple ID. Subscription automatically renews unless cancelled at least 24 hours before the end of the current period.")
- .font(.system(size: 11))
- .foregroundStyle(theme.tertiaryText)
- .multilineTextAlignment(.center)
- .padding(.horizontal, 32)
-
- Spacer().frame(height: 12)
-
- // Terms & Privacy links
- HStack(spacing: 16) {
- Link("Terms of Use (EULA)", destination: URL(string: "https://codync.dev/terms")!)
- Link("Privacy Policy", destination: URL(string: "https://codync.dev/privacy")!)
- }
- .font(.system(size: 11))
- .foregroundStyle(theme.tertiaryText)
-
- Spacer().frame(height: 32)
- }
- }
- }
- .task {
- do {
- let offerings = try await Purchases.shared.offerings()
- offering = offerings.current
- } catch {
- errorMessage = error.localizedDescription
- }
- }
- }
-
- @ViewBuilder
- private func featureRow(icon: String, title: String, subtitle: String) -> some View {
- HStack(spacing: 14) {
- Image(systemName: icon)
- .font(.system(size: 16))
- .foregroundStyle(theme.primaryText)
- .frame(width: 32, height: 32)
- .background(theme.glassBackground, in: RoundedRectangle(cornerRadius: 8, style: .continuous))
-
- VStack(alignment: .leading, spacing: 2) {
- Text(title)
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(theme.primaryText)
- Text(subtitle)
- .font(.system(size: 12))
- .foregroundStyle(theme.secondaryText)
- }
- Spacer()
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 14)
- }
-
- private func purchase() async {
- guard let pkg = offering?.monthly ?? offering?.availablePackages.first else {
- errorMessage = "No product available"
- return
- }
- isPurchasing = true
- errorMessage = nil
- do {
- let result = try await Purchases.shared.purchase(package: pkg)
- if !result.userCancelled {
- await PremiumManager.shared.refreshStatus()
- // Pro requires notifications for APNs push
- let center = UNUserNotificationCenter.current()
- let settings = await center.notificationSettings()
- if settings.authorizationStatus == .notDetermined {
- _ = try? await center.requestAuthorization(options: [.alert, .sound, .badge])
- } else if settings.authorizationStatus == .denied {
- if let url = URL(string: UIApplication.openNotificationSettingsURLString) {
- await UIApplication.shared.open(url)
- }
- }
- dismiss()
- }
- } catch {
- errorMessage = error.localizedDescription
- }
- isPurchasing = false
- }
-
- private func restore() async {
- isPurchasing = true
- errorMessage = nil
- do {
- try await PremiumManager.shared.restorePurchases()
- if PremiumManager.shared.isPro {
- dismiss()
- } else {
- errorMessage = "No active subscription found"
- }
- } catch {
- errorMessage = error.localizedDescription
- }
- isPurchasing = false
- }
-}
diff --git a/Codync-iOS/Views/PermissionCard.swift b/Codync-iOS/Views/PermissionCard.swift
new file mode 100644
index 00000000..90bc5580
--- /dev/null
+++ b/Codync-iOS/Views/PermissionCard.swift
@@ -0,0 +1,186 @@
+import CodyncKit
+import SwiftUI
+
+/// Grok Bot's approval card: what the agent wants, where it runs, and
+/// Allow once / Always allow / Deny straight from the chat.
+struct PermissionCard: View {
+ let entry: Entry
+ let hostName: String
+ let respond: (String?) -> Void
+ @State private var expanded = false
+
+ private var d: EntryData { entry.data }
+ private var pending: Bool { d.status == "pending" }
+
+ private var headline: String {
+ switch d.toolKind {
+ case "execute": "Wants to run a command"
+ case "edit", "delete", "move": "Wants to change files"
+ case "fetch": "Wants to access the web"
+ case "read", "search": "Wants to read files"
+ default: "Wants to use a tool"
+ }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 8) {
+ Image(systemName: "hand.raised.fill")
+ .foregroundStyle(pending ? Palette.warning : Palette.tertiary)
+ Text(headline).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text)
+ }
+ Text(d.title ?? "")
+ .font(.callout)
+ .foregroundStyle(Palette.text)
+ .lineLimit(expanded ? nil : 3)
+ Label("Runs on \(hostName)\(d.cwd.map { " · \(($0 as NSString).lastPathComponent)" } ?? "")", systemImage: "desktopcomputer")
+ .font(.caption)
+ .foregroundStyle(Palette.tertiary)
+
+ if hasDetail {
+ DisclosureGroup(isExpanded: $expanded) {
+ VStack(alignment: .leading, spacing: 8) {
+ if let command = d.command, !command.isEmpty {
+ CodeBox(text: command)
+ }
+ if let detail = d.detail, !detail.isEmpty {
+ CodeBox(text: String(detail.prefix(2000)))
+ }
+ ForEach(d.diffs ?? [], id: \.self) { DiffView(diff: $0) }
+ }
+ .padding(.top, 6)
+ } label: {
+ Text("Details").font(.caption.weight(.medium)).foregroundStyle(Palette.secondary)
+ }
+ }
+
+ if pending {
+ buttons
+ } else {
+ Text(outcome)
+ .font(.caption.weight(.medium))
+ .foregroundStyle(Palette.secondary)
+ }
+ }
+ .padding(14)
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: 16, style: .continuous)
+ .stroke(pending ? Palette.warning.opacity(0.6) : Palette.border)
+ )
+ .padding(.leading, 36)
+ }
+
+ private var hasDetail: Bool {
+ !(d.command ?? "").isEmpty || !(d.detail ?? "").isEmpty || !(d.diffs ?? []).isEmpty
+ }
+
+ /// Ordered like Grok Bot: Allow once, Always allow, then Deny.
+ private var ordered: [PermissionOption] {
+ let rank = ["allow_once": 0, "allow_always": 1, "reject_once": 2, "reject_always": 3]
+ return (d.options ?? []).sorted { (rank[$0.kind] ?? 9) < (rank[$1.kind] ?? 9) }
+ }
+
+ private func label(_ o: PermissionOption) -> String {
+ switch o.kind {
+ case "allow_once": "Allow once"
+ case "allow_always": "Always allow"
+ case "reject_once": "Deny"
+ case "reject_always": "Never"
+ default: o.name
+ }
+ }
+
+ private var buttons: some View {
+ let options = ordered
+ return VStack(spacing: 8) {
+ HStack(spacing: 8) {
+ ForEach(options.filter { $0.kind.hasPrefix("allow") }) { o in
+ Button(label(o)) { respond(o.optionId) }
+ .buttonStyle(CardButton(primary: o.kind == "allow_once"))
+ }
+ }
+ HStack(spacing: 8) {
+ ForEach(options.filter { !$0.kind.hasPrefix("allow") }) { o in
+ Button(label(o), role: .destructive) { respond(o.optionId) }
+ .buttonStyle(CardButton(primary: false))
+ }
+ }
+ }
+ }
+
+ private var outcome: String {
+ switch d.status {
+ case "answered":
+ let chosen = d.options?.first { $0.optionId == d.selected }
+ return switch chosen?.kind {
+ case "allow_once": "Allowed once"
+ case "allow_always": "Always allowed"
+ case "reject_once": "Denied"
+ case "reject_always": "Never allowed"
+ default: chosen?.name ?? "Answered"
+ }
+ case "cancelled": return "Cancelled"
+ default: return "Expired — the agent moved on"
+ }
+ }
+}
+
+struct CardButton: ButtonStyle {
+ let primary: Bool
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .font(.subheadline.weight(.semibold))
+ .frame(maxWidth: .infinity, minHeight: 38)
+ .foregroundStyle(primary ? Palette.onAccent : configuration.role == .destructive ? Palette.danger : Palette.text)
+ .background(primary ? Palette.accentFill : Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 10, style: .continuous))
+ .opacity(configuration.isPressed ? 0.7 : 1)
+ }
+}
+
+struct CodeBox: View {
+ let text: String
+
+ var body: some View {
+ ScrollView(.horizontal, showsIndicators: false) {
+ Text(text)
+ .font(.system(.caption, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .textSelection(.enabled)
+ .padding(8)
+ }
+ .frame(maxHeight: 240)
+ .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))
+ }
+}
+
+struct DiffView: View {
+ let diff: FileDiff
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 6) {
+ Image(systemName: diff.isNew ? "doc.badge.plus" : "doc.text")
+ Text((diff.path as NSString).lastPathComponent).lineLimit(1)
+ Spacer()
+ Text("+\(diff.added)").foregroundStyle(Palette.added)
+ Text("−\(diff.removed)").foregroundStyle(Palette.removed)
+ }
+ .font(.caption.monospaced())
+ .foregroundStyle(Palette.secondary)
+ ScrollView(.horizontal, showsIndicators: false) {
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(diff.patch.split(separator: "\n", omittingEmptySubsequences: false).prefix(80).enumerated()), id: \.offset) { _, line in
+ Text(line.isEmpty ? " " : String(line))
+ .foregroundStyle(line.hasPrefix("+") ? Palette.added : line.hasPrefix("-") ? Palette.removed : Palette.secondary)
+ }
+ }
+ .font(.system(.caption2, design: .monospaced))
+ .padding(8)
+ }
+ .frame(maxHeight: 260)
+ .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))
+ }
+ }
+}
diff --git a/Codync-iOS/Views/RootView.swift b/Codync-iOS/Views/RootView.swift
new file mode 100644
index 00000000..35e17fc5
--- /dev/null
+++ b/Codync-iOS/Views/RootView.swift
@@ -0,0 +1,29 @@
+import CodyncKit
+import SwiftUI
+
+struct RootView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(Router.self) private var router
+
+ var body: some View {
+ @Bindable var router = router
+ Group {
+ if model.pairing == nil {
+ PairingView()
+ } else {
+ NavigationStack(path: $router.path) {
+ BotListView()
+ .navigationDestination(for: String.self) { botId in
+ ThreadView(botId: botId)
+ }
+ }
+ }
+ }
+ .background(Palette.background)
+ .alert("Something went wrong", isPresented: Binding(get: { model.lastError != nil }, set: { if !$0 { model.lastError = nil } })) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(model.lastError ?? "")
+ }
+ }
+}
diff --git a/Codync-iOS/Views/SettingsView.swift b/Codync-iOS/Views/SettingsView.swift
index 3a93205e..7400c964 100644
--- a/Codync-iOS/Views/SettingsView.swift
+++ b/Codync-iOS/Views/SettingsView.swift
@@ -1,149 +1,179 @@
+import CodyncKit
import SwiftUI
-import RevenueCatUI
+import UserNotifications
struct SettingsView: View {
+ @Environment(AppModel.self) private var model
@Environment(\.dismiss) private var dismiss
- @AppStorage("codync_darkMode") private var isDarkMode = true
- @State private var showPaywall = false
-
- private var theme: CodyncTheme { CodyncTheme(isDark: isDarkMode) }
+ @State private var notificationsAllowed: Bool?
+ @State private var confirmUnpair = false
var body: some View {
- NavigationStack {
- List {
- // MARK: - Subscription
- Section {
- subscriptionRow
- } header: {
- Text("Subscription").foregroundStyle(.secondary)
+ Form {
+ Section("Computer") {
+ LabeledContent("Name", value: model.hostName)
+ LabeledContent("Status") {
+ switch model.connection {
+ case .online: Text("Connected").foregroundStyle(Palette.accent)
+ case .connecting: Text("Connecting…")
+ case .offline: Text("Offline").foregroundStyle(Palette.warning)
+ case .unpaired: Text("Not paired")
+ }
+ }
+ if let url = model.client?.baseURL.absoluteString {
+ LabeledContent("Address", value: url).font(.footnote.monospaced())
+ }
+ if let hello = model.hello {
+ LabeledContent("Host version", value: hello.version)
+ LabeledContent("System", value: hello.os)
}
+ }
+
+ Section {
+ ForEach(model.usage.providers) { UsageCard(provider: $0) }
+ Button("Refresh") { Task { await model.refreshUsage() } }
+ } header: {
+ Text("Usage limits")
+ } footer: {
+ Text("Read on your computer from Claude Code and Codex. Add the Codync widget to your Home or Lock Screen to keep an eye on them.")
+ }
- // MARK: - Appearance
- Section {
- Toggle(isOn: $isDarkMode) {
- Label("Dark Mode", systemImage: "moon.fill")
+ Section("Notifications") {
+ if notificationsAllowed == false {
+ Button("Allow in Settings") {
+ UIApplication.shared.open(URL(string: UIApplication.openNotificationSettingsURLString)!)
}
- .tint(.primary)
- } header: {
- Text("Appearance").foregroundStyle(.secondary)
+ } else if notificationsAllowed == nil {
+ Button("Turn on notifications") {
+ Task { notificationsAllowed = await PushRegistrar.shared.requestAuthorization() }
+ }
+ } else {
+ Label("On — you'll hear when a bot needs you or finishes", systemImage: "bell.badge")
+ .font(.footnote)
}
+ }
- // MARK: - Notifications
- Section {
- Button {
- if let url = URL(string: UIApplication.openNotificationSettingsURLString) {
- UIApplication.shared.open(url)
- }
- } label: {
+ if !model.hiddenBots.isEmpty {
+ Section("Hidden bots") {
+ ForEach(model.hiddenBots) { bot in
HStack {
- Label("Push Notifications", systemImage: "bell.badge")
+ CharacterAvatar(bot: bot, size: 28, animated: false)
+ Text(bot.name)
Spacer()
- Image(systemName: "arrow.up.forward")
- .font(.caption)
- .foregroundStyle(.tertiary)
+ Button("Unhide") { model.setHidden(bot, false) }
}
}
- .tint(.primary)
- } header: {
- Text("Notifications").foregroundStyle(.secondary)
- } footer: {
- Text("Only the pinned primary session sends completion alerts.")
}
+ }
- // MARK: - Support
- Section {
- Link(destination: URL(string: "mailto:[email protected]")!) {
- Label("Contact Support", systemImage: "envelope")
- }
- .tint(.primary)
- Link(destination: URL(string: "https://github.com/anthropics/claude-code")!) {
- Label("Claude Code", systemImage: "link")
- }
- .tint(.primary)
- } header: {
- Text("Support").foregroundStyle(.secondary)
- }
+ Section {
+ Button("Unpair this phone", role: .destructive) { confirmUnpair = true }
+ } footer: {
+ Text("Bots and conversations stay on your computer.")
+ }
- // MARK: - About
- Section {
- HStack {
- Text("Version")
- Spacer()
- Text(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "—")
- .foregroundStyle(.secondary)
- }
- Button {
- UserDefaults.standard.set(false, forKey: "codync_onboardingComplete")
- dismiss()
- } label: {
- Label("Reset Onboarding", systemImage: "arrow.counterclockwise")
- }
- .tint(.secondary)
- } header: {
- Text("About").foregroundStyle(.secondary)
- }
+ Section {
+ Link("Source code", destination: URL(string: "https://github.com/leepokai/Codync")!)
+ LabeledContent("App version", value: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "")
}
- .tint(.primary)
- .navigationTitle("Settings")
- .navigationBarTitleDisplayMode(.inline)
- .toolbar {
- ToolbarItem(placement: .topBarTrailing) {
- Button("Done") { dismiss() }
- }
+ }
+ .scrollContentBackground(.hidden)
+ .background(Palette.background)
+ .navigationTitle("Settings")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } }
+ }
+ .confirmationDialog("Unpair from \(model.hostName)?", isPresented: $confirmUnpair, titleVisibility: .visible) {
+ Button("Unpair", role: .destructive) {
+ model.unpair()
+ dismiss()
}
- .sheet(isPresented: $showPaywall) {
- CodyncPaywallView()
- .environment(\.theme, theme)
- .preferredColorScheme(isDarkMode ? .dark : .light)
+ }
+ .task {
+ let status = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
+ notificationsAllowed = switch status {
+ case .authorized, .provisional, .ephemeral: true
+ case .denied: false
+ default: nil
}
}
- .preferredColorScheme(isDarkMode ? .dark : .light)
}
+}
- @ViewBuilder
- private var subscriptionRow: some View {
- let premium = PremiumManager.shared
- Button {
- if premium.isPro {
- if let url = URL(string: "https://apps.apple.com/account/subscriptions") {
- UIApplication.shared.open(url)
- }
- } else {
- showPaywall = true
- }
- } label: {
+struct UsageCard: View {
+ let provider: UsageProvider
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
HStack {
- Label {
- Text("Codync Pro")
- } icon: {
- Image(systemName: premium.isPro ? "checkmark.seal.fill" : "seal")
- }
+ Text(provider.name).font(.subheadline.bold())
Spacer()
- if premium.isPro {
- Image(systemName: "arrow.up.forward")
- .font(.caption)
- .foregroundStyle(.tertiary)
- } else {
- Text("$0.99/mo")
- .font(.subheadline)
- .foregroundStyle(.secondary)
- Image(systemName: "chevron.right")
- .font(.caption)
- .foregroundStyle(.tertiary)
+ Text("updated \(RelativeTime.short(Date(milliseconds: provider.updatedAt)))")
+ .font(.caption2)
+ .foregroundStyle(Palette.tertiary)
+ }
+ ForEach(provider.windows) { w in
+ VStack(alignment: .leading, spacing: 3) {
+ HStack {
+ Text(w.label).font(.caption)
+ Spacer()
+ Text("\(Int(w.percent.rounded()))%").font(.caption.monospacedDigit().bold())
+ if let reset = w.resetDate {
+ Text("· resets in \(RelativeTime.until(reset))").font(.caption2).foregroundStyle(Palette.tertiary)
+ }
+ }
+ UsageBar(percent: w.percent)
}
}
}
- .tint(.primary)
+ .padding(.vertical, 4)
+ }
+}
+
+struct UsageBar: View {
+ let percent: Double
+
+ var body: some View {
+ GeometryReader { geo in
+ ZStack(alignment: .leading) {
+ Capsule().fill(Palette.bubbleAgent)
+ Capsule()
+ .fill(percent >= 90 ? Palette.danger : percent >= 70 ? Palette.warning : Palette.accentFill)
+ .frame(width: geo.size.width * min(1, max(0.02, percent / 100)))
+ }
+ }
+ .frame(height: 6)
+ }
+}
+
+/// Compact usage chips at the top of the roster.
+struct UsageStrip: View {
+ let usage: Usage
- if !premium.isPro {
- Button {
- Task {
- try? await premium.restorePurchases()
+ var body: some View {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 8) {
+ ForEach(usage.providers) { p in
+ ForEach(p.windows.prefix(2)) { w in
+ HStack(spacing: 6) {
+ Gauge(value: min(w.percent, 100), in: 0...100) { EmptyView() }
+ .gaugeStyle(.accessoryCircularCapacity)
+ .scaleEffect(0.42)
+ .frame(width: 22, height: 22)
+ .tint(w.percent >= 90 ? Palette.danger : w.percent >= 70 ? Palette.warning : Palette.accent)
+ VStack(alignment: .leading, spacing: 0) {
+ Text("\(p.name) \(w.label)").font(.caption2).foregroundStyle(Palette.tertiary)
+ Text("\(Int(w.percent.rounded()))%").font(.caption.bold().monospacedDigit()).foregroundStyle(Palette.text)
+ }
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .background(Palette.surface, in: Capsule())
+ .overlay(Capsule().stroke(Palette.border))
+ }
}
- } label: {
- Label("Restore Purchases", systemImage: "arrow.clockwise")
}
- .tint(.secondary)
}
}
}
diff --git a/Codync-iOS/Views/SyncErrorSheet.swift b/Codync-iOS/Views/SyncErrorSheet.swift
deleted file mode 100644
index 2b399a68..00000000
--- a/Codync-iOS/Views/SyncErrorSheet.swift
+++ /dev/null
@@ -1,117 +0,0 @@
-import SwiftUI
-
-struct SyncErrorSheet: View {
- let error: CloudKitReceiver.SyncError?
- @Environment(\.dismiss) private var dismiss
- @Environment(\.theme) private var theme
-
- var body: some View {
- ZStack {
- theme.background.ignoresSafeArea()
-
- VStack(spacing: 0) {
- HStack {
- Spacer()
- Button { dismiss() } label: {
- Image(systemName: "xmark")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.tertiaryText)
- .frame(width: 32, height: 32)
- .background(theme.cardBackground, in: Circle())
- }
- }
- .padding(.horizontal, 20)
- .padding(.top, 16)
-
- Spacer()
-
- VStack(spacing: 20) {
- Image(systemName: "icloud.slash")
- .font(.system(size: 40))
- .foregroundStyle(theme.secondaryText)
-
- Text(error?.title ?? "Sync Error")
- .font(.title2.bold())
- .foregroundStyle(theme.primaryText)
-
- VStack(alignment: .leading, spacing: 12) {
- if case .quotaExceeded = error {
- infoRow(
- icon: "externaldrive.badge.xmark",
- text: "Your iCloud storage is full. Codync cannot sync session data from your Mac."
- )
- infoRow(
- icon: "clock.arrow.circlepath",
- text: "Session status shown here may be outdated and won't update until storage is freed."
- )
- infoRow(
- icon: "gearshape",
- text: "Go to Settings → Apple Account → iCloud → Manage Storage to free up space."
- )
- } else if case .networkUnavailable = error {
- infoRow(
- icon: "wifi.slash",
- text: "No internet connection. Session data cannot be synced from your Mac."
- )
- infoRow(
- icon: "clock.arrow.circlepath",
- text: "Data will refresh automatically when connectivity is restored."
- )
- } else {
- infoRow(
- icon: "exclamationmark.triangle",
- text: "An unexpected error occurred while syncing with iCloud."
- )
- infoRow(
- icon: "clock.arrow.circlepath",
- text: "Codync will retry automatically. If the issue persists, try restarting the app."
- )
- }
- }
- .padding(.horizontal, 8)
- }
- .padding(.horizontal, 24)
-
- Spacer()
-
- if case .quotaExceeded = error {
- Button {
- if let url = URL(string: "App-prefs:root=CASTLE&path=STORAGE_AND_BACKUP") {
- UIApplication.shared.open(url)
- }
- } label: {
- Text("Open iCloud Settings")
- .font(.headline)
- .foregroundStyle(theme.isDark ? .black : .white)
- .frame(maxWidth: .infinity)
- .padding(.vertical, 14)
- .background(theme.primaryText, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
- }
- .padding(.horizontal, 24)
- .padding(.bottom, 8)
- }
-
- Button { dismiss() } label: {
- Text("Dismiss")
- .font(.subheadline)
- .foregroundStyle(theme.tertiaryText)
- }
- .padding(.bottom, 24)
- }
- }
- }
-
- @ViewBuilder
- private func infoRow(icon: String, text: String) -> some View {
- HStack(alignment: .top, spacing: 12) {
- Image(systemName: icon)
- .font(.system(size: 16, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- .frame(width: 24)
- Text(text)
- .font(.subheadline)
- .foregroundStyle(theme.secondaryText)
- .fixedSize(horizontal: false, vertical: true)
- }
- }
-}
diff --git a/Codync-iOS/Views/TabRootView.swift b/Codync-iOS/Views/TabRootView.swift
deleted file mode 100644
index 7b11087c..00000000
--- a/Codync-iOS/Views/TabRootView.swift
+++ /dev/null
@@ -1,41 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-// TODO: Re-enable TabView with Cowork and Codex tabs once those features are implemented.
-// enum AppTab: String, CaseIterable {
-// case claudeCode
-// case cowork
-// case codex
-// }
-
-struct TabRootView: View {
- let sessions: [SessionState]
- var syncError: CloudKitReceiver.SyncError?
- @ObservedObject var liveActivityManager: LiveActivityManager
- @ObservedObject var primarySessionManager: PrimarySessionManager
-
- // private let iconSize: CGFloat = 22
-
- var body: some View {
- // TODO: Restore TabView when Cowork / Codex tabs are ready.
- // TabView(selection: $selectedTab) {
- // Tab(value: AppTab.claudeCode.rawValue) { ... }
- // Tab(value: AppTab.cowork.rawValue) {
- // ComingSoonView(icon: "CoworkIcon", isSystemImage: false,
- // title: "Cowork", description: "Monitor Claude Cowork sessions in real time")
- // }
- // Tab(value: AppTab.codex.rawValue) {
- // ComingSoonView(icon: "CodexIcon", isSystemImage: false,
- // title: "Codex", description: "Track OpenAI Codex jobs and costs")
- // }
- // }
- NavigationStack {
- IOSSessionListView(
- sessions: sessions,
- syncError: syncError,
- liveActivityManager: liveActivityManager,
- primarySessionManager: primarySessionManager
- )
- }
- }
-}
diff --git a/Codync-iOS/Views/ThreadView.swift b/Codync-iOS/Views/ThreadView.swift
new file mode 100644
index 00000000..6e250f61
--- /dev/null
+++ b/Codync-iOS/Views/ThreadView.swift
@@ -0,0 +1,413 @@
+import CodyncKit
+import SwiftUI
+
+/// One endless conversation with a bot. Only deliberate messages show here;
+/// tool calls and thinking live in the "Full conversation" sheet.
+struct ThreadView: View {
+ let botId: String
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ @State private var draft = ""
+ @State private var showTrace = false
+ @State private var editing: EditorRequest?
+ @State private var confirmNewSession = false
+ @State private var confirmDelete = false
+ @FocusState private var composerFocused: Bool
+
+ private var bot: Bot? { model.bots[botId] }
+
+ var body: some View {
+ let thread = model.thread(botId)
+ let items = ChatItem.build(thread)
+ ScrollViewReader { proxy in
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ if !model.historyComplete.contains(botId), thread.count >= 50 {
+ Button("Load earlier messages") { Task { await model.loadOlder(botId) } }
+ .font(.footnote)
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 12)
+ }
+ if items.isEmpty, let bot {
+ IntroCard(bot: bot).padding(.top, 40)
+ }
+ ForEach(items) { item in
+ row(item)
+ .id(item.id)
+ }
+ if let bot, bot.isWorking {
+ WorkingIndicator(bot: bot) { showTrace = true }
+ .padding(.top, 6)
+ .id("working")
+ }
+ Color.clear.frame(height: 8).id("bottom")
+ }
+ .padding(.horizontal, 14)
+ .padding(.top, 8)
+ }
+ .defaultScrollAnchor(.bottom)
+ .scrollDismissesKeyboard(.interactively)
+ .onChange(of: items.last?.id) { _, _ in
+ withAnimation(.snappy) { proxy.scrollTo("bottom", anchor: .bottom) }
+ model.markRead(botId)
+ }
+ .onChange(of: bot?.isWorking) { _, _ in
+ withAnimation(.snappy) { proxy.scrollTo("bottom", anchor: .bottom) }
+ }
+ }
+ .background(Palette.background)
+ .safeAreaInset(edge: .bottom) { composer }
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .principal) { header }
+ ToolbarItem(placement: .topBarTrailing) { menu }
+ }
+ .onAppear { model.markRead(botId) }
+ .sheet(isPresented: $showTrace) {
+ NavigationStack { TraceView(botId: botId) }
+ .presentationDetents([.medium, .large])
+ .presentationDragIndicator(.visible)
+ }
+ .sheet(item: $editing) { request in
+ NavigationStack { BotEditorView(draft: request.draft) }
+ }
+ .confirmationDialog("Start a new session?", isPresented: $confirmNewSession, titleVisibility: .visible) {
+ Button("New session") { model.newSession(botId) }
+ } message: {
+ Text("The conversation stays here, but the agent starts with a fresh context.")
+ }
+ .confirmationDialog("Delete \(bot?.name ?? "bot")?", isPresented: $confirmDelete, titleVisibility: .visible) {
+ Button("Delete bot and its conversation", role: .destructive) {
+ if let bot { model.delete(bot) }
+ dismiss()
+ }
+ }
+ }
+
+ // MARK: rows
+
+ @ViewBuilder private func row(_ item: ChatItem) -> some View {
+ switch item.kind {
+ case let .separator(date):
+ Text(date.formatted(.relative(presentation: .named)).capitalized + " · " + date.formatted(date: .omitted, time: .shortened))
+ .font(.caption2)
+ .foregroundStyle(Palette.tertiary)
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 14)
+ case let .entry(e, groupStart):
+ switch e.kind {
+ case "user":
+ UserBubble(entry: e, botWorking: bot?.isWorking == true)
+ .padding(.top, groupStart ? 12 : 3)
+ case "agent":
+ AgentBubble(entry: e, bot: bot, showAvatar: groupStart) { showTrace = true }
+ .padding(.top, groupStart ? 12 : 3)
+ case "permission":
+ PermissionCard(entry: e, hostName: model.hostName) { option in
+ model.respond(e, option: option)
+ }
+ .padding(.top, 12)
+ default:
+ NoticeRow(entry: e).padding(.top, 10)
+ }
+ }
+ }
+
+ // MARK: chrome
+
+ private var header: some View {
+ HStack(spacing: 8) {
+ if let bot { CharacterAvatar(bot: bot, size: 28) }
+ VStack(alignment: .leading, spacing: 0) {
+ Text(bot?.name ?? "").font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text)
+ Group {
+ if let bot, bot.needsInput {
+ Text("Needs you").foregroundStyle(Palette.warning)
+ } else if let bot, bot.isWorking {
+ Text("Working").foregroundStyle(Palette.accent)
+ } else if let bot {
+ Text("\(BackendInfo.name(bot.backend)) · \(bot.folderName)").foregroundStyle(Palette.tertiary)
+ }
+ }
+ .font(.caption2)
+ .lineLimit(1)
+ }
+ }
+ .onTapGesture { if let bot { editing = EditorRequest(BotDraft(bot)) } }
+ }
+
+ private var menu: some View {
+ Menu {
+ Button("Full conversation", systemImage: "list.bullet.rectangle") { showTrace = true }
+ if let bot {
+ Button("Edit profile", systemImage: "pencil") { editing = EditorRequest(BotDraft(bot)) }
+ Button(bot.pinned ? "Unpin" : "Pin", systemImage: "pin") { model.setPinned(bot, !bot.pinned) }
+ }
+ Button("New session", systemImage: "arrow.counterclockwise") { confirmNewSession = true }
+ Divider()
+ Button("Delete bot", systemImage: "trash", role: .destructive) { confirmDelete = true }
+ } label: {
+ Image(systemName: "ellipsis.circle")
+ }
+ }
+
+ private var composer: some View {
+ let working = bot?.isWorking == true
+ let canSend = !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && model.connection == .online
+ return HStack(alignment: .bottom, spacing: 8) {
+ TextField(working ? "Message (queued until it's done)" : "Message \(bot?.name ?? "")", text: $draft, axis: .vertical)
+ .lineLimit(1...6)
+ .focused($composerFocused)
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 20, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 20, style: .continuous).stroke(Palette.border))
+ if working && draft.isEmpty {
+ Button {
+ model.stop(botId)
+ } label: {
+ Image(systemName: "stop.fill")
+ .font(.system(size: 14, weight: .bold))
+ .frame(width: 38, height: 38)
+ .background(Palette.bubbleAgent, in: Circle())
+ .foregroundStyle(Palette.text)
+ }
+ .accessibilityLabel("Stop")
+ } else {
+ Button {
+ model.send(draft, to: botId)
+ draft = ""
+ } label: {
+ Image(systemName: "arrow.up")
+ .font(.system(size: 16, weight: .bold))
+ .frame(width: 38, height: 38)
+ .background(canSend ? Palette.accentFill : Palette.bubbleAgent, in: Circle())
+ .foregroundStyle(canSend ? Palette.onAccent : Palette.tertiary)
+ }
+ .disabled(!canSend)
+ .accessibilityLabel("Send")
+ }
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .background(.bar)
+ }
+}
+
+// MARK: - Chat model
+
+struct ChatItem: Identifiable {
+ enum Kind {
+ case separator(Date)
+ case entry(Entry, groupStart: Bool)
+ }
+
+ let id: String
+ let kind: Kind
+
+ /// Chat-visible entries plus time separators (gaps > 1 h) and author grouping.
+ static func build(_ entries: [Entry]) -> [ChatItem] {
+ var out: [ChatItem] = []
+ var lastDate: Date?
+ var lastAuthor: String?
+ for e in entries where e.isChat {
+ let date = e.date
+ if lastDate.map({ date.timeIntervalSince($0) > 3600 }) ?? true {
+ out.append(ChatItem(id: "sep-\(e.id)", kind: .separator(date)))
+ lastAuthor = nil
+ }
+ let author = e.kind == "user" ? "user" : e.kind == "agent" ? "agent" : e.kind
+ out.append(ChatItem(id: e.id, kind: .entry(e, groupStart: author != lastAuthor)))
+ lastAuthor = (author == "user" || author == "agent") ? author : nil
+ lastDate = date
+ }
+ return out
+ }
+}
+
+// MARK: - Rows
+
+struct UserBubble: View {
+ let entry: Entry
+ let botWorking: Bool
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ VStack(alignment: .trailing, spacing: 4) {
+ Text(entry.data.text ?? "")
+ .font(.body)
+ .foregroundStyle(Palette.onAccent)
+ .textSelection(.enabled)
+ .padding(.horizontal, 13)
+ .padding(.vertical, 9)
+ .background(Palette.accentFill, in: RoundedRectangle(cornerRadius: 18, style: .continuous))
+ .contextMenu {
+ Button("Copy", systemImage: "doc.on.doc") { UIPasteboard.general.string = entry.data.text }
+ }
+ status
+ }
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ .padding(.leading, 48)
+ }
+
+ @ViewBuilder private var status: some View {
+ switch entry.data.status {
+ case "sending":
+ Text("Sending…").font(.caption2).foregroundStyle(Palette.tertiary)
+ case "queued" where botWorking:
+ Text("Waiting to send — it'll read this when it's done").font(.caption2).foregroundStyle(Palette.tertiary)
+ case "failed":
+ HStack(spacing: 10) {
+ Text("Failed to send").foregroundStyle(Palette.danger)
+ Button("Resend") { model.retry(entry) }
+ Button("Delete") { model.discard(entry) }
+ }
+ .font(.caption2.bold())
+ case "cancelled":
+ Text("Not sent — stopped").font(.caption2).foregroundStyle(Palette.tertiary)
+ default:
+ EmptyView()
+ }
+ }
+}
+
+struct AgentBubble: View {
+ let entry: Entry
+ let bot: Bot?
+ let showAvatar: Bool
+ let openTrace: () -> Void
+
+ var body: some View {
+ HStack(alignment: .bottom, spacing: 8) {
+ Group {
+ if showAvatar, let bot {
+ CharacterAvatar(bot: bot, size: 28, animated: false)
+ } else {
+ Color.clear
+ }
+ }
+ .frame(width: 28, height: 28)
+ MarkdownText(entry.data.text ?? "")
+ .padding(.horizontal, 13)
+ .padding(.vertical, 9)
+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))
+ .contextMenu {
+ Button("Copy", systemImage: "doc.on.doc") { UIPasteboard.general.string = entry.data.text }
+ Button("Show what it did", systemImage: "list.bullet.rectangle", action: openTrace)
+ }
+ Spacer(minLength: 24)
+ }
+ }
+}
+
+struct NoticeRow: View {
+ let entry: Entry
+
+ var body: some View {
+ let text = entry.data.text ?? ""
+ switch entry.data.style {
+ case "divider":
+ HStack(spacing: 10) {
+ Rectangle().fill(Palette.border).frame(height: 1)
+ Text(text)
+ .font(.caption2)
+ .foregroundStyle(Palette.tertiary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: 260)
+ .layoutPriority(1)
+ Rectangle().fill(Palette.border).frame(height: 1)
+ }
+ .padding(.vertical, 6)
+ case "error":
+ Label {
+ Text(text).font(.footnote).foregroundStyle(Palette.text).textSelection(.enabled)
+ } icon: {
+ Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(Palette.danger)
+ }
+ .padding(12)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Palette.danger.opacity(0.12), in: RoundedRectangle(cornerRadius: 12))
+ default:
+ Text(text)
+ .font(.caption)
+ .foregroundStyle(Palette.tertiary)
+ .frame(maxWidth: .infinity)
+ }
+ }
+}
+
+/// Grok Bot's typing bubble, plus the live activity line and elapsed time.
+struct WorkingIndicator: View {
+ let bot: Bot
+ let openTrace: () -> Void
+
+ var body: some View {
+ HStack(alignment: .center, spacing: 8) {
+ CharacterAvatar(bot: bot, size: 28)
+ VStack(alignment: .leading, spacing: 4) {
+ TypingDots()
+ .padding(.horizontal, 12)
+ .padding(.vertical, 11)
+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
+ Button(action: openTrace) {
+ HStack(spacing: 4) {
+ Text(bot.activity.isEmpty ? "Working…" : bot.activity).lineLimit(1)
+ if let started = bot.startedAt {
+ Text("·")
+ Text(Date(milliseconds: started), style: .timer).monospacedDigit()
+ }
+ Image(systemName: "chevron.right").font(.caption2)
+ }
+ .font(.caption)
+ .foregroundStyle(bot.needsInput ? Palette.warning : Palette.secondary)
+ }
+ .buttonStyle(.plain)
+ }
+ Spacer()
+ }
+ }
+}
+
+struct TypingDots: View {
+ var body: some View {
+ HStack(spacing: 4) {
+ ForEach(0..<3, id: \.self) { i in
+ Circle()
+ .fill(Palette.secondary)
+ .frame(width: 6, height: 6)
+ .phaseAnimator([0.3, 1.0]) { view, phase in
+ view.opacity(phase)
+ } animation: { _ in .easeInOut(duration: 0.5).delay(Double(i) * 0.15) }
+ }
+ }
+ }
+}
+
+private struct IntroCard: View {
+ let bot: Bot
+
+ var body: some View {
+ VStack(spacing: 12) {
+ CharacterAvatar(bot: bot, size: 72)
+ Text(bot.name).font(.title2.bold()).foregroundStyle(Palette.text)
+ Text("\(BackendInfo.name(bot.backend)) in \(bot.cwd)")
+ .font(.footnote.monospaced())
+ .foregroundStyle(Palette.tertiary)
+ .multilineTextAlignment(.center)
+ if !bot.description.isEmpty {
+ Text(bot.description)
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ .multilineTextAlignment(.center)
+ }
+ Text("Tell it what you need. You'll get a notification when it's done or needs you.")
+ .font(.footnote)
+ .foregroundStyle(Palette.tertiary)
+ .multilineTextAlignment(.center)
+ .padding(.top, 4)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.horizontal, 24)
+ }
+}
diff --git a/Codync-iOS/Views/TraceView.swift b/Codync-iOS/Views/TraceView.swift
new file mode 100644
index 00000000..47de8d1e
--- /dev/null
+++ b/Codync-iOS/Views/TraceView.swift
@@ -0,0 +1,132 @@
+import CodyncKit
+import SwiftUI
+
+/// "Full conversation": everything the agent did — narration, thinking, tool
+/// calls with output and diffs, plans — grouped by turn.
+struct TraceView: View {
+ let botId: String
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+
+ var body: some View {
+ let turns = Dictionary(grouping: model.thread(botId), by: \.turn)
+ .sorted { $0.key < $1.key }
+ List {
+ if turns.isEmpty {
+ Text("Nothing yet.").foregroundStyle(Palette.tertiary)
+ }
+ ForEach(turns, id: \.key) { turn, entries in
+ Section {
+ ForEach(entries) { TraceRow(entry: $0) }
+ } header: {
+ Text(entries.first { $0.kind == "user" }?.data.text ?? "Turn \(turn)")
+ .lineLimit(1)
+ .textCase(nil)
+ }
+ }
+ }
+ .listStyle(.insetGrouped)
+ .scrollContentBackground(.hidden)
+ .background(Palette.background)
+ .navigationTitle("Full conversation")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } }
+ }
+ .defaultScrollAnchor(.bottom)
+ }
+}
+
+private struct TraceRow: View {
+ let entry: Entry
+
+ var body: some View {
+ let d = entry.data
+ switch entry.kind {
+ case "user":
+ Label { Text(d.text ?? "").foregroundStyle(Palette.text) } icon: { Image(systemName: "person.fill") }
+ .font(.subheadline)
+ case "agent":
+ VStack(alignment: .leading, spacing: 4) {
+ Text(d.final == true ? "Reply" : "Said").font(.caption2.bold()).foregroundStyle(Palette.tertiary)
+ MarkdownText(d.text ?? "")
+ }
+ case "thought":
+ DisclosureGroup {
+ Text(d.text ?? "").font(.footnote).foregroundStyle(Palette.secondary).textSelection(.enabled)
+ } label: {
+ Label("Thinking", systemImage: "brain").font(.subheadline).foregroundStyle(Palette.secondary)
+ }
+ case "tool":
+ ToolRow(data: d)
+ case "plan":
+ VStack(alignment: .leading, spacing: 6) {
+ Label("Plan", systemImage: "checklist").font(.subheadline.bold())
+ ForEach(Array((d.entries ?? []).enumerated()), id: \.offset) { _, item in
+ Label {
+ Text(item.content).strikethrough(item.status == "completed").foregroundStyle(Palette.text)
+ } icon: {
+ Image(systemName: item.status == "completed" ? "checkmark.circle.fill" : item.status == "in_progress" ? "circle.dotted" : "circle")
+ .foregroundStyle(item.status == "completed" ? Palette.accent : Palette.tertiary)
+ }
+ .font(.footnote)
+ }
+ }
+ case "permission":
+ Label(d.title ?? "Approval", systemImage: "hand.raised")
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ default:
+ Text(d.text ?? "").font(.footnote).foregroundStyle(Palette.tertiary)
+ }
+ }
+}
+
+struct ToolRow: View {
+ let data: EntryData
+
+ private var icon: String {
+ switch data.toolKind {
+ case "read": "doc.text"
+ case "edit": "pencil"
+ case "delete": "trash"
+ case "move": "arrow.right.doc.on.clipboard"
+ case "search": "magnifyingglass"
+ case "execute": "terminal"
+ case "think": "brain"
+ case "fetch": "globe"
+ default: "wrench.and.screwdriver"
+ }
+ }
+
+ private var hasBody: Bool {
+ !(data.output ?? "").isEmpty || !(data.diffs ?? []).isEmpty
+ }
+
+ var body: some View {
+ if hasBody {
+ DisclosureGroup {
+ VStack(alignment: .leading, spacing: 8) {
+ ForEach(data.diffs ?? [], id: \.self) { DiffView(diff: $0) }
+ if let out = data.output, !out.isEmpty { CodeBox(text: out) }
+ }
+ } label: { label }
+ } else {
+ label
+ }
+ }
+
+ private var label: some View {
+ HStack(spacing: 8) {
+ Image(systemName: icon).frame(width: 18).foregroundStyle(Palette.secondary)
+ Text(data.title ?? "Tool").font(.subheadline).foregroundStyle(Palette.text).lineLimit(2)
+ Spacer(minLength: 4)
+ switch data.status {
+ case "completed": Image(systemName: "checkmark").foregroundStyle(Palette.accent)
+ case "failed": Image(systemName: "xmark").foregroundStyle(Palette.danger)
+ default: ProgressView().controlSize(.mini)
+ }
+ }
+ .font(.caption)
+ }
+}
diff --git a/Codync-iOS/Views/YouTubePlayerView.swift b/Codync-iOS/Views/YouTubePlayerView.swift
deleted file mode 100644
index 381f244f..00000000
--- a/Codync-iOS/Views/YouTubePlayerView.swift
+++ /dev/null
@@ -1,101 +0,0 @@
-import SwiftUI
-import WebKit
-
-struct YouTubePlayerView: UIViewRepresentable {
- let videoId: String
-
- func makeUIView(context: Context) -> WKWebView {
- let config = WKWebViewConfiguration()
- config.allowsInlineMediaPlayback = true
- config.mediaTypesRequiringUserActionForPlayback = []
- let webView = WKWebView(frame: .zero, configuration: config)
- webView.isOpaque = false
- webView.backgroundColor = .black
- webView.scrollView.backgroundColor = .black
- return webView
- }
-
- func updateUIView(_ webView: WKWebView, context: Context) {
- let url = URL(string: "https://www.youtube.com/watch?v=\(videoId)")!
- webView.load(URLRequest(url: url))
- }
-}
-
-private struct DemoVideoItem: Identifiable, Hashable {
- let id: String // YouTube video ID
- let title: String
- let subtitle: String
- let icon: String
-}
-
-private let demoVideos: [DemoVideoItem] = [
- DemoVideoItem(id: "A5ki29svIc4", title: "App Overview", subtitle: "Full walkthrough on Mac & iPhone", icon: "play.rectangle"),
- DemoVideoItem(id: "9klpDsbHwJU", title: "Real Device Demo", subtitle: "iCloud sync between Mac, iPhone & Watch", icon: "iphone.and.arrow.forward"),
- DemoVideoItem(id: "N-qhrJugoZo", title: "Apple Watch", subtitle: "Live session monitoring on your wrist", icon: "applewatch"),
-]
-
-struct DemoVideoSheet: View {
- @Environment(\.dismiss) private var dismiss
- @State private var selectedVideo: DemoVideoItem?
-
- var body: some View {
- NavigationStack {
- List(demoVideos) { video in
- Button {
- selectedVideo = video
- } label: {
- HStack(spacing: 14) {
- Image(systemName: video.icon)
- .font(.system(size: 20))
- .foregroundStyle(.white)
- .frame(width: 36, height: 36)
- VStack(alignment: .leading, spacing: 2) {
- Text(video.title)
- .font(.system(size: 16, weight: .semibold))
- .foregroundStyle(.white)
- Text(video.subtitle)
- .font(.system(size: 13))
- .foregroundStyle(.secondary)
- }
- Spacer()
- Image(systemName: "play.circle.fill")
- .font(.system(size: 22))
- .foregroundStyle(.secondary)
- }
- .padding(.vertical, 4)
- }
- }
- .listStyle(.plain)
- .navigationTitle("Demos")
- .navigationBarTitleDisplayMode(.inline)
- .toolbar {
- ToolbarItem(placement: .topBarTrailing) {
- Button("Done") { dismiss() }
- }
- }
- .navigationDestination(item: $selectedVideo) { video in
- YouTubePlayerView(videoId: video.id)
- .ignoresSafeArea(edges: .bottom)
- .navigationTitle(video.title)
- .navigationBarTitleDisplayMode(.inline)
- .toolbar {
- ToolbarItem(placement: .topBarTrailing) {
- Button {
- if let url = URL(string: "https://youtu.be/\(video.id)") {
- UIApplication.shared.open(url)
- }
- } label: {
- HStack(spacing: 4) {
- Image(systemName: "arrow.up.forward")
- .font(.system(size: 11, weight: .semibold))
- Text("YouTube")
- .font(.system(size: 14, weight: .medium))
- }
- }
- }
- }
- }
- }
- .preferredColorScheme(.dark)
- }
-}
diff --git a/Codync-macOS/App/CodyncApp.swift b/Codync-macOS/App/CodyncApp.swift
deleted file mode 100644
index 13fab46b..00000000
--- a/Codync-macOS/App/CodyncApp.swift
+++ /dev/null
@@ -1,73 +0,0 @@
-import SwiftUI
-import AppKit
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync", category: "App")
-
-@main
-struct CodyncApp: App {
- @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
-
- var body: some Scene {
- Settings { EmptyView() }
- }
-}
-
-@MainActor
-final class AppDelegate: NSObject, NSApplicationDelegate {
- var menuBarController: MenuBarController?
- let scanner = SessionScanner()
- var stateManager: SessionStateManager!
- var cloudKitSync: CloudKitSync!
- let hookServer = ClaudeHookServer()
-
- func applicationDidFinishLaunching(_ notification: Notification) {
- NSApp.setActivationPolicy(.accessory)
-
- scanner.hookServer = hookServer
- stateManager = SessionStateManager(scanner: scanner)
- stateManager.hookServer = hookServer
- cloudKitSync = CloudKitSync(stateManager: stateManager)
- menuBarController = MenuBarController(stateManager: stateManager)
-
- hookServer.ensureHooksConfigured()
- // SessionStart/SessionEnd: immediate refresh (new/removed session)
- hookServer.onSessionEvent = { [weak self] in
- Task { @MainActor in
- self?.stateManager.refreshFromHookState()
- }
- }
- // All other hooks: immediate refresh with hook signal applied first
- hookServer.onHookSignal = { [weak self] sessionId, signal, toolName in
- Task { @MainActor in
- self?.stateManager.transcriptWatcher.handleHookSignal(
- sessionId: sessionId, signal: signal, toolName: toolName
- )
- self?.stateManager.refreshFromHookState()
- }
- }
- hookServer.start()
-
- scanner.start()
- logger.info("Codync launched — hook-driven status detection (7 hooks) + JSONL supplementary data")
-
- Task {
- do {
- let activeIds = Set(scanner.activeSessions.keys)
- try await CloudKitManager.shared.deleteOrphans(activeSessionIds: activeIds)
- } catch {
- logger.warning("Orphan cleanup failed: \(error.localizedDescription)")
- }
- }
- }
-
- func applicationWillTerminate(_ notification: Notification) {
- scanner.stop()
- hookServer.stop()
- }
-
- func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
- false
- }
-}
diff --git a/Codync-macOS/App/CodyncPanel.swift b/Codync-macOS/App/CodyncPanel.swift
deleted file mode 100644
index ec44681b..00000000
--- a/Codync-macOS/App/CodyncPanel.swift
+++ /dev/null
@@ -1,42 +0,0 @@
-import AppKit
-
-extension Notification.Name {
- static let codePulseShouldCollapse = Notification.Name("codePulseShouldCollapse")
-}
-
-/// A borderless, transparent floating panel for Codync's notch UI
-final class CodyncPanel: NSPanel {
- init(frame: CGRect) {
- super.init(
- contentRect: frame,
- styleMask: [.borderless, .nonactivatingPanel],
- backing: .buffered,
- defer: false
- )
-
- isFloatingPanel = true
- becomesKeyOnlyIfNeeded = true
-
- level = .mainMenu + 3
- collectionBehavior = [
- .fullScreenAuxiliary,
- .stationary,
- .canJoinAllSpaces,
- .ignoresCycle,
- ]
-
- isOpaque = false
- backgroundColor = .clear
- hasShadow = false
- isMovable = false
- }
-
- override var canBecomeKey: Bool { true }
- override var canBecomeMain: Bool { false }
-
- override func keyDown(with event: NSEvent) {
- if event.keyCode == 53 { // ESC
- NotificationCenter.default.post(name: .codePulseShouldCollapse, object: nil)
- }
- }
-}
diff --git a/Codync-macOS/App/CodyncPanelShape.swift b/Codync-macOS/App/CodyncPanelShape.swift
deleted file mode 100644
index 8ac82d8a..00000000
--- a/Codync-macOS/App/CodyncPanelShape.swift
+++ /dev/null
@@ -1,63 +0,0 @@
-import SwiftUI
-
-/// Panel clip shape with animatable corner radii.
-/// Top corners curve inward (connecting to screen bezel), bottom corners curve outward.
-nonisolated struct CodyncPanelShape: Shape {
- var topCornerRadius: CGFloat
- var bottomCornerRadius: CGFloat
-
- init(topCornerRadius: CGFloat = 6, bottomCornerRadius: CGFloat = 14) {
- self.topCornerRadius = topCornerRadius
- self.bottomCornerRadius = bottomCornerRadius
- }
-
- var animatableData: AnimatablePair<CGFloat, CGFloat> {
- get { .init(topCornerRadius, bottomCornerRadius) }
- set {
- topCornerRadius = newValue.first
- bottomCornerRadius = newValue.second
- }
- }
-
- func path(in rect: CGRect) -> Path {
- var path = Path()
-
- path.move(to: CGPoint(x: rect.minX, y: rect.minY))
-
- // Top-left: inward curve connecting to the screen bezel
- path.addQuadCurve(
- to: CGPoint(x: rect.minX + topCornerRadius, y: rect.minY + topCornerRadius),
- control: CGPoint(x: rect.minX + topCornerRadius, y: rect.minY)
- )
-
- // Left edge
- path.addLine(to: CGPoint(x: rect.minX + topCornerRadius, y: rect.maxY - bottomCornerRadius))
-
- // Bottom-left: outward curve
- path.addQuadCurve(
- to: CGPoint(x: rect.minX + topCornerRadius + bottomCornerRadius, y: rect.maxY),
- control: CGPoint(x: rect.minX + topCornerRadius, y: rect.maxY)
- )
-
- // Bottom edge
- path.addLine(to: CGPoint(x: rect.maxX - topCornerRadius - bottomCornerRadius, y: rect.maxY))
-
- // Bottom-right: outward curve
- path.addQuadCurve(
- to: CGPoint(x: rect.maxX - topCornerRadius, y: rect.maxY - bottomCornerRadius),
- control: CGPoint(x: rect.maxX - topCornerRadius, y: rect.maxY)
- )
-
- // Right edge
- path.addLine(to: CGPoint(x: rect.maxX - topCornerRadius, y: rect.minY + topCornerRadius))
-
- // Top-right: inward curve connecting to the screen bezel
- path.addQuadCurve(
- to: CGPoint(x: rect.maxX, y: rect.minY),
- control: CGPoint(x: rect.maxX - topCornerRadius, y: rect.minY)
- )
-
- path.closeSubpath()
- return path
- }
-}
diff --git a/Codync-macOS/App/EventMonitor.swift b/Codync-macOS/App/EventMonitor.swift
deleted file mode 100644
index 7eecefe8..00000000
--- a/Codync-macOS/App/EventMonitor.swift
+++ /dev/null
@@ -1,34 +0,0 @@
-import AppKit
-
-final class EventMonitor {
- private var globalMonitor: Any?
- private var localMonitor: Any?
- private let mask: NSEvent.EventTypeMask
- private let handler: @Sendable (NSEvent) -> Void
-
- init(mask: NSEvent.EventTypeMask, handler: @escaping @Sendable (NSEvent) -> Void) {
- self.mask = mask
- self.handler = handler
- }
-
- deinit {
- stop()
- }
-
- func start() {
- globalMonitor = NSEvent.addGlobalMonitorForEvents(matching: mask) { [weak self] event in
- self?.handler(event)
- }
- }
-
- func stop() {
- if let monitor = globalMonitor {
- NSEvent.removeMonitor(monitor)
- globalMonitor = nil
- }
- if let monitor = localMonitor {
- NSEvent.removeMonitor(monitor)
- localMonitor = nil
- }
- }
-}
diff --git a/Codync-macOS/App/MenuBarController.swift b/Codync-macOS/App/MenuBarController.swift
deleted file mode 100644
index 7740371a..00000000
--- a/Codync-macOS/App/MenuBarController.swift
+++ /dev/null
@@ -1,336 +0,0 @@
-import SwiftUI
-import Combine
-import CodyncShared
-
-// MARK: - Panel State
-
-@MainActor
-final class CodyncPanelState: ObservableObject {
- @Published var isExpanded = false
- @Published var isPinned = false
- @Published var headerSize: CGSize = .zero
- @Published var contentHeight: CGFloat = 0
- var collapsedRect: CGRect = .zero
- var panelRect: CGRect = .zero // fixed size — used for hitTest
- var contentRect: CGRect = .zero // dynamic — used for click-outside dismissal
-
- private let expandedWidth: CGFloat = 380
- private let expandedHeight: CGFloat = 500
- private var screenRef: NSScreen?
-
- func updateGeometry(for screen: NSScreen) {
- screenRef = screen
- headerSize = screen.notchSize
- recomputeRects()
- }
-
- func recomputeRects() {
- guard let screen = screenRef else { return }
- let centerX = screen.frame.origin.x + screen.frame.width / 2
-
- let iconExtension: CGFloat = 40
- collapsedRect = CGRect(
- x: centerX - headerSize.width / 2,
- y: screen.frame.maxY - headerSize.height,
- width: headerSize.width + iconExtension,
- height: headerSize.height
- )
-
- // hitTest rect — always full size so clicks reach SwiftUI
- panelRect = CGRect(
- x: centerX - expandedWidth / 2,
- y: screen.frame.maxY - expandedHeight,
- width: expandedWidth,
- height: expandedHeight
- )
-
- // content rect — dynamic, for click-outside dismissal
- let h = contentHeight > 0 ? min(contentHeight, expandedHeight) : expandedHeight
- contentRect = CGRect(
- x: centerX - expandedWidth / 2,
- y: screen.frame.maxY - h,
- width: expandedWidth,
- height: h
- )
- }
-}
-
-// MARK: - Menu Bar Controller
-
-@MainActor
-final class MenuBarController: NSObject {
- private var statusItem: NSStatusItem!
- private let stateManager: SessionStateManager
- private var cancellables = Set<AnyCancellable>()
-
- private var panel: CodyncPanel?
- private var hitTestView: CodyncHitTestView?
- private let panelState = CodyncPanelState()
- private var mouseDownMonitor: EventMonitor?
-
- init(stateManager: SessionStateManager) {
- self.stateManager = stateManager
- super.init()
- if NSScreen.builtInOrMain.hasNotch {
- setupPanel()
- } else {
- setupStatusItem()
- setupPanel()
- observeSessionCount()
- }
- setupClickOutsideMonitor()
- observeScreenChanges()
- observePanelState()
- }
-
- // MARK: - Status Item
-
- private func setupStatusItem() {
- statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
- if let button = statusItem.button {
- let icon = NSImage(named: "CodyncIcon")
- icon?.size = NSSize(width: 18, height: 18)
- icon?.isTemplate = true
- button.image = icon
- button.action = #selector(togglePanel)
- button.target = self
- }
- }
-
- private func observeSessionCount() {
- stateManager.$sessions
- .receive(on: RunLoop.main)
- .sink { [weak self] sessions in
- let activeCount = sessions.filter { $0.status.isActive }.count
- self?.updateBadge(count: activeCount)
- }
- .store(in: &cancellables)
- }
-
- private func updateBadge(count: Int) {
- guard let button = statusItem.button else { return }
- button.title = count > 0 ? " \(count)" : ""
- }
-
- // MARK: - Panel Setup
-
- private func setupPanel() {
- let screen = NSScreen.builtInOrMain
- panelState.updateGeometry(for: screen)
-
- let panel = CodyncPanel(frame: fullScreenTopFrame(for: screen))
-
- let contentView = CodyncPanelContentView(
- panelState: panelState,
- stateManager: stateManager
- )
- let hostingView = NSHostingView(rootView: contentView)
-
- let hitTestView = CodyncHitTestView()
- hitTestView.collapsedRect = panelState.collapsedRect
- hitTestView.panelRect = panelState.panelRect
- hitTestView.addSubview(hostingView)
- hostingView.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- hostingView.topAnchor.constraint(equalTo: hitTestView.topAnchor),
- hostingView.bottomAnchor.constraint(equalTo: hitTestView.bottomAnchor),
- hostingView.leadingAnchor.constraint(equalTo: hitTestView.leadingAnchor),
- hostingView.trailingAnchor.constraint(equalTo: hitTestView.trailingAnchor),
- ])
-
- panel.contentView = hitTestView
- panel.orderFrontRegardless()
-
- self.panel = panel
- self.hitTestView = hitTestView
- }
-
- private func fullScreenTopFrame(for screen: NSScreen) -> NSRect {
- let height: CGFloat = 500
- return NSRect(
- x: screen.frame.origin.x,
- y: screen.frame.maxY - height,
- width: screen.frame.width,
- height: height
- )
- }
-
- @objc private func togglePanel() {
- panelState.isExpanded.toggle()
- }
-
- // MARK: - State Sync
-
- private func observePanelState() {
- panelState.$isExpanded
- .sink { [weak self] expanded in
- self?.hitTestView?.isExpanded = expanded
- }
- .store(in: &cancellables)
-
- panelState.$contentHeight
- .sink { [weak self] _ in
- guard let self else { return }
- self.panelState.recomputeRects()
- // hitTestView.panelRect stays fixed — only contentRect is dynamic
- }
- .store(in: &cancellables)
-
- NotificationCenter.default.addObserver(
- forName: .codePulseShouldCollapse,
- object: nil,
- queue: .main
- ) { [weak self] _ in
- Task { @MainActor in
- self?.panelState.isExpanded = false
- }
- }
- }
-
- // MARK: - Click Outside to Dismiss
-
- private func setupClickOutsideMonitor() {
- mouseDownMonitor = EventMonitor(mask: .leftMouseDown) { [weak self] _ in
- Task { @MainActor in
- self?.handleGlobalClick()
- }
- }
- mouseDownMonitor?.start()
- }
-
- private func handleGlobalClick() {
- guard panelState.isExpanded, !panelState.isPinned else { return }
- panelState.isExpanded = false
- }
-
- // MARK: - Screen Changes
-
- private func observeScreenChanges() {
- NotificationCenter.default.addObserver(
- self,
- selector: #selector(screenDidChange),
- name: NSApplication.didChangeScreenParametersNotification,
- object: nil
- )
- }
-
- @objc private func screenDidChange() {
- MainActor.assumeIsolated {
- let screen = NSScreen.builtInOrMain
- panelState.updateGeometry(for: screen)
- hitTestView?.collapsedRect = panelState.collapsedRect
- hitTestView?.panelRect = panelState.panelRect // fixed full-size rect
- panel?.setFrame(fullScreenTopFrame(for: screen), display: true)
- }
- }
-}
-
-// MARK: - Hit Test View
-
-/// Passes through clicks outside the active rect (collapsed header vs expanded panel).
-private final class CodyncHitTestView: NSView {
- var isExpanded = false
- var collapsedRect: CGRect = .zero
- var panelRect: CGRect = .zero
-
- override func hitTest(_ point: NSPoint) -> NSView? {
- guard let window else { return nil }
- let screenPoint = window.convertPoint(toScreen: convert(point, to: nil))
- let activeRect = isExpanded ? panelRect : collapsedRect
- guard activeRect.contains(screenPoint) else { return nil }
- return super.hitTest(point)
- }
-}
-
-// MARK: - Panel Content View
-
-/// The SwiftUI root view for the Codync panel.
-/// Collapsed: invisible black shape matching the screen header area.
-/// Expanded: shape extends downward with spring animation, revealing SessionListView.
-private struct CodyncPanelContentView: View {
- @ObservedObject var panelState: CodyncPanelState
- @ObservedObject var stateManager: SessionStateManager
- @AppStorage("codync_darkMode") private var isDarkMode = true
-
- private var headerSize: CGSize { panelState.headerSize }
- private var isExpanded: Bool { panelState.isExpanded }
-
- private var panelAnimation: Animation {
- isExpanded
- ? .spring(response: 0.42, dampingFraction: 0.78)
- : .spring(response: 0.35, dampingFraction: 1.0)
- }
-
- private var topCornerRadius: CGFloat {
- isExpanded ? 19 : 6
- }
-
- private var bottomCornerRadius: CGFloat {
- isExpanded ? 24 : 14
- }
-
- var body: some View {
- VStack(spacing: 0) {
- // Header — matches screen notch height, tappable to expand
- HStack(spacing: 0) {
- Color.clear
- if !isExpanded {
- Image("CodyncIcon")
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 18, height: 18)
- .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous))
- .frame(width: 32, height: headerSize.height)
- }
- }
- .frame(height: headerSize.height)
- .contentShape(Rectangle())
- .onTapGesture {
- panelState.isExpanded.toggle()
- }
-
- // Session list appears when expanded
- if isExpanded {
- SessionListView(stateManager: stateManager, panelState: panelState)
- .environment(\.theme, CodyncTheme(isDark: true, isPanel: true))
- .preferredColorScheme(.dark)
- .transition(
- .asymmetric(
- insertion: .opacity
- .combined(with: .scale(scale: 0.88, anchor: .top))
- .animation(.smooth(duration: 0.3).delay(0.06)),
- removal: .opacity
- .animation(.easeOut(duration: 0.12))
- )
- )
- }
- }
- .frame(width: isExpanded ? 320 : headerSize.width + 18)
- .padding(.horizontal, isExpanded ? 19 : 6)
- .padding(.bottom, isExpanded ? 12 : 0)
- .background(Color.black)
- .clipShape(CodyncPanelShape(
- topCornerRadius: topCornerRadius,
- bottomCornerRadius: bottomCornerRadius
- ))
- .shadow(color: isExpanded ? .black.opacity(0.6) : .clear, radius: 8)
- .offset(x: isExpanded ? 0 : 15)
- .background(
- GeometryReader { geo in
- Color.clear.preference(key: ContentHeightKey.self, value: geo.size.height)
- }
- )
- .onPreferenceChange(ContentHeightKey.self) { height in
- if height > 0 { panelState.contentHeight = height }
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
- .animation(panelAnimation, value: isExpanded)
- }
-}
-
-private struct ContentHeightKey: PreferenceKey {
- static let defaultValue: CGFloat = 0
- static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
- value = max(value, nextValue())
- }
-}
diff --git a/Codync-macOS/App/NSScreen+Notch.swift b/Codync-macOS/App/NSScreen+Notch.swift
deleted file mode 100644
index f49b8ee2..00000000
--- a/Codync-macOS/App/NSScreen+Notch.swift
+++ /dev/null
@@ -1,35 +0,0 @@
-import AppKit
-
-extension NSScreen {
- /// Returns the built-in MacBook display, falling back to the main screen
- static var builtInOrMain: NSScreen {
- screens.first { $0.isBuiltIn } ?? main!
- }
-
- /// Whether this screen is the built-in display
- var isBuiltIn: Bool {
- guard let screenNumber = deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID else {
- return false
- }
- return CGDisplayIsBuiltin(screenNumber) != 0
- }
-
- /// Whether this screen has a notch (safeAreaInsets.top > 0)
- var hasNotch: Bool {
- safeAreaInsets.top > 0
- }
-
- /// Calculates the notch dimensions for this screen
- var notchSize: CGSize {
- guard hasNotch else {
- // Fallback for non-notch screens: approximate a notch-like area
- return CGSize(width: 224, height: 38)
- }
- let fullWidth = frame.width
- let leftPadding = auxiliaryTopLeftArea?.width ?? 0
- let rightPadding = auxiliaryTopRightArea?.width ?? 0
- let notchWidth = fullWidth - leftPadding - rightPadding
- let notchHeight = safeAreaInsets.top + 1
- return CGSize(width: notchWidth, height: notchHeight)
- }
-}
diff --git a/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/Contents.json b/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/Contents.json
deleted file mode 100644
index 1258da4b..00000000
--- a/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/Contents.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "images" : [
- {
- "filename" : "image 5.png",
- "idiom" : "universal",
- "scale" : "1x"
- },
- {
- "filename" : "image 6.png",
- "idiom" : "universal",
- "scale" : "2x"
- },
- {
- "filename" : "image 7.png",
- "idiom" : "universal",
- "scale" : "3x"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- },
- "properties" : {
- "template-rendering-intent" : "original"
- }
-}
diff --git a/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/image 5.png b/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/image 5.png
deleted file mode 100644
index 9738d48d..00000000
Binary files a/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/image 5.png and /dev/null differ
diff --git a/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/image 6.png b/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/image 6.png
deleted file mode 100644
index c3a45433..00000000
Binary files a/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/image 6.png and /dev/null differ
diff --git a/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/image 7.png b/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/image 7.png
deleted file mode 100644
index d7a95064..00000000
Binary files a/Codync-macOS/Assets.xcassets/CodyncIcon.imageset/image 7.png and /dev/null differ
diff --git a/Codync-macOS/CodyncMacApp.swift b/Codync-macOS/CodyncMacApp.swift
new file mode 100644
index 00000000..2c862c6c
--- /dev/null
+++ b/Codync-macOS/CodyncMacApp.swift
@@ -0,0 +1,270 @@
+import CodyncKit
+import CoreImage.CIFilterBuiltins
+import SwiftUI
+
+@main
+struct CodyncMacApp: App {
+ @State private var host = HostController()
+
+ var body: some Scene {
+ MenuBarExtra {
+ MenuView()
+ .environment(host)
+ .frame(width: 340)
+ } label: {
+ Image(systemName: host.needsAttention ? "person.2.badge.gearshape.fill" : host.working > 0 ? "person.2.wave.2.fill" : "person.2.fill")
+ .task { host.start() }
+ }
+ .menuBarExtraStyle(.window)
+ }
+}
+
+struct MenuView: View {
+ @Environment(HostController.self) private var host
+ @State private var showPairing = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ header
+ Divider().overlay(Palette.border)
+ if showPairing {
+ PairingPanel { showPairing = false }
+ } else {
+ content
+ }
+ Divider().overlay(Palette.border)
+ footer
+ }
+ .background(Palette.background)
+ }
+
+ private var header: some View {
+ HStack(spacing: 10) {
+ CharacterAvatar(shape: "blob", color: "green", size: 26, mood: host.working > 0 ? .working : .idle)
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Codync").font(.headline).foregroundStyle(Palette.text)
+ Text(statusLine).font(.caption).foregroundStyle(Palette.secondary)
+ }
+ Spacer()
+ if host.state == .running {
+ Button {
+ showPairing.toggle()
+ if showPairing { host.loadPairing() }
+ } label: {
+ Label("Pair iPhone", systemImage: "qrcode")
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Palette.accentFill)
+ .foregroundStyle(Palette.onAccent)
+ .controlSize(.small)
+ }
+ }
+ .padding(12)
+ }
+
+ private var statusLine: String {
+ switch host.state {
+ case .missingBinary: "Host not found"
+ case .notInstalled: "Host not installed"
+ case .starting: "Starting host…"
+ case .running: host.working > 0 ? "\(host.working) bot\(host.working == 1 ? "" : "s") working" : "Ready · v\(host.version ?? "")"
+ case .failed: "Host problem"
+ }
+ }
+
+ @ViewBuilder private var content: some View {
+ switch host.state {
+ case .missingBinary:
+ Notice(text: "This build of Codync doesn't include codync-host. Reinstall the app, or install the host with Homebrew:", code: "brew install leepokai/codync/codync-host")
+ case .notInstalled:
+ VStack(alignment: .leading, spacing: 10) {
+ Text("Run your bots on this Mac").font(.subheadline.bold()).foregroundStyle(Palette.text)
+ Text("Codync installs a small background service that runs Claude Code, Codex and other agents for your bots — even when this menu is closed.")
+ .font(.caption)
+ .foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ Button("Install host") { host.install() }
+ .buttonStyle(.borderedProminent)
+ .tint(Palette.accentFill)
+ .foregroundStyle(Palette.onAccent)
+ }
+ .padding(12)
+ case .starting:
+ HStack { ProgressView().controlSize(.small); Text("Connecting…").font(.caption) }.padding(12)
+ case let .failed(message):
+ VStack(alignment: .leading, spacing: 8) {
+ Text(message).font(.caption).foregroundStyle(Palette.danger).textSelection(.enabled)
+ HStack {
+ Button("Restart host") { host.restart() }
+ Button("Open log") { NSWorkspace.shared.open(host.logURL) }
+ }
+ }
+ .padding(12)
+ case .running:
+ running
+ }
+ }
+
+ private var running: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ if host.bots.isEmpty {
+ Text("No bots yet. Create one from the Codync app on your iPhone.")
+ .fixedSize(horizontal: false, vertical: true)
+ .font(.caption)
+ .foregroundStyle(Palette.secondary)
+ .padding(12)
+ } else {
+ ScrollView {
+ VStack(spacing: 2) {
+ ForEach(host.bots) { bot in
+ BotLine(bot: bot) { host.stop(bot) }
+ }
+ }
+ .padding(6)
+ }
+ // ScrollView has no intrinsic height inside a MenuBarExtra window.
+ .frame(height: min(CGFloat(host.bots.count) * 46 + 12, 320))
+ }
+ if !host.usage.providers.isEmpty {
+ Divider().overlay(Palette.border)
+ VStack(alignment: .leading, spacing: 8) {
+ ForEach(host.usage.providers) { p in
+ ForEach(p.windows) { w in
+ HStack(spacing: 8) {
+ Text("\(p.name) \(w.label)").font(.caption).foregroundStyle(Palette.secondary).frame(width: 130, alignment: .leading)
+ ProgressView(value: min(w.percent, 100), total: 100)
+ .tint(w.percent >= 90 ? Palette.danger : w.percent >= 70 ? Palette.warning : Palette.accent)
+ Text("\(Int(w.percent.rounded()))%").font(.caption.monospacedDigit()).frame(width: 36, alignment: .trailing)
+ }
+ }
+ }
+ }
+ .padding(12)
+ }
+ }
+ }
+
+ private var footer: some View {
+ @Bindable var host = host
+ return HStack {
+ Toggle("Open at login", isOn: Binding(get: { host.launchAtLogin }, set: { host.setLaunchAtLogin($0) }))
+ .toggleStyle(.checkbox)
+ .font(.caption)
+ Spacer()
+ Menu {
+ Button("Restart host") { host.restart() }
+ Button("Open log") { NSWorkspace.shared.open(host.logURL) }
+ Divider()
+ Button("Uninstall host service") { host.uninstall() }
+ } label: {
+ Image(systemName: "gearshape")
+ }
+ .menuStyle(.borderlessButton)
+ .fixedSize()
+ Button("Quit") { NSApp.terminate(nil) }
+ .font(.caption)
+ }
+ .padding(10)
+ }
+}
+
+private struct BotLine: View {
+ let bot: Bot
+ let stop: () -> Void
+ @State private var hovering = false
+
+ var body: some View {
+ HStack(spacing: 10) {
+ AvatarWithStatus(bot: bot, size: 30)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(bot.name).font(.callout.weight(.medium)).foregroundStyle(Palette.text)
+ Text(bot.isWorking ? (bot.activity.isEmpty ? "Working…" : bot.activity) : (bot.lastMessage ?? bot.folderName))
+ .font(.caption)
+ .foregroundStyle(bot.needsInput ? Palette.warning : bot.isWorking ? Palette.accent : Palette.secondary)
+ .lineLimit(1)
+ }
+ Spacer()
+ if bot.isWorking && hovering {
+ Button("Stop", action: stop).controlSize(.small)
+ } else {
+ Text(RelativeTime.short(Date(milliseconds: bot.lastAt))).font(.caption2).foregroundStyle(Palette.tertiary)
+ }
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 6)
+ .background(hovering ? Palette.bubbleAgent : .clear, in: RoundedRectangle(cornerRadius: 8))
+ .onHover { hovering = $0 }
+ }
+}
+
+private struct PairingPanel: View {
+ @Environment(HostController.self) private var host
+ let close: () -> Void
+
+ var body: some View {
+ VStack(spacing: 12) {
+ if let info = host.pairInfo {
+ if let image = qr(info.pairingUrl) {
+ Image(nsImage: image)
+ .interpolation(.none)
+ .resizable()
+ .frame(width: 200, height: 200)
+ .padding(10)
+ .background(.white, in: RoundedRectangle(cornerRadius: 12))
+ }
+ Text("Scan with the Codync app or the iPhone Camera.")
+ .font(.caption)
+ .foregroundStyle(Palette.secondary)
+ if info.urls.isEmpty {
+ Text("No network address found. Connect this Mac to Wi-Fi or Tailscale.")
+ .font(.caption)
+ .foregroundStyle(Palette.warning)
+ } else if !info.urls.contains(where: { $0.contains("://100.") || $0.contains(".ts.net") }) {
+ Text("Tip: install Tailscale on this Mac and your iPhone to reach your bots from anywhere.")
+ .font(.caption)
+ .foregroundStyle(Palette.tertiary)
+ .multilineTextAlignment(.center)
+ }
+ Button("Copy link") {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(info.pairingUrl, forType: .string)
+ }
+ .controlSize(.small)
+ } else {
+ ProgressView()
+ }
+ Button("Done", action: close).controlSize(.small)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(16)
+ }
+
+ private func qr(_ string: String) -> NSImage? {
+ let filter = CIFilter.qrCodeGenerator()
+ filter.message = Data(string.utf8)
+ filter.correctionLevel = "M"
+ guard let output = filter.outputImage else { return nil }
+ let rep = NSCIImageRep(ciImage: output)
+ let image = NSImage(size: rep.size)
+ image.addRepresentation(rep)
+ return image
+ }
+}
+
+private struct Notice: View {
+ let text: String
+ let code: String
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(text).font(.caption).foregroundStyle(Palette.secondary).fixedSize(horizontal: false, vertical: true)
+ Text(code)
+ .font(.caption.monospaced())
+ .textSelection(.enabled)
+ .padding(8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 6))
+ }
+ .padding(12)
+ }
+}
diff --git a/Codync-macOS/HostController.swift b/Codync-macOS/HostController.swift
new file mode 100644
index 00000000..6fe280c9
--- /dev/null
+++ b/Codync-macOS/HostController.swift
@@ -0,0 +1,205 @@
+import CodyncKit
+import Foundation
+import Observation
+import ServiceManagement
+
+/// Manages the local codync-host: finds the binary, installs the background
+/// service, and mirrors bots + usage over the same API the phone uses.
+@MainActor
+@Observable
+final class HostController {
+ enum State: Equatable {
+ case missingBinary
+ case notInstalled
+ case starting
+ case running
+ case failed(String)
+ }
+
+ struct PairInfo: Decodable {
+ var name: String
+ var token: String
+ var urls: [String]
+ var pairingUrl: String
+ }
+
+ /// `CODYNC_PORT` / `CODYNC_HOME` point the app at a dev host started with `codync-host serve`.
+ static let devPort = ProcessInfo.processInfo.environment["CODYNC_PORT"].flatMap(Int.init)
+ static let port = devPort ?? 19222
+ static let dataDir = ProcessInfo.processInfo.environment["CODYNC_HOME"].map { URL(filePath: $0) }
+ ?? FileManager.default.homeDirectoryForCurrentUser.appending(path: ".codync")
+
+ private(set) var state: State = .starting
+ private(set) var bots: [Bot] = []
+ private(set) var usage = Usage()
+ private(set) var pairInfo: PairInfo?
+ private(set) var version: String?
+ var launchAtLogin: Bool = SMAppService.mainApp.status == .enabled
+
+ private var streamTask: Task<Void, Never>?
+
+ var needsAttention: Bool { bots.contains(where: \.needsInput) }
+ var working: Int { bots.filter(\.isWorking).count }
+
+ /// Bundled next to the app executable, else a Homebrew / cargo install.
+ var binaryURL: URL? {
+ let candidates = [
+ Bundle.main.bundleURL.appending(path: "Contents/MacOS/codync-host"),
+ URL(filePath: "/opt/homebrew/bin/codync-host"),
+ URL(filePath: "/usr/local/bin/codync-host"),
+ FileManager.default.homeDirectoryForCurrentUser.appending(path: ".cargo/bin/codync-host"),
+ ]
+ return candidates.first { FileManager.default.isExecutableFile(atPath: $0.path) }
+ }
+
+ private var plistURL: URL {
+ FileManager.default.homeDirectoryForCurrentUser.appending(path: "Library/LaunchAgents/com.pokai.codync.host.plist")
+ }
+
+ private var tokenURL: URL { Self.dataDir.appending(path: "token") }
+
+ var logURL: URL { Self.dataDir.appending(path: "host.log") }
+
+ func start() {
+ refresh()
+ }
+
+ func refresh() {
+ guard binaryURL != nil else {
+ state = .missingBinary
+ return
+ }
+ guard Self.devPort != nil || FileManager.default.fileExists(atPath: plistURL.path) else {
+ state = .notInstalled
+ return
+ }
+ connect()
+ }
+
+ /// `codync-host install` also removes Codync 1.x Claude hooks.
+ func install() {
+ guard let bin = binaryURL else { return }
+ state = .starting
+ Task {
+ let result = await Self.run(bin, ["install", "--port", "\(Self.port)"])
+ if result.status != 0 {
+ state = .failed(result.output.isEmpty ? "Install failed" : result.output)
+ } else {
+ try? await Task.sleep(for: .seconds(1))
+ connect()
+ }
+ }
+ }
+
+ func restart() {
+ let uid = getuid()
+ Task {
+ _ = await Self.run(URL(filePath: "/bin/launchctl"), ["kickstart", "-k", "gui/\(uid)/com.pokai.codync.host"])
+ try? await Task.sleep(for: .seconds(1))
+ connect()
+ }
+ }
+
+ func uninstall() {
+ guard let bin = binaryURL else { return }
+ streamTask?.cancel()
+ Task {
+ _ = await Self.run(bin, ["uninstall"])
+ bots = []
+ state = .notInstalled
+ }
+ }
+
+ func loadPairing() {
+ guard let bin = binaryURL else { return }
+ Task {
+ let result = await Self.run(bin, ["pair", "--json", "--port", "\(Self.port)"])
+ pairInfo = try? JSONDecoder().decode(PairInfo.self, from: Data(result.output.utf8))
+ }
+ }
+
+ func setLaunchAtLogin(_ on: Bool) {
+ do {
+ if on { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() }
+ } catch {}
+ launchAtLogin = SMAppService.mainApp.status == .enabled
+ }
+
+ func stop(_ bot: Bot) {
+ Task { try? await client()?.stop(bot.id) }
+ }
+
+ private func client() -> HostClient? {
+ guard let token = try? String(contentsOf: tokenURL, encoding: .utf8) else { return nil }
+ return HostClient(baseURL: URL(string: "http://127.0.0.1:\(Self.port)")!, token: token.trimmingCharacters(in: .whitespacesAndNewlines))
+ }
+
+ private func connect() {
+ streamTask?.cancel()
+ streamTask = Task { [weak self] in
+ var attempts = 0
+ while !Task.isCancelled {
+ guard let self else { return }
+ guard let client = self.client(), await client.healthy(timeout: 2) else {
+ attempts += 1
+ self.state = attempts > 5 ? .failed("The host isn't responding. See the log for details.") : .starting
+ try? await Task.sleep(for: .seconds(2))
+ continue
+ }
+ attempts = 0
+ self.version = (try? await client.hello())?.version
+ var mirror: [String: Bot] = [:]
+ do {
+ for try await event in client.events(since: 0, client: "mac") {
+ self.state = .running
+ switch event {
+ case let .bot(bot): mirror[bot.id] = bot
+ case let .botDeleted(id, _): mirror[id] = nil
+ case let .hello(_, _, usage), let .usage(usage): self.usage = usage
+ case .entry, .resync, .undecodable: break
+ }
+ self.bots = mirror.values.filter { !$0.hidden }.sorted { $0.lastAt > $1.lastAt }
+ }
+ } catch {}
+ try? await Task.sleep(for: .seconds(2))
+ }
+ }
+ }
+
+ nonisolated static func run(_ bin: URL, _ args: [String]) async -> (status: Int32, output: String) {
+ await withCheckedContinuation { cont in
+ let p = Process()
+ p.executableURL = bin
+ p.arguments = args
+ // GUI apps get a minimal PATH; give the service the usual tool locations.
+ var env = ProcessInfo.processInfo.environment
+ let home = FileManager.default.homeDirectoryForCurrentUser.path
+ let extra = ["/opt/homebrew/bin", "/usr/local/bin", "\(home)/.local/bin", "\(home)/.cargo/bin", "\(home)/.bun/bin", "\(home)/.opencode/bin"]
+ env["PATH"] = (extra + [loginShellPath() ?? "/usr/bin:/bin:/usr/sbin:/sbin"]).joined(separator: ":")
+ p.environment = env
+ let pipe = Pipe()
+ p.standardOutput = pipe
+ p.standardError = pipe
+ p.terminationHandler = { proc in
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ cont.resume(returning: (proc.terminationStatus, String(decoding: data, as: UTF8.self)))
+ }
+ do { try p.run() } catch { cont.resume(returning: (-1, error.localizedDescription)) }
+ }
+ }
+
+ /// The user's interactive PATH (nvm, asdf, …) so npx/claude/codex resolve in the service.
+ nonisolated static func loginShellPath() -> String? {
+ let shell = ProcessInfo.processInfo.environment["SHELL"] ?? "/bin/zsh"
+ let p = Process()
+ p.executableURL = URL(filePath: shell)
+ p.arguments = ["-ilc", "printf %s \"$PATH\""]
+ let pipe = Pipe()
+ p.standardOutput = pipe
+ p.standardError = FileHandle.nullDevice
+ guard (try? p.run()) != nil else { return nil }
+ p.waitUntilExit()
+ let out = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
+ return out.isEmpty ? nil : out
+ }
+}
diff --git a/Codync-macOS/Services/APNsPushService.swift b/Codync-macOS/Services/APNsPushService.swift
deleted file mode 100644
index 327cfaf2..00000000
--- a/Codync-macOS/Services/APNsPushService.swift
+++ /dev/null
@@ -1,244 +0,0 @@
-import Foundation
-import CloudKit
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync", category: "APNsPush")
-
-@MainActor
-final class APNsPushService {
- static let shared = APNsPushService()
-
- private let workerURL = URL(string: APNsSecrets.workerURL)!
- private let apiSecret = APNsSecrets.apiSecret
-
- private(set) var pushTokens: [String: String] = [:] // sessionId → token hex
- var tokenCount: Int { pushTokens.count }
- private var isFetchingTokens = false
- private var lastTokenFetch: Date = .distantPast
- private init() {
- logger.info("APNs push service ready (Worker relay)")
- }
-
- // MARK: - Public API
-
- func sendUpdate(session: SessionState) async {
- guard let tokenHex = pushTokens[session.sessionId] else { return }
-
- let contentState = Self.buildContentState(from: session)
- let payload: [String: Any] = [
- "pushToken": tokenHex,
- "event": "update",
- "contentState": contentState
- ]
- await post(payload: payload, label: "update \(session.sessionId)")
- }
-
- func sendOverallUpdate(sessions: [SessionState], primarySessionId: String?) async {
- guard let tokenHex = pushTokens["__overall__"] else { return }
-
- let summaries: [[String: Any]] = sessions.prefix(4).map { session in
- let liveDuration = max(session.durationSec, Int(Date().timeIntervalSince(session.startedAt)))
- var s: [String: Any] = [
- "sessionId": session.sessionId,
- "projectName": session.projectName,
- "status": session.status.rawValue,
- "model": session.model,
- "costUSD": session.costUSD,
- "durationSec": liveDuration,
- "completedCount": session.completedTaskCount,
- "totalCount": session.totalTaskCount
- ]
- if let task = session.currentTask { s["currentTask"] = task }
- return s
- }
-
- let contentState: [String: Any] = [
- "sessions": summaries,
- "primarySessionId": primarySessionId as Any,
- "totalCost": sessions.reduce(0) { $0 + $1.costUSD },
- "isDark": true
- ]
-
- let payload: [String: Any] = [
- "pushToken": tokenHex,
- "event": "update",
- "contentState": contentState
- ]
- logger.info("Sending overall update (\(sessions.count) sessions)")
- await post(payload: payload, label: "overall-update")
- }
-
- func sendEnd(sessionId: String) async {
- guard let tokenHex = pushTokens[sessionId] else { return }
-
- let payload: [String: Any] = [
- "pushToken": tokenHex,
- "event": "end"
- ]
- await post(payload: payload, label: "end \(sessionId)")
- pushTokens.removeValue(forKey: sessionId)
- }
-
- // MARK: - Alert Push (Pro: session completion)
-
- func sendCompletionAlert(session: SessionState) async {
- // Fetch device push token from CloudKit
- let recordID = CKRecord.ID(
- recordName: "device-push-token",
- zoneID: CloudKitManager.zoneID
- )
- guard let record = try? await CloudKitManager.shared.database.record(for: recordID),
- let tokenHex = record["token"] as? String else {
- return
- }
-
- let payload: [String: Any] = [
- "pushToken": tokenHex,
- "type": "alert",
- "title": session.projectName,
- "body": "Session complete"
- ]
- // Retry up to 3 times with backoff (429 from APNs rate limit)
- for attempt in 0..<3 {
- if attempt > 0 {
- try? await Task.sleep(for: .seconds(Double(attempt) * 2))
- }
- let success = await postWithResult(payload: payload, label: "alert \(session.projectName)")
- if success { break }
- }
- }
-
- // MARK: - Push Token Sync (from CloudKit)
-
- func fetchPushTokens(sessionIds: [String] = []) async {
- guard !isFetchingTokens else { return }
- guard Date().timeIntervalSince(lastTokenFetch) > 10 else { return }
- isFetchingTokens = true
- lastTokenFetch = Date()
- defer { isFetchingTokens = false }
-
- // Fetch known push token records by ID (query requires indexing; direct fetch doesn't)
- var allIds = sessionIds
- if !allIds.contains("__overall__") { allIds.append("__overall__") }
-
- let recordIDs = allIds.map {
- CKRecord.ID(recordName: "pushtoken-\($0)", zoneID: CloudKitManager.zoneID)
- }
-
- do {
- let recordResults = try await CloudKitManager.shared.database.records(for: recordIDs)
- var tokens: [String: String] = [:]
- for (_, result) in recordResults {
- guard case .success(let record) = result,
- let sessionId = record["sessionId"] as? String,
- let tokenHex = record["token"] as? String else { continue }
- tokens[sessionId] = tokenHex
- }
- if tokens != pushTokens {
- pushTokens = tokens
- logger.info("Fetched \(tokens.count) push tokens from CloudKit")
- }
- } catch {
- logger.warning("Failed to fetch push tokens: \(error)")
- }
- }
-
- // MARK: - HTTP
-
- private func postWithResult(payload: [String: Any], label: String) async -> Bool {
- guard let body = try? JSONSerialization.data(withJSONObject: payload) else { return false }
- var request = URLRequest(url: workerURL)
- request.httpMethod = "POST"
- request.setValue("application/json", forHTTPHeaderField: "Content-Type")
- request.setValue("Bearer \(apiSecret)", forHTTPHeaderField: "Authorization")
- request.httpBody = body
- do {
- let (data, response) = try await URLSession.shared.data(for: request)
- if let http = response as? HTTPURLResponse {
- #if DEBUG
- if http.statusCode == 200 {
- Self.log("APNs → \(label) ✓")
- } else {
- let reason = String(data: data, encoding: .utf8) ?? ""
- Self.log("APNs → \(label) ✗ \(http.statusCode): \(reason)")
- }
- #endif
- _ = data
- return http.statusCode == 200
- }
- } catch {
- #if DEBUG
- Self.log("APNs → \(label) ✗ \(error.localizedDescription)")
- #endif
- }
- return false
- }
-
- private func post(payload: [String: Any], label: String) async {
- guard let body = try? JSONSerialization.data(withJSONObject: payload) else {
- Self.log("APNs FAIL serialize \(label)")
- return
- }
-
- var request = URLRequest(url: workerURL)
- request.httpMethod = "POST"
- request.setValue("application/json", forHTTPHeaderField: "Content-Type")
- request.setValue("Bearer \(apiSecret)", forHTTPHeaderField: "Authorization")
- request.httpBody = body
-
- do {
- let (data, response) = try await URLSession.shared.data(for: request)
- if let http = response as? HTTPURLResponse {
- #if DEBUG
- if http.statusCode == 200 {
- Self.log("APNs → \(label) ✓")
- } else {
- let reason = String(data: data, encoding: .utf8) ?? ""
- Self.log("APNs → \(label) ✗ \(http.statusCode): \(reason)")
- }
- #endif
- _ = data // suppress unused warning in release
- }
- } catch {
- #if DEBUG
- Self.log("APNs → \(label) ✗ \(error.localizedDescription)")
- #endif
- }
- }
-
- private static func log(_ msg: String) {
- let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".codync/sync.log")
- let fmt = DateFormatter()
- fmt.dateFormat = "HH:mm:ss"
- let line = "[\(fmt.string(from: Date()))] \(msg)\n"
- if let h = try? FileHandle(forWritingTo: url) { h.seekToEndOfFile(); h.write(line.data(using: .utf8)!); try? h.close() }
- else { try? line.write(to: url, atomically: false, encoding: .utf8) }
- }
-
- // MARK: - Content State
-
- private static func buildContentState(from session: SessionState) -> [String: Any] {
- let liveDuration = max(session.durationSec, Int(Date().timeIntervalSince(session.startedAt)))
- var state: [String: Any] = [
- "status": session.status.rawValue,
- "model": session.model,
- "completedCount": session.completedTaskCount,
- "totalCount": session.totalTaskCount,
- "contextPct": session.contextPct,
- "costUSD": session.costUSD,
- "durationSec": liveDuration,
- "sessionStartDate": session.startedAt.timeIntervalSinceReferenceDate
- ]
- if let task = session.currentTask, !task.isEmpty {
- state["currentTask"] = task
- }
- if let tasksData = try? JSONEncoder().encode(session.truncatedTasks),
- let tasksArray = try? JSONSerialization.jsonObject(with: tasksData) {
- state["tasks"] = tasksArray
- } else {
- state["tasks"] = [] as [Any]
- }
- return state
- }
-}
diff --git a/Codync-macOS/Services/APNsSecrets.example.swift b/Codync-macOS/Services/APNsSecrets.example.swift
deleted file mode 100644
index 06502e34..00000000
--- a/Codync-macOS/Services/APNsSecrets.example.swift
+++ /dev/null
@@ -1,6 +0,0 @@
-// Copy this file to APNsSecrets.swift and fill in your values.
-// APNsSecrets.swift is git-ignored and will not be committed.
-enum APNsSecrets {
- static let workerURL = "YOUR_WORKER_URL"
- static let apiSecret = "YOUR_API_SECRET"
-}
diff --git a/Codync-macOS/Services/ClaudeHookServer.swift b/Codync-macOS/Services/ClaudeHookServer.swift
deleted file mode 100644
index e5af6889..00000000
--- a/Codync-macOS/Services/ClaudeHookServer.swift
+++ /dev/null
@@ -1,377 +0,0 @@
-import Foundation
-import Network
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync", category: "HookServer")
-
-/// Thread-safe mutable data buffer for NWConnection receive loop.
-private final class AccumulatedData: @unchecked Sendable {
- private var _data = Data()
- private let lock = NSLock()
-
- var data: Data { lock.withLock { _data } }
- var count: Int { lock.withLock { _data.count } }
-
- func append(_ newData: Data) {
- lock.withLock { _data.append(newData) }
- }
-}
-
-/// Hook-driven status detection server.
-/// Receives events from 7 Claude Code hooks via notify.sh command script.
-/// Hook events are the primary status source — JSONL parsing is supplementary.
-final class ClaudeHookServer: @unchecked Sendable {
- private var listener: NWListener?
- private let port: UInt16
- private let queue = DispatchQueue(label: "com.pokai.Codync.hooks", qos: .utility)
- private let lock = NSLock()
-
- private var _permissionSessions: Set<String> = []
- private var _stopSessions: Set<String> = []
- private var _toolRunningSessions: Set<String> = []
-
- /// All sessionIds seen from hook events, grouped by cwd.
- private var _cwdToSessionIds: [String: Set<String>] = [:]
-
- /// Maps TTY → sessionId. TTY uniquely identifies a terminal,
- /// so this correctly resolves multiple sessions in the same cwd.
- private var _ttyToSessionId: [String: String] = [:]
-
- // MARK: - Thread-safe accessors
-
- func needsPermission(_ sessionId: String) -> Bool {
- withLock { _permissionSessions.contains(sessionId) }
- }
-
- func isStopped(_ sessionId: String) -> Bool {
- withLock { _stopSessions.contains(sessionId) }
- }
-
- func isToolRunning(_ sessionId: String) -> Bool {
- withLock { _toolRunningSessions.contains(sessionId) }
- }
-
- func clearPermission(_ sessionId: String) {
- withLock { _permissionSessions.remove(sessionId) }
- }
-
- func clearStop(_ sessionId: String) {
- withLock { _stopSessions.remove(sessionId) }
- }
-
- func clearToolRunning(_ sessionId: String) {
- withLock { _toolRunningSessions.remove(sessionId) }
- }
-
- /// Remove all state for sessions no longer alive.
- func pruneStale(activeSessionIds: Set<String>) {
- withLock {
- _permissionSessions.formIntersection(activeSessionIds)
- _stopSessions.formIntersection(activeSessionIds)
- _toolRunningSessions.formIntersection(activeSessionIds)
- // Prune cwd and tty mappings
- for (cwd, ids) in _cwdToSessionIds {
- let pruned = ids.intersection(activeSessionIds)
- _cwdToSessionIds[cwd] = pruned.isEmpty ? nil : pruned
- }
- _ttyToSessionId = _ttyToSessionId.filter { activeSessionIds.contains($0.value) }
- }
- }
-
- /// Get all sessionIds seen from hooks for a cwd.
- func activeSessionIds(forCwd cwd: String) -> Set<String> {
- withLock { _cwdToSessionIds[cwd] ?? [] }
- }
-
- /// Get the sessionId for a specific TTY device.
- func sessionId(forTty tty: String) -> String? {
- withLock { _ttyToSessionId[tty] }
- }
-
- // MARK: - Callbacks
-
- var onHookSignal: (@Sendable (_ sessionId: String, _ signal: HookSignalType, _ toolName: String?) -> Void)?
- var onSessionEvent: (@Sendable () -> Void)?
-
- init(port: UInt16 = 19221) {
- self.port = port
- }
-
- // MARK: - Lock helper
-
- @discardableResult
- private func withLock<T>(_ body: () -> T) -> T {
- lock.lock()
- defer { lock.unlock() }
- return body()
- }
-
- /// Update all three state sets atomically for a session.
- private func setSessionState(
- _ sessionId: String,
- permission: Bool? = nil,
- stopped: Bool? = nil,
- toolRunning: Bool? = nil
- ) {
- withLock {
- if let p = permission { if p { _permissionSessions.insert(sessionId) } else { _permissionSessions.remove(sessionId) } }
- if let s = stopped { if s { _stopSessions.insert(sessionId) } else { _stopSessions.remove(sessionId) } }
- if let t = toolRunning { if t { _toolRunningSessions.insert(sessionId) } else { _toolRunningSessions.remove(sessionId) } }
- }
- }
-
- // MARK: - Hook Configuration
-
- func ensureHooksConfigured() {
- installNotifyScript()
- updateSettingsJson()
- }
-
- private func installNotifyScript() {
- let scriptDir = FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent(".codync")
- let scriptPath = scriptDir.appendingPathComponent("notify.sh")
-
- try? FileManager.default.createDirectory(at: scriptDir, withIntermediateDirectories: true)
-
- // Detect TTY from parent process chain (like cc-status-bar's TtyDetector).
- // This uniquely identifies which terminal the hook fired from,
- // allowing us to distinguish multiple sessions in the same cwd.
- let script = """
- #!/bin/bash
- INPUT=$(cat)
-
- # Detect TTY from ancestor processes
- TTY=""
- PID=$$
- for i in 1 2 3 4 5; do
- T=$(ps -o tty= -p $PID 2>/dev/null | tr -d ' ')
- if [ -n "$T" ] && [ "$T" != "??" ]; then
- TTY="/dev/$T"
- break
- fi
- PID=$(ps -o ppid= -p $PID 2>/dev/null | tr -d ' ')
- [ -z "$PID" ] || [ "$PID" = "0" ] && break
- done
-
- # Inject tty into the JSON payload (use | as sed delimiter to avoid /dev/ conflicts)
- if [ -n "$TTY" ]; then
- INPUT=$(echo "$INPUT" | sed 's|}$|,"tty":"'"$TTY"'"}|')
- fi
-
- curl -s --max-time 1 -X POST "http://127.0.0.1:\(port)/codync-event" \
- -H "Content-Type: application/json" \
- -d "$INPUT" 2>/dev/null &
- exit 0
- """
-
- try? script.write(to: scriptPath, atomically: true, encoding: .utf8)
- var attrs = [FileAttributeKey: Any]()
- attrs[.posixPermissions] = 0o755
- try? FileManager.default.setAttributes(attrs, ofItemAtPath: scriptPath.path)
- }
-
- private func updateSettingsJson() {
- let home = FileManager.default.homeDirectoryForCurrentUser
- let settingsURL = home.appendingPathComponent(".claude/settings.json")
- let oldHttpURL = "http://localhost:\(port)/codync-event"
- let scriptPath = home.appendingPathComponent(".codync/notify.sh").path
-
- guard FileManager.default.fileExists(atPath: settingsURL.path),
- let data = try? Data(contentsOf: settingsURL),
- var root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }
-
- var hooks = root["hooks"] as? [String: Any] ?? [:]
- var changed = false
-
- // Remove old Codync hooks
- for event in hooks.keys {
- guard var entries = hooks[event] as? [[String: Any]] else { continue }
- let before = entries.count
- entries.removeAll { entry in
- guard let entryHooks = entry["hooks"] as? [[String: Any]] else { return false }
- return entryHooks.contains { hook in
- (hook["url"] as? String) == oldHttpURL
- || (hook["command"] as? String)?.contains("codync") == true
- }
- }
- if entries.count != before {
- hooks[event] = entries.isEmpty ? nil : entries
- changed = true
- }
- }
-
- // Register all 7 hooks
- let commandHook: [String: Any] = ["type": "command", "command": scriptPath]
- let hookEntry: [String: Any] = ["hooks": [commandHook]]
- let hookEvents = ["Notification", "Stop", "UserPromptSubmit", "PreToolUse", "PostToolUse", "SessionStart", "SessionEnd"]
-
- for event in hookEvents {
- var entries = hooks[event] as? [[String: Any]] ?? []
- let alreadyPresent = entries.contains { entry in
- guard let entryHooks = entry["hooks"] as? [[String: Any]] else { return false }
- return entryHooks.contains { ($0["command"] as? String) == scriptPath }
- }
- if !alreadyPresent {
- entries.append(hookEntry)
- hooks[event] = entries
- changed = true
- }
- }
-
- if changed {
- root["hooks"] = hooks
- if let data = try? JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys]) {
- try? data.write(to: settingsURL, options: .atomic)
- logger.info("Updated hooks in settings.json (7 hook events)")
- }
- }
- }
-
- // MARK: - Server
-
- func start() {
- do {
- let params = NWParameters.tcp
- params.allowLocalEndpointReuse = true
- params.requiredLocalEndpoint = NWEndpoint.hostPort(
- host: .init("127.0.0.1"),
- port: NWEndpoint.Port(rawValue: port)!
- )
- listener = try NWListener(using: params)
- } catch {
- logger.error("Failed to create listener: \(error.localizedDescription)")
- return
- }
-
- listener?.stateUpdateHandler = { state in
- if case .ready = state {
- logger.info("Hook server listening on port \(self.port)")
- }
- }
- listener?.newConnectionHandler = { [weak self] conn in self?.handleConnection(conn) }
- listener?.start(queue: queue)
- }
-
- func stop() {
- listener?.cancel()
- listener = nil
- }
-
- // MARK: - Connection
-
- private func handleConnection(_ connection: NWConnection) {
- connection.start(queue: queue)
- let accumulated = AccumulatedData()
-
- @Sendable func receiveMore() {
- connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, isComplete, error in
- if let data { accumulated.append(data) }
- if accumulated.count > 512_000 { connection.cancel(); return }
-
- let done = isComplete || error != nil
- let snapshot = accumulated.data
- let hasFullRequest = String(data: snapshot, encoding: .utf8)?.contains("\r\n\r\n") ?? false
-
- if done || hasFullRequest {
- self?.processRequest(snapshot)
- let response = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}"
- connection.send(content: response.data(using: .utf8), completion: .contentProcessed { _ in
- connection.cancel()
- })
- } else {
- receiveMore()
- }
- }
- }
- receiveMore()
- }
-
- // MARK: - Event Processing
-
- private func processRequest(_ data: Data) {
- guard let text = String(data: data, encoding: .utf8),
- let bodyStart = text.range(of: "\r\n\r\n") else { return }
-
- let body = String(text[bodyStart.upperBound...])
- guard let bodyData = body.data(using: .utf8),
- let json = try? JSONSerialization.jsonObject(with: bodyData) as? [String: Any] else { return }
-
- let eventName = json["hook_event_name"] as? String ?? ""
- let sessionId = json["session_id"] as? String
- let toolName = json["tool_name"] as? String
- let cwd = json["cwd"] as? String
-
- let tty = json["tty"] as? String
-
- // Track sessionId by cwd and by TTY
- if let sessionId, let cwd {
- withLock {
- _cwdToSessionIds[cwd, default: []].insert(sessionId)
- if let tty { _ttyToSessionId[tty] = sessionId }
- }
- }
-
- switch eventName {
- case "Notification":
- guard let sessionId else { return }
- let notificationType = json["notification_type"] as? String
- ?? (json["message"] as? [String: Any])?["notification_type"] as? String
-
- if toolName == "AskUserQuestion" {
- setSessionState(sessionId, permission: true, stopped: false, toolRunning: false)
- emit(sessionId, .askUserQuestion, toolName)
- } else if notificationType == "permission_prompt" {
- setSessionState(sessionId, permission: true, stopped: false, toolRunning: false)
- emit(sessionId, .permissionRequest, toolName)
- } else if notificationType == "elicitation_dialog" {
- setSessionState(sessionId, permission: true, stopped: false)
- emit(sessionId, .elicitationDialog, nil)
- }
-
- case "Stop":
- guard let sessionId else { return }
- setSessionState(sessionId, permission: false, stopped: true, toolRunning: false)
- emit(sessionId, .stop, nil)
-
- case "UserPromptSubmit":
- guard let sessionId else { return }
- setSessionState(sessionId, permission: false, stopped: false, toolRunning: false)
- emit(sessionId, .userPromptSubmit, nil)
-
- case "PreToolUse":
- guard let sessionId else { return }
- setSessionState(sessionId, stopped: false, toolRunning: true)
- emit(sessionId, .preToolUse, toolName)
-
- case "PostToolUse":
- guard let sessionId else { return }
- setSessionState(sessionId, toolRunning: false)
- emit(sessionId, .postToolUse, toolName)
-
- case "SessionStart":
- logger.info("SessionStart\(sessionId.map { " \($0.prefix(8))..." } ?? "")")
- Task { @MainActor [weak self] in self?.onSessionEvent?() }
-
- case "SessionEnd":
- guard let sessionId else {
- Task { @MainActor [weak self] in self?.onSessionEvent?() }
- return
- }
- setSessionState(sessionId, permission: false, stopped: false, toolRunning: false)
- logger.info("SessionEnd \(sessionId.prefix(8))...")
- Task { @MainActor [weak self] in self?.onSessionEvent?() }
-
- default:
- break
- }
- }
-
- private func emit(_ sessionId: String, _ signal: HookSignalType, _ toolName: String?) {
- Task { @MainActor [weak self] in
- self?.onHookSignal?(sessionId, signal, toolName)
- self?.onSessionEvent?()
- }
- }
-}
diff --git a/Codync-macOS/Services/CloudKitSync.swift b/Codync-macOS/Services/CloudKitSync.swift
deleted file mode 100644
index 3eb70131..00000000
--- a/Codync-macOS/Services/CloudKitSync.swift
+++ /dev/null
@@ -1,164 +0,0 @@
-import Foundation
-import Combine
-import CloudKit
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync", category: "CloudKitSync")
-
-@MainActor
-final class CloudKitSync {
- private let stateManager: SessionStateManager
- private var cancellables = Set<AnyCancellable>()
- private var previousStates: [String: SessionState] = [:]
- private var previousSessionIds: Set<String> = []
- private var isSyncing = false
- private var quotaBackoffUntil: Date?
-
- private static func log(_ msg: String) {
- let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".codync/sync.log")
- let fmt = DateFormatter()
- fmt.dateFormat = "HH:mm:ss"
- let line = "[\(fmt.string(from: Date()))] \(msg)\n"
- if let h = try? FileHandle(forWritingTo: url) { h.seekToEndOfFile(); h.write(line.data(using: .utf8)!); try? h.close() }
- else { try? line.write(to: url, atomically: false, encoding: .utf8) }
- }
-
- init(stateManager: SessionStateManager) {
- self.stateManager = stateManager
-
- // Ensure custom zone exists before any saves
- Task {
- do {
- try await CloudKitManager.shared.ensureZoneExists()
- logger.info("Custom zone ready")
- } catch {
- logger.warning("Zone creation failed: \(error) — will retry on next save")
- }
- }
-
- stateManager.$sessions
- .throttle(for: .milliseconds(500), scheduler: RunLoop.main, latest: true)
- .sink { [weak self] sessions in
- self?.syncToCloud(sessions)
- }
- .store(in: &cancellables)
- }
-
- private func syncToCloud(_ sessions: [SessionState]) {
- guard !isSyncing else { return }
-
- if let backoff = quotaBackoffUntil, Date() < backoff { return }
- quotaBackoffUntil = nil
-
- let currentIds = Set(sessions.map(\.sessionId))
-
- // DELETE only when session disappears from the list entirely.
- // This means the PID is dead and SessionScanner dropped it.
- // Status changes (working → idle → needsInput → completed) are always SAVED, never deleted.
- let disappearedIds = previousSessionIds.subtracting(currentIds)
- let toDelete = Array(disappearedIds)
-
- // SAVE any session whose state changed (exclude durationSec/updatedAt — they change every second)
- let toSave = sessions.filter { session in
- guard let prev = previousStates[session.sessionId] else { return true }
- return prev.status != session.status
- || prev.currentTask != session.currentTask
- || prev.waitingReason != session.waitingReason
- || prev.tasks != session.tasks
- || prev.model != session.model
- || prev.summary != session.summary
- || prev.costUSD != session.costUSD
- || prev.contextPct != session.contextPct
- || prev.lastEvent != session.lastEvent
- }
-
- guard !toDelete.isEmpty || !toSave.isEmpty else {
- previousSessionIds = currentIds
- return
- }
-
- isSyncing = true
-
- Task {
- defer {
- isSyncing = false
- previousSessionIds = currentIds
- }
-
- do {
- // Send end push BEFORE deleting (tokens still needed)
- for id in toDelete {
- await APNsPushService.shared.sendEnd(sessionId: id)
- }
-
- if !toDelete.isEmpty {
- Self.log("delete \(toDelete.count) sessions")
- try await CloudKitManager.shared.deleteByIds(toDelete)
- Self.log("deleted OK")
- for id in toDelete {
- previousStates.removeValue(forKey: id)
- }
- }
-
- if !toSave.isEmpty {
- // Fetch primary session once — reused for alert + overall push
- let primary = await CloudKitManager.shared.fetchPrimarySession()
-
- // Send completion alert for the locked primary session
- // Check ALL sessions (not just toSave) so throttle can't swallow the transition
- if let lockedPrimaryId = primary.sessionId, primary.locked,
- let session = sessions.first(where: { $0.sessionId == lockedPrimaryId }),
- (session.status == .idle || session.status == .needsInput),
- previousStates[session.sessionId]?.status == .working {
- #if DEBUG
- Self.log("ALERT SENDING for \(session.projectName) (\(session.status.rawValue))")
- #endif
- await APNsPushService.shared.sendCompletionAlert(session: session)
- }
-
- let desc = toSave.map { "\($0.projectName):\($0.status.rawValue)" }.joined(separator: ", ")
- Self.log("save \(toSave.count): \(desc)")
- try await CloudKitManager.shared.saveBatch(toSave)
- Self.log("saved OK")
- for session in toSave {
- previousStates[session.sessionId] = session
- }
- // Always track primary session state for alert detection,
- // even if it wasn't in toSave (throttle may merge its changes)
- if let lockedPrimaryId = primary.sessionId, primary.locked,
- let session = sessions.first(where: { $0.sessionId == lockedPrimaryId }) {
- previousStates[session.sessionId] = session
- }
-
- // Push to APNs via Worker relay for Live Activity background updates
- await APNsPushService.shared.fetchPushTokens(sessionIds: sessions.map(\.sessionId))
- #if DEBUG
- Self.log("APNs tokens: \(APNsPushService.shared.tokenCount)")
- #endif
- // Individual mode: per-session push
- for session in toSave {
- await APNsPushService.shared.sendUpdate(session: session)
- }
- // Overall mode: send all active sessions with user's primary selection
- let allActive = sessions.filter { $0.status != .completed }
- let primaryId = primary.sessionId
- ?? allActive.first(where: { $0.status == .working })?.sessionId
- // Sync primary to macOS panel sorting
- stateManager.primarySessionId = primaryId
- await APNsPushService.shared.sendOverallUpdate(
- sessions: allActive,
- primarySessionId: primaryId
- )
- }
- } catch let error as CKError where error.code == .quotaExceeded || error.code == .requestRateLimited {
- let retryAfter = error.retryAfterSeconds ?? 600
- Self.log("QUOTA: backoff \(Int(retryAfter * 2))s")
- quotaBackoffUntil = Date().addingTimeInterval(retryAfter * 2)
- } catch {
- Self.log("ERROR: \(error)")
- quotaBackoffUntil = Date().addingTimeInterval(300)
- }
- }
- }
-}
diff --git a/Codync-macOS/Services/SessionFileParser.swift b/Codync-macOS/Services/SessionFileParser.swift
deleted file mode 100644
index c600ac66..00000000
--- a/Codync-macOS/Services/SessionFileParser.swift
+++ /dev/null
@@ -1,123 +0,0 @@
-import Foundation
-import CodyncShared
-
-struct RawSessionFile: Codable, Equatable {
- let pid: Int
- let sessionId: String
- let cwd: String
- let startedAt: Int64
-}
-
-struct SessionIndexEntry: Codable {
- let sessionId: String
- let firstPrompt: String?
- let summary: String?
- let messageCount: Int?
- let gitBranch: String?
- let projectPath: String?
-}
-
-struct SessionIndex: Codable {
- let version: Int
- let entries: [SessionIndexEntry]
-}
-
-struct RawTask: Codable {
- let content: String?
- let subject: String?
- let status: String
- let activeForm: String?
- let id: String?
- let description: String?
-}
-
-enum SessionFileParser {
- static func parseSessionFiles() -> [RawSessionFile] {
- let dir = ClaudePaths.sessionsDir
- guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
- .filter({ $0.pathExtension == "json" }) else { return [] }
-
- return files.compactMap { url in
- guard let data = try? Data(contentsOf: url),
- let session = try? JSONDecoder().decode(RawSessionFile.self, from: data) else { return nil }
- return session
- }
- }
-
- static func parseTasks(sessionId: String) -> [TaskItem] {
- // Try new format first: ~/.claude/tasks/{sessionId}/{id}.json
- let tasksDirTasks = parseTasksDir(sessionId: sessionId)
- if !tasksDirTasks.isEmpty { return tasksDirTasks }
-
- // Fallback: old format ~/.claude/todos/{sessionId}-agent-*.json
- return parseTodos(sessionId: sessionId)
- }
-
- /// Parse tasks from ~/.claude/tasks/{sessionId}/ — each task is a separate JSON file
- private static func parseTasksDir(sessionId: String) -> [TaskItem] {
- let dir = ClaudePaths.tasksDir.appendingPathComponent(sessionId)
- guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
- .filter({ $0.pathExtension == "json" }) else { return [] }
-
- let decoder = JSONDecoder()
- return files.compactMap { url in
- guard let data = try? Data(contentsOf: url),
- let raw = try? decoder.decode(RawTask.self, from: data) else { return nil }
- let status: TaskStatus = switch raw.status {
- case "completed": .completed
- case "in_progress": .inProgress
- default: .pending
- }
- return TaskItem(
- id: raw.id ?? url.deletingPathExtension().lastPathComponent,
- content: raw.subject ?? raw.content ?? raw.description ?? "Task",
- status: status,
- activeForm: raw.activeForm
- )
- }.sorted { ($0.id) < ($1.id) }
- }
-
- static func parseTodos(sessionId: String) -> [TaskItem] {
- let dir = ClaudePaths.todosDir
- guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) else { return [] }
-
- let matching = files.filter { $0.lastPathComponent.hasPrefix(ClaudePaths.todosPattern(sessionId: sessionId)) }
-
- for file in matching {
- guard let data = try? Data(contentsOf: file),
- let rawTasks = try? JSONDecoder().decode([RawTask].self, from: data),
- !rawTasks.isEmpty else { continue }
-
- return rawTasks.enumerated().map { index, raw in
- let status: TaskStatus = switch raw.status {
- case "completed": .completed
- case "in_progress": .inProgress
- default: .pending
- }
- return TaskItem(
- id: raw.id ?? "\(index + 1)",
- content: raw.subject ?? raw.content ?? "Task \(index + 1)",
- status: status,
- activeForm: raw.activeForm
- )
- }
- }
- return []
- }
-
- static func parseSessionIndex(cwd: String, sessionId: String) -> SessionIndexEntry? {
- let path = ClaudePaths.sessionIndexPath(cwd: cwd)
- guard let data = try? Data(contentsOf: path),
- let index = try? JSONDecoder().decode(SessionIndex.self, from: data) else { return nil }
- return index.entries.first { $0.sessionId == sessionId }
- }
-
- /// Fall back to the latest entry in sessions-index.json for a project.
- /// Used when the active sessionId (resolved from JSONL) differs from what's in the index.
- static func parseLatestSessionIndex(cwd: String) -> SessionIndexEntry? {
- let path = ClaudePaths.sessionIndexPath(cwd: cwd)
- guard let data = try? Data(contentsOf: path),
- let index = try? JSONDecoder().decode(SessionIndex.self, from: data) else { return nil }
- return index.entries.last
- }
-}
diff --git a/Codync-macOS/Services/SessionScanner.swift b/Codync-macOS/Services/SessionScanner.swift
deleted file mode 100644
index e744decc..00000000
--- a/Codync-macOS/Services/SessionScanner.swift
+++ /dev/null
@@ -1,174 +0,0 @@
-import Foundation
-import Combine
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync", category: "SessionScanner")
-
-@MainActor
-final class SessionScanner: ObservableObject {
- @Published var activeSessions: [String: RawSessionFile] = [:]
-
- var hookServer: ClaudeHookServer?
-
- private var sessionsWatcher: DispatchSourceFileSystemObject?
- private var scanTimer: Timer?
- private let debounceInterval: TimeInterval = 1.0
- private var debounceTask: Task<Void, Never>?
-
- func start() {
- scan()
- watchDirectory(ClaudePaths.sessionsDir) { [weak self] in
- self?.scheduleScan()
- }
- scanTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
- Task { @MainActor in
- self?.scan()
- }
- }
- logger.info("SessionScanner started")
- }
-
- func stop() {
- sessionsWatcher?.cancel()
- sessionsWatcher = nil
- scanTimer?.invalidate()
- scanTimer = nil
- debounceTask?.cancel()
- }
-
- private func scheduleScan() {
- debounceTask?.cancel()
- debounceTask = Task { @MainActor in
- try? await Task.sleep(for: .seconds(debounceInterval))
- guard !Task.isCancelled else { return }
- scan()
- }
- }
-
- func scheduleScanFromHook() {
- scheduleScan()
- }
-
- func scan() {
- let files = SessionFileParser.parseSessionFiles()
- var newSessions: [String: RawSessionFile] = [:]
-
- var alivePids = Set<Int>()
- for file in files {
- guard PIDChecker.isAlive(pid: file.pid) else { continue }
- alivePids.insert(file.pid)
- let resolved = resolveSessionId(file)
- // Dict keyed by sessionId — if two PIDs resolve to the same JSONL,
- // the later one wins (acceptable: they share the same transcript)
- newSessions[resolved.sessionId] = resolved
- }
-
- // Clean up TTY cache for dead PIDs
- ttyCache = ttyCache.filter { alivePids.contains($0.key) }
-
- if newSessions != activeSessions {
- if newSessions.count != activeSessions.count {
- logger.info("Active sessions: \(newSessions.count)")
- }
- activeSessions = newSessions
- }
- }
-
- // MARK: - Session ID Resolution
-
- private func resolveSessionId(_ file: RawSessionFile) -> RawSessionFile {
- // 1. TTY-based resolution (most precise — each terminal has a unique TTY)
- if let tty = detectAndCacheTty(pid: file.pid),
- let hookSessionId = hookServer?.sessionId(forTty: tty) {
- return RawSessionFile(pid: file.pid, sessionId: hookSessionId, cwd: file.cwd, startedAt: file.startedAt)
- }
-
- // 2. Original JSONL exists — but verify it's the most recent one.
- // Claude Code can keep stale PID files pointing to old sessionIds
- // while actively writing to a newer JSONL.
- let originalJsonl = ClaudePaths.jsonlPath(cwd: file.cwd, sessionId: file.sessionId)
- if FileManager.default.fileExists(atPath: originalJsonl.path) {
- let resolved = resolveFromJsonlDirectory(file)
- if resolved.sessionId != file.sessionId {
- // A more recently modified JSONL exists — use it instead
- return resolved
- }
- return file
- }
-
- // 3. Hook server cwd-based (when only 1 session per cwd, unambiguous)
- let hookIds = hookServer?.activeSessionIds(forCwd: file.cwd) ?? []
- if hookIds.count == 1, let hookId = hookIds.first {
- let hookJsonl = ClaudePaths.jsonlPath(cwd: file.cwd, sessionId: hookId)
- if FileManager.default.fileExists(atPath: hookJsonl.path) {
- return RawSessionFile(pid: file.pid, sessionId: hookId, cwd: file.cwd, startedAt: file.startedAt)
- }
- }
-
- // 4. Last resort: most recently modified JSONL in the project directory
- return resolveFromJsonlDirectory(file)
- }
-
- // MARK: - TTY Cache (caches both hits and misses to avoid repeated subprocess spawns)
-
- private var ttyCache: [Int: String?] = [:]
-
- private func detectAndCacheTty(pid: Int) -> String? {
- if let cached = ttyCache[pid] { return cached }
- let tty = PIDChecker.tty(for: pid)
- ttyCache[pid] = tty // cache nil too — avoids retrying every 5s
- return tty
- }
-
- private func resolveFromJsonlDirectory(_ file: RawSessionFile) -> RawSessionFile {
- let projectDir = ClaudePaths.projectsDir
- .appendingPathComponent(ClaudePaths.mangledCwd(file.cwd))
-
- guard let contents = try? FileManager.default.contentsOfDirectory(
- at: projectDir, includingPropertiesForKeys: [.contentModificationDateKey]
- ) else {
- return file
- }
-
- let jsonlFiles = contents.filter { url in
- url.pathExtension == "jsonl"
- && !url.lastPathComponent.hasPrefix("agent-")
- }
-
- var bestURL: URL?
- var bestDate: Date = .distantPast
- for url in jsonlFiles {
- guard let values = try? url.resourceValues(forKeys: [.contentModificationDateKey]),
- let modDate = values.contentModificationDate else { continue }
- if modDate > bestDate {
- bestDate = modDate
- bestURL = url
- }
- }
-
- guard let activeURL = bestURL else { return file }
- let activeSessionId = activeURL.deletingPathExtension().lastPathComponent
-
- if activeSessionId != file.sessionId {
- return RawSessionFile(pid: file.pid, sessionId: activeSessionId, cwd: file.cwd, startedAt: file.startedAt)
- }
-
- return file
- }
-
- // MARK: - Directory Watching
-
- private func watchDirectory(_ url: URL, handler: @escaping () -> Void) {
- let fd = open(url.path, O_EVTONLY)
- guard fd >= 0 else { return }
- let source = DispatchSource.makeFileSystemObjectSource(
- fileDescriptor: fd,
- eventMask: [.write, .rename, .delete],
- queue: .main
- )
- source.setEventHandler(handler: handler)
- source.setCancelHandler { close(fd) }
- source.resume()
- sessionsWatcher = source
- }
-}
diff --git a/Codync-macOS/Services/SessionStateManager.swift b/Codync-macOS/Services/SessionStateManager.swift
deleted file mode 100644
index f9b3fd6f..00000000
--- a/Codync-macOS/Services/SessionStateManager.swift
+++ /dev/null
@@ -1,251 +0,0 @@
-import Foundation
-import Combine
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync", category: "StateManager")
-
-@MainActor
-final class SessionStateManager: ObservableObject {
- @Published var sessions: [SessionState] = []
- @Published var primarySessionId: String?
-
- private let scanner: SessionScanner
- let transcriptWatcher = TranscriptWatcher()
- var hookServer: ClaudeHookServer?
-
- private var cancellables = Set<AnyCancellable>()
- private let deviceId = Host.current().localizedName ?? UUID().uuidString
-
- init(scanner: SessionScanner) {
- self.scanner = scanner
- scanner.$activeSessions
- .debounce(for: .seconds(0.5), scheduler: RunLoop.main)
- .sink { [weak self] rawSessions in
- self?.updateSessions(from: rawSessions)
- }
- .store(in: &cancellables)
- }
-
- /// Force a status re-evaluation.
- /// Called when hook state changes (Stop, Permission, etc.).
- /// Re-scans first so sessionIds are resolved with latest hook data,
- /// then runs updateSessions even if the session list looks the same.
- func refreshFromHookState() {
- scanner.scan()
- updateSessions(from: scanner.activeSessions)
- }
-
- private func updateSessions(from rawSessions: [String: RawSessionFile]) {
- var updated: [SessionState] = []
-
- for (sessionId, raw) in rawSessions {
- // Parse JSONL incrementally — supplementary data (model, tokens, cost, lastEvent)
- let jsonlUrl = ClaudePaths.jsonlPath(cwd: raw.cwd, sessionId: sessionId)
- transcriptWatcher.update(sessionId: sessionId, jsonlURL: jsonlUrl)
-
- let transcript = transcriptWatcher.state(for: sessionId)
- let tasks = SessionFileParser.parseTasks(sessionId: sessionId)
- // Try exact sessionId first, then fall back to latest entry for this project
- // (handles resolved sessions where sessionId differs from index)
- let indexEntry = SessionFileParser.parseSessionIndex(cwd: raw.cwd, sessionId: sessionId)
- ?? SessionFileParser.parseLatestSessionIndex(cwd: raw.cwd)
-
- // Hook-driven: clear stale hook states when transcript shows activity resumed
- let needsPermission = hookServer?.needsPermission(sessionId) ?? false
- if needsPermission, let t = transcript, t.status == .working {
- hookServer?.clearPermission(sessionId)
- }
- if hookServer?.isStopped(sessionId) == true, let t = transcript, t.status == .working {
- hookServer?.clearStop(sessionId)
- }
-
- let (status, waitingReason) = detectStatus(
- raw: raw,
- transcript: transcript,
- tasks: tasks,
- needsPermission: needsPermission
- )
-
- let projectName = URL(fileURLWithPath: raw.cwd).lastPathComponent
- let startDate = Date(timeIntervalSince1970: TimeInterval(raw.startedAt) / 1000)
- let duration = Int(Date().timeIntervalSince(startDate))
- let currentTask = tasks.first(where: { $0.status == .inProgress })?.activeForm
- ?? transcript?.lastEvent
- let lastEvent = transcript?.lastEvent
-
- // Summary priority: sessions-index summary > lastPrompt > firstPrompt > project name
- // Filter out system messages like "[Request interrupted by user]"
- let isUsable = { (s: String) -> Bool in
- !s.isEmpty && !s.hasPrefix("[Request") && !s.hasPrefix("[Error")
- }
- let summary: String = {
- if let s = indexEntry?.summary, isUsable(s) { return s }
- if let lp = transcript?.lastPrompt, isUsable(lp) { return lp }
- if let fp = transcript?.firstPrompt, isUsable(fp) { return fp }
- if let fp = indexEntry?.firstPrompt, isUsable(fp) { return String(fp.prefix(80)) }
- return projectName
- }()
-
- // Git branch: sessions-index > direct git query > "unknown"
- let gitBranch = indexEntry?.gitBranch ?? Self.gitBranch(cwd: raw.cwd)
-
- let existingSession = sessions.first { $0.sessionId == sessionId }
- let updatedAt = transcript?.lastActivityTime ?? existingSession?.updatedAt ?? startDate
-
- let session = SessionState(
- sessionId: sessionId,
- projectName: projectName,
- gitBranch: gitBranch,
- status: status,
- model: ModelInfo.parse(transcript?.model ?? "Unknown").displayLabel,
- summary: summary,
- currentTask: currentTask,
- lastEvent: lastEvent,
- waitingReason: waitingReason,
- tasks: tasks,
- contextPct: transcript?.contextPct ?? 0,
- costUSD: transcript?.costUSD ?? 0,
- startedAt: startDate,
- durationSec: duration,
- deviceId: deviceId,
- updatedAt: updatedAt
- )
- updated.append(session)
- }
-
- // Mark disappeared sessions as completed
- for existing in sessions where existing.status != .completed {
- if !rawSessions.keys.contains(existing.sessionId) {
- var completed = existing
- completed.status = .completed
- completed.waitingReason = nil
- completed.updatedAt = Date()
- updated.append(completed)
- transcriptWatcher.removeSession(existing.sessionId)
- }
- }
-
- // Sort: primary first, then working, then by most recent activity
- let pid = primarySessionId
- let newSessions = updated.sorted { a, b in
- if a.sessionId == pid { return true }
- if b.sessionId == pid { return false }
- let aWeight = a.status == .working ? 0 : a.status == .needsInput ? 1 : 2
- let bWeight = b.status == .working ? 0 : b.status == .needsInput ? 1 : 2
- if aWeight != bWeight { return aWeight < bWeight }
- return a.updatedAt > b.updatedAt
- }
- // Always assign — hook state changes (status, waitingReason) must propagate
- // to UI even when the session list structure hasn't changed
- sessions = newSessions
- }
-
- private var skipPermissionsCache: [Int: Bool] = [:]
-
- private func isSkipPermissions(pid: Int) -> Bool {
- if let cached = skipPermissionsCache[pid] { return cached }
- let result = PIDChecker.skipsPermissions(pid: pid)
- skipPermissionsCache[pid] = result
- return result
- }
-
- /// Hook-driven status detection.
- /// Priority: PID check → Stop hook → Permission hook → Tool running hook → Transcript → Tasks → Idle
- private func detectStatus(
- raw: RawSessionFile,
- transcript: TranscriptState?,
- tasks: [TaskItem],
- needsPermission: Bool
- ) -> (SessionStatus, WaitingReason?) {
- // 1. PID dead → completed
- guard PIDChecker.isAlive(pid: raw.pid) else {
- skipPermissionsCache.removeValue(forKey: raw.pid)
- return (.completed, nil)
- }
-
- let bypassed = isSkipPermissions(pid: raw.pid)
- let sessionId = raw.sessionId
-
- // 2. Hook: Stop fired → waiting for user input (yellow)
- if hookServer?.isStopped(sessionId) == true {
- return (.needsInput, .commandComplete)
- }
-
- // 3. Hook: Permission/elicitation/askUserQuestion needed (red or yellow)
- if needsPermission && !bypassed {
- let reason: WaitingReason
- if let lastEvent = transcript?.lastEvent {
- if lastEvent.contains("Waiting for input") {
- reason = .askUserQuestion
- } else {
- reason = .permissionPrompt
- }
- } else {
- reason = .permissionPrompt
- }
- return (.needsInput, reason)
- }
-
- // 4. Hook: Tool currently running → working
- // But transcript idle/end_turn overrides stale toolRunning
- // (handles lost postToolUse hooks)
- if hookServer?.isToolRunning(sessionId) == true {
- if let transcript, transcript.status == .idle {
- hookServer?.clearToolRunning(sessionId)
- } else {
- return (.working, nil)
- }
- }
-
- // 5. Transcript state (supplementary — for working/compacting/idle)
- if let transcript {
- switch transcript.status {
- case .working:
- return (.working, nil)
- case .waitingForUser:
- return (bypassed ? .idle : .needsInput, bypassed ? nil : .unknown)
- case .compacting:
- return (.compacting, nil)
- case .idle:
- return (.idle, nil)
- }
- }
-
- // 6. Fallback: check tasks
- if tasks.contains(where: { $0.status == .inProgress }) { return (.working, nil) }
-
- // 7. No signal → idle
- return (.idle, nil)
- }
-
- private static var gitBranchCache: [String: (branch: String, time: Date)] = [:]
-
- private static func gitBranch(cwd: String) -> String {
- // Cache for 30 seconds to avoid spawning git on every scan
- if let cached = gitBranchCache[cwd],
- Date().timeIntervalSince(cached.time) < 30 {
- return cached.branch
- }
- let proc = Process()
- proc.executableURL = URL(fileURLWithPath: "/usr/bin/git")
- proc.arguments = ["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"]
- proc.currentDirectoryURL = URL(fileURLWithPath: cwd)
- let pipe = Pipe()
- proc.standardOutput = pipe
- proc.standardError = FileHandle.nullDevice
- do {
- try proc.run()
- proc.waitUntilExit()
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- let branch = String(data: data, encoding: .utf8)?
- .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
- let result = branch.isEmpty ? "unknown" : branch
- gitBranchCache[cwd] = (result, Date())
- return result
- } catch {
- return "unknown"
- }
- }
-
-}
diff --git a/Codync-macOS/Services/TranscriptWatcher.swift b/Codync-macOS/Services/TranscriptWatcher.swift
deleted file mode 100644
index 65a70912..00000000
--- a/Codync-macOS/Services/TranscriptWatcher.swift
+++ /dev/null
@@ -1,515 +0,0 @@
-import Foundation
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync", category: "TranscriptWatcher")
-
-/// Per-session transcript state derived from incremental JSONL parsing.
-/// State machine inspired by claude-status (gmr/claude-status-plugin).
-struct TranscriptState: Sendable {
- var status: TranscriptStatus = .idle
- var lastEvent: String = ""
- var toolName: String?
- var model: String = "Unknown"
- var latestInputTokens: Int = 0
- var totalOutputTokens: Int = 0
- var lastActivityTime: Date = Date()
- var firstPrompt: String = ""
- var lastPrompt: String = ""
-
- /// Context usage as percentage. Window size derived from model ID
- /// (e.g., 1M for Opus 4.6+, 200k for older models).
- var contextPct: Int {
- guard latestInputTokens > 0 else { return 0 }
- let contextWindow = ModelInfo.parse(model).contextWindow
- return min(100, (latestInputTokens * 100) / contextWindow)
- }
-
- var costUSD: Double {
- let (inputRate, outputRate) = modelPricing
- return Double(latestInputTokens) * inputRate / 1_000_000
- + Double(totalOutputTokens) * outputRate / 1_000_000
- }
-
- private var modelPricing: (Double, Double) {
- if model.contains("opus") { return (15.0, 75.0) }
- if model.contains("sonnet") { return (3.0, 15.0) }
- if model.contains("haiku") { return (0.25, 1.25) }
- return (3.0, 15.0)
- }
-}
-
-enum TranscriptStatus: Sendable {
- case working
- case waitingForUser
- case compacting
- case idle
-}
-
-/// Incrementally parses JSONL transcript files to detect session state.
-/// Zero impact on Claude Code — reads files only, no hooks for tool events.
-@MainActor
-final class TranscriptWatcher {
- /// Per-session tracking (mirrors claude-status's DaemonState)
- private struct SessionTracker {
- var fileOffset: UInt64 = 0
- var lineBuffer: String = ""
- var state: TranscriptState = TranscriptState()
-
- // Agent tracking: tool_use IDs for Agent tools (subagents)
- var activeAgents: Set<String> = []
- // All active tool_use IDs (for permission timeout heuristic)
- var activeToolIds: Set<String> = []
- var lastToolStartTime: Date?
-
- // Compaction state: when true, suppress replayed user/progress messages
- var isCompacting: Bool = false
-
- // Whether this session has received at least one hook event.
- // Sessions that started before hooks were registered need JSONL-based
- // permission timeout as a fallback.
- var hasReceivedHookEvent: Bool = false
- }
-
- private var trackers: [String: SessionTracker] = [:]
- private let decoder = JSONDecoder()
-
- // MARK: - Public API
-
- func state(for sessionId: String) -> TranscriptState? {
- trackers[sessionId]?.state
- }
-
- /// Receive a hook signal from ClaudeHookServer.
- /// Hook signals are the primary status source — they override JSONL-derived state.
- func handleHookSignal(sessionId: String, signal: HookSignalType, toolName: String? = nil) {
- guard var tracker = trackers[sessionId] else {
- var newTracker = SessionTracker()
- newTracker.state.lastActivityTime = Date()
- applyHookSignal(signal, toolName: toolName, tracker: &newTracker)
- trackers[sessionId] = newTracker
- return
- }
- tracker.state.lastActivityTime = Date()
- applyHookSignal(signal, toolName: toolName, tracker: &tracker)
- trackers[sessionId] = tracker
- }
-
- private func applyHookSignal(_ signal: HookSignalType, toolName: String?, tracker: inout SessionTracker) {
- tracker.hasReceivedHookEvent = true
- switch signal {
- case .permissionRequest:
- tracker.state.status = .waitingForUser
- tracker.state.lastEvent = toolName.map { "Permission: \($0)" } ?? "Needs permission"
- case .askUserQuestion:
- tracker.state.status = .waitingForUser
- tracker.state.lastEvent = "Waiting for input"
- case .elicitationDialog:
- tracker.state.status = .waitingForUser
- tracker.state.lastEvent = "Waiting for input"
- case .stop:
- tracker.state.status = .idle
- tracker.state.lastEvent = ""
- tracker.activeToolIds.removeAll()
- tracker.activeAgents.removeAll()
- tracker.lastToolStartTime = nil
- case .userPromptSubmit:
- tracker.state.status = .working
- tracker.state.lastEvent = "Processing prompt..."
- tracker.activeToolIds.removeAll()
- tracker.activeAgents.removeAll()
- tracker.lastToolStartTime = nil
- case .preToolUse:
- tracker.state.status = .working
- if let toolName {
- tracker.state.lastEvent = formatToolStatus(name: toolName, input: nil)
- }
- case .postToolUse:
- break
- }
- }
-
- /// Process new data from a session's JSONL file. Call this on each scan cycle.
- func update(sessionId: String, jsonlURL: URL) {
- var tracker = trackers[sessionId] ?? SessionTracker()
-
- guard let fileHandle = try? FileHandle(forReadingFrom: jsonlURL) else { return }
- defer { try? fileHandle.close() }
-
- let fileSize = fileHandle.seekToEndOfFile()
-
- // First time — skip to end but detect initial status from tail
- if tracker.fileOffset == 0 && trackers[sessionId] == nil {
- tracker.fileOffset = fileSize
- let info = JSONLTailReader.extractInfo(url: jsonlURL)
- tracker.state.model = info.model
- tracker.state.latestInputTokens = info.latestInputTokens
- tracker.state.totalOutputTokens = info.totalOutputTokens
- let (initialStatus, lastEvent) = detectInitialStatus(url: jsonlURL)
- tracker.state.status = initialStatus
- if let lastEvent { tracker.state.lastEvent = lastEvent }
- trackers[sessionId] = tracker
- return
- }
-
- guard fileSize > tracker.fileOffset else {
- updateTimeouts(&tracker)
- trackers[sessionId] = tracker
- return
- }
-
- fileHandle.seek(toFileOffset: tracker.fileOffset)
- guard let newData = try? fileHandle.readToEnd(),
- let newText = String(data: newData, encoding: .utf8) else {
- trackers[sessionId] = tracker
- return
- }
-
- tracker.fileOffset = fileSize
- tracker.state.lastActivityTime = Date()
-
- let text = tracker.lineBuffer + newText
- var lines = text.components(separatedBy: "\n")
- tracker.lineBuffer = lines.removeLast()
-
- for line in lines where !line.isEmpty {
- processLine(line, tracker: &tracker)
- }
-
- trackers[sessionId] = tracker
- }
-
- func removeSession(_ sessionId: String) {
- trackers.removeValue(forKey: sessionId)
- }
-
- // MARK: - Line Processing
-
- private func processLine(_ line: String, tracker: inout SessionTracker) {
- guard let data = line.data(using: .utf8),
- let entry = try? decoder.decode(JSONLTranscriptEntry.self, from: data) else { return }
-
- // Skip meta messages (plugin commands, local output)
- if entry.isMeta == true { return }
-
- // Compaction detection via agentId prefix
- if let agentId = entry.agentId, agentId.hasPrefix("acompact-") {
- if tracker.state.status != .compacting {
- tracker.state.status = .compacting
- tracker.state.lastEvent = "Compacting context..."
- tracker.isCompacting = true
- }
- return
- }
-
- switch entry.type {
- case "assistant":
- processAssistant(entry, tracker: &tracker)
- case "user":
- processUser(entry, tracker: &tracker)
- case "system":
- processSystem(entry, tracker: &tracker)
- case "progress":
- processProgress(entry, tracker: &tracker)
- case "last-prompt":
- if let prompt = entry.lastPrompt, !prompt.isEmpty {
- tracker.state.lastPrompt = String(prompt.prefix(100))
- }
- default:
- break
- }
- }
-
- private func processAssistant(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
- guard let message = entry.message else { return }
-
- // An assistant response clears compaction flag
- if tracker.isCompacting {
- tracker.isCompacting = false
- }
-
- // Update model and usage
- if let model = message.model, !model.isEmpty {
- tracker.state.model = model
- }
- if let usage = message.usage {
- let contextTokens = usage.totalContextTokens
- if contextTokens > 0 {
- tracker.state.latestInputTokens = contextTokens
- }
- tracker.state.totalOutputTokens += usage.outputTokens ?? 0
- }
-
- guard let content = message.content else { return }
-
- // Track tool_use blocks
- let toolUseBlocks = content.filter { $0.type == "tool_use" }
- for block in toolUseBlocks {
- if let id = block.id {
- tracker.activeToolIds.insert(id)
- // Track Agent tool specifically for subagent awareness
- if block.name == "Agent" {
- tracker.activeAgents.insert(id)
- }
- }
- if let name = block.name {
- tracker.state.toolName = name
- tracker.state.lastEvent = formatToolStatus(name: name, input: block.input)
- }
- }
- if !toolUseBlocks.isEmpty {
- tracker.lastToolStartTime = Date()
- }
-
- // Determine state from stop_reason (key insight from claude-status)
- switch message.stopReason {
- case nil:
- // Still streaming — active
- tracker.state.status = .working
-
- case "tool_use":
- // About to execute tools — active
- tracker.state.status = .working
-
- case "end_turn":
- if !tracker.activeAgents.isEmpty {
- // Subagents still running — stay active
- tracker.state.status = .working
- tracker.state.lastEvent = "Running sub-agent"
- } else {
- // Turn finished — idle
- tracker.state.status = .idle
- tracker.state.lastEvent = ""
- tracker.activeToolIds.removeAll()
- tracker.lastToolStartTime = nil
- }
-
- case "stop_sequence", "max_tokens":
- tracker.state.status = .idle
- tracker.state.lastEvent = ""
- tracker.activeToolIds.removeAll()
- tracker.activeAgents.removeAll()
- tracker.lastToolStartTime = nil
-
- default:
- // Unknown stop_reason — treat as still working if we have tool activity
- if !toolUseBlocks.isEmpty || !tracker.activeToolIds.isEmpty {
- tracker.state.status = .working
- }
- }
-
- // If no stop_reason and has text, still working
- if message.stopReason == nil, content.contains(where: { $0.type == "text" }), toolUseBlocks.isEmpty {
- tracker.state.status = .working
- if tracker.state.lastEvent.isEmpty {
- tracker.state.lastEvent = "Thinking..."
- }
- }
- }
-
- private func processUser(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
- // During compaction, user messages are replayed context — skip
- if tracker.isCompacting { return }
-
- guard let content = entry.message?.content else { return }
-
- let toolResults = content.filter { $0.type == "tool_result" }
-
- if !toolResults.isEmpty {
- // Tool completed — remove from tracking
- for result in toolResults {
- if let id = result.toolUseId {
- tracker.activeToolIds.remove(id)
- // Only remove from activeAgents if not async
- if result.isAsync != true {
- tracker.activeAgents.remove(id)
- }
- }
- }
- if tracker.activeToolIds.isEmpty {
- tracker.lastToolStartTime = nil
- }
- } else if entry.promptId != nil {
- // Real user prompt (has promptId) — new turn starting
- tracker.state.status = .working
- tracker.state.lastEvent = "Processing prompt..."
- tracker.activeToolIds.removeAll()
- tracker.activeAgents.removeAll()
- tracker.lastToolStartTime = nil
-
- // Extract prompt text for summary
- if let textBlock = content.first(where: { $0.type == "text" }),
- let text = textBlock.text?.trimmingCharacters(in: .whitespacesAndNewlines),
- !text.isEmpty, !text.hasPrefix("<") {
- let clean = String(text.prefix(100))
- tracker.state.lastPrompt = clean
- if tracker.state.firstPrompt.isEmpty {
- tracker.state.firstPrompt = clean
- }
- }
- } else {
- // User message without promptId and without tool_result — likely still working
- tracker.state.status = .working
- tracker.state.lastEvent = "Processing..."
- }
- }
-
- private func processSystem(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
- switch entry.subtype {
- case "turn_duration", "stop_hook_summary":
- // Turn end signals — stop_hook_summary fires after hooks complete,
- // turn_duration may follow (but not always). Either one marks turn as done.
- tracker.activeAgents.removeAll()
- tracker.activeToolIds.removeAll()
- tracker.lastToolStartTime = nil
- if tracker.state.status == .working || tracker.state.status == .compacting {
- tracker.state.status = .idle
- tracker.state.lastEvent = ""
- }
-
- case "compact_boundary":
- tracker.state.status = .compacting
- tracker.state.lastEvent = "Compacting context..."
- tracker.isCompacting = true
-
- default:
- break
- }
- }
-
- private func processProgress(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
- // During compaction, progress messages are replayed — skip
- if tracker.isCompacting { return }
-
- guard let dataType = entry.data?.type else { return }
-
- switch dataType {
- case "agent_progress":
- tracker.state.status = .working
- tracker.state.lastEvent = "Running sub-agent"
- case "bash_progress":
- tracker.state.status = .working
- tracker.state.lastEvent = "Running command..."
- case "mcp_progress":
- tracker.state.status = .working
- tracker.state.lastEvent = "MCP tool running..."
- case "hook_progress":
- // Hooks running (e.g. notify.sh) — NOT real work, don't change state
- break
- default:
- break
- }
- }
-
- // MARK: - Timeout Checks
-
- private func updateTimeouts(_ tracker: inout SessionTracker) {
- let now = Date()
- let sinceLastActivity = now.timeIntervalSince(tracker.state.lastActivityTime)
-
- // For sessions that started BEFORE hooks were registered (e.g., app just installed),
- // use JSONL-based permission timeout as fallback. Once any hook fires, this is disabled.
- if !tracker.hasReceivedHookEvent,
- !tracker.activeToolIds.isEmpty,
- tracker.activeAgents.isEmpty,
- let toolStart = tracker.lastToolStartTime,
- now.timeIntervalSince(toolStart) > 8.0 {
- if tracker.state.status == .working {
- tracker.state.status = .waitingForUser
- tracker.state.lastEvent = "Needs permission"
- }
- }
-
- // Safety net: if working with no activity for 30s and no active tools, assume idle.
- // Normally Stop hook handles this instantly — this catches edge cases only.
- if tracker.state.status == .working,
- tracker.activeToolIds.isEmpty,
- tracker.activeAgents.isEmpty,
- sinceLastActivity > 30.0 {
- tracker.state.status = .idle
- tracker.state.lastEvent = ""
- }
- }
-
- // MARK: - Initial Status Detection
-
- private func detectInitialStatus(url: URL) -> (TranscriptStatus, String?) {
- let lines = JSONLTailReader.readTail(url: url, lineCount: 20)
-
- for line in lines.reversed() {
- guard let data = line.data(using: .utf8),
- let entry = try? decoder.decode(JSONLTranscriptEntry.self, from: data) else { continue }
-
- if entry.isMeta == true { continue }
-
- if entry.type == "system" {
- if entry.subtype == "turn_duration" || entry.subtype == "stop_hook_summary" {
- return (.idle, nil)
- }
- if entry.subtype == "compact_boundary" { return (.compacting, "Compacting context...") }
- }
-
- if entry.type == "assistant" {
- if let stopReason = entry.message?.stopReason {
- if stopReason == "end_turn" || stopReason == "stop_sequence" || stopReason == "max_tokens" {
- return (.idle, nil)
- }
- }
- if let content = entry.message?.content,
- let toolBlock = content.first(where: { $0.type == "tool_use" }),
- let toolName = toolBlock.name {
- return (.working, formatToolStatus(name: toolName, input: toolBlock.input))
- }
- return (.working, "Thinking...")
- }
-
- if entry.type == "user" {
- if let content = entry.message?.content,
- content.contains(where: { $0.type == "tool_result" }) {
- return (.working, nil)
- }
- return (.working, "Processing prompt...")
- }
-
- if entry.type == "progress" {
- return (.working, "Running...")
- }
- }
-
- return (.idle, nil)
- }
-
- // MARK: - Display Formatting
-
- private func formatToolStatus(name: String, input: JSONLToolInput?) -> String {
- switch name {
- case "Read":
- if let fp = input?.filePath { return "Reading \(URL(fileURLWithPath: fp).lastPathComponent)" }
- return "Reading file"
- case "Edit":
- if let fp = input?.filePath { return "Editing \(URL(fileURLWithPath: fp).lastPathComponent)" }
- return "Editing file"
- case "Write":
- if let fp = input?.filePath { return "Writing \(URL(fileURLWithPath: fp).lastPathComponent)" }
- return "Writing file"
- case "Bash":
- if let cmd = input?.command {
- let short = cmd.prefix(40)
- return "Running: \(short)\(cmd.count > 40 ? "..." : "")"
- }
- return "Running command"
- case "Glob":
- return "Searching files"
- case "Grep":
- return "Searching code"
- case "Agent":
- return "Running sub-agent"
- case "WebFetch":
- return "Fetching web content"
- case "WebSearch":
- return "Searching the web"
- default:
- return "Using \(name)"
- }
- }
-}
diff --git a/Codync-macOS/Utilities/ClaudePaths.swift b/Codync-macOS/Utilities/ClaudePaths.swift
deleted file mode 100644
index 84a6ffdc..00000000
--- a/Codync-macOS/Utilities/ClaudePaths.swift
+++ /dev/null
@@ -1,32 +0,0 @@
-import Foundation
-
-enum ClaudePaths {
- static var claudeDir: URL {
- FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude")
- }
-
- static var sessionsDir: URL { claudeDir.appendingPathComponent("sessions") }
- static var tasksDir: URL { claudeDir.appendingPathComponent("tasks") }
- static var todosDir: URL { claudeDir.appendingPathComponent("todos") }
- static var projectsDir: URL { claudeDir.appendingPathComponent("projects") }
-
- static func mangledCwd(_ cwd: String) -> String {
- cwd.replacingOccurrences(of: "/", with: "-")
- }
-
- static func sessionIndexPath(cwd: String) -> URL {
- projectsDir
- .appendingPathComponent(mangledCwd(cwd))
- .appendingPathComponent("sessions-index.json")
- }
-
- static func jsonlPath(cwd: String, sessionId: String) -> URL {
- projectsDir
- .appendingPathComponent(mangledCwd(cwd))
- .appendingPathComponent("\(sessionId).jsonl")
- }
-
- static func todosPattern(sessionId: String) -> String {
- "\(sessionId)-agent-"
- }
-}
diff --git a/Codync-macOS/Utilities/JSONLTailReader.swift b/Codync-macOS/Utilities/JSONLTailReader.swift
deleted file mode 100644
index 3d1eb14d..00000000
--- a/Codync-macOS/Utilities/JSONLTailReader.swift
+++ /dev/null
@@ -1,148 +0,0 @@
-import Foundation
-
-struct JSONLUsage: Codable {
- let inputTokens: Int?
- let outputTokens: Int?
- let cacheCreationInputTokens: Int?
- let cacheReadInputTokens: Int?
-
- /// Total context window usage: input + cache_creation + cache_read
- var totalContextTokens: Int {
- let input = inputTokens ?? 0
- guard input > 0 else { return 0 }
- return input + (cacheCreationInputTokens ?? 0) + (cacheReadInputTokens ?? 0)
- }
-
- enum CodingKeys: String, CodingKey {
- case inputTokens = "input_tokens"
- case outputTokens = "output_tokens"
- case cacheCreationInputTokens = "cache_creation_input_tokens"
- case cacheReadInputTokens = "cache_read_input_tokens"
- }
-}
-
-struct JSONLMessage: Codable {
- let role: String?
- let model: String?
- let usage: JSONLUsage?
-}
-
-struct JSONLEntry: Codable {
- let type: String?
- let message: JSONLMessage?
- let timestamp: String?
-}
-
-// MARK: - Transcript Content Blocks
-
-struct JSONLContentBlock: Codable {
- let type: String
- let id: String?
- let name: String?
- let text: String?
- let input: JSONLToolInput?
- let toolUseId: String?
- let isAsync: Bool?
-
- enum CodingKeys: String, CodingKey {
- case type, id, name, text, input
- case toolUseId = "tool_use_id"
- case isAsync
- }
-}
-
-struct JSONLToolInput: Codable {
- let command: String?
- let filePath: String?
- let pattern: String?
-
- enum CodingKeys: String, CodingKey {
- case command
- case filePath = "file_path"
- case pattern
- }
-}
-
-struct JSONLTranscriptMessage: Codable {
- let role: String?
- let model: String?
- let usage: JSONLUsage?
- let content: [JSONLContentBlock]?
- let stopReason: String?
-
- enum CodingKeys: String, CodingKey {
- case role, model, usage, content
- case stopReason = "stop_reason"
- }
-}
-
-struct JSONLProgressData: Codable {
- let type: String?
-}
-
-struct JSONLTranscriptEntry: Codable {
- let type: String?
- let subtype: String?
- let message: JSONLTranscriptMessage?
- let timestamp: String?
- let isMeta: Bool?
- let agentId: String?
- let promptId: String?
- let data: JSONLProgressData?
- /// Present on "last-prompt" type entries
- let lastPrompt: String?
-}
-
-struct JSONLSessionInfo {
- var model: String = "Unknown"
- var latestInputTokens: Int = 0
- var totalOutputTokens: Int = 0
-}
-
-enum JSONLTailReader {
- static func readTail(url: URL, lineCount: Int = 50) -> [String] {
- guard let fileHandle = try? FileHandle(forReadingFrom: url) else { return [] }
- defer { try? fileHandle.close() }
-
- let fileSize = fileHandle.seekToEndOfFile()
- guard fileSize > 0 else { return [] }
-
- // ~4KB per line: JSONL entries with tool outputs average 3-5KB
- let chunkSize = min(fileSize, UInt64(lineCount * 4000))
- fileHandle.seek(toFileOffset: fileSize - chunkSize)
-
- guard let data = try? fileHandle.readToEnd(),
- let text = String(data: data, encoding: .utf8) else { return [] }
-
- let lines = text.components(separatedBy: "\n").filter { !$0.isEmpty }
- return Array(lines.suffix(lineCount))
- }
-
- static func extractInfo(url: URL) -> JSONLSessionInfo {
- let lines = readTail(url: url, lineCount: 100) // read more lines for better coverage
- var info = JSONLSessionInfo()
- var totalOutputTokens = 0
-
- let decoder = JSONDecoder()
- for line in lines {
- guard let data = line.data(using: .utf8),
- let entry = try? decoder.decode(JSONLEntry.self, from: data) else { continue }
-
- if let message = entry.message {
- if let model = message.model, !model.isEmpty {
- info.model = model
- }
- if let usage = message.usage {
- let contextTokens = usage.totalContextTokens
- if contextTokens > 0 {
- info.latestInputTokens = contextTokens
- }
- totalOutputTokens += usage.outputTokens ?? 0
- }
- }
- }
-
- info.totalOutputTokens = totalOutputTokens
- return info
- }
-}
diff --git a/Codync-macOS/Utilities/PIDChecker.swift b/Codync-macOS/Utilities/PIDChecker.swift
deleted file mode 100644
index 09c5aacf..00000000
--- a/Codync-macOS/Utilities/PIDChecker.swift
+++ /dev/null
@@ -1,47 +0,0 @@
-import Foundation
-
-enum PIDChecker {
- static func isAlive(pid: Int) -> Bool {
- kill(Int32(pid), 0) == 0
- }
-
- /// Get the TTY device for a PID by walking up the process tree.
- /// Uses a single `ps -o tty=,ppid=` per iteration (max 5 subprocesses).
- static func tty(for pid: Int) -> String? {
- var current = Int32(pid)
- for _ in 0..<5 {
- guard let output = psColumns(pid: current, columns: "tty=,ppid=") else { break }
- let parts = output.split(separator: " ", maxSplits: 1)
- let tty = parts.first.map(String.init)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
- if !tty.isEmpty && tty != "??" {
- return "/dev/\(tty)"
- }
- guard parts.count > 1,
- let ppid = Int32(parts[1].trimmingCharacters(in: .whitespacesAndNewlines)),
- ppid > 0 else { break }
- current = ppid
- }
- return nil
- }
-
- /// Run `ps -o <columns> -p <pid>` and return the output string.
- private static func psColumns(pid: Int32, columns: String) -> String? {
- let proc = Process()
- proc.executableURL = URL(fileURLWithPath: "/bin/ps")
- proc.arguments = ["-o", columns, "-p", "\(pid)"]
- let pipe = Pipe()
- proc.standardOutput = pipe
- proc.standardError = FileHandle.nullDevice
- guard (try? proc.run()) != nil else { return nil }
- proc.waitUntilExit()
- guard proc.terminationStatus == 0 else { return nil }
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- return String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
- }
-
- /// Check if a process was launched with --dangerously-skip-permissions
- static func skipsPermissions(pid: Int) -> Bool {
- guard let args = psColumns(pid: Int32(pid), columns: "args=") else { return false }
- return args.contains("--dangerously-skip-permissions")
- }
-}
diff --git a/Codync-macOS/Views/PanelHeaderView.swift b/Codync-macOS/Views/PanelHeaderView.swift
deleted file mode 100644
index 94a8ea42..00000000
--- a/Codync-macOS/Views/PanelHeaderView.swift
+++ /dev/null
@@ -1,45 +0,0 @@
-import SwiftUI
-
-struct PanelHeaderView: View {
- @ObservedObject var panelState: CodyncPanelState
- @AppStorage("codync_darkMode") private var isDarkMode = true
- @Environment(\.theme) private var theme
-
- var body: some View {
- HStack(spacing: 8) {
- Image("CodyncIcon")
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 16, height: 16)
- .clipShape(RoundedRectangle(cornerRadius: 3, style: .continuous))
-
- Spacer()
-
- Button(action: { isDarkMode.toggle() }) {
- Image(systemName: isDarkMode ? "sun.max" : "moon")
- .font(.system(size: 11))
- .foregroundStyle(theme.secondaryText)
- }
- .buttonStyle(.plain)
-
- Button(action: { panelState.isPinned.toggle() }) {
- Image(systemName: panelState.isPinned ? "pin.fill" : "pin")
- .font(.system(size: 11))
- .foregroundStyle(panelState.isPinned ? theme.primaryText : theme.secondaryText)
- .rotationEffect(.degrees(panelState.isPinned ? 0 : 45))
- }
- .buttonStyle(.plain)
-
- Button(action: { NSApp.terminate(nil) }) {
- Image(systemName: "xmark")
- .font(.system(size: 10, weight: .medium))
- .foregroundStyle(theme.secondaryText)
- .frame(width: 24, height: 24)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- }
- .padding(.horizontal, 14)
- .padding(.vertical, 8)
- }
-}
diff --git a/Codync-macOS/Views/SessionDetailView.swift b/Codync-macOS/Views/SessionDetailView.swift
deleted file mode 100644
index 0c9340d5..00000000
--- a/Codync-macOS/Views/SessionDetailView.swift
+++ /dev/null
@@ -1,187 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-struct SessionDetailView: View {
- let session: SessionState
- let onBack: () -> Void
- @Environment(\.theme) private var theme
-
- var body: some View {
- VStack(spacing: 0) {
- HStack(spacing: 6) {
- Button(action: onBack) {
- HStack(spacing: 2) {
- Image(systemName: "chevron.left")
- .font(.system(size: 11, weight: .semibold))
- Text("Back")
- .font(.system(size: 12))
- }
- .foregroundStyle(theme.secondaryText)
- }
- .buttonStyle(.plain)
- .onHover { inside in
- if inside { NSCursor.pointingHand.push() }
- else { NSCursor.pop() }
- }
-
- Spacer()
-
- SessionStatusView(
- status: session.status,
- completedTasks: session.completedTaskCount,
- totalTasks: session.totalTaskCount,
- waitingReason: session.waitingReason
- )
- Text(statusLabel)
- .font(.system(size: 11, weight: .medium))
- .foregroundStyle(statusLabelColor)
- }
- .padding(.horizontal, 12)
- .padding(.vertical, 8)
-
- Divider().padding(.horizontal, 8)
-
- ScrollView(.vertical, showsIndicators: false) {
- VStack(alignment: .leading, spacing: 12) {
- VStack(alignment: .leading, spacing: 4) {
- HStack(spacing: 4) {
- Text(session.projectName)
- .font(.system(size: 14, weight: .semibold))
- .foregroundStyle(theme.primaryText)
- if !session.model.isEmpty {
- SessionTagView(tag: session.model)
- }
- }
- if session.summary != session.projectName {
- Text(session.summary)
- .font(.system(size: 12))
- .foregroundStyle(theme.secondaryText)
- .lineLimit(2)
- }
- HStack(spacing: 6) {
- Label(session.gitBranch.isEmpty ? session.projectName : session.gitBranch, systemImage: "arrow.triangle.branch")
- }
- .font(.system(size: 11))
- .foregroundStyle(theme.tertiaryText)
- }
-
- HStack(spacing: 0) {
- statItem("\(session.contextPct)%", "Context")
- Divider().frame(height: 24)
- statItem(String(format: "$%.2f", session.costUSD), "Cost")
- Divider().frame(height: 24)
- statItem(formatDuration(session.durationSec), "Duration")
- }
- .padding(.vertical, 6)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(theme.cardBackground)
- )
-
- if !session.tasks.isEmpty {
- VStack(alignment: .leading, spacing: 10) {
- HStack(spacing: 10) {
- DetailProgressRing(completed: session.completedTaskCount, total: session.totalTaskCount)
- VStack(alignment: .leading, spacing: 2) {
- Text("Tasks")
- .font(.system(size: 12, weight: .medium))
- .foregroundStyle(theme.primaryText)
- Text("\(session.completedTaskCount) of \(session.totalTaskCount) completed")
- .font(.system(size: 11))
- .foregroundStyle(theme.secondaryText)
- }
- Spacer()
- }
- VStack(alignment: .leading, spacing: 4) {
- ForEach(session.tasks) { task in
- HStack(spacing: 6) {
- taskIcon(task.status)
- Text(task.content)
- .font(.system(size: 12))
- .foregroundStyle(task.status == .pending ? theme.secondaryText : theme.primaryText)
- .lineLimit(1)
- }
- }
- }
- }
- }
- }
- .padding(.horizontal, 12)
- .padding(.vertical, 10)
- }
- }
- }
-
- private var statusLabel: String {
- guard session.status == .needsInput else { return session.status.label }
- return session.waitingReason?.label ?? "Needs Input"
- }
-
- private var statusLabelColor: Color {
- guard session.status == .needsInput else { return theme.secondaryText }
- return theme.waitingColor(for: session.waitingReason)
- }
-
- private func taskIcon(_ status: TaskStatus) -> some View {
- Group {
- switch status {
- case .completed:
- Image(systemName: "checkmark.circle.fill").foregroundStyle(theme.primaryText.opacity(0.7))
- case .inProgress:
- Image(systemName: "circlebadge.fill").foregroundStyle(theme.primaryText.opacity(0.7))
- case .pending:
- Image(systemName: "circle").foregroundStyle(theme.tertiaryText)
- }
- }
- .font(.system(size: 11))
- }
-
- private func statItem(_ value: String, _ label: String) -> some View {
- VStack(spacing: 2) {
- Text(value)
- .font(.system(size: 13, weight: .semibold, design: .monospaced))
- .foregroundStyle(theme.primaryText)
- Text(label)
- .font(.system(size: 10))
- .foregroundStyle(theme.tertiaryText)
- }
- .frame(maxWidth: .infinity)
- }
-
- private func formatDuration(_ seconds: Int) -> String {
- if seconds < 60 { return "\(seconds)s" }
- if seconds < 3600 { return "\(seconds / 60)m" }
- let h = seconds / 3600
- let m = (seconds % 3600) / 60
- return "\(h)h \(m)m"
- }
-}
-
-private struct DetailProgressRing: View {
- let completed: Int
- let total: Int
- @Environment(\.theme) private var theme
- @State private var animatedProgress: Double = 0
-
- private var progress: Double {
- total > 0 ? Double(completed) / Double(total) : 0
- }
-
- var body: some View {
- ZStack {
- Circle().stroke(theme.secondaryText.opacity(0.15), lineWidth: 3)
- Circle()
- .trim(from: 0, to: animatedProgress)
- .stroke(theme.primaryText.opacity(0.7), style: StrokeStyle(lineWidth: 3, lineCap: .round))
- .rotationEffect(.degrees(-90))
- Text("\(Int(progress * 100))%")
- .font(.system(size: 10, weight: .semibold, design: .monospaced))
- .foregroundStyle(theme.primaryText)
- }
- .frame(width: 36, height: 36)
- .onAppear { withAnimation(.easeOut(duration: 0.6)) { animatedProgress = progress } }
- .onChange(of: progress) { _, newValue in
- withAnimation(.easeOut(duration: 0.4)) { animatedProgress = newValue }
- }
- }
-}
diff --git a/Codync-macOS/Views/SessionListView.swift b/Codync-macOS/Views/SessionListView.swift
deleted file mode 100644
index 03754c15..00000000
--- a/Codync-macOS/Views/SessionListView.swift
+++ /dev/null
@@ -1,105 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-struct SessionListView: View {
- @ObservedObject var stateManager: SessionStateManager
- var panelState: CodyncPanelState?
- @AppStorage("codync_darkMode") private var storedDarkMode = true
- @State private var isDarkMode = true
- @State private var selectedSession: SessionState?
- @State private var displayedSessions: [SessionState] = []
- @State private var reorderTimer: Timer?
- @Environment(\.theme) private var injectedTheme
-
- private var theme: CodyncTheme {
- injectedTheme.isPanel ? injectedTheme : CodyncTheme(isDark: isDarkMode)
- }
-
- var body: some View {
- VStack(spacing: 0) {
- if let selected = selectedSession {
- let liveSession = stateManager.sessions.first { $0.sessionId == selected.sessionId } ?? selected
- SessionDetailView(session: liveSession) {
- withAnimation(.easeInOut(duration: 0.2)) { selectedSession = nil }
- }
- } else {
- sessionList
- }
- }
- .frame(width: 320)
- .fixedSize(horizontal: true, vertical: true)
- .background(theme.background)
- .environment(\.theme, theme)
- .preferredColorScheme(theme.isDark ? .dark : .light)
- .onAppear { isDarkMode = storedDarkMode }
- .onChange(of: storedDarkMode) { _, newValue in
- withAnimation(.easeInOut(duration: 0.6)) { isDarkMode = newValue }
- }
- .task {
- displayedSessions = stateManager.sessions
- reorderTimer?.invalidate()
- reorderTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
- Task { @MainActor in
- let sorted = stateManager.sessions
- withAnimation(.spring(duration: 2.0, bounce: 0.1)) {
- displayedSessions = sorted
- }
- }
- }
- }
- .onDisappear {
- reorderTimer?.invalidate()
- reorderTimer = nil
- }
- }
-
- private var sessionList: some View {
- VStack(spacing: 0) {
- if let panelState {
- PanelHeaderView(panelState: panelState)
- }
-
- if displayedSessions.isEmpty && stateManager.sessions.isEmpty {
- emptyState
- } else {
- ScrollView(.vertical, showsIndicators: false) {
- VStack(spacing: 2) {
- ForEach(displayedSessions) { session in
- SessionRowView(
- session: session,
- isPrimary: stateManager.primarySessionId != nil
- && session.sessionId == stateManager.primarySessionId
- ) {
- withAnimation(.easeInOut(duration: 0.2)) { selectedSession = session }
- }
- }
- }
- .padding(.vertical, 6)
- .padding(.horizontal, 4)
- }
- .environment(\.theme, CodyncTheme(isDark: isDarkMode, isPanel: false))
- .frame(maxHeight: 420)
- .background(
- (isDarkMode ? theme.cardBackground : Color.white.opacity(0.85)),
- in: RoundedRectangle(cornerRadius: 12, style: .continuous)
- )
- .padding(.horizontal, 14)
- .padding(.vertical, 6)
- }
- }
- }
-
- private var emptyState: some View {
- VStack(spacing: 8) {
- Image(systemName: "terminal")
- .font(.system(size: 24, weight: .light))
- .foregroundStyle(theme.secondaryText)
- Text("No active sessions")
- .font(.system(size: 13))
- .foregroundStyle(theme.secondaryText)
- }
- .frame(height: 120)
- .frame(maxWidth: .infinity)
- }
-
-}
diff --git a/Codync-macOS/Views/SessionRowView.swift b/Codync-macOS/Views/SessionRowView.swift
deleted file mode 100644
index caa4737a..00000000
--- a/Codync-macOS/Views/SessionRowView.swift
+++ /dev/null
@@ -1,85 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-struct SessionRowView: View {
- let session: SessionState
- var isPrimary: Bool = false
- let onSelect: () -> Void
- @Environment(\.theme) private var theme
- @State private var isHovered = false
- @State private var isPressed = false
-
- var body: some View {
- Button(action: {
- withAnimation(.spring(duration: 0.15)) { isPressed = true }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) {
- withAnimation(.spring(duration: 0.15)) { isPressed = false }
- }
- onSelect()
- }) {
- HStack(spacing: 8) {
- SessionStatusView(
- status: session.status,
- completedTasks: session.completedTaskCount,
- totalTasks: session.totalTaskCount,
- waitingReason: session.waitingReason
- )
-
- VStack(alignment: .leading, spacing: 2) {
- HStack(spacing: 4) {
- Text(session.projectName)
- .font(.system(size: 13, weight: isHovered ? .medium : .regular))
- .foregroundStyle(theme.primaryText)
- .lineLimit(1)
- if !session.model.isEmpty {
- SessionTagView(tag: session.model)
- }
- }
- if let desc = session.statusDescription {
- Text(desc)
- .font(.system(size: 11))
- .foregroundStyle(subtitleColor)
- .lineLimit(1)
- }
- }
-
- Spacer(minLength: 4)
-
- Text(relativeTime(session.updatedAt))
- .font(.system(size: 11, design: .monospaced))
- .foregroundStyle(theme.tertiaryText)
- }
- .padding(.leading, 6)
- .padding(.trailing, 10)
- .padding(.vertical, 5)
- .background(
- RoundedRectangle(cornerRadius: 5, style: .continuous)
- .fill(isPressed ? theme.pressedBackground
- : isHovered ? theme.hoverBackground
- : isPrimary ? theme.primaryText.opacity(0.06)
- : Color.clear)
- )
- .scaleEffect(isPressed ? 0.98 : 1.0)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .padding(.horizontal, 2)
- .onHover { hovering in
- withAnimation(.easeOut(duration: 0.12)) { isHovered = hovering }
- }
- }
-
- private var subtitleColor: Color {
- guard session.status == .needsInput else { return theme.secondaryText }
- return theme.waitingColor(for: session.waitingReason)
- }
-
- private func relativeTime(_ date: Date) -> String {
- let seconds = -date.timeIntervalSinceNow
- if seconds < 60 { return "now" }
- if seconds < 3600 { return "\(Int(seconds / 60))m" }
- if seconds < 86400 { return "\(Int(seconds / 3600))h" }
- if seconds < 604800 { return "\(Int(seconds / 86400))d" }
- return "\(Int(seconds / 604800))w"
- }
-}
diff --git a/Codync-macOS/Views/SessionTagView.swift b/Codync-macOS/Views/SessionTagView.swift
deleted file mode 100644
index 9038bb9c..00000000
--- a/Codync-macOS/Views/SessionTagView.swift
+++ /dev/null
@@ -1,18 +0,0 @@
-import SwiftUI
-
-struct SessionTagView: View {
- let tag: String
- @Environment(\.theme) private var theme
-
- var body: some View {
- Text(tag)
- .font(.system(size: 9, weight: .medium, design: .monospaced))
- .foregroundStyle(theme.tertiaryText)
- .padding(.horizontal, 4)
- .padding(.vertical, 1)
- .background(
- RoundedRectangle(cornerRadius: 3, style: .continuous)
- .fill(theme.border)
- )
- }
-}
diff --git a/Codync-macOS/Views/StatusDotView.swift b/Codync-macOS/Views/StatusDotView.swift
deleted file mode 100644
index 26144272..00000000
--- a/Codync-macOS/Views/StatusDotView.swift
+++ /dev/null
@@ -1,83 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-struct SessionStatusView: View {
- let status: SessionStatus
- let completedTasks: Int
- let totalTasks: Int
- var waitingReason: WaitingReason?
- @Environment(\.theme) private var theme
-
- private var hasTasks: Bool { totalTasks > 0 }
-
- var body: some View {
- if hasTasks {
- SegmentedRingView(
- completedCount: completedTasks,
- totalCount: totalTasks,
- isWorking: status == .working,
- fg: theme.primaryText,
- lineWidth: 1.5,
- gapDegrees: 24
- )
- .frame(width: 12, height: 12)
- } else if status == .working {
- ClaudeSparkleView()
- .frame(width: 14, height: 14)
- } else {
- MinimalDotView(status: status, waitingReason: waitingReason)
- }
- }
-}
-
-// MARK: - Minimal Dot
-
-private struct MinimalDotView: View {
- let status: SessionStatus
- var waitingReason: WaitingReason?
- @Environment(\.theme) private var theme
- @State private var isPulsing = false
-
- private var needsPulse: Bool { status == .needsInput || status == .error }
-
- var body: some View {
- Circle()
- .fill(dotColor)
- .frame(width: 7, height: 7)
- .frame(width: 14, height: 14)
- }
-
- private var dotColor: Color {
- switch status {
- case .needsInput, .error:
- return theme.waitingColor(for: waitingReason)
- case .idle: return theme.tertiaryText
- case .completed: return theme.tertiaryText.opacity(0.7)
- default: return theme.tertiaryText
- }
- }
-}
-
-// MARK: - Claude Sparkle
-
-struct ClaudeSparkleView: View {
- private static let phases: [String] = ["·", "✢", "✶", "✻", "✽"]
- private static let cycle: [String] = phases + phases.dropFirst().dropLast().reversed()
- @Environment(\.theme) private var theme
- @State private var currentIndex = 0
- private let timer = Timer.publish(every: 0.22, on: .main, in: .common).autoconnect()
-
- var body: some View {
- Text(Self.cycle[currentIndex])
- .font(.system(size: 12))
- .foregroundStyle(theme.primaryText.opacity(opacity))
- .onReceive(timer) { _ in
- currentIndex = (currentIndex + 1) % Self.cycle.count
- }
- }
-
- private var opacity: Double {
- let pos = Double(currentIndex) / Double(Self.cycle.count - 1)
- return 0.4 + sin(pos * .pi) * 0.6
- }
-}
diff --git a/Codync-macOS/Views/Theme.swift b/Codync-macOS/Views/Theme.swift
deleted file mode 100644
index 4a8da6bd..00000000
--- a/Codync-macOS/Views/Theme.swift
+++ /dev/null
@@ -1,110 +0,0 @@
-import SwiftUI
-import CodyncShared
-
-/// Codync design system inspired by Vercel/Cursor.
-/// Panel mode: pure black + single-source opacity hierarchy.
-/// Standard mode: light/dark adaptive colors.
-struct CodyncTheme: GlassThemeProvider, Sendable {
- let isDark: Bool
- let isPanel: Bool
-
- init(isDark: Bool, isPanel: Bool = false) {
- self.isDark = isDark
- self.isPanel = isPanel
- }
-
- // MARK: - Base foreground (single-source opacity system for panel)
-
- /// Panel uses #ededed as the single source color, varied by opacity.
- private static let panelForeground = Color(red: 0.93, green: 0.93, blue: 0.93)
-
- // MARK: - Backgrounds
-
- var background: Color {
- if isPanel { return isDark ? .black : Color(red: 0.95, green: 0.95, blue: 0.96) }
- return isDark ? Color(red: 0.11, green: 0.11, blue: 0.12) : .white
- }
-
- var glassBackground: Color {
- isDark ? Color.white.opacity(0.05) : Color.white.opacity(0.70)
- }
-
- /// Elevated surface for cards/stats — Vercel uses #111 or white 4-5%
- var cardBackground: Color {
- if isPanel { return .white.opacity(0.10) }
- return isDark ? .white.opacity(0.05) : .black.opacity(0.03)
- }
-
- /// Hover/press state — Cursor uses white 6%
- var hoverBackground: Color {
- if isPanel { return .white.opacity(0.06) }
- return isDark ? .white.opacity(0.06) : .black.opacity(0.04)
- }
-
- var pressedBackground: Color {
- if isPanel { return .white.opacity(0.10) }
- return isDark ? .white.opacity(0.10) : .black.opacity(0.08)
- }
-
- // MARK: - Text hierarchy (opacity-based for panel)
-
- var primaryText: Color {
- if isPanel { return Self.panelForeground }
- return isDark ? Color(red: 0.93, green: 0.93, blue: 0.93) : Color(red: 0.11, green: 0.11, blue: 0.12)
- }
-
- /// 55% opacity — Cursor's secondary text
- var secondaryText: Color {
- if isPanel { return Self.panelForeground.opacity(0.55) }
- return isDark ? .white.opacity(0.55) : .black.opacity(0.50)
- }
-
- /// 35% opacity — captions, timestamps
- var tertiaryText: Color {
- if isPanel { return Self.panelForeground.opacity(0.35) }
- return isDark ? .white.opacity(0.35) : .black.opacity(0.35)
- }
-
- // MARK: - Borders & separators — Vercel uses #242424 ≈ white 8%
-
- var separator: Color {
- if isPanel { return .white.opacity(0.08) }
- return isDark ? .white.opacity(0.10) : .black.opacity(0.08)
- }
-
- var border: Color {
- if isPanel { return .white.opacity(0.08) }
- return isDark ? .white.opacity(0.10) : .black.opacity(0.10)
- }
-
- var borderHover: Color {
- if isPanel { return .white.opacity(0.15) }
- return isDark ? .white.opacity(0.18) : .black.opacity(0.18)
- }
-
- // MARK: - Semantic colors
-
- var accent: Color { primaryText }
-
- var warning: Color { primaryText }
- var danger: Color { primaryText }
-
- /// Color for a waiting session based on its reason.
- /// Permission prompt = danger (red), everything else = warning (yellow/orange).
- func waitingColor(for reason: WaitingReason?) -> Color {
- reason?.isPermission == true ? danger : warning
- }
-}
-
-// MARK: - Environment
-
-private struct ThemeKey: EnvironmentKey {
- static let defaultValue = CodyncTheme(isDark: false)
-}
-
-extension EnvironmentValues {
- var theme: CodyncTheme {
- get { self[ThemeKey.self] }
- set { self[ThemeKey.self] = newValue }
- }
-}
diff --git a/Codync.xcodeproj/project.pbxproj b/Codync.xcodeproj/project.pbxproj
index f76c9690..a3b3d9b9 100644
--- a/Codync.xcodeproj/project.pbxproj
+++ b/Codync.xcodeproj/project.pbxproj
@@ -3,87 +3,53 @@
archiveVersion = 1;
classes = {
};
- objectVersion = 63;
+ objectVersion = 77;
objects = {
/* Begin PBXBuildFile section */
- 0205D611148BDCAB840D0F47 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9580D32B5B29E049090D66C8 /* Assets.xcassets */; };
- 0294408FF2BC2367453C118C /* SessionListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA699D0197B8A14FD7D1BDC4 /* SessionListView.swift */; };
- 070688CBF55E74F38DC650E3 /* CodyncShared in Frameworks */ = {isa = PBXBuildFile; productRef = 4BA154F0B1967DCBBB7600E5 /* CodyncShared */; };
- 0B6B1D4B20837A47EAF88322 /* IOSSessionDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C01C9748A39F3475869F956 /* IOSSessionDetailView.swift */; };
- 0CFFA94EEF8F4C33AB86012A /* YouTubePlayerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3716B87C0A7249268846AB6C /* YouTubePlayerView.swift */; };
- 106A1E305D6DBDFC35AF01BD /* CloudKitSync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22479FA0953120F3B50A1AF3 /* CloudKitSync.swift */; };
- 1122334455667788AABBCCDD /* CodyncPanelShape.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABBCCDD11223344556677EE /* CodyncPanelShape.swift */; };
- 21DBF9BED5F40E2F671CB1F9 /* StatusDotView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEED6193555CB3FAC1BA7E2A /* StatusDotView.swift */; };
- 3DC7D9E7E79444359ED6D09F /* ClaudePaths.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F1E5418D5496E651BD58FA2 /* ClaudePaths.swift */; };
- 4450C6683BA7614D2DBB5E55 /* MenuBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C55AF6C89E20B6FD1CF5CD4 /* MenuBarController.swift */; };
- 6A5A77C9C3AF37A8E371F5CB /* SessionStateManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = F71E03612F167D883C324D25 /* SessionStateManager.swift */; };
- 73382915E3200DDC5EF16C2F /* SessionFileParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = A19BA18A6829F0BE991D4C7D /* SessionFileParser.swift */; };
- 7534D98B6CDF84E44B0D25A9 /* CloudKitReceiver.swift in Sources */ = {isa = PBXBuildFile; fileRef = F19A27E00B1B13A579A950F4 /* CloudKitReceiver.swift */; };
- 7851B112737C5DD8B8C3380C /* JSONLTailReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05154CFD496486BA9E126E9D /* JSONLTailReader.swift */; };
- 804863D604952293533147CF /* CodyncLiveActivity.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 3B652652FD106495A82565C8 /* CodyncLiveActivity.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
- 911C6ABDB9539A60844931F2 /* PIDChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D161FDC49BE96E3A73FEA33 /* PIDChecker.swift */; };
- A30C11E610763F5064698D43 /* IOSSessionListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A01A225437E7A00B3337883E /* IOSSessionListView.swift */; };
- A3F82B14C7E94D61B0E53D92 /* LiveActivityPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6D91C43F0A24E87A2C74F56 /* LiveActivityPreview.swift */; };
- A98E0466D559EC6EBE0E39F4 /* ClaudeHookServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = E25C5CD874B7119D57AB2BB1 /* ClaudeHookServer.swift */; };
- APNS0001D559EC6EBE0E39F4 /* APNsPushService.swift in Sources */ = {isa = PBXBuildFile; fileRef = APNS0002D559EC6EBE0E39F4 /* APNsPushService.swift */; };
- APNS0003D559EC6EBE0E39F4 /* APNsSecrets.swift in Sources */ = {isa = PBXBuildFile; fileRef = APNS0004D559EC6EBE0E39F4 /* APNsSecrets.swift */; };
- B1C2D3E4F5A6B7C8D9E0F1A1 /* IOSTheme.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1A1 /* IOSTheme.swift */; };
- B1C2D3E4F5A6B7C8D9E0F1A2 /* IOSStatusIndicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1A2 /* IOSStatusIndicator.swift */; };
- B1C2D3E4F5A6B7C8D9E0F1A3 /* IOSSessionTagView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1A3 /* IOSSessionTagView.swift */; };
- B575261E2F89280C4805C654 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3935CEE144EC8AFCA3AEAEA3 /* Assets.xcassets */; };
- B8C9D0E1F2A3B4C5D6E7F8A9 /* ComingSoonView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7B8C9D0E1F2A3B4C5D6E7F8 /* ComingSoonView.swift */; };
- BB50434DF1BC51FED1AFED51 /* CodyncLiveActivityWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A9A7BAE27F6E4CEEDA1B48D /* CodyncLiveActivityWidget.swift */; };
- BF17F10AC69617C12975E0EB /* SessionDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D10CABFC27BF22D45064777A /* SessionDetailView.swift */; };
- C4D5E6F7A8B9C0D1E2F3A4B5 /* Theme.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5E6F7A8B9C0D1E2F3A4B5C6 /* Theme.swift */; };
- C7E108B87747D1CB7E7E1699 /* CodyncShared in Frameworks */ = {isa = PBXBuildFile; productRef = C1CA2B270135307CC4E2724D /* CodyncShared */; };
- D2A3B4C5E6F7081920314253 /* TranscriptWatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3C4D5E6F708192A3B4C5D6E /* TranscriptWatcher.swift */; };
- D4BC114BC4A6C08EECD54925 /* CodyncShared in Frameworks */ = {isa = PBXBuildFile; productRef = 7660B5D6DD8CC2065A9F4ED3 /* CodyncShared */; };
- D4E5F6A7B8C9D0E1F2A3B4C5 /* PrimarySessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3D4E5F6A7B8C9D0E1F2A3B4 /* PrimarySessionManager.swift */; };
- DBD957B5BFDEC3B62B310F8F /* IOSRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF291DF4A4EF932B774F227D /* IOSRootView.swift */; };
- DD44EE55FF66001122334455 /* CodyncPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA11BB22CC33DD44EE55FF66 /* CodyncPanel.swift */; };
- E1740D692C1C19693058D20B /* SessionRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD09204E8CD3C16D75BA3048 /* SessionRowView.swift */; };
- E36D87A2D2D0F1177F263772 /* CodyncLiveActivityBundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BCD1168005B123A7F9ACB37 /* CodyncLiveActivityBundle.swift */; };
- EB132AF39AB968D2DFA6151B /* CodyncApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A67A3CD19408484AB11BB73 /* CodyncApp.swift */; };
- EDCB66A65FD85B26FE7B4664 /* SessionScanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42BAF66F7C50D732B7E69333 /* SessionScanner.swift */; };
- EE55FF6600112233445566AA /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB22CC33DD44EE55FF660011 /* EventMonitor.swift */; };
- EEF78145300C2A3547AD832A /* IOSOnboardingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D866EFD6224AECD6846B76BE /* IOSOnboardingView.swift */; };
- EF0A0CEAD3C7B875064F8556 /* LiveActivityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADC1A963B2C1124F480F9CE /* LiveActivityManager.swift */; };
- F1E2D3C4B5A6F7E8D9C0B1A2 /* SessionTagView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1F2 /* SessionTagView.swift */; };
- F4F54F91459EE6A15DD7B246 /* CodyncIOSApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8453D8BE6EE838E1B9EA4588 /* CodyncIOSApp.swift */; };
- F5A6B7C8D9E0F1A2B3C4D5E6 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5A6B7C8D9E0F1A2B3C4D5E7 /* AppDelegate.swift */; };
- F6A7B8C9D0E1F2A3B4C5D6E7 /* TabRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5F6A7B8C9D0E1F2A3B4C5D6 /* TabRootView.swift */; };
- F7407323258F4D54ABC49AA7 /* ModePillToggle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D38EB22B9A74DB4A5A84274 /* ModePillToggle.swift */; };
- FF66001122334455667788BB /* NSScreen+Notch.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC33DD44EE55FF6600112233 /* NSScreen+Notch.swift */; };
- PANEL001122334455667788 /* PanelHeaderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = PANEL002233445566778899 /* PanelHeaderView.swift */; };
- PM0001A0B1C2D3E4F5A6B7C8 /* PremiumManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = PM0002A0B1C2D3E4F5A6B7C8 /* PremiumManager.swift */; };
- RCS00100B1C2D3E4F5A6B7C8 /* RevenueCatSecrets.swift in Sources */ = {isa = PBXBuildFile; fileRef = RCS00200B1C2D3E4F5A6B7C8 /* RevenueCatSecrets.swift */; };
- PW0001A0B1C2D3E4F5A6B7C8 /* PaywallView.swift in Sources */ = {isa = PBXBuildFile; fileRef = PW0002A0B1C2D3E4F5A6B7C8 /* PaywallView.swift */; };
- RC0001A0B1C2D3E4F5A6B7C8 /* RevenueCat in Frameworks */ = {isa = PBXBuildFile; productRef = RC0003A0B1C2D3E4F5A6B7C8 /* RevenueCat */; };
- RC0002A0B1C2D3E4F5A6B7C8 /* RevenueCatUI in Frameworks */ = {isa = PBXBuildFile; productRef = RC0004A0B1C2D3E4F5A6B7C8 /* RevenueCatUI */; };
- SV0001A0B1C2D3E4F5A6B7C8 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = SV0002A0B1C2D3E4F5A6B7C8 /* SettingsView.swift */; };
- FW0001A0B1C2D3E4F5A6B7C8 /* FreeWarningSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = FW0002A0B1C2D3E4F5A6B7C8 /* FreeWarningSheet.swift */; };
- SE0001A0B1C2D3E4F5A6B7C8 /* SyncErrorSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = SE0002A0B1C2D3E4F5A6B7C8 /* SyncErrorSheet.swift */; };
+ 07670DD412E0F79796D44699 /* BotListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 371D72CCCB665E6442DED8C8 /* BotListView.swift */; };
+ 087DC53315FB092D4F6436AD /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EBEF05AFCCF44C92BDA91A3 /* RootView.swift */; };
+ 187068689418B6B25AE7B26A /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B274A0195CB3B2409EA4C194 /* WidgetKit.framework */; };
+ 1BD8A64454E95EF3726132A4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9FCF7D2E2AEC8C83B89E7B36 /* Assets.xcassets */; };
+ 1C2298904CADCA68ADF64F6B /* CodyncWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = E70F8B0E7E2E15AAA8A2A0A7 /* CodyncWidgets.swift */; };
+ 2C21D097FD9AF73AE3B40DDE /* MarkdownText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 417B586A0D9A447747D1BEFC /* MarkdownText.swift */; };
+ 341AB84FEF28FF194872D861 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = CDE38864BDC425F1240E1C02 /* CodyncKit */; };
+ 4F70D744ED9A696854EADA91 /* TraceView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A9EEFF0BB95647BE483A211 /* TraceView.swift */; };
+ 55D43F0D178B7A63BA4E81F3 /* CodyncWidgets.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 04030896973C4041E7FEB319 /* CodyncWidgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
+ 575ABFE8E1FBD2865793F45D /* AppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 092242ADE0E7FF8A82051511 /* AppModel.swift */; };
+ 61455BFB935FE1AAF67C4CD4 /* Push.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74E27E10BA8F07E552E99BE9 /* Push.swift */; };
+ 745062481B4868CF3F2950BF /* BotEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF5B67443AC77DA4414E6EBE /* BotEditorView.swift */; };
+ 76E613DFEABF73915C5FE9DC /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = AF5474468D6EBF22CB2FA1E9 /* Assets.xcassets */; };
+ 989285CFB52552A97D95366C /* PairingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 528534881700FE0CF94A49BC /* PairingView.swift */; };
+ 9D644515BB782DC91B1B71C8 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD4B599F142017103B340A87 /* SettingsView.swift */; };
+ CED43A6F2ED71E48C95E9E38 /* HostController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01C28522569623733B9B096D /* HostController.swift */; };
+ CEFE64EFFEA10B5ED60F2CE3 /* CodyncApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3FCD76B514C8ECF2211945A /* CodyncApp.swift */; };
+ D667C45D828CAD079A2EDD77 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4364B5D2EE15CB00ACF26E5D /* CodyncKit */; };
+ D8E9E7B47361EEE30424455F /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 234AA35A60DF7D3E6D7CA45E /* CodyncKit */; };
+ DC0510188C0A2C8FAEA5CC8D /* ThreadView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C70DB39404824DBE6E38B94C /* ThreadView.swift */; };
+ ED9C1500FD1CC591FCBD26CB /* CodyncMacApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 280FA54859773B9355860354 /* CodyncMacApp.swift */; };
+ FB33CDB6D44A6023BB565200 /* PermissionCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31D94A23B2E38E9DE6CAA984 /* PermissionCard.swift */; };
+ FEEBCD214CE268A636921FD9 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1E47C60032C326157E0386B8 /* SwiftUI.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
- B38F144A3A8B56B1FC2398CE /* PBXContainerItemProxy */ = {
+ 65AAB675493CB6BE712818A9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
- containerPortal = 755EE78C119E5281024E6F90 /* Project object */;
+ containerPortal = 5B6351DD20AF4506794D6460 /* Project object */;
proxyType = 1;
- remoteGlobalIDString = 6B3B927655EA5C595A71E513;
- remoteInfo = CodyncLiveActivity;
+ remoteGlobalIDString = 95A633B0E0FD05A1D35CA468;
+ remoteInfo = CodyncWidgets;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
- FC965E0F58168E06F093EAB5 /* Embed Foundation Extensions */ = {
+ AA3D7E40FB2438A6CD2D3DE7 /* Embed Foundation Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 13;
files = (
- 804863D604952293533147CF /* CodyncLiveActivity.appex in Embed Foundation Extensions */,
+ 55D43F0D178B7A63BA4E81F3 /* CodyncWidgets.appex in Embed Foundation Extensions */,
);
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
@@ -91,340 +57,248 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
- 05154CFD496486BA9E126E9D /* JSONLTailReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONLTailReader.swift; sourceTree = "<group>"; };
- 0D161FDC49BE96E3A73FEA33 /* PIDChecker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PIDChecker.swift; sourceTree = "<group>"; };
- 22479FA0953120F3B50A1AF3 /* CloudKitSync.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudKitSync.swift; sourceTree = "<group>"; };
- 3716B87C0A7249268846AB6C /* YouTubePlayerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YouTubePlayerView.swift; sourceTree = "<group>"; };
- 3935CEE144EC8AFCA3AEAEA3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
- 3B652652FD106495A82565C8 /* CodyncLiveActivity.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = CodyncLiveActivity.appex; sourceTree = BUILT_PRODUCTS_DIR; };
- 3BCD1168005B123A7F9ACB37 /* CodyncLiveActivityBundle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncLiveActivityBundle.swift; sourceTree = "<group>"; };
- 3EB0548BFADFAFC3616A8C4B /* Codync.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Codync.app; sourceTree = BUILT_PRODUCTS_DIR; };
- 42BAF66F7C50D732B7E69333 /* SessionScanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionScanner.swift; sourceTree = "<group>"; };
- 433D534BFD8D3D76B489B324 /* Codync-iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "Codync-iOS.entitlements"; sourceTree = "<group>"; };
- 4A67A3CD19408484AB11BB73 /* CodyncApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncApp.swift; sourceTree = "<group>"; };
- 4C55AF6C89E20B6FD1CF5CD4 /* MenuBarController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MenuBarController.swift; sourceTree = "<group>"; };
- 8453D8BE6EE838E1B9EA4588 /* CodyncIOSApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncIOSApp.swift; sourceTree = "<group>"; };
- 8A9A7BAE27F6E4CEEDA1B48D /* CodyncLiveActivityWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncLiveActivityWidget.swift; sourceTree = "<group>"; };
- 8B5EA7075E9DC97237EF2227 /* Codync.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Codync.app; sourceTree = BUILT_PRODUCTS_DIR; };
- 8F1E5418D5496E651BD58FA2 /* ClaudePaths.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudePaths.swift; sourceTree = "<group>"; };
- 9580D32B5B29E049090D66C8 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
- 9C01C9748A39F3475869F956 /* IOSSessionDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSSessionDetailView.swift; sourceTree = "<group>"; };
- 9D38EB22B9A74DB4A5A84274 /* ModePillToggle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModePillToggle.swift; sourceTree = "<group>"; };
- A01A225437E7A00B3337883E /* IOSSessionListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSSessionListView.swift; sourceTree = "<group>"; };
- A19BA18A6829F0BE991D4C7D /* SessionFileParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionFileParser.swift; sourceTree = "<group>"; };
- A1B2C3D4E5F6A7B8C9D0E1A1 /* IOSTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSTheme.swift; sourceTree = "<group>"; };
- A1B2C3D4E5F6A7B8C9D0E1A2 /* IOSStatusIndicator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSStatusIndicator.swift; sourceTree = "<group>"; };
- A1B2C3D4E5F6A7B8C9D0E1A3 /* IOSSessionTagView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSSessionTagView.swift; sourceTree = "<group>"; };
- A1B2C3D4E5F6A7B8C9D0E1F2 /* SessionTagView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionTagView.swift; sourceTree = "<group>"; };
- A7B8C9D0E1F2A3B4C5D6E7F8 /* ComingSoonView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComingSoonView.swift; sourceTree = "<group>"; };
- AA11BB22CC33DD44EE55FF66 /* CodyncPanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncPanel.swift; sourceTree = "<group>"; };
- AABBCCDD11223344556677EE /* CodyncPanelShape.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncPanelShape.swift; sourceTree = "<group>"; };
- AB156A392F6DC850001D15CE /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
- AD09204E8CD3C16D75BA3048 /* SessionRowView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionRowView.swift; sourceTree = "<group>"; };
- APNS0002D559EC6EBE0E39F4 /* APNsPushService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APNsPushService.swift; sourceTree = "<group>"; };
- APNS0004D559EC6EBE0E39F4 /* APNsSecrets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APNsSecrets.swift; sourceTree = "<group>"; };
- B3C4D5E6F708192A3B4C5D6E /* TranscriptWatcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TranscriptWatcher.swift; sourceTree = "<group>"; };
- B6D91C43F0A24E87A2C74F56 /* LiveActivityPreview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveActivityPreview.swift; sourceTree = "<group>"; };
- BB22CC33DD44EE55FF660011 /* EventMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventMonitor.swift; sourceTree = "<group>"; };
- C3D4E5F6A7B8C9D0E1F2A3B4 /* PrimarySessionManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimarySessionManager.swift; sourceTree = "<group>"; };
- CADC1A963B2C1124F480F9CE /* LiveActivityManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveActivityManager.swift; sourceTree = "<group>"; };
- CC33DD44EE55FF6600112233 /* NSScreen+Notch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSScreen+Notch.swift"; sourceTree = "<group>"; };
- CD5A99B72DC7E1F01D755DF6 /* Codync.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Codync.entitlements; sourceTree = "<group>"; };
- CEED6193555CB3FAC1BA7E2A /* StatusDotView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusDotView.swift; sourceTree = "<group>"; };
- D10CABFC27BF22D45064777A /* SessionDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionDetailView.swift; sourceTree = "<group>"; };
- D5E6F7A8B9C0D1E2F3A4B5C6 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = "<group>"; };
- D866EFD6224AECD6846B76BE /* IOSOnboardingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSOnboardingView.swift; sourceTree = "<group>"; };
- DA699D0197B8A14FD7D1BDC4 /* SessionListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionListView.swift; sourceTree = "<group>"; };
- DF291DF4A4EF932B774F227D /* IOSRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSRootView.swift; sourceTree = "<group>"; };
- E25C5CD874B7119D57AB2BB1 /* ClaudeHookServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeHookServer.swift; sourceTree = "<group>"; };
- E5F6A7B8C9D0E1F2A3B4C5D6 /* TabRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TabRootView.swift; sourceTree = "<group>"; };
- F033CA1408917B1655BC66D2 /* CodyncShared */ = {isa = PBXFileReference; lastKnownFileType = folder; path = CodyncShared; sourceTree = SOURCE_ROOT; };
- F19A27E00B1B13A579A950F4 /* CloudKitReceiver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudKitReceiver.swift; sourceTree = "<group>"; };
- F5A6B7C8D9E0F1A2B3C4D5E7 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
- F71E03612F167D883C324D25 /* SessionStateManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionStateManager.swift; sourceTree = "<group>"; };
- PANEL002233445566778899 /* PanelHeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PanelHeaderView.swift; sourceTree = "<group>"; };
- PM0002A0B1C2D3E4F5A6B7C8 /* PremiumManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PremiumManager.swift; sourceTree = "<group>"; };
- RCS00200B1C2D3E4F5A6B7C8 /* RevenueCatSecrets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RevenueCatSecrets.swift; sourceTree = "<group>"; };
- PW0002A0B1C2D3E4F5A6B7C8 /* PaywallView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PaywallView.swift; sourceTree = "<group>"; };
- SV0002A0B1C2D3E4F5A6B7C8 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
- FW0002A0B1C2D3E4F5A6B7C8 /* FreeWarningSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FreeWarningSheet.swift; sourceTree = "<group>"; };
- SE0002A0B1C2D3E4F5A6B7C8 /* SyncErrorSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncErrorSheet.swift; sourceTree = "<group>"; };
+ 01C28522569623733B9B096D /* HostController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostController.swift; sourceTree = "<group>"; };
+ 04030896973C4041E7FEB319 /* CodyncWidgets.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = CodyncWidgets.appex; sourceTree = BUILT_PRODUCTS_DIR; };
+ 092242ADE0E7FF8A82051511 /* AppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppModel.swift; sourceTree = "<group>"; };
+ 155F1B6DC4518164BE2C527F /* Codync-macOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Codync-macOS.app"; sourceTree = BUILT_PRODUCTS_DIR; };
+ 1753C1409D62F8F721BE833F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
+ 1E47C60032C326157E0386B8 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };
+ 280FA54859773B9355860354 /* CodyncMacApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncMacApp.swift; sourceTree = "<group>"; };
+ 2A9EEFF0BB95647BE483A211 /* TraceView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TraceView.swift; sourceTree = "<group>"; };
+ 31D94A23B2E38E9DE6CAA984 /* PermissionCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PermissionCard.swift; sourceTree = "<group>"; };
+ 371D72CCCB665E6442DED8C8 /* BotListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotListView.swift; sourceTree = "<group>"; };
+ 38FE26380B2072AE3FBD5CF5 /* CodyncWidgets.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = CodyncWidgets.entitlements; sourceTree = "<group>"; };
+ 417B586A0D9A447747D1BEFC /* MarkdownText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownText.swift; sourceTree = "<group>"; };
+ 528534881700FE0CF94A49BC /* PairingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingView.swift; sourceTree = "<group>"; };
+ 6CCA896856A480F390EBA9AB /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
+ 6EBEF05AFCCF44C92BDA91A3 /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };
+ 74E27E10BA8F07E552E99BE9 /* Push.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Push.swift; sourceTree = "<group>"; };
+ 835DB0566D924C508E360B8F /* CodyncKit */ = {isa = PBXFileReference; lastKnownFileType = folder; name = CodyncKit; path = CodyncKit; sourceTree = SOURCE_ROOT; };
+ 84B947AD5A042EA315737BBC /* Codync-iOS.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = "Codync-iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; };
+ 9FCF7D2E2AEC8C83B89E7B36 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ A30032680EAD00ABD06D30BE /* Codync-iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "Codync-iOS.entitlements"; sourceTree = "<group>"; };
+ A3FCD76B514C8ECF2211945A /* CodyncApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncApp.swift; sourceTree = "<group>"; };
+ AF5474468D6EBF22CB2FA1E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ AF5B67443AC77DA4414E6EBE /* BotEditorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotEditorView.swift; sourceTree = "<group>"; };
+ B274A0195CB3B2409EA4C194 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };
+ C70DB39404824DBE6E38B94C /* ThreadView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThreadView.swift; sourceTree = "<group>"; };
+ CD4B599F142017103B340A87 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
+ E70F8B0E7E2E15AAA8A2A0A7 /* CodyncWidgets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncWidgets.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
- 33BB45F688B4E120B83A8B95 /* Frameworks */ = {
+ 23D362028BD4C2D187672C6B /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- D4BC114BC4A6C08EECD54925 /* CodyncShared in Frameworks */,
+ 341AB84FEF28FF194872D861 /* CodyncKit in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- B751B672F1F83A923532F25D /* Frameworks */ = {
+ BC19FCC84D9B1AF54A43BDB1 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- 070688CBF55E74F38DC650E3 /* CodyncShared in Frameworks */,
+ D8E9E7B47361EEE30424455F /* CodyncKit in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- EBDCA5828CAAF005C11D4017 /* Frameworks */ = {
+ F84176A6E29D7445556D4800 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- C7E108B87747D1CB7E7E1699 /* CodyncShared in Frameworks */,
- RC0001A0B1C2D3E4F5A6B7C8 /* RevenueCat in Frameworks */,
- RC0002A0B1C2D3E4F5A6B7C8 /* RevenueCatUI in Frameworks */,
+ D667C45D828CAD079A2EDD77 /* CodyncKit in Frameworks */,
+ 187068689418B6B25AE7B26A /* WidgetKit.framework in Frameworks */,
+ FEEBCD214CE268A636921FD9 /* SwiftUI.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
- 04721CC753DB3D170E2C8A15 /* Products */ = {
+ 3B3D0635CC47A804415E49C9 /* Frameworks */ = {
isa = PBXGroup;
children = (
- 3EB0548BFADFAFC3616A8C4B /* Codync.app */,
- 8B5EA7075E9DC97237EF2227 /* Codync.app */,
- 3B652652FD106495A82565C8 /* CodyncLiveActivity.appex */,
+ 1E47C60032C326157E0386B8 /* SwiftUI.framework */,
+ B274A0195CB3B2409EA4C194 /* WidgetKit.framework */,
);
- name = Products;
+ name = Frameworks;
sourceTree = "<group>";
};
- 0C96AC38D8727BFA29C5A3C2 /* Codync-iOS */ = {
+ 3EC1FDCCFFFB4BA1A23FDDB0 /* Products */ = {
isa = PBXGroup;
children = (
- AB156A392F6DC850001D15CE /* Info.plist */,
- 9580D32B5B29E049090D66C8 /* Assets.xcassets */,
- 1826180B05CCD48B46767A6C /* App */,
- BF38CE6E12412C3D21C0B979 /* Services */,
- 32B90F722211C6377233886C /* Views */,
+ 84B947AD5A042EA315737BBC /* Codync-iOS.app */,
+ 155F1B6DC4518164BE2C527F /* Codync-macOS.app */,
+ 04030896973C4041E7FEB319 /* CodyncWidgets.appex */,
);
- path = "Codync-iOS";
+ name = Products;
sourceTree = "<group>";
};
- 1826180B05CCD48B46767A6C /* App */ = {
+ A5F024E89FF18E86F969369F /* CodyncWidgets */ = {
isa = PBXGroup;
children = (
- 433D534BFD8D3D76B489B324 /* Codync-iOS.entitlements */,
- F5A6B7C8D9E0F1A2B3C4D5E7 /* AppDelegate.swift */,
- 8453D8BE6EE838E1B9EA4588 /* CodyncIOSApp.swift */,
+ 38FE26380B2072AE3FBD5CF5 /* CodyncWidgets.entitlements */,
+ E70F8B0E7E2E15AAA8A2A0A7 /* CodyncWidgets.swift */,
+ 1753C1409D62F8F721BE833F /* Info.plist */,
);
- path = App;
+ path = CodyncWidgets;
sourceTree = "<group>";
};
- 1A0CEB1937DE4129AB71C6FC /* Components */ = {
+ AD54741A2330C502CD3BB628 /* Packages */ = {
isa = PBXGroup;
children = (
- 9D38EB22B9A74DB4A5A84274 /* ModePillToggle.swift */,
- B6D91C43F0A24E87A2C74F56 /* LiveActivityPreview.swift */,
+ 835DB0566D924C508E360B8F /* CodyncKit */,
);
- path = Components;
+ name = Packages;
sourceTree = "<group>";
};
- 32B90F722211C6377233886C /* Views */ = {
+ C9B7D3953422AE726DDC6347 = {
isa = PBXGroup;
children = (
- 1A0CEB1937DE4129AB71C6FC /* Components */,
- A7B8C9D0E1F2A3B4C5D6E7F8 /* ComingSoonView.swift */,
- PW0002A0B1C2D3E4F5A6B7C8 /* PaywallView.swift */,
- FW0002A0B1C2D3E4F5A6B7C8 /* FreeWarningSheet.swift */,
- SE0002A0B1C2D3E4F5A6B7C8 /* SyncErrorSheet.swift */,
- SV0002A0B1C2D3E4F5A6B7C8 /* SettingsView.swift */,
- D866EFD6224AECD6846B76BE /* IOSOnboardingView.swift */,
- 3716B87C0A7249268846AB6C /* YouTubePlayerView.swift */,
- DF291DF4A4EF932B774F227D /* IOSRootView.swift */,
- 9C01C9748A39F3475869F956 /* IOSSessionDetailView.swift */,
- A01A225437E7A00B3337883E /* IOSSessionListView.swift */,
- A1B2C3D4E5F6A7B8C9D0E1A1 /* IOSTheme.swift */,
- A1B2C3D4E5F6A7B8C9D0E1A2 /* IOSStatusIndicator.swift */,
- A1B2C3D4E5F6A7B8C9D0E1A3 /* IOSSessionTagView.swift */,
- E5F6A7B8C9D0E1F2A3B4C5D6 /* TabRootView.swift */,
+ E096D8F5E751972A522C83C9 /* Codync-iOS */,
+ D268A75203C21E1F0385AB59 /* Codync-macOS */,
+ A5F024E89FF18E86F969369F /* CodyncWidgets */,
+ AD54741A2330C502CD3BB628 /* Packages */,
+ 3B3D0635CC47A804415E49C9 /* Frameworks */,
+ 3EC1FDCCFFFB4BA1A23FDDB0 /* Products */,
);
- path = Views;
sourceTree = "<group>";
};
- 38DD3C2C943D4DCC5208E8BB /* Codync-macOS */ = {
+ D268A75203C21E1F0385AB59 /* Codync-macOS */ = {
isa = PBXGroup;
children = (
- 3935CEE144EC8AFCA3AEAEA3 /* Assets.xcassets */,
- A938E4429F7EF26E67792A2E /* App */,
- BF668ADCDAD9595E867B23D0 /* Services */,
- 3FCF1C54EE1B71553A70301E /* Utilities */,
- 81EF17B3D3346D74A837F710 /* Views */,
+ 9FCF7D2E2AEC8C83B89E7B36 /* Assets.xcassets */,
+ 280FA54859773B9355860354 /* CodyncMacApp.swift */,
+ 01C28522569623733B9B096D /* HostController.swift */,
);
path = "Codync-macOS";
sourceTree = "<group>";
};
- 3FCF1C54EE1B71553A70301E /* Utilities */ = {
- isa = PBXGroup;
- children = (
- 8F1E5418D5496E651BD58FA2 /* ClaudePaths.swift */,
- 05154CFD496486BA9E126E9D /* JSONLTailReader.swift */,
- 0D161FDC49BE96E3A73FEA33 /* PIDChecker.swift */,
- );
- path = Utilities;
- sourceTree = "<group>";
- };
- 5B3C3F020EFA3298682EBB4D /* CodyncLiveActivity */ = {
+ E096D8F5E751972A522C83C9 /* Codync-iOS */ = {
isa = PBXGroup;
children = (
- 3BCD1168005B123A7F9ACB37 /* CodyncLiveActivityBundle.swift */,
- 8A9A7BAE27F6E4CEEDA1B48D /* CodyncLiveActivityWidget.swift */,
+ AF5474468D6EBF22CB2FA1E9 /* Assets.xcassets */,
+ A30032680EAD00ABD06D30BE /* Codync-iOS.entitlements */,
+ 6CCA896856A480F390EBA9AB /* Info.plist */,
+ F474B3D70851CF6BC24ED9DE /* App */,
+ EE65F2FAD6D95ABE28885E83 /* Views */,
);
- path = CodyncLiveActivity;
+ path = "Codync-iOS";
sourceTree = "<group>";
};
- 81EF17B3D3346D74A837F710 /* Views */ = {
+ EE65F2FAD6D95ABE28885E83 /* Views */ = {
isa = PBXGroup;
children = (
- PANEL002233445566778899 /* PanelHeaderView.swift */,
- D10CABFC27BF22D45064777A /* SessionDetailView.swift */,
- DA699D0197B8A14FD7D1BDC4 /* SessionListView.swift */,
- AD09204E8CD3C16D75BA3048 /* SessionRowView.swift */,
- A1B2C3D4E5F6A7B8C9D0E1F2 /* SessionTagView.swift */,
- CEED6193555CB3FAC1BA7E2A /* StatusDotView.swift */,
- D5E6F7A8B9C0D1E2F3A4B5C6 /* Theme.swift */,
+ AF5B67443AC77DA4414E6EBE /* BotEditorView.swift */,
+ 371D72CCCB665E6442DED8C8 /* BotListView.swift */,
+ 417B586A0D9A447747D1BEFC /* MarkdownText.swift */,
+ 528534881700FE0CF94A49BC /* PairingView.swift */,
+ 31D94A23B2E38E9DE6CAA984 /* PermissionCard.swift */,
+ 6EBEF05AFCCF44C92BDA91A3 /* RootView.swift */,
+ CD4B599F142017103B340A87 /* SettingsView.swift */,
+ C70DB39404824DBE6E38B94C /* ThreadView.swift */,
+ 2A9EEFF0BB95647BE483A211 /* TraceView.swift */,
);
path = Views;
sourceTree = "<group>";
};
- A938E4429F7EF26E67792A2E /* App */ = {
+ F474B3D70851CF6BC24ED9DE /* App */ = {
isa = PBXGroup;
children = (
- CD5A99B72DC7E1F01D755DF6 /* Codync.entitlements */,
- 4A67A3CD19408484AB11BB73 /* CodyncApp.swift */,
- AABBCCDD11223344556677EE /* CodyncPanelShape.swift */,
- AA11BB22CC33DD44EE55FF66 /* CodyncPanel.swift */,
- BB22CC33DD44EE55FF660011 /* EventMonitor.swift */,
- 4C55AF6C89E20B6FD1CF5CD4 /* MenuBarController.swift */,
- CC33DD44EE55FF6600112233 /* NSScreen+Notch.swift */,
+ 092242ADE0E7FF8A82051511 /* AppModel.swift */,
+ A3FCD76B514C8ECF2211945A /* CodyncApp.swift */,
+ 74E27E10BA8F07E552E99BE9 /* Push.swift */,
);
path = App;
sourceTree = "<group>";
};
- BF38CE6E12412C3D21C0B979 /* Services */ = {
- isa = PBXGroup;
- children = (
- F19A27E00B1B13A579A950F4 /* CloudKitReceiver.swift */,
- CADC1A963B2C1124F480F9CE /* LiveActivityManager.swift */,
- PM0002A0B1C2D3E4F5A6B7C8 /* PremiumManager.swift */,
- RCS00200B1C2D3E4F5A6B7C8 /* RevenueCatSecrets.swift */,
- C3D4E5F6A7B8C9D0E1F2A3B4 /* PrimarySessionManager.swift */,
- );
- path = Services;
- sourceTree = "<group>";
- };
- BF668ADCDAD9595E867B23D0 /* Services */ = {
- isa = PBXGroup;
- children = (
- APNS0002D559EC6EBE0E39F4 /* APNsPushService.swift */,
- APNS0004D559EC6EBE0E39F4 /* APNsSecrets.swift */,
- E25C5CD874B7119D57AB2BB1 /* ClaudeHookServer.swift */,
- 22479FA0953120F3B50A1AF3 /* CloudKitSync.swift */,
- A19BA18A6829F0BE991D4C7D /* SessionFileParser.swift */,
- 42BAF66F7C50D732B7E69333 /* SessionScanner.swift */,
- F71E03612F167D883C324D25 /* SessionStateManager.swift */,
- B3C4D5E6F708192A3B4C5D6E /* TranscriptWatcher.swift */,
- );
- path = Services;
- sourceTree = "<group>";
- };
- E69FE1F86317CB89D608ED70 /* Packages */ = {
- isa = PBXGroup;
- children = (
- F033CA1408917B1655BC66D2 /* CodyncShared */,
- );
- name = Packages;
- sourceTree = "<group>";
- };
- F6E0D7AC712AA3B0F1759540 = {
- isa = PBXGroup;
- children = (
- 0C96AC38D8727BFA29C5A3C2 /* Codync-iOS */,
- 38DD3C2C943D4DCC5208E8BB /* Codync-macOS */,
- 5B3C3F020EFA3298682EBB4D /* CodyncLiveActivity */,
- E69FE1F86317CB89D608ED70 /* Packages */,
- 04721CC753DB3D170E2C8A15 /* Products */,
- );
- sourceTree = "<group>";
- };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
- 6B3B927655EA5C595A71E513 /* CodyncLiveActivity */ = {
+ 306ED26C181D06BDE1E6EB55 /* Codync-iOS */ = {
isa = PBXNativeTarget;
- buildConfigurationList = DF32303A18F63D7469748788 /* Build configuration list for PBXNativeTarget "CodyncLiveActivity" */;
+ buildConfigurationList = 300BC84D64F107B41629DDFD /* Build configuration list for PBXNativeTarget "Codync-iOS" */;
buildPhases = (
- 20089E1B60BEFCC7A55A8FB6 /* Sources */,
- B751B672F1F83A923532F25D /* Frameworks */,
+ A9B4AF2EC917CEFCB162B091 /* Sources */,
+ D4DD49FA9E802F4F2DF2B232 /* Resources */,
+ 23D362028BD4C2D187672C6B /* Frameworks */,
+ AA3D7E40FB2438A6CD2D3DE7 /* Embed Foundation Extensions */,
);
buildRules = (
);
dependencies = (
+ 3AA5CFC9DFBBAE9D4564C791 /* PBXTargetDependency */,
);
- name = CodyncLiveActivity;
+ name = "Codync-iOS";
packageProductDependencies = (
- 4BA154F0B1967DCBBB7600E5 /* CodyncShared */,
+ CDE38864BDC425F1240E1C02 /* CodyncKit */,
);
- productName = CodyncLiveActivity;
- productReference = 3B652652FD106495A82565C8 /* CodyncLiveActivity.appex */;
- productType = "com.apple.product-type.app-extension";
+ productName = "Codync-iOS";
+ productReference = 84B947AD5A042EA315737BBC /* Codync-iOS.app */;
+ productType = "com.apple.product-type.application";
};
- 842C52E994476FBBD71C5E66 /* Codync-iOS */ = {
+ 95A633B0E0FD05A1D35CA468 /* CodyncWidgets */ = {
isa = PBXNativeTarget;
- buildConfigurationList = C0E163C029ACFE1211477667 /* Build configuration list for PBXNativeTarget "Codync-iOS" */;
+ buildConfigurationList = 44E0D659F23143196DD57DE0 /* Build configuration list for PBXNativeTarget "CodyncWidgets" */;
buildPhases = (
- E9BB052BDAD97370F33645C0 /* Sources */,
- D24261284760002490375CA2 /* Resources */,
- EBDCA5828CAAF005C11D4017 /* Frameworks */,
- FC965E0F58168E06F093EAB5 /* Embed Foundation Extensions */,
+ EB674074085209A1C457557E /* Sources */,
+ F84176A6E29D7445556D4800 /* Frameworks */,
);
buildRules = (
);
dependencies = (
- 2486A6FA3EF6F07F8C8C1869 /* PBXTargetDependency */,
);
- name = "Codync-iOS";
+ name = CodyncWidgets;
packageProductDependencies = (
- C1CA2B270135307CC4E2724D /* CodyncShared */,
- RC0003A0B1C2D3E4F5A6B7C8 /* RevenueCat */,
- RC0004A0B1C2D3E4F5A6B7C8 /* RevenueCatUI */,
+ 4364B5D2EE15CB00ACF26E5D /* CodyncKit */,
);
- productName = "Codync-iOS";
- productReference = 3EB0548BFADFAFC3616A8C4B /* Codync.app */;
- productType = "com.apple.product-type.application";
+ productName = CodyncWidgets;
+ productReference = 04030896973C4041E7FEB319 /* CodyncWidgets.appex */;
+ productType = "com.apple.product-type.app-extension";
};
- AD1C1A5F9DF9E66175980B2F /* Codync */ = {
+ E8A9607522E696738C5CA56E /* Codync-macOS */ = {
isa = PBXNativeTarget;
- buildConfigurationList = 760757829424481109E47CF8 /* Build configuration list for PBXNativeTarget "Codync" */;
+ buildConfigurationList = 055E41E3751AF5C2889C3938 /* Build configuration list for PBXNativeTarget "Codync-macOS" */;
buildPhases = (
- 7F9A36AEDBA1D656A9BF8ADE /* Sources */,
- B2D37B30DF1C57C6200F77CB /* Resources */,
- 33BB45F688B4E120B83A8B95 /* Frameworks */,
+ E5233A2EF3EBD0703A3CD62B /* Sources */,
+ E7B25FBC4C007B3E1A7E8B39 /* Resources */,
+ BC19FCC84D9B1AF54A43BDB1 /* Frameworks */,
+ 35A6B7A814D5FF8E400C0EBA /* Embed codync-host */,
);
buildRules = (
);
dependencies = (
);
- name = Codync;
+ name = "Codync-macOS";
packageProductDependencies = (
- 7660B5D6DD8CC2065A9F4ED3 /* CodyncShared */,
+ 234AA35A60DF7D3E6D7CA45E /* CodyncKit */,
);
- productName = Codync;
- productReference = 8B5EA7075E9DC97237EF2227 /* Codync.app */;
+ productName = "Codync-macOS";
+ productReference = 155F1B6DC4518164BE2C527F /* Codync-macOS.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
- 755EE78C119E5281024E6F90 /* Project object */ = {
+ 5B6351DD20AF4506794D6460 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
- LastUpgradeCheck = 2620;
+ LastUpgradeCheck = 1430;
+ TargetAttributes = {
+ 306ED26C181D06BDE1E6EB55 = {
+ ProvisioningStyle = Automatic;
+ };
+ 95A633B0E0FD05A1D35CA468 = {
+ ProvisioningStyle = Automatic;
+ };
+ E8A9607522E696738C5CA56E = {
+ ProvisioningStyle = Automatic;
+ };
+ };
};
- buildConfigurationList = DA5B2EF5E622786143AC38D4 /* Build configuration list for PBXProject "Codync" */;
+ buildConfigurationList = F977CF173B7D60769B393751 /* Build configuration list for PBXProject "Codync" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
@@ -432,157 +306,203 @@
Base,
en,
);
- mainGroup = F6E0D7AC712AA3B0F1759540;
+ mainGroup = C9B7D3953422AE726DDC6347;
minimizedProjectReferenceProxies = 1;
packageReferences = (
- 2546D0E01391BBF7D36B931E /* XCLocalSwiftPackageReference "CodyncShared" */,
- RC0005A0B1C2D3E4F5A6B7C8 /* XCRemoteSwiftPackageReference "purchases-ios-spm" */,
+ F89E9C0E1EDA8BE6657FAB55 /* XCLocalSwiftPackageReference "CodyncKit" */,
);
+ preferredProjectObjectVersion = 77;
projectDirPath = "";
projectRoot = "";
targets = (
- AD1C1A5F9DF9E66175980B2F /* Codync */,
- 842C52E994476FBBD71C5E66 /* Codync-iOS */,
- 6B3B927655EA5C595A71E513 /* CodyncLiveActivity */,
+ 306ED26C181D06BDE1E6EB55 /* Codync-iOS */,
+ E8A9607522E696738C5CA56E /* Codync-macOS */,
+ 95A633B0E0FD05A1D35CA468 /* CodyncWidgets */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
- B2D37B30DF1C57C6200F77CB /* Resources */ = {
+ D4DD49FA9E802F4F2DF2B232 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- B575261E2F89280C4805C654 /* Assets.xcassets in Resources */,
+ 76E613DFEABF73915C5FE9DC /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- D24261284760002490375CA2 /* Resources */ = {
+ E7B25FBC4C007B3E1A7E8B39 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- 0205D611148BDCAB840D0F47 /* Assets.xcassets in Resources */,
+ 1BD8A64454E95EF3726132A4 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
+/* Begin PBXShellScriptBuildPhase section */
+ 35A6B7A814D5FF8E400C0EBA /* Embed codync-host */ = {
+ isa = PBXShellScriptBuildPhase;
+ alwaysOutOfDate = 1;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputFileListPaths = (
+ );
+ inputPaths = (
+ );
+ name = "Embed codync-host";
+ outputFileListPaths = (
+ );
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "# Builds the Rust host and ships it inside Codync.app/Contents/MacOS.\nexport PATH=\"$HOME/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:$PATH\"\nif ! command -v cargo >/dev/null; then\n echo \"warning: cargo not found; Codync.app will look for codync-host on PATH instead\"\n exit 0\nfi\nPROFILE=release\n[ \"$CONFIGURATION\" = \"Debug\" ] && PROFILE=debug\nFLAGS=\"\"\n[ \"$PROFILE\" = \"release\" ] && FLAGS=\"--release\"\nif [ \"$PROFILE\" = \"release\" ]; then\n rustup target add aarch64-apple-darwin x86_64-apple-darwin >/dev/null 2>&1 || true\n cargo build --release --manifest-path \"$SRCROOT/host/Cargo.toml\" --target aarch64-apple-darwin &&\n cargo build --release --manifest-path \"$SRCROOT/host/Cargo.toml\" --target x86_64-apple-darwin &&\n lipo -create -output \"$SRCROOT/host/target/codync-host-universal\" \\\n \"$SRCROOT/host/target/aarch64-apple-darwin/release/codync-host\" \\\n \"$SRCROOT/host/target/x86_64-apple-darwin/release/codync-host\" &&\n BIN=\"$SRCROOT/host/target/codync-host-universal\" ||\n { cargo build --release --manifest-path \"$SRCROOT/host/Cargo.toml\" && BIN=\"$SRCROOT/host/target/release/codync-host\"; }\nelse\n cargo build --manifest-path \"$SRCROOT/host/Cargo.toml\" && BIN=\"$SRCROOT/host/target/debug/codync-host\"\nfi\nDEST=\"$TARGET_BUILD_DIR/$EXECUTABLE_FOLDER_PATH/codync-host\"\ncp \"$BIN\" \"$DEST\"\nif [ -n \"$EXPANDED_CODE_SIGN_IDENTITY\" ] && [ \"$CODE_SIGNING_ALLOWED\" != \"NO\" ]; then\n codesign --force --options runtime --timestamp=none --sign \"$EXPANDED_CODE_SIGN_IDENTITY\" \"$DEST\"\nfi\n";
+ showEnvVarsInLog = 0;
+ };
+/* End PBXShellScriptBuildPhase section */
+
/* Begin PBXSourcesBuildPhase section */
- 20089E1B60BEFCC7A55A8FB6 /* Sources */ = {
+ A9B4AF2EC917CEFCB162B091 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- E36D87A2D2D0F1177F263772 /* CodyncLiveActivityBundle.swift in Sources */,
- BB50434DF1BC51FED1AFED51 /* CodyncLiveActivityWidget.swift in Sources */,
+ 575ABFE8E1FBD2865793F45D /* AppModel.swift in Sources */,
+ 745062481B4868CF3F2950BF /* BotEditorView.swift in Sources */,
+ 07670DD412E0F79796D44699 /* BotListView.swift in Sources */,
+ CEFE64EFFEA10B5ED60F2CE3 /* CodyncApp.swift in Sources */,
+ 2C21D097FD9AF73AE3B40DDE /* MarkdownText.swift in Sources */,
+ 989285CFB52552A97D95366C /* PairingView.swift in Sources */,
+ FB33CDB6D44A6023BB565200 /* PermissionCard.swift in Sources */,
+ 61455BFB935FE1AAF67C4CD4 /* Push.swift in Sources */,
+ 087DC53315FB092D4F6436AD /* RootView.swift in Sources */,
+ 9D644515BB782DC91B1B71C8 /* SettingsView.swift in Sources */,
+ DC0510188C0A2C8FAEA5CC8D /* ThreadView.swift in Sources */,
+ 4F70D744ED9A696854EADA91 /* TraceView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- 7F9A36AEDBA1D656A9BF8ADE /* Sources */ = {
+ E5233A2EF3EBD0703A3CD62B /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- APNS0001D559EC6EBE0E39F4 /* APNsPushService.swift in Sources */,
- APNS0003D559EC6EBE0E39F4 /* APNsSecrets.swift in Sources */,
- A98E0466D559EC6EBE0E39F4 /* ClaudeHookServer.swift in Sources */,
- 3DC7D9E7E79444359ED6D09F /* ClaudePaths.swift in Sources */,
- 106A1E305D6DBDFC35AF01BD /* CloudKitSync.swift in Sources */,
- EB132AF39AB968D2DFA6151B /* CodyncApp.swift in Sources */,
- 7851B112737C5DD8B8C3380C /* JSONLTailReader.swift in Sources */,
- 1122334455667788AABBCCDD /* CodyncPanelShape.swift in Sources */,
- DD44EE55FF66001122334455 /* CodyncPanel.swift in Sources */,
- EE55FF6600112233445566AA /* EventMonitor.swift in Sources */,
- 4450C6683BA7614D2DBB5E55 /* MenuBarController.swift in Sources */,
- FF66001122334455667788BB /* NSScreen+Notch.swift in Sources */,
- PANEL001122334455667788 /* PanelHeaderView.swift in Sources */,
- 911C6ABDB9539A60844931F2 /* PIDChecker.swift in Sources */,
- BF17F10AC69617C12975E0EB /* SessionDetailView.swift in Sources */,
- 73382915E3200DDC5EF16C2F /* SessionFileParser.swift in Sources */,
- 0294408FF2BC2367453C118C /* SessionListView.swift in Sources */,
- E1740D692C1C19693058D20B /* SessionRowView.swift in Sources */,
- F1E2D3C4B5A6F7E8D9C0B1A2 /* SessionTagView.swift in Sources */,
- EDCB66A65FD85B26FE7B4664 /* SessionScanner.swift in Sources */,
- 6A5A77C9C3AF37A8E371F5CB /* SessionStateManager.swift in Sources */,
- 21DBF9BED5F40E2F671CB1F9 /* StatusDotView.swift in Sources */,
- D2A3B4C5E6F7081920314253 /* TranscriptWatcher.swift in Sources */,
- C4D5E6F7A8B9C0D1E2F3A4B5 /* Theme.swift in Sources */,
+ ED9C1500FD1CC591FCBD26CB /* CodyncMacApp.swift in Sources */,
+ CED43A6F2ED71E48C95E9E38 /* HostController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
- E9BB052BDAD97370F33645C0 /* Sources */ = {
+ EB674074085209A1C457557E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- B8C9D0E1F2A3B4C5D6E7F8A9 /* ComingSoonView.swift in Sources */,
- 7534D98B6CDF84E44B0D25A9 /* CloudKitReceiver.swift in Sources */,
- F4F54F91459EE6A15DD7B246 /* CodyncIOSApp.swift in Sources */,
- F5A6B7C8D9E0F1A2B3C4D5E6 /* AppDelegate.swift in Sources */,
- EEF78145300C2A3547AD832A /* IOSOnboardingView.swift in Sources */,
- 0CFFA94EEF8F4C33AB86012A /* YouTubePlayerView.swift in Sources */,
- DBD957B5BFDEC3B62B310F8F /* IOSRootView.swift in Sources */,
- 0B6B1D4B20837A47EAF88322 /* IOSSessionDetailView.swift in Sources */,
- A30C11E610763F5064698D43 /* IOSSessionListView.swift in Sources */,
- EF0A0CEAD3C7B875064F8556 /* LiveActivityManager.swift in Sources */,
- PM0001A0B1C2D3E4F5A6B7C8 /* PremiumManager.swift in Sources */,
- RCS00100B1C2D3E4F5A6B7C8 /* RevenueCatSecrets.swift in Sources */,
- PW0001A0B1C2D3E4F5A6B7C8 /* PaywallView.swift in Sources */,
- FW0001A0B1C2D3E4F5A6B7C8 /* FreeWarningSheet.swift in Sources */,
- SE0001A0B1C2D3E4F5A6B7C8 /* SyncErrorSheet.swift in Sources */,
- SV0001A0B1C2D3E4F5A6B7C8 /* SettingsView.swift in Sources */,
- D4E5F6A7B8C9D0E1F2A3B4C5 /* PrimarySessionManager.swift in Sources */,
- F6A7B8C9D0E1F2A3B4C5D6E7 /* TabRootView.swift in Sources */,
- B1C2D3E4F5A6B7C8D9E0F1A1 /* IOSTheme.swift in Sources */,
- B1C2D3E4F5A6B7C8D9E0F1A2 /* IOSStatusIndicator.swift in Sources */,
- B1C2D3E4F5A6B7C8D9E0F1A3 /* IOSSessionTagView.swift in Sources */,
- F7407323258F4D54ABC49AA7 /* ModePillToggle.swift in Sources */,
- A3F82B14C7E94D61B0E53D92 /* LiveActivityPreview.swift in Sources */,
+ 1C2298904CADCA68ADF64F6B /* CodyncWidgets.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
- 2486A6FA3EF6F07F8C8C1869 /* PBXTargetDependency */ = {
+ 3AA5CFC9DFBBAE9D4564C791 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
- target = 6B3B927655EA5C595A71E513 /* CodyncLiveActivity */;
- targetProxy = B38F144A3A8B56B1FC2398CE /* PBXContainerItemProxy */;
+ target = 95A633B0E0FD05A1D35CA468 /* CodyncWidgets */;
+ targetProxy = 65AAB675493CB6BE712818A9 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
- 05A665239A83C10C704662CC /* Release */ = {
+ 0FE1E0F076B087CEBC2AD3BE /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
- GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = CodyncLiveActivity/Info.plist;
- INFOPLIST_KEY_CFBundleDisplayName = CodyncLiveActivity;
- INFOPLIST_KEY_NSExtension_NSExtensionPointIdentifier = "com.apple.widgetkit-extension";
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGN_STYLE = Automatic;
+ COPY_PHASE_STRIP = NO;
+ CURRENT_PROJECT_VERSION = 17;
+ DEAD_CODE_STRIPPING = YES;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ ENABLE_USER_SCRIPT_SANDBOXING = NO;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
+ MACOSX_DEPLOYMENT_TARGET = 14.0;
+ MARKETING_VERSION = 2.0.0;
+ MTL_ENABLE_DEBUG_INFO = NO;
+ MTL_FAST_MATH = YES;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_COMPILATION_MODE = wholemodule;
+ SWIFT_OPTIMIZATION_LEVEL = "-O";
+ SWIFT_STRICT_CONCURRENCY = complete;
+ SWIFT_VERSION = 6.0;
+ };
+ name = Release;
+ };
+ 54EA3D52E88009D955D76EA4 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ CODE_SIGN_ENTITLEMENTS = CodyncWidgets/CodyncWidgets.entitlements;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = CodyncWidgets/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = Codync;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.ios.LiveActivity;
- PRODUCT_NAME = CodyncLiveActivity;
+ PRODUCT_NAME = CodyncWidgets;
SDKROOT = iphoneos;
- SWIFT_VERSION = 6.0;
+ SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
};
- name = Release;
+ name = Debug;
};
- 0C75283ACAEDF302C26EABAE /* Release */ = {
+ 5EAF02B30FB1CCFAE0E18AAE /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
- CODE_SIGN_ENTITLEMENTS = "Codync-macOS/App/Codync.entitlements";
- CODE_SIGN_IDENTITY = "Apple Development";
- CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- DEAD_CODE_STRIPPING = YES;
ENABLE_APP_SANDBOX = NO;
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
+ INFOPLIST_KEY_CFBundleDisplayName = Codync;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
INFOPLIST_KEY_LSUIElement = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
@@ -590,28 +510,51 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MACOSX_DEPLOYMENT_TARGET = 14.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync;
PRODUCT_NAME = Codync;
- PROVISIONING_PROFILE_SPECIFIER = "";
SDKROOT = macosx;
- SWIFT_VERSION = 6.0;
+ };
+ name = Debug;
+ };
+ 7984345FB6F55041E94F9B88 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CODE_SIGN_ENTITLEMENTS = "Codync-iOS/Codync-iOS.entitlements";
+ CODE_SIGN_IDENTITY = "iPhone Developer";
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = "Codync-iOS/Info.plist";
+ INFOPLIST_KEY_CFBundleDisplayName = Codync;
+ INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
+ INFOPLIST_KEY_NSCameraUsageDescription = "Scan the pairing code shown on your computer.";
+ INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Codync connects to the computer running your bots on your local network.";
+ INFOPLIST_KEY_NSSupportsLiveActivities = YES;
+ INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
+ INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
+ INFOPLIST_KEY_UILaunchScreen_Generation = YES;
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = UIInterfaceOrientationPortrait;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.ios;
+ PRODUCT_NAME = Codync;
+ SDKROOT = iphoneos;
+ TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
- 0F19986BCBA4168115C96CAA /* Debug */ = {
+ 7AECEDF558C927EA14CD5EB5 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
- CODE_SIGN_ENTITLEMENTS = "Codync-macOS/App/Codync.entitlements";
- CODE_SIGN_IDENTITY = "Apple Development";
- CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- DEAD_CODE_STRIPPING = YES;
ENABLE_APP_SANDBOX = NO;
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
+ INFOPLIST_KEY_CFBundleDisplayName = Codync;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
INFOPLIST_KEY_LSUIElement = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
@@ -619,16 +562,13 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MACOSX_DEPLOYMENT_TARGET = 14.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync;
PRODUCT_NAME = Codync;
- PROVISIONING_PROFILE_SPECIFIER = "";
SDKROOT = macosx;
- SWIFT_VERSION = 6.0;
};
- name = Debug;
+ name = Release;
};
- 1BD4F14F5BA62C58590E3C84 /* Debug */ = {
+ A8BF4A3388AA1B9ECD65A197 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
@@ -661,13 +601,14 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 16;
+ CURRENT_PROJECT_VERSION = 17;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
- ENABLE_USER_SCRIPT_SANDBOXING = YES;
+ ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
@@ -682,70 +623,59 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
- IPHONEOS_DEPLOYMENT_TARGET = 17.0;
+ IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 1.0.5;
+ MARKETING_VERSION = 2.0.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
- STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
- SWIFT_VERSION = 5.0;
+ SWIFT_STRICT_CONCURRENCY = complete;
+ SWIFT_VERSION = 6.0;
};
name = Debug;
};
- 74301E9EAFCD478E76A7FDEF /* Release */ = {
+ AE9BE3BA396DE6267749F8AF /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
- CODE_SIGN_ENTITLEMENTS = "Codync-iOS/App/Codync-iOS.entitlements";
- CODE_SIGN_IDENTITY = "iPhone Developer";
+ CODE_SIGN_ENTITLEMENTS = CodyncWidgets/CodyncWidgets.entitlements;
GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = "Codync-iOS/Info.plist";
- INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
- INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
- INFOPLIST_KEY_NSSupportsLiveActivities = YES;
- INFOPLIST_KEY_NSSupportsLiveActivitiesFrequentUpdates = YES;
- INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
- INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
- INFOPLIST_KEY_UIBackgroundModes = "remote-notification";
- INFOPLIST_KEY_UILaunchScreen_Generation = YES;
- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
- IPHONEOS_DEPLOYMENT_TARGET = 18.6;
+ INFOPLIST_FILE = CodyncWidgets/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = Codync;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
);
- PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.ios;
- PRODUCT_NAME = Codync;
+ PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.ios.LiveActivity;
+ PRODUCT_NAME = CodyncWidgets;
SDKROOT = iphoneos;
- SWIFT_VERSION = 6.0;
+ SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
- 9A811AEDB402F850CF77C133 /* Debug */ = {
+ F1217CDE3A9CDFEC5BE16BD6 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
- CODE_SIGN_ENTITLEMENTS = "Codync-iOS/App/Codync-iOS.entitlements";
+ CODE_SIGN_ENTITLEMENTS = "Codync-iOS/Codync-iOS.entitlements";
CODE_SIGN_IDENTITY = "iPhone Developer";
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Codync-iOS/Info.plist";
+ INFOPLIST_KEY_CFBundleDisplayName = Codync;
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
+ INFOPLIST_KEY_NSCameraUsageDescription = "Scan the pairing code shown on your computer.";
+ INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Codync connects to the computer running your bots on your local network.";
INFOPLIST_KEY_NSSupportsLiveActivities = YES;
- INFOPLIST_KEY_NSSupportsLiveActivitiesFrequentUpdates = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
- INFOPLIST_KEY_UIBackgroundModes = "remote-notification";
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
- IPHONEOS_DEPLOYMENT_TARGET = 18.6;
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = UIInterfaceOrientationPortrait;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -753,128 +683,45 @@
PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.ios;
PRODUCT_NAME = Codync;
SDKROOT = iphoneos;
- SWIFT_VERSION = 6.0;
- TARGETED_DEVICE_FAMILY = "1,2";
- };
- name = Debug;
- };
- BBB96964FECC01CD9E90CE59 /* Debug */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- GENERATE_INFOPLIST_FILE = YES;
- INFOPLIST_FILE = CodyncLiveActivity/Info.plist;
- INFOPLIST_KEY_CFBundleDisplayName = CodyncLiveActivity;
- INFOPLIST_KEY_NSExtension_NSExtensionPointIdentifier = "com.apple.widgetkit-extension";
- IPHONEOS_DEPLOYMENT_TARGET = 18.0;
- LD_RUNPATH_SEARCH_PATHS = (
- "$(inherited)",
- "@executable_path/Frameworks",
- "@executable_path/../../Frameworks",
- );
- PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.ios.LiveActivity;
- PRODUCT_NAME = CodyncLiveActivity;
- SDKROOT = iphoneos;
- SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
- EB49C7981C3E87EE7E670063 /* Release */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
- CLANG_ANALYZER_NONNULL = YES;
- CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
- CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
- CLANG_CXX_LIBRARY = "libc++";
- CLANG_ENABLE_MODULES = YES;
- CLANG_ENABLE_OBJC_ARC = YES;
- CLANG_ENABLE_OBJC_WEAK = YES;
- CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
- CLANG_WARN_BOOL_CONVERSION = YES;
- CLANG_WARN_COMMA = YES;
- CLANG_WARN_CONSTANT_CONVERSION = YES;
- CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
- CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
- CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
- CLANG_WARN_EMPTY_BODY = YES;
- CLANG_WARN_ENUM_CONVERSION = YES;
- CLANG_WARN_INFINITE_RECURSION = YES;
- CLANG_WARN_INT_CONVERSION = YES;
- CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
- CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
- CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
- CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
- CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
- CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
- CLANG_WARN_STRICT_PROTOTYPES = YES;
- CLANG_WARN_SUSPICIOUS_MOVE = YES;
- CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
- CLANG_WARN_UNREACHABLE_CODE = YES;
- CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
- COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 16;
- DEAD_CODE_STRIPPING = YES;
- DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
- ENABLE_NS_ASSERTIONS = NO;
- ENABLE_STRICT_OBJC_MSGSEND = YES;
- ENABLE_USER_SCRIPT_SANDBOXING = YES;
- GCC_C_LANGUAGE_STANDARD = gnu11;
- GCC_NO_COMMON_BLOCKS = YES;
- GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
- GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
- GCC_WARN_UNDECLARED_SELECTOR = YES;
- GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
- GCC_WARN_UNUSED_FUNCTION = YES;
- GCC_WARN_UNUSED_VARIABLE = YES;
- IPHONEOS_DEPLOYMENT_TARGET = 17.0;
- MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 1.0.5;
- MTL_ENABLE_DEBUG_INFO = NO;
- MTL_FAST_MATH = YES;
- PRODUCT_NAME = "$(TARGET_NAME)";
- STRING_CATALOG_GENERATE_SYMBOLS = YES;
- SWIFT_COMPILATION_MODE = wholemodule;
- SWIFT_OPTIMIZATION_LEVEL = "-O";
- SWIFT_VERSION = 5.0;
- };
- name = Release;
- };
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
- 760757829424481109E47CF8 /* Build configuration list for PBXNativeTarget "Codync" */ = {
+ 055E41E3751AF5C2889C3938 /* Build configuration list for PBXNativeTarget "Codync-macOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
- 0F19986BCBA4168115C96CAA /* Debug */,
- 0C75283ACAEDF302C26EABAE /* Release */,
+ 5EAF02B30FB1CCFAE0E18AAE /* Debug */,
+ 7AECEDF558C927EA14CD5EB5 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Debug;
};
- C0E163C029ACFE1211477667 /* Build configuration list for PBXNativeTarget "Codync-iOS" */ = {
+ 300BC84D64F107B41629DDFD /* Build configuration list for PBXNativeTarget "Codync-iOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
- 9A811AEDB402F850CF77C133 /* Debug */,
- 74301E9EAFCD478E76A7FDEF /* Release */,
+ F1217CDE3A9CDFEC5BE16BD6 /* Debug */,
+ 7984345FB6F55041E94F9B88 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Debug;
};
- DA5B2EF5E622786143AC38D4 /* Build configuration list for PBXProject "Codync" */ = {
+ 44E0D659F23143196DD57DE0 /* Build configuration list for PBXNativeTarget "CodyncWidgets" */ = {
isa = XCConfigurationList;
buildConfigurations = (
- 1BD4F14F5BA62C58590E3C84 /* Debug */,
- EB49C7981C3E87EE7E670063 /* Release */,
+ 54EA3D52E88009D955D76EA4 /* Debug */,
+ AE9BE3BA396DE6267749F8AF /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Debug;
};
- DF32303A18F63D7469748788 /* Build configuration list for PBXNativeTarget "CodyncLiveActivity" */ = {
+ F977CF173B7D60769B393751 /* Build configuration list for PBXProject "Codync" */ = {
isa = XCConfigurationList;
buildConfigurations = (
- BBB96964FECC01CD9E90CE59 /* Debug */,
- 05A665239A83C10C704662CC /* Release */,
+ A8BF4A3388AA1B9ECD65A197 /* Debug */,
+ 0FE1E0F076B087CEBC2AD3BE /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Debug;
@@ -882,47 +729,26 @@
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
- 2546D0E01391BBF7D36B931E /* XCLocalSwiftPackageReference "CodyncShared" */ = {
+ F89E9C0E1EDA8BE6657FAB55 /* XCLocalSwiftPackageReference "CodyncKit" */ = {
isa = XCLocalSwiftPackageReference;
- relativePath = CodyncShared;
+ relativePath = CodyncKit;
};
/* End XCLocalSwiftPackageReference section */
-/* Begin XCRemoteSwiftPackageReference section */
- RC0005A0B1C2D3E4F5A6B7C8 /* XCRemoteSwiftPackageReference "purchases-ios-spm" */ = {
- isa = XCRemoteSwiftPackageReference;
- repositoryURL = "https://github.com/RevenueCat/purchases-ios-spm.git";
- requirement = {
- kind = upToNextMajorVersion;
- minimumVersion = 5.0.0;
- };
- };
-/* End XCRemoteSwiftPackageReference section */
-
/* Begin XCSwiftPackageProductDependency section */
- 4BA154F0B1967DCBBB7600E5 /* CodyncShared */ = {
- isa = XCSwiftPackageProductDependency;
- productName = CodyncShared;
- };
- 7660B5D6DD8CC2065A9F4ED3 /* CodyncShared */ = {
- isa = XCSwiftPackageProductDependency;
- productName = CodyncShared;
- };
- C1CA2B270135307CC4E2724D /* CodyncShared */ = {
+ 234AA35A60DF7D3E6D7CA45E /* CodyncKit */ = {
isa = XCSwiftPackageProductDependency;
- productName = CodyncShared;
+ productName = CodyncKit;
};
- RC0003A0B1C2D3E4F5A6B7C8 /* RevenueCat */ = {
+ 4364B5D2EE15CB00ACF26E5D /* CodyncKit */ = {
isa = XCSwiftPackageProductDependency;
- package = RC0005A0B1C2D3E4F5A6B7C8 /* XCRemoteSwiftPackageReference "purchases-ios-spm" */;
- productName = RevenueCat;
+ productName = CodyncKit;
};
- RC0004A0B1C2D3E4F5A6B7C8 /* RevenueCatUI */ = {
+ CDE38864BDC425F1240E1C02 /* CodyncKit */ = {
isa = XCSwiftPackageProductDependency;
- package = RC0005A0B1C2D3E4F5A6B7C8 /* XCRemoteSwiftPackageReference "purchases-ios-spm" */;
- productName = RevenueCatUI;
+ productName = CodyncKit;
};
/* End XCSwiftPackageProductDependency section */
};
- rootObject = 755EE78C119E5281024E6F90 /* Project object */;
+ rootObject = 5B6351DD20AF4506794D6460 /* Project object */;
}
diff --git a/Codync.xcodeproj/xcshareddata/xcschemes/Codync-iOS.xcscheme b/Codync.xcodeproj/xcshareddata/xcschemes/Codync-iOS.xcscheme
deleted file mode 100644
index 9fde6df1..00000000
--- a/Codync.xcodeproj/xcshareddata/xcschemes/Codync-iOS.xcscheme
+++ /dev/null
@@ -1,78 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<Scheme
- LastUpgradeVersion = "2620"
- version = "1.7">
- <BuildAction
- parallelizeBuildables = "YES"
- buildImplicitDependencies = "YES"
- buildArchitectures = "Automatic">
- <BuildActionEntries>
- <BuildActionEntry
- buildForTesting = "YES"
- buildForRunning = "YES"
- buildForProfiling = "YES"
- buildForArchiving = "YES"
- buildForAnalyzing = "YES">
- <BuildableReference
- BuildableIdentifier = "primary"
- BlueprintIdentifier = "842C52E994476FBBD71C5E66"
- BuildableName = "Codync.app"
- BlueprintName = "Codync-iOS"
- ReferencedContainer = "container:Codync.xcodeproj">
- </BuildableReference>
- </BuildActionEntry>
- </BuildActionEntries>
- </BuildAction>
- <TestAction
- buildConfiguration = "Debug"
- selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
- selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- shouldUseLaunchSchemeArgsEnv = "YES"
- shouldAutocreateTestPlan = "YES">
- </TestAction>
- <LaunchAction
- buildConfiguration = "Debug"
- selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
- selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- launchStyle = "0"
- useCustomWorkingDirectory = "NO"
- ignoresPersistentStateOnLaunch = "NO"
- debugDocumentVersioning = "YES"
- debugServiceExtension = "internal"
- allowLocationSimulation = "YES">
- <BuildableProductRunnable
- runnableDebuggingMode = "0">
- <BuildableReference
- BuildableIdentifier = "primary"
- BlueprintIdentifier = "842C52E994476FBBD71C5E66"
- BuildableName = "Codync.app"
- BlueprintName = "Codync-iOS"
- ReferencedContainer = "container:Codync.xcodeproj">
- </BuildableReference>
- </BuildableProductRunnable>
- </LaunchAction>
- <ProfileAction
- buildConfiguration = "Release"
- shouldUseLaunchSchemeArgsEnv = "YES"
- savedToolIdentifier = ""
- useCustomWorkingDirectory = "NO"
- debugDocumentVersioning = "YES">
- <BuildableProductRunnable
- runnableDebuggingMode = "0">
- <BuildableReference
- BuildableIdentifier = "primary"
- BlueprintIdentifier = "842C52E994476FBBD71C5E66"
- BuildableName = "Codync.app"
- BlueprintName = "Codync-iOS"
- ReferencedContainer = "container:Codync.xcodeproj">
- </BuildableReference>
- </BuildableProductRunnable>
- </ProfileAction>
- <AnalyzeAction
- buildConfiguration = "Debug">
- </AnalyzeAction>
- <ArchiveAction
- buildConfiguration = "Release"
- revealArchiveInOrganizer = "YES">
- </ArchiveAction>
-</Scheme>
diff --git a/Codync.xcodeproj/xcshareddata/xcschemes/CodyncLiveActivity.xcscheme b/Codync.xcodeproj/xcshareddata/xcschemes/CodyncLiveActivity.xcscheme
deleted file mode 100644
index 74cec19d..00000000
--- a/Codync.xcodeproj/xcshareddata/xcschemes/CodyncLiveActivity.xcscheme
+++ /dev/null
@@ -1,97 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<Scheme
- LastUpgradeVersion = "2620"
- wasCreatedForAppExtension = "YES"
- version = "2.0">
- <BuildAction
- parallelizeBuildables = "YES"
- buildImplicitDependencies = "YES"
- buildArchitectures = "Automatic">
- <BuildActionEntries>
- <BuildActionEntry
- buildForTesting = "YES"
- buildForRunning = "YES"
- buildForProfiling = "YES"
- buildForArchiving = "YES"
- buildForAnalyzing = "YES">
- <BuildableReference
- BuildableIdentifier = "primary"
- BlueprintIdentifier = "6B3B927655EA5C595A71E513"
- BuildableName = "CodyncLiveActivity.appex"
- BlueprintName = "CodyncLiveActivity"
- ReferencedContainer = "container:Codync.xcodeproj">
- </BuildableReference>
- </BuildActionEntry>
- <BuildActionEntry
- buildForTesting = "YES"
- buildForRunning = "YES"
- buildForProfiling = "YES"
- buildForArchiving = "YES"
- buildForAnalyzing = "YES">
- <BuildableReference
- BuildableIdentifier = "primary"
- BlueprintIdentifier = "842C52E994476FBBD71C5E66"
- BuildableName = "Codync.app"
- BlueprintName = "Codync-iOS"
- ReferencedContainer = "container:Codync.xcodeproj">
- </BuildableReference>
- </BuildActionEntry>
- </BuildActionEntries>
- </BuildAction>
- <TestAction
- buildConfiguration = "Debug"
- selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
- selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- shouldUseLaunchSchemeArgsEnv = "YES"
- shouldAutocreateTestPlan = "YES">
- </TestAction>
- <LaunchAction
- buildConfiguration = "Debug"
- selectedDebuggerIdentifier = ""
- selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
- launchStyle = "0"
- askForAppToLaunch = "Yes"
- useCustomWorkingDirectory = "NO"
- ignoresPersistentStateOnLaunch = "NO"
- debugDocumentVersioning = "YES"
- debugServiceExtension = "internal"
- allowLocationSimulation = "YES"
- launchAutomaticallySubstyle = "2">
- <BuildableProductRunnable
- runnableDebuggingMode = "0">
- <BuildableReference
- BuildableIdentifier = "primary"
- BlueprintIdentifier = "842C52E994476FBBD71C5E66"
- BuildableName = "Codync.app"
- BlueprintName = "Codync-iOS"
- ReferencedContainer = "container:Codync.xcodeproj">
- </BuildableReference>
- </BuildableProductRunnable>
- </LaunchAction>
- <ProfileAction
- buildConfiguration = "Release"
- shouldUseLaunchSchemeArgsEnv = "YES"
- savedToolIdentifier = ""
- useCustomWorkingDirectory = "NO"
- debugDocumentVersioning = "YES"
- askForAppToLaunch = "Yes"
- launchAutomaticallySubstyle = "2">
- <BuildableProductRunnable
- runnableDebuggingMode = "0">
- <BuildableReference
- BuildableIdentifier = "primary"
- BlueprintIdentifier = "842C52E994476FBBD71C5E66"
- BuildableName = "Codync.app"
- BlueprintName = "Codync-iOS"
- ReferencedContainer = "container:Codync.xcodeproj">
- </BuildableReference>
- </BuildableProductRunnable>
- </ProfileAction>
- <AnalyzeAction
- buildConfiguration = "Debug">
- </AnalyzeAction>
- <ArchiveAction
- buildConfiguration = "Release"
- revealArchiveInOrganizer = "YES">
- </ArchiveAction>
-</Scheme>
diff --git a/CodyncKit/Package.swift b/CodyncKit/Package.swift
new file mode 100644
index 00000000..a31fbd9a
--- /dev/null
+++ b/CodyncKit/Package.swift
@@ -0,0 +1,14 @@
+// swift-tools-version: 6.0
+import PackageDescription
+
+let package = Package(
+ name: "CodyncKit",
+ platforms: [.macOS(.v14), .iOS(.v17)],
+ products: [
+ .library(name: "CodyncKit", targets: ["CodyncKit"]),
+ ],
+ targets: [
+ .target(name: "CodyncKit"),
+ .testTarget(name: "CodyncKitTests", dependencies: ["CodyncKit"], resources: [.copy("Fixtures")]),
+ ]
+)
diff --git a/CodyncKit/Sources/CodyncKit/BotActivity.swift b/CodyncKit/Sources/CodyncKit/BotActivity.swift
new file mode 100644
index 00000000..aff7592a
--- /dev/null
+++ b/CodyncKit/Sources/CodyncKit/BotActivity.swift
@@ -0,0 +1,33 @@
+#if os(iOS)
+import ActivityKit
+import Foundation
+
+/// Live Activity for a bot working on something the user just delegated.
+/// Content state keys must match what codync-host pushes (host/src/push.rs).
+public struct BotActivityAttributes: ActivityAttributes {
+ public struct ContentState: Codable, Hashable, Sendable {
+ /// idle | working | needsInput | error
+ public var status: String
+ public var activity: String
+ public var startedAt: Date?
+
+ public init(status: String, activity: String, startedAt: Date?) {
+ self.status = status
+ self.activity = activity
+ self.startedAt = startedAt
+ }
+ }
+
+ public var botId: String
+ public var name: String
+ public var avatarShape: String
+ public var avatarColor: String
+
+ public init(bot: Bot) {
+ botId = bot.id
+ name = bot.name
+ avatarShape = bot.avatarShape
+ avatarColor = bot.avatarColor
+ }
+}
+#endif
diff --git a/CodyncKit/Sources/CodyncKit/CharacterAvatar.swift b/CodyncKit/Sources/CodyncKit/CharacterAvatar.swift
new file mode 100644
index 00000000..a6382760
--- /dev/null
+++ b/CodyncKit/Sources/CodyncKit/CharacterAvatar.swift
@@ -0,0 +1,152 @@
+import SwiftUI
+
+/// Grok-Bot-style character: a colored shape with eyes. The eyes look around
+/// while the bot works; a badge shows when it needs you.
+public struct CharacterAvatar: View {
+ public enum Mood: Sendable { case idle, working, needsInput }
+
+ let shape: String
+ let color: Color
+ let size: CGFloat
+ let mood: Mood
+
+ public init(shape: String, color: String, size: CGFloat = 40, mood: Mood = .idle) {
+ self.shape = shape
+ self.color = AvatarPalette.color(color)
+ self.size = size
+ self.mood = mood
+ }
+
+ public init(bot: Bot, size: CGFloat = 40, animated: Bool = true) {
+ self.init(
+ shape: bot.avatarShape,
+ color: bot.avatarColor,
+ size: size,
+ mood: !animated ? .idle : bot.needsInput ? .needsInput : bot.isWorking ? .working : .idle
+ )
+ }
+
+ public var body: some View {
+ ZStack {
+ CharacterShape(kind: shape)
+ .fill(color.gradient)
+ Eyes(size: size, working: mood == .working)
+ .offset(y: -size * 0.03)
+ }
+ .frame(width: size, height: size)
+ .accessibilityHidden(true)
+ }
+}
+
+private struct Eyes: View {
+ let size: CGFloat
+ let working: Bool
+
+ var body: some View {
+ let eye = size * 0.17
+ HStack(spacing: size * 0.12) {
+ ForEach(0..<2, id: \.self) { _ in
+ Capsule()
+ .fill(.white)
+ .frame(width: eye * 0.8, height: eye * 1.15)
+ .overlay(
+ Circle().fill(Color(hex: 0x141712)).frame(width: eye * 0.45)
+ )
+ }
+ }
+ .phaseAnimator(working ? [-1.0, 1.0] : [0.0]) { view, phase in
+ view.offset(x: phase * size * 0.06)
+ } animation: { _ in .easeInOut(duration: 0.9) }
+ }
+}
+
+/// The eight Grok Bot character silhouettes.
+public struct CharacterShape: Shape {
+ let kind: String
+
+ public init(kind: String) { self.kind = kind }
+
+ public func path(in r: CGRect) -> Path {
+ let w = r.width, h = r.height
+ switch kind {
+ case "pebble":
+ return Path(ellipseIn: r.insetBy(dx: 0, dy: h * 0.1))
+ case "squircle":
+ return Path(roundedRect: r.insetBy(dx: w * 0.04, dy: h * 0.04), cornerRadius: w * 0.3, style: .continuous)
+ case "tablet":
+ return Path(roundedRect: r.insetBy(dx: w * 0.14, dy: 0), cornerRadius: w * 0.22, style: .continuous)
+ case "wedge":
+ var p = Path()
+ p.move(to: CGPoint(x: w * 0.5, y: h * 0.04))
+ p.addQuadCurve(to: CGPoint(x: w * 0.98, y: h * 0.86), control: CGPoint(x: w * 0.9, y: h * 0.4))
+ p.addQuadCurve(to: CGPoint(x: w * 0.02, y: h * 0.86), control: CGPoint(x: w * 0.5, y: h * 1.04))
+ p.addQuadCurve(to: CGPoint(x: w * 0.5, y: h * 0.04), control: CGPoint(x: w * 0.1, y: h * 0.4))
+ return p
+ case "hex":
+ var p = Path()
+ for i in 0..<6 {
+ let a = Double(i) * .pi / 3 - .pi / 2
+ let pt = CGPoint(x: w / 2 + cos(a) * w * 0.49, y: h / 2 + sin(a) * h * 0.49)
+ i == 0 ? p.move(to: pt) : p.addLine(to: pt)
+ }
+ p.closeSubpath()
+ return p.strokedPath(.init(lineWidth: w * 0.08, lineJoin: .round)).union(p)
+ case "cloud":
+ var p = Path()
+ p.addEllipse(in: CGRect(x: 0, y: h * 0.3, width: w * 0.55, height: h * 0.55))
+ p.addEllipse(in: CGRect(x: w * 0.45, y: h * 0.3, width: w * 0.55, height: h * 0.55))
+ p.addEllipse(in: CGRect(x: w * 0.18, y: h * 0.08, width: w * 0.64, height: h * 0.64))
+ p.addRoundedRect(in: CGRect(x: w * 0.1, y: h * 0.5, width: w * 0.8, height: h * 0.35), cornerSize: CGSize(width: w * 0.15, height: w * 0.15))
+ return p
+ case "teardrop":
+ var p = Path()
+ p.move(to: CGPoint(x: w * 0.5, y: 0))
+ p.addCurve(to: CGPoint(x: w * 0.94, y: h * 0.62), control1: CGPoint(x: w * 0.62, y: h * 0.2), control2: CGPoint(x: w * 0.94, y: h * 0.38))
+ p.addArc(center: CGPoint(x: w * 0.5, y: h * 0.62), radius: w * 0.44, startAngle: .degrees(0), endAngle: .degrees(180), clockwise: false)
+ p.addCurve(to: CGPoint(x: w * 0.5, y: 0), control1: CGPoint(x: w * 0.06, y: h * 0.38), control2: CGPoint(x: w * 0.38, y: h * 0.2))
+ return p
+ default: // blob
+ var p = Path()
+ let c = CGPoint(x: w / 2, y: h / 2)
+ let steps = 64
+ for i in 0...steps {
+ let a = Double(i) / Double(steps) * 2 * .pi
+ let rr = 0.46 + 0.035 * sin(a * 3 + 0.6)
+ let pt = CGPoint(x: c.x + cos(a) * w * rr, y: c.y + sin(a) * h * rr)
+ i == 0 ? p.move(to: pt) : p.addLine(to: pt)
+ }
+ p.closeSubpath()
+ return p
+ }
+ }
+}
+
+/// Avatar with the roster status dot: lime = unread, orange = needs you.
+public struct AvatarWithStatus: View {
+ let bot: Bot
+ let size: CGFloat
+
+ public init(bot: Bot, size: CGFloat = 44) {
+ self.bot = bot
+ self.size = size
+ }
+
+ public var body: some View {
+ CharacterAvatar(bot: bot, size: size)
+ .overlay(alignment: .bottomTrailing) {
+ if bot.needsInput {
+ Image(systemName: "exclamationmark")
+ .font(.system(size: size * 0.2, weight: .black))
+ .foregroundStyle(.white)
+ .frame(width: size * 0.36, height: size * 0.36)
+ .background(Palette.warning, in: Circle())
+ .overlay(Circle().stroke(Palette.background, lineWidth: 2))
+ } else if bot.unread > 0 {
+ Circle()
+ .fill(Palette.accentFill)
+ .frame(width: size * 0.28, height: size * 0.28)
+ .overlay(Circle().stroke(Palette.background, lineWidth: 2))
+ }
+ }
+ }
+}
diff --git a/CodyncKit/Sources/CodyncKit/HostClient.swift b/CodyncKit/Sources/CodyncKit/HostClient.swift
new file mode 100644
index 00000000..ada49863
--- /dev/null
+++ b/CodyncKit/Sources/CodyncKit/HostClient.swift
@@ -0,0 +1,248 @@
+import Foundation
+
+/// What `codync-host pair` encodes: `codync://pair?name=…&token=…&urls=a,b`.
+public struct Pairing: Codable, Hashable, Sendable {
+ public var name: String
+ public var token: String
+ public var urls: [String]
+
+ public init(name: String, token: String, urls: [String]) {
+ self.name = name
+ self.token = token
+ self.urls = urls
+ }
+
+ public init?(url: URL) {
+ guard url.scheme == "codync", url.host() == "pair",
+ let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else { return nil }
+ let q = Dictionary(items.map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { a, _ in a })
+ guard let token = q["token"], !token.isEmpty else { return nil }
+ let urls = (q["urls"] ?? "").split(separator: ",").map(String.init).filter { URL(string: $0) != nil }
+ guard !urls.isEmpty else { return nil }
+ self.init(name: q["name"].flatMap { $0.isEmpty ? nil : $0 } ?? "My computer", token: token, urls: urls)
+ }
+
+ public init?(string: String) {
+ guard let url = URL(string: string.trimmingCharacters(in: .whitespacesAndNewlines)) else { return nil }
+ self.init(url: url)
+ }
+}
+
+public enum HostError: LocalizedError, Sendable {
+ case http(Int, String)
+ case unreachable
+
+ public var errorDescription: String? {
+ switch self {
+ case .http(401, _): "This phone isn't paired with the host anymore. Pair again."
+ case let .http(_, message): message
+ case .unreachable: "Can't reach your computer. Is it awake and on Tailscale or the same Wi-Fi?"
+ }
+ }
+}
+
+public enum HostEvent: Sendable {
+ case hello(hostId: String, rev: Int64, usage: Usage)
+ case bot(Bot)
+ case botDeleted(id: String, rev: Int64)
+ case entry(Entry)
+ case usage(Usage)
+ case resync
+ /// An event this app version couldn't decode (host newer/older than the app).
+ case undecodable(type: String)
+}
+
+public struct Empty: Codable, Sendable {
+ public init() {}
+}
+
+public struct HostClient: Sendable {
+ public let baseURL: URL
+ public let token: String
+
+ public init(baseURL: URL, token: String) {
+ self.baseURL = baseURL
+ self.token = token
+ }
+
+ static let decoder = JSONDecoder()
+ static let encoder = JSONEncoder()
+
+ private var session: URLSession { .shared }
+
+ public func call<T: Decodable>(_ method: String, _ body: some Encodable = Empty(), timeout: TimeInterval = 20) async throws -> T {
+ var req = URLRequest(url: baseURL.appending(path: "api/\(method)"), timeoutInterval: timeout)
+ req.httpMethod = "POST"
+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ req.httpBody = try Self.encoder.encode(body)
+ let (data, response) = try await session.data(for: req)
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard (200..<300).contains(status) else {
+ let message = (try? JSONDecoder().decode([String: String].self, from: data))?["error"] ?? "Host error \(status)"
+ throw HostError.http(status, message)
+ }
+ return try Self.decoder.decode(T.self, from: data)
+ }
+
+ public func healthy(timeout: TimeInterval = 4) async -> Bool {
+ var req = URLRequest(url: baseURL.appending(path: "health"), timeoutInterval: timeout)
+ req.cachePolicy = .reloadIgnoringLocalCacheData
+ guard let (_, response) = try? await session.data(for: req) else { return false }
+ return (response as? HTTPURLResponse)?.statusCode == 200
+ }
+
+ /// First address (in the pairing's preference order) that answers `/health`.
+ public static func resolve(_ pairing: Pairing) async -> HostClient? {
+ let candidates = pairing.urls.compactMap(URL.init(string:)).map { HostClient(baseURL: $0, token: pairing.token) }
+ return await withTaskGroup(of: (Int, Bool).self) { group in
+ for (i, c) in candidates.enumerated() {
+ group.addTask { (i, await c.healthy()) }
+ }
+ var ok: [Int] = []
+ for await (i, healthy) in group where healthy {
+ ok.append(i)
+ // The best-ranked address won; no need to wait for slower ones.
+ if i == 0 { break }
+ }
+ group.cancelAll()
+ return ok.min().map { candidates[$0] }
+ }
+ }
+
+ /// Server-sent events: catch-up since `since`, then live updates.
+ public func events(since: Int64, client: String) -> AsyncThrowingStream<HostEvent, Error> {
+ var comps = URLComponents(url: baseURL.appending(path: "events"), resolvingAgainstBaseURL: false)!
+ comps.queryItems = [.init(name: "since", value: String(since)), .init(name: "client", value: client)]
+ var req = URLRequest(url: comps.url!, timeoutInterval: 60 * 60 * 24)
+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ req.setValue("text/event-stream", forHTTPHeaderField: "Accept")
+ let session = self.session
+ let request = req
+ return AsyncThrowingStream { continuation in
+ let task = Task {
+ do {
+ let (bytes, response) = try await session.bytes(for: request)
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard status == 200 else { throw HostError.http(status, "Host error \(status)") }
+ for try await line in bytes.lines {
+ guard line.hasPrefix("data:") else { continue }
+ let payload = Data(line.dropFirst(5).utf8)
+ if let event = Self.parseEvent(payload) {
+ continuation.yield(event)
+ }
+ }
+ continuation.finish()
+ } catch {
+ continuation.finish(throwing: error)
+ }
+ }
+ continuation.onTermination = { _ in task.cancel() }
+ }
+ }
+
+ public static func parseEvent(_ data: Data) -> HostEvent? {
+ struct Envelope: Decodable {
+ var type: String
+ var hostId: String?
+ var rev: Int64?
+ }
+ struct BotWrap: Decodable { var bot: Bot }
+ struct StubWrap: Decodable { var bot: BotStub }
+ struct EntryWrap: Decodable { var entry: Entry }
+ struct UsageWrap: Decodable { var usage: Usage }
+ let d = decoder
+ guard let env = try? d.decode(Envelope.self, from: data) else { return nil }
+ switch env.type {
+ case "hello":
+ let usage = (try? d.decode(UsageWrap.self, from: data))?.usage ?? Usage()
+ return .hello(hostId: env.hostId ?? "", rev: env.rev ?? 0, usage: usage)
+ case "bot":
+ if let stub = try? d.decode(StubWrap.self, from: data), stub.bot.deleted == true {
+ return .botDeleted(id: stub.bot.id, rev: stub.bot.rev)
+ }
+ return (try? d.decode(BotWrap.self, from: data)).map { .bot($0.bot) } ?? .undecodable(type: "bot")
+ case "entry":
+ return (try? d.decode(EntryWrap.self, from: data)).map { .entry($0.entry) } ?? .undecodable(type: "entry")
+ case "usage":
+ return (try? d.decode(UsageWrap.self, from: data)).map { .usage($0.usage) }
+ case "resync":
+ return .resync
+ default:
+ return nil
+ }
+ }
+}
+
+// MARK: - Typed calls
+
+public extension HostClient {
+ func hello() async throws -> Hello { try await call("hello") }
+
+ func sync(since: Int64) async throws -> SyncResponse {
+ try await call("sync", ["since": since])
+ }
+
+ func history(botId: String, beforeSeq: Int64, limit: Int = 100) async throws -> [Entry] {
+ struct Body: Encodable { var botId: String; var beforeSeq: Int64; var limit: Int }
+ struct Res: Decodable { var entries: [Entry] }
+ let res: Res = try await call("history", Body(botId: botId, beforeSeq: beforeSeq, limit: limit))
+ return res.entries
+ }
+
+ func createBot(_ draft: BotDraft) async throws -> Bot {
+ struct Res: Decodable { var bot: Bot }
+ let res: Res = try await call("createBot", draft)
+ return res.bot
+ }
+
+ func updateBot(_ draft: BotDraft) async throws -> Bot {
+ struct Res: Decodable { var bot: Bot }
+ let res: Res = try await call("updateBot", draft)
+ return res.bot
+ }
+
+ func deleteBot(_ id: String) async throws {
+ let _: Empty = try await call("deleteBot", ["botId": id])
+ }
+
+ func markRead(_ id: String) async throws {
+ let _: Empty = try await call("markRead", ["botId": id])
+ }
+
+ func send(botId: String, text: String, clientNonce: String) async throws -> Entry {
+ struct Res: Decodable { var entry: Entry }
+ let res: Res = try await call("send", ["botId": botId, "text": text, "clientNonce": clientNonce])
+ return res.entry
+ }
+
+ func stop(_ botId: String) async throws {
+ let _: Empty = try await call("stop", ["botId": botId])
+ }
+
+ func newSession(_ botId: String) async throws {
+ let _: Empty = try await call("newSession", ["botId": botId])
+ }
+
+ func respondPermission(entryId: String, optionId: String?) async throws {
+ struct Body: Encodable { var entryId: String; var optionId: String? }
+ let _: Empty = try await call("respondPermission", Body(entryId: entryId, optionId: optionId))
+ }
+
+ func registerDevice(ticket: String, relay: String, name: String) async throws {
+ let _: Empty = try await call("registerDevice", ["ticket": ticket, "relay": relay, "name": name])
+ }
+
+ func registerActivity(botId: String, ticket: String) async throws {
+ let _: Empty = try await call("registerActivity", ["botId": botId, "ticket": ticket])
+ }
+
+ func usage(refresh: Bool = false) async throws -> Usage {
+ try await call("usage", ["refresh": refresh])
+ }
+
+ func listDirs(_ path: String?) async throws -> DirListing {
+ struct Body: Encodable { var path: String? }
+ return try await call("listDirs", Body(path: path))
+ }
+}
diff --git a/CodyncKit/Sources/CodyncKit/Models.swift b/CodyncKit/Sources/CodyncKit/Models.swift
new file mode 100644
index 00000000..8e6996a0
--- /dev/null
+++ b/CodyncKit/Sources/CodyncKit/Models.swift
@@ -0,0 +1,272 @@
+import Foundation
+
+// Wire types for codync-host (see host/src/api.rs). Field names match the
+// host's camelCase JSON. Timestamps are epoch milliseconds.
+
+public struct Bot: Codable, Identifiable, Hashable, Sendable {
+ public var id: String
+ public var name: String
+ public var description: String
+ public var avatarColor: String
+ public var avatarShape: String
+ public var backend: String
+ public var command: String?
+ public var cwd: String
+ /// `ask` or `auto`.
+ public var permission: String
+ public var model: String?
+ public var pinned: Bool
+ public var hidden: Bool
+ public var notify: Bool?
+ public var createdAt: Int64
+
+ // Runtime, filled in by the host.
+ public var rev: Int64
+ /// idle | working | needsInput | error
+ public var status: String
+ public var activity: String
+ public var startedAt: Int64?
+ public var unread: Int
+ public var lastMessage: String?
+ public var lastAt: Int64
+
+ public var isWorking: Bool { status == "working" || status == "needsInput" }
+ public var needsInput: Bool { status == "needsInput" }
+ public var folderName: String { (cwd as NSString).lastPathComponent }
+}
+
+/// Just enough of a `bot` event to detect deletions.
+struct BotStub: Decodable {
+ var id: String
+ var deleted: Bool?
+ var rev: Int64
+}
+
+public struct Entry: Codable, Identifiable, Hashable, Sendable {
+ public var id: String
+ public var seq: Int64
+ public var botId: String
+ public var rev: Int64
+ /// user | agent | thought | tool | plan | permission | notice
+ public var kind: String
+ public var turn: Int64
+ public var data: EntryData
+ public var createdAt: Int64
+ public var updatedAt: Int64
+
+ public init(id: String, seq: Int64, botId: String, rev: Int64, kind: String, turn: Int64, data: EntryData, createdAt: Int64, updatedAt: Int64) {
+ self.id = id
+ self.seq = seq
+ self.botId = botId
+ self.rev = rev
+ self.kind = kind
+ self.turn = turn
+ self.data = data
+ self.createdAt = createdAt
+ self.updatedAt = updatedAt
+ }
+
+ /// Chat-visible (Grok Bot model): user messages, final replies, approval cards, notices.
+ public var isChat: Bool {
+ switch kind {
+ case "user", "permission", "notice": true
+ case "agent": data.final == true
+ default: false
+ }
+ }
+
+ public var date: Date { Date(milliseconds: createdAt) }
+}
+
+public struct EntryData: Codable, Hashable, Sendable {
+ public var text: String?
+ public var final: Bool?
+ /// user: queued | sent | cancelled | failed · tool: pending | in_progress | completed | failed · permission: pending | answered | cancelled | expired
+ public var status: String?
+ public var clientNonce: String?
+ public var title: String?
+ public var toolKind: String?
+ public var output: String?
+ public var diffs: [FileDiff]?
+ public var locations: [Location]?
+ public var options: [PermissionOption]?
+ public var selected: String?
+ public var command: String?
+ public var detail: String?
+ public var cwd: String?
+ public var entries: [PlanItem]?
+ /// notice: info | error | divider
+ public var style: String?
+
+ public init(text: String? = nil, status: String? = nil, clientNonce: String? = nil) {
+ self.text = text
+ self.status = status
+ self.clientNonce = clientNonce
+ }
+}
+
+public struct FileDiff: Codable, Hashable, Sendable {
+ public var path: String
+ public var added: Int
+ public var removed: Int
+ public var isNew: Bool
+ public var startLine: Int
+ public var patch: String
+}
+
+public struct Location: Codable, Hashable, Sendable {
+ public var path: String
+ public var line: Int?
+}
+
+public struct PermissionOption: Codable, Hashable, Sendable, Identifiable {
+ public var optionId: String
+ public var name: String
+ /// allow_once | allow_always | reject_once | reject_always
+ public var kind: String
+ public var id: String { optionId }
+}
+
+public struct PlanItem: Codable, Hashable, Sendable {
+ public var content: String
+ public var status: String
+ public var priority: String?
+}
+
+public struct Usage: Codable, Hashable, Sendable {
+ public var providers: [UsageProvider]
+ public init(providers: [UsageProvider] = []) { self.providers = providers }
+}
+
+public struct UsageProvider: Codable, Hashable, Sendable, Identifiable {
+ public var id: String
+ public var name: String
+ public var windows: [UsageWindow]
+ public var source: String
+ public var updatedAt: Int64
+}
+
+public struct UsageWindow: Codable, Hashable, Sendable, Identifiable {
+ public var id: String
+ public var label: String
+ public var percent: Double
+ public var resetsAt: Int64?
+ public var resetDate: Date? { resetsAt.map(Date.init(milliseconds:)) }
+}
+
+public struct Backend: Codable, Hashable, Sendable, Identifiable {
+ public var id: String
+ public var name: String
+ public var available: Bool
+ public var command: String
+ public var installHint: String
+}
+
+public struct Hello: Codable, Sendable {
+ public var hostId: String
+ public var name: String
+ public var version: String
+ public var os: String
+ public var home: String?
+ public var backends: [Backend]
+ public var rev: Int64
+}
+
+public struct SyncResponse: Codable, Sendable {
+ public var hostId: String
+ public var rev: Int64
+ public var bots: [Bot]
+ public var entries: [Entry]
+ public var usage: Usage
+}
+
+public struct DirListing: Codable, Sendable {
+ public var path: String
+ public var parent: String?
+ public var isGit: Bool
+ public var dirs: [DirItem]
+}
+
+public struct DirItem: Codable, Hashable, Sendable, Identifiable {
+ public var name: String
+ public var path: String
+ public var isGit: Bool
+ public var id: String { path }
+}
+
+/// Create / update payload for a bot.
+public struct BotDraft: Codable, Hashable, Sendable {
+ public var id: String?
+ public var name: String
+ public var description: String
+ public var avatarColor: String
+ public var avatarShape: String
+ public var backend: String
+ public var command: String?
+ public var cwd: String
+ public var permission: String
+ public var model: String?
+ public var pinned: Bool?
+ public var hidden: Bool?
+ public var notify: Bool?
+
+ public init(name: String = "", description: String = "", avatarColor: String = AvatarPalette.colors.randomElement()!.id,
+ avatarShape: String = AvatarPalette.shapes.randomElement()!, backend: String = "claude", cwd: String = "",
+ permission: String = "ask") {
+ self.name = name
+ self.description = description
+ self.avatarColor = avatarColor
+ self.avatarShape = avatarShape
+ self.backend = backend
+ self.cwd = cwd
+ self.permission = permission
+ }
+
+ public init(_ bot: Bot) {
+ id = bot.id
+ name = bot.name
+ description = bot.description
+ avatarColor = bot.avatarColor
+ avatarShape = bot.avatarShape
+ backend = bot.backend
+ command = bot.command
+ cwd = bot.cwd
+ permission = bot.permission
+ model = bot.model
+ pinned = bot.pinned
+ hidden = bot.hidden
+ notify = bot.notify
+ }
+}
+
+public extension Date {
+ init(milliseconds: Int64) { self.init(timeIntervalSince1970: Double(milliseconds) / 1000) }
+}
+
+extension Bot {
+ /// Lenient: a host that is a little newer or older than the app still yields a usable bot.
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ id = try c.decode(String.self, forKey: .id)
+ name = try c.decodeIfPresent(String.self, forKey: .name) ?? "Bot"
+ description = try c.decodeIfPresent(String.self, forKey: .description) ?? ""
+ avatarColor = try c.decodeIfPresent(String.self, forKey: .avatarColor) ?? "blue"
+ avatarShape = try c.decodeIfPresent(String.self, forKey: .avatarShape) ?? "blob"
+ backend = try c.decodeIfPresent(String.self, forKey: .backend) ?? "custom"
+ command = try c.decodeIfPresent(String.self, forKey: .command)
+ cwd = try c.decodeIfPresent(String.self, forKey: .cwd) ?? ""
+ permission = try c.decodeIfPresent(String.self, forKey: .permission) ?? "ask"
+ model = try c.decodeIfPresent(String.self, forKey: .model)
+ pinned = try c.decodeIfPresent(Bool.self, forKey: .pinned) ?? false
+ hidden = try c.decodeIfPresent(Bool.self, forKey: .hidden) ?? false
+ notify = try c.decodeIfPresent(Bool.self, forKey: .notify)
+ createdAt = try c.decodeIfPresent(Int64.self, forKey: .createdAt) ?? 0
+ rev = try c.decodeIfPresent(Int64.self, forKey: .rev) ?? 0
+ status = try c.decodeIfPresent(String.self, forKey: .status) ?? "idle"
+ activity = try c.decodeIfPresent(String.self, forKey: .activity) ?? ""
+ startedAt = try c.decodeIfPresent(Int64.self, forKey: .startedAt)
+ unread = try c.decodeIfPresent(Int.self, forKey: .unread) ?? 0
+ lastMessage = try c.decodeIfPresent(String.self, forKey: .lastMessage)
+ lastAt = try c.decodeIfPresent(Int64.self, forKey: .lastAt) ?? createdAt
+ }
+}
diff --git a/CodyncKit/Sources/CodyncKit/SharedStore.swift b/CodyncKit/Sources/CodyncKit/SharedStore.swift
new file mode 100644
index 00000000..1b0d379c
--- /dev/null
+++ b/CodyncKit/Sources/CodyncKit/SharedStore.swift
@@ -0,0 +1,35 @@
+import Foundation
+
+/// Values shared between the iOS app and its widgets through the App Group.
+public enum SharedStore {
+ public static let appGroup = "group.com.pokai.Codync"
+ /// Codync push relay (relay/ in this repo).
+ public static let relayURL = "https://codync-relay.kevin2005ha.workers.dev"
+
+ private static var defaults: UserDefaults { UserDefaults(suiteName: appGroup) ?? .standard }
+
+ public static var pairing: Pairing? {
+ get { defaults.data(forKey: "pairing").flatMap { try? JSONDecoder().decode(Pairing.self, from: $0) } }
+ set { defaults.set(newValue.flatMap { try? JSONEncoder().encode($0) }, forKey: "pairing") }
+ }
+
+ /// Last address that answered, tried first next time.
+ public static var preferredURL: String? {
+ get { defaults.string(forKey: "preferredURL") }
+ set { defaults.set(newValue, forKey: "preferredURL") }
+ }
+
+ public static var usage: Usage? {
+ get { defaults.data(forKey: "usage").flatMap { try? JSONDecoder().decode(Usage.self, from: $0) } }
+ set { defaults.set(newValue.flatMap { try? JSONEncoder().encode($0) }, forKey: "usage") }
+ }
+
+ /// Pairing with the last working address moved to the front.
+ public static var orderedPairing: Pairing? {
+ guard var p = pairing else { return nil }
+ if let preferred = preferredURL, let i = p.urls.firstIndex(of: preferred) {
+ p.urls.insert(p.urls.remove(at: i), at: 0)
+ }
+ return p
+ }
+}
diff --git a/CodyncKit/Sources/CodyncKit/Theme.swift b/CodyncKit/Sources/CodyncKit/Theme.swift
new file mode 100644
index 00000000..97255a07
--- /dev/null
+++ b/CodyncKit/Sources/CodyncKit/Theme.swift
@@ -0,0 +1,123 @@
+import SwiftUI
+
+#if canImport(UIKit)
+import UIKit
+private typealias PlatformColor = UIColor
+#else
+import AppKit
+private typealias PlatformColor = NSColor
+#endif
+
+private extension PlatformColor {
+ convenience init(hex: UInt32, alpha: CGFloat = 1) {
+ self.init(
+ red: CGFloat((hex >> 16) & 0xFF) / 255,
+ green: CGFloat((hex >> 8) & 0xFF) / 255,
+ blue: CGFloat(hex & 0xFF) / 255,
+ alpha: alpha
+ )
+ }
+}
+
+public extension Color {
+ init(hex: UInt32) {
+ self.init(red: Double((hex >> 16) & 0xFF) / 255, green: Double((hex >> 8) & 0xFF) / 255, blue: Double(hex & 0xFF) / 255)
+ }
+
+ /// Light/dark pair resolved by the system appearance.
+ init(light: UInt32, dark: UInt32) {
+ #if canImport(UIKit)
+ self.init(uiColor: UIColor { $0.userInterfaceStyle == .dark ? UIColor(hex: dark) : UIColor(hex: light) })
+ #else
+ self.init(nsColor: NSColor(name: nil) { appearance in
+ appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? NSColor(hex: dark) : NSColor(hex: light)
+ })
+ #endif
+ }
+}
+
+/// Palette lifted from Grok Bot's shipped renderer: green-tinted graphite with a lime accent.
+public enum Palette {
+ public static let background = Color(light: 0xF6F7F3, dark: 0x121411)
+ public static let surface = Color(light: 0xFFFFFF, dark: 0x1A1D19)
+ public static let bubbleAgent = Color(light: 0xECEFE7, dark: 0x20231F)
+ public static let border = Color(light: 0xDCE0D6, dark: 0x343832)
+ public static let text = Color(light: 0x1A1D19, dark: 0xEEF3E7)
+ public static let secondary = Color(light: 0x5B6256, dark: 0xA9AFA3)
+ public static let tertiary = Color(light: 0x8A9184, dark: 0x747B70)
+ /// Lime used for fills (user bubbles, primary buttons).
+ public static let accentFill = Color(hex: 0xC7EC6B)
+ /// Lime/olive readable as text on the background.
+ public static let accent = Color(light: 0x557212, dark: 0xC7EC6B)
+ public static let onAccent = Color(hex: 0x141712)
+ public static let accentDim = Color(light: 0xC9D9A0, dark: 0x53632F)
+ public static let danger = Color(light: 0xC23A2B, dark: 0xF0A7A7)
+ public static let warning = Color(hex: 0xFF9800)
+ public static let codeBackground = Color(light: 0xF0F2EC, dark: 0x1A1D19)
+ public static let added = Color(light: 0x2E7D32, dark: 0x8FD18B)
+ public static let removed = Color(light: 0xC62828, dark: 0xF0A7A7)
+}
+
+public enum AvatarPalette {
+ public struct Swatch: Identifiable, Hashable, Sendable {
+ public let id: String
+ public let label: String
+ public let hex: UInt32
+ public var color: Color { Color(hex: hex) }
+ }
+
+ public static let colors: [Swatch] = [
+ .init(id: "black", label: "Black", hex: 0x2B2B2B),
+ .init(id: "brown", label: "Brown", hex: 0x936439),
+ .init(id: "red", label: "Red", hex: 0xFF263C),
+ .init(id: "orange", label: "Orange", hex: 0xFF6700),
+ .init(id: "yellow", label: "Yellow", hex: 0xFF9800),
+ .init(id: "green", label: "Green", hex: 0x00C972),
+ .init(id: "cyan", label: "Cyan", hex: 0x00BCA6),
+ .init(id: "blue", label: "Blue", hex: 0x1084FE),
+ .init(id: "violet", label: "Violet", hex: 0x9159FE),
+ .init(id: "magenta", label: "Magenta", hex: 0xFF309B),
+ .init(id: "gray", label: "Gray", hex: 0x777777),
+ ]
+
+ public static let shapes = ["blob", "pebble", "squircle", "tablet", "wedge", "hex", "cloud", "teardrop"]
+
+ public static func color(_ id: String) -> Color {
+ (colors.first { $0.id == id } ?? colors[7]).color
+ }
+}
+
+public enum RelativeTime {
+ /// Grok-style compact age: now · 5m · 3h · 2d · Sep 3
+ public static func short(_ date: Date, now: Date = .now) -> String {
+ let s = max(0, now.timeIntervalSince(date))
+ switch s {
+ case ..<60: return "now"
+ case ..<3600: return "\(Int(s / 60))m"
+ case ..<86_400: return "\(Int(s / 3600))h"
+ case ..<(86_400 * 7): return "\(Int(s / 86_400))d"
+ default: return date.formatted(.dateTime.month(.abbreviated).day())
+ }
+ }
+
+ public static func until(_ date: Date, now: Date = .now) -> String {
+ let s = max(0, date.timeIntervalSince(now))
+ let h = Int(s / 3600), m = Int(s.truncatingRemainder(dividingBy: 3600) / 60)
+ if h >= 48 { return "\(h / 24)d" }
+ if h > 0 { return "\(h)h \(m)m" }
+ return "\(m)m"
+ }
+}
+
+public enum BackendInfo {
+ public static func name(_ id: String) -> String {
+ switch id {
+ case "claude": "Claude Code"
+ case "codex": "Codex"
+ case "opencode": "OpenCode"
+ case "grok": "Grok Build"
+ case "gemini": "Gemini CLI"
+ default: "Custom agent"
+ }
+ }
+}
diff --git a/CodyncKit/Tests/CodyncKitTests/CodyncKitTests.swift b/CodyncKit/Tests/CodyncKitTests/CodyncKitTests.swift
new file mode 100644
index 00000000..4a707310
--- /dev/null
+++ b/CodyncKit/Tests/CodyncKitTests/CodyncKitTests.swift
@@ -0,0 +1,35 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+@Test func parsesHostEvents() throws {
+ let url = try #require(Bundle.module.url(forResource: "events", withExtension: "txt", subdirectory: "Fixtures"))
+ let lines = try String(contentsOf: url, encoding: .utf8).split(separator: "\n")
+ let events = lines.compactMap { HostClient.parseEvent(Data($0.dropFirst(5).utf8)) }
+ #expect(events.count == 6)
+ guard case let .hello(hostId, rev, usage) = events[0] else { Issue.record("hello"); return }
+ #expect(hostId == "h1" && rev == 42 && usage.providers.first?.windows.first?.percent == 8)
+ guard case let .bot(bot) = events[1] else { Issue.record("bot"); return }
+ #expect(bot.name == "Rex" && bot.command == nil && !bot.isWorking)
+ guard case let .entry(perm) = events[2] else { Issue.record("perm"); return }
+ #expect(perm.isChat && perm.data.options?.first?.kind == "allow_once")
+ guard case let .entry(tool) = events[3] else { Issue.record("tool"); return }
+ #expect(!tool.isChat && tool.data.diffs?.first?.added == 1)
+ guard case let .botDeleted(id, _) = events[4] else { Issue.record("deleted"); return }
+ #expect(id == "b2")
+}
+
+@Test func parsesPairingURL() throws {
+ let p = try #require(Pairing(string: "codync://pair?name=Kevin%27s%20Mac&token=t0k&urls=http%3A%2F%2F100.1.2.3%3A19222%2Chttp%3A%2F%2Fa%3A1"))
+ #expect(p.name == "Kevin's Mac")
+ #expect(p.token == "t0k")
+ #expect(p.urls == ["http://100.1.2.3:19222", "http://a:1"])
+ #expect(Pairing(string: "codync://pair?token=") == nil)
+}
+
+@Test func relativeTime() {
+ let now = Date(timeIntervalSince1970: 1_000_000)
+ #expect(RelativeTime.short(now.addingTimeInterval(-30), now: now) == "now")
+ #expect(RelativeTime.short(now.addingTimeInterval(-600), now: now) == "10m")
+ #expect(RelativeTime.short(now.addingTimeInterval(-7200), now: now) == "2h")
+}
diff --git a/CodyncKit/Tests/CodyncKitTests/Fixtures/events.txt b/CodyncKit/Tests/CodyncKitTests/Fixtures/events.txt
new file mode 100644
index 00000000..c43fef18
--- /dev/null
+++ b/CodyncKit/Tests/CodyncKitTests/Fixtures/events.txt
@@ -0,0 +1,6 @@
+data: {"type":"hello","hostId":"h1","rev":42,"usage":{"providers":[{"id":"claude","name":"Claude","source":"oauth","updatedAt":1,"windows":[{"id":"five_hour","label":"5-hour","percent":8.0,"resetsAt":1790283599811}]}]}}
+data: {"type":"bot","rev":2,"bot":{"activity":"","avatarColor":"blue","avatarShape":"blob","backend":"claude","command":null,"createdAt":1790275262217,"cwd":"/tmp/work","deleted":false,"description":"Terse reviewer.","hidden":false,"id":"b1","lastAt":1790275262217,"lastMessage":null,"model":null,"name":"Rex","notify":null,"permission":"ask","pinned":false,"rev":2,"startedAt":null,"status":"idle","unread":0}}
+data: {"type":"entry","rev":56,"entry":{"botId":"b1","createdAt":1,"data":{"command":"sed -i s/x/y/ a.txt","cwd":"/tmp","detail":"","diffs":[],"options":[{"kind":"allow_once","name":"Allow","optionId":"allow"}],"selected":null,"status":"pending","title":"Edit a.txt","toolKind":"edit"},"id":"e1","kind":"permission","rev":56,"seq":7,"turn":2,"updatedAt":1}}
+data: {"type":"entry","rev":57,"entry":{"botId":"b1","createdAt":1,"data":{"diffs":[{"added":1,"isNew":false,"patch":"-x\n+y\n","path":"a.txt","removed":1,"startLine":1}],"locations":null,"output":"","status":"pending","title":"Edit a.txt","toolCallId":"t1","toolKind":"edit"},"id":"e2","kind":"tool","rev":57,"seq":8,"turn":2,"updatedAt":1}}
+data: {"type":"bot","rev":60,"bot":{"id":"b2","deleted":true,"rev":60}}
+data: {"type":"resync"}
diff --git a/CodyncLiveActivity/CodyncLiveActivityBundle.swift b/CodyncLiveActivity/CodyncLiveActivityBundle.swift
deleted file mode 100644
index 7c895e81..00000000
--- a/CodyncLiveActivity/CodyncLiveActivityBundle.swift
+++ /dev/null
@@ -1,10 +0,0 @@
-import WidgetKit
-import SwiftUI
-
-@main
-struct CodyncLiveActivityBundle: WidgetBundle {
- var body: some Widget {
- CodyncLiveActivityWidget()
- OverallLiveActivityWidget()
- }
-}
diff --git a/CodyncLiveActivity/CodyncLiveActivityWidget.swift b/CodyncLiveActivity/CodyncLiveActivityWidget.swift
deleted file mode 100644
index f3347ffb..00000000
--- a/CodyncLiveActivity/CodyncLiveActivityWidget.swift
+++ /dev/null
@@ -1,909 +0,0 @@
-import ActivityKit
-import WidgetKit
-import SwiftUI
-import CodyncShared
-
-/// Monochrome palette — dark navy for light mode, white for dark mode
-private let widgetFgLight = Color(red: 47/255, green: 59/255, blue: 84/255)
-private let widgetFgDark = Color(red: 0.93, green: 0.93, blue: 0.93)
-
-/// Legacy alias used in Dynamic Island (always dark background)
-private let widgetFg = widgetFgLight
-
-/// Shared SF Symbol name for the code icon used across all DI/Watch views
-private let codeIconName = "chevron.left.forwardslash.chevron.right"
-
-/// Code icon opacity based on session state
-private func codeIconOpacity(isBusy: Bool, isCompleted: Bool) -> Double {
- isBusy ? 0.8 : (isCompleted ? 0.3 : 0.5)
-}
-
-/// Treat empty strings as nil — CloudKit stores nil optionals as ""
-private func nonEmpty(_ value: String?) -> String? {
- guard let value, !value.isEmpty else { return nil }
- return value
-}
-
-/// Simplify tool text: "Running: cd /Users/foo/bar && cmd" → "Running command"
-private func simplifyToolText(_ text: String?) -> String? {
- guard let text, !text.isEmpty else { return nil }
- let lower = text.lowercased()
- if lower.hasPrefix("running:") || lower.contains("bash") { return "Running command" }
- if lower.hasPrefix("reading") {
- let file = URL(fileURLWithPath: text.replacingOccurrences(of: "Reading ", with: "")).lastPathComponent
- return file.isEmpty ? "Reading file" : "Reading \(file)"
- }
- if lower.hasPrefix("editing") || lower.hasPrefix("writing") {
- let file = URL(fileURLWithPath: text.replacingOccurrences(of: "Editing ", with: "").replacingOccurrences(of: "Writing ", with: "")).lastPathComponent
- return file.isEmpty ? "Editing file" : "Editing \(file)"
- }
- if lower.contains("grep") || lower.contains("search") { return "Searching code" }
- if lower.contains("glob") { return "Finding files" }
- if lower.contains("agent") { return "Dispatching agent" }
- if lower.contains("git") { return "Git operation" }
- if lower.contains("web") || lower.contains("fetch") { return "Fetching web" }
- if lower.contains("mcp") { return "Using tool" }
- if text.count > 40 { return String(text.prefix(37)) + "…" }
- return text
-}
-
-/// Status label shared across all widgets
-private func statusLabel(_ status: String) -> String {
- switch status {
- case "working": "Working"
- case "idle": "Idle"
- case "needsInput": "Needs Input"
- case "compacting": "Compacting"
- case "error": "Error"
- case "completed": "Complete"
- default: "Working"
- }
-}
-
-struct CodyncLiveActivityWidget: Widget {
- let kind: String = "CodyncLiveActivity"
-
- var body: some WidgetConfiguration {
- ActivityConfiguration(for: CodyncAttributes.self) { context in
- ActivityFamilyRouter {
- WatchIndividualView(attributes: context.attributes, state: context.state)
- } medium: {
- lockScreenBanner(context: context)
- }
- } dynamicIsland: { context in
- DynamicIsland {
- DynamicIslandExpandedRegion(.leading) {
- Image(systemName: codeIconName)
- .font(.system(size: 11, weight: .bold))
- .foregroundStyle(.white.opacity(codeIconOpacity(isBusy: context.state.isBusy, isCompleted: context.state.isCompleted)))
- .padding(.top, 4)
- }
- DynamicIslandExpandedRegion(.center) {
- VStack(alignment: .leading, spacing: 4) {
- Text(context.attributes.projectName)
- .font(.headline)
- Text(simplifyToolText(context.state.currentTask) ?? statusLabel(context.state.status))
- .font(.subheadline)
- .foregroundStyle(.secondary)
- .lineLimit(2)
- .id(context.state.currentTask ?? context.state.status)
- .transition(.push(from: .bottom))
- }
- }
- DynamicIslandExpandedRegion(.trailing) {
- if context.state.costUSD > 0 {
- Text(String(format: "$%.2f", context.state.costUSD))
- .font(.system(size: 11, weight: .semibold).monospacedDigit())
- .foregroundStyle(.white.opacity(0.5))
- .padding(.top, 4)
- }
- }
- DynamicIslandExpandedRegion(.bottom) {
- if context.state.totalCount > 0 {
- HStack(spacing: 2) {
- ForEach(Array(context.state.tasks.enumerated()), id: \.offset) { _, task in
- RoundedRectangle(cornerRadius: 2)
- .fill(islandTaskColor(task.status))
- .frame(height: 4)
- }
- }
- } else {
- HStack(spacing: 6) {
- let completed = context.state.tasks.filter { $0.status == .completed }
- if let prev = completed.last, !context.state.isCompleted {
- Image(systemName: "checkmark")
- .font(.caption2.weight(.semibold))
- .foregroundStyle(.white.opacity(0.7))
- Text(prev.truncatedContent)
- .font(.caption2)
- .foregroundStyle(.secondary)
- .lineLimit(1)
- }
- Spacer()
- }
- }
- }
- } compactLeading: {
- Image(systemName: codeIconName)
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(.white.opacity(codeIconOpacity(isBusy: context.state.isBusy, isCompleted: context.state.isCompleted)))
- } compactTrailing: {
- Image(systemName: compactTrailingIcon(context.state.status))
- .font(.system(size: 10, weight: .semibold))
- .foregroundStyle(.white.opacity(compactTrailingOpacity(context.state.status)))
- } minimal: {
- Image(systemName: codeIconName)
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(.white.opacity(codeIconOpacity(isBusy: context.state.isBusy, isCompleted: context.state.isCompleted)))
- }
- }
- .supplementalActivityFamilies([.small])
- }
-
- // MARK: - Lock Screen Banner
-
- @ViewBuilder
- private func lockScreenBanner(context: ActivityViewContext<CodyncAttributes>) -> some View {
- if context.state.totalCount > 0 {
- progressBanner(context: context)
- } else {
- cardBanner(context: context)
- }
- }
-
- // MARK: - Progress Bar Mode
-
- @ViewBuilder
- private func progressBanner(context: ActivityViewContext<CodyncAttributes>) -> some View {
- let state = context.state
- let dark = state.isDark
- let fg = dark ? widgetFgDark : widgetFgLight
- let progress = state.totalCount > 0
- ? Double(state.completedCount) / Double(state.totalCount)
- : 0
-
- VStack(alignment: .leading, spacing: 0) {
- bannerHeader(context: context)
-
- VStack(alignment: .leading, spacing: 10) {
- if state.isCompleted {
- HStack(spacing: 8) {
- Image(systemName: "checkmark.circle.fill")
- .font(.system(size: 20))
- .foregroundStyle(fg)
- VStack(alignment: .leading, spacing: 1) {
- Text("All tasks complete")
- .font(.subheadline.bold())
- .foregroundStyle(fg)
- Text("$\(String(format: "%.2f", state.costUSD))")
- .font(.caption)
- .foregroundStyle(fg.opacity(0.5))
- }
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(.horizontal, 6)
- } else if let task = nonEmpty(state.currentTask) {
- HStack(alignment: .top, spacing: 6) {
- Image(systemName: "arrow.turn.down.right")
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(fg.opacity(0.4))
- .frame(width: 16, height: 16)
- .padding(.top, 1)
- Text(task)
- .font(.callout)
- .foregroundStyle(fg)
- .lineLimit(2)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- .padding(.horizontal, 6)
- .id(task)
- .transition(.push(from: .bottom))
- }
-
- VStack(spacing: 6) {
- HStack(spacing: 2) {
- ForEach(Array(state.tasks.enumerated()), id: \.offset) { _, task in
- RoundedRectangle(cornerRadius: 3)
- .fill(taskColor(task.status, isDark: dark))
- .frame(height: 6)
- }
- }
- .padding(.horizontal, 6)
-
- HStack {
- Text("\(state.completedCount)/\(state.totalCount) tasks")
- .font(.caption)
- .foregroundStyle(fg.opacity(0.5))
- Spacer()
- Text("\(Int(progress * 100))%")
- .font(.caption.bold())
- .foregroundStyle(fg.opacity(0.6))
- }
- .padding(.horizontal, 6)
- }
- }
- .frame(maxHeight: .infinity)
-
- bannerFooter(context: context, isWaiting: false)
- }
- .padding(.horizontal, 8)
- .padding(.vertical, 10)
- .frame(height: 160)
- .background(dark ? Color.black.opacity(0.8) : Color.white.opacity(state.isCompleted ? 1 : 0.75))
- .activityBackgroundTint(.clear)
- }
-
- // MARK: - Card Stack Mode
-
- @ViewBuilder
- private func cardBanner(context: ActivityViewContext<CodyncAttributes>) -> some View {
- let state = context.state
- let dark = state.isDark
- let fg = dark ? widgetFgDark : widgetFgLight
-
- let prevTool = nonEmpty(state.previousTask)
- let hasToolActivity = prevTool != nil
- let isWaiting = !hasToolActivity && !state.isCompleted
-
- VStack(alignment: .leading, spacing: 4) {
- bannerHeader(context: context)
-
- ZStack {
- if state.isCompleted {
- VStack(alignment: .center, spacing: 8) {
- Image(systemName: "checkmark")
- .font(.system(size: 16, weight: .bold))
- .foregroundStyle(dark ? Color.black : Color.white)
- .frame(width: 28, height: 28)
- .background(fg, in: Circle())
-
- VStack(spacing: 2) {
- Text("Session Complete")
- .font(.subheadline.bold())
- .foregroundStyle(fg)
- Text("$\(String(format: "%.2f", state.costUSD))")
- .font(.footnote)
- .foregroundStyle(fg.opacity(0.5))
- }
- }
- .frame(maxWidth: .infinity)
- .padding(.bottom, 12)
- } else if isWaiting {
- let prompt = nonEmpty(context.attributes.summary) ?? "Analyzing code…"
- Text(prompt)
- .lineLimit(2)
- .multilineTextAlignment(.leading)
- .foregroundStyle(dark ? .white : .blue)
- .padding(12)
- .frame(minWidth: 52)
- .background(
- (dark ? Color.white : Color.blue).opacity(0.12),
- in: RoundedRectangle(cornerRadius: 16, style: .continuous)
- )
- .padding(.leading, 48)
- .padding(.trailing, 8)
- .font(.callout)
- .frame(maxWidth: .infinity, alignment: .trailing)
- .transition(.push(from: .bottom))
- } else {
- // Stacked cards: secondPrevious behind, previous in front
- let secondPrev = nonEmpty(state.secondPreviousTask)
- ZStack {
- if let sp = secondPrev {
- TaskCard(
- text: simplifyToolText(sp) ?? sp,
- icon: toolIcon(for: sp),
- isBehind: true,
- isDark: dark
- )
- }
- TaskCard(
- text: simplifyToolText(prevTool) ?? prevTool ?? "",
- icon: toolIcon(for: prevTool),
- isBehind: false,
- isDark: dark
- )
- .id(prevTool)
- .transition(.asymmetric(
- insertion: .offset(y: 120),
- removal: .opacity
- ))
- }
- .compositingGroup()
- }
- }
- .frame(height: 80)
- .padding(.bottom, 8)
- .frame(maxHeight: .infinity)
- .zIndex(10)
-
- bannerFooter(context: context, isWaiting: isWaiting)
- }
- .padding(.horizontal, 8)
- .padding(.vertical, 10)
- .frame(height: 160)
- .background(dark ? Color.black.opacity(0.8) : Color.white.opacity(isWaiting || state.isCompleted ? 1 : 0.75))
- .activityBackgroundTint(.clear)
- }
-
- // MARK: - Shared Components
-
- @ViewBuilder
- private func bannerHeader(context: ActivityViewContext<CodyncAttributes>) -> some View {
- let state = context.state
- let fg = state.isDark ? widgetFgDark : widgetFgLight
-
- HStack(spacing: 10) {
- HStack(spacing: 6) {
- Image(systemName: codeIconName)
- .font(.system(size: 10, weight: .bold))
- .foregroundStyle(fg.opacity(0.6))
- .frame(width: 21, height: 21)
- .background(fg.opacity(0.08), in: Circle())
-
- Text(context.attributes.projectName)
- .font(.callout.bold())
- .opacity(0.72)
- .lineLimit(1)
- }
-
- Spacer()
-
- if state.costUSD > 0 {
- let costStr = String(format: "$%.2f", state.costUSD)
- let alert = state.costUSD >= 1.0
- Text(costStr)
- .font(.subheadline)
- .fontWeight(.regular)
- .padding(.vertical, 4)
- .padding(.horizontal, 8)
- .overlay {
- Capsule()
- .stroke(fg.opacity(alert ? 0.06 : 0.12))
- }
- .background(fg.opacity(alert ? 0.12 : 0), in: Capsule())
- .monospacedDigit()
- } else {
- HStack(spacing: 5) {
- Circle()
- .fill(fg)
- .frame(width: 5, height: 5)
- Text(statusLabel(state.status))
- .opacity(0.48)
- }
- .transition(.push(from: .bottom))
- }
- }
- .font(.subheadline.bold())
- .frame(height: 28)
- .padding(.horizontal, 6)
- .foregroundStyle(fg)
- }
-
- @ViewBuilder
- private func bannerFooter(context: ActivityViewContext<CodyncAttributes>, isWaiting: Bool) -> some View {
- let state = context.state
- let fg = state.isDark ? widgetFgDark : widgetFgLight
-
- HStack(spacing: 6) {
- if state.isCompleted {
- Text("^[\(state.totalCount) task](inflect: true) completed")
- .transition(.push(from: .bottom))
- .padding(.leading, 8)
- } else {
- HStack(spacing: 4) {
- Image(systemName: toolIcon(for: state.currentTask))
- .font(.system(size: 10, weight: .semibold))
- .frame(width: 20, height: 18)
- Text(isWaiting ? "Thinking…" : (nonEmpty(state.currentTask) ?? statusLabel(state.status)))
- .lineLimit(1)
- .frame(maxWidth: .infinity, alignment: .leading)
- .multilineTextAlignment(.leading)
- }
- .id(state.currentTask)
- .transition(.push(from: .bottom))
- }
-
- Spacer()
-
- if !isWaiting {
- Text("00:00")
- .opacity(0)
- .overlay(alignment: .trailing) {
- Text(state.sessionStartDate, style: .timer)
- .contentTransition(.numericText(countsDown: false))
- .opacity(0.5)
- }
- .font(.footnote.bold())
- .monospacedDigit()
- .multilineTextAlignment(.trailing)
- .layoutPriority(1)
- }
- }
- .foregroundStyle(fg)
- .padding(.leading, 4)
- .padding(.trailing, 12)
- .font(.footnote.bold())
- .opacity(isWaiting || state.isCompleted ? 0.36 : 1)
- }
-
- // MARK: - Helpers
-
- /// Map Claude Code tool names to SF Symbol icons
- private func toolIcon(for task: String?) -> String {
- guard let task = task?.lowercased() else { return "arrow.turn.down.right" }
- if task.contains("read") || task.contains("reading") { return "doc.text" }
- if task.contains("edit") || task.contains("editing") || task.contains("write") || task.contains("writing") { return "pencil.line" }
- if task.contains("bash") || task.contains("command") || task.contains("running") { return "terminal" }
- if task.contains("grep") || task.contains("search") || task.contains("glob") { return "magnifyingglass" }
- if task.contains("agent") || task.contains("dispatch") { return "person.2" }
- if task.contains("notebook") { return "book" }
- if task.contains("web") || task.contains("fetch") { return "globe" }
- if task.contains("git") || task.contains("commit") || task.contains("push") { return "arrow.triangle.branch" }
- if task.contains("test") { return "checkmark.diamond" }
- if task.contains("todo") || task.contains("task") { return "checklist" }
- return "arrow.turn.down.right"
- }
-
-
- private func compactTrailingIcon(_ status: String) -> String {
- switch status {
- case "working", "compacting": codeIconName
- case "needsInput": "hand.raised.fill"
- case "completed": "checkmark"
- case "idle": "pause"
- default: codeIconName
- }
- }
-
- private func compactTrailingOpacity(_ status: String) -> Double {
- switch status {
- case "working", "compacting": 0.8
- case "needsInput": 1.0
- case "completed": 0.4
- case "idle": 0.4
- default: 0.6
- }
- }
-
- /// Lock Screen task segments — adapts to light/dark mode
- private func taskColor(_ status: TaskStatus, isDark: Bool = false) -> Color {
- let fg = isDark ? widgetFgDark : widgetFgLight
- switch status {
- case .completed: return fg
- case .inProgress: return fg.opacity(0.4)
- case .pending: return fg.opacity(0.12)
- }
- }
-
- /// Dynamic Island task segments — monochrome white at different opacities
- private func islandTaskColor(_ status: TaskStatus) -> Color {
- switch status {
- case .completed: .white
- case .inProgress: .white.opacity(0.4)
- case .pending: .white.opacity(0.12)
- }
- }
-}
-
-// MARK: - Task Card
-
-struct TaskCard: View {
- let text: String
- let icon: String
- let isBehind: Bool
- var isInProgress: Bool = false
- var isDark: Bool = false
-
- private var cornerRadius: CGFloat { isBehind ? 10 : 16 }
- private var fg: Color { isDark ? widgetFgDark : widgetFgLight }
- private var cardBg: Color {
- if isBehind {
- return isDark ? Color.white.opacity(0.08) : Color.white.opacity(0.85)
- }
- // Front card must be opaque to hide the card behind it
- return isDark ? Color(red: 0.14, green: 0.14, blue: 0.16) : Color.white
- }
-
- var body: some View {
- HStack(spacing: 8) {
- Image(systemName: isInProgress ? icon : "checkmark")
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(fg.opacity(0.5))
- .frame(width: 21, height: 21)
- .background(
- Circle()
- .foregroundStyle(fg.opacity(0.12))
- )
-
- Text(text)
- .font(.callout)
- .foregroundStyle(fg)
- .lineLimit(2)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- .padding(12)
- .frame(maxWidth: .infinity, alignment: .leading)
- .frame(height: 60)
- .background(cardBg, in: RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
- .scaleEffect(isBehind ? 0.9 : 1)
- .offset(y: isBehind ? 10 : 0)
- .opacity(isBehind ? 0.72 : 1)
- .zIndex(isBehind ? 0 : 1)
- .transition(.asymmetric(
- insertion: .offset(y: 120),
- removal: .opacity
- ))
- }
-}
-
-// MARK: - Overall Live Activity Widget
-
-struct OverallLiveActivityWidget: Widget {
- let kind: String = "CodyncOverallLiveActivity"
-
- var body: some WidgetConfiguration {
- ActivityConfiguration(for: OverallAttributes.self) { context in
- ActivityFamilyRouter {
- WatchOverallView(state: context.state)
- } medium: {
- overallLockScreen(context: context)
- }
- } dynamicIsland: { context in
- DynamicIsland {
- DynamicIslandExpandedRegion(.leading) {
- }
- DynamicIslandExpandedRegion(.center) {
- let primary = self.primarySession(from: context.state)
- let anyWorking = context.state.sessions.contains { $0.status == .working }
- HStack(spacing: 6) {
- Image(systemName: codeIconName)
- .font(.system(size: 11, weight: .bold))
- .foregroundStyle(.white.opacity(anyWorking ? 0.8 : 0.3))
- Text(primary?.projectName ?? "Codync")
- .font(.headline)
- if let task = simplifyToolText(primary?.currentTask) {
- Text(task)
- .font(.subheadline)
- .foregroundStyle(.white.opacity(0.5))
- .lineLimit(1)
- .id(task)
- .transition(.push(from: .bottom))
- }
- }
- }
- DynamicIslandExpandedRegion(.trailing) {
- }
- DynamicIslandExpandedRegion(.bottom) {
- let primaryId = context.state.primarySessionId
- let primary = self.primarySession(from: context.state)
- VStack(spacing: 4) {
- if let p = primary, p.totalCount > 0 {
- HStack(spacing: 2) {
- ForEach(0..<p.totalCount, id: \.self) { i in
- RoundedRectangle(cornerRadius: 2)
- .fill(.white.opacity(i < p.completedCount ? 1.0 : 0.12))
- .frame(height: 3)
- }
- }
- }
- HStack(spacing: 5) {
- ForEach(context.state.sessions, id: \.sessionId) { s in
- let isPrimary = s.sessionId == primaryId
- let isWorking = s.status == .working
- HStack(spacing: 3) {
- Circle()
- .fill(.white.opacity(isWorking ? 1.0 : 0.3))
- .frame(width: isWorking ? 5 : 4, height: isWorking ? 5 : 4)
- Text(s.projectName)
- .font(.system(size: 10, weight: isPrimary ? .semibold : .regular))
- .foregroundStyle(.white.opacity(isWorking ? 0.9 : 0.4))
- .lineLimit(1)
- }
- .padding(.horizontal, 7)
- .padding(.vertical, 3)
- .background(.white.opacity(isPrimary ? 0.15 : 0.06), in: Capsule())
- }
- }
- .frame(maxWidth: .infinity)
- }
- }
- } compactLeading: {
- let anyWorking = context.state.sessions.contains { $0.status == .working }
- Image(systemName: codeIconName)
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(.white.opacity(anyWorking ? 0.8 : 0.4))
- } compactTrailing: {
- Text("\(context.state.sessions.count)")
- .font(.caption2.bold())
- } minimal: {
- let anyWorking = context.state.sessions.contains { $0.status == .working }
- Image(systemName: codeIconName)
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(.white.opacity(anyWorking ? 0.8 : 0.4))
- }
- }
- .supplementalActivityFamilies([.small])
- }
-
- @ViewBuilder
- private func overallLockScreen(context: ActivityViewContext<OverallAttributes>) -> some View {
- let sessions = context.state.sessions
- let primaryId = context.state.primarySessionId
- let dark = context.state.isDark
-
- VStack(spacing: 0) {
- ForEach(sessions, id: \.sessionId) { session in
- let isPrimary = session.sessionId == primaryId
- overallSessionRow(session: session, isPrimary: isPrimary, isDark: dark)
- .id(session.sessionId)
- .transition(.move(edge: .bottom).combined(with: .opacity))
- }
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 12)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(dark ? Color.black.opacity(0.8) : Color.white)
- .activityBackgroundTint(.clear)
- }
-
- @ViewBuilder
- private func overallSessionRow(session: SessionSummary, isPrimary: Bool, isDark: Bool) -> some View {
- let fg: Color = isDark ? .white : widgetFg
-
- OverallSessionRow(
- projectName: session.projectName,
- model: session.model,
- currentTask: session.currentTask,
- status: session.status,
- isPrimary: isPrimary,
- fg: fg,
- completedCount: session.completedCount,
- totalCount: session.totalCount
- )
- .padding(.horizontal, 12)
- .padding(.vertical, 8)
- .background(
- isPrimary
- ? RoundedRectangle(cornerRadius: 10, style: .continuous)
- .fill(fg.opacity(0.06))
- : nil
- )
- }
-
- private func primarySession(from state: OverallAttributes.ContentState) -> SessionSummary? {
- state.sessions.first { $0.sessionId == state.primarySessionId }
- ?? state.sessions.first
- }
-
-}
-
-// MARK: - Activity Family Router
-
-/// Routes between Apple Watch Smart Stack (.small) and iPhone Lock Screen (.medium)
-struct ActivityFamilyRouter<Small: View, Medium: View>: View {
- @Environment(\.activityFamily) var activityFamily
- let small: () -> Small
- let medium: () -> Medium
-
- init(@ViewBuilder small: @escaping () -> Small, @ViewBuilder medium: @escaping () -> Medium) {
- self.small = small
- self.medium = medium
- }
-
- var body: some View {
- switch activityFamily {
- case .small:
- small()
- default:
- medium()
- }
- }
-}
-
-// MARK: - Watch Individual View (Apple Watch Smart Stack)
-
-struct WatchIndividualView: View {
- let attributes: CodyncAttributes
- let state: CodyncAttributes.ContentState
-
- var body: some View {
- Group {
- if state.isCompleted {
- watchCompletedView
- } else if state.totalCount > 0 {
- watchProgressView
- } else {
- watchMinimalView
- }
- }
- .padding(12)
- }
-
- // MARK: Completed — checkmark + ProjectName + $cost / Session Complete
-
- @ViewBuilder
- private var watchCompletedView: some View {
- VStack(alignment: .leading, spacing: 4) {
- HStack(spacing: 6) {
- Image(systemName: "checkmark.circle.fill")
- .font(.system(size: 13))
- .foregroundStyle(.white.opacity(0.6))
- Text(attributes.projectName)
- .font(.headline)
- .foregroundStyle(.white)
- .lineLimit(1)
- Spacer()
- Text(String(format: "$%.2f", state.costUSD))
- .font(.caption.bold())
- .foregroundStyle(.white.opacity(0.5))
- .monospacedDigit()
- }
- Text("Session Complete")
- .font(.subheadline)
- .foregroundStyle(.white.opacity(0.4))
- }
- }
-
- // MARK: Progress (Design A) — sparkle + Project + timer / task / bars + count
-
- @ViewBuilder
- private var watchProgressView: some View {
- VStack(alignment: .leading, spacing: 5) {
- HStack(spacing: 6) {
- watchStatusIndicator
- Text(attributes.projectName)
- .font(.headline)
- .foregroundStyle(.white)
- .lineLimit(1)
- Spacer()
- watchTimer
- }
-
- if let task = nonEmpty(state.currentTask) {
- Text(task)
- .font(.subheadline)
- .foregroundStyle(.white.opacity(0.7))
- .lineLimit(1)
- .id(task)
- .transition(.push(from: .bottom))
- }
-
- HStack(spacing: 2) {
- ForEach(Array(state.tasks.enumerated()), id: \.offset) { _, task in
- RoundedRectangle(cornerRadius: 1.5)
- .fill(watchTaskColor(task.status))
- .frame(height: 3)
- }
-
- Text("\(state.completedCount)/\(state.totalCount)")
- .font(.system(size: 10, weight: .medium).monospacedDigit())
- .foregroundStyle(.white.opacity(0.4))
- .fixedSize()
- .padding(.leading, 4)
- }
- }
- }
-
- // MARK: Minimal (Design C) — sparkle + Project + timer / icon + tool
-
- @ViewBuilder
- private var watchMinimalView: some View {
- VStack(alignment: .leading, spacing: 8) {
- HStack(spacing: 6) {
- watchStatusIndicator
- Text(attributes.projectName)
- .font(.headline)
- .foregroundStyle(.white)
- .lineLimit(1)
- Spacer()
- watchTimer
- }
-
- if let task = nonEmpty(state.currentTask) {
- Text(task)
- .font(.subheadline)
- .foregroundStyle(.white.opacity(0.7))
- .lineLimit(1)
- .id(task)
- .transition(.push(from: .bottom))
- } else {
- Text(statusLabel(state.status))
- .font(.subheadline)
- .foregroundStyle(.white.opacity(0.4))
- }
- }
- }
-
- // MARK: Shared Components
-
- @ViewBuilder
- private var watchStatusIndicator: some View {
- Image(systemName: codeIconName)
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(.white.opacity(codeIconOpacity(isBusy: state.isBusy, isCompleted: state.isCompleted)))
- }
-
- @ViewBuilder
- private var watchTimer: some View {
- Text(state.sessionStartDate, style: .timer)
- .font(.caption2.bold().monospacedDigit())
- .foregroundStyle(.white.opacity(0.5))
- .contentTransition(.numericText(countsDown: false))
- }
-
- // MARK: Helpers
-
- private func watchTaskColor(_ status: TaskStatus) -> Color {
- switch status {
- case .completed: .white
- case .inProgress: .white.opacity(0.4)
- case .pending: .white.opacity(0.12)
- }
- }
-
-}
-
-// MARK: - Watch Overall View (Apple Watch Smart Stack)
-
-struct WatchOverallView: View {
- let state: OverallAttributes.ContentState
-
- var body: some View {
- VStack(spacing: 0) {
- ForEach(state.sessions.prefix(3), id: \.sessionId) { session in
- let isPrimary = session.sessionId == state.primarySessionId
- watchSessionRow(session: session, isPrimary: isPrimary)
- .id(session.sessionId)
- .transition(.move(edge: .bottom).combined(with: .opacity))
- }
- }
- .padding(.horizontal, 12)
- .padding(.vertical, 10)
- }
-
- @ViewBuilder
- private func watchSessionRow(session: SessionSummary, isPrimary: Bool) -> some View {
- HStack(spacing: 6) {
- Circle()
- .fill(watchDotColor(session: session, isPrimary: isPrimary))
- .frame(width: 6, height: 6)
-
- Text(session.projectName)
- .font(.system(size: 13, weight: isPrimary ? .semibold : .medium))
- .foregroundStyle(.white)
- .lineLimit(1)
- .layoutPriority(1)
-
- Text(session.model)
- .font(.system(size: 9, weight: .medium))
- .foregroundStyle(.white.opacity(0.4))
- .padding(.horizontal, 5)
- .padding(.vertical, 1)
- .background(.white.opacity(0.08), in: Capsule())
-
- Spacer(minLength: 0)
-
- if let task = session.currentTask, !task.isEmpty {
- Text(task)
- .font(.system(size: 10))
- .foregroundStyle(.white.opacity(0.35))
- .lineLimit(1)
- } else if session.status == .working {
- Image(systemName: codeIconName)
- .font(.system(size: 8, weight: .bold))
- .foregroundStyle(.white.opacity(0.5))
- }
- }
- .padding(.vertical, 5)
- }
-
- private func watchDotColor(session: SessionSummary, isPrimary: Bool) -> Color {
- if isPrimary { return .white }
- switch session.status {
- case .working: return .white.opacity(0.8)
- case .idle: return .white.opacity(0.3)
- default: return .white.opacity(0.5)
- }
- }
-}
diff --git a/CodyncShared/Package.swift b/CodyncShared/Package.swift
deleted file mode 100644
index 9828342a..00000000
--- a/CodyncShared/Package.swift
+++ /dev/null
@@ -1,14 +0,0 @@
-// swift-tools-version: 6.0
-import PackageDescription
-
-let package = Package(
- name: "CodyncShared",
- platforms: [.macOS(.v14), .iOS(.v17)],
- products: [
- .library(name: "CodyncShared", targets: ["CodyncShared"]),
- ],
- targets: [
- .target(name: "CodyncShared", path: "Sources"),
- .testTarget(name: "CodyncSharedTests", dependencies: ["CodyncShared"], path: "Tests"),
- ]
-)
diff --git a/CodyncShared/Sources/CloudKit/CKRecordMapper.swift b/CodyncShared/Sources/CloudKit/CKRecordMapper.swift
deleted file mode 100644
index 75cf451f..00000000
--- a/CodyncShared/Sources/CloudKit/CKRecordMapper.swift
+++ /dev/null
@@ -1,81 +0,0 @@
-import CloudKit
-import Foundation
-
-public enum CKRecordMapper {
- public static let recordType = "SessionState"
-
- public static func toRecord(_ session: SessionState, zoneID: CKRecordZone.ID = .default) -> CKRecord {
- let recordID = CKRecord.ID(recordName: session.sessionId, zoneID: zoneID)
- let record = CKRecord(recordType: recordType, recordID: recordID)
- record["sessionId"] = session.sessionId as CKRecordValue
- record["projectName"] = session.projectName as CKRecordValue
- record["gitBranch"] = session.gitBranch as CKRecordValue
- record["status"] = session.status.rawValue as CKRecordValue
- record["model"] = session.model as CKRecordValue
- record["summary"] = session.summary as CKRecordValue
- record["currentTask"] = (session.currentTask ?? "") as CKRecordValue
- record["lastEvent"] = (session.lastEvent ?? "") as CKRecordValue
- record["waitingReason"] = (session.waitingReason?.rawValue ?? "") as CKRecordValue
- record["contextPct"] = session.contextPct as CKRecordValue
- record["costUSD"] = session.costUSD as CKRecordValue
- record["startedAt"] = session.startedAt as CKRecordValue
- record["durationSec"] = session.durationSec as CKRecordValue
- record["deviceId"] = session.deviceId as CKRecordValue
- record["updatedAt"] = session.updatedAt as CKRecordValue
- if let tasksData = try? JSONEncoder().encode(session.truncatedTasks) {
- record["tasks"] = tasksData as CKRecordValue
- }
- return record
- }
-
- /// Update an existing CKRecord's fields (preserves change tag for conflict-free saves)
- public static func updateRecord(_ record: CKRecord, with session: SessionState) {
- record["sessionId"] = session.sessionId as CKRecordValue
- record["projectName"] = session.projectName as CKRecordValue
- record["gitBranch"] = session.gitBranch as CKRecordValue
- record["status"] = session.status.rawValue as CKRecordValue
- record["model"] = session.model as CKRecordValue
- record["summary"] = session.summary as CKRecordValue
- record["currentTask"] = (session.currentTask ?? "") as CKRecordValue
- record["lastEvent"] = (session.lastEvent ?? "") as CKRecordValue
- record["waitingReason"] = (session.waitingReason?.rawValue ?? "") as CKRecordValue
- record["contextPct"] = session.contextPct as CKRecordValue
- record["costUSD"] = session.costUSD as CKRecordValue
- record["startedAt"] = session.startedAt as CKRecordValue
- record["durationSec"] = session.durationSec as CKRecordValue
- record["deviceId"] = session.deviceId as CKRecordValue
- record["updatedAt"] = session.updatedAt as CKRecordValue
- if let tasksData = try? JSONEncoder().encode(session.truncatedTasks) {
- record["tasks"] = tasksData as CKRecordValue
- }
- }
-
- public static func fromRecord(_ record: CKRecord) -> SessionState? {
- guard let sessionId = record["sessionId"] as? String,
- let statusRaw = record["status"] as? String,
- let status = SessionStatus(rawValue: statusRaw) else { return nil }
- var tasks: [TaskItem] = []
- if let tasksData = record["tasks"] as? Data {
- tasks = (try? JSONDecoder().decode([TaskItem].self, from: tasksData)) ?? []
- }
- let waitingReason = (record["waitingReason"] as? String).flatMap(WaitingReason.init)
- return SessionState(
- sessionId: sessionId,
- projectName: record["projectName"] as? String ?? "",
- gitBranch: record["gitBranch"] as? String ?? "",
- status: status,
- model: record["model"] as? String ?? "Unknown",
- summary: record["summary"] as? String ?? "",
- currentTask: record["currentTask"] as? String,
- lastEvent: record["lastEvent"] as? String,
- waitingReason: waitingReason,
- tasks: tasks,
- contextPct: record["contextPct"] as? Int ?? 0,
- costUSD: record["costUSD"] as? Double ?? 0,
- startedAt: record["startedAt"] as? Date ?? Date(),
- durationSec: record["durationSec"] as? Int ?? 0,
- deviceId: record["deviceId"] as? String ?? "",
- updatedAt: record["updatedAt"] as? Date ?? Date()
- )
- }
-}
diff --git a/CodyncShared/Sources/CloudKit/CloudKitManager.swift b/CodyncShared/Sources/CloudKit/CloudKitManager.swift
deleted file mode 100644
index 1f66d526..00000000
--- a/CodyncShared/Sources/CloudKit/CloudKitManager.swift
+++ /dev/null
@@ -1,230 +0,0 @@
-import CloudKit
-import Foundation
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync", category: "CloudKit")
-
-public final class CloudKitManager: Sendable {
- public static let shared = CloudKitManager()
- private let container = CKContainer(identifier: "iCloud.com.pokai.Codync")
- public var database: CKDatabase { container.privateCloudDatabase }
-
- /// Custom zone — required for reliable silent push notifications.
- /// Default zone does not support CKRecordZoneSubscription or change tokens.
- public static let zoneID = CKRecordZone.ID(zoneName: "Sessions", ownerName: CKCurrentUserDefaultName)
-
- private init() {}
-
- // MARK: - Zone Setup
-
- /// Create the custom zone if it doesn't exist. Idempotent — safe to call on every launch.
- public func ensureZoneExists() async throws {
- let zone = CKRecordZone(zoneID: Self.zoneID)
- _ = try await database.save(zone)
- }
-
- // MARK: - Write (macOS)
-
- /// Save sessions to CloudKit custom zone. Fetches existing records first to avoid conflicts.
- public func saveBatch(_ sessions: [SessionState]) async throws {
- guard !sessions.isEmpty else { return }
-
- let recordIDs = sessions.map { CKRecord.ID(recordName: $0.sessionId, zoneID: Self.zoneID) }
- var existing: [String: CKRecord] = [:]
- let results = (try? await database.records(for: recordIDs)) ?? [:]
- for (id, result) in results {
- if case .success(let record) = result {
- existing[id.recordName] = record
- }
- }
-
- var savedCount = 0
- for session in sessions {
- let record: CKRecord
- if let server = existing[session.sessionId] {
- CKRecordMapper.updateRecord(server, with: session)
- record = server
- } else {
- record = CKRecordMapper.toRecord(session, zoneID: Self.zoneID)
- }
- _ = try await database.save(record)
- savedCount += 1
- }
- logger.info("Saved \(savedCount)/\(sessions.count) sessions to CloudKit")
- }
-
- // MARK: - Read (iOS)
-
- public func fetchAll() async throws -> [SessionState] {
- let query = CKQuery(recordType: CKRecordMapper.recordType, predicate: NSPredicate(value: true))
- query.sortDescriptors = [NSSortDescriptor(key: "updatedAt", ascending: false)]
- let (results, _) = try await database.records(
- matching: query, inZoneWith: Self.zoneID, resultsLimit: 20
- )
- let sessions = results.compactMap { _, result in
- guard case .success(let record) = result else { return nil as SessionState? }
- return CKRecordMapper.fromRecord(record)
- }
- logger.info("Fetched \(sessions.count) sessions from CloudKit")
- return sessions
- }
-
- // MARK: - Subscribe (iOS)
-
- private static let subscriptionKey = "codync_ck_zone_subscription_v2"
-
- public func subscribeToChanges() async throws {
- let subscriptionID = "session-zone-changes"
-
- if UserDefaults.standard.bool(forKey: Self.subscriptionKey) {
- logger.info("CloudKit zone subscription already created (cached)")
- return
- }
-
- // Delete old default-zone subscription if it exists
- _ = try? await database.deleteSubscription(withID: "session-changes")
-
- if (try? await database.subscription(for: subscriptionID)) != nil {
- UserDefaults.standard.set(true, forKey: Self.subscriptionKey)
- logger.info("CloudKit zone subscription already exists")
- return
- }
-
- // CKRecordZoneSubscription on custom zone — this is the reliable pattern
- let subscription = CKRecordZoneSubscription(
- zoneID: Self.zoneID,
- subscriptionID: subscriptionID
- )
- let info = CKSubscription.NotificationInfo()
- info.shouldSendContentAvailable = true
- subscription.notificationInfo = info
- _ = try await database.save(subscription)
- UserDefaults.standard.set(true, forKey: Self.subscriptionKey)
- logger.info("Created CloudKit zone subscription")
- }
-
- // MARK: - Delete
-
- public func deleteByIds(_ sessionIds: [String]) async throws {
- guard !sessionIds.isEmpty else { return }
- let recordIDs = sessionIds.map { CKRecord.ID(recordName: $0, zoneID: Self.zoneID) }
- for id in recordIDs {
- _ = try? await database.deleteRecord(withID: id)
- }
- logger.info("Deleted \(sessionIds.count) session records from CloudKit")
- }
-
- // MARK: - Pinned Sessions
-
- static let pinnedRecordType = "PinnedSession"
-
- public func fetchPinnedSessionIds() async throws -> Set<String> {
- let query = CKQuery(recordType: Self.pinnedRecordType, predicate: NSPredicate(value: true))
- let (results, _) = try await database.records(matching: query, inZoneWith: Self.zoneID, resultsLimit: 10)
- var ids = Set<String>()
- for (_, result) in results {
- if case .success(let record) = result,
- let sessionId = record["sessionId"] as? String {
- ids.insert(sessionId)
- }
- }
- return ids
- }
-
- public func pinSession(_ sessionId: String) async throws {
- let recordID = CKRecord.ID(recordName: "pin-\(sessionId)", zoneID: Self.zoneID)
- let record = CKRecord(recordType: Self.pinnedRecordType, recordID: recordID)
- record["sessionId"] = sessionId as CKRecordValue
- _ = try await database.save(record)
- }
-
- public func unpinSession(_ sessionId: String) async throws {
- let recordID = CKRecord.ID(recordName: "pin-\(sessionId)", zoneID: Self.zoneID)
- try await database.deleteRecord(withID: recordID)
- }
-
- public func deleteOrphans(activeSessionIds: Set<String>) async throws {
- let query = CKQuery(recordType: CKRecordMapper.recordType, predicate: NSPredicate(value: true))
- let (results, _) = try await database.records(
- matching: query, inZoneWith: Self.zoneID, resultsLimit: 50
- )
- var deletedCount = 0
- for (id, result) in results {
- guard case .success = result else { continue }
- if !activeSessionIds.contains(id.recordName) {
- _ = try? await database.deleteRecord(withID: id)
- deletedCount += 1
- }
- }
- if deletedCount > 0 {
- logger.info("Cleaned up \(deletedCount) orphan records from CloudKit")
- }
- }
-
- // MARK: - Primary Session
-
- static let primarySessionRecordType = "PrimarySession"
- private static let primarySessionRecordName = "primary-session"
-
- public func fetchPrimarySession() async -> (sessionId: String?, locked: Bool) {
- let recordID = CKRecord.ID(recordName: Self.primarySessionRecordName, zoneID: Self.zoneID)
- do {
- let record = try await database.record(for: recordID)
- let sessionId = record["sessionId"] as? String
- let locked = (record["isManuallyLocked"] as? Int64 ?? 0) == 1
- return (sessionId, locked)
- } catch {
- return (nil, false)
- }
- }
-
- public func setPrimarySession(_ sessionId: String, locked: Bool) async {
- let recordID = CKRecord.ID(recordName: Self.primarySessionRecordName, zoneID: Self.zoneID)
- let record: CKRecord
- if let existing = try? await database.record(for: recordID) {
- record = existing
- } else {
- record = CKRecord(recordType: Self.primarySessionRecordType, recordID: recordID)
- }
- record["sessionId"] = sessionId as CKRecordValue
- record["isManuallyLocked"] = (locked ? 1 : 0) as CKRecordValue
- record["updatedAt"] = Date() as CKRecordValue
- _ = try? await database.save(record)
- }
-
- public func clearPrimarySession() async {
- let recordID = CKRecord.ID(recordName: Self.primarySessionRecordName, zoneID: Self.zoneID)
- _ = try? await database.deleteRecord(withID: recordID)
- }
-
- // MARK: - Live Activity Preference
-
- static let liveActivityPrefRecordType = "LiveActivityPreference"
- private static let liveActivityPrefRecordName = "live-activity-pref"
-
- public func fetchLiveActivityPreference() async -> (mode: LiveActivityMode, maxSessions: Int) {
- let recordID = CKRecord.ID(recordName: Self.liveActivityPrefRecordName, zoneID: Self.zoneID)
- do {
- let record = try await database.record(for: recordID)
- let modeStr = record["mode"] as? String ?? "overall"
- let mode = LiveActivityMode(rawValue: modeStr) ?? .overall
- let maxSessions = record["maxSessions"] as? Int64 ?? 4
- return (mode, Int(maxSessions))
- } catch {
- return (.overall, 4)
- }
- }
-
- public func setLiveActivityPreference(mode: LiveActivityMode, maxSessions: Int) async {
- let recordID = CKRecord.ID(recordName: Self.liveActivityPrefRecordName, zoneID: Self.zoneID)
- let record: CKRecord
- if let existing = try? await database.record(for: recordID) {
- record = existing
- } else {
- record = CKRecord(recordType: Self.liveActivityPrefRecordType, recordID: recordID)
- }
- record["mode"] = mode.rawValue as CKRecordValue
- record["maxSessions"] = maxSessions as CKRecordValue
- _ = try? await database.save(record)
- }
-}
diff --git a/CodyncShared/Sources/Models/CodyncAttributes.swift b/CodyncShared/Sources/Models/CodyncAttributes.swift
deleted file mode 100644
index 6659ba09..00000000
--- a/CodyncShared/Sources/Models/CodyncAttributes.swift
+++ /dev/null
@@ -1,118 +0,0 @@
-import Foundation
-
-#if os(iOS)
-import ActivityKit
-
-public struct CodyncAttributes: ActivityAttributes, Codable, Sendable {
- public let sessionId: String
- public let projectName: String
- public let summary: String
-
- public init(sessionId: String, projectName: String, summary: String = "") {
- self.sessionId = sessionId
- self.projectName = projectName
- self.summary = summary
- }
-
- public struct ContentState: Codable, Hashable, Sendable {
- public let status: String
- public let model: String
- public let tasks: [TaskItem]
- public let completedCount: Int
- public let totalCount: Int
- public let currentTask: String?
- public let previousTask: String?
- public let secondPreviousTask: String?
- public let contextPct: Int
- public let costUSD: Double
- public let durationSec: Int
- public let sessionStartDate: Date
- public let isDark: Bool
-
- public init(status: String, model: String, tasks: [TaskItem],
- completedCount: Int, totalCount: Int, currentTask: String?,
- previousTask: String? = nil,
- secondPreviousTask: String? = nil,
- contextPct: Int, costUSD: Double, durationSec: Int,
- sessionStartDate: Date = Date(), isDark: Bool = true) {
- self.status = status
- self.model = model
- self.tasks = tasks
- self.completedCount = completedCount
- self.totalCount = totalCount
- self.currentTask = currentTask
- self.previousTask = previousTask
- self.secondPreviousTask = secondPreviousTask
- self.contextPct = contextPct
- self.costUSD = costUSD
- self.durationSec = durationSec
- self.sessionStartDate = sessionStartDate
- self.isDark = isDark
- }
-
- /// Whether the session is actively processing (working or compacting)
- public var isBusy: Bool { status == "working" || status == "compacting" }
-
- /// Whether the session has finished
- public var isCompleted: Bool { status == "completed" }
- }
-}
-
-#else
-
-public struct CodyncAttributes: Codable, Sendable {
- public let sessionId: String
- public let projectName: String
- public let summary: String
-
- public init(sessionId: String, projectName: String, summary: String = "") {
- self.sessionId = sessionId
- self.projectName = projectName
- self.summary = summary
- }
-
- public struct ContentState: Codable, Hashable, Sendable {
- public let status: String
- public let model: String
- public let tasks: [TaskItem]
- public let completedCount: Int
- public let totalCount: Int
- public let currentTask: String?
- public let previousTask: String?
- public let secondPreviousTask: String?
- public let contextPct: Int
- public let costUSD: Double
- public let durationSec: Int
- public let sessionStartDate: Date
- public let isDark: Bool
-
- public init(status: String, model: String, tasks: [TaskItem],
- completedCount: Int, totalCount: Int, currentTask: String?,
- previousTask: String? = nil,
- secondPreviousTask: String? = nil,
- contextPct: Int, costUSD: Double, durationSec: Int,
- sessionStartDate: Date = Date(), isDark: Bool = true) {
- self.status = status
- self.model = model
- self.tasks = tasks
- self.completedCount = completedCount
- self.totalCount = totalCount
- self.currentTask = currentTask
- self.previousTask = previousTask
- self.secondPreviousTask = secondPreviousTask
- self.contextPct = contextPct
- self.costUSD = costUSD
- self.durationSec = durationSec
- self.sessionStartDate = sessionStartDate
- self.isDark = isDark
- }
-
- /// Whether the session is actively processing (working or compacting)
- public var isBusy: Bool { status == "working" || status == "compacting" }
-
- /// Whether the session has finished
- public var isCompleted: Bool { status == "completed" }
- }
-}
-
-#endif
diff --git a/CodyncShared/Sources/Models/LiveActivityMode.swift b/CodyncShared/Sources/Models/LiveActivityMode.swift
deleted file mode 100644
index 8df123bc..00000000
--- a/CodyncShared/Sources/Models/LiveActivityMode.swift
+++ /dev/null
@@ -1,6 +0,0 @@
-import Foundation
-
-public enum LiveActivityMode: String, Codable, Sendable {
- case overall
- case individual
-}
diff --git a/CodyncShared/Sources/Models/ModelLabel.swift b/CodyncShared/Sources/Models/ModelLabel.swift
deleted file mode 100644
index c78db0d7..00000000
--- a/CodyncShared/Sources/Models/ModelLabel.swift
+++ /dev/null
@@ -1,93 +0,0 @@
-import Foundation
-
-/// Parsed model metadata from a Claude model ID string.
-public struct ModelInfo: Sendable {
- public let family: String // "Opus", "Sonnet", "Haiku"
- public let version: String // "4.6", "3.5", "" if unknown
- public let displayLabel: String // "Opus 4.6", "Sonnet", etc.
- public let contextWindow: Int // 1_000_000 or 200_000
-
- /// Parse a raw Claude model ID into structured info.
- /// Examples: "claude-opus-4-6", "claude-3-5-sonnet-20241022", "claude-haiku-4-5-20251001"
- public static func parse(_ model: String) -> ModelInfo {
- let lower = model.lowercased()
-
- // Skip placeholder values
- if lower == "unknown" || lower.contains("synthetic") {
- return ModelInfo(family: "", version: "", displayLabel: "", contextWindow: 200_000)
- }
-
- // Detect family
- let family: String
- if lower.contains("opus") { family = "Opus" }
- else if lower.contains("sonnet") { family = "Sonnet" }
- else if lower.contains("haiku") { family = "Haiku" }
- else {
- return ModelInfo(family: "", version: "", displayLabel: model, contextWindow: 200_000)
- }
-
- // Extract version — try new format first: claude-{family}-{major}-{minor}
- // then old format: claude-{major}-{minor}-{family}
- let version = extractVersion(from: lower, family: family.lowercased())
-
- let displayLabel = version.isEmpty ? family : "\(family) \(version)"
-
- // Context window: 1M for version >= 4.6 or explicit [1m] suffix
- let has1mSuffix = lower.contains("[1m]")
- let isLargeContext = has1mSuffix || versionAtLeast(version, major: 4, minor: 6)
- let contextWindow = isLargeContext ? 1_000_000 : 200_000
-
- return ModelInfo(
- family: family,
- version: version,
- displayLabel: displayLabel,
- contextWindow: contextWindow
- )
- }
-
- /// Extract version number from a model ID string.
- /// Handles both new format (claude-opus-4-6) and legacy format (claude-3-5-sonnet-20241022).
- private static func extractVersion(from lower: String, family: String) -> String {
- // New format: claude-{family}-{major}-{minor}[-date]
- // e.g., "claude-opus-4-6", "claude-haiku-4-5-20251001"
- if let range = lower.range(of: "\(family)-") {
- let afterFamily = lower[range.upperBound...]
- let version = parseVersionDigits(String(afterFamily))
- if !version.isEmpty { return version }
- }
-
- // Old format: claude-{major}-{minor}-{family}[-date]
- // e.g., "claude-3-5-sonnet-20241022"
- if let range = lower.range(of: "-\(family)") {
- let beforeFamily = lower[lower.startIndex..<range.lowerBound]
- let parts = beforeFamily.split(separator: "-")
- if parts.count >= 2,
- let major = Int(parts[parts.count - 2]),
- let minor = Int(parts[parts.count - 1]) {
- return "\(major).\(minor)"
- }
- }
-
- return ""
- }
-
- /// Parse "4-6..." into "4.6", "4-5-20251001" into "4.5"
- private static func parseVersionDigits(_ s: String) -> String {
- let parts = s.split(separator: "-")
- guard parts.count >= 2,
- let major = Int(parts[0]) else { return "" }
- // Minor part may have trailing non-numeric chars (e.g., "6[1m]")
- let minorStr = String(parts[1]).prefix(while: \.isNumber)
- guard let minor = Int(minorStr) else { return "" }
- return "\(major).\(minor)"
- }
-
- private static func versionAtLeast(_ version: String, major: Int, minor: Int) -> Bool {
- let parts = version.split(separator: ".")
- guard parts.count == 2,
- let vMajor = Int(parts[0]),
- let vMinor = Int(parts[1]) else { return false }
- return vMajor > major || (vMajor == major && vMinor >= minor)
- }
-}
-
diff --git a/CodyncShared/Sources/Models/OverallAttributes.swift b/CodyncShared/Sources/Models/OverallAttributes.swift
deleted file mode 100644
index e4c2369a..00000000
--- a/CodyncShared/Sources/Models/OverallAttributes.swift
+++ /dev/null
@@ -1,44 +0,0 @@
-import Foundation
-
-#if os(iOS)
-import ActivityKit
-
-public struct OverallAttributes: ActivityAttributes, Codable, Sendable {
- public struct ContentState: Codable, Hashable, Sendable {
- public let sessions: [SessionSummary]
- public let primarySessionId: String?
- public let totalCost: Double
- public let isDark: Bool
-
- public init(sessions: [SessionSummary], primarySessionId: String?, totalCost: Double, isDark: Bool = true) {
- self.sessions = sessions
- self.primarySessionId = primarySessionId
- self.totalCost = totalCost
- self.isDark = isDark
- }
- }
-
- public init() {}
-}
-
-#else
-
-public struct OverallAttributes: Codable, Sendable {
- public struct ContentState: Codable, Hashable, Sendable {
- public let sessions: [SessionSummary]
- public let primarySessionId: String?
- public let totalCost: Double
- public let isDark: Bool
-
- public init(sessions: [SessionSummary], primarySessionId: String?, totalCost: Double, isDark: Bool = true) {
- self.sessions = sessions
- self.primarySessionId = primarySessionId
- self.totalCost = totalCost
- self.isDark = isDark
- }
- }
-
- public init() {}
-}
-
-#endif
diff --git a/CodyncShared/Sources/Models/SessionState.swift b/CodyncShared/Sources/Models/SessionState.swift
deleted file mode 100644
index 570ac346..00000000
--- a/CodyncShared/Sources/Models/SessionState.swift
+++ /dev/null
@@ -1,69 +0,0 @@
-import Foundation
-
-public struct SessionState: Codable, Identifiable, Equatable, Sendable {
- public let sessionId: String
- public var projectName: String
- public var gitBranch: String
- public var status: SessionStatus
- public var model: String
- public var summary: String
- public var currentTask: String?
- public var lastEvent: String?
- public var waitingReason: WaitingReason?
- public var tasks: [TaskItem]
- public var contextPct: Int
- public var costUSD: Double
- public var startedAt: Date
- public var durationSec: Int
- public var deviceId: String
- public var updatedAt: Date
-
- public var id: String { sessionId }
-
- public var completedTaskCount: Int {
- tasks.filter { $0.status == .completed }.count
- }
-
- public var totalTaskCount: Int {
- tasks.count
- }
-
- public var truncatedTasks: [TaskItem] {
- Array(tasks.suffix(10))
- }
-
- /// Display text below project name: lastEvent when working, otherwise summary
- public var statusDescription: String? {
- if status == .working, let event = lastEvent, !event.isEmpty {
- return event
- }
- return summary != projectName ? summary : nil
- }
-
- public init(
- sessionId: String, projectName: String, gitBranch: String,
- status: SessionStatus, model: String, summary: String,
- currentTask: String? = nil, lastEvent: String? = nil,
- waitingReason: WaitingReason? = nil, tasks: [TaskItem] = [],
- contextPct: Int = 0, costUSD: Double = 0,
- startedAt: Date = Date(), durationSec: Int = 0,
- deviceId: String = "", updatedAt: Date = Date()
- ) {
- self.sessionId = sessionId
- self.projectName = projectName
- self.gitBranch = gitBranch
- self.status = status
- self.model = model
- self.summary = summary
- self.currentTask = currentTask
- self.lastEvent = lastEvent
- self.waitingReason = waitingReason
- self.tasks = tasks
- self.contextPct = contextPct
- self.costUSD = costUSD
- self.startedAt = startedAt
- self.durationSec = durationSec
- self.deviceId = deviceId
- self.updatedAt = updatedAt
- }
-}
diff --git a/CodyncShared/Sources/Models/SessionStatus.swift b/CodyncShared/Sources/Models/SessionStatus.swift
deleted file mode 100644
index 519dafcb..00000000
--- a/CodyncShared/Sources/Models/SessionStatus.swift
+++ /dev/null
@@ -1,59 +0,0 @@
-import SwiftUI
-
-public enum SessionStatus: String, Codable, Sendable {
- case working
- case idle
- case needsInput
- case compacting
- case error
- case completed
-
- public var label: String {
- switch self {
- case .working: return "Working"
- case .idle: return "Idle"
- case .needsInput: return "Needs Input"
- case .compacting: return "Compacting"
- case .error: return "Error"
- case .completed: return "Completed"
- }
- }
-
- public var isActive: Bool {
- switch self {
- case .working, .idle, .needsInput, .compacting, .error: return true
- case .completed: return false
- }
- }
-}
-
-public enum WaitingReason: String, Codable, Sendable {
- case permissionPrompt // Red — needs permission approval
- case commandComplete // Yellow — Stop hook, command finished
- case askUserQuestion // Yellow — AskUserQuestion tool
- case elicitation // Yellow — elicitation dialog
- case unknown // Yellow — fallback
-
- public var label: String {
- switch self {
- case .permissionPrompt: return "Needs Permission"
- case .commandComplete: return "Waiting for Input"
- case .askUserQuestion: return "Question"
- case .elicitation: return "Waiting for Input"
- case .unknown: return "Needs Input"
- }
- }
-
- public var isPermission: Bool { self == .permissionPrompt }
-}
-
-/// Type-safe hook signal types between ClaudeHookServer and TranscriptWatcher.
-public enum HookSignalType: String, Sendable {
- case permissionRequest = "permission_request"
- case askUserQuestion = "ask_user_question"
- case elicitationDialog = "elicitation_dialog"
- case stop
- case userPromptSubmit = "user_prompt_submit"
- case preToolUse = "pre_tool_use"
- case postToolUse = "post_tool_use"
-}
diff --git a/CodyncShared/Sources/Models/SessionSummary.swift b/CodyncShared/Sources/Models/SessionSummary.swift
deleted file mode 100644
index 0cad919f..00000000
--- a/CodyncShared/Sources/Models/SessionSummary.swift
+++ /dev/null
@@ -1,27 +0,0 @@
-import Foundation
-
-public struct SessionSummary: Codable, Hashable, Sendable {
- public let sessionId: String
- public let projectName: String
- public let status: SessionStatus
- public let model: String
- public let currentTask: String?
- public let costUSD: Double
- public let durationSec: Int
- public let completedCount: Int
- public let totalCount: Int
-
- public init(sessionId: String, projectName: String, status: SessionStatus,
- model: String, currentTask: String?, costUSD: Double,
- durationSec: Int = 0, completedCount: Int = 0, totalCount: Int = 0) {
- self.sessionId = sessionId
- self.projectName = projectName
- self.status = status
- self.model = model
- self.currentTask = currentTask
- self.costUSD = costUSD
- self.durationSec = durationSec
- self.completedCount = completedCount
- self.totalCount = totalCount
- }
-}
diff --git a/CodyncShared/Sources/Models/TaskItem.swift b/CodyncShared/Sources/Models/TaskItem.swift
deleted file mode 100644
index c3a2df06..00000000
--- a/CodyncShared/Sources/Models/TaskItem.swift
+++ /dev/null
@@ -1,28 +0,0 @@
-import Foundation
-
-public struct TaskItem: Codable, Hashable, Sendable, Identifiable {
- public let id: String
- public let content: String
- public let status: TaskStatus
- public let activeForm: String?
-
- public init(id: String, content: String, status: TaskStatus, activeForm: String? = nil) {
- self.id = id
- self.content = content
- self.status = status
- self.activeForm = activeForm
- }
-
- public var truncatedContent: String {
- if content.count > 50 {
- return String(content.prefix(47)) + "..."
- }
- return content
- }
-}
-
-public enum TaskStatus: String, Codable, Sendable {
- case pending
- case inProgress = "in_progress"
- case completed
-}
diff --git a/CodyncShared/Sources/Theme/GlassTheme.swift b/CodyncShared/Sources/Theme/GlassTheme.swift
deleted file mode 100644
index 00695bb4..00000000
--- a/CodyncShared/Sources/Theme/GlassTheme.swift
+++ /dev/null
@@ -1,192 +0,0 @@
-import SwiftUI
-
-// MARK: - GlassCardStyle
-
-public enum GlassCardStyle: Sendable {
- case normal
- case elevated
- case receded
-}
-
-// MARK: - GlassThemeProvider
-
-public protocol GlassThemeProvider: Sendable {
- var isDark: Bool { get }
-
- // Backgrounds
- var background: Color { get }
- var cardBackground: Color { get }
- var glassBackground: Color { get }
-
- // Text
- var primaryText: Color { get }
- var secondaryText: Color { get }
- var tertiaryText: Color { get }
-
- // Borders
- var separator: Color { get }
- var border: Color { get }
-
- // Glass tokens — default implementations provided below
- var glassBorder: Color { get }
- var glassInnerHighlight: Color { get }
- var glassShadow: Color { get }
- var glassShadowRadius: CGFloat { get }
-
- // Semantic
- var accent: Color { get }
- func waitingColor(for reason: WaitingReason?) -> Color
-}
-
-// MARK: - Default glass token implementations
-
-public extension GlassThemeProvider {
- var glassBorder: Color {
- isDark
- ? Color.white.opacity(0.18)
- : Color.white.opacity(0.60)
- }
-
- var glassInnerHighlight: Color {
- isDark
- ? Color.white.opacity(0.12)
- : Color.white.opacity(0.75)
- }
-
- var glassShadow: Color {
- isDark
- ? Color.black.opacity(0.55)
- : Color.black.opacity(0.18)
- }
-
- var glassShadowRadius: CGFloat {
- isDark ? 16 : 10
- }
-}
-
-// MARK: - GlassCardModifier
-
-public struct GlassCardModifier: ViewModifier {
- public let style: GlassCardStyle
- public let isDark: Bool
-
- public init(style: GlassCardStyle, isDark: Bool) {
- self.style = style
- self.isDark = isDark
- }
-
- // Resolved token values
-
- private var resolvedBackground: Color {
- switch style {
- case .normal:
- return isDark
- ? Color.white.opacity(0.05)
- : Color.white.opacity(0.70)
- case .elevated:
- return isDark
- ? Color.white.opacity(0.10)
- : Color.white.opacity(0.85)
- case .receded:
- return isDark
- ? Color.white.opacity(0.02)
- : Color.white.opacity(0.35)
- }
- }
-
- private var resolvedBorderColor: Color {
- switch style {
- case .normal:
- return isDark
- ? Color.white.opacity(0.10)
- : Color.black.opacity(0.06)
- case .elevated:
- return isDark
- ? Color.white.opacity(0.25)
- : Color.white.opacity(0.80)
- case .receded:
- return isDark
- ? Color.white.opacity(0.04)
- : Color.black.opacity(0.03)
- }
- }
-
- private var resolvedBorderWidth: CGFloat {
- switch style {
- case .normal: return 0.5
- case .elevated: return 1.0
- case .receded: return 0.5
- }
- }
-
- private var resolvedScale: CGFloat {
- switch style {
- case .normal: return 1.0
- case .elevated: return 1.01
- case .receded: return 0.95
- }
- }
-
- private var resolvedOpacity: Double {
- switch style {
- case .normal, .elevated: return 1.0
- case .receded: return 0.5
- }
- }
-
- private var shadowRadius: CGFloat {
- isDark ? 16 : 10
- }
-
- private var shadowColor: Color {
- isDark
- ? Color.black.opacity(0.55)
- : Color.black.opacity(0.18)
- }
-
- private var innerHighlight: Color {
- isDark
- ? Color.white.opacity(0.12)
- : Color.white.opacity(0.75)
- }
-
- private let cornerRadius: CGFloat = 14
-
- public func body(content: Content) -> some View {
- if style == .normal {
- // Pass-through — no glass effect in normal state
- content
- } else {
- let shape = RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
-
- content
- .background(resolvedBackground, in: shape)
- .overlay {
- if style == .elevated {
- LinearGradient(
- colors: [innerHighlight, Color.clear],
- startPoint: .top,
- endPoint: .center
- )
- .clipShape(shape)
- }
- }
- .overlay(shape.stroke(resolvedBorderColor, lineWidth: resolvedBorderWidth))
- .shadow(
- color: style == .elevated ? shadowColor : .clear,
- radius: style == .elevated ? shadowRadius : 0,
- x: 0, y: 4
- )
- .scaleEffect(resolvedScale)
- .opacity(resolvedOpacity)
- }
- }
-}
-
-// MARK: - View extension
-
-public extension View {
- func glassCard(_ style: GlassCardStyle = .normal, isDark: Bool) -> some View {
- modifier(GlassCardModifier(style: style, isDark: isDark))
- }
-}
diff --git a/CodyncShared/Sources/Theme/SegmentedRingView.swift b/CodyncShared/Sources/Theme/SegmentedRingView.swift
deleted file mode 100644
index d33fa277..00000000
--- a/CodyncShared/Sources/Theme/SegmentedRingView.swift
+++ /dev/null
@@ -1,63 +0,0 @@
-import SwiftUI
-
-/// Segmented progress ring showing individual task segments.
-/// Each task is a separate arc with brightness indicating status.
-/// Shared across iOS and macOS targets.
-public struct SegmentedRingView: View {
- public let completedCount: Int
- public let totalCount: Int
- public let isWorking: Bool
- public let fg: Color
- public var lineWidth: CGFloat = 2
- public var gapDegrees: Double = 6
-
- public init(completedCount: Int, totalCount: Int, isWorking: Bool, fg: Color,
- lineWidth: CGFloat = 2, gapDegrees: Double = 6) {
- self.completedCount = completedCount
- self.totalCount = totalCount
- self.isWorking = isWorking
- self.fg = fg
- self.lineWidth = lineWidth
- self.gapDegrees = gapDegrees
- }
-
- public var body: some View {
- Canvas { context, size in
- let center = CGPoint(x: size.width / 2, y: size.height / 2)
- let radius = min(size.width, size.height) / 2 - lineWidth / 2
- let total = max(totalCount, 1)
- let totalGap = gapDegrees * Double(total)
- let segmentDegrees = (360.0 - totalGap) / Double(total)
-
- for i in 0..<total {
- let startAngle = -90.0 + Double(i) * (segmentDegrees + gapDegrees)
- let endAngle = startAngle + segmentDegrees
-
- let path = Path { p in
- p.addArc(
- center: center,
- radius: radius,
- startAngle: .degrees(startAngle),
- endAngle: .degrees(endAngle),
- clockwise: false
- )
- }
-
- let opacity: Double
- if i < completedCount {
- opacity = 0.8
- } else if i == completedCount && isWorking {
- opacity = 0.4
- } else {
- opacity = 0.12
- }
-
- context.stroke(
- path,
- with: .color(fg.opacity(opacity)),
- style: StrokeStyle(lineWidth: lineWidth, lineCap: .round)
- )
- }
- }
- }
-}
diff --git a/CodyncShared/Sources/Theme/SessionRowView.swift b/CodyncShared/Sources/Theme/SessionRowView.swift
deleted file mode 100644
index 19297bcd..00000000
--- a/CodyncShared/Sources/Theme/SessionRowView.swift
+++ /dev/null
@@ -1,82 +0,0 @@
-import SwiftUI
-
-/// Shared session row used in both Live Activity widget and in-app preview.
-/// Renders: dot + project name + model tag + spacer + current task
-public struct OverallSessionRow: View {
- public let projectName: String
- public let model: String
- public let currentTask: String?
- public let status: SessionStatus
- public let isPrimary: Bool
- public let fg: Color
- public var completedCount: Int = 0
- public var totalCount: Int = 0
-
- public init(
- projectName: String, model: String, currentTask: String?,
- status: SessionStatus, isPrimary: Bool, fg: Color,
- completedCount: Int = 0, totalCount: Int = 0
- ) {
- self.projectName = projectName
- self.model = model
- self.currentTask = currentTask
- self.status = status
- self.isPrimary = isPrimary
- self.fg = fg
- self.completedCount = completedCount
- self.totalCount = totalCount
- }
-
- public var body: some View {
- HStack(spacing: 8) {
- if totalCount > 0 {
- SegmentedRingView(
- completedCount: completedCount,
- totalCount: totalCount,
- isWorking: status == .working,
- fg: fg,
- lineWidth: 1.5,
- gapDegrees: 24
- )
- .frame(width: 12, height: 12)
- } else {
- Circle()
- .fill(dotColor)
- .frame(width: 7, height: 7)
- }
-
- Text(projectName)
- .font(.system(size: 13, weight: isPrimary ? .semibold : .medium))
- .foregroundStyle(fg)
- .lineLimit(1)
- .layoutPriority(1)
-
- Text(model)
- .font(.system(size: 10, weight: .medium))
- .foregroundStyle(fg.opacity(0.5))
- .padding(.horizontal, 6)
- .padding(.vertical, 2)
- .background(fg.opacity(0.08), in: Capsule())
-
- Spacer(minLength: 0)
-
- if let task = currentTask, !task.isEmpty {
- Text(task)
- .font(.system(size: 11))
- .foregroundStyle(fg.opacity(0.4))
- .lineLimit(1)
- .id(task)
- .transition(.push(from: .bottom))
- }
- }
- }
-
- private var dotColor: Color {
- if isPrimary { return fg }
- switch status {
- case .working: return fg
- case .idle: return fg.opacity(0.3)
- default: return fg.opacity(0.5)
- }
- }
-}
diff --git a/CodyncShared/Tests/ModelsTests.swift b/CodyncShared/Tests/ModelsTests.swift
deleted file mode 100644
index 07803320..00000000
--- a/CodyncShared/Tests/ModelsTests.swift
+++ /dev/null
@@ -1,71 +0,0 @@
-import XCTest
-@testable import CodyncShared
-
-final class ModelsTests: XCTestCase {
- func testSessionStatusColors() {
- XCTAssertTrue(SessionStatus.working.isActive)
- XCTAssertTrue(SessionStatus.needsInput.isActive)
- XCTAssertFalse(SessionStatus.completed.isActive)
- }
-
- func testTaskItemTruncation() {
- let short = TaskItem(id: "1", content: "Short task", status: .pending)
- XCTAssertEqual(short.truncatedContent, "Short task")
-
- let long = TaskItem(id: "2", content: String(repeating: "a", count: 60), status: .pending)
- XCTAssertEqual(long.truncatedContent.count, 50)
- XCTAssertTrue(long.truncatedContent.hasSuffix("..."))
- }
-
- func testSessionStateTaskCounts() {
- let session = SessionState(
- sessionId: "test", projectName: "Proj", gitBranch: "main",
- status: .working, model: "Opus", summary: "Testing",
- tasks: [
- TaskItem(id: "1", content: "Done", status: .completed),
- TaskItem(id: "2", content: "Doing", status: .inProgress),
- TaskItem(id: "3", content: "Todo", status: .pending),
- ]
- )
- XCTAssertEqual(session.completedTaskCount, 1)
- XCTAssertEqual(session.totalTaskCount, 3)
- }
-
- func testSessionStateTruncation() {
- let tasks = (1...15).map { TaskItem(id: "\($0)", content: "Task \($0)", status: .pending) }
- let session = SessionState(
- sessionId: "test", projectName: "Proj", gitBranch: "main",
- status: .working, model: "Opus", summary: "Testing", tasks: tasks
- )
- XCTAssertEqual(session.truncatedTasks.count, 10)
- XCTAssertEqual(session.truncatedTasks.first?.id, "6")
- }
-
- // MARK: - ModelInfo
-
- func testModelDisplayLabel() {
- XCTAssertEqual(ModelInfo.parse("claude-opus-4-6").displayLabel, "Opus 4.6")
- XCTAssertEqual(ModelInfo.parse("claude-opus-4-6[1m]").displayLabel, "Opus 4.6")
- XCTAssertEqual(ModelInfo.parse("claude-sonnet-4-6").displayLabel, "Sonnet 4.6")
- XCTAssertEqual(ModelInfo.parse("claude-haiku-4-5-20251001").displayLabel, "Haiku 4.5")
- XCTAssertEqual(ModelInfo.parse("claude-opus-4-1-20250805").displayLabel, "Opus 4.1")
- XCTAssertEqual(ModelInfo.parse("claude-3-5-sonnet-20241022").displayLabel, "Sonnet 3.5")
- XCTAssertEqual(ModelInfo.parse("unknown-model").displayLabel, "unknown-model")
- }
-
- func testModelContextWindow() {
- XCTAssertEqual(ModelInfo.parse("claude-opus-4-6").contextWindow, 1_000_000)
- XCTAssertEqual(ModelInfo.parse("claude-sonnet-4-6").contextWindow, 1_000_000)
- XCTAssertEqual(ModelInfo.parse("claude-haiku-4-5-20251001").contextWindow, 200_000)
- XCTAssertEqual(ModelInfo.parse("claude-opus-4-1-20250805").contextWindow, 200_000)
- XCTAssertEqual(ModelInfo.parse("claude-3-5-sonnet-20241022").contextWindow, 200_000)
- // [1m] suffix forces 1M even on older models
- XCTAssertEqual(ModelInfo.parse("claude-opus-4-1-20250805[1m]").contextWindow, 1_000_000)
- }
-
- func testTaskStatusDecoding() throws {
- let json = #"{"id":"1","content":"test","status":"in_progress"}"#
- let task = try JSONDecoder().decode(TaskItem.self, from: json.data(using: .utf8)!)
- XCTAssertEqual(task.status, .inProgress)
- }
-}
diff --git a/Codync-macOS/App/Codync.entitlements b/CodyncWidgets/CodyncWidgets.entitlements
similarity index 50%
rename from Codync-macOS/App/Codync.entitlements
rename to CodyncWidgets/CodyncWidgets.entitlements
index 3554934f..291cf12d 100644
--- a/Codync-macOS/App/Codync.entitlements
+++ b/CodyncWidgets/CodyncWidgets.entitlements
@@ -2,13 +2,9 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
- <key>com.apple.developer.icloud-container-identifiers</key>
+ <key>com.apple.security.application-groups</key>
<array>
- <string>iCloud.com.pokai.Codync</string>
- </array>
- <key>com.apple.developer.icloud-services</key>
- <array>
- <string>CloudKit</string>
+ <string>group.com.pokai.Codync</string>
</array>
</dict>
</plist>
diff --git a/CodyncWidgets/CodyncWidgets.swift b/CodyncWidgets/CodyncWidgets.swift
new file mode 100644
index 00000000..4ab2ecad
--- /dev/null
+++ b/CodyncWidgets/CodyncWidgets.swift
@@ -0,0 +1,216 @@
+import ActivityKit
+import AppIntents
+import CodyncKit
+import SwiftUI
+import WidgetKit
+
+@main
+struct CodyncWidgets: WidgetBundle {
+ var body: some Widget {
+ UsageWidget()
+ BotLiveActivity()
+ }
+}
+
+// MARK: - Usage widget
+
+struct UsageEntry: TimelineEntry {
+ let date: Date
+ let usage: Usage
+}
+
+struct UsageIntent: WidgetConfigurationIntent {
+ static let title: LocalizedStringResource = "Usage limits"
+}
+
+struct UsageTimeline: AppIntentTimelineProvider {
+ func placeholder(in context: Context) -> UsageEntry {
+ UsageEntry(date: .now, usage: .sample)
+ }
+
+ func snapshot(for configuration: UsageIntent, in context: Context) async -> UsageEntry {
+ UsageEntry(date: .now, usage: SharedStore.usage ?? .sample)
+ }
+
+ func timeline(for configuration: UsageIntent, in context: Context) async -> Timeline<UsageEntry> {
+ let usage = await Self.fetch() ?? SharedStore.usage ?? Usage()
+ return Timeline(entries: [UsageEntry(date: .now, usage: usage)], policy: .after(.now + 15 * 60))
+ }
+
+ /// Asks the paired host directly (works over Tailscale), falling back to the app's cache.
+ static func fetch() async -> Usage? {
+ guard let pairing = SharedStore.orderedPairing, let client = await HostClient.resolve(pairing),
+ let usage = try? await client.usage() else { return nil }
+ SharedStore.usage = usage
+ return usage
+ }
+}
+
+extension Usage {
+ static let sample = Usage(providers: [])
+}
+
+struct UsageWidget: Widget {
+ var body: some WidgetConfiguration {
+ AppIntentConfiguration(kind: "CodyncUsage", intent: UsageIntent.self, provider: UsageTimeline()) { entry in
+ UsageWidgetView(entry: entry)
+ .containerBackground(Palette.background, for: .widget)
+ }
+ .configurationDisplayName("Usage limits")
+ .description("Claude and Codex subscription limits from your computer.")
+ .supportedFamilies([.systemSmall, .systemMedium, .accessoryCircular, .accessoryRectangular])
+ }
+}
+
+struct UsageWidgetView: View {
+ let entry: UsageEntry
+ @Environment(\.widgetFamily) private var family
+
+ private var windows: [(provider: String, window: UsageWindow)] {
+ entry.usage.providers.flatMap { p in p.windows.map { (p.name, $0) } }
+ }
+
+ var body: some View {
+ switch family {
+ case .accessoryCircular:
+ if let first = windows.first {
+ Gauge(value: min(first.window.percent, 100), in: 0...100) {
+ Text(first.provider.prefix(1))
+ } currentValueLabel: {
+ Text("\(Int(first.window.percent.rounded()))")
+ }
+ .gaugeStyle(.accessoryCircularCapacity)
+ } else {
+ Image(systemName: "gauge.with.dots.needle.0percent")
+ }
+ case .accessoryRectangular:
+ VStack(alignment: .leading, spacing: 2) {
+ ForEach(Array(windows.prefix(3).enumerated()), id: \.offset) { _, item in
+ HStack {
+ Text("\(item.provider) \(item.window.label)").lineLimit(1)
+ Spacer()
+ Text("\(Int(item.window.percent.rounded()))%").monospacedDigit()
+ }
+ .font(.caption2)
+ }
+ }
+ default:
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 6) {
+ CharacterAvatar(shape: "blob", color: "green", size: 16)
+ Text("Usage").font(.caption.bold()).foregroundStyle(Palette.text)
+ }
+ if windows.isEmpty {
+ Text("Open Codync and pair with your computer.")
+ .font(.caption2)
+ .foregroundStyle(Palette.secondary)
+ }
+ ForEach(Array(windows.prefix(family == .systemSmall ? 3 : 4).enumerated()), id: \.offset) { _, item in
+ VStack(alignment: .leading, spacing: 3) {
+ HStack {
+ Text("\(item.provider) · \(item.window.label)").lineLimit(1)
+ Spacer(minLength: 2)
+ Text("\(Int(item.window.percent.rounded()))%").bold().monospacedDigit()
+ }
+ .font(.caption2)
+ .foregroundStyle(Palette.text)
+ GeometryReader { geo in
+ ZStack(alignment: .leading) {
+ Capsule().fill(Palette.bubbleAgent)
+ Capsule()
+ .fill(item.window.percent >= 90 ? Palette.danger : item.window.percent >= 70 ? Palette.warning : Palette.accentFill)
+ .frame(width: geo.size.width * min(1, max(0.02, item.window.percent / 100)))
+ }
+ }
+ .frame(height: 5)
+ if family == .systemMedium, let reset = item.window.resetDate {
+ Text("resets \(reset, style: .relative)").font(.system(size: 9)).foregroundStyle(Palette.tertiary)
+ }
+ }
+ }
+ Spacer(minLength: 0)
+ }
+ }
+ }
+}
+
+// MARK: - Live Activity
+
+struct BotLiveActivity: Widget {
+ var body: some WidgetConfiguration {
+ ActivityConfiguration(for: BotActivityAttributes.self) { context in
+ LockScreenView(context: context)
+ .activityBackgroundTint(Palette.background)
+ .widgetURL(URL(string: "codync://bot/\(context.attributes.botId)"))
+ } dynamicIsland: { context in
+ let s = context.state
+ return DynamicIsland {
+ DynamicIslandExpandedRegion(.leading) {
+ CharacterAvatar(shape: context.attributes.avatarShape, color: context.attributes.avatarColor, size: 36,
+ mood: s.status == "needsInput" ? .needsInput : .working)
+ }
+ DynamicIslandExpandedRegion(.center) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(context.attributes.name).font(.headline)
+ Text(statusText(s)).font(.caption).foregroundStyle(s.status == "needsInput" ? Palette.warning : .secondary).lineLimit(2)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ DynamicIslandExpandedRegion(.trailing) {
+ if let started = s.startedAt, s.status == "working" {
+ Text(started, style: .timer).font(.caption.monospacedDigit()).frame(width: 52)
+ }
+ }
+ } compactLeading: {
+ CharacterAvatar(shape: context.attributes.avatarShape, color: context.attributes.avatarColor, size: 20)
+ } compactTrailing: {
+ if s.status == "needsInput" {
+ Image(systemName: "hand.raised.fill").foregroundStyle(Palette.warning)
+ } else if s.status == "working", let started = s.startedAt {
+ Text(started, style: .timer).font(.caption2.monospacedDigit()).frame(width: 40)
+ } else {
+ Image(systemName: "checkmark").foregroundStyle(Palette.accentFill)
+ }
+ } minimal: {
+ CharacterAvatar(shape: context.attributes.avatarShape, color: context.attributes.avatarColor, size: 20)
+ }
+ .widgetURL(URL(string: "codync://bot/\(context.attributes.botId)"))
+ }
+ }
+}
+
+private func statusText(_ s: BotActivityAttributes.ContentState) -> String {
+ switch s.status {
+ case "needsInput": s.activity.isEmpty ? "Needs your approval" : s.activity
+ case "working": s.activity.isEmpty ? "Working…" : s.activity
+ case "error": "Stopped with an error"
+ default: "Done"
+ }
+}
+
+private struct LockScreenView: View {
+ let context: ActivityViewContext<BotActivityAttributes>
+
+ var body: some View {
+ let s = context.state
+ HStack(spacing: 12) {
+ CharacterAvatar(shape: context.attributes.avatarShape, color: context.attributes.avatarColor, size: 44,
+ mood: s.status == "needsInput" ? .needsInput : s.status == "working" ? .working : .idle)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(context.attributes.name).font(.headline).foregroundStyle(Palette.text)
+ Text(statusText(s))
+ .font(.subheadline)
+ .foregroundStyle(s.status == "needsInput" ? Palette.warning : Palette.secondary)
+ .lineLimit(2)
+ }
+ Spacer()
+ if s.status == "working", let started = s.startedAt {
+ Text(started, style: .timer)
+ .font(.title3.monospacedDigit())
+ .foregroundStyle(Palette.accent)
+ .frame(width: 70, alignment: .trailing)
+ }
+ }
+ .padding(16)
+ }
+}
diff --git a/CodyncLiveActivity/Info.plist b/CodyncWidgets/Info.plist
similarity index 51%
rename from CodyncLiveActivity/Info.plist
rename to CodyncWidgets/Info.plist
index d0bb9cf5..046bb469 100644
--- a/CodyncLiveActivity/Info.plist
+++ b/CodyncWidgets/Info.plist
@@ -2,14 +2,25 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
- <key>CFBundleVersion</key>
- <string>1</string>
- <key>CFBundleShortVersionString</key>
- <string>1.0</string>
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.widgetkit-extension</string>
</dict>
+ <key>NSAppTransportSecurity</key>
+ <dict>
+ <key>NSAllowsLocalNetworking</key>
+ <true/>
+ <key>NSExceptionDomains</key>
+ <dict>
+ <key>ts.net</key>
+ <dict>
+ <key>NSIncludesSubdomains</key>
+ <true/>
+ <key>NSExceptionAllowsInsecureHTTPLoads</key>
+ <true/>
+ </dict>
+ </dict>
+ </dict>
</dict>
</plist>
diff --git a/README.md b/README.md
index aa725213..e1c4ab7f 100644
--- a/README.md
+++ b/README.md
@@ -1,71 +1,95 @@
# Codync
-A real-time companion for [Claude Code](https://docs.anthropic.com/en/docs/claude-code) — monitor your coding sessions from anywhere, on any Apple device.
+**Your coding agents, as teammates you can message.**
-> Now you can vibe code with Claude Code while jogging.
+Codync turns Claude Code, Codex, OpenCode, Grok Build and Gemini CLI into persistent *bots* you delegate to from your iPhone — the way you'd message a colleague. Pick who, say what, put the phone away. You get a notification when a bot finishes or needs your approval.
+
+> Why bots? On a phone, "find the right working session, then pick an environment" is too slow. With bots you already know who to hand the intent to: open the chat, type, done.
[![Download on the App Store](https://img.shields.io/badge/App_Store-iOS-blue?logo=apple)](https://apps.apple.com/tw/app/codync/id6760984418?l=en-GB)
-[![Download for macOS](https://img.shields.io/badge/Download-macOS-black?logo=apple)](https://github.com/leepokai/Codync/releases/latest/download/Codync-macOS.dmg)
[![Homebrew](https://img.shields.io/badge/Homebrew-codync-orange?logo=homebrew)](https://github.com/leepokai/homebrew-codync)
-## Features
+## How it works
-- **Dynamic Island & Live Activity** — See session status right on your Lock Screen and Dynamic Island, even when the app is closed
-- **macOS Menu Bar** — Instant session overview without leaving your workflow
-- **Cross-device Sync** — CloudKit-powered sync between Mac and iPhone, no LAN required
-- **Push Notifications** — Get notified when Claude needs your input or finishes a task
-- **Hook-driven Detection** — 7 Claude Code hooks provide instant, accurate status with ~20ms latency
-- **Zero Configuration** — One-click install, no login, no account, no analytics
+```
+iPhone (Codync) ⇄ HTTP + SSE over Tailscale / Wi-Fi ⇄ codync-host ⇄ ACP (stdio) ⇄ claude · codex · opencode · grok · gemini
+ ▲ │
+ └──────── APNs ◀── relay (Cloudflare Worker) ◀────────┘ "needs you" / "done"
+```
-## How It Works
+- **Bots** have a name, a character avatar, standing instructions, an agent backend, a project folder and a permission policy. Each bot is **one endless conversation**; the agent sessions underneath are an implementation detail (resumed with `session/load`, restarted with *New session*).
+- **The chat only shows what matters**: your messages, each turn's final reply, approval cards and notices. Every tool call, diff, plan and thought is one tap away in *Full conversation*. While a bot works, its row shows what it's doing right now.
+- **codync-host** (Rust, macOS + Linux) runs on your computer. It speaks the [Agent Client Protocol](https://agentclientprotocol.com) to each agent, keeps transcripts in SQLite, and serves the phone. Every change carries a global `rev`, so the phone reconnects with `since: rev` and never misses anything.
+- **Usage limits**: the host reads Claude (statusline `rate_limits`, or the OAuth usage endpoint with the token Claude Code already stored) and Codex (`~/.codex/sessions`) limits. Tokens never leave your computer; the phone and widgets only see percentages.
+- **Push** goes through a tiny relay that holds the APNs key. The phone trades its device token for an encrypted ticket; the host only ever holds tickets.
-1. **macOS app** installs lightweight hook scripts into Claude Code
-2. Hooks fire on session events (start, stop, tool use, permission requests, etc.)
-3. Session state syncs to iOS via CloudKit in real-time
-4. iOS app displays status via Live Activity, Dynamic Island, and push notifications
+UI patterns (roster, character avatars, approval cards, trace sheet, "needs you / done" notifications) follow Grok Bot.
## Install
-**macOS (Homebrew)**
+**Mac**
```bash
-brew tap leepokai/codync
-brew install --cask codync
+brew install --cask leepokai/codync/codync
```
-**macOS (Manual)** — Download the [latest DMG](https://github.com/leepokai/Codync/releases/latest/download/Codync-macOS.dmg) and drag to Applications
+Open Codync in the menu bar → **Install host** → **Pair iPhone**, and scan the code with the Codync app.
+
+**Linux**
-**iOS** — Install from the [App Store](https://apps.apple.com/tw/app/codync/id6760984418?l=en-GB)
+```bash
+brew install leepokai/codync/codync-host # or download a release tarball
+codync-host install # systemd --user service
+codync-host pair # shows the QR code in the terminal
+```
-The in-app onboarding wizard will guide you through setup — just open the macOS app and follow the steps.
+Install [Tailscale](https://tailscale.com) on the computer and the phone to reach your bots from anywhere.
-## Project Structure
+**Agents** — install and log in to whichever you use: `claude`, `codex`, `opencode`, `grok`, `gemini`. Claude Code and Codex are driven through their ACP adapters (`@agentclientprotocol/claude-agent-acp`, `@agentclientprotocol/codex-acp`), which `npx` fetches on first use, so Node.js is required for those two.
-| Target | Description |
+Optional: show usage in Claude Code's status line and feed live limits to the host:
+
+```json
+{ "statusLine": { "type": "command", "command": "codync-host statusline" } }
+```
+
+## `codync-host`
+
+| Command | |
|---|---|
-| `Codync-macOS` | macOS menu bar app — hook server, transcript parsing, CloudKit sync |
-| `Codync-iOS` | iOS companion — Live Activity, Dynamic Island, push notifications |
-| `CodyncShared` | Shared Swift Package — models, CloudKit logic, theme |
-| `CodyncLiveActivity` | iOS Live Activity widget extension |
-| `worker/` | Cloudflare Worker — APNs relay for background Live Activity updates |
-| `Codync-web/` | Landing page (Next.js) |
+| `codync-host install` / `uninstall` | background service (launchd on macOS, systemd `--user` on Linux); also removes Codync 1.x Claude hooks |
+| `codync-host pair [--json]` | pairing QR code / link |
+| `codync-host status` | installed? running? |
+| `codync-host serve [--port 19222]` | run in the foreground |
+| `codync-host statusline` | Claude Code status line command |
+| `codync-host reset-token` | unpair every phone |
-## Tech Stack
+Data lives in `~/.codync` (`codync.db`, `token`, `host.log`). The API is `POST /api/<method>` + `GET /events` (SSE), both with `Authorization: Bearer <token>`; see `host/src/api.rs`.
-- Swift 6 strict concurrency
-- SwiftUI + `@Observable`
-- CloudKit for cross-device sync
-- Claude Code hooks (command-based, ~20ms overhead)
-- Cloudflare Worker for APNs relay
-- Next.js landing page
+## Repository
+
+| Path | |
+|---|---|
+| `host/` | `codync-host` — Rust daemon: ACP client, SQLite transcript, HTTP/SSE API, push, usage |
+| `Codync-iOS/` | iOS app: roster, threads, approval cards, trace, bot editor, pairing |
+| `CodyncWidgets/` | Usage widget + bot Live Activity |
+| `Codync-macOS/` | Menu bar app: installs/monitors the host, pairing QR, usage |
+| `CodyncKit/` | Shared Swift package: wire models, host client, theme, avatars |
+| `relay/` | Cloudflare Worker APNs relay with encrypted per-device tickets |
+| `packaging/` | Homebrew formula template |
-## Acknowledgments
+The Xcode project is generated: `xcodegen generate`.
+
+```bash
+cd host && cargo test # host
+cd CodyncKit && swift test # shared Swift
+cd relay && npm test # relay tickets
+```
-Inspired by these awesome projects:
+## Versioning
-- [chowder-iOS](https://github.com/newmaterialco/chowder-iOS) — Native iOS client for AI agent interaction with real-time thinking and tool activity display
-- [notchi](https://github.com/sk-ruban/notchi) — macOS notch companion that reacts to Claude Code activity in real-time
+The major version is the phone ↔ host protocol: 2.x apps work with 2.x hosts. Codync 2 replaces the 1.x hook/CloudKit monitor entirely.
## License
-[MIT](LICENSE) © Po Kai Lee
+MIT
diff --git a/docs/architecture-decisions/2026-03-20-apns-worker-push-removed.md b/docs/architecture-decisions/2026-03-20-apns-worker-push-removed.md
deleted file mode 100644
index d2e81cce..00000000
--- a/docs/architecture-decisions/2026-03-20-apns-worker-push-removed.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# APNs Worker Push — Removed (2026-03-20)
-
-## What It Was
-
-A secondary push path for updating iOS Live Activities via a Cloudflare Worker relay:
-
-```
-macOS → POST to Cloudflare Worker → Worker signs APNs JWT → Apple APNs → iOS Live Activity widget
-```
-
-### Implementation
-
-- **Worker**: `worker/src/index.ts` — Cloudflare Worker at `https://codync-push.kevin2005ha.workers.dev`
- - Receives `{pushToken, event, contentState}` from macOS
- - Signs with APNs credentials (Team ID, Key ID, .p8 signing key stored in Worker secrets)
- - Sends to `api.sandbox.push.apple.com` with push type `liveactivity`
- - Bundle ID: `com.pokai.Codync.ios.push-type.liveactivity`
-
-- **macOS side** (`APNsPushService.swift`):
- - Fetches push tokens from CloudKit every 30 seconds (`PushToken` record type)
- - After each CloudKit save, calls `sendUpdate(session:)` for changed sessions
- - On session disappear, calls `sendEnd(sessionId:)` before deleting CloudKit record
- - Bearer token auth to Worker
-
-- **iOS side** (`LiveActivityManager.swift`):
- - On `Activity.request(pushType: .token)`, observes `activity.pushTokenUpdates`
- - Saves hex-encoded push token to CloudKit as `PushToken` record (keyed by `pushtoken-{sessionId}`)
- - macOS reads these tokens to address APNs pushes
-
-### Push Token Sync Chain
-
-```
-iOS starts Live Activity → gets push token from ActivityKit
- → saves to CloudKit (PushToken record)
- → macOS fetches tokens every 30s
- → macOS POSTs to Worker with token + contentState
- → Worker → APNs → iOS Live Activity widget updates on Lock Screen
-```
-
-## Why It Was Removed
-
-### CloudKit Silent Push Is Sufficient
-
-Testing on 2026-03-20 confirmed that CloudKit zone subscription silent push (`CKRecordZoneSubscription` with `shouldSendContentAvailable: true`) is:
-- **Immediate**: every CloudKit record save triggers a silent push within ~1 second
-- **Reliable**: consistently delivered while the iOS app is in background (not force-quit)
-- **Sufficient**: iOS `didReceiveRemoteNotification` wakes the app, fetches fresh data, and calls `activity.update()` locally
-
-### Worker Push Was Redundant
-
-With silent push working, the Worker relay added complexity without benefit:
-- Extra network hop (macOS → Worker → APNs) vs. native (macOS → CloudKit → Apple silent push → iOS)
-- Push token sync overhead (CloudKit PushToken records, 30s fetch interval)
-- Worker maintenance (secrets, deployment, sandbox vs production APNs endpoint)
-- Both paths ultimately update the same Live Activity
-
-### Known Limitation
-
-**When the iOS app is force-quit by the user** (swipe up to kill), silent push is not delivered by iOS. In this scenario, the Worker APNs push would have been the only way to update the Live Activity on the Lock Screen. Without it, the Live Activity will show stale data until the user reopens the app.
-
-This trade-off was accepted because:
-1. Force-quit is an explicit user action — they chose to stop the app
-2. The Live Activity will eventually be dismissed by iOS (8-hour expiry)
-3. The complexity cost of maintaining the Worker path outweighed this edge case
-
-## How to Restore
-
-If needed in the future, the full implementation is in git history:
-- Commit before removal: `c88c368` (feat: APNs push diagnostic logging)
-- Key files: `APNsPushService.swift`, `CloudKitSync.swift` (the APNs call sites), `worker/src/index.ts`
-- CloudKit record type: `PushToken` (still exists in schema, iOS still saves tokens)
-
-To restore: re-add `APNsPushService.shared.fetchPushTokens()` and `sendUpdate(session:)` calls in `CloudKitSync.syncToCloud()` after the `saveBatch` succeeds.
-
-## Current Architecture
-
-```
-macOS hooks → SessionStateManager → CloudKitSync → CloudKit
- ↓
- Apple silent push (automatic)
- ↓
- iOS didReceiveRemoteNotification
- ↓
- CloudKitReceiver.fetch() → LiveActivityManager.updateSessions()
- ↓
- activity.update() (local)
-```
-
-Single path. No Worker, no polling, no APNs relay.
diff --git a/docs/architecture-decisions/2026-03-21-heartbeat-worker-fallback.md b/docs/architecture-decisions/2026-03-21-heartbeat-worker-fallback.md
deleted file mode 100644
index fd6fb213..00000000
--- a/docs/architecture-decisions/2026-03-21-heartbeat-worker-fallback.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# Heartbeat + Worker APNs Fallback (2026-03-21)
-
-## Problem
-
-CloudKit silent push is the primary sync path for iOS Live Activity updates, but iOS throttles it when the app is in background for a while or gets killed. This causes Live Activity to freeze with stale data.
-
-The Worker APNs Live Activity push was previously removed because it was always-on (redundant when silent push works) and there was no way to know if the iOS app was still running.
-
-## Proposed Solution: Heartbeat Detection + Smart Fallback
-
-### Heartbeat Mechanism
-
-1. iOS app writes a heartbeat record to CloudKit every 30 seconds while running
-2. macOS reads the heartbeat timestamp before deciding which push path to use
-3. If heartbeat is fresh (< 60s): iOS app is alive → silent push is sufficient → skip Worker
-4. If heartbeat is stale (> 60s): iOS app is suspended/killed → send Worker APNs push
-
-### Architecture
-
-```
-iOS app running:
- - Every 30s → write heartbeat to CloudKit
- - Silent push arrives → fetch → update Live Activity locally
-
-iOS app suspended/killed:
- - Heartbeat stops → timestamp becomes stale
- - macOS detects stale heartbeat → sends Worker APNs push
- - APNs push updates Live Activity directly (no app needed)
-```
-
-### CloudKit Record
-
-```
-Record Type: "Heartbeat"
-Record Name: "heartbeat-{deviceId}"
-Fields:
- - deviceId: String
- - timestamp: Date
- - appState: String ("active" | "background" | "suspended")
-```
-
-## Paid Feature Tier (Future)
-
-| | Free | Pro |
-|--|------|-----|
-| Foreground sync | CloudKit silent push | Same |
-| Background sync | Silent push (iOS may throttle) | Worker APNs (direct Live Activity update) |
-| App killed | Live Activity freezes | Worker keeps updating |
-| Heartbeat detection | — | Smart fallback switching |
-
-### Pro Selling Point
-
-"Always-on Live Activity" — Dynamic Island and Lock Screen stay updated even when the app is closed.
-
-### Cost Considerations
-
-- Cloudflare Worker: free tier covers ~100k requests/day
-- APNs: free (Apple doesn't charge)
-- CloudKit heartbeat: minimal (1 write/30s per device)
-- Main cost is APNs signing key management and Worker maintenance
-
-## Implementation Order
-
-1. Add heartbeat write to iOS app (CloudKit record every 30s)
-2. Add heartbeat read to macOS CloudKitSync (check before save)
-3. Re-enable Worker APNs push in CloudKitSync (only when heartbeat stale)
-4. Add paid gate (UserDefaults flag or StoreKit check)
-
-## References
-
-- Worker code: `worker/src/index.ts` (still deployed)
-- Previous APNs implementation: git commit `c88c368`
-- Removal decision: `docs/architecture-decisions/2026-03-20-apns-worker-push-removed.md`
diff --git a/docs/architecture-decisions/2026-03-21-ios-ui-architecture-vision.md b/docs/architecture-decisions/2026-03-21-ios-ui-architecture-vision.md
deleted file mode 100644
index d7e8b1ee..00000000
--- a/docs/architecture-decisions/2026-03-21-ios-ui-architecture-vision.md
+++ /dev/null
@@ -1,87 +0,0 @@
-# iOS UI Architecture Vision (2026-03-21)
-
-## Current State
-- Single view: session list with flat navigation
-- No tab system, no feature switching
-
-## Future Features
-- **Claude Code sessions** (current)
-- **Codex** integration
-- **Claude Remote Control / Cowork** mode
-- **Overall Live Activity** vs **Individual Live Activity** mode switching
-
-## Proposed Architecture
-
-### Tab Bar with Liquid Glass
-
-Bottom tab bar (or segmented control at top) with glass morph aesthetic:
-
-```
-┌──────────────────────────────────────┐
-│ [Sessions] [Codex] [Remote] │ ← liquid glass tabs
-├──────────────────────────────────────┤
-│ │
-│ Session list / Codex view / etc. │
-│ │
-└──────────────────────────────────────┘
-```
-
-Each tab = a different AI workflow:
-- **Sessions**: Claude Code session monitoring (current functionality)
-- **Codex**: Codex job tracking (future)
-- **Remote**: Remote control / cowork mode (future)
-
-### Live Activity Configuration (in Sessions tab)
-
-Top of session list:
-```
-┌──────────────────────────────────────┐
-│ [Overall] [Individual] │ ← mode switcher
-├──────────────────────────────────────┤
-│ Max sessions: [1] [2] [3] [4] │ ← only in Overall mode
-│ Primary: ByCrawl ★ │ ← tap to set primary
-├──────────────────────────────────────┤
-│ ✦ ByCrawl Opus working │
-│ ● Codync Opus idle │
-│ ... │
-└──────────────────────────────────────┘
-```
-
-### Overall Live Activity Layout
-
-```
-Lock Screen (max 4 sessions):
-┌──────────────────────────────────────┐
-│ Codync $2.30 │
-│ │
-│ ★ ByCrawl Opus ⌨️ Running.. │ ← primary (highlighted color)
-│ ● Codync Opus idle │ ← normal row
-│ ● SignalWeb Sonnet idle │ ← normal row
-│ │
-│ ⌨️ Running command 0:05 │ ← primary's current tool
-└──────────────────────────────────────┘
-
-Dynamic Island: shows primary session only
-Apple Watch: shows primary session only
-```
-
-### Design Principles
-
-1. **Liquid glass tab bar**: frosted glass background, smooth transitions between tabs
-2. **Progressive disclosure**: start with Sessions tab, add tabs as features are built
-3. **Primary session**: single source of truth for Dynamic Island / Watch / notification focus
-4. **Overall mode**: compact multi-session view, primary highlighted
-5. **Individual mode**: current per-session Live Activity approach
-
-### Implementation Priority
-
-1. Live Activity redesign (Overall + Individual modes, primary session)
-2. Top-level mode switcher UI
-3. Tab bar skeleton (Sessions only, prepared for future tabs)
-4. Codex tab (when ready)
-5. Remote tab (when ready)
-
-## Questions
-- Tab bar style: bottom TabView or top segmented control?
-- Should the liquid glass tab have animation between tabs (slide/morph)?
-- Codex integration: what data to show? Job status, logs, cost?
diff --git a/docs/architecture-decisions/2026-03-21-live-activity-redesign-proposal.md b/docs/architecture-decisions/2026-03-21-live-activity-redesign-proposal.md
deleted file mode 100644
index 92a59dbe..00000000
--- a/docs/architecture-decisions/2026-03-21-live-activity-redesign-proposal.md
+++ /dev/null
@@ -1,68 +0,0 @@
-# Live Activity Redesign Proposal (2026-03-21)
-
-## Current Issues
-- Multiple Live Activities (up to 4) with complex tracking, grace periods, auto-fill
-- iOS controls which one shows on Dynamic Island (unpredictable)
-- No way to show all sessions at once
-
-## Proposed Design
-
-### Two Modes
-
-**Mode A: Overall (unified Live Activity)**
-- Single Live Activity showing ALL tracked sessions as a compact list
-- User selects how many sessions to show (1-N, system adapts layout)
-- Lock Screen shows all sessions with status indicators
-
-**Mode B: Individual (current approach)**
-- Separate Live Activity per session
-- Same as current but simplified
-
-### Primary Session
-- User designates ONE session as "primary"
-- Primary session shown on:
- - Dynamic Island (compact + expanded)
- - Apple Watch (future)
-- If primary session killed (not found in CloudKit) → auto-select next working session
-- Only ONE primary at a time, persisted via CloudKit
-
-### Layout Adaptation
-- 1 session: full detail view (tool cards, stacking, timer)
-- 2-3 sessions: medium rows (status + project + current tool)
-- 4+ sessions: compact rows (status dot + project name only)
-
-### Data Model Changes
-```swift
-// New ContentState for Overall mode
-struct OverallContentState {
- let sessions: [SessionSummary]
- let primarySessionId: String?
- let totalCost: Double
-}
-
-struct SessionSummary {
- let sessionId: String
- let projectName: String
- let status: String
- let currentTask: String?
- let model: String
- let costUSD: Double
-}
-```
-
-### Primary Session Detection
-- Stored as CloudKit record: `PrimarySession`
-- macOS checks if PID is alive → if dead, CloudKit record deleted
-- iOS detects deletion → auto-promotes next working session
-
-### Implementation Order
-1. Design the two Live Activity layouts (overall + individual)
-2. Add primary session CloudKit record
-3. Rewrite LiveActivityManager for dual-mode support
-4. Add mode selector UI in iOS app
-5. Apple Watch support (future)
-
-## Questions to Resolve
-- Max sessions to display? (Lock Screen height ~160pt limits to ~5-6 rows)
-- Should overall mode show tool stacking for primary session?
-- Watch complication design?
diff --git a/docs/superpowers/plans/2026-03-21-ios-ui-architecture-redesign.md b/docs/superpowers/plans/2026-03-21-ios-ui-architecture-redesign.md
deleted file mode 100644
index c248b2a9..00000000
--- a/docs/superpowers/plans/2026-03-21-ios-ui-architecture-redesign.md
+++ /dev/null
@@ -1,1366 +0,0 @@
-# iOS UI Architecture Redesign — Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Restructure the Codync iOS app into a tabbed architecture with dual Live Activity modes and Primary Session support.
-
-**Architecture:** Incremental refactor — wrap existing views in TabView, extend LiveActivityManager with dual mode, add PrimarySessionManager as new service. All changes are additive; existing Individual mode logic preserved.
-
-**Tech Stack:** Swift 6 (strict concurrency), SwiftUI, ActivityKit, CloudKit, CodyncShared package
-
-**Spec:** `docs/superpowers/specs/2026-03-21-ios-ui-architecture-redesign.md`
-
----
-
-## Task 1: Shared Data Models
-
-**Files:**
-- Create: `CodyncShared/Sources/Models/LiveActivityMode.swift`
-- Create: `CodyncShared/Sources/Models/SessionSummary.swift`
-- Create: `CodyncShared/Sources/Models/OverallAttributes.swift`
-
-These models are used by both the iOS app and the Live Activity widget extension. They must be in `CodyncShared` so both targets can import them.
-
-- [ ] **Step 1: Create LiveActivityMode enum**
-
-Create `CodyncShared/Sources/Models/LiveActivityMode.swift`:
-
-```swift
-import Foundation
-
-public enum LiveActivityMode: String, Codable, Sendable {
- case overall
- case individual
-}
-```
-
-- [ ] **Step 2: Create SessionSummary model**
-
-Create `CodyncShared/Sources/Models/SessionSummary.swift`:
-
-```swift
-import Foundation
-
-public struct SessionSummary: Codable, Hashable, Sendable {
- public let sessionId: String
- public let projectName: String
- public let status: SessionStatus
- public let model: String
- public let currentTask: String?
- public let costUSD: Double
-
- public init(sessionId: String, projectName: String, status: SessionStatus,
- model: String, currentTask: String?, costUSD: Double) {
- self.sessionId = sessionId
- self.projectName = projectName
- self.status = status
- self.model = model
- self.currentTask = currentTask
- self.costUSD = costUSD
- }
-}
-```
-
-- [ ] **Step 3: Create OverallAttributes**
-
-Create `CodyncShared/Sources/Models/OverallAttributes.swift`:
-
-```swift
-import Foundation
-
-#if os(iOS)
-import ActivityKit
-
-public struct OverallAttributes: ActivityAttributes, Codable, Sendable {
- public struct ContentState: Codable, Hashable, Sendable {
- public let sessions: [SessionSummary]
- public let primarySessionId: String?
- public let totalCost: Double
-
- public init(sessions: [SessionSummary], primarySessionId: String?, totalCost: Double) {
- self.sessions = sessions
- self.primarySessionId = primarySessionId
- self.totalCost = totalCost
- }
- }
-
- public init() {}
-}
-
-#else
-
-public struct OverallAttributes: Codable, Sendable {
- public struct ContentState: Codable, Hashable, Sendable {
- public let sessions: [SessionSummary]
- public let primarySessionId: String?
- public let totalCost: Double
-
- public init(sessions: [SessionSummary], primarySessionId: String?, totalCost: Double) {
- self.sessions = sessions
- self.primarySessionId = primarySessionId
- self.totalCost = totalCost
- }
- }
-
- public init() {}
-}
-
-#endif
-```
-
-Note: Uses the same `#if os(iOS)` pattern as `CodyncAttributes.swift` — `ActivityAttributes` conformance on iOS only, plain `Codable` on macOS.
-
-- [ ] **Step 4: Build to verify compilation**
-
-Run: `xcodebuild -scheme CodyncShared -destination 'generic/platform=iOS' build 2>&1 | tail -5`
-
-Expected: `BUILD SUCCEEDED`
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add CodyncShared/Sources/Models/LiveActivityMode.swift \
- CodyncShared/Sources/Models/SessionSummary.swift \
- CodyncShared/Sources/Models/OverallAttributes.swift
-git commit -m "feat: add shared models for dual Live Activity mode"
-```
-
----
-
-## Task 2: CloudKit — Primary Session & Live Activity Preference
-
-**Files:**
-- Modify: `CodyncShared/Sources/CloudKit/CloudKitManager.swift`
-
-Add methods to manage two new singleton CloudKit records: `PrimarySession` and `LiveActivityPreference`. Both use fixed `recordName` values for upsert semantics.
-
-- [ ] **Step 1: Add PrimarySession record methods**
-
-Add to `CloudKitManager.swift` after the existing `// MARK: - Pinned Sessions` section:
-
-```swift
-// MARK: - Primary Session
-
-static let primarySessionRecordType = "PrimarySession"
-private static let primarySessionRecordName = "primary-session"
-
-public func fetchPrimarySession() async -> (sessionId: String?, locked: Bool) {
- let recordID = CKRecord.ID(recordName: Self.primarySessionRecordName, zoneID: Self.zoneID)
- do {
- let record = try await database.record(for: recordID)
- let sessionId = record["sessionId"] as? String
- let locked = (record["isManuallyLocked"] as? Int64 ?? 0) == 1
- return (sessionId, locked)
- } catch {
- return (nil, false)
- }
-}
-
-public func setPrimarySession(_ sessionId: String, locked: Bool) async {
- let recordID = CKRecord.ID(recordName: Self.primarySessionRecordName, zoneID: Self.zoneID)
- let record: CKRecord
- if let existing = try? await database.record(for: recordID) {
- record = existing
- } else {
- record = CKRecord(recordType: Self.primarySessionRecordType, recordID: recordID)
- }
- record["sessionId"] = sessionId as CKRecordValue
- record["isManuallyLocked"] = (locked ? 1 : 0) as CKRecordValue
- record["updatedAt"] = Date() as CKRecordValue
- _ = try? await database.save(record)
-}
-
-public func clearPrimarySession() async {
- let recordID = CKRecord.ID(recordName: Self.primarySessionRecordName, zoneID: Self.zoneID)
- try? await database.deleteRecord(withID: recordID)
-}
-```
-
-- [ ] **Step 2: Add LiveActivityPreference record methods**
-
-Add after the Primary Session section:
-
-```swift
-// MARK: - Live Activity Preference
-
-static let liveActivityPrefRecordType = "LiveActivityPreference"
-private static let liveActivityPrefRecordName = "live-activity-pref"
-
-public func fetchLiveActivityPreference() async -> (mode: LiveActivityMode, maxSessions: Int) {
- let recordID = CKRecord.ID(recordName: Self.liveActivityPrefRecordName, zoneID: Self.zoneID)
- do {
- let record = try await database.record(for: recordID)
- let modeStr = record["mode"] as? String ?? "overall"
- let mode = LiveActivityMode(rawValue: modeStr) ?? .overall
- let maxSessions = record["maxSessions"] as? Int64 ?? 4
- return (mode, Int(maxSessions))
- } catch {
- return (.overall, 4)
- }
-}
-
-public func setLiveActivityPreference(mode: LiveActivityMode, maxSessions: Int) async {
- let recordID = CKRecord.ID(recordName: Self.liveActivityPrefRecordName, zoneID: Self.zoneID)
- let record: CKRecord
- if let existing = try? await database.record(for: recordID) {
- record = existing
- } else {
- record = CKRecord(recordType: Self.liveActivityPrefRecordType, recordID: recordID)
- }
- record["mode"] = mode.rawValue as CKRecordValue
- record["maxSessions"] = maxSessions as CKRecordValue
- _ = try? await database.save(record)
-}
-```
-
-- [ ] **Step 3: Add import for LiveActivityMode**
-
-The file already imports `Foundation` and `CloudKit`. `LiveActivityMode` is in the same `CodyncShared` module, so no extra import needed. Verify it compiles:
-
-Run: `xcodebuild -scheme CodyncShared -destination 'generic/platform=iOS' build 2>&1 | tail -5`
-
-Expected: `BUILD SUCCEEDED`
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add CodyncShared/Sources/CloudKit/CloudKitManager.swift
-git commit -m "feat: add CloudKit methods for PrimarySession and LiveActivityPreference"
-```
-
----
-
-## Task 3: PrimarySessionManager
-
-**Files:**
-- Create: `Codync-iOS/Services/PrimarySessionManager.swift`
-
-New `@MainActor` service that manages which session is "primary" for Dynamic Island focus. Supports auto-selection (most active session) and manual lock.
-
-- [ ] **Step 1: Create PrimarySessionManager**
-
-Create `Codync-iOS/Services/PrimarySessionManager.swift`:
-
-```swift
-import Foundation
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync.ios", category: "PrimarySession")
-
-@MainActor
-final class PrimarySessionManager: ObservableObject {
- @Published var primarySessionId: String?
- @Published var isManuallyLocked: Bool = false
-
- func autoSelect(from sessions: [SessionState]) {
- guard !isManuallyLocked else {
- // If locked session no longer exists, unlock
- if let lockedId = primarySessionId,
- !sessions.contains(where: { $0.sessionId == lockedId }) {
- logger.info("Locked primary session \(lockedId) no longer exists, unlocking")
- isManuallyLocked = false
- // Fall through to auto-select
- } else {
- return
- }
- }
- let best = sessions
- .sorted { autoFillPriority($0) > autoFillPriority($1) }
- .first
- if primarySessionId != best?.sessionId {
- primarySessionId = best?.sessionId
- if let id = primarySessionId {
- logger.info("Auto-selected primary: \(id)")
- }
- }
- }
-
- func manualLock(_ sessionId: String) {
- primarySessionId = sessionId
- isManuallyLocked = true
- logger.info("Manually locked primary: \(sessionId)")
- Task { await save() }
- }
-
- func unlock() {
- isManuallyLocked = false
- logger.info("Unlocked primary session")
- Task { await save() }
- }
-
- func load() async {
- let result = await CloudKitManager.shared.fetchPrimarySession()
- primarySessionId = result.sessionId
- isManuallyLocked = result.locked
- if let id = result.sessionId {
- logger.info("Loaded primary: \(id), locked: \(result.locked)")
- }
- }
-
- func save() async {
- if let id = primarySessionId {
- await CloudKitManager.shared.setPrimarySession(id, locked: isManuallyLocked)
- } else {
- await CloudKitManager.shared.clearPrimarySession()
- }
- }
-
- private func autoFillPriority(_ s: SessionState) -> Int {
- switch s.status {
- case .working: 5
- case .needsInput: 4
- case .compacting: 3
- case .idle, .error: 2
- case .completed: 0
- }
- }
-}
-```
-
-- [ ] **Step 2: Build to verify**
-
-Run: `xcodebuild -scheme Codync-iOS -destination 'generic/platform=iOS' build 2>&1 | tail -5`
-
-Expected: `BUILD SUCCEEDED`
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add Codync-iOS/Services/PrimarySessionManager.swift
-git commit -m "feat: add PrimarySessionManager with auto-select and manual lock"
-```
-
----
-
-## Task 4: Tab Architecture — TabRootView & ComingSoonView
-
-**Files:**
-- Create: `Codync-iOS/Views/TabRootView.swift`
-- Create: `Codync-iOS/Views/ComingSoonView.swift`
-- Modify: `Codync-iOS/Views/IOSRootView.swift`
-
-- [ ] **Step 1: Create ComingSoonView**
-
-Create `Codync-iOS/Views/ComingSoonView.swift`:
-
-```swift
-import SwiftUI
-
-struct ComingSoonView: View {
- let icon: String
- let isSystemImage: Bool
- let title: String
- let description: String
- @Environment(\.theme) private var theme
-
- var body: some View {
- VStack(spacing: 16) {
- if isSystemImage {
- Image(systemName: icon)
- .font(.system(size: 48))
- .foregroundStyle(theme.tertiaryText)
- } else {
- Image(icon)
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 48, height: 48)
- .foregroundStyle(theme.tertiaryText)
- }
- Text(title)
- .font(.title2.bold())
- .foregroundStyle(theme.primaryText)
- Text(description)
- .font(.subheadline)
- .foregroundStyle(theme.secondaryText)
- .multilineTextAlignment(.center)
- .padding(.horizontal, 40)
- Text("Coming Soon")
- .font(.caption.bold())
- .foregroundStyle(theme.tertiaryText)
- .padding(.horizontal, 12)
- .padding(.vertical, 6)
- .background(theme.tertiaryText.opacity(0.1), in: Capsule())
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(theme.background)
- }
-}
-```
-
-- [ ] **Step 2: Create TabRootView**
-
-Create `Codync-iOS/Views/TabRootView.swift`:
-
-```swift
-import SwiftUI
-import CodyncShared
-
-enum AppTab: String, CaseIterable {
- case claudeCode
- case cowork
- case codex
-}
-
-struct TabRootView: View {
- let sessions: [SessionState]
- @ObservedObject var liveActivityManager: LiveActivityManager
- @ObservedObject var primarySessionManager: PrimarySessionManager
- @AppStorage("codync_selectedTab") private var selectedTab: String = AppTab.claudeCode.rawValue
-
- var body: some View {
- TabView(selection: $selectedTab) {
- Tab("Claude Code", image: "ClaudeIcon", value: AppTab.claudeCode.rawValue) {
- NavigationStack {
- IOSSessionListView(
- sessions: sessions,
- liveActivityManager: liveActivityManager
- )
- }
- }
-
- Tab("Cowork", systemImage: "person.2.fill", value: AppTab.cowork.rawValue) {
- ComingSoonView(
- icon: "person.2.fill",
- isSystemImage: true,
- title: "Cowork",
- description: "Monitor Claude Cowork sessions in real time"
- )
- }
-
- Tab("Codex", image: "CodexIcon", value: AppTab.codex.rawValue) {
- ComingSoonView(
- icon: "CodexColorIcon",
- isSystemImage: false,
- title: "Codex",
- description: "Track OpenAI Codex jobs and costs"
- )
- }
- }
- }
-}
-```
-
-- [ ] **Step 3: Modify IOSRootView to use TabRootView**
-
-In `Codync-iOS/Views/IOSRootView.swift`, the view currently wraps everything in a `NavigationStack` and shows `IOSSessionListView` directly. Replace it so the `NavigationStack` is inside each tab, and use `TabRootView` post-onboarding.
-
-Replace the entire content of `IOSRootView.swift` with:
-
-```swift
-import SwiftUI
-import CodyncShared
-
-struct IOSRootView: View {
- @ObservedObject var receiver: CloudKitReceiver
- @ObservedObject var liveActivityManager: LiveActivityManager
- @ObservedObject var primarySessionManager: PrimarySessionManager
- @AppStorage("codync_onboardingComplete") private var onboardingComplete = false
- @AppStorage("codync_darkMode") private var isDarkMode = true
- @State private var displayedSessions: [SessionState] = []
- @State private var reorderTimer: Timer?
-
- var body: some View {
- Group {
- if !onboardingComplete {
- NavigationStack {
- IOSOnboardingView()
- }
- } else {
- TabRootView(
- sessions: displayedSessions,
- liveActivityManager: liveActivityManager,
- primarySessionManager: primarySessionManager
- )
- }
- }
- .environment(\.theme, CodyncTheme(isDark: isDarkMode))
- .preferredColorScheme(isDarkMode ? .dark : .light)
- .onChange(of: receiver.sessions) { _, sessions in
- if !sessions.isEmpty {
- onboardingComplete = true
- }
- liveActivityManager.updateSessions(sessions)
- primarySessionManager.autoSelect(from: sessions)
- }
- .task {
- displayedSessions = sortSessions(receiver.sessions)
- reorderTimer?.invalidate()
- reorderTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
- Task { @MainActor in
- let sorted = sortSessions(receiver.sessions)
- withAnimation(.spring(duration: 2.0, bounce: 0.1)) {
- displayedSessions = sorted
- }
- }
- }
- }
- .onDisappear {
- reorderTimer?.invalidate()
- reorderTimer = nil
- }
- }
-
- private func sortSessions(_ sessions: [SessionState]) -> [SessionState] {
- sessions.sorted { a, b in
- let aWeight = a.status == .working ? 0 : a.status == .needsInput ? 1 : 2
- let bWeight = b.status == .working ? 0 : b.status == .needsInput ? 1 : 2
- if aWeight != bWeight { return aWeight < bWeight }
- return a.updatedAt > b.updatedAt
- }
- }
-}
-```
-
-Key changes:
-- Accepts `primarySessionManager` parameter
-- Removed outer `NavigationStack` (each tab has its own)
-- Onboarding view gets its own `NavigationStack`
-- Added `primarySessionManager.autoSelect(from:)` in `onChange`
-- Passes `primarySessionManager` to `TabRootView`
-
-- [ ] **Step 4: Build to verify**
-
-Run: `xcodebuild -scheme Codync-iOS -destination 'generic/platform=iOS' build 2>&1 | tail -5`
-
-This will fail because `CodyncIOSApp` and `AppDelegate` don't pass `primarySessionManager` yet. That's expected — Task 5 fixes this.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add Codync-iOS/Views/TabRootView.swift \
- Codync-iOS/Views/ComingSoonView.swift \
- Codync-iOS/Views/IOSRootView.swift
-git commit -m "feat: add TabRootView with Claude Code, Cowork, Codex tabs"
-```
-
----
-
-## Task 5: AppDelegate Consolidation
-
-**Files:**
-- Modify: `Codync-iOS/App/AppDelegate.swift`
-- Modify: `Codync-iOS/App/CodyncIOSApp.swift`
-
-Move all initialization from SwiftUI `.task` blocks into AppDelegate, add `primarySessionManager`.
-
-- [ ] **Step 1: Update AppDelegate**
-
-Replace `Codync-iOS/App/AppDelegate.swift` with:
-
-```swift
-import UIKit
-import CloudKit
-import CodyncShared
-import os
-
-private let logger = Logger(subsystem: "com.pokai.Codync.ios", category: "AppDelegate")
-
-final class AppDelegate: NSObject, UIApplicationDelegate {
- let receiver = CloudKitReceiver()
- let liveActivityManager = LiveActivityManager()
- let primarySessionManager = PrimarySessionManager()
-
- func application(
- _ application: UIApplication,
- didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
- ) -> Bool {
- application.registerForRemoteNotifications()
- Task {
- async let startReceiver: () = receiver.start()
- async let loadPins: () = liveActivityManager.loadPinnedSessions()
- async let loadPrimary: () = primarySessionManager.load()
- _ = await (startReceiver, loadPins, loadPrimary)
-
- liveActivityManager.updateSessions(receiver.sessions)
- primarySessionManager.autoSelect(from: receiver.sessions)
-
- let center = UNUserNotificationCenter.current()
- try? await center.requestAuthorization(options: [.alert, .sound, .badge])
- }
- return true
- }
-
- func application(
- _ application: UIApplication,
- didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
- ) {
- let hex = deviceToken.prefix(4).map { String(format: "%02x", $0) }.joined()
- logger.info("APNs device token registered: \(hex)...")
- }
-
- func application(
- _ application: UIApplication,
- didFailToRegisterForRemoteNotificationsWithError error: Error
- ) {
- logger.error("APNs registration failed: \(error.localizedDescription)")
- }
-
- func application(
- _ application: UIApplication,
- didReceiveRemoteNotification userInfo: [AnyHashable: Any]
- ) async -> UIBackgroundFetchResult {
- let notification = CKNotification(fromRemoteNotificationDictionary: userInfo)
- let subID = notification?.subscriptionID
- guard subID == "session-zone-changes" || subID == "session-changes" else {
- return .noData
- }
- let fmt = DateFormatter()
- fmt.dateFormat = "HH:mm:ss"
- let ts = fmt.string(from: Date())
- logger.info("[\(ts)] CloudKit push received")
- await receiver.fetch(source: "silent-push")
- let statuses = receiver.sessions.map { "\($0.projectName):\($0.status.rawValue)" }.joined(separator: ", ")
- logger.info("[\(ts)] → \(statuses)")
- liveActivityManager.updateSessions(receiver.sessions)
- primarySessionManager.autoSelect(from: receiver.sessions)
- return .newData
- }
-}
-```
-
-Changes from current:
-- Added `primarySessionManager` property
-- `didFinishLaunchingWithOptions` now runs parallel init: `receiver.start()`, `loadPinnedSessions()`, `primarySessionManager.load()`
-- After init, calls `updateSessions` and `autoSelect`
-- Requests notification auth
-- `didReceiveRemoteNotification` also calls `primarySessionManager.autoSelect`
-- Added `import UserNotifications` (implicit via UIKit, but explicit is cleaner — actually UIKit already provides it)
-
-- [ ] **Step 2: Update CodyncIOSApp**
-
-Replace `Codync-iOS/App/CodyncIOSApp.swift` with:
-
-```swift
-import SwiftUI
-import CodyncShared
-
-@main
-struct CodyncIOSApp: App {
- @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
- @Environment(\.scenePhase) private var scenePhase
-
- var body: some Scene {
- WindowGroup {
- IOSRootView(
- receiver: appDelegate.receiver,
- liveActivityManager: appDelegate.liveActivityManager,
- primarySessionManager: appDelegate.primarySessionManager
- )
- }
- .onChange(of: scenePhase) { _, phase in
- if phase == .active {
- Task {
- await appDelegate.receiver.fetch(source: "foreground-return")
- appDelegate.liveActivityManager.updateSessions(appDelegate.receiver.sessions)
- appDelegate.primarySessionManager.autoSelect(from: appDelegate.receiver.sessions)
- }
- }
- }
- }
-}
-```
-
-All three `.task` blocks removed — init is now in AppDelegate. The `scenePhase` foreground-return handler is preserved and extended with `primarySessionManager.autoSelect`.
-
-- [ ] **Step 3: Build to verify**
-
-Run: `xcodebuild -scheme Codync-iOS -destination 'generic/platform=iOS' build 2>&1 | tail -5`
-
-Expected: `BUILD SUCCEEDED`
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add Codync-iOS/App/AppDelegate.swift \
- Codync-iOS/App/CodyncIOSApp.swift
-git commit -m "refactor: consolidate init into AppDelegate, add PrimarySessionManager"
-```
-
----
-
-## Task 6: LiveActivityManager — Dual Mode Support
-
-**Files:**
-- Modify: `Codync-iOS/Services/LiveActivityManager.swift`
-
-Extend the existing manager to support Overall mode alongside the existing Individual mode.
-
-- [ ] **Step 1: Add mode property and Overall activity tracking**
-
-At the top of `LiveActivityManager` class, after existing property declarations, add:
-
-```swift
-@Published var mode: LiveActivityMode = .overall
-@Published var maxOverallSessions: Int = 4
-private var overallActivity: Activity<OverallAttributes>?
-private var lastOverallState: OverallAttributes.ContentState?
-private var overallTrackedIds: Set<String> = [] // tracks sessions seen in Overall mode for completion notifications
-```
-
-- [ ] **Step 2: Add loadPreference method**
-
-Add after `loadPinnedSessions()`:
-
-```swift
-func loadPreference() async {
- let pref = await CloudKitManager.shared.fetchLiveActivityPreference()
- mode = pref.mode
- maxOverallSessions = pref.maxSessions
-}
-
-func savePreference() async {
- await CloudKitManager.shared.setLiveActivityPreference(mode: mode, maxSessions: maxOverallSessions)
-}
-```
-
-- [ ] **Step 3: Modify updateSessions to route by mode**
-
-Rename the existing `updateSessions` body into `updateIndividual`, then create a new `updateSessions` that routes:
-
-```swift
-func updateSessions(_ sessions: [SessionState]) {
- let statuses = sessions.map { "\($0.projectName):\($0.status.rawValue)" }.joined(separator: ", ")
- logger.debug("updateSessions (\(self.mode.rawValue)): \(statuses)")
- sessionsByID = Dictionary(sessions.map { ($0.sessionId, $0) }, uniquingKeysWith: { _, last in last })
-
- switch mode {
- case .individual: updateIndividual(sessions)
- case .overall: updateOverall(sessions)
- }
-}
-```
-
-Move the existing `updateSessions` logic (cleanup, grace timers, desired set, start/stop tracking) into a new `private func updateIndividual(_ sessions: [SessionState])`.
-
-- [ ] **Step 4: Implement updateOverall**
-
-Add the Overall mode logic:
-
-```swift
-private func updateOverall(_ sessions: [SessionState]) {
- let active = sessions
- .filter { $0.status != .completed }
- .sorted { autoFillPriority($0) < autoFillPriority($1) }
- .prefix(maxOverallSessions)
-
- let summaries = active.map { session in
- SessionSummary(
- sessionId: session.sessionId,
- projectName: session.projectName,
- status: session.status,
- model: session.model,
- currentTask: session.currentTask,
- costUSD: session.costUSD
- )
- }
-
- let totalCost = sessions.reduce(0) { $0 + $1.costUSD }
-
- // Find primary (from PrimarySessionManager, passed via caller)
- // For now, use first working session as primary
- let primaryId = active.first { $0.status == .working }?.sessionId
- ?? active.first?.sessionId
-
- let state = OverallAttributes.ContentState(
- sessions: summaries,
- primarySessionId: primaryId,
- totalCost: totalCost
- )
-
- guard state != lastOverallState else { return }
- lastOverallState = state
-
- if overallActivity == nil {
- guard UIApplication.shared.applicationState == .active else { return }
- do {
- overallActivity = try Activity.request(
- attributes: OverallAttributes(),
- content: .init(state: state, staleDate: nil)
- )
- logger.info("Started Overall Live Activity with \(summaries.count) sessions")
- } catch {
- logger.error("Failed to start Overall Live Activity: \(error)")
- }
- } else {
- Task {
- await overallActivity?.update(.init(state: state, staleDate: nil, relevanceScore: 100))
- }
- }
-
- // Track sessions seen in Overall mode
- for session in active {
- overallTrackedIds.insert(session.sessionId)
- }
-
- // Send completion notifications for newly completed sessions
- for session in sessions where session.status == .completed {
- if overallTrackedIds.contains(session.sessionId) {
- sendCompletionNotification(session)
- overallTrackedIds.remove(session.sessionId)
- }
- }
-}
-```
-
-- [ ] **Step 5: Add switchMode method**
-
-```swift
-func switchMode(to newMode: LiveActivityMode) {
- guard newMode != mode else { return }
- logger.info("Switching Live Activity mode: \(self.mode.rawValue) → \(newMode.rawValue)")
-
- // End all current activities
- if mode == .individual {
- for sessionId in Array(trackedSessionIds) {
- stopTracking(sessionId: sessionId)
- }
- } else {
- if let activity = overallActivity {
- Task { await activity.end(nil, dismissalPolicy: .immediate) }
- overallActivity = nil
- lastOverallState = nil
- }
- }
-
- // Reset transient state
- previousTasks.removeAll()
- secondPreviousTasks.removeAll()
- graceTimers.removeAll()
- lastPushedState.removeAll()
- overallTrackedIds.removeAll()
-
- mode = newMode
- Task { await savePreference() }
-
- // Recreate with current data
- updateSessions(Array(sessionsByID.values))
-}
-```
-
-- [ ] **Step 6: Update AppDelegate to load preference**
-
-In `Codync-iOS/App/AppDelegate.swift`, add `loadPreference` to the parallel init:
-
-```swift
-async let startReceiver: () = receiver.start()
-async let loadPins: () = liveActivityManager.loadPinnedSessions()
-async let loadPrimary: () = primarySessionManager.load()
-async let loadPref: () = liveActivityManager.loadPreference()
-_ = await (startReceiver, loadPins, loadPrimary, loadPref)
-```
-
-- [ ] **Step 7: Build to verify**
-
-Run: `xcodebuild -scheme Codync-iOS -destination 'generic/platform=iOS' build 2>&1 | tail -5`
-
-Expected: `BUILD SUCCEEDED`
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add Codync-iOS/Services/LiveActivityManager.swift \
- Codync-iOS/App/AppDelegate.swift
-git commit -m "feat: add dual mode support to LiveActivityManager (Overall + Individual)"
-```
-
----
-
-## Task 7: Mode Switcher UI in SessionListView
-
-**Files:**
-- Modify: `Codync-iOS/Views/IOSSessionListView.swift`
-
-Add a Segmented Control at the top of the session list for switching between Overall and Individual modes, plus primary session selection controls in Overall mode.
-
-- [ ] **Step 1: Add mode switcher and primary controls**
-
-Modify `IOSSessionListView` to accept additional dependencies and add the mode/primary UI:
-
-```swift
-struct IOSSessionListView: View {
- let sessions: [SessionState]
- @ObservedObject var liveActivityManager: LiveActivityManager
- @ObservedObject var primarySessionManager: PrimarySessionManager
- @Environment(\.theme) private var theme
-
- var body: some View {
- ScrollView {
- LazyVStack(spacing: 1) {
- // Mode switcher
- modeSection
-
- // Primary session controls (Overall mode only)
- if liveActivityManager.mode == .overall {
- primarySection
- }
-
- // Session list
- ForEach(sessions) { session in
- NavigationLink(destination: IOSSessionDetailView(session: session)) {
- SessionRowContent(
- session: session,
- isTracking: liveActivityManager.isTracking(sessionId: session.sessionId),
- isPinned: liveActivityManager.isPinned(sessionId: session.sessionId),
- isPrimary: primarySessionManager.primarySessionId == session.sessionId,
- showPrimary: liveActivityManager.mode == .overall,
- onTogglePin: { liveActivityManager.togglePin(session.sessionId) },
- onSetPrimary: { primarySessionManager.manualLock(session.sessionId) }
- )
- }
- .buttonStyle(.plain)
- .tint(theme.primaryText)
- }
- }
- }
- .background(theme.background)
- .navigationBarTitleDisplayMode(.inline)
- .toolbar {
- ToolbarItem(placement: .principal) {
- Image("CodyncIcon")
- .resizable()
- .aspectRatio(contentMode: .fit)
- .frame(width: 22, height: 22)
- .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous))
- }
- }
- .toolbarColorScheme(.dark, for: .navigationBar)
- }
-
- @ViewBuilder
- private var modeSection: some View {
- Picker("Live Activity Mode", selection: Binding(
- get: { liveActivityManager.mode },
- set: { liveActivityManager.switchMode(to: $0) }
- )) {
- Text("Overall").tag(LiveActivityMode.overall)
- Text("Individual").tag(LiveActivityMode.individual)
- }
- .pickerStyle(.segmented)
- .padding(.horizontal, 16)
- .padding(.vertical, 8)
- }
-
- @ViewBuilder
- private var primarySection: some View {
- VStack(alignment: .leading, spacing: 8) {
- // Max sessions picker
- HStack {
- Text("Max Sessions")
- .font(.caption.bold())
- .foregroundStyle(theme.secondaryText)
- Spacer()
- Picker("Max", selection: Binding(
- get: { liveActivityManager.maxOverallSessions },
- set: { newVal in
- liveActivityManager.maxOverallSessions = newVal
- Task { await liveActivityManager.savePreference() }
- }
- )) {
- ForEach(1...4, id: \.self) { n in
- Text("\(n)").tag(n)
- }
- }
- .pickerStyle(.segmented)
- .frame(width: 160)
- }
-
- // Primary session
- HStack {
- Text("Primary Session")
- .font(.caption.bold())
- .foregroundStyle(theme.secondaryText)
- Spacer()
- if primarySessionManager.isManuallyLocked {
- Button("Unlock") {
- primarySessionManager.unlock()
- primarySessionManager.autoSelect(from: sessions)
- }
- .font(.caption)
- }
- }
- if let primaryId = primarySessionManager.primarySessionId,
- let session = sessions.first(where: { $0.sessionId == primaryId }) {
- HStack(spacing: 6) {
- Image(systemName: "star.fill")
- .font(.system(size: 10))
- .foregroundStyle(.yellow)
- Text(session.projectName)
- .font(.subheadline.bold())
- .foregroundStyle(theme.primaryText)
- if primarySessionManager.isManuallyLocked {
- Image(systemName: "lock.fill")
- .font(.system(size: 9))
- .foregroundStyle(theme.tertiaryText)
- }
- }
- } else {
- Text("No active session")
- .font(.subheadline)
- .foregroundStyle(theme.tertiaryText)
- }
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 8)
- }
-}
-```
-
-- [ ] **Step 2: Update SessionRowContent for primary indicator**
-
-Add `isPrimary`, `showPrimary`, and `onSetPrimary` parameters to `SessionRowContent`:
-
-```swift
-private struct SessionRowContent: View {
- let session: SessionState
- let isTracking: Bool
- let isPinned: Bool
- let isPrimary: Bool
- let showPrimary: Bool
- let onTogglePin: () -> Void
- let onSetPrimary: () -> Void
- @Environment(\.theme) private var theme
-
- var body: some View {
- HStack(spacing: 10) {
- SessionStatusView(
- status: session.status,
- completedTasks: session.completedTaskCount,
- totalTasks: session.totalTaskCount,
- waitingReason: session.waitingReason
- )
-
- VStack(alignment: .leading, spacing: 3) {
- HStack(spacing: 5) {
- if showPrimary && isPrimary {
- Image(systemName: "star.fill")
- .font(.system(size: 9))
- .foregroundStyle(.yellow)
- }
- Text(session.projectName)
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(theme.primaryText)
- .lineLimit(1)
- if !session.model.isEmpty {
- SessionTagView(tag: session.model)
- }
- Spacer(minLength: 4)
- }
- if session.statusDescription != nil || !session.tasks.isEmpty {
- HStack(spacing: 4) {
- if let desc = session.statusDescription {
- Text(desc)
- .font(.system(size: 13))
- .foregroundStyle(subtitleColor)
- .lineLimit(1)
- }
- Spacer()
- Text(relativeTime(session.updatedAt))
- .font(.system(size: 12, design: .monospaced))
- .foregroundStyle(theme.tertiaryText)
- }
- }
- if !session.tasks.isEmpty {
- MiniProgressBar(tasks: session.tasks)
- }
- }
-
- if showPrimary {
- Button(action: onSetPrimary) {
- Image(systemName: isPrimary ? "star.fill" : "star")
- .font(.system(size: 13))
- .foregroundStyle(isPrimary ? .yellow : theme.tertiaryText)
- .frame(width: 28, height: 28)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- } else {
- Button(action: onTogglePin) {
- Image(systemName: isPinned ? "pin.fill" : "pin")
- .font(.system(size: 13))
- .foregroundStyle(isPinned ? theme.primaryText : theme.tertiaryText)
- .frame(width: 28, height: 28)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- }
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 8)
- }
-
- // ... subtitleColor and relativeTime unchanged
-```
-
-- [ ] **Step 3: Update TabRootView to pass primarySessionManager**
-
-In `TabRootView.swift`, update the Claude Code tab to pass `primarySessionManager`:
-
-```swift
-Tab("Claude Code", image: "ClaudeIcon", value: AppTab.claudeCode.rawValue) {
- NavigationStack {
- IOSSessionListView(
- sessions: sessions,
- liveActivityManager: liveActivityManager,
- primarySessionManager: primarySessionManager
- )
- }
-}
-```
-
-- [ ] **Step 4: Build to verify**
-
-Run: `xcodebuild -scheme Codync-iOS -destination 'generic/platform=iOS' build 2>&1 | tail -5`
-
-Expected: `BUILD SUCCEEDED`
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add Codync-iOS/Views/IOSSessionListView.swift \
- Codync-iOS/Views/TabRootView.swift
-git commit -m "feat: add mode switcher and primary session UI to session list"
-```
-
----
-
-## Task 8: Overall Live Activity Widget Layout
-
-**Files:**
-- Modify: `CodyncLiveActivity/CodyncLiveActivityWidget.swift`
-
-Add a new widget configuration for `OverallAttributes` that adapts its layout based on session count.
-
-- [ ] **Step 1: Create OverallLiveActivityWidget**
-
-Add a new widget struct at the bottom of `CodyncLiveActivityWidget.swift` (before the closing of the file):
-
-```swift
-// MARK: - Overall Live Activity Widget
-
-struct OverallLiveActivityWidget: Widget {
- let kind: String = "CodyncOverallLiveActivity"
-
- var body: some WidgetConfiguration {
- ActivityConfiguration(for: OverallAttributes.self) { context in
- overallLockScreen(context: context)
- } dynamicIsland: { context in
- // Dynamic Island shows primary session only
- let primary = context.state.sessions.first { $0.sessionId == context.state.primarySessionId }
- ?? context.state.sessions.first
- DynamicIsland {
- DynamicIslandExpandedRegion(.leading) {
- if let p = primary, p.status == .working {
- Circle().fill(.white).frame(width: 8, height: 8)
- } else {
- Circle().fill(.white.opacity(0.5)).frame(width: 8, height: 8)
- }
- }
- DynamicIslandExpandedRegion(.center) {
- VStack(alignment: .leading, spacing: 4) {
- Text(primary?.projectName ?? "Codync")
- .font(.headline)
- Text(primary?.currentTask ?? statusLabel(primary?.status.rawValue ?? "idle"))
- .font(.subheadline)
- .foregroundStyle(.secondary)
- .lineLimit(1)
- }
- }
- DynamicIslandExpandedRegion(.trailing) {
- Text(String(format: "$%.2f", context.state.totalCost))
- .font(.caption2.bold())
- .foregroundStyle(.secondary)
- }
- DynamicIslandExpandedRegion(.bottom) {
- HStack(spacing: 4) {
- ForEach(context.state.sessions, id: \.sessionId) { s in
- HStack(spacing: 3) {
- Circle()
- .fill(s.sessionId == context.state.primarySessionId ? .white : .white.opacity(0.5))
- .frame(width: 5, height: 5)
- Text(s.projectName)
- .font(.caption2)
- .lineLimit(1)
- }
- }
- }
- }
- } compactLeading: {
- Circle().fill(.white).frame(width: 6, height: 6)
- } compactTrailing: {
- Text("\(context.state.sessions.count)")
- .font(.caption2.bold())
- } minimal: {
- Circle().fill(.white).frame(width: 6, height: 6)
- }
- }
- }
-
- @ViewBuilder
- private func overallLockScreen(context: ActivityViewContext<OverallAttributes>) -> some View {
- let sessions = context.state.sessions
- let primaryId = context.state.primarySessionId
-
- VStack(alignment: .leading, spacing: 0) {
- // Header
- HStack {
- HStack(spacing: 6) {
- Image(systemName: "chevron.left.forwardslash.chevron.right")
- .font(.system(size: 10, weight: .bold))
- .foregroundStyle(widgetFg.opacity(0.6))
- .frame(width: 21, height: 21)
- .background(widgetFg.opacity(0.08), in: Circle())
- Text("Codync")
- .font(.callout.bold())
- .opacity(0.72)
- }
- Spacer()
- Text(String(format: "$%.2f", context.state.totalCost))
- .font(.subheadline)
- .monospacedDigit()
- .opacity(0.5)
- }
- .foregroundStyle(widgetFg)
- .padding(.horizontal, 6)
- .frame(height: 28)
-
- // Session rows — layout adapts by count
- VStack(spacing: 2) {
- ForEach(sessions, id: \.sessionId) { session in
- let isPrimary = session.sessionId == primaryId
- if sessions.count <= 3 {
- mediumRow(session: session, isPrimary: isPrimary)
- } else {
- compactRow(session: session, isPrimary: isPrimary)
- }
- }
- }
- .frame(maxHeight: .infinity)
- }
- .padding(.horizontal, 8)
- .padding(.vertical, 10)
- .frame(height: 160)
- .background(Color.white.opacity(0.75))
- .activityBackgroundTint(.clear)
- }
-
- @ViewBuilder
- private func mediumRow(session: SessionSummary, isPrimary: Bool) -> some View {
- HStack(spacing: 8) {
- Circle()
- .fill(isPrimary ? widgetFg : widgetFg.opacity(0.4))
- .frame(width: 6, height: 6)
- Text(session.projectName)
- .font(.subheadline.bold())
- .foregroundStyle(widgetFg)
- .lineLimit(1)
- Text(session.model)
- .font(.caption2)
- .foregroundStyle(widgetFg.opacity(0.4))
- Spacer()
- if let task = session.currentTask, !task.isEmpty {
- Text(task)
- .font(.caption2)
- .foregroundStyle(widgetFg.opacity(0.6))
- .lineLimit(1)
- .frame(maxWidth: 120, alignment: .trailing)
- } else {
- Text(statusLabel(session.status.rawValue))
- .font(.caption2)
- .foregroundStyle(widgetFg.opacity(0.4))
- }
- }
- .padding(.horizontal, 6)
- .padding(.vertical, 6)
- }
-
- @ViewBuilder
- private func compactRow(session: SessionSummary, isPrimary: Bool) -> some View {
- HStack(spacing: 8) {
- Circle()
- .fill(isPrimary ? widgetFg : widgetFg.opacity(0.4))
- .frame(width: 5, height: 5)
- Text(session.projectName)
- .font(.caption.bold())
- .foregroundStyle(widgetFg)
- .lineLimit(1)
- Spacer()
- Text(statusLabel(session.status.rawValue))
- .font(.caption2)
- .foregroundStyle(widgetFg.opacity(0.4))
- }
- .padding(.horizontal, 6)
- .padding(.vertical, 4)
- }
-
- private func statusLabel(_ status: String) -> String {
- switch status {
- case "working": "Working"
- case "idle": "Idle"
- case "needsInput": "Needs Input"
- case "compacting": "Compacting"
- case "error": "Error"
- case "completed": "Complete"
- default: "Working"
- }
- }
-}
-```
-
-- [ ] **Step 2: Register the new widget in the widget bundle**
-
-Edit `CodyncLiveActivity/CodyncLiveActivityBundle.swift` — add `OverallLiveActivityWidget()` to the existing bundle:
-
-```swift
-import WidgetKit
-import SwiftUI
-
-@main
-struct CodyncLiveActivityBundle: WidgetBundle {
- var body: some Widget {
- CodyncLiveActivityWidget()
- OverallLiveActivityWidget()
- }
-}
-```
-
-- [ ] **Step 3: Build to verify**
-
-Run: `xcodebuild -scheme CodyncLiveActivity -destination 'generic/platform=iOS' build 2>&1 | tail -5`
-
-Expected: `BUILD SUCCEEDED`
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add CodyncLiveActivity/
-git commit -m "feat: add Overall mode Live Activity widget layout"
-```
-
----
-
-## Task 9: Integration Verification
-
-- [ ] **Step 1: Full project build**
-
-Run: `xcodebuild -scheme Codync-iOS -destination 'generic/platform=iOS' build 2>&1 | tail -10`
-
-Expected: `BUILD SUCCEEDED` with no warnings related to our changes.
-
-- [ ] **Step 2: Verify all targets compile**
-
-```bash
-xcodebuild -scheme CodyncShared -destination 'generic/platform=iOS' build 2>&1 | tail -3
-xcodebuild -scheme Codync-macOS -destination 'generic/platform=macOS' build 2>&1 | tail -3
-```
-
-Expected: Both `BUILD SUCCEEDED`. The macOS target should compile with the `#else` stubs for `OverallAttributes`.
-
-- [ ] **Step 3: Final commit if any fixups needed**
-
-```bash
-git add -A
-git commit -m "fix: resolve any compilation issues from integration"
-```
-
-Only create this commit if there were actual fixes needed.
diff --git a/docs/superpowers/specs/2026-03-21-ios-ui-architecture-redesign.md b/docs/superpowers/specs/2026-03-21-ios-ui-architecture-redesign.md
deleted file mode 100644
index 179e8fcd..00000000
--- a/docs/superpowers/specs/2026-03-21-ios-ui-architecture-redesign.md
+++ /dev/null
@@ -1,351 +0,0 @@
-# iOS UI Architecture Redesign — Design Spec
-
-**Date:** 2026-03-21
-**Status:** Approved
-**Approach:** Incremental refactor (方案 A)
-
-## Overview
-
-Restructure the Codync iOS app from a flat `NavigationStack` into a tabbed architecture with dual Live Activity modes (Overall / Individual) and a Primary Session concept.
-
-## Confirmed Requirements
-
-- Bottom `TabView` with three tabs: Claude Code, Cowork (Coming Soon), Codex (Coming Soon)
-- Live Activity dual mode: Overall (unified) + Individual (per-session), top Segmented Control to switch
-- Overall mode shows max 4 sessions
-- Primary Session: hybrid mode — auto-select most active, user can manually lock
-- Primary shown on Dynamic Island and Apple Watch (future)
-- AppDelegate consolidates all initialization (CloudKit fetch, pins, preferences, notification auth)
-- Icons from lobehub/lobe-icons (MIT License), stored in Asset Catalog as SVG
-
-## Section 1: Tab Architecture
-
-### View Hierarchy
-
-```
-CodyncIOSApp
-└── IOSRootView (retains onboarding gate)
- ├── IOSOnboardingView (first launch)
- └── TabRootView (post-onboarding)
- ├── Tab 1: Claude Code (image: "ClaudeIcon")
- │ └── NavigationStack
- │ ├── IOSSessionListView (reused)
- │ └── IOSSessionDetailView (reused)
- ├── Tab 2: Cowork (systemImage: "person.2.fill") — Coming Soon
- │ └── ComingSoonView
- └── Tab 3: Codex (image: "CodexIcon") — Coming Soon
- └── ComingSoonView
-```
-
-### New Files
-
-- `Codync-iOS/Views/TabRootView.swift` — `TabView` container with `@AppStorage("selectedTab")` persistence
-- `Codync-iOS/Views/ComingSoonView.swift` — Generic placeholder (icon + title + description)
-
-### Key Decisions
-
-- Each tab has its own `NavigationStack` — independent navigation stacks
-- Tab selection persisted via `@AppStorage` — restores last tab on relaunch
-- iOS 26 automatically applies liquid glass tab bar effect — no custom styling needed
-- `IOSRootView` retains onboarding gate logic, delegates to `TabRootView` after completion
-
-### Tab Enum
-
-```swift
-enum AppTab: String, CaseIterable {
- case claudeCode
- case cowork
- case codex
-}
-```
-
-## Section 2: Live Activity Dual Mode
-
-### Mode Switcher UI
-
-Top of Sessions tab (`IOSSessionListView`):
-
-```
-┌──────────────────────────────────┐
-│ [Overall] [Individual] │ ← Picker, SegmentedPickerStyle
-├──────────────────────────────────┤
-│ (Overall mode extra controls) │
-│ Primary: ByCrawl ★ │
-│ Max sessions: [1][2][3][4] │
-├──────────────────────────────────┤
-│ Session list... │
-└──────────────────────────────────┘
-```
-
-- `Picker` with `.segmentedPickerStyle()` in a `Section` header or toolbar area
-- Overall-only controls (primary selector, max session count) shown conditionally
-- Mode persisted via CloudKit `LiveActivityPreference` record
-
-### Data Model Changes (CodyncShared)
-
-**New: `OverallAttributes`**
-
-```swift
-struct OverallAttributes: ActivityAttributes {
- struct ContentState: Codable, Hashable {
- let sessions: [SessionSummary]
- let primarySessionId: String?
- let totalCost: Double
- }
-}
-```
-
-**New: `SessionSummary`**
-
-```swift
-struct SessionSummary: Codable, Hashable, Sendable {
- let sessionId: String
- let projectName: String
- let status: SessionStatus
- let model: String
- let currentTask: String?
- let costUSD: Double
-}
-```
-
-**New: `LiveActivityMode`**
-
-```swift
-enum LiveActivityMode: String, Codable, Sendable {
- case overall
- case individual
-}
-```
-
-Existing `CodyncAttributes` remains unchanged — used for Individual mode.
-
-### LiveActivityManager Extension
-
-```swift
-@MainActor
-class LiveActivityManager: ObservableObject {
- @Published var mode: LiveActivityMode = .overall
-
- // Existing (Individual mode)
- var activities: [String: Activity<CodyncAttributes>]
- var trackedSessionIds: Set<String>
- var pinnedSessionIds: Set<String>
-
- // New (Overall mode)
- var overallActivity: Activity<OverallAttributes>?
-
- func updateSessions(_ sessions: [SessionState]) {
- switch mode {
- case .overall: updateOverall(sessions)
- case .individual: updateIndividual(sessions) // existing logic
- }
- }
-
- func switchMode(to newMode: LiveActivityMode) {
- // 1. End all current activities (individual or overall)
- // 2. Reset transient state: previousTasks, secondPreviousTasks, grace periods
- // 3. Switch mode
- // 4. Recreate activities in new mode from current session data
- }
-
- func loadPreference() async {
- // Fetch mode + maxSessions from CloudKit
- }
-}
-```
-
-### Overall Mode Layout Adaptation (Live Activity Widget)
-
-| Session Count | Layout | Details |
-|---|---|---|
-| 1 | Full detail | Tool cards + timer + stacking, similar to Individual |
-| 2–3 | Medium rows | Status dot + project + model + currentTask |
-| 4 | Compact rows | Status dot + project name only |
-
-Dynamic Island always shows primary session only.
-
-### PrimarySessionManager (New)
-
-```swift
-@MainActor
-final class PrimarySessionManager: ObservableObject {
- @Published var primarySessionId: String?
- @Published var isManuallyLocked: Bool = false
-
- /// Priority order matches LiveActivityManager.autoFillPriority:
- /// working(5) > needsInput(4) > compacting(3) > idle/error(2) > completed(0)
- func autoSelect(from sessions: [SessionState]) {
- guard !isManuallyLocked else { return }
- primarySessionId = sessions
- .sorted { autoFillPriority($0) > autoFillPriority($1) }
- .first?.sessionId
- }
-
- private func autoFillPriority(_ s: SessionState) -> Int {
- switch s.status {
- case .working: 5
- case .needsInput: 4
- case .compacting: 3
- case .idle, .error: 2
- case .completed: 0
- }
- }
-
- func manualLock(_ sessionId: String) {
- primarySessionId = sessionId
- isManuallyLocked = true
- }
-
- func unlock() {
- isManuallyLocked = false
- // autoSelect will run on next updateSessions
- }
-
- func load() async {
- // Fetch from CloudKit PrimarySession record
- }
-
- func save() async {
- // Persist to CloudKit PrimarySession record
- }
-}
-```
-
-- If manually locked session disappears from CloudKit → auto-unlock and select next
-- CloudKit persistence allows macOS to read the primary session choice
-
-## Section 3: CloudKit Changes
-
-### New Record Types
-
-**PrimarySession** (singleton, fixed `recordName: "primary-session"`):
-
-| Field | Type | Description |
-|---|---|---|
-| sessionId | String | Currently selected primary session |
-| isManuallyLocked | Bool | Whether user manually locked this choice |
-| updatedAt | Date | Last modification time |
-
-**LiveActivityPreference** (singleton, fixed `recordName: "live-activity-pref"`):
-
-| Field | Type | Description |
-|---|---|---|
-| mode | String | "overall" or "individual" |
-| maxSessions | Int | 1–4, used in Overall mode |
-
-### CloudKitManager Additions
-
-```swift
-extension CloudKitManager {
- func fetchPrimarySession() async -> (sessionId: String?, locked: Bool)
- func setPrimarySession(_ sessionId: String, locked: Bool) async
- func clearPrimarySession() async
-
- func fetchLiveActivityPreference() async -> (mode: LiveActivityMode, maxSessions: Int)
- func setLiveActivityPreference(mode: LiveActivityMode, maxSessions: Int) async
-}
-```
-
-Both records use fixed `recordName` values to ensure only one instance exists (upsert semantics).
-
-## Section 4: AppDelegate Consolidation
-
-### Before (scattered initialization)
-
-```swift
-// AppDelegate: only APNs registration
-// CodyncIOSApp .task {}: receiver.start(), loadPinnedSessions(), notification auth
-```
-
-### After (unified initialization)
-
-```swift
-final class AppDelegate: NSObject, UIApplicationDelegate {
- let receiver = CloudKitReceiver()
- let liveActivityManager = LiveActivityManager()
- let primarySessionManager = PrimarySessionManager()
-
- func application(_ application: UIApplication,
- didFinishLaunchingWithOptions ...) -> Bool {
- application.registerForRemoteNotifications()
- Task {
- async let startReceiver: () = receiver.start()
- async let loadPins: () = liveActivityManager.loadPinnedSessions()
- async let loadPrimary: () = primarySessionManager.load()
- async let loadPref: () = liveActivityManager.loadPreference()
- _ = await (startReceiver, loadPins, loadPrimary, loadPref)
-
- liveActivityManager.updateSessions(receiver.sessions)
- primarySessionManager.autoSelect(from: receiver.sessions)
-
- let center = UNUserNotificationCenter.current()
- try? await center.requestAuthorization(options: [.alert, .sound, .badge])
- }
- return true
- }
-
- func application(_ application: UIApplication,
- didReceiveRemoteNotification userInfo: [AnyHashable: Any]
- ) async -> UIBackgroundFetchResult {
- // Existing push handling + primarySessionManager.autoSelect(...)
- }
-}
-```
-
-`CodyncIOSApp` simplified — no `.task` blocks, just passes dependencies to `IOSRootView`.
-
-## File Change Summary
-
-### New Files (6)
-
-| File | Description |
-|---|---|
-| `Codync-iOS/Views/TabRootView.swift` | TabView container |
-| `Codync-iOS/Views/ComingSoonView.swift` | Coming Soon placeholder |
-| `Codync-iOS/Services/PrimarySessionManager.swift` | Primary session logic |
-| `CodyncShared/Sources/Models/OverallAttributes.swift` | Overall Activity data model |
-| `CodyncShared/Sources/Models/SessionSummary.swift` | Session summary model |
-| `CodyncShared/Sources/Models/LiveActivityMode.swift` | Mode enum |
-
-### Modified Files (7)
-
-| File | Changes |
-|---|---|
-| `Codync-iOS/App/AppDelegate.swift` | Consolidate init, add primarySessionManager |
-| `Codync-iOS/App/CodyncIOSApp.swift` | Remove .task blocks, pass new dependencies |
-| `Codync-iOS/Views/IOSRootView.swift` | Show TabRootView post-onboarding |
-| `Codync-iOS/Views/IOSSessionListView.swift` | Mode switcher + primary selection UI |
-| `Codync-iOS/Services/LiveActivityManager.swift` | Dual mode support |
-| `CodyncShared/Sources/CloudKit/CloudKitManager.swift` | Primary + preference methods |
-| `CodyncLiveActivity/CodyncLiveActivityWidget.swift` | Overall mode layout |
-
-### Already Added (Assets)
-
-| Asset | File | Rendering |
-|---|---|---|
-| `ClaudeIcon` | claude.svg | template (follows tint) |
-| `ClaudeColorIcon` | claude-color.svg | original (#D97757) |
-| `CodexIcon` | codex.svg | template (follows tint) |
-| `CodexColorIcon` | codex-color.svg | original (gradient) |
-
-### Unchanged Files
-
-- `IOSSessionDetailView.swift`
-- `IOSStatusIndicator.swift`
-- `IOSTheme.swift`
-- `IOSSessionTagView.swift`
-- `IOSOnboardingView.swift`
-- `CKRecordMapper.swift`
-- `SessionState.swift`, `SessionStatus.swift`, `WaitingReason.swift`, `TaskItem.swift`
-- `CodyncAttributes.swift` (retained for Individual mode)
-
-## Implementation Priority
-
-1. Tab architecture (TabRootView + ComingSoonView + IOSRootView modification)
-2. AppDelegate consolidation (unified init, remove .task blocks)
-3. Data models (OverallAttributes, SessionSummary, LiveActivityMode)
-4. PrimarySessionManager + CloudKit records
-5. LiveActivityManager dual mode
-6. Mode switcher UI in IOSSessionListView
-7. Overall Live Activity widget layout
-8. Primary selection UI (manual lock/unlock)
diff --git a/host/.gitignore b/host/.gitignore
new file mode 100644
index 00000000..2f7896d1
--- /dev/null
+++ b/host/.gitignore
@@ -0,0 +1 @@
+target/
diff --git a/host/Cargo.lock b/host/Cargo.lock
new file mode 100644
index 00000000..ff7c8804
--- /dev/null
+++ b/host/Cargo.lock
@@ -0,0 +1,2252 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "anstream"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+
+[[package]]
+name = "anstyle-parse"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "aws-lc-rs"
+version = "1.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"
+dependencies = [
+ "aws-lc-sys",
+ "zeroize",
+]
+
+[[package]]
+name = "aws-lc-sys"
+version = "0.45.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"
+dependencies = [
+ "cc",
+ "cmake",
+ "dunce",
+ "fs_extra",
+ "pkg-config",
+]
+
+[[package]]
+name = "axum"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
+dependencies = [
+ "axum-core",
+ "bytes",
+ "form_urlencoded",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde_core",
+ "serde_json",
+ "serde_path_to_error",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "axum-core"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+
+[[package]]
+name = "cc"
+version = "1.4.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313"
+dependencies = [
+ "find-msvc-tools",
+ "jobserver",
+ "libc",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "chacha20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "rand_core",
+]
+
+[[package]]
+name = "clap"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
+
+[[package]]
+name = "cmake"
+version = "0.1.58"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "codync-host"
+version = "2.0.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "clap",
+ "dirs",
+ "futures",
+ "gethostname",
+ "if-addrs",
+ "qrcode",
+ "reqwest",
+ "rusqlite",
+ "serde",
+ "serde_json",
+ "tokio",
+ "tokio-stream",
+ "tracing",
+ "tracing-subscriber",
+ "uuid",
+]
+
+[[package]]
+name = "colorchoice"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+
+[[package]]
+name = "combine"
+version = "4.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"
+dependencies = [
+ "bytes",
+ "memchr",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "dirs"
+version = "7.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"
+dependencies = [
+ "dirs-sys",
+]
+
+[[package]]
+name = "dirs-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
+dependencies = [
+ "libc",
+ "option-ext",
+ "redox_users",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "dunce"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "fallible-iterator"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
+
+[[package]]
+name = "fallible-streaming-iterator"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "fs_extra"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
+
+[[package]]
+name = "futures"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "gethostname"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
+dependencies = [
+ "rustix",
+ "windows-link",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "wasi",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "r-efi",
+ "rand_core",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashlink"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
+dependencies = [
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "http"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "hyper"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "http",
+ "http-body",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-rustls"
+version = "0.27.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
+dependencies = [
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
+dependencies = [
+ "base64",
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "httparse",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "tokio",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
+
+[[package]]
+name = "icu_properties"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
+
+[[package]]
+name = "icu_provider"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "if-addrs"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "jni"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
+dependencies = [
+ "cfg-if",
+ "combine",
+ "jni-macros",
+ "jni-sys",
+ "log",
+ "simd_cesu8",
+ "thiserror",
+ "walkdir",
+ "windows-link",
+]
+
+[[package]]
+name = "jni-macros"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "simd_cesu8",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
+dependencies = [
+ "jni-sys-macros",
+]
+
+[[package]]
+name = "jni-sys-macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "jobserver"
+version = "0.1.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
+dependencies = [
+ "getrandom 0.4.3",
+ "libc",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "libredox"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "libsqlite3-sys"
+version = "0.38.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8"
+dependencies = [
+ "cc",
+ "pkg-config",
+ "vcpkg",
+]
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "litemap"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "lru-slab"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
+
+[[package]]
+name = "matchers"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
+dependencies = [
+ "regex-automata",
+]
+
+[[package]]
+name = "matchit"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
+[[package]]
+name = "mio"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "nu-ansi-term"
+version = "0.50.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
+[[package]]
+name = "option-ext"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "potential_utf"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
+dependencies = [
+ "zerovec",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "qrcode"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
+
+[[package]]
+name = "quinn"
+version = "0.11.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc"
+dependencies = [
+ "aws-lc-rs",
+ "bytes",
+ "getrandom 0.4.3",
+ "lru-slab",
+ "rand",
+ "rand_pcg",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.3",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "rand_pcg"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
+dependencies = [
+ "rand_core",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "redox_users"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"
+dependencies = [
+ "libredox",
+ "thiserror",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "reqwest"
+version = "0.13.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"
+dependencies = [
+ "base64",
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-rustls",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "quinn",
+ "rustls",
+ "rustls-pki-types",
+ "rustls-platform-verifier",
+ "serde",
+ "serde_json",
+ "sync_wrapper",
+ "tokio",
+ "tokio-rustls",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "rsqlite-vfs"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c"
+dependencies = [
+ "hashbrown 0.16.1",
+ "thiserror",
+]
+
+[[package]]
+name = "rusqlite"
+version = "0.40.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3"
+dependencies = [
+ "bitflags",
+ "fallible-iterator",
+ "fallible-streaming-iterator",
+ "hashlink",
+ "libsqlite3-sys",
+ "smallvec",
+ "sqlite-wasm-rs",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
+dependencies = [
+ "aws-lc-rs",
+ "once_cell",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "web-time",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-platform-verifier"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"
+dependencies = [
+ "core-foundation",
+ "core-foundation-sys",
+ "jni",
+ "log",
+ "once_cell",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-platform-verifier-android",
+ "rustls-webpki",
+ "security-framework",
+ "security-framework-sys",
+ "webpki-root-certs",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls-platform-verifier-android"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
+dependencies = [
+ "aws-lc-rs",
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "ryu"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags",
+ "core-foundation",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "indexmap",
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_urlencoded"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
+dependencies = [
+ "form_urlencoded",
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "sharded-slab"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
+dependencies = [
+ "lazy_static",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
+[[package]]
+name = "simd_cesu8"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
+dependencies = [
+ "rustc_version",
+ "simdutf8",
+]
+
+[[package]]
+name = "simdutf8"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
+
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "sqlite-wasm-rs"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75"
+dependencies = [
+ "cc",
+ "js-sys",
+ "rsqlite-vfs",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "thread_local"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
+[[package]]
+name = "tokio"
+version = "1.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "parking_lot",
+ "pin-project-lite",
+ "signal-hook-registry",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "tokio-rustls"
+version = "0.26.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67"
+dependencies = [
+ "rustls",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-stream"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+ "tokio",
+ "tokio-util",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
+dependencies = [
+ "bitflags",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "url",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "log",
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+ "valuable",
+]
+
+[[package]]
+name = "tracing-log"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
+dependencies = [
+ "log",
+ "once_cell",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-subscriber"
+version = "0.3.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
+dependencies = [
+ "matchers",
+ "nu-ansi-term",
+ "once_cell",
+ "regex-automata",
+ "sharded-slab",
+ "smallvec",
+ "thread_local",
+ "tracing",
+ "tracing-core",
+ "tracing-log",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
+
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "uuid"
+version = "1.26.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
+dependencies = [
+ "getrandom 0.4.3",
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "valuable"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+
+[[package]]
+name = "vcpkg"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.128"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.78"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.128"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.128"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.128"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "webpki-root-certs"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
+dependencies = [
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "writeable"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+
+[[package]]
+name = "zerotrie"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/host/Cargo.toml b/host/Cargo.toml
new file mode 100644
index 00000000..9b545fff
--- /dev/null
+++ b/host/Cargo.toml
@@ -0,0 +1,23 @@
+[package]
+name = "codync-host"
+version = "2.0.0"
+edition = "2024"
+
+[dependencies]
+anyhow = "1.0.104"
+axum = "0.8.9"
+clap = { version = "4.6.7", features = ["derive"] }
+dirs = "7.0.0"
+futures = "0.3.34"
+gethostname = "1.1.0"
+if-addrs = "0.15.0"
+qrcode = { version = "0.14.1", default-features = false }
+reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json"] }
+rusqlite = { version = "0.40.2", features = ["bundled"] }
+serde = { version = "1.0.229", features = ["derive"] }
+serde_json = { version = "1.0.151", features = ["preserve_order"] }
+tokio = { version = "1.53.1", features = ["full"] }
+tokio-stream = { version = "0.1.19", features = ["sync"] }
+tracing = "0.1.44"
+tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
+uuid = { version = "1.26.1", features = ["v4"] }
diff --git a/host/src/acp.rs b/host/src/acp.rs
new file mode 100644
index 00000000..57df2454
--- /dev/null
+++ b/host/src/acp.rs
@@ -0,0 +1,216 @@
+//! Minimal ACP (Agent Client Protocol) client: JSON-RPC 2.0 over a child
+//! process's stdio. Updates are kept as `serde_json::Value` on purpose so a
+//! newer adapter adding a variant never breaks parsing.
+
+use anyhow::{Result, anyhow, bail};
+use serde_json::{Value, json};
+use std::collections::{HashMap, VecDeque};
+use std::process::Stdio;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicI64, Ordering};
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use tokio::process::{Child, ChildStdin, Command};
+use tokio::sync::{Mutex, mpsc, oneshot};
+
+pub enum Incoming {
+ Notification { method: String, params: Value },
+ Request { id: Value, method: String, params: Value },
+ Closed { stderr_tail: String },
+}
+
+type Pending = Arc<Mutex<HashMap<i64, oneshot::Sender<Result<Value, Value>>>>>;
+
+pub struct Acp {
+ stdin: Mutex<ChildStdin>,
+ next_id: AtomicI64,
+ pending: Pending,
+ child: Mutex<Child>,
+}
+
+impl Acp {
+ /// Spawns `command` through `sh -c` so user-provided commands (npx, env vars) just work.
+ pub fn spawn(command: &str, cwd: &str) -> Result<(Arc<Self>, mpsc::UnboundedReceiver<Incoming>)> {
+ let mut child = Command::new("/bin/sh")
+ .arg("-c")
+ .arg(format!("exec {command}"))
+ .current_dir(cwd)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true)
+ .spawn()
+ .map_err(|e| anyhow!("failed to start `{command}`: {e}"))?;
+ let stdin = child.stdin.take().unwrap();
+ let stdout = child.stdout.take().unwrap();
+ let stderr = child.stderr.take().unwrap();
+ let (tx, rx) = mpsc::unbounded_channel();
+ let pending: Pending = Default::default();
+
+ let tail = Arc::new(std::sync::Mutex::new(VecDeque::<String>::new()));
+ {
+ let tail = tail.clone();
+ tokio::spawn(async move {
+ let mut lines = BufReader::new(stderr).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ tracing::debug!(target: "agent", "{line}");
+ let mut t = tail.lock().unwrap();
+ if t.len() == 12 {
+ t.pop_front();
+ }
+ t.push_back(line);
+ }
+ });
+ }
+ {
+ let pending = pending.clone();
+ tokio::spawn(async move {
+ let mut lines = BufReader::new(stdout).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ let Ok(msg) = serde_json::from_str::<Value>(&line) else {
+ tracing::debug!(target: "agent", "non-json stdout: {line}");
+ continue;
+ };
+ let method = msg["method"].as_str().map(str::to_owned);
+ match (method, msg.get("id").cloned()) {
+ (Some(method), Some(id)) if !id.is_null() => {
+ let _ = tx.send(Incoming::Request { id, method, params: msg["params"].clone() });
+ }
+ (Some(method), _) => {
+ let _ = tx.send(Incoming::Notification { method, params: msg["params"].clone() });
+ }
+ (None, Some(id)) => {
+ if let Some(id) = id.as_i64()
+ && let Some(waiter) = pending.lock().await.remove(&id)
+ {
+ let res = match msg.get("error") {
+ Some(err) => Err(err.clone()),
+ None => Ok(msg["result"].clone()),
+ };
+ let _ = waiter.send(res);
+ }
+ }
+ _ => {}
+ }
+ }
+ // Process gone: fail everyone still waiting.
+ for (_, w) in pending.lock().await.drain() {
+ let _ = w.send(Err(json!({"message": "agent process exited"})));
+ }
+ let stderr_tail = tail.lock().unwrap().iter().cloned().collect::<Vec<_>>().join("\n");
+ let _ = tx.send(Incoming::Closed { stderr_tail });
+ });
+ }
+
+ let acp = Arc::new(Self {
+ stdin: Mutex::new(stdin),
+ next_id: AtomicI64::new(1),
+ pending,
+ child: Mutex::new(child),
+ });
+ Ok((acp, rx))
+ }
+
+ async fn write(&self, msg: Value) -> Result<()> {
+ let mut line = serde_json::to_vec(&msg)?;
+ line.push(b'\n');
+ let mut stdin = self.stdin.lock().await;
+ stdin.write_all(&line).await?;
+ stdin.flush().await?;
+ Ok(())
+ }
+
+ pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
+ let id = self.next_id.fetch_add(1, Ordering::Relaxed);
+ let (tx, rx) = oneshot::channel();
+ self.pending.lock().await.insert(id, tx);
+ self.write(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})).await?;
+ match rx.await {
+ Ok(Ok(v)) => Ok(v),
+ Ok(Err(e)) => {
+ let msg = e["message"].as_str().map(str::to_owned).unwrap_or_else(|| e.to_string());
+ match e["data"]["details"].as_str().or(e["data"].as_str()) {
+ Some(d) => bail!("{msg} ({d})"),
+ None => bail!("{msg}"),
+ }
+ }
+ Err(_) => bail!("{method}: connection closed"),
+ }
+ }
+
+ pub async fn notify(&self, method: &str, params: Value) -> Result<()> {
+ self.write(json!({"jsonrpc": "2.0", "method": method, "params": params})).await
+ }
+
+ pub async fn respond(&self, id: Value, result: Value) -> Result<()> {
+ self.write(json!({"jsonrpc": "2.0", "id": id, "result": result})).await
+ }
+
+ pub async fn respond_error(&self, id: Value, code: i64, message: &str) -> Result<()> {
+ self.write(json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})).await
+ }
+
+ pub async fn kill(&self) {
+ let _ = self.child.lock().await.kill().await;
+ }
+}
+
+/// Plain-text rendering of an ACP content block list / tool-call content list.
+pub fn content_text(v: &Value) -> String {
+ match v {
+ Value::Array(items) => items.iter().map(content_text).filter(|s| !s.is_empty()).collect::<Vec<_>>().join("\n"),
+ Value::Object(o) => match o.get("type").and_then(Value::as_str) {
+ Some("text") => o.get("text").and_then(Value::as_str).unwrap_or_default().to_owned(),
+ Some("content") => o.get("content").map(content_text).unwrap_or_default(),
+ Some("resource_link") => o.get("uri").and_then(Value::as_str).unwrap_or_default().to_owned(),
+ Some("resource") => o
+ .get("resource")
+ .and_then(|r| r.get("text"))
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_owned(),
+ _ => String::new(),
+ },
+ _ => String::new(),
+ }
+}
+
+pub fn truncate(s: &str, max: usize) -> String {
+ if s.len() <= max {
+ return s.to_owned();
+ }
+ let mut end = max;
+ while !s.is_char_boundary(end) {
+ end -= 1;
+ }
+ format!("{}…", &s[..end])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn content_text_flattens_blocks() {
+ let v = json!([
+ {"type": "content", "content": {"type": "text", "text": "a"}},
+ {"type": "diff", "path": "/x"},
+ {"type": "text", "text": "b"}
+ ]);
+ assert_eq!(content_text(&v), "a\nb");
+ assert_eq!(truncate("héllo", 2), "h…");
+ }
+
+ #[tokio::test]
+ async fn request_response_roundtrip() {
+ // A fake agent: answers `initialize`, then sends a notification and exits.
+ let script = r#"read l; id=$(echo "$l" | sed 's/.*"id":\([0-9]*\).*/\1/'); echo "{\"jsonrpc\":\"2.0\",\"id\":$id,\"result\":{\"ok\":true}}"; echo '{"jsonrpc":"2.0","method":"session/update","params":{"x":1}}'"#;
+ let (acp, mut rx) = Acp::spawn(&format!("sh -c '{}'", script.replace('\'', "'\\''")), "/tmp").unwrap();
+ let res = acp.request("initialize", json!({})).await.unwrap();
+ assert_eq!(res["ok"], true);
+ match rx.recv().await.unwrap() {
+ Incoming::Notification { method, .. } => assert_eq!(method, "session/update"),
+ _ => panic!("expected notification"),
+ }
+ assert!(matches!(rx.recv().await.unwrap(), Incoming::Closed { .. }));
+ }
+}
diff --git a/host/src/api.rs b/host/src/api.rs
new file mode 100644
index 00000000..36eff358
--- /dev/null
+++ b/host/src/api.rs
@@ -0,0 +1,274 @@
+//! HTTP API: `POST /api/<method>` commands + `GET /events` SSE.
+//! Auth: `Authorization: Bearer <token>` (or `?token=` for SSE).
+
+use crate::bot::Cmd;
+use crate::hub::Hub;
+use crate::store::BotConfig;
+use crate::{backends, usage};
+use anyhow::{Result, anyhow};
+use axum::extract::{Path, Query, State};
+use axum::http::{HeaderMap, StatusCode};
+use axum::response::sse::{Event, KeepAlive, Sse};
+use axum::response::{IntoResponse, Response};
+use axum::routing::{get, post};
+use axum::{Json, Router};
+use futures::{Stream, StreamExt, stream};
+use serde::Deserialize;
+use serde_json::{Value, json};
+use std::convert::Infallible;
+use std::sync::Arc;
+use std::sync::atomic::Ordering;
+use std::time::Duration;
+use tokio_stream::wrappers::BroadcastStream;
+
+pub fn router(hub: Arc<Hub>) -> Router {
+ Router::new()
+ .route("/health", get(health))
+ .route("/events", get(events))
+ .route("/api/{method}", post(command))
+ .route("/ingest/statusline", post(statusline))
+ .with_state(hub)
+}
+
+fn authorized(hub: &Hub, headers: &HeaderMap, query_token: Option<&str>) -> bool {
+ let header = headers
+ .get("authorization")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "));
+ let given = header.or(query_token).unwrap_or_default();
+ // Constant-time compare.
+ given.len() == hub.token.len() && given.bytes().zip(hub.token.bytes()).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0
+}
+
+struct ApiError(StatusCode, String);
+
+impl IntoResponse for ApiError {
+ fn into_response(self) -> Response {
+ (self.0, Json(json!({"error": self.1}))).into_response()
+ }
+}
+
+async fn health(State(hub): State<Arc<Hub>>) -> Json<Value> {
+ Json(json!({"ok": true, "hostId": hub.host_id, "version": env!("CARGO_PKG_VERSION")}))
+}
+
+async fn statusline(State(hub): State<Arc<Hub>>, headers: HeaderMap, Json(body): Json<Value>) -> StatusCode {
+ if !authorized(&hub, &headers, None) {
+ return StatusCode::UNAUTHORIZED;
+ }
+ usage::ingest_statusline(&hub, &body);
+ StatusCode::NO_CONTENT
+}
+
+async fn command(
+ State(hub): State<Arc<Hub>>,
+ Path(method): Path<String>,
+ headers: HeaderMap,
+ body: Option<Json<Value>>,
+) -> Result<Json<Value>, ApiError> {
+ if !authorized(&hub, &headers, None) {
+ return Err(ApiError(StatusCode::UNAUTHORIZED, "invalid token".into()));
+ }
+ let body = body.map(|b| b.0).unwrap_or(Value::Null);
+ match dispatch(&hub, &method, body).await {
+ Ok(v) => Ok(Json(v)),
+ Err(e) if e.to_string() == "unknown method" => Err(ApiError(StatusCode::NOT_FOUND, e.to_string())),
+ Err(e) => Err(ApiError(StatusCode::BAD_REQUEST, e.to_string())),
+ }
+}
+
+fn str_arg<'a>(b: &'a Value, k: &str) -> Result<&'a str> {
+ b[k].as_str().ok_or_else(|| anyhow!("`{k}` is required"))
+}
+
+pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
+ Ok(match method {
+ "hello" => json!({
+ "hostId": hub.host_id,
+ "name": crate::service::host_name(),
+ "version": env!("CARGO_PKG_VERSION"),
+ "os": std::env::consts::OS,
+ "home": dirs::home_dir().map(|p| p.to_string_lossy().into_owned()),
+ "backends": backends::list(),
+ "rev": hub.store.current_rev(),
+ }),
+ "sync" => {
+ let since = b["since"].as_i64().unwrap_or(0);
+ json!({
+ "hostId": hub.host_id,
+ "rev": hub.store.current_rev(),
+ "bots": hub.bots_json(since)?,
+ "entries": hub.store.entries_since(since, 200)?,
+ "usage": hub.usage.lock().unwrap().clone(),
+ })
+ }
+ "history" => {
+ let bot = str_arg(&b, "botId")?;
+ let before = b["beforeSeq"].as_i64().unwrap_or(i64::MAX);
+ let limit = b["limit"].as_i64().unwrap_or(100).clamp(1, 500);
+ json!({"entries": hub.store.history(bot, before, limit)?})
+ }
+ "createBot" => {
+ let mut b = b;
+ b["id"] = "".into();
+ let cfg: BotConfig = serde_json::from_value(b).map_err(|e| anyhow!("invalid bot: {e}"))?;
+ json!({"bot": hub.create_bot(cfg)?})
+ }
+ "updateBot" => json!({"bot": hub.update_bot(b)?}),
+ "deleteBot" => {
+ hub.delete_bot(str_arg(&b, "botId")?)?;
+ json!({})
+ }
+ "markRead" => {
+ hub.mark_read(str_arg(&b, "botId")?)?;
+ json!({})
+ }
+ "send" => {
+ let bot = str_arg(&b, "botId")?;
+ let text = str_arg(&b, "text")?.trim();
+ if text.is_empty() {
+ return Err(anyhow!("empty message"));
+ }
+ let nonce = b["clientNonce"].as_str().unwrap_or_default();
+ if !nonce.is_empty()
+ && let Some(e) = hub.store.find_by_nonce(bot, nonce)
+ {
+ return Ok(json!({"entry": e}));
+ }
+ hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;
+ let turn = hub.store.max_turn(bot) + 1;
+ let e = hub.add_entry(bot, "user", turn, json!({"text": text, "clientNonce": nonce, "status": "queued"}))?;
+ hub.send_cmd(bot, Cmd::Send { entry_id: e.id.clone(), text: text.to_owned() })?;
+ let _ = hub.mark_read(bot);
+ json!({"entry": e})
+ }
+ "stop" => {
+ hub.send_cmd(str_arg(&b, "botId")?, Cmd::Stop)?;
+ json!({})
+ }
+ "newSession" => {
+ hub.send_cmd(str_arg(&b, "botId")?, Cmd::NewSession)?;
+ json!({})
+ }
+ "respondPermission" => {
+ let entry_id = str_arg(&b, "entryId")?;
+ let e = hub.store.entry(entry_id).ok_or_else(|| anyhow!("unknown card"))?;
+ let option_id = b["optionId"].as_str().map(str::to_owned);
+ hub.send_cmd(&e.bot_id, Cmd::Permission { entry_id: entry_id.to_owned(), option_id })?;
+ json!({})
+ }
+ "registerDevice" => {
+ let ticket = str_arg(&b, "ticket")?;
+ if let Some(relay) = b["relay"].as_str().filter(|r| r.starts_with("https://")) {
+ hub.store.kv_set("relay_url", relay.trim_end_matches('/'))?;
+ }
+ hub.store.add_device(ticket, b["name"].as_str().unwrap_or("iPhone"))?;
+ json!({})
+ }
+ "unregisterDevice" => {
+ hub.store.remove_device(str_arg(&b, "ticket")?)?;
+ json!({})
+ }
+ "registerActivity" => {
+ let bot = str_arg(&b, "botId")?.to_owned();
+ let ticket = str_arg(&b, "ticket")?.to_owned();
+ let mut map = hub.activities.lock().unwrap();
+ let list = map.entry(bot).or_default();
+ if !list.contains(&ticket) {
+ list.push(ticket);
+ }
+ json!({})
+ }
+ "usage" => {
+ if b["refresh"].as_bool().unwrap_or(false) {
+ usage::refresh(hub).await;
+ }
+ hub.usage.lock().unwrap().clone()
+ }
+ "listDirs" => list_dirs(b["path"].as_str())?,
+ _ => return Err(anyhow!("unknown method")),
+ })
+}
+
+fn list_dirs(path: Option<&str>) -> Result<Value> {
+ let home = dirs::home_dir().ok_or_else(|| anyhow!("no home"))?;
+ let dir = path.map(std::path::PathBuf::from).unwrap_or(home);
+ let mut dirs: Vec<Value> = std::fs::read_dir(&dir)?
+ .filter_map(|e| e.ok())
+ .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
+ .filter_map(|e| {
+ let name = e.file_name().to_string_lossy().into_owned();
+ if name.starts_with('.') {
+ return None;
+ }
+ let p = e.path();
+ Some(json!({"name": name, "path": p.to_string_lossy(), "isGit": p.join(".git").exists()}))
+ })
+ .collect();
+ dirs.sort_by_key(|d| d["name"].as_str().unwrap_or_default().to_lowercase());
+ Ok(json!({
+ "path": dir.to_string_lossy(),
+ "parent": dir.parent().map(|p| p.to_string_lossy().into_owned()),
+ "isGit": dir.join(".git").exists(),
+ "dirs": dirs,
+ }))
+}
+
+#[derive(Deserialize)]
+struct EventsQuery {
+ since: Option<i64>,
+ token: Option<String>,
+ client: Option<String>,
+}
+
+struct ClientGuard(Arc<Hub>, bool);
+
+impl Drop for ClientGuard {
+ fn drop(&mut self) {
+ if self.1 {
+ self.0.ios_clients.fetch_sub(1, Ordering::Relaxed);
+ }
+ }
+}
+
+/// Subscribes first, then sends a catch-up (everything after `since`, in rev
+/// order), then live events. Duplicates are fine: clients upsert by id/rev.
+async fn events(
+ State(hub): State<Arc<Hub>>,
+ headers: HeaderMap,
+ Query(q): Query<EventsQuery>,
+) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, ApiError> {
+ if !authorized(&hub, &headers, q.token.as_deref()) {
+ return Err(ApiError(StatusCode::UNAUTHORIZED, "invalid token".into()));
+ }
+ let live = BroadcastStream::new(hub.events.subscribe());
+ let since = q.since.unwrap_or(0);
+ let mut catch_up: Vec<Value> = vec![];
+ for bot in hub.bots_json(since).map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))? {
+ catch_up.push(json!({"type": "bot", "rev": bot["rev"], "bot": bot}));
+ }
+ for e in hub.store.entries_since(since, 200).unwrap_or_default() {
+ catch_up.push(json!({"type": "entry", "rev": e.rev, "entry": e}));
+ }
+ catch_up.sort_by_key(|v| v["rev"].as_i64().unwrap_or(0));
+ let hello = json!({"type": "hello", "hostId": hub.host_id, "rev": hub.store.current_rev(), "usage": hub.usage.lock().unwrap().clone()});
+ catch_up.insert(0, hello);
+
+ let is_ios = q.client.as_deref() == Some("ios");
+ if is_ios {
+ hub.ios_clients.fetch_add(1, Ordering::Relaxed);
+ }
+ let guard = Arc::new(ClientGuard(hub.clone(), is_ios));
+ let head = stream::iter(catch_up.into_iter().map(|v| Ok(Event::default().data(v.to_string()))));
+ let tail = live.filter_map(move |msg| {
+ let _keep = guard.clone();
+ async move {
+ match msg {
+ Ok(v) => Some(Ok(Event::default().data(v.to_string()))),
+ // Lagged: tell the client to resync from its last rev.
+ Err(_) => Some(Ok(Event::default().data(json!({"type": "resync"}).to_string()))),
+ }
+ }
+ });
+ Ok(Sse::new(head.chain(tail)).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))))
+}
diff --git a/host/src/backends.rs b/host/src/backends.rs
new file mode 100644
index 00000000..e20b6eca
--- /dev/null
+++ b/host/src/backends.rs
@@ -0,0 +1,78 @@
+//! Known coding-agent backends and the ACP command that drives each one.
+
+use serde_json::{Value, json};
+
+pub struct Backend {
+ pub id: &'static str,
+ pub name: &'static str,
+ /// ACP stdio command.
+ pub command: &'static str,
+ /// CLI that must be installed and logged in for the adapter to work.
+ pub requires: &'static str,
+ pub install_hint: &'static str,
+}
+
+pub const BACKENDS: &[Backend] = &[
+ Backend {
+ id: "claude",
+ name: "Claude Code",
+ command: "npx -y @agentclientprotocol/claude-agent-acp",
+ requires: "claude",
+ install_hint: "Install Claude Code and run `claude` once to log in. Node.js (npx) is required for the ACP adapter.",
+ },
+ Backend {
+ id: "codex",
+ name: "Codex",
+ command: "npx -y @agentclientprotocol/codex-acp",
+ requires: "codex",
+ install_hint: "Install Codex CLI and run `codex login`. Node.js (npx) is required for the ACP adapter.",
+ },
+ Backend {
+ id: "opencode",
+ name: "OpenCode",
+ command: "opencode acp",
+ requires: "opencode",
+ install_hint: "Install OpenCode: curl -fsSL https://opencode.ai/install | bash",
+ },
+ Backend {
+ id: "grok",
+ name: "Grok Build",
+ command: "grok agent stdio",
+ requires: "grok",
+ install_hint: "Install Grok Build: curl -fsSL https://x.ai/cli/install.sh | bash",
+ },
+ Backend {
+ id: "gemini",
+ name: "Gemini CLI",
+ command: "gemini --experimental-acp",
+ requires: "gemini",
+ install_hint: "Install Gemini CLI: npm install -g @google/gemini-cli",
+ },
+];
+
+pub fn command(id: &str) -> Option<&'static str> {
+ BACKENDS.iter().find(|b| b.id == id).map(|b| b.command)
+}
+
+pub fn on_path(bin: &str) -> bool {
+ std::env::var_os("PATH")
+ .map(|p| std::env::split_paths(&p).any(|d| d.join(bin).is_file()))
+ .unwrap_or(false)
+}
+
+pub fn list() -> Vec<Value> {
+ BACKENDS
+ .iter()
+ .map(|b| {
+ let needs_npx = b.command.starts_with("npx ");
+ let available = on_path(b.requires) && (!needs_npx || on_path("npx"));
+ json!({
+ "id": b.id,
+ "name": b.name,
+ "available": available,
+ "command": b.command,
+ "installHint": b.install_hint,
+ })
+ })
+ .collect()
+}
diff --git a/host/src/bot.rs b/host/src/bot.rs
new file mode 100644
index 00000000..14f02cbe
--- /dev/null
+++ b/host/src/bot.rs
@@ -0,0 +1,719 @@
+//! One actor per bot. It owns the bot's ACP process and session, runs turns one
+//! at a time, and maps ACP `session/update`s onto transcript entries.
+//!
+//! Chat model (from Grok Bot): the thread only shows user messages, the *final*
+//! agent message of each turn, permission cards and notices. Narration between
+//! tool calls, thoughts, tool calls and plans are trace entries shown in the
+//! "full conversation" sheet, and surface live as the roster activity line.
+
+use crate::acp::{self, Acp, Incoming};
+use crate::hub::Hub;
+use crate::push;
+use crate::store::{BotConfig, now_ms};
+use anyhow::{Result, anyhow};
+use serde_json::{Value, json};
+use std::collections::{HashMap, HashSet, VecDeque};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+use tokio::sync::mpsc;
+
+pub enum Cmd {
+ Send { entry_id: String, text: String },
+ Stop,
+ Permission { entry_id: String, option_id: Option<String> },
+ NewSession,
+ Reconfigure(Box<BotConfig>),
+ Shutdown,
+}
+
+pub struct BotHandle {
+ pub tx: mpsc::UnboundedSender<Cmd>,
+}
+
+pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {
+ let (tx, rx) = mpsc::unbounded_channel();
+ let session_id = hub.store.bot(&cfg.id).ok().flatten().and_then(|b| b.session_id);
+ let actor = Actor {
+ hub,
+ cfg,
+ conn: None,
+ session_id,
+ session_fresh: false,
+ turn: None,
+ queue: VecDeque::new(),
+ seg: Seg::None,
+ tools: HashMap::new(),
+ plan_entry: None,
+ last_text: None,
+ perms: HashMap::new(),
+ stop_requested: false,
+ };
+ tokio::spawn(actor.run(rx));
+ BotHandle { tx }
+}
+
+struct Conn {
+ acp: Arc<Acp>,
+ rx: mpsc::UnboundedReceiver<Incoming>,
+ can_load: bool,
+ /// Sessions already created or loaded in this process.
+ loaded: HashSet<String>,
+}
+
+#[derive(Clone, Copy, PartialEq)]
+enum SegKind {
+ Text,
+ Thought,
+}
+
+enum Seg {
+ None,
+ Open { kind: SegKind, entry_id: String, buf: String, flushed: Instant, dirty: bool },
+}
+
+struct Actor {
+ hub: Arc<Hub>,
+ cfg: BotConfig,
+ conn: Option<Conn>,
+ session_id: Option<String>,
+ /// True until the first prompt of a new ACP session has been sent.
+ session_fresh: bool,
+ turn: Option<i64>,
+ queue: VecDeque<(String, String)>,
+ seg: Seg,
+ tools: HashMap<String, String>,
+ plan_entry: Option<String>,
+ last_text: Option<String>,
+ /// permission entry id -> JSON-RPC request id
+ perms: HashMap<String, Value>,
+ stop_requested: bool,
+}
+
+type Done = Result<Value>;
+
+impl Actor {
+ async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Cmd>) {
+ let (done_tx, mut done_rx) = mpsc::unbounded_channel::<Done>();
+ let mut flush_tick = tokio::time::interval(Duration::from_millis(300));
+ loop {
+ tokio::select! {
+ cmd = rx.recv() => {
+ let Some(cmd) = cmd else { break };
+ if !self.on_cmd(cmd, &done_tx).await { break }
+ }
+ inc = recv_incoming(&mut self.conn) => self.on_incoming(inc).await,
+ Some(done) = done_rx.recv() => {
+ // Updates sent before the prompt response are already queued; apply them first.
+ while let Some(inc) = self.conn.as_mut().and_then(|c| c.rx.try_recv().ok()) {
+ self.on_incoming(Some(inc)).await;
+ }
+ self.finish_turn(done).await;
+ self.next_in_queue(&done_tx).await;
+ }
+ _ = flush_tick.tick() => self.flush(false),
+ }
+ }
+ if let Some(c) = self.conn.take() {
+ c.acp.kill().await;
+ }
+ }
+
+ fn id(&self) -> String {
+ self.cfg.id.clone()
+ }
+
+ // MARK: commands
+
+ async fn on_cmd(&mut self, cmd: Cmd, done_tx: &mpsc::UnboundedSender<Done>) -> bool {
+ match cmd {
+ Cmd::Send { entry_id, text } => {
+ self.queue.push_back((entry_id, text));
+ if self.turn.is_none() {
+ self.next_in_queue(done_tx).await;
+ }
+ }
+ Cmd::Stop => self.stop().await,
+ Cmd::Permission { entry_id, option_id } => self.answer_permission(&entry_id, option_id).await,
+ Cmd::NewSession => {
+ if self.turn.is_some() {
+ self.stop().await;
+ }
+ self.session_id = None;
+ let _ = self.hub.store.set_session(&self.cfg.id, None);
+ self.notice("New session — the agent starts with a fresh context.", "divider");
+ }
+ Cmd::Reconfigure(cfg) => {
+ let cfg = *cfg;
+ let restart = cfg.backend != self.cfg.backend || cfg.command != self.cfg.command || cfg.cwd != self.cfg.cwd;
+ self.cfg = cfg;
+ if restart {
+ if let Some(c) = self.conn.take() {
+ c.acp.kill().await;
+ }
+ self.session_id = None;
+ let _ = self.hub.store.set_session(&self.cfg.id, None);
+ // A running prompt now fails; finish_turn reports it.
+ }
+ }
+ Cmd::Shutdown => return false,
+ }
+ true
+ }
+
+ async fn stop(&mut self) {
+ // Queued messages are dropped too: Stop means "stop everything".
+ for (entry_id, _) in self.queue.drain(..) {
+ if let Some(mut e) = self.hub.store.entry(&entry_id) {
+ e.data["status"] = "cancelled".into();
+ let _ = self.hub.set_entry(&entry_id, e.data);
+ }
+ }
+ if self.turn.is_none() {
+ return;
+ }
+ self.stop_requested = true;
+ let ids: Vec<String> = self.perms.keys().cloned().collect();
+ for id in ids {
+ self.answer_permission(&id, None).await;
+ }
+ if let (Some(c), Some(sid)) = (&self.conn, &self.session_id) {
+ let _ = c.acp.notify("session/cancel", json!({"sessionId": sid})).await;
+ }
+ }
+
+ async fn next_in_queue(&mut self, done_tx: &mpsc::UnboundedSender<Done>) {
+ while self.turn.is_none() {
+ let Some((entry_id, text)) = self.queue.pop_front() else { return };
+ if let Err(e) = self.start_turn(&entry_id, &text, done_tx).await {
+ self.notice(&format!("Couldn't start the agent: {e}"), "error");
+ self.turn = None;
+ self.hub.set_runtime(&self.id(), |r| {
+ r.status = "error".into();
+ r.activity = "Couldn't start".into();
+ r.started_at = None;
+ });
+ }
+ }
+ }
+
+ async fn start_turn(&mut self, entry_id: &str, text: &str, done_tx: &mpsc::UnboundedSender<Done>) -> Result<()> {
+ let turn = self.hub.store.entry(entry_id).map(|e| e.turn).unwrap_or(0);
+ if let Some(mut e) = self.hub.store.entry(entry_id) {
+ e.data["status"] = "sent".into();
+ self.hub.set_entry(entry_id, e.data)?;
+ }
+ self.turn = Some(turn);
+ self.stop_requested = false;
+ self.seg = Seg::None;
+ self.tools.clear();
+ self.plan_entry = None;
+ self.last_text = None;
+ self.hub.set_runtime(&self.id(), |r| {
+ r.status = "working".into();
+ r.activity = "Starting…".into();
+ r.started_at = Some(now_ms());
+ });
+
+ self.ensure_session().await?;
+ let conn = self.conn.as_ref().ok_or_else(|| anyhow!("agent not running"))?;
+ let mut prompt = text.to_owned();
+ if self.session_fresh {
+ self.session_fresh = false;
+ let mut profile = format!("You are \"{}\", a persistent agent the user delegates work to from their phone.", self.cfg.name);
+ if !self.cfg.description.trim().is_empty() {
+ profile.push_str(&format!(" Standing instructions:\n{}", self.cfg.description.trim()));
+ }
+ profile.push_str("\nKeep your final reply short and phone-friendly: say what you did and what needs the user.");
+ prompt = format!("<bot-profile>\n{profile}\n</bot-profile>\n\n{text}");
+ }
+ self.hub.set_runtime(&self.id(), |r| r.activity = "Thinking…".into());
+ let acp = conn.acp.clone();
+ let params = json!({
+ "sessionId": self.session_id,
+ "prompt": [{"type": "text", "text": prompt}],
+ });
+ let done_tx = done_tx.clone();
+ tokio::spawn(async move {
+ let _ = done_tx.send(acp.request("session/prompt", params).await);
+ });
+ Ok(())
+ }
+
+ async fn ensure_session(&mut self) -> Result<()> {
+ if self.conn.is_none() {
+ let command = match self.cfg.command.as_deref().map(str::trim) {
+ Some(c) if !c.is_empty() => c.to_owned(),
+ _ => crate::backends::command(&self.cfg.backend)
+ .ok_or_else(|| anyhow!("unknown backend"))?
+ .to_owned(),
+ };
+ self.hub.set_runtime(&self.id(), |r| r.activity = "Starting agent…".into());
+ let (acp, rx) = Acp::spawn(&command, &self.cfg.cwd)?;
+ let init = tokio::time::timeout(
+ Duration::from_secs(120),
+ acp.request(
+ "initialize",
+ json!({
+ "protocolVersion": 1,
+ "clientCapabilities": {"fs": {"readTextFile": false, "writeTextFile": false}, "terminal": false},
+ "clientInfo": {"name": "codync", "title": "Codync", "version": env!("CARGO_PKG_VERSION")},
+ }),
+ ),
+ )
+ .await
+ .map_err(|_| anyhow!("agent did not answer `initialize` within 2 minutes"))??;
+ let can_load = init["agentCapabilities"]["loadSession"].as_bool().unwrap_or(false);
+ self.conn = Some(Conn { acp, rx, can_load, loaded: HashSet::new() });
+ }
+ let conn = self.conn.as_mut().unwrap();
+ if let Some(sid) = self.session_id.clone() {
+ if conn.loaded.contains(&sid) {
+ return Ok(());
+ }
+ if !conn.can_load {
+ self.notice("This agent can't resume sessions after a restart — starting a fresh one.", "divider");
+ self.session_id = None;
+ return Box::pin(self.ensure_session()).await;
+ }
+ self.hub.set_runtime(&self.cfg.id, |r| r.activity = "Resuming session…".into());
+ let res = conn
+ .acp
+ .request("session/load", json!({"sessionId": sid, "cwd": self.cfg.cwd, "mcpServers": []}))
+ .await;
+ // The agent replays history as session/update before answering; drop it.
+ while let Ok(inc) = conn.rx.try_recv() {
+ if let Incoming::Request { id, .. } = inc {
+ let _ = conn.acp.respond_error(id, -32601, "not supported").await;
+ }
+ }
+ match res {
+ Ok(_) => {
+ conn.loaded.insert(sid);
+ return Ok(());
+ }
+ Err(e) => {
+ tracing::warn!("session/load failed, starting fresh: {e}");
+ self.notice("Couldn't resume the previous session — starting a fresh one.", "divider");
+ }
+ }
+ }
+ let conn = self.conn.as_mut().unwrap();
+ let res = conn
+ .acp
+ .request("session/new", json!({"cwd": self.cfg.cwd, "mcpServers": []}))
+ .await?;
+ let sid = res["sessionId"].as_str().ok_or_else(|| anyhow!("agent returned no sessionId"))?.to_owned();
+ conn.loaded.insert(sid.clone());
+ if let Some(model) = self.cfg.model.clone().filter(|m| !m.is_empty()) {
+ let has_model = res["configOptions"].as_array().is_some_and(|o| o.iter().any(|o| o["id"] == "model"));
+ let r = if has_model {
+ conn.acp
+ .request("session/set_config_option", json!({"sessionId": sid, "configId": "model", "value": model}))
+ .await
+ } else {
+ conn.acp.request("session/set_model", json!({"sessionId": sid, "modelId": model})).await
+ };
+ if let Err(e) = r {
+ tracing::warn!("couldn't set model {model}: {e}");
+ }
+ }
+ self.session_id = Some(sid.clone());
+ self.session_fresh = true;
+ self.hub.store.set_session(&self.cfg.id, Some(&sid))?;
+ Ok(())
+ }
+
+ async fn finish_turn(&mut self, done: Done) {
+ if self.turn.is_none() {
+ return;
+ }
+ self.flush(true);
+ self.seg = Seg::None;
+ // Unanswered permission cards can't be answered after the turn.
+ let ids: Vec<String> = self.perms.drain().map(|(k, _)| k).collect();
+ for id in ids {
+ if let Some(mut e) = self.hub.store.entry(&id) {
+ e.data["status"] = "expired".into();
+ let _ = self.hub.set_entry(&id, e.data);
+ }
+ }
+ let stopped = self.stop_requested || matches!(&done, Ok(v) if v["stopReason"] == "cancelled");
+ // Tool calls the agent never closed out would spin forever in the trace.
+ for entry_id in self.tools.values() {
+ if let Some(mut e) = self.hub.store.entry(entry_id)
+ && matches!(e.data["status"].as_str(), Some("pending" | "in_progress"))
+ {
+ e.data["status"] = if stopped || done.is_err() { "failed" } else { "completed" }.into();
+ let _ = self.hub.set_entry(entry_id, e.data);
+ }
+ }
+ let mut final_text = None;
+ if let Some(id) = self.last_text.take().filter(|_| !stopped)
+ && let Some(mut e) = self.hub.store.entry(&id)
+ {
+ e.data["final"] = true.into();
+ final_text = e.data["text"].as_str().map(str::to_owned);
+ let _ = self.hub.set_entry(&id, e.data);
+ }
+ let stop_reason = match &done {
+ Ok(v) => v["stopReason"].as_str().unwrap_or("end_turn").to_owned(),
+ Err(_) => "error".into(),
+ };
+ match (&done, stop_reason.as_str()) {
+ (Err(e), _) if !self.stop_requested => self.notice(&format!("The agent failed: {e}"), "error"),
+ (_, "cancelled") | (Err(_), _) => self.notice("Stopped.", "info"),
+ (_, "max_tokens") => self.notice("The agent hit its output limit.", "info"),
+ (_, "max_turn_requests") => self.notice("The agent hit its step limit for this turn.", "info"),
+ (_, "refusal") => self.notice("The agent declined to continue.", "info"),
+ _ => {}
+ }
+ let failed = done.is_err() && !self.stop_requested;
+ self.turn = None;
+ self.hub.set_runtime(&self.id(), |r| {
+ r.status = if failed { "error" } else { "idle" }.into();
+ r.activity = String::new();
+ r.started_at = None;
+ });
+ if !self.stop_requested {
+ let body = final_text.unwrap_or_else(|| if failed { "The agent failed.".into() } else { "Finished.".into() });
+ push::notify(&self.hub, &self.cfg, &self.cfg.name, &body, "done");
+ }
+ push::live_activity_end(&self.hub, &self.cfg.id);
+ }
+
+ // MARK: agent → client
+
+ async fn on_incoming(&mut self, inc: Option<Incoming>) {
+ match inc {
+ None | Some(Incoming::Closed { .. }) => {
+ let tail = match inc {
+ Some(Incoming::Closed { stderr_tail }) => stderr_tail,
+ _ => String::new(),
+ };
+ self.conn = None;
+ if self.turn.is_some() {
+ let detail = if tail.is_empty() { String::new() } else { format!("\n\n{}", acp::truncate(&tail, 1200)) };
+ self.notice(&format!("The agent process exited.{detail}"), "error");
+ }
+ // The in-flight prompt request resolves with an error and finishes the turn.
+ }
+ Some(Incoming::Notification { method, params }) => {
+ if method == "session/update" && params["sessionId"].as_str() == self.session_id.as_deref() && self.turn.is_some() {
+ self.on_update(&params["update"]);
+ }
+ }
+ Some(Incoming::Request { id, method, params }) => {
+ let Some(conn) = &self.conn else { return };
+ let acp = conn.acp.clone();
+ if method == "session/request_permission" && self.turn.is_some() {
+ self.on_permission(id, params).await;
+ } else {
+ let _ = acp.respond_error(id, -32601, &format!("{method} is not supported by Codync")).await;
+ }
+ }
+ }
+ }
+
+ fn on_update(&mut self, u: &Value) {
+ let turn = self.turn.unwrap_or(0);
+ match u["sessionUpdate"].as_str().unwrap_or_default() {
+ "agent_message_chunk" => {
+ let t = acp::content_text(&u["content"]);
+ self.append(SegKind::Text, &t);
+ self.set_activity("Writing a reply…");
+ }
+ "agent_thought_chunk" => {
+ let t = acp::content_text(&u["content"]);
+ self.append(SegKind::Thought, &t);
+ self.set_activity("Thinking…");
+ }
+ "tool_call" => {
+ self.close_seg();
+ let tool_id = u["toolCallId"].as_str().unwrap_or_default().to_owned();
+ let mut data = json!({
+ "toolCallId": tool_id,
+ "title": u["title"].as_str().unwrap_or("Tool"),
+ "toolKind": u["kind"].as_str().unwrap_or("other"),
+ "status": u["status"].as_str().unwrap_or("pending"),
+ "output": "",
+ "diffs": [],
+ "locations": u["locations"].clone(),
+ });
+ merge_tool_content(&mut data, &u["content"]);
+ let title = data["title"].as_str().unwrap_or("Tool").to_owned();
+ if let Ok(e) = self.hub.add_entry(&self.cfg.id, "tool", turn, data) {
+ self.tools.insert(tool_id, e.id);
+ }
+ self.set_activity(&title);
+ }
+ "tool_call_update" => {
+ let tool_id = u["toolCallId"].as_str().unwrap_or_default();
+ let Some(entry_id) = self.tools.get(tool_id).cloned() else { return };
+ let Some(mut e) = self.hub.store.entry(&entry_id) else { return };
+ for (k, key) in [("title", "title"), ("kind", "toolKind"), ("status", "status")] {
+ if let Some(v) = u[k].as_str() {
+ e.data[key] = v.into();
+ }
+ }
+ if !u["locations"].is_null() {
+ e.data["locations"] = u["locations"].clone();
+ }
+ merge_tool_content(&mut e.data, &u["content"]);
+ let status = e.data["status"].as_str().unwrap_or_default().to_owned();
+ let title = e.data["title"].as_str().unwrap_or_default().to_owned();
+ let _ = self.hub.set_entry(&entry_id, e.data);
+ if status == "in_progress" {
+ self.set_activity(&title);
+ }
+ }
+ "plan" => {
+ let data = json!({"entries": u["entries"].clone()});
+ match &self.plan_entry {
+ Some(id) => {
+ let _ = self.hub.set_entry(id, data);
+ }
+ None => {
+ if let Ok(e) = self.hub.add_entry(&self.cfg.id, "plan", turn, data) {
+ self.plan_entry = Some(e.id);
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+
+ async fn on_permission(&mut self, rpc_id: Value, params: Value) {
+ let options = params["options"].as_array().cloned().unwrap_or_default();
+ let tool = &params["toolCall"];
+ if self.cfg.permission == "auto" {
+ let pick = ["allow_once", "allow_always"]
+ .iter()
+ .find_map(|k| options.iter().find(|o| o["kind"] == *k))
+ .or_else(|| options.first());
+ if let (Some(o), Some(conn)) = (pick, &self.conn) {
+ let _ = conn
+ .acp
+ .respond(rpc_id, json!({"outcome": {"outcome": "selected", "optionId": o["optionId"]}}))
+ .await;
+ return;
+ }
+ }
+ let title = tool["title"]
+ .as_str()
+ .filter(|t| !t.is_empty())
+ .map(str::to_owned)
+ .or_else(|| {
+ let eid = self.tools.get(tool["toolCallId"].as_str()?)?;
+ self.hub.store.entry(eid)?.data["title"].as_str().map(str::to_owned)
+ })
+ .unwrap_or_else(|| "Use a tool".into());
+ let mut detail = json!({"output": "", "diffs": []});
+ merge_tool_content(&mut detail, &tool["content"]);
+ let raw = &tool["rawInput"];
+ let command = raw["command"]
+ .as_str()
+ .map(str::to_owned)
+ .or_else(|| raw["command"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" ")));
+ let data = json!({
+ "title": title,
+ "toolKind": tool["kind"].as_str().unwrap_or("other"),
+ "command": command,
+ "detail": detail["output"],
+ "diffs": detail["diffs"],
+ "cwd": self.cfg.cwd,
+ "options": options.iter().map(|o| json!({"optionId": o["optionId"], "name": o["name"], "kind": o["kind"]})).collect::<Vec<_>>(),
+ "status": "pending",
+ "selected": Value::Null,
+ });
+ let turn = self.turn.unwrap_or(0);
+ self.close_seg();
+ if let Ok(e) = self.hub.add_entry(&self.cfg.id, "permission", turn, data) {
+ self.perms.insert(e.id, rpc_id);
+ }
+ self.hub.set_runtime(&self.cfg.id, |r| {
+ r.status = "needsInput".into();
+ r.activity = format!("Needs approval: {title}");
+ });
+ push::notify(&self.hub, &self.cfg, &format!("{} needs you", self.cfg.name), &title, "needsInput");
+ }
+
+ async fn answer_permission(&mut self, entry_id: &str, option_id: Option<String>) {
+ let Some(rpc_id) = self.perms.remove(entry_id) else { return };
+ let outcome = match &option_id {
+ Some(o) => json!({"outcome": {"outcome": "selected", "optionId": o}}),
+ None => json!({"outcome": {"outcome": "cancelled"}}),
+ };
+ if let Some(conn) = &self.conn {
+ let _ = conn.acp.respond(rpc_id, outcome).await;
+ }
+ if let Some(mut e) = self.hub.store.entry(entry_id) {
+ e.data["status"] = if option_id.is_some() { "answered" } else { "cancelled" }.into();
+ e.data["selected"] = option_id.into();
+ let _ = self.hub.set_entry(entry_id, e.data);
+ }
+ if self.perms.is_empty() && self.turn.is_some() {
+ self.hub.set_runtime(&self.cfg.id, |r| {
+ r.status = "working".into();
+ r.activity = "Continuing…".into();
+ });
+ }
+ }
+
+ // MARK: streaming text segments
+
+ fn append(&mut self, kind: SegKind, text: &str) {
+ if text.is_empty() {
+ return;
+ }
+ let same = matches!(&self.seg, Seg::Open { kind: k, .. } if *k == kind);
+ if !same {
+ self.close_seg();
+ let (k, data) = match kind {
+ SegKind::Text => ("agent", json!({"text": text, "final": false})),
+ SegKind::Thought => ("thought", json!({"text": text})),
+ };
+ if let Ok(e) = self.hub.add_entry(&self.cfg.id, k, self.turn.unwrap_or(0), data) {
+ if kind == SegKind::Text {
+ self.last_text = Some(e.id.clone());
+ }
+ self.seg = Seg::Open { kind, entry_id: e.id, buf: text.to_owned(), flushed: Instant::now(), dirty: false };
+ }
+ return;
+ }
+ if let Seg::Open { buf, dirty, .. } = &mut self.seg {
+ buf.push_str(text);
+ *dirty = true;
+ }
+ }
+
+ /// Persists streamed text at most every 300 ms (or immediately with `force`).
+ fn flush(&mut self, force: bool) {
+ if let Seg::Open { kind, entry_id, buf, flushed, dirty } = &mut self.seg
+ && *dirty
+ && (force || flushed.elapsed() >= Duration::from_millis(300))
+ {
+ let data = match kind {
+ SegKind::Text => json!({"text": buf, "final": false}),
+ SegKind::Thought => json!({"text": buf}),
+ };
+ let _ = self.hub.set_entry(entry_id, data);
+ *flushed = Instant::now();
+ *dirty = false;
+ }
+ }
+
+ fn close_seg(&mut self) {
+ self.flush(true);
+ self.seg = Seg::None;
+ }
+
+ fn set_activity(&self, a: &str) {
+ if self.hub.runtime(&self.cfg.id).activity != a {
+ let a = a.to_owned();
+ self.hub.set_runtime(&self.cfg.id, |r| {
+ if r.status == "working" {
+ r.activity = a;
+ }
+ });
+ }
+ }
+
+ fn notice(&self, text: &str, style: &str) {
+ let turn = self.turn.unwrap_or_else(|| self.hub.store.max_turn(&self.cfg.id));
+ let _ = self.hub.add_entry(&self.cfg.id, "notice", turn, json!({"text": text, "style": style}));
+ }
+}
+
+async fn recv_incoming(conn: &mut Option<Conn>) -> Option<Incoming> {
+ match conn {
+ Some(c) => c.rx.recv().await,
+ None => std::future::pending().await,
+ }
+}
+
+/// Folds ACP tool-call `content` into `{output, diffs}` on an entry's data.
+pub fn merge_tool_content(data: &mut Value, content: &Value) {
+ let Some(items) = content.as_array() else { return };
+ let mut out = String::new();
+ let mut diffs = vec![];
+ for item in items {
+ match item["type"].as_str() {
+ Some("diff") => {
+ let path = item["path"].as_str().unwrap_or_default();
+ let old = item["oldText"].as_str().unwrap_or_default();
+ let new = item["newText"].as_str().unwrap_or_default();
+ diffs.push(diff_summary(path, old, new));
+ }
+ Some("terminal") => {}
+ _ => {
+ let t = acp::content_text(item);
+ if !t.is_empty() {
+ if !out.is_empty() {
+ out.push('\n');
+ }
+ out.push_str(&t);
+ }
+ }
+ }
+ }
+ if !out.is_empty() {
+ data["output"] = acp::truncate(&out, 6000).into();
+ }
+ if !diffs.is_empty() {
+ data["diffs"] = diffs.into();
+ }
+}
+
+/// Changed-region summary: trims the common prefix/suffix and reports the middle.
+pub fn diff_summary(path: &str, old: &str, new: &str) -> Value {
+ let a: Vec<&str> = old.lines().collect();
+ let b: Vec<&str> = new.lines().collect();
+ let prefix = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
+ let suffix = a[prefix..].iter().rev().zip(b[prefix..].iter().rev()).take_while(|(x, y)| x == y).count();
+ let removed = &a[prefix..a.len() - suffix];
+ let added = &b[prefix..b.len() - suffix];
+ let mut patch = String::new();
+ for l in removed {
+ patch.push_str(&format!("-{l}\n"));
+ }
+ for l in added {
+ patch.push_str(&format!("+{l}\n"));
+ }
+ json!({
+ "path": path,
+ "added": added.len(),
+ "removed": removed.len(),
+ "isNew": old.is_empty(),
+ "startLine": prefix + 1,
+ "patch": acp::truncate(&patch, 6000),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn diff_counts_changed_middle() {
+ let d = diff_summary("f", "a\nb\nc\n", "a\nB\nB2\nc\n");
+ assert_eq!(d["added"], 2);
+ assert_eq!(d["removed"], 1);
+ assert_eq!(d["startLine"], 2);
+ assert_eq!(d["patch"], "-b\n+B\n+B2\n");
+ }
+
+ #[test]
+ fn tool_content_merges_text_and_diffs() {
+ let mut data = json!({"output": "", "diffs": []});
+ merge_tool_content(
+ &mut data,
+ &json!([
+ {"type": "content", "content": {"type": "text", "text": "ok"}},
+ {"type": "diff", "path": "/a.rs", "oldText": "", "newText": "x\n"}
+ ]),
+ );
+ assert_eq!(data["output"], "ok");
+ assert_eq!(data["diffs"][0]["isNew"], true);
+ }
+}
diff --git a/host/src/hub.rs b/host/src/hub.rs
new file mode 100644
index 00000000..9cdc03e0
--- /dev/null
+++ b/host/src/hub.rs
@@ -0,0 +1,245 @@
+//! Shared host state: store, event fan-out, bot actors, push, usage.
+
+use crate::bot::{self, BotHandle, Cmd};
+use crate::store::{BotConfig, BotRow, Entry, Store};
+use crate::{push, service};
+use anyhow::{Result, anyhow};
+use serde_json::{Value, json};
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use tokio::sync::broadcast;
+
+#[derive(Clone, Default, Debug)]
+pub struct Runtime {
+ /// idle | working | needsInput | error
+ pub status: String,
+ pub activity: String,
+ pub started_at: Option<i64>,
+}
+
+pub struct Hub {
+ pub store: Store,
+ pub host_id: String,
+ pub token: String,
+ pub events: broadcast::Sender<Value>,
+ /// Held across "mutate store + broadcast" so events leave in rev order.
+ emit_lock: Mutex<()>,
+ bots: Mutex<HashMap<String, BotHandle>>,
+ runtime: Mutex<HashMap<String, Runtime>>,
+ pub ios_clients: AtomicUsize,
+ pub usage: Mutex<Value>,
+ keep_awake: Mutex<service::KeepAwake>,
+ /// botId -> Live Activity push tickets.
+ pub activities: Mutex<HashMap<String, Vec<String>>>,
+}
+
+impl Hub {
+ pub fn new(store: Store, host_id: String, token: String) -> Arc<Self> {
+ let (events, _) = broadcast::channel(1024);
+ Arc::new(Self {
+ store,
+ host_id,
+ token,
+ events,
+ emit_lock: Mutex::new(()),
+ bots: Default::default(),
+ runtime: Default::default(),
+ ios_clients: AtomicUsize::new(0),
+ usage: Mutex::new(json!({"providers": []})),
+ keep_awake: Default::default(),
+ activities: Default::default(),
+ })
+ }
+
+ pub fn start(self: &Arc<Self>) -> Result<()> {
+ // Approval cards and queued sends from a previous run can't be honored anymore.
+ self.store.expire_pending()?;
+ for row in self.store.bots()? {
+ if !row.deleted {
+ self.spawn_bot(row.config);
+ }
+ }
+ Ok(())
+ }
+
+ fn spawn_bot(self: &Arc<Self>, cfg: BotConfig) {
+ let id = cfg.id.clone();
+ self.runtime.lock().unwrap().insert(
+ id.clone(),
+ Runtime { status: "idle".into(), ..Default::default() },
+ );
+ let handle = bot::spawn(self.clone(), cfg);
+ self.bots.lock().unwrap().insert(id, handle);
+ }
+
+ pub fn send_cmd(&self, bot_id: &str, cmd: Cmd) -> Result<()> {
+ let bots = self.bots.lock().unwrap();
+ let h = bots.get(bot_id).ok_or_else(|| anyhow!("unknown bot"))?;
+ h.tx.send(cmd).map_err(|_| anyhow!("bot stopped"))
+ }
+
+ // MARK: bots
+
+ pub fn bot_json(&self, row: &BotRow) -> Value {
+ let mut v = serde_json::to_value(&row.config).unwrap();
+ let rt = self.runtime.lock().unwrap().get(&row.config.id).cloned().unwrap_or_default();
+ let last = self.store.last_message(&row.config.id);
+ v["rev"] = row.rev.into();
+ v["deleted"] = row.deleted.into();
+ v["status"] = if rt.status.is_empty() { "idle".into() } else { rt.status.into() };
+ v["activity"] = rt.activity.into();
+ v["startedAt"] = rt.started_at.into();
+ v["unread"] = self.store.unread(&row.config.id, row.read_rev).into();
+ v["lastMessage"] = last.as_ref().map(|l| crate::acp::truncate(&l.0, 280)).into();
+ v["lastAt"] = last.map(|l| l.1).unwrap_or(row.config.created_at).into();
+ v
+ }
+
+ pub fn bots_json(&self, since: i64) -> Result<Vec<Value>> {
+ Ok(self
+ .store
+ .bots()?
+ .iter()
+ .filter(|b| b.rev > since && !(since == 0 && b.deleted))
+ .map(|b| self.bot_json(b))
+ .collect())
+ }
+
+ pub fn create_bot(self: &Arc<Self>, mut cfg: BotConfig) -> Result<Value> {
+ cfg.id = uuid::Uuid::new_v4().to_string();
+ cfg.created_at = crate::store::now_ms();
+ validate(&cfg)?;
+ {
+ let _g = self.emit_lock.lock().unwrap();
+ self.store.save_bot(&cfg)?;
+ }
+ self.spawn_bot(cfg.clone());
+ self.emit_bot(&cfg.id);
+ Ok(self.bot_value(&cfg.id).unwrap_or(Value::Null))
+ }
+
+ pub fn update_bot(&self, patch: Value) -> Result<Value> {
+ let id = patch["id"].as_str().ok_or_else(|| anyhow!("id required"))?.to_owned();
+ let row = self.store.bot(&id)?.filter(|b| !b.deleted).ok_or_else(|| anyhow!("unknown bot"))?;
+ let mut merged = serde_json::to_value(&row.config)?;
+ for (k, v) in patch.as_object().into_iter().flatten() {
+ if k != "id" && k != "createdAt" {
+ merged[k] = v.clone();
+ }
+ }
+ let cfg: BotConfig = serde_json::from_value(merged)?;
+ validate(&cfg)?;
+ {
+ let _g = self.emit_lock.lock().unwrap();
+ self.store.save_bot(&cfg)?;
+ }
+ self.send_cmd(&id, Cmd::Reconfigure(Box::new(cfg)))?;
+ self.emit_bot(&id);
+ Ok(self.bot_value(&id).unwrap_or(Value::Null))
+ }
+
+ pub fn delete_bot(&self, id: &str) -> Result<()> {
+ let _ = self.send_cmd(id, Cmd::Shutdown);
+ self.bots.lock().unwrap().remove(id);
+ self.runtime.lock().unwrap().remove(id);
+ let _g = self.emit_lock.lock().unwrap();
+ let rev = self.store.delete_bot(id)?;
+ let _ = self.events.send(json!({"type": "bot", "rev": rev, "bot": {"id": id, "deleted": true, "rev": rev}}));
+ Ok(())
+ }
+
+ pub fn mark_read(&self, id: &str) -> Result<()> {
+ {
+ let _g = self.emit_lock.lock().unwrap();
+ self.store.mark_read(id)?;
+ }
+ self.emit_bot_row(id);
+ Ok(())
+ }
+
+ fn bot_value(&self, id: &str) -> Option<Value> {
+ self.store.bot(id).ok().flatten().map(|r| self.bot_json(&r))
+ }
+
+ /// Bumps the bot's rev and broadcasts its current state.
+ pub fn emit_bot(&self, id: &str) {
+ let _g = self.emit_lock.lock().unwrap();
+ if self.store.touch_bot(id).is_ok()
+ && let Some(v) = self.bot_value(id)
+ {
+ let _ = self.events.send(json!({"type": "bot", "rev": v["rev"], "bot": v}));
+ }
+ }
+
+ fn emit_bot_row(&self, id: &str) {
+ let _g = self.emit_lock.lock().unwrap();
+ if let Some(v) = self.bot_value(id) {
+ let _ = self.events.send(json!({"type": "bot", "rev": v["rev"], "bot": v}));
+ }
+ }
+
+ pub fn set_runtime(&self, id: &str, f: impl FnOnce(&mut Runtime)) {
+ let (before, after) = {
+ let mut map = self.runtime.lock().unwrap();
+ let rt = map.entry(id.to_owned()).or_default();
+ let before = rt.clone();
+ f(rt);
+ (before, rt.clone())
+ };
+ if before.status != after.status || before.activity != after.activity {
+ self.emit_bot(id);
+ self.update_keep_awake();
+ push::live_activity_update(self, id, &after);
+ }
+ }
+
+ pub fn runtime(&self, id: &str) -> Runtime {
+ self.runtime.lock().unwrap().get(id).cloned().unwrap_or_default()
+ }
+
+ fn update_keep_awake(&self) {
+ let busy = self.runtime.lock().unwrap().values().any(|r| r.status == "working");
+ self.keep_awake.lock().unwrap().set(busy);
+ }
+
+ // MARK: entries
+
+ pub fn add_entry(&self, bot_id: &str, kind: &str, turn: i64, data: Value) -> Result<Entry> {
+ let _g = self.emit_lock.lock().unwrap();
+ let e = self.store.insert_entry(bot_id, kind, turn, &data)?;
+ let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));
+ Ok(e)
+ }
+
+ pub fn set_entry(&self, id: &str, data: Value) -> Result<Option<Entry>> {
+ let _g = self.emit_lock.lock().unwrap();
+ let e = self.store.update_entry(id, &data)?;
+ if let Some(e) = &e {
+ let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));
+ }
+ Ok(e)
+ }
+
+ pub fn set_usage(&self, usage: Value) {
+ *self.usage.lock().unwrap() = usage.clone();
+ let _ = self.events.send(json!({"type": "usage", "usage": usage}));
+ }
+
+ pub fn ios_connected(&self) -> bool {
+ self.ios_clients.load(Ordering::Relaxed) > 0
+ }
+}
+
+fn validate(cfg: &BotConfig) -> Result<()> {
+ if cfg.name.trim().is_empty() {
+ return Err(anyhow!("name is required"));
+ }
+ if !std::path::Path::new(&cfg.cwd).is_dir() {
+ return Err(anyhow!("workspace folder does not exist: {}", cfg.cwd));
+ }
+ if cfg.command.as_deref().map(str::trim).unwrap_or_default().is_empty() && crate::backends::command(&cfg.backend).is_none() {
+ return Err(anyhow!("unknown backend {}", cfg.backend));
+ }
+ Ok(())
+}
diff --git a/host/src/main.rs b/host/src/main.rs
new file mode 100644
index 00000000..aacdd1c9
--- /dev/null
+++ b/host/src/main.rs
@@ -0,0 +1,206 @@
+mod acp;
+mod api;
+mod backends;
+mod bot;
+mod hub;
+mod push;
+mod service;
+mod store;
+mod usage;
+
+use anyhow::Result;
+use clap::{Parser, Subcommand};
+use serde_json::json;
+use std::io::Read;
+use std::time::Duration;
+
+#[derive(Parser)]
+#[command(name = "codync-host", version, about = "Codync host: runs your coding-agent bots and serves the Codync phone app")]
+struct Cli {
+ #[command(subcommand)]
+ cmd: Option<Sub>,
+}
+
+#[derive(Subcommand)]
+enum Sub {
+ /// Run the host in the foreground (what the background service runs).
+ Serve {
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ /// Address to bind. Defaults to all interfaces so the phone can reach it over Tailscale/LAN.
+ #[arg(long, default_value = "0.0.0.0")]
+ bind: String,
+ },
+ /// Show the pairing QR code for the Codync iOS app.
+ Pair {
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ /// Print machine-readable JSON instead of a QR code.
+ #[arg(long)]
+ json: bool,
+ },
+ /// Install and start the host as a background service (launchd / systemd --user).
+ Install {
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ },
+ /// Stop and remove the background service.
+ Uninstall,
+ /// Show whether the host is installed and running.
+ Status {
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ },
+ /// Claude Code statusLine command: forwards usage limits to the host and prints a short status line.
+ Statusline {
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ },
+ /// Rotate the pairing token (unpairs every phone).
+ ResetToken,
+}
+
+/// Host identity + auth token live in the database; the token is mirrored to
+/// `~/.codync/token` (0600) for local helpers like the statusline command.
+fn open_store() -> Result<(store::Store, String, String)> {
+ let dir = service::data_dir();
+ std::fs::create_dir_all(&dir)?;
+ let store = store::Store::open(&dir.join("codync.db"))?;
+ let host_id = match store.kv_get("host_id") {
+ Some(v) => v,
+ None => {
+ let v = uuid::Uuid::new_v4().to_string();
+ store.kv_set("host_id", &v)?;
+ v
+ }
+ };
+ let token = match store.kv_get("token") {
+ Some(v) => v,
+ None => rotate_token(&store)?,
+ };
+ Ok((store, host_id, token))
+}
+
+fn rotate_token(store: &store::Store) -> Result<String> {
+ let t = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
+ store.kv_set("token", &t)?;
+ write_token_file(&t)?;
+ Ok(t)
+}
+
+fn write_token_file(token: &str) -> Result<()> {
+ let path = service::data_dir().join("token");
+ std::fs::write(&path, token)?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
+ }
+ Ok(())
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let cli = Cli::parse();
+ match cli.cmd.unwrap_or(Sub::Serve { port: service::DEFAULT_PORT, bind: "0.0.0.0".into() }) {
+ Sub::Serve { port, bind } => serve(&bind, port).await,
+ Sub::Pair { port, json } => {
+ let (_, host_id, token) = open_store()?;
+ let urls = service::addresses(port);
+ let name = service::host_name();
+ let url = service::pairing_url(&name, &token, &urls);
+ if json {
+ println!("{}", json!({"name": name, "hostId": host_id, "token": token, "urls": urls, "pairingUrl": url}));
+ } else {
+ let code = qrcode::QrCode::new(url.as_bytes())?;
+ println!("{}", code.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build());
+ println!("Scan with the Codync iOS app, or open this link on the phone:\n{url}\n");
+ if urls.is_empty() {
+ println!("⚠︎ No Tailscale or LAN address found — the phone won't be able to reach this machine.");
+ } else if !urls.iter().any(|u| u.contains("://100.") || u.contains(".ts.net")) {
+ println!("Tip: install Tailscale on this machine and your phone to reach it from anywhere.");
+ }
+ }
+ Ok(())
+ }
+ Sub::Install { port } => {
+ open_store()?;
+ if let Some(home) = dirs::home_dir() {
+ match service::remove_legacy_hooks(&home.join(".claude/settings.json")) {
+ Ok(0) => {}
+ Ok(n) => println!("Removed {n} Codync 1.x hook(s) from ~/.claude/settings.json (backup saved next to it)."),
+ Err(e) => eprintln!("Couldn't clean up Codync 1.x hooks: {e}"),
+ }
+ }
+ service::install(port)?;
+ println!("Codync host installed and started on port {port}. Run `codync-host pair` to connect your phone.");
+ Ok(())
+ }
+ Sub::Uninstall => {
+ service::uninstall()?;
+ println!("Codync host service removed. Data is kept in {}", service::data_dir().display());
+ Ok(())
+ }
+ Sub::Status { port } => {
+ let running = reqwest::Client::new()
+ .get(format!("http://127.0.0.1:{port}/health"))
+ .timeout(Duration::from_secs(2))
+ .send()
+ .await
+ .is_ok_and(|r| r.status().is_success());
+ println!("installed: {}\nrunning: {running}\nport: {port}\ndata: {}", service::installed(), service::data_dir().display());
+ Ok(())
+ }
+ Sub::Statusline { port } => {
+ statusline(port).await;
+ Ok(())
+ }
+ Sub::ResetToken => {
+ let (store, _, _) = open_store()?;
+ rotate_token(&store)?;
+ println!("Token rotated. Restart the host and pair your phone again.");
+ Ok(())
+ }
+ }
+}
+
+async fn serve(bind: &str, port: u16) -> Result<()> {
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "codync_host=info".into()),
+ )
+ .init();
+ let (store, host_id, token) = open_store()?;
+ write_token_file(&token)?;
+ let hub = hub::Hub::new(store, host_id, token);
+ hub.start()?;
+ tokio::spawn(usage::poll(hub.clone()));
+ let listener = tokio::net::TcpListener::bind((bind, port)).await?;
+ tracing::info!("codync-host {} listening on {bind}:{port}", env!("CARGO_PKG_VERSION"));
+ axum::serve(listener, api::router(hub)).await?;
+ Ok(())
+}
+
+/// Never blocks Claude Code: 1 s budget, all errors ignored.
+async fn statusline(port: u16) {
+ let mut input = String::new();
+ let _ = std::io::stdin().read_to_string(&mut input);
+ let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
+ if let Ok(token) = std::fs::read_to_string(service::data_dir().join("token")) {
+ let _ = reqwest::Client::new()
+ .post(format!("http://127.0.0.1:{port}/ingest/statusline"))
+ .bearer_auth(token.trim())
+ .json(&v)
+ .timeout(Duration::from_secs(1))
+ .send()
+ .await;
+ }
+ let model = v["model"]["display_name"].as_str().unwrap_or("Claude");
+ let mut line = model.to_owned();
+ for (k, label) in [("five_hour", "5h"), ("seven_day", "7d")] {
+ if let Some(p) = v["rate_limits"][k]["used_percentage"].as_f64() {
+ line.push_str(&format!(" · {label} {p:.0}%"));
+ }
+ }
+ println!("{line}");
+}
diff --git a/host/src/push.rs b/host/src/push.rs
new file mode 100644
index 00000000..a8f0fc9c
--- /dev/null
+++ b/host/src/push.rs
@@ -0,0 +1,106 @@
+//! Push via the Codync relay (it holds the APNs key; the host only holds opaque
+//! per-device tickets the relay issued to the phone).
+//!
+//! Like Grok Bot there are only two alert kinds: "needs you" and "done", and
+//! none are sent while the phone app is connected (it's in the foreground).
+
+use crate::hub::{Hub, Runtime};
+use crate::store::BotConfig;
+use serde_json::{Value, json};
+use std::collections::HashMap;
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+static LAST: Mutex<Option<HashMap<String, Instant>>> = Mutex::new(None);
+/// Tickets the relay reported as dead (app uninstalled / token rotated); purged on the next push.
+static GONE: Mutex<Vec<String>> = Mutex::new(Vec::new());
+
+fn relay_url(hub: &Hub) -> Option<String> {
+ std::env::var("CODYNC_RELAY_URL").ok().or_else(|| hub.store.kv_get("relay_url")).filter(|u| !u.is_empty())
+}
+
+fn post(url: String, body: Value) {
+ tokio::spawn(async move {
+ let client = reqwest::Client::new();
+ match client.post(&url).json(&body).timeout(Duration::from_secs(10)).send().await {
+ Ok(r) if r.status().is_success() => {}
+ Ok(r) if r.status() == reqwest::StatusCode::GONE => {
+ if let Some(t) = body["ticket"].as_str() {
+ GONE.lock().unwrap().push(t.to_owned());
+ }
+ }
+ Ok(r) => tracing::warn!("relay {} → {}", url, r.status()),
+ Err(e) => tracing::warn!("relay {url}: {e}"),
+ }
+ });
+}
+
+pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: &str) {
+ if bot.notify == Some(false) || bot.hidden || hub.ios_connected() {
+ return;
+ }
+ // At most one alert per bot+kind every 5 s.
+ {
+ let mut last = LAST.lock().unwrap();
+ let map = last.get_or_insert_with(HashMap::new);
+ let key = format!("{}:{kind}", bot.id);
+ if map.get(&key).is_some_and(|t| t.elapsed() < Duration::from_secs(5)) {
+ return;
+ }
+ map.insert(key, Instant::now());
+ }
+ let Some(relay) = relay_url(hub) else { return };
+ for t in std::mem::take(&mut *GONE.lock().unwrap()) {
+ let _ = hub.store.remove_device(&t);
+ }
+ for ticket in hub.store.devices() {
+ post(
+ format!("{relay}/push"),
+ json!({
+ "ticket": ticket,
+ "alert": {"title": title, "body": crate::acp::truncate(body, 140)},
+ "threadId": bot.id,
+ "category": kind,
+ "data": {"botId": bot.id},
+ }),
+ );
+ }
+}
+
+/// Throttled Live Activity content updates for bots the phone is watching.
+pub fn live_activity_update(hub: &Hub, bot_id: &str, rt: &Runtime) {
+ let tickets = hub.activities.lock().unwrap().get(bot_id).cloned().unwrap_or_default();
+ if tickets.is_empty() {
+ return;
+ }
+ {
+ let mut last = LAST.lock().unwrap();
+ let map = last.get_or_insert_with(HashMap::new);
+ let key = format!("{bot_id}:la");
+ let urgent = rt.status != "working";
+ if !urgent && map.get(&key).is_some_and(|t| t.elapsed() < Duration::from_secs(8)) {
+ return;
+ }
+ map.insert(key, Instant::now());
+ }
+ let Some(relay) = relay_url(hub) else { return };
+ let state = json!({
+ "status": if rt.status.is_empty() { "idle" } else { &rt.status },
+ "activity": rt.activity,
+ "startedAt": rt.started_at.map(|ms| ms as f64 / 1000.0 - 978_307_200.0), // Swift Date reference epoch
+ });
+ for ticket in tickets {
+ post(format!("{relay}/push"), json!({"ticket": ticket, "liveActivity": {"event": "update", "contentState": state}}));
+ }
+}
+
+pub fn live_activity_end(hub: &Hub, bot_id: &str) {
+ let tickets = hub.activities.lock().unwrap().remove(bot_id).unwrap_or_default();
+ let Some(relay) = relay_url(hub) else { return };
+ for ticket in tickets {
+ post(
+ format!("{relay}/push"),
+ json!({"ticket": ticket, "liveActivity": {"event": "end", "contentState": {"status": "idle", "activity": "", "startedAt": null}}}),
+ );
+ }
+}
diff --git a/host/src/service.rs b/host/src/service.rs
new file mode 100644
index 00000000..ef04a7a0
--- /dev/null
+++ b/host/src/service.rs
@@ -0,0 +1,264 @@
+//! Platform glue: data dir, background service install (launchd / systemd),
+//! keeping the machine awake during turns, and pairing addresses.
+
+use anyhow::{Context, Result, bail};
+use std::path::PathBuf;
+use std::process::{Child, Command, Stdio};
+
+pub const DEFAULT_PORT: u16 = 19222;
+const LABEL: &str = "com.pokai.codync.host";
+
+pub fn data_dir() -> PathBuf {
+ std::env::var_os("CODYNC_HOME")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| dirs::home_dir().expect("no home dir").join(".codync"))
+}
+
+fn launchd_plist() -> PathBuf {
+ dirs::home_dir().unwrap().join(format!("Library/LaunchAgents/{LABEL}.plist"))
+}
+
+fn systemd_unit() -> PathBuf {
+ dirs::config_dir().unwrap().join("systemd/user/codync-host.service")
+}
+
+fn xml_escape(s: &str) -> String {
+ s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
+}
+
+/// Installs and starts the host as a per-user background service. The current
+/// PATH is captured so the service finds `npx`, `claude`, `codex`, …
+pub fn install(port: u16) -> Result<()> {
+ let exe = std::env::current_exe()?.canonicalize()?;
+ let exe = exe.to_string_lossy();
+ let path = std::env::var("PATH").unwrap_or_default();
+ let log = data_dir().join("host.log");
+ std::fs::create_dir_all(data_dir())?;
+ if cfg!(target_os = "macos") {
+ let plist = format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key><string>{LABEL}</string>
+ <key>ProgramArguments</key><array><string>{exe}</string><string>serve</string><string>--port</string><string>{port}</string></array>
+ <key>EnvironmentVariables</key><dict><key>PATH</key><string>{path}</string></dict>
+ <key>RunAtLoad</key><true/>
+ <key>KeepAlive</key><true/>
+ <key>ProcessType</key><string>Interactive</string>
+ <key>StandardOutPath</key><string>{log}</string>
+ <key>StandardErrorPath</key><string>{log}</string>
+</dict>
+</plist>
+"#,
+ exe = xml_escape(&exe),
+ path = xml_escape(&path),
+ log = xml_escape(&log.to_string_lossy()),
+ );
+ let file = launchd_plist();
+ std::fs::create_dir_all(file.parent().unwrap())?;
+ let uid = unsafe_uid();
+ let _ = Command::new("launchctl").args(["bootout", &format!("gui/{uid}/{LABEL}")]).status();
+ std::fs::write(&file, plist)?;
+ let ok = Command::new("launchctl")
+ .args(["bootstrap", &format!("gui/{uid}"), &file.to_string_lossy()])
+ .status()?
+ .success();
+ if !ok {
+ bail!("launchctl bootstrap failed");
+ }
+ } else {
+ let unit = format!(
+ "[Unit]\nDescription=Codync host\nAfter=network-online.target\n\n[Service]\nExecStart={exe} serve --port {port}\nEnvironment=PATH={path}\nRestart=always\nRestartSec=3\n\n[Install]\nWantedBy=default.target\n"
+ );
+ let file = systemd_unit();
+ std::fs::create_dir_all(file.parent().unwrap())?;
+ std::fs::write(&file, unit)?;
+ run("systemctl", &["--user", "daemon-reload"])?;
+ run("systemctl", &["--user", "enable", "--now", "codync-host.service"])?;
+ println!("Tip: `loginctl enable-linger $USER` keeps the host running while you're logged out.");
+ }
+ Ok(())
+}
+
+pub fn uninstall() -> Result<()> {
+ if cfg!(target_os = "macos") {
+ let _ = Command::new("launchctl").args(["bootout", &format!("gui/{}/{LABEL}", unsafe_uid())]).status();
+ let _ = std::fs::remove_file(launchd_plist());
+ } else {
+ let _ = run("systemctl", &["--user", "disable", "--now", "codync-host.service"]);
+ let _ = std::fs::remove_file(systemd_unit());
+ let _ = run("systemctl", &["--user", "daemon-reload"]);
+ }
+ Ok(())
+}
+
+pub fn installed() -> bool {
+ if cfg!(target_os = "macos") { launchd_plist().exists() } else { systemd_unit().exists() }
+}
+
+fn run(cmd: &str, args: &[&str]) -> Result<()> {
+ let ok = Command::new(cmd).args(args).status().with_context(|| format!("running {cmd}"))?.success();
+ if !ok {
+ bail!("{cmd} {} failed", args.join(" "));
+ }
+ Ok(())
+}
+
+fn unsafe_uid() -> String {
+ Command::new("id")
+ .arg("-u")
+ .output()
+ .ok()
+ .and_then(|o| String::from_utf8(o.stdout).ok())
+ .map(|s| s.trim().to_owned())
+ .unwrap_or_else(|| "501".into())
+}
+
+/// Holds a sleep inhibitor while any bot is working.
+#[derive(Default)]
+pub struct KeepAwake(Option<Child>);
+
+impl KeepAwake {
+ pub fn set(&mut self, on: bool) {
+ match (on, self.0.is_some()) {
+ (true, false) => {
+ let pid = std::process::id().to_string();
+ let child = if cfg!(target_os = "macos") {
+ Command::new("caffeinate").args(["-i", "-w", &pid]).stdout(Stdio::null()).spawn()
+ } else {
+ Command::new("systemd-inhibit")
+ .args(["--what=sleep:idle", "--who=Codync", "--why=A bot is working", "--mode=block", "sleep", "infinity"])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ };
+ self.0 = child.ok();
+ }
+ (false, true) => {
+ if let Some(mut c) = self.0.take() {
+ let _ = c.kill();
+ let _ = c.wait();
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+/// Addresses the phone can try, best first: Tailscale, then LAN.
+pub fn addresses(port: u16) -> Vec<String> {
+ let mut tailscale = vec![];
+ let mut lan = vec![];
+ for iface in if_addrs::get_if_addrs().unwrap_or_default() {
+ if iface.is_loopback() {
+ continue;
+ }
+ if let std::net::IpAddr::V4(ip) = iface.ip() {
+ let o = ip.octets();
+ if o[0] == 100 && (64..128).contains(&o[1]) {
+ tailscale.push(format!("http://{ip}:{port}"));
+ } else if ip.is_private() {
+ lan.push(format!("http://{ip}:{port}"));
+ }
+ }
+ }
+ if let Ok(out) = Command::new("tailscale").args(["status", "--json"]).output()
+ && let Ok(v) = serde_json::from_slice::<serde_json::Value>(&out.stdout)
+ && let Some(dns) = v["Self"]["DNSName"].as_str()
+ {
+ let dns = dns.trim_end_matches('.');
+ if !dns.is_empty() {
+ tailscale.insert(0, format!("http://{dns}:{port}"));
+ }
+ }
+ tailscale.sort();
+ tailscale.dedup();
+ lan.sort();
+ lan.dedup();
+ tailscale.into_iter().chain(lan).collect()
+}
+
+pub fn host_name() -> String {
+ let n = gethostname::gethostname().to_string_lossy().into_owned();
+ n.trim_end_matches(".local").to_owned()
+}
+
+fn pct(s: &str) -> String {
+ s.bytes()
+ .map(|b| match b {
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
+ _ => format!("%{b:02X}"),
+ })
+ .collect()
+}
+
+pub fn pairing_url(name: &str, token: &str, urls: &[String]) -> String {
+ format!(
+ "codync://pair?name={}&token={}&urls={}",
+ pct(name),
+ pct(token),
+ pct(&urls.join(","))
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn pairing_url_is_escaped() {
+ let u = super::pairing_url("Kevin's Mac", "t0k", &["http://100.1.2.3:19222".into(), "http://a:1".into()]);
+ assert_eq!(u, "codync://pair?name=Kevin%27s%20Mac&token=t0k&urls=http%3A%2F%2F100.1.2.3%3A19222%2Chttp%3A%2F%2Fa%3A1");
+ }
+}
+
+/// Codync 1.x installed `~/.codync/notify.sh` as Claude Code hooks. 2.x drives
+/// agents over ACP instead, so those hooks are dead weight; remove only them.
+/// Returns how many hook commands were removed.
+pub fn remove_legacy_hooks(settings: &std::path::Path) -> Result<usize> {
+ let Ok(text) = std::fs::read_to_string(settings) else { return Ok(0) };
+ let mut v: serde_json::Value = serde_json::from_str(&text).context("parsing Claude settings")?;
+ let mut removed = 0;
+ if let Some(hooks) = v.get_mut("hooks").and_then(|h| h.as_object_mut()) {
+ for groups in hooks.values_mut() {
+ let Some(groups) = groups.as_array_mut() else { continue };
+ for g in groups.iter_mut() {
+ if let Some(list) = g.get_mut("hooks").and_then(|l| l.as_array_mut()) {
+ let before = list.len();
+ list.retain(|h| !h["command"].as_str().is_some_and(|c| c.ends_with(".codync/notify.sh")));
+ removed += before - list.len();
+ }
+ }
+ groups.retain(|g| g["hooks"].as_array().is_none_or(|l| !l.is_empty()));
+ }
+ hooks.retain(|_, groups| groups.as_array().is_none_or(|g| !g.is_empty()));
+ }
+ if v.get("hooks").and_then(|h| h.as_object()).is_some_and(|h| h.is_empty()) {
+ v.as_object_mut().unwrap().remove("hooks");
+ }
+ if removed > 0 {
+ std::fs::copy(settings, settings.with_extension("json.codync-backup"))?;
+ std::fs::write(settings, serde_json::to_string_pretty(&v)? + "\n")?;
+ }
+ Ok(removed)
+}
+
+#[cfg(test)]
+mod legacy_tests {
+ #[test]
+ fn removes_only_codync_hooks() {
+ let dir = std::env::temp_dir().join(format!("codync-legacy-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let f = dir.join("settings.json");
+ std::fs::write(
+ &f,
+ r#"{"model":"x","hooks":{"Stop":[{"hooks":[{"type":"command","command":"/Users/a/.codync/notify.sh"},{"type":"command","command":"say hi"}]}],"Notification":[{"hooks":[{"type":"command","command":"/Users/a/.codync/notify.sh"}]}]}}"#,
+ )
+ .unwrap();
+ assert_eq!(super::remove_legacy_hooks(&f).unwrap(), 2);
+ let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&f).unwrap()).unwrap();
+ assert_eq!(v["hooks"]["Stop"][0]["hooks"].as_array().unwrap().len(), 1);
+ assert!(v["hooks"].get("Notification").is_none());
+ assert_eq!(v["model"], "x");
+ assert!(dir.join("settings.json.codync-backup").exists());
+ }
+}
diff --git a/host/src/store.rs b/host/src/store.rs
new file mode 100644
index 00000000..b218c158
--- /dev/null
+++ b/host/src/store.rs
@@ -0,0 +1,457 @@
+//! SQLite persistence. Every mutation stamps a global, monotonically increasing
+//! `rev`; clients sync with `since: rev` and never need a separate event log.
+
+use anyhow::Result;
+use rusqlite::{Connection, OptionalExtension, params};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::path::Path;
+use std::sync::Mutex;
+
+#[derive(Serialize, Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct BotConfig {
+ pub id: String,
+ pub name: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default = "default_color")]
+ pub avatar_color: String,
+ /// Grok-Bot-style character shape: blob | pebble | squircle | tablet | wedge | hex | cloud | teardrop.
+ #[serde(default = "default_shape")]
+ pub avatar_shape: String,
+ pub backend: String,
+ #[serde(default)]
+ pub command: Option<String>,
+ pub cwd: String,
+ /// `ask` = every permission request goes to the phone; `auto` = approve once automatically.
+ #[serde(default = "default_permission")]
+ pub permission: String,
+ #[serde(default)]
+ pub model: Option<String>,
+ #[serde(default)]
+ pub pinned: bool,
+ #[serde(default)]
+ pub hidden: bool,
+ #[serde(default)]
+ pub notify: Option<bool>,
+ #[serde(default)]
+ pub created_at: i64,
+}
+
+fn default_color() -> String {
+ "blue".into()
+}
+fn default_shape() -> String {
+ "blob".into()
+}
+fn default_permission() -> String {
+ "ask".into()
+}
+
+#[derive(Serialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct Entry {
+ pub id: String,
+ pub seq: i64,
+ pub bot_id: String,
+ pub rev: i64,
+ pub kind: String,
+ pub turn: i64,
+ pub data: Value,
+ pub created_at: i64,
+ pub updated_at: i64,
+}
+
+pub struct BotRow {
+ pub config: BotConfig,
+ pub rev: i64,
+ pub deleted: bool,
+ pub session_id: Option<String>,
+ pub read_rev: i64,
+}
+
+pub struct Store {
+ db: Mutex<Connection>,
+}
+
+pub fn now_ms() -> i64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_millis() as i64
+}
+
+fn next_rev(c: &Connection) -> Result<i64> {
+ Ok(c.query_row(
+ "INSERT INTO kv(k, v) VALUES('rev', '1') ON CONFLICT(k) DO UPDATE SET v = CAST(v AS INTEGER) + 1 RETURNING CAST(v AS INTEGER)",
+ [],
+ |r| r.get(0),
+ )?)
+}
+
+fn row_entry(r: &rusqlite::Row) -> rusqlite::Result<Entry> {
+ let data: String = r.get(6)?;
+ Ok(Entry {
+ seq: r.get(0)?,
+ id: r.get(1)?,
+ bot_id: r.get(2)?,
+ rev: r.get(3)?,
+ kind: r.get(4)?,
+ turn: r.get(5)?,
+ data: serde_json::from_str(&data).unwrap_or(Value::Null),
+ created_at: r.get(7)?,
+ updated_at: r.get(8)?,
+ })
+}
+
+const ENTRY_COLS: &str = "seq, id, bot_id, rev, kind, turn, data, created_at, updated_at";
+
+impl Store {
+ pub fn open(path: &Path) -> Result<Self> {
+ let c = Connection::open(path)?;
+ c.execute_batch(
+ "PRAGMA journal_mode=WAL;
+ PRAGMA synchronous=NORMAL;
+ CREATE TABLE IF NOT EXISTS kv(k TEXT PRIMARY KEY, v TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS bots(
+ id TEXT PRIMARY KEY, rev INTEGER NOT NULL, deleted INTEGER NOT NULL DEFAULT 0,
+ config TEXT NOT NULL, session_id TEXT, read_rev INTEGER NOT NULL DEFAULT 0);
+ CREATE TABLE IF NOT EXISTS entries(
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL, bot_id TEXT NOT NULL,
+ rev INTEGER NOT NULL, kind TEXT NOT NULL, turn INTEGER NOT NULL, data TEXT NOT NULL,
+ created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
+ CREATE INDEX IF NOT EXISTS entries_rev ON entries(rev);
+ CREATE INDEX IF NOT EXISTS entries_bot ON entries(bot_id, seq);
+ CREATE TABLE IF NOT EXISTS devices(ticket TEXT PRIMARY KEY, name TEXT, created_at INTEGER NOT NULL);",
+ )?;
+ Ok(Self { db: Mutex::new(c) })
+ }
+
+ pub fn kv_get(&self, k: &str) -> Option<String> {
+ let c = self.db.lock().unwrap();
+ c.query_row("SELECT v FROM kv WHERE k = ?", [k], |r| r.get(0))
+ .optional()
+ .ok()
+ .flatten()
+ }
+
+ pub fn kv_set(&self, k: &str, v: &str) -> Result<()> {
+ let c = self.db.lock().unwrap();
+ c.execute(
+ "INSERT INTO kv(k, v) VALUES(?1, ?2) ON CONFLICT(k) DO UPDATE SET v = ?2",
+ params![k, v],
+ )?;
+ Ok(())
+ }
+
+ pub fn current_rev(&self) -> i64 {
+ self.kv_get("rev").and_then(|v| v.parse().ok()).unwrap_or(0)
+ }
+
+ // MARK: bots
+
+ pub fn bots(&self) -> Result<Vec<BotRow>> {
+ let c = self.db.lock().unwrap();
+ let mut st = c.prepare("SELECT config, rev, deleted, session_id, read_rev FROM bots")?;
+ let rows = st
+ .query_map([], |r| {
+ let cfg: String = r.get(0)?;
+ Ok((cfg, r.get(1)?, r.get::<_, i64>(2)? != 0, r.get(3)?, r.get(4)?))
+ })?
+ .filter_map(|r| r.ok())
+ .filter_map(|(cfg, rev, deleted, session_id, read_rev)| {
+ Some(BotRow {
+ config: serde_json::from_str(&cfg).ok()?,
+ rev,
+ deleted,
+ session_id,
+ read_rev,
+ })
+ })
+ .collect();
+ Ok(rows)
+ }
+
+ pub fn bot(&self, id: &str) -> Result<Option<BotRow>> {
+ Ok(self.bots()?.into_iter().find(|b| b.config.id == id))
+ }
+
+ pub fn save_bot(&self, cfg: &BotConfig) -> Result<i64> {
+ let c = self.db.lock().unwrap();
+ let rev = next_rev(&c)?;
+ c.execute(
+ "INSERT INTO bots(id, rev, config) VALUES(?1, ?2, ?3)
+ ON CONFLICT(id) DO UPDATE SET rev = ?2, config = ?3, deleted = 0",
+ params![cfg.id, rev, serde_json::to_string(cfg)?],
+ )?;
+ Ok(rev)
+ }
+
+ pub fn touch_bot(&self, id: &str) -> Result<i64> {
+ let c = self.db.lock().unwrap();
+ let rev = next_rev(&c)?;
+ c.execute("UPDATE bots SET rev = ?2 WHERE id = ?1", params![id, rev])?;
+ Ok(rev)
+ }
+
+ pub fn delete_bot(&self, id: &str) -> Result<i64> {
+ let c = self.db.lock().unwrap();
+ let rev = next_rev(&c)?;
+ c.execute(
+ "UPDATE bots SET rev = ?2, deleted = 1, session_id = NULL WHERE id = ?1",
+ params![id, rev],
+ )?;
+ c.execute("DELETE FROM entries WHERE bot_id = ?1", [id])?;
+ Ok(rev)
+ }
+
+ pub fn set_session(&self, id: &str, session: Option<&str>) -> Result<()> {
+ let c = self.db.lock().unwrap();
+ c.execute("UPDATE bots SET session_id = ?2 WHERE id = ?1", params![id, session])?;
+ Ok(())
+ }
+
+ pub fn mark_read(&self, id: &str) -> Result<i64> {
+ let c = self.db.lock().unwrap();
+ let rev = next_rev(&c)?;
+ c.execute(
+ "UPDATE bots SET read_rev = ?2, rev = ?2 WHERE id = ?1",
+ params![id, rev],
+ )?;
+ Ok(rev)
+ }
+
+ /// Final agent messages + pending permission cards newer than what the user has read.
+ pub fn unread(&self, id: &str, read_rev: i64) -> i64 {
+ let c = self.db.lock().unwrap();
+ c.query_row(
+ "SELECT COUNT(*) FROM entries WHERE bot_id = ?1 AND rev > ?2 AND
+ ((kind = 'agent' AND json_extract(data, '$.final') = 1) OR
+ (kind = 'permission' AND json_extract(data, '$.status') = 'pending'))",
+ params![id, read_rev],
+ |r| r.get(0),
+ )
+ .unwrap_or(0)
+ }
+
+ /// Newest chat-visible line for the roster preview.
+ pub fn last_message(&self, id: &str) -> Option<(String, i64)> {
+ let c = self.db.lock().unwrap();
+ c.query_row(
+ "SELECT kind, data, updated_at FROM entries WHERE bot_id = ?1 AND
+ (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))
+ ORDER BY seq DESC LIMIT 1",
+ [id],
+ |r| {
+ let kind: String = r.get(0)?;
+ let data: String = r.get(1)?;
+ let at: i64 = r.get(2)?;
+ let text = serde_json::from_str::<Value>(&data)
+ .ok()
+ .and_then(|v| v["text"].as_str().map(str::to_owned))
+ .unwrap_or_default();
+ let text = if kind == "user" { format!("You: {text}") } else { text };
+ Ok((text, at))
+ },
+ )
+ .optional()
+ .ok()
+ .flatten()
+ }
+
+ // MARK: entries
+
+ pub fn insert_entry(&self, bot_id: &str, kind: &str, turn: i64, data: &Value) -> Result<Entry> {
+ let c = self.db.lock().unwrap();
+ let rev = next_rev(&c)?;
+ let now = now_ms();
+ let id = uuid::Uuid::new_v4().to_string();
+ c.execute(
+ "INSERT INTO entries(id, bot_id, rev, kind, turn, data, created_at, updated_at)
+ VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)",
+ params![id, bot_id, rev, kind, turn, data.to_string(), now],
+ )?;
+ Ok(Entry {
+ id,
+ seq: c.last_insert_rowid(),
+ bot_id: bot_id.into(),
+ rev,
+ kind: kind.into(),
+ turn,
+ data: data.clone(),
+ created_at: now,
+ updated_at: now,
+ })
+ }
+
+ pub fn update_entry(&self, id: &str, data: &Value) -> Result<Option<Entry>> {
+ let c = self.db.lock().unwrap();
+ let rev = next_rev(&c)?;
+ c.execute(
+ "UPDATE entries SET rev = ?2, data = ?3, updated_at = ?4 WHERE id = ?1",
+ params![id, rev, data.to_string(), now_ms()],
+ )?;
+ Ok(c.query_row(
+ &format!("SELECT {ENTRY_COLS} FROM entries WHERE id = ?1"),
+ [id],
+ row_entry,
+ )
+ .optional()?)
+ }
+
+ pub fn entry(&self, id: &str) -> Option<Entry> {
+ let c = self.db.lock().unwrap();
+ c.query_row(
+ &format!("SELECT {ENTRY_COLS} FROM entries WHERE id = ?1"),
+ [id],
+ row_entry,
+ )
+ .optional()
+ .ok()
+ .flatten()
+ }
+
+ pub fn find_by_nonce(&self, bot_id: &str, nonce: &str) -> Option<Entry> {
+ let c = self.db.lock().unwrap();
+ c.query_row(
+ &format!(
+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND kind = 'user' AND json_extract(data, '$.clientNonce') = ?2"
+ ),
+ params![bot_id, nonce],
+ row_entry,
+ )
+ .optional()
+ .ok()
+ .flatten()
+ }
+
+ pub fn max_turn(&self, bot_id: &str) -> i64 {
+ let c = self.db.lock().unwrap();
+ c.query_row(
+ "SELECT COALESCE(MAX(turn), 0) FROM entries WHERE bot_id = ?1",
+ [bot_id],
+ |r| r.get(0),
+ )
+ .unwrap_or(0)
+ }
+
+ /// Entries changed after `since`. A fresh client (`since == 0`) only gets the
+ /// newest `cap` entries per bot and pages older ones in with `history`.
+ pub fn entries_since(&self, since: i64, cap: i64) -> Result<Vec<Entry>> {
+ let c = self.db.lock().unwrap();
+ let sql = if since == 0 {
+ format!(
+ "SELECT {ENTRY_COLS} FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY bot_id ORDER BY seq DESC) AS rn FROM entries)
+ WHERE rn <= ?2 AND rev > ?1 ORDER BY seq"
+ )
+ } else {
+ format!("SELECT {ENTRY_COLS} FROM entries WHERE rev > ?1 AND ?2 > 0 ORDER BY seq")
+ };
+ let mut st = c.prepare(&sql)?;
+ let rows = st.query_map(params![since, cap], row_entry)?.filter_map(|r| r.ok()).collect();
+ Ok(rows)
+ }
+
+ pub fn history(&self, bot_id: &str, before_seq: i64, limit: i64) -> Result<Vec<Entry>> {
+ let c = self.db.lock().unwrap();
+ let mut st = c.prepare(&format!(
+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq < ?2 ORDER BY seq DESC LIMIT ?3"
+ ))?;
+ let mut rows: Vec<Entry> = st
+ .query_map(params![bot_id, before_seq, limit], row_entry)?
+ .filter_map(|r| r.ok())
+ .collect();
+ rows.reverse();
+ Ok(rows)
+ }
+
+ /// Permission cards left `pending` by a crash or restart can never be answered.
+ pub fn expire_pending(&self) -> Result<Vec<Entry>> {
+ let ids: Vec<String> = {
+ let c = self.db.lock().unwrap();
+ let mut st = c.prepare(
+ "SELECT id FROM entries WHERE (kind = 'permission' AND json_extract(data, '$.status') = 'pending')
+ OR (kind = 'user' AND json_extract(data, '$.status') = 'queued')",
+ )?;
+ st.query_map([], |r| r.get(0))?.filter_map(|r| r.ok()).collect()
+ };
+ let mut out = vec![];
+ for id in ids {
+ if let Some(mut e) = self.entry(&id) {
+ let status = if e.kind == "user" { "failed" } else { "expired" };
+ e.data["status"] = status.into();
+ if let Some(e) = self.update_entry(&id, &e.data)? {
+ out.push(e);
+ }
+ }
+ }
+ Ok(out)
+ }
+
+ // MARK: devices
+
+ pub fn add_device(&self, ticket: &str, name: &str) -> Result<()> {
+ let c = self.db.lock().unwrap();
+ c.execute(
+ "INSERT INTO devices(ticket, name, created_at) VALUES(?1, ?2, ?3)
+ ON CONFLICT(ticket) DO UPDATE SET name = ?2",
+ params![ticket, name, now_ms()],
+ )?;
+ Ok(())
+ }
+
+ pub fn remove_device(&self, ticket: &str) -> Result<()> {
+ self.db.lock().unwrap().execute("DELETE FROM devices WHERE ticket = ?1", [ticket])?;
+ Ok(())
+ }
+
+ pub fn devices(&self) -> Vec<String> {
+ let c = self.db.lock().unwrap();
+ let Ok(mut st) = c.prepare("SELECT ticket FROM devices") else { return vec![] };
+ st.query_map([], |r| r.get(0))
+ .map(|rows| rows.filter_map(|r| r.ok()).collect())
+ .unwrap_or_default()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn rev_sync_and_unread() {
+ let dir = std::env::temp_dir().join(format!("codync-test-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let s = Store::open(&dir.join("t.db")).unwrap();
+ let cfg = BotConfig {
+ id: "b1".into(),
+ name: "Rev".into(),
+ description: String::new(),
+ avatar_color: "blue".into(),
+ avatar_shape: "blob".into(),
+ backend: "claude".into(),
+ command: None,
+ cwd: "/tmp".into(),
+ permission: "ask".into(),
+ model: None,
+ pinned: false,
+ hidden: false,
+ notify: None,
+ created_at: 0,
+ };
+ s.save_bot(&cfg).unwrap();
+ let u = s.insert_entry("b1", "user", 1, &serde_json::json!({"text": "hi"})).unwrap();
+ let a = s.insert_entry("b1", "agent", 1, &serde_json::json!({"text": "yo", "final": false})).unwrap();
+ assert!(a.rev > u.rev);
+ assert_eq!(s.unread("b1", 0), 0, "narration is not unread");
+ let a2 = s.update_entry(&a.id, &serde_json::json!({"text": "yo!", "final": true})).unwrap().unwrap();
+ assert_eq!(s.unread("b1", 0), 1);
+ assert_eq!(s.entries_since(a2.rev - 1, 500).unwrap().len(), 1);
+ assert_eq!(s.entries_since(0, 1).unwrap().len(), 1, "fresh sync is capped per bot");
+ assert_eq!(s.last_message("b1").unwrap().0, "yo!");
+ let r = s.mark_read("b1").unwrap();
+ assert_eq!(s.unread("b1", r), 0);
+ assert_eq!(s.history("b1", a.seq, 10).unwrap().len(), 1);
+ }
+}
diff --git a/host/src/usage.rs b/host/src/usage.rs
new file mode 100644
index 00000000..5d6badba
--- /dev/null
+++ b/host/src/usage.rs
@@ -0,0 +1,236 @@
+//! Subscription usage limits, read on the host only (tokens never leave it).
+//!
+//! Claude: the statusline `rate_limits` payload (documented) when Claude Code
+//! runs, plus the undocumented `/api/oauth/usage` endpoint as a poller using the
+//! token Claude Code already stored. Codex: the newest `rate_limits` event in
+//! `~/.codex/sessions` rollout files.
+
+use crate::hub::Hub;
+use serde_json::{Value, json};
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::time::Duration;
+
+pub fn window(id: &str, label: &str, percent: f64, resets_at_ms: Option<i64>) -> Value {
+ json!({"id": id, "label": label, "percent": percent, "resetsAt": resets_at_ms})
+}
+
+fn provider(id: &str, name: &str, windows: Vec<Value>, source: &str) -> Value {
+ json!({"id": id, "name": name, "windows": windows, "source": source, "updatedAt": crate::store::now_ms()})
+}
+
+fn merge(hub: &Hub, p: Value) {
+ let mut usage = hub.usage.lock().unwrap().clone();
+ let list = usage["providers"].as_array_mut().unwrap();
+ list.retain(|x| x["id"] != p["id"]);
+ list.push(p);
+ list.sort_by_key(|x| x["id"].as_str().unwrap_or_default().to_owned());
+ hub.set_usage(usage);
+}
+
+pub async fn poll(hub: Arc<Hub>) {
+ loop {
+ refresh(&hub).await;
+ tokio::time::sleep(Duration::from_secs(300)).await;
+ }
+}
+
+pub async fn refresh(hub: &Hub) {
+ match claude_oauth_usage().await {
+ Ok(Some(p)) => merge(hub, p),
+ Ok(None) => {}
+ Err(e) => tracing::debug!("claude usage: {e}"),
+ }
+ if let Some(p) = tokio::task::spawn_blocking(codex_usage).await.ok().flatten() {
+ merge(hub, p);
+ }
+}
+
+/// `POST /ingest/statusline` body: Claude Code's statusline JSON.
+pub fn ingest_statusline(hub: &Hub, body: &Value) {
+ let rl = &body["rate_limits"];
+ let mut windows = vec![];
+ for (key, label) in [("five_hour", "5-hour"), ("seven_day", "Weekly")] {
+ if let Some(p) = rl[key]["used_percentage"].as_f64() {
+ windows.push(window(key, label, p, rl[key]["resets_at"].as_i64().map(|s| s * 1000)));
+ }
+ }
+ if !windows.is_empty() {
+ merge(hub, provider("claude", "Claude", windows, "statusline"));
+ }
+}
+
+fn claude_token() -> Option<String> {
+ let raw = if cfg!(target_os = "macos") {
+ let out = std::process::Command::new("security")
+ .args(["find-generic-password", "-s", "Claude Code-credentials", "-w"])
+ .output()
+ .ok()?;
+ String::from_utf8(out.stdout).ok()?
+ } else {
+ std::fs::read_to_string(dirs::home_dir()?.join(".claude/.credentials.json")).ok()?
+ };
+ let v: Value = serde_json::from_str(raw.trim()).ok()?;
+ let oauth = &v["claudeAiOauth"];
+ if oauth["expiresAt"].as_i64().is_some_and(|exp| exp < crate::store::now_ms()) {
+ return None; // Expired: Claude Code refreshes it next time it runs; we never touch credentials.
+ }
+ oauth["accessToken"].as_str().map(str::to_owned)
+}
+
+fn claude_version() -> String {
+ std::process::Command::new("claude")
+ .arg("--version")
+ .output()
+ .ok()
+ .and_then(|o| String::from_utf8(o.stdout).ok())
+ .and_then(|s| s.split_whitespace().next().map(str::to_owned))
+ .unwrap_or_else(|| "2.1.0".into())
+}
+
+async fn claude_oauth_usage() -> anyhow::Result<Option<Value>> {
+ let Some(token) = tokio::task::spawn_blocking(claude_token).await? else { return Ok(None) };
+ let version = tokio::task::spawn_blocking(claude_version).await?;
+ let res: Value = reqwest::Client::new()
+ .get("https://api.anthropic.com/api/oauth/usage")
+ .bearer_auth(token)
+ .header("anthropic-beta", "oauth-2025-04-20")
+ .header("User-Agent", format!("claude-code/{version}"))
+ .timeout(Duration::from_secs(15))
+ .send()
+ .await?
+ .error_for_status()?
+ .json()
+ .await?;
+ Ok(Some(provider("claude", "Claude", parse_claude(&res), "oauth")))
+}
+
+pub fn parse_claude(res: &Value) -> Vec<Value> {
+ let labels = [
+ ("five_hour", "5-hour"),
+ ("seven_day", "Weekly"),
+ ("seven_day_opus", "Weekly · Opus"),
+ ("seven_day_sonnet", "Weekly · Sonnet"),
+ ];
+ labels
+ .iter()
+ .filter_map(|(k, label)| {
+ let w = &res[*k];
+ let pct = w["utilization"].as_f64()?;
+ let resets = w["resets_at"].as_str().and_then(parse_rfc3339_ms);
+ Some(window(k, label, pct, resets))
+ })
+ .collect()
+}
+
+/// Minimal RFC 3339 → epoch ms (UTC offsets supported), avoiding a date crate.
+pub fn parse_rfc3339_ms(s: &str) -> Option<i64> {
+ let (date, time) = s.split_once('T')?;
+ let mut d = date.split('-').map(|x| x.parse::<i64>());
+ let (y, m, day) = (d.next()?.ok()?, d.next()?.ok()?, d.next()?.ok()?);
+ let (clock, offset_min) = if let Some(c) = time.strip_suffix('Z') {
+ (c, 0)
+ } else {
+ let idx = time.rfind(['+', '-'])?;
+ let (c, off) = time.split_at(idx);
+ let sign = if off.starts_with('-') { -1 } else { 1 };
+ let mut o = off[1..].split(':');
+ let oh: i64 = o.next()?.parse().ok()?;
+ let om: i64 = o.next().unwrap_or("0").parse().ok()?;
+ (c, sign * (oh * 60 + om))
+ };
+ let mut c = clock.split(':');
+ let (h, mi) = (c.next()?.parse::<i64>().ok()?, c.next()?.parse::<i64>().ok()?);
+ let sec: f64 = c.next().unwrap_or("0").parse().ok()?;
+ // Days from civil (Howard Hinnant).
+ let y2 = if m <= 2 { y - 1 } else { y };
+ let era = y2.div_euclid(400);
+ let yoe = y2 - era * 400;
+ let mp = (m + 9) % 12;
+ let doy = (153 * mp + 2) / 5 + day - 1;
+ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
+ let days = era * 146_097 + doe - 719_468;
+ let secs = days * 86_400 + h * 3600 + mi * 60 - offset_min * 60;
+ Some(secs * 1000 + (sec * 1000.0) as i64)
+}
+
+fn newest_rollout(root: &Path) -> Option<PathBuf> {
+ // sessions/YYYY/MM/DD/rollout-*.jsonl — descend into the lexicographically largest dir each level.
+ let mut dir = root.to_path_buf();
+ for _ in 0..3 {
+ let mut subs: Vec<PathBuf> = std::fs::read_dir(&dir).ok()?.filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.is_dir()).collect();
+ subs.sort();
+ dir = subs.pop()?;
+ }
+ std::fs::read_dir(&dir)
+ .ok()?
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|x| x == "jsonl"))
+ .max_by_key(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
+}
+
+fn codex_usage() -> Option<Value> {
+ let path = newest_rollout(&dirs::home_dir()?.join(".codex/sessions"))?;
+ let text = std::fs::read_to_string(&path).ok()?;
+ let line = text.lines().rev().find(|l| l.contains("\"rate_limits\""))?;
+ let v: Value = serde_json::from_str(line).ok()?;
+ let rl = if v["payload"]["rate_limits"].is_object() { &v["payload"]["rate_limits"] } else { &v["rate_limits"] };
+ let modified_ms = std::fs::metadata(&path)
+ .and_then(|m| m.modified())
+ .ok()
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_millis() as i64)
+ .unwrap_or(0);
+ let windows = parse_codex(rl, modified_ms);
+ (!windows.is_empty()).then(|| provider("codex", "Codex", windows, "sessions"))
+}
+
+pub fn parse_codex(rl: &Value, observed_ms: i64) -> Vec<Value> {
+ ["primary", "secondary"]
+ .iter()
+ .filter_map(|k| {
+ let w = &rl[*k];
+ let pct = w["used_percent"].as_f64()?;
+ let minutes = w["window_minutes"].as_i64().unwrap_or(0);
+ let label = match minutes {
+ 300 => "5-hour".to_owned(),
+ 10080 => "Weekly".to_owned(),
+ m if m > 0 && m % 1440 == 0 => format!("{}-day", m / 1440),
+ m if m > 0 => format!("{}-hour", m / 60),
+ _ => (*k).to_owned(),
+ };
+ let resets = w["resets_at"]
+ .as_i64()
+ .map(|s| s * 1000)
+ .or_else(|| w["resets_in_seconds"].as_i64().map(|s| observed_ms + s * 1000));
+ Some(window(k, &label, pct, resets))
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_claude_and_codex_shapes() {
+ let c = parse_claude(&json!({
+ "five_hour": {"utilization": 12.0, "resets_at": "2026-09-25T10:00:00+00:00"},
+ "seven_day": {"utilization": 55.5, "resets_at": "2026-09-25T10:00:00.500Z"},
+ "seven_day_opus": null
+ }));
+ assert_eq!(c.len(), 2);
+ assert_eq!(c[0]["resetsAt"], 1_790_330_400_000i64);
+ assert_eq!(c[1]["resetsAt"], 1_790_330_400_500i64);
+ let x = parse_codex(
+ &json!({"primary": {"used_percent": 3.0, "window_minutes": 300, "resets_in_seconds": 10},
+ "secondary": {"used_percent": 40.0, "window_minutes": 10080, "resets_at": 100}}),
+ 1000,
+ );
+ assert_eq!(x[0]["label"], "5-hour");
+ assert_eq!(x[0]["resetsAt"], 11_000);
+ assert_eq!(x[1]["resetsAt"], 100_000);
+ assert_eq!(parse_rfc3339_ms("1970-01-01T01:00:00+01:00"), Some(0));
+ }
+}
diff --git a/packaging/homebrew/codync-host.rb b/packaging/homebrew/codync-host.rb
new file mode 100644
index 00000000..e54db07c
--- /dev/null
+++ b/packaging/homebrew/codync-host.rb
@@ -0,0 +1,49 @@
+# Homebrew formula for the leepokai/homebrew-codync tap.
+# After tagging `host-vX.Y.Z`, update `version` and the four sha256 values from the
+# release's *.sha256 files, then copy this file to Formula/codync-host.rb in the tap.
+class CodyncHost < Formula
+ desc "Runs your coding-agent bots (Claude Code, Codex, OpenCode…) for the Codync app"
+ homepage "https://github.com/leepokai/Codync"
+ version "2.0.0"
+ license "MIT"
+
+ base = "https://github.com/leepokai/Codync/releases/download/host-v#{version}/codync-host-#{version}"
+
+ on_macos do
+ on_arm do
+ url "#{base}-aarch64-apple-darwin.tar.gz"
+ sha256 "REPLACE_WITH_SHA256"
+ end
+ on_intel do
+ url "#{base}-x86_64-apple-darwin.tar.gz"
+ sha256 "REPLACE_WITH_SHA256"
+ end
+ end
+
+ on_linux do
+ on_arm do
+ url "#{base}-aarch64-unknown-linux-gnu.tar.gz"
+ sha256 "REPLACE_WITH_SHA256"
+ end
+ on_intel do
+ url "#{base}-x86_64-unknown-linux-gnu.tar.gz"
+ sha256 "REPLACE_WITH_SHA256"
+ end
+ end
+
+ def install
+ bin.install "codync-host"
+ end
+
+ def caveats
+ <<~EOS
+ Start the host in the background and pair your iPhone:
+ codync-host install
+ codync-host pair
+ EOS
+ end
+
+ test do
+ assert_match version.to_s, shell_output("#{bin}/codync-host --version")
+ end
+end
diff --git a/project.yml b/project.yml
new file mode 100644
index 00000000..a4664709
--- /dev/null
+++ b/project.yml
@@ -0,0 +1,120 @@
+# Generate the Xcode project with: xcodegen generate
+name: Codync
+options:
+ bundleIdPrefix: com.pokai
+ deploymentTarget:
+ iOS: "18.0"
+ macOS: "14.0"
+ createIntermediateGroups: true
+packages:
+ CodyncKit:
+ path: CodyncKit
+settings:
+ base:
+ MARKETING_VERSION: 2.0.0
+ CURRENT_PROJECT_VERSION: 17
+ SWIFT_VERSION: "6.0"
+ SWIFT_STRICT_CONCURRENCY: complete
+ CODE_SIGN_STYLE: Automatic
+ DEAD_CODE_STRIPPING: YES
+ ENABLE_USER_SCRIPT_SANDBOXING: NO
+targets:
+ Codync-macOS:
+ type: application
+ platform: macOS
+ sources:
+ - Codync-macOS
+ dependencies:
+ - package: CodyncKit
+ settings:
+ base:
+ PRODUCT_NAME: Codync
+ PRODUCT_BUNDLE_IDENTIFIER: com.pokai.Codync
+ GENERATE_INFOPLIST_FILE: YES
+ INFOPLIST_KEY_LSUIElement: YES
+ INFOPLIST_KEY_CFBundleDisplayName: Codync
+ INFOPLIST_KEY_LSApplicationCategoryType: public.app-category.developer-tools
+ INFOPLIST_KEY_NSHumanReadableCopyright: ""
+ ENABLE_HARDENED_RUNTIME: YES
+ ENABLE_APP_SANDBOX: NO
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
+ postBuildScripts:
+ - name: Embed codync-host
+ basedOnDependencyAnalysis: false
+ showEnvVars: false
+ script: |
+ # Builds the Rust host and ships it inside Codync.app/Contents/MacOS.
+ export PATH="$HOME/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"
+ if ! command -v cargo >/dev/null; then
+ echo "warning: cargo not found; Codync.app will look for codync-host on PATH instead"
+ exit 0
+ fi
+ PROFILE=release
+ [ "$CONFIGURATION" = "Debug" ] && PROFILE=debug
+ FLAGS=""
+ [ "$PROFILE" = "release" ] && FLAGS="--release"
+ if [ "$PROFILE" = "release" ]; then
+ rustup target add aarch64-apple-darwin x86_64-apple-darwin >/dev/null 2>&1 || true
+ cargo build --release --manifest-path "$SRCROOT/host/Cargo.toml" --target aarch64-apple-darwin &&
+ cargo build --release --manifest-path "$SRCROOT/host/Cargo.toml" --target x86_64-apple-darwin &&
+ lipo -create -output "$SRCROOT/host/target/codync-host-universal" \
+ "$SRCROOT/host/target/aarch64-apple-darwin/release/codync-host" \
+ "$SRCROOT/host/target/x86_64-apple-darwin/release/codync-host" &&
+ BIN="$SRCROOT/host/target/codync-host-universal" ||
+ { cargo build --release --manifest-path "$SRCROOT/host/Cargo.toml" && BIN="$SRCROOT/host/target/release/codync-host"; }
+ else
+ cargo build --manifest-path "$SRCROOT/host/Cargo.toml" && BIN="$SRCROOT/host/target/debug/codync-host"
+ fi
+ DEST="$TARGET_BUILD_DIR/$EXECUTABLE_FOLDER_PATH/codync-host"
+ cp "$BIN" "$DEST"
+ if [ -n "$EXPANDED_CODE_SIGN_IDENTITY" ] && [ "$CODE_SIGNING_ALLOWED" != "NO" ]; then
+ codesign --force --options runtime --timestamp=none --sign "$EXPANDED_CODE_SIGN_IDENTITY" "$DEST"
+ fi
+ Codync-iOS:
+ type: application
+ platform: iOS
+ sources:
+ - Codync-iOS
+ dependencies:
+ - package: CodyncKit
+ - target: CodyncWidgets
+ embed: true
+ settings:
+ base:
+ PRODUCT_NAME: Codync
+ PRODUCT_BUNDLE_IDENTIFIER: com.pokai.Codync.ios
+ INFOPLIST_FILE: Codync-iOS/Info.plist
+ GENERATE_INFOPLIST_FILE: YES
+ CODE_SIGN_ENTITLEMENTS: Codync-iOS/Codync-iOS.entitlements
+ TARGETED_DEVICE_FAMILY: "1,2"
+ INFOPLIST_KEY_CFBundleDisplayName: Codync
+ INFOPLIST_KEY_LSApplicationCategoryType: public.app-category.developer-tools
+ INFOPLIST_KEY_ITSAppUsesNonExemptEncryption: NO
+ INFOPLIST_KEY_UILaunchScreen_Generation: YES
+ INFOPLIST_KEY_UIApplicationSceneManifest_Generation: YES
+ INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents: YES
+ INFOPLIST_KEY_NSSupportsLiveActivities: YES
+ INFOPLIST_KEY_NSCameraUsageDescription: Scan the pairing code shown on your computer.
+ INFOPLIST_KEY_NSLocalNetworkUsageDescription: Codync connects to the computer running your bots on your local network.
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone: UIInterfaceOrientationPortrait
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad: "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
+ CodyncWidgets:
+ type: app-extension
+ platform: iOS
+ sources:
+ - CodyncWidgets
+ dependencies:
+ - package: CodyncKit
+ - sdk: WidgetKit.framework
+ - sdk: SwiftUI.framework
+ settings:
+ base:
+ PRODUCT_NAME: CodyncWidgets
+ PRODUCT_BUNDLE_IDENTIFIER: com.pokai.Codync.ios.LiveActivity
+ INFOPLIST_FILE: CodyncWidgets/Info.plist
+ GENERATE_INFOPLIST_FILE: YES
+ CODE_SIGN_ENTITLEMENTS: CodyncWidgets/CodyncWidgets.entitlements
+ INFOPLIST_KEY_CFBundleDisplayName: Codync
+ TARGETED_DEVICE_FAMILY: "1,2"
+ SKIP_INSTALL: YES
diff --git a/worker/.gitignore b/relay/.gitignore
similarity index 100%
rename from worker/.gitignore
rename to relay/.gitignore
diff --git a/relay/README.md b/relay/README.md
new file mode 100644
index 00000000..6a42da6c
--- /dev/null
+++ b/relay/README.md
@@ -0,0 +1,28 @@
+# Codync relay
+
+Cloudflare Worker that holds the APNs key and forwards pushes for codync-host.
+The phone exchanges its APNs token for an AES-GCM **ticket** (`POST /register`);
+hosts only ever see tickets (`POST /push`). A ticket is useless without the
+worker's `TICKET_KEY`, and it only reaches the one device it was issued for.
+
+## Deploy
+
+```bash
+npm install
+npx wrangler secret put APNS_TEAM_ID # Apple Developer team ID
+npx wrangler secret put APNS_KEY_ID # e.g. the ID in AuthKey_XXXXXXXXXX.p8
+npx wrangler secret put APNS_SIGNING_KEY # contents of the .p8 file
+openssl rand -base64 32 | npx wrangler secret put TICKET_KEY
+npm run deploy
+```
+
+It deploys as `codync-relay` (the 1.x `codync-push` worker keeps serving old
+installs). The iOS app points at `SharedStore.relayURL` in `CodyncKit`.
+Rotating `TICKET_KEY` invalidates every ticket; phones re-register on launch.
+
+## Test
+
+```bash
+npm test # ticket seal/open round trip
+npm run typecheck
+```
diff --git a/worker/package-lock.json b/relay/package-lock.json
similarity index 99%
rename from worker/package-lock.json
rename to relay/package-lock.json
index 47ebff18..30b5f498 100644
--- a/worker/package-lock.json
+++ b/relay/package-lock.json
@@ -1,11 +1,11 @@
{
- "name": "worker",
+ "name": "codync-relay",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
- "name": "worker",
+ "name": "codync-relay",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
diff --git a/worker/package.json b/relay/package.json
similarity index 52%
rename from worker/package.json
rename to relay/package.json
index 59b26eab..c876e566 100644
--- a/worker/package.json
+++ b/relay/package.json
@@ -1,10 +1,12 @@
{
- "name": "worker",
+ "name": "codync-relay",
"version": "1.0.0",
- "description": "",
- "main": "index.js",
+ "description": "Codync APNs push relay (Cloudflare Worker)",
+ "main": "src/index.ts",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
+ "deploy": "wrangler deploy",
+ "typecheck": "tsc",
+ "test": "node --experimental-strip-types --no-warnings test/ticket.test.ts"
},
"keywords": [],
"author": "",
@@ -16,5 +18,6 @@
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20260317.1"
- }
+ },
+ "private": true
}
diff --git a/relay/src/index.ts b/relay/src/index.ts
new file mode 100644
index 00000000..3521b024
--- /dev/null
+++ b/relay/src/index.ts
@@ -0,0 +1,157 @@
+// Codync push relay.
+//
+// The APNs key lives only here. The phone registers its device (or Live
+// Activity) token and gets back an opaque, encrypted *ticket*; it hands the
+// ticket to its own codync-host, which can then ask the relay to push to that
+// one device — without ever learning the raw token or holding a shared secret.
+//
+// POST /register { token, env: "sandbox" | "production", kind: "alert" | "liveactivity" } -> { ticket }
+// POST /push { ticket, alert?: { title, body }, threadId?, category?, data?,
+// liveActivity?: { event: "update" | "end", contentState } }
+
+import { ApnsClient, Notification, PushType, Priority } from "@fivesheepco/cloudflare-apns2";
+
+export interface Env {
+ APNS_TEAM_ID: string;
+ APNS_KEY_ID: string;
+ APNS_SIGNING_KEY: string;
+ /** base64 of 32 random bytes: `openssl rand -base64 32` */
+ TICKET_KEY: string;
+}
+
+type ApnsEnv = "sandbox" | "production";
+type Kind = "alert" | "liveactivity";
+interface TicketPayload { t: string; e: ApnsEnv; k: Kind }
+
+const BUNDLE_ID = "com.pokai.Codync.ios";
+
+// ---- tickets (AES-GCM, key from TICKET_KEY) ----
+
+const b64url = (bytes: Uint8Array) =>
+ btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+
+const fromB64url = (s: string) => {
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4);
+ return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
+};
+
+let cachedKey: { raw: string; key: CryptoKey } | null = null;
+
+async function ticketKey(env: Env): Promise<CryptoKey> {
+ if (cachedKey?.raw === env.TICKET_KEY) return cachedKey.key;
+ const raw = Uint8Array.from(atob(env.TICKET_KEY), (c) => c.charCodeAt(0));
+ const key = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]);
+ cachedKey = { raw: env.TICKET_KEY, key };
+ return key;
+}
+
+export async function sealTicket(env: Env, p: TicketPayload): Promise<string> {
+ const iv = crypto.getRandomValues(new Uint8Array(12));
+ const ct = new Uint8Array(
+ await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await ticketKey(env), new TextEncoder().encode(JSON.stringify(p))),
+ );
+ const out = new Uint8Array(iv.length + ct.length);
+ out.set(iv);
+ out.set(ct, iv.length);
+ return b64url(out);
+}
+
+export async function openTicket(env: Env, ticket: string): Promise<TicketPayload | null> {
+ try {
+ const bytes = fromB64url(ticket);
+ const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, await ticketKey(env), bytes.slice(12));
+ return JSON.parse(new TextDecoder().decode(pt)) as TicketPayload;
+ } catch {
+ return null;
+ }
+}
+
+// ---- APNs clients, cached per isolate (JWT reused while valid) ----
+
+const clients = new Map<string, ApnsClient>();
+
+function client(env: Env, apnsEnv: ApnsEnv, kind: Kind): ApnsClient {
+ const id = `${env.APNS_KEY_ID}:${apnsEnv}:${kind}`;
+ let c = clients.get(id);
+ if (!c) {
+ c = new ApnsClient({
+ team: env.APNS_TEAM_ID,
+ keyId: env.APNS_KEY_ID,
+ signingKey: env.APNS_SIGNING_KEY.replace(/\\n/g, "\n"),
+ defaultTopic: kind === "liveactivity" ? `${BUNDLE_ID}.push-type.liveactivity` : BUNDLE_ID,
+ host: apnsEnv === "production" ? "api.push.apple.com" : "api.sandbox.push.apple.com",
+ });
+ clients.set(id, c);
+ }
+ return c;
+}
+
+const json = (body: unknown, status = 200) => Response.json(body, { status });
+
+async function register(req: Request, env: Env): Promise<Response> {
+ const body = (await req.json().catch(() => null)) as { token?: string; env?: string; kind?: string } | null;
+ if (!body?.token || !/^[0-9a-fA-F]{32,200}$/.test(body.token)) return json({ error: "invalid token" }, 400);
+ const e: ApnsEnv = body.env === "production" ? "production" : "sandbox";
+ const k: Kind = body.kind === "liveactivity" ? "liveactivity" : "alert";
+ return json({ ticket: await sealTicket(env, { t: body.token, e, k }) });
+}
+
+interface PushBody {
+ ticket?: string;
+ alert?: { title?: string; body?: string };
+ threadId?: string;
+ category?: string;
+ data?: Record<string, unknown>;
+ liveActivity?: { event?: "update" | "end"; contentState?: Record<string, unknown> };
+}
+
+async function push(req: Request, env: Env): Promise<Response> {
+ const body = (await req.json().catch(() => null)) as PushBody | null;
+ const t = body?.ticket ? await openTicket(env, body.ticket) : null;
+ if (!body || !t) return json({ error: "invalid ticket" }, 403);
+ // ponytail: no per-ticket rate limit; add a Durable Object counter if tickets get abused.
+ try {
+ if (t.k === "alert") {
+ if (!body.alert) return json({ error: "alert required" }, 400);
+ await client(env, t.e, "alert").send(
+ new Notification(t.t, {
+ type: PushType.alert,
+ priority: Priority.immediate,
+ aps: {
+ alert: { title: (body.alert.title ?? "Codync").slice(0, 120), body: (body.alert.body ?? "").slice(0, 400) },
+ sound: "default",
+ "thread-id": body.threadId,
+ category: body.category,
+ },
+ data: body.data ?? {},
+ }),
+ );
+ } else {
+ const la = body.liveActivity;
+ if (!la) return json({ error: "liveActivity required" }, 400);
+ const now = Math.floor(Date.now() / 1000);
+ const aps: Record<string, unknown> = { timestamp: now, event: la.event ?? "update", "content-state": la.contentState ?? {} };
+ if (la.event === "end") aps["dismissal-date"] = now + 60;
+ await client(env, t.e, "liveactivity").send(
+ new Notification(t.t, { type: PushType.liveactivity, priority: Priority.immediate, aps }),
+ );
+ }
+ return json({ ok: true });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ // 410 Unregistered / BadDeviceToken: tell the host to drop the ticket.
+ const gone = /Unregistered|BadDeviceToken|ExpiredToken/.test(message);
+ return json({ error: message, gone }, gone ? 410 : 502);
+ }
+}
+
+export default {
+ async fetch(req: Request, env: Env): Promise<Response> {
+ const { pathname } = new URL(req.url);
+ if (req.method === "GET" && pathname === "/health") return json({ ok: true });
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
+ if (pathname === "/register") return register(req, env);
+ if (pathname === "/push") return push(req, env);
+ return json({ error: "not found" }, 404);
+ },
+};
diff --git a/relay/test/ticket.test.ts b/relay/test/ticket.test.ts
new file mode 100644
index 00000000..3c319546
--- /dev/null
+++ b/relay/test/ticket.test.ts
@@ -0,0 +1,12 @@
+// Ticket round-trip: sealed tickets open with the same key and fail with another.
+import assert from "node:assert/strict";
+import { sealTicket, openTicket } from "../src/index.ts";
+
+const key = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))));
+const env = { TICKET_KEY: key } as any;
+const ticket = await sealTicket(env, { t: "ab".repeat(32), e: "sandbox", k: "alert" });
+assert.deepEqual(await openTicket(env, ticket), { t: "ab".repeat(32), e: "sandbox", k: "alert" });
+const other = { TICKET_KEY: btoa(String.fromCharCode(...new Uint8Array(32))) } as any;
+assert.equal(await openTicket(other, ticket), null);
+assert.equal(await openTicket(env, ticket.slice(0, -2) + "AA"), null);
+console.log("ticket tests ok");
diff --git a/worker/tsconfig.json b/relay/tsconfig.json
similarity index 100%
rename from worker/tsconfig.json
rename to relay/tsconfig.json
diff --git a/worker/wrangler.toml b/relay/wrangler.toml
similarity index 81%
rename from worker/wrangler.toml
rename to relay/wrangler.toml
index 282003b0..8491eeb8 100644
--- a/worker/wrangler.toml
+++ b/relay/wrangler.toml
@@ -1,4 +1,4 @@
-name = "codync-push"
+name = "codync-relay"
main = "src/index.ts"
compatibility_date = "2024-09-23"
compatibility_flags = ["nodejs_compat"]
diff --git a/worker/src/index.ts b/worker/src/index.ts
deleted file mode 100644
index 1d247732..00000000
--- a/worker/src/index.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { ApnsClient, Notification, PushType, Priority } from "@fivesheepco/cloudflare-apns2";
-
-export interface Env {
- APNS_TEAM_ID: string;
- APNS_KEY_ID: string;
- APNS_SIGNING_KEY: string;
- API_SECRET: string;
-}
-
-interface PushRequest {
- pushToken: string;
- event?: "update" | "end";
- contentState?: Record<string, unknown>;
- // Alert push fields
- type?: "liveactivity" | "alert";
- title?: string;
- body?: string;
-}
-
-// Cache ApnsClient instances at module level — reuses JWT token across requests
-// within the same Worker isolate (token valid 20-60 min per Apple docs)
-let cachedAlertClient: ApnsClient | null = null;
-let cachedLiveActivityClient: ApnsClient | null = null;
-let cachedEnvHash: string | null = null;
-
-function getClients(env: Env): { alertClient: ApnsClient; liveActivityClient: ApnsClient } {
- const envHash = `${env.APNS_TEAM_ID}:${env.APNS_KEY_ID}`;
- if (cachedAlertClient && cachedLiveActivityClient && cachedEnvHash === envHash) {
- return { alertClient: cachedAlertClient, liveActivityClient: cachedLiveActivityClient };
- }
-
- const signingKey = env.APNS_SIGNING_KEY.replace(/\\n/g, "\n");
- const bundleId = "com.pokai.Codync.ios";
-
- cachedAlertClient = new ApnsClient({
- team: env.APNS_TEAM_ID,
- keyId: env.APNS_KEY_ID,
- signingKey,
- defaultTopic: bundleId,
- host: "api.sandbox.push.apple.com",
- });
-
- cachedLiveActivityClient = new ApnsClient({
- team: env.APNS_TEAM_ID,
- keyId: env.APNS_KEY_ID,
- signingKey,
- defaultTopic: `${bundleId}.push-type.liveactivity`,
- host: "api.sandbox.push.apple.com",
- });
-
- cachedEnvHash = envHash;
- return { alertClient: cachedAlertClient, liveActivityClient: cachedLiveActivityClient };
-}
-
-export default {
- async fetch(request: Request, env: Env): Promise<Response> {
- if (request.method !== "POST") {
- return new Response("Method not allowed", { status: 405 });
- }
-
- const auth = request.headers.get("Authorization");
- if (auth !== `Bearer ${env.API_SECRET}`) {
- return new Response("Unauthorized", { status: 401 });
- }
-
- let body: PushRequest;
- try {
- body = await request.json() as PushRequest;
- } catch {
- return new Response("Invalid JSON", { status: 400 });
- }
-
- if (!body.pushToken) {
- return new Response("Missing pushToken", { status: 400 });
- }
-
- const { alertClient, liveActivityClient } = getClients(env);
- const pushType = body.type ?? "liveactivity";
-
- if (pushType === "alert") {
- // Regular alert notification (e.g., session completed)
- const notification = new Notification(body.pushToken, {
- type: PushType.alert,
- priority: Priority.immediate,
- aps: {
- alert: {
- title: body.title ?? "Codync",
- body: body.body ?? "",
- },
- sound: "default",
- },
- });
-
- try {
- await alertClient.send(notification);
- return Response.json({ success: true });
- } catch (err: unknown) {
- const message = err instanceof Error ? err.message : String(err);
- console.error("APNs alert error:", message);
- return Response.json({ success: false, error: message }, { status: 502 });
- }
- }
-
- // Live Activity push
- const event = body.event ?? "update";
-
- const aps: Record<string, unknown> = {
- timestamp: Math.floor(Date.now() / 1000),
- event,
- };
-
- if (event === "update" && body.contentState) {
- aps["content-state"] = body.contentState;
- }
-
- if (event === "end") {
- aps["dismissal-date"] = Math.floor(Date.now() / 1000);
- }
-
- const notification = new Notification(body.pushToken, {
- type: PushType.liveactivity,
- priority: Priority.throttled,
- aps,
- });
-
- try {
- await liveActivityClient.send(notification);
- return Response.json({ success: true });
- } catch (err: unknown) {
- const message = err instanceof Error ? err.message : String(err);
- console.error("APNs error:", message);
- return Response.json({ success: false, error: message }, { status: 502 });
- }
- },
-};