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.

Auto-detect coding agents, native Mac chat window, local usage limits

leepokaib2a3e03d1afc
diff --git a/Codync-iOS/App/CodyncApp.swift b/Codync-iOS/App/CodyncApp.swift
index 7420c79f..6d6c83f0 100644
--- a/Codync-iOS/App/CodyncApp.swift
+++ b/Codync-iOS/App/CodyncApp.swift
@@ -1,25 +1,25 @@
import CodyncKit
+import CodyncUI
import SwiftUI
import UserNotifications
+import WidgetKit
@main
struct CodyncApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) private var delegate
- @State private var model = AppModel()
- @State private var router = Router.shared
+ @State private var model = AppStore.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)
+ model.selection = url.lastPathComponent
}
}
.onChange(of: scenePhase, initial: true) { _, phase in
@@ -37,15 +37,20 @@ struct CodyncApp: App {
}
}
+/// The phone's store, wired to push registration, Live Activities and widgets.
@MainActor
-@Observable
-final class Router {
- static let shared = Router()
- var path: [String] = []
-
- func open(botId: String) {
- path = [botId]
- }
+enum AppStore {
+ static let shared: BotStore = {
+ let store = BotStore(pairing: SharedStore.pairing, clientKind: "ios", persistsPairing: true)
+ store.onPaired = { PushRegistrar.shared.syncDevice(with: $0) }
+ store.onBotUpdated = { LiveActivities.shared.update(bot: $0) }
+ store.onSent = { LiveActivities.shared.start(for: $0, model: store) }
+ store.onUsageChanged = { usage in
+ SharedStore.usage = usage
+ WidgetCenter.shared.reloadAllTimelines()
+ }
+ return store
+ }()
}
final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
@@ -61,7 +66,7 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
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) }
+ await MainActor.run { AppStore.shared.selection = botId }
}
}
diff --git a/Codync-iOS/App/Push.swift b/Codync-iOS/App/Push.swift
index 59ce47ce..94b2ca15 100644
--- a/Codync-iOS/App/Push.swift
+++ b/Codync-iOS/App/Push.swift
@@ -1,5 +1,6 @@
import ActivityKit
import CodyncKit
+import CodyncUI
import Foundation
import UIKit
import UserNotifications
@@ -33,7 +34,7 @@ final class PushRegistrar {
static let shared = PushRegistrar()
private var deviceToken: Data?
- private weak var model: AppModel?
+ private weak var model: BotStore?
func requestAuthorization() async -> Bool {
let granted = (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])) ?? false
@@ -47,7 +48,7 @@ final class PushRegistrar {
}
/// Sends our ticket to the host whenever we have both a token and a pairing.
- func syncDevice(with model: AppModel) {
+ func syncDevice(with model: BotStore) {
self.model = model
guard let token = deviceToken else {
Task {
@@ -78,7 +79,7 @@ final class LiveActivities {
Activity<BotActivityAttributes>.activities.first { $0.attributes.botId == botId }
}
- func start(for bot: Bot, model: AppModel) {
+ func start(for bot: Bot, model: BotStore) {
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) }
diff --git a/Codync-iOS/Views/BotListView.swift b/Codync-iOS/Views/BotListView.swift
index 5b1ad815..22f7770d 100644
--- a/Codync-iOS/Views/BotListView.swift
+++ b/Codync-iOS/Views/BotListView.swift
@@ -1,9 +1,10 @@
import CodyncKit
+import CodyncUI
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
+ @Environment(BotStore.self) private var model
@State private var editing: EditorRequest?
@State private var showSettings = false
@State private var confirmDelete: Bot?
@@ -92,74 +93,6 @@ struct BotListView: View {
}
}
-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
@@ -181,26 +114,3 @@ private struct EmptyRoster: View {
}
}
-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/PairingView.swift b/Codync-iOS/Views/PairingView.swift
index b1a3cd5f..240298bd 100644
--- a/Codync-iOS/Views/PairingView.swift
+++ b/Codync-iOS/Views/PairingView.swift
@@ -1,10 +1,11 @@
import CodyncKit
+import CodyncUI
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
+ @Environment(BotStore.self) private var model
@State private var scanning = false
@State private var pasted = ""
@State private var error: String?
diff --git a/Codync-iOS/Views/RootView.swift b/Codync-iOS/Views/RootView.swift
index 35e17fc5..fbeb3928 100644
--- a/Codync-iOS/Views/RootView.swift
+++ b/Codync-iOS/Views/RootView.swift
@@ -1,17 +1,21 @@
import CodyncKit
+import CodyncUI
import SwiftUI
struct RootView: View {
- @Environment(AppModel.self) private var model
- @Environment(Router.self) private var router
+ @Environment(BotStore.self) private var model
+
+ /// The open bot, as a NavigationStack path.
+ private var path: Binding<[String]> {
+ Binding(get: { model.selection.map { [$0] } ?? [] }, set: { model.selection = $0.last })
+ }
var body: some View {
- @Bindable var router = router
Group {
if model.pairing == nil {
PairingView()
} else {
- NavigationStack(path: $router.path) {
+ NavigationStack(path: path) {
BotListView()
.navigationDestination(for: String.self) { botId in
ThreadView(botId: botId)
diff --git a/Codync-iOS/Views/SettingsView.swift b/Codync-iOS/Views/SettingsView.swift
index 7400c964..51073ffe 100644
--- a/Codync-iOS/Views/SettingsView.swift
+++ b/Codync-iOS/Views/SettingsView.swift
@@ -1,9 +1,10 @@
import CodyncKit
+import CodyncUI
import SwiftUI
import UserNotifications
struct SettingsView: View {
- @Environment(AppModel.self) private var model
+ @Environment(BotStore.self) private var model
@Environment(\.dismiss) private var dismiss
@State private var notificationsAllowed: Bool?
@State private var confirmUnpair = false
@@ -101,79 +102,3 @@ struct SettingsView: View {
}
}
-struct UsageCard: View {
- let provider: UsageProvider
-
- var body: some View {
- VStack(alignment: .leading, spacing: 8) {
- HStack {
- Text(provider.name).font(.subheadline.bold())
- Spacer()
- 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)
- }
- }
- }
- .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
-
- 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))
- }
- }
- }
- }
- }
-}
diff --git a/Codync-macOS/ChatWindow.swift b/Codync-macOS/ChatWindow.swift
new file mode 100644
index 00000000..9757c1a3
--- /dev/null
+++ b/Codync-macOS/ChatWindow.swift
@@ -0,0 +1,103 @@
+import CodyncKit
+import CodyncUI
+import SwiftUI
+
+/// Native desktop chat: roster on the left, the conversation on the right
+/// (Grok Bot's desktop layout), sharing its views with the iPhone app.
+struct ChatWindow: View {
+ @Environment(HostController.self) private var host
+
+ var body: some View {
+ Group {
+ if let store = host.store {
+ ChatSplitView().environment(store)
+ } else {
+ ContentUnavailableView(
+ "Codync host isn't running",
+ systemImage: "desktopcomputer.trianglebadge.exclamationmark",
+ description: Text("Open Codync from the menu bar to install or restart it.")
+ )
+ }
+ }
+ .frame(minWidth: 760, minHeight: 500)
+ .background(Palette.background)
+ .tint(Palette.accent)
+ }
+}
+
+private struct ChatSplitView: View {
+ @Environment(BotStore.self) private var model
+ @State private var editing: EditorRequest?
+ @State private var confirmDelete: Bot?
+
+ var body: some View {
+ @Bindable var model = model
+ NavigationSplitView {
+ List(selection: $model.selection) {
+ ConnectionBanner()
+ if !model.usage.providers.isEmpty {
+ UsageStrip(usage: model.usage)
+ .listRowSeparator(.hidden)
+ }
+ ForEach(model.roster) { bot in
+ BotRow(bot: bot)
+ .tag(bot.id)
+ .contextMenu {
+ Button(bot.pinned ? "Unpin" : "Pin") { model.setPinned(bot, !bot.pinned) }
+ Button("Edit Profile…") { editing = EditorRequest(BotDraft(bot)) }
+ Button("Mark as Read") { model.markRead(bot.id) }
+ Button("Hide from List") { model.setHidden(bot, true) }
+ Divider()
+ Button("Delete…", role: .destructive) { confirmDelete = bot }
+ }
+ }
+ }
+ .navigationSplitViewColumnWidth(min: 260, ideal: 300, max: 420)
+ .navigationTitle(model.hostName)
+ .toolbar {
+ ToolbarItem {
+ Button("New Bot", systemImage: "square.and.pencil") { editing = EditorRequest(BotDraft()) }
+ .keyboardShortcut("n")
+ .disabled(model.connection != .online)
+ }
+ }
+ } detail: {
+ if let id = model.selection, model.bots[id] != nil {
+ NavigationStack { ThreadView(botId: id) }
+ .id(id)
+ } else {
+ VStack(spacing: 14) {
+ HStack(spacing: -10) {
+ CharacterAvatar(shape: "blob", color: "blue", size: 60, mood: .working)
+ CharacterAvatar(shape: "squircle", color: "orange", size: 60)
+ CharacterAvatar(shape: "teardrop", color: "violet", size: 60, mood: .working)
+ }
+ Text("Your coding agents, as teammates.").font(.title2.bold())
+ Text("Pick a bot, or create one for each kind of work and point it at a project.")
+ .foregroundStyle(Palette.secondary)
+ Button("New Bot") { editing = EditorRequest(BotDraft()) }
+ .buttonStyle(.borderedProminent)
+ .tint(Palette.accentFill)
+ .foregroundStyle(Palette.onAccent)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+ .sheet(item: $editing) { request in
+ NavigationStack { BotEditorView(draft: request.draft) }
+ .frame(minWidth: 520, minHeight: 640)
+ }
+ .confirmationDialog("Delete \(confirmDelete?.name ?? "")?", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } })) {
+ Button("Delete Bot and Conversation", role: .destructive) {
+ if let bot = confirmDelete { model.delete(bot) }
+ }
+ } message: {
+ Text("Files it changed on this computer stay as they are.")
+ }
+ .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-macOS/CodyncMacApp.swift b/Codync-macOS/CodyncMacApp.swift
index 2c862c6c..a357878d 100644
--- a/Codync-macOS/CodyncMacApp.swift
+++ b/Codync-macOS/CodyncMacApp.swift
@@ -1,4 +1,5 @@
import CodyncKit
+import CodyncUI
import CoreImage.CIFilterBuiltins
import SwiftUI
@@ -16,11 +17,18 @@ struct CodyncMacApp: App {
.task { host.start() }
}
.menuBarExtraStyle(.window)
+
+ Window("Codync", id: "chat") {
+ ChatWindow()
+ .environment(host)
+ }
+ .defaultSize(width: 1100, height: 760)
}
}
struct MenuView: View {
@Environment(HostController.self) private var host
+ @Environment(\.openWindow) private var openWindow
@State private var showPairing = false
var body: some View {
@@ -47,11 +55,18 @@ struct MenuView: View {
}
Spacer()
if host.state == .running {
+ Button {
+ openWindow(id: "chat")
+ NSApp.activate()
+ } label: {
+ Label("Open", systemImage: "bubble.left.and.bubble.right")
+ }
+ .controlSize(.small)
Button {
showPairing.toggle()
if showPairing { host.loadPairing() }
} label: {
- Label("Pair iPhone", systemImage: "qrcode")
+ Label("Pair", systemImage: "qrcode")
}
.buttonStyle(.borderedProminent)
.tint(Palette.accentFill)
@@ -118,6 +133,12 @@ struct MenuView: View {
VStack(spacing: 2) {
ForEach(host.bots) { bot in
BotLine(bot: bot) { host.stop(bot) }
+ .contentShape(Rectangle())
+ .onTapGesture {
+ host.store?.selection = bot.id
+ openWindow(id: "chat")
+ NSApp.activate()
+ }
}
}
.padding(6)
diff --git a/Codync-macOS/HostController.swift b/Codync-macOS/HostController.swift
index 8a84ceaa..dffb8f01 100644
--- a/Codync-macOS/HostController.swift
+++ b/Codync-macOS/HostController.swift
@@ -1,10 +1,11 @@
import CodyncKit
+import CodyncUI
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.
+/// service, and owns the BotStore the menu and the chat window share.
@MainActor
@Observable
final class HostController {
@@ -28,14 +29,16 @@ final class HostController {
?? FileManager.default.homeDirectoryForCurrentUser.appending(path: ".codync")
private(set) var state: State = .starting
- private(set) var bots: [Bot] = []
- private(set) var usage = Usage()
+ /// Live mirror of the host (same store the iPhone uses), once it's reachable.
+ private(set) var store: BotStore?
private(set) var pairInfo: PairInfo?
private(set) var version: String?
var launchAtLogin: Bool = SMAppService.mainApp.status == .enabled
private var streamTask: Task<Void, Never>?
+ var bots: [Bot] { store?.roster ?? [] }
+ var usage: Usage { store?.usage ?? Usage() }
var needsAttention: Bool { bots.contains(where: \.needsInput) }
var working: Int { bots.filter(\.isWorking).count }
@@ -103,7 +106,7 @@ final class HostController {
streamTask?.cancel()
Task {
_ = await Self.run(bin, ["uninstall"])
- bots = []
+ store = nil
state = .notInstalled
}
}
@@ -132,34 +135,32 @@ final class HostController {
return HostClient(baseURL: URL(string: "http://127.0.0.1:\(Self.port)")!, token: token.trimmingCharacters(in: .whitespacesAndNewlines))
}
+ /// Watches the host's health; the BotStore handles the event stream itself.
private func connect() {
streamTask?.cancel()
streamTask = Task { [weak self] in
- var attempts = 0
+ var failures = 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 }
+ if let client = self.client(), await client.healthy(timeout: 2) {
+ failures = 0
+ if self.store == nil || self.store?.pairing?.token != client.token {
+ self.version = (try? await client.hello())?.version
+ let store = BotStore(
+ pairing: Pairing(name: Host.current().localizedName ?? "This Mac", token: client.token, urls: [client.baseURL.absoluteString]),
+ clientKind: "mac",
+ persistsPairing: false
+ )
+ store.restartStream()
+ self.store = store
}
- } catch {}
- try? await Task.sleep(for: .seconds(2))
+ self.state = .running
+ } else {
+ failures += 1
+ if failures > 5 { self.state = .failed("The host isn't responding. See the log for details.") }
+ else if self.state != .running { self.state = .starting }
+ }
+ try? await Task.sleep(for: .seconds(5))
}
}
}
diff --git a/Codync.xcodeproj/project.pbxproj b/Codync.xcodeproj/project.pbxproj
index a3b3d9b9..d34b09a7 100644
--- a/Codync.xcodeproj/project.pbxproj
+++ b/Codync.xcodeproj/project.pbxproj
@@ -12,13 +12,12 @@
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 */; };
+ 2C1D071F93F790133BCB64DC /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3EC157070A9B0A033C7F2A0 /* CodyncUI */; };
+ 30814D765E2D3522EC337CB8 /* ChatWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F8473D6F162F5D18EF9D2EC /* ChatWindow.swift */; };
341AB84FEF28FF194872D861 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = CDE38864BDC425F1240E1C02 /* CodyncKit */; };
- 4F70D744ED9A696854EADA91 /* TraceView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A9EEFF0BB95647BE483A211 /* TraceView.swift */; };
+ 499113F4AB77E9EFEA72767F /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = 5DAFE014EAFE809C427A475D /* CodyncUI */; };
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 */; };
@@ -26,9 +25,7 @@
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 */
@@ -59,19 +56,16 @@
/* Begin PBXFileReference section */
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>"; };
+ 6F8473D6F162F5D18EF9D2EC /* ChatWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatWindow.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; };
@@ -79,9 +73,7 @@
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 */
@@ -92,6 +84,7 @@
buildActionMask = 2147483647;
files = (
341AB84FEF28FF194872D861 /* CodyncKit in Frameworks */,
+ 499113F4AB77E9EFEA72767F /* CodyncUI in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -100,6 +93,7 @@
buildActionMask = 2147483647;
files = (
D8E9E7B47361EEE30424455F /* CodyncKit in Frameworks */,
+ 2C1D071F93F790133BCB64DC /* CodyncUI in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -169,6 +163,7 @@
isa = PBXGroup;
children = (
9FCF7D2E2AEC8C83B89E7B36 /* Assets.xcassets */,
+ 6F8473D6F162F5D18EF9D2EC /* ChatWindow.swift */,
280FA54859773B9355860354 /* CodyncMacApp.swift */,
01C28522569623733B9B096D /* HostController.swift */,
);
@@ -190,15 +185,10 @@
EE65F2FAD6D95ABE28885E83 /* Views */ = {
isa = PBXGroup;
children = (
- 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>";
@@ -206,7 +196,6 @@
F474B3D70851CF6BC24ED9DE /* App */ = {
isa = PBXGroup;
children = (
- 092242ADE0E7FF8A82051511 /* AppModel.swift */,
A3FCD76B514C8ECF2211945A /* CodyncApp.swift */,
74E27E10BA8F07E552E99BE9 /* Push.swift */,
);
@@ -233,6 +222,7 @@
name = "Codync-iOS";
packageProductDependencies = (
CDE38864BDC425F1240E1C02 /* CodyncKit */,
+ 5DAFE014EAFE809C427A475D /* CodyncUI */,
);
productName = "Codync-iOS";
productReference = 84B947AD5A042EA315737BBC /* Codync-iOS.app */;
@@ -273,6 +263,7 @@
name = "Codync-macOS";
packageProductDependencies = (
234AA35A60DF7D3E6D7CA45E /* CodyncKit */,
+ C3EC157070A9B0A033C7F2A0 /* CodyncUI */,
);
productName = "Codync-macOS";
productReference = 155F1B6DC4518164BE2C527F /* Codync-macOS.app */;
@@ -359,7 +350,7 @@
);
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";
+ 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\n[ -n \"$BIN\" ] || { echo \"error: building codync-host failed\"; exit 1; }\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 */
@@ -369,18 +360,12 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- 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;
};
@@ -388,6 +373,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ 30814D765E2D3522EC337CB8 /* ChatWindow.swift in Sources */,
ED9C1500FD1CC591FCBD26CB /* CodyncMacApp.swift in Sources */,
CED43A6F2ED71E48C95E9E38 /* HostController.swift in Sources */,
);
@@ -744,6 +730,14 @@
isa = XCSwiftPackageProductDependency;
productName = CodyncKit;
};
+ 5DAFE014EAFE809C427A475D /* CodyncUI */ = {
+ isa = XCSwiftPackageProductDependency;
+ productName = CodyncUI;
+ };
+ C3EC157070A9B0A033C7F2A0 /* CodyncUI */ = {
+ isa = XCSwiftPackageProductDependency;
+ productName = CodyncUI;
+ };
CDE38864BDC425F1240E1C02 /* CodyncKit */ = {
isa = XCSwiftPackageProductDependency;
productName = CodyncKit;
diff --git a/CodyncKit/Package.swift b/CodyncKit/Package.swift
index a31fbd9a..2ee8b076 100644
--- a/CodyncKit/Package.swift
+++ b/CodyncKit/Package.swift
@@ -6,9 +6,11 @@ let package = Package(
platforms: [.macOS(.v14), .iOS(.v17)],
products: [
.library(name: "CodyncKit", targets: ["CodyncKit"]),
+ .library(name: "CodyncUI", targets: ["CodyncUI"]),
],
targets: [
.target(name: "CodyncKit"),
+ .target(name: "CodyncUI", dependencies: ["CodyncKit"]),
.testTarget(name: "CodyncKitTests", dependencies: ["CodyncKit"], resources: [.copy("Fixtures")]),
]
)
diff --git a/CodyncKit/Sources/CodyncKit/Models.swift b/CodyncKit/Sources/CodyncKit/Models.swift
index 8e6996a0..4fc16707 100644
--- a/CodyncKit/Sources/CodyncKit/Models.swift
+++ b/CodyncKit/Sources/CodyncKit/Models.swift
@@ -151,7 +151,15 @@ public struct UsageWindow: Codable, Hashable, Sendable, Identifiable {
public var label: String
public var percent: Double
public var resetsAt: Int64?
+ /// Human text when only that is known ("Sep 26 at 12pm (Asia/Taipei)").
+ public var resetsText: String?
public var resetDate: Date? { resetsAt.map(Date.init(milliseconds:)) }
+
+ /// "resets in 3h 20m" / "resets Sep 26 at 12pm", or nil.
+ public var resetDescription: String? {
+ if let d = resetDate { return "resets in \(RelativeTime.until(d))" }
+ return resetsText.map { "resets \($0.replacingOccurrences(of: #" \(.*\)$"#, with: "", options: .regularExpression))" }
+ }
}
public struct Backend: Codable, Hashable, Sendable, Identifiable {
diff --git a/Codync-iOS/Views/BotEditorView.swift b/CodyncKit/Sources/CodyncUI/BotEditorView.swift
similarity index 93%
rename from Codync-iOS/Views/BotEditorView.swift
rename to CodyncKit/Sources/CodyncUI/BotEditorView.swift
index c4c59ad3..6f8927d4 100644
--- a/Codync-iOS/Views/BotEditorView.swift
+++ b/CodyncKit/Sources/CodyncUI/BotEditorView.swift
@@ -1,25 +1,27 @@
import CodyncKit
import SwiftUI
-struct EditorRequest: Identifiable {
- let id = UUID()
- var draft: BotDraft
+public struct EditorRequest: Identifiable {
+ public let id = UUID()
+ public var draft: BotDraft
- init(_ draft: BotDraft) { self.draft = draft }
+ public 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
+public struct BotEditorView: View {
+ @Environment(BotStore.self) private var model
@Environment(\.dismiss) private var dismiss
@State var draft: BotDraft
+
+ public init(draft: BotDraft) { _draft = State(initialValue: draft) }
@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 {
+ public var body: some View {
Form {
Section {
VStack(spacing: 14) {
@@ -55,11 +57,11 @@ struct BotEditorView: View {
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)
+ .plainTextInput()
.autocorrectionDisabled()
}
TextField("Model (optional)", text: Binding(get: { draft.model ?? "" }, set: { draft.model = $0.isEmpty ? nil : $0 }))
- .textInputAutocapitalization(.never)
+ .plainTextInput()
.autocorrectionDisabled()
}
@@ -98,7 +100,7 @@ struct BotEditorView: View {
.scrollContentBackground(.hidden)
.background(Palette.background)
.navigationTitle(isNew ? "New bot" : "Edit bot")
- .navigationBarTitleDisplayMode(.inline)
+ .inlineNavigationTitle()
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
ToolbarItem(placement: .confirmationAction) {
@@ -137,7 +139,7 @@ struct BotEditorView: View {
do {
let bot = try await model.save(draft)
dismiss()
- if isNew { Router.shared.open(botId: bot.id) }
+ if isNew { model.selection = bot.id }
} catch {
self.error = error.localizedDescription
}
@@ -188,7 +190,7 @@ struct AvatarPicker: View {
struct FolderPicker: View {
let path: String?
let onPick: (String) -> Void
- @Environment(AppModel.self) private var model
+ @Environment(BotStore.self) private var model
@State private var listing: DirListing?
@State private var error: String?
@State private var filter = ""
@@ -228,7 +230,7 @@ struct FolderPicker: View {
}
.searchable(text: $filter)
.navigationTitle(listing.map { ($0.path as NSString).lastPathComponent } ?? "Folders")
- .navigationBarTitleDisplayMode(.inline)
+ .inlineNavigationTitle()
.task {
do { listing = try await model.listDirs(path) } catch { self.error = error.localizedDescription }
}
diff --git a/Codync-iOS/App/AppModel.swift b/CodyncKit/Sources/CodyncUI/BotStore.swift
similarity index 72%
rename from Codync-iOS/App/AppModel.swift
rename to CodyncKit/Sources/CodyncUI/BotStore.swift
index 3792273b..175c7eb2 100644
--- a/Codync-iOS/App/AppModel.swift
+++ b/CodyncKit/Sources/CodyncUI/BotStore.swift
@@ -1,34 +1,45 @@
import CodyncKit
import Foundation
import Observation
-import UIKit
-import WidgetKit
import os
-private let log = Logger(subsystem: "com.pokai.Codync.ios", category: "AppModel")
+private let log = Logger(subsystem: "com.pokai.Codync", category: "BotStore")
-/// Single source of truth for the phone: mirrors the host's bots and
-/// transcripts via one SSE stream (catch-up since `rev`, then live).
+/// Single source of truth for a Codync client (iPhone app, Mac window): 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 {
+public final class BotStore {
+ public 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()
+ public private(set) var pairing: Pairing?
+ public private(set) var connection: Connection = .unpaired
+ public private(set) var client: HostClient?
+ public private(set) var hello: Hello?
+ public private(set) var bots: [String: Bot] = [:]
+ public private(set) var entries: [String: [Entry]] = [:]
+ public 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?
+ public private(set) var historyComplete: Set<String> = []
+ public var lastError: String?
+ /// The open conversation (iOS navigation path / Mac sidebar selection).
+ public var selection: String?
+
+ // Platform hooks (push registration, Live Activities, widgets).
+ public var onPaired: (@MainActor (BotStore) -> Void)?
+ public var onBotUpdated: (@MainActor (Bot) -> Void)?
+ public var onUsageChanged: (@MainActor (Usage) -> Void)?
+ public var onSent: (@MainActor (Bot) -> Void)?
+
+ /// `ios` clients suppress pushes while connected; others don't.
+ private let clientKind: String
+ /// Whether pairing lives in the shared App Group (iPhone) or is supplied each launch (Mac).
+ private let persistsPairing: Bool
private var rev: Int64 = 0
private var hostId: String?
@@ -37,46 +48,61 @@ final class AppModel {
private var saveTask: Task<Void, Never>?
private var rewound = false
- init() {
+ public init(pairing: Pairing?, clientKind: String, persistsPairing: Bool) {
+ self.pairing = pairing
+ self.clientKind = clientKind
+ self.persistsPairing = persistsPairing
loadCache()
connection = pairing == nil ? .unpaired : .connecting
}
// MARK: derived
- var hostName: String { hello?.name ?? pairing?.name ?? "Computer" }
+ private var orderedPairing: Pairing? {
+ guard persistsPairing else { return pairing }
+ return SharedStore.orderedPairing ?? pairing
+ }
+
+ public var hostName: String { hello?.name ?? pairing?.name ?? "Computer" }
/// Roster order: pinned first (manual order not tracked yet), then most recent activity.
- var roster: [Bot] {
+ public 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 } }
+ /// Display name for a harness id, as the host reports it (falls back to the built-in list).
+ public func backendName(_ id: String) -> String {
+ hello?.backends.first { $0.id == id }?.name ?? BackendInfo.name(id)
+ }
- func thread(_ botId: String) -> [Entry] { entries[botId] ?? [] }
+ public var hiddenBots: [Bot] { bots.values.filter(\.hidden).sorted { $0.name < $1.name } }
+
+ public func thread(_ botId: String) -> [Entry] { entries[botId] ?? [] }
// MARK: pairing
- func pair(_ p: Pairing) {
+ public func pair(_ p: Pairing) {
let changedHost = pairing?.token != p.token
pairing = p
- SharedStore.pairing = p
- SharedStore.preferredURL = nil
+ if persistsPairing {
+ SharedStore.pairing = p
+ SharedStore.preferredURL = nil
+ }
if changedHost { resetMirror() }
connection = .connecting
restartStream()
- PushRegistrar.shared.syncDevice(with: self)
+ onPaired?(self)
}
- func unpair() {
+ public func unpair() {
streamTask?.cancel()
pairing = nil
client = nil
hello = nil
- SharedStore.pairing = nil
+ if persistsPairing { SharedStore.pairing = nil }
resetMirror()
connection = .unpaired
}
@@ -92,7 +118,7 @@ final class AppModel {
// MARK: lifecycle
- func setActive(_ active: Bool) {
+ public func setActive(_ active: Bool) {
isActive = active
if active {
restartStream()
@@ -104,7 +130,7 @@ final class AppModel {
}
}
- func restartStream() {
+ public func restartStream() {
streamTask?.cancel()
guard pairing != nil, isActive else { return }
streamTask = Task { [weak self] in await self?.runStream() }
@@ -113,7 +139,7 @@ final class AppModel {
private func runStream() async {
var backoff: Double = 1
while !Task.isCancelled {
- guard let pairing = SharedStore.orderedPairing else { return }
+ guard let pairing = orderedPairing else { return }
if connection != .online { connection = .connecting }
guard let client = await HostClient.resolve(pairing) else {
connection = .offline(HostError.unreachable.localizedDescription)
@@ -122,7 +148,7 @@ final class AppModel {
continue
}
self.client = client
- SharedStore.preferredURL = client.baseURL.absoluteString
+ if persistsPairing { SharedStore.preferredURL = client.baseURL.absoluteString }
do {
if hello == nil || hello?.hostId != hostId {
let h = try await client.hello()
@@ -133,7 +159,7 @@ final class AppModel {
cacheStamp = nil
}
}
- for try await event in client.events(since: rev, client: "ios") {
+ for try await event in client.events(since: rev, client: clientKind) {
connection = .online
backoff = 1
apply(event)
@@ -167,7 +193,7 @@ final class AppModel {
case let .bot(bot):
bots[bot.id] = bot
bump(bot.rev)
- LiveActivities.shared.update(bot: bot)
+ onBotUpdated?(bot)
case let .botDeleted(id, r):
bots[id] = nil
entries[id] = nil
@@ -196,6 +222,8 @@ final class AppModel {
private func upsert(_ e: Entry) {
var list = entries[e.botId] ?? []
if let i = list.firstIndex(where: { $0.id == e.id }) {
+ // A late API response mustn't undo a newer SSE update.
+ guard e.rev >= list[i].rev else { return }
list[i] = e
} else {
// Replace the optimistic copy of a message we sent.
@@ -215,8 +243,7 @@ final class AppModel {
private func setUsage(_ u: Usage) {
guard u != usage else { return }
usage = u
- SharedStore.usage = u
- WidgetCenter.shared.reloadAllTimelines()
+ onUsageChanged?(u)
}
// MARK: actions
@@ -226,7 +253,7 @@ final class AppModel {
return client
}
- func send(_ text: String, to botId: String) {
+ public func send(_ text: String, to botId: String) {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
let nonce = UUID().uuidString
@@ -240,20 +267,20 @@ final class AppModel {
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) }
+ if let bot = bots[botId] { onSent?(bot) }
} catch {
markLocal(nonce: nonce, botId: botId, status: "failed")
}
}
}
- func retry(_ entry: Entry) {
+ public 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) {
+ public func discard(_ entry: Entry) {
entries[entry.botId]?.removeAll { $0.id == entry.id }
}
@@ -263,56 +290,56 @@ final class AppModel {
entries[botId] = list
}
- func stop(_ botId: String) { perform { try await $0.stop(botId) } }
- func newSession(_ botId: String) { perform { try await $0.newSession(botId) } }
+ public func stop(_ botId: String) { perform { try await $0.stop(botId) } }
+ public func newSession(_ botId: String) { perform { try await $0.newSession(botId) } }
- func respond(_ entry: Entry, option: String?) {
+ public func respond(_ entry: Entry, option: String?) {
perform { try await $0.respondPermission(entryId: entry.id, optionId: option) }
}
- func markRead(_ botId: String) {
+ public 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) {
+ public 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) {
+ public 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) {
+ public 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 {
+ public 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 {
+ public func listDirs(_ path: String?) async throws -> DirListing {
try await require().listDirs(path)
}
- func refreshUsage() async {
+ public func refreshUsage() async {
guard let client else { return }
if let u = try? await client.usage(refresh: true) { setUsage(u) }
}
- func loadOlder(_ botId: String) async {
+ public 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 }
@@ -345,7 +372,7 @@ final class AppModel {
private var cacheStamp: String?
private static var cacheURL: URL {
- URL.cachesDirectory.appending(path: "codync-mirror.json")
+ URL.cachesDirectory.appending(path: "codync-mirror-\(Bundle.main.bundleIdentifier ?? "app").json")
}
private func loadCache() {
@@ -368,7 +395,7 @@ final class AppModel {
}
}
- func saveCache() {
+ public 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)
diff --git a/Codync-iOS/Views/MarkdownText.swift b/CodyncKit/Sources/CodyncUI/MarkdownText.swift
similarity index 97%
rename from Codync-iOS/Views/MarkdownText.swift
rename to CodyncKit/Sources/CodyncUI/MarkdownText.swift
index cafdf761..62e4e0e4 100644
--- a/Codync-iOS/Views/MarkdownText.swift
+++ b/CodyncKit/Sources/CodyncUI/MarkdownText.swift
@@ -3,10 +3,10 @@ import SwiftUI
/// Small block-level Markdown renderer: paragraphs, headings, lists, quotes and
/// fenced code; inline styling comes from `AttributedString(markdown:)`.
-struct MarkdownText: View {
+public struct MarkdownText: View {
let blocks: [Block]
- init(_ source: String) {
+ public init(_ source: String) {
blocks = Self.parse(source)
}
@@ -18,7 +18,7 @@ struct MarkdownText: View {
case code(String, language: String)
}
- var body: some View {
+ public var body: some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in
view(for: block)
diff --git a/Codync-iOS/Views/PermissionCard.swift b/CodyncKit/Sources/CodyncUI/PermissionCard.swift
similarity index 100%
rename from Codync-iOS/Views/PermissionCard.swift
rename to CodyncKit/Sources/CodyncUI/PermissionCard.swift
diff --git a/CodyncKit/Sources/CodyncUI/Platform.swift b/CodyncKit/Sources/CodyncUI/Platform.swift
new file mode 100644
index 00000000..1ade92ca
--- /dev/null
+++ b/CodyncKit/Sources/CodyncUI/Platform.swift
@@ -0,0 +1,44 @@
+import SwiftUI
+#if canImport(UIKit)
+import UIKit
+#else
+import AppKit
+#endif
+
+enum Pasteboard {
+ static func copy(_ text: String?) {
+ guard let text else { return }
+ #if canImport(UIKit)
+ UIPasteboard.general.string = text
+ #else
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ #endif
+ }
+}
+
+extension View {
+ func inlineNavigationTitle() -> some View {
+ #if os(iOS)
+ navigationBarTitleDisplayMode(.inline)
+ #else
+ self
+ #endif
+ }
+
+ func plainTextInput() -> some View {
+ #if os(iOS)
+ textInputAutocapitalization(.never).autocorrectionDisabled()
+ #else
+ autocorrectionDisabled()
+ #endif
+ }
+
+ @ViewBuilder func groupedList() -> some View {
+ #if os(iOS)
+ listStyle(.insetGrouped)
+ #else
+ listStyle(.inset)
+ #endif
+ }
+}
diff --git a/CodyncKit/Sources/CodyncUI/Roster.swift b/CodyncKit/Sources/CodyncUI/Roster.swift
new file mode 100644
index 00000000..b11476d0
--- /dev/null
+++ b/CodyncKit/Sources/CodyncUI/Roster.swift
@@ -0,0 +1,99 @@
+import CodyncKit
+import SwiftUI
+
+public struct BotRow: View {
+ let bot: Bot
+ @Environment(BotStore.self) private var model
+
+ public init(bot: Bot) { self.bot = bot }
+
+ public 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 ?? "\(model.backendName(bot.backend)) · \(bot.folderName)")
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ .lineLimit(2)
+ }
+ }
+}
+
+public struct ConnectionBanner: View {
+ @Environment(BotStore.self) private var model
+
+ public init() {}
+
+ public 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/ThreadView.swift b/CodyncKit/Sources/CodyncUI/ThreadView.swift
similarity index 95%
rename from Codync-iOS/Views/ThreadView.swift
rename to CodyncKit/Sources/CodyncUI/ThreadView.swift
index 6e250f61..c3bb0d8a 100644
--- a/Codync-iOS/Views/ThreadView.swift
+++ b/CodyncKit/Sources/CodyncUI/ThreadView.swift
@@ -3,9 +3,11 @@ 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 {
+public struct ThreadView: View {
let botId: String
- @Environment(AppModel.self) private var model
+
+ public init(botId: String) { self.botId = botId }
+ @Environment(BotStore.self) private var model
@Environment(\.dismiss) private var dismiss
@State private var draft = ""
@State private var showTrace = false
@@ -16,7 +18,7 @@ struct ThreadView: View {
private var bot: Bot? { model.bots[botId] }
- var body: some View {
+ public var body: some View {
let thread = model.thread(botId)
let items = ChatItem.build(thread)
ScrollViewReader { proxy in
@@ -57,10 +59,10 @@ struct ThreadView: View {
}
.background(Palette.background)
.safeAreaInset(edge: .bottom) { composer }
- .navigationBarTitleDisplayMode(.inline)
+ .inlineNavigationTitle()
.toolbar {
ToolbarItem(placement: .principal) { header }
- ToolbarItem(placement: .topBarTrailing) { menu }
+ ToolbarItem(placement: .primaryAction) { menu }
}
.onAppear { model.markRead(botId) }
.sheet(isPresented: $showTrace) {
@@ -126,7 +128,7 @@ struct ThreadView: View {
} 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)
+ Text("\(model.backendName(bot.backend)) · \(bot.folderName)").foregroundStyle(Palette.tertiary)
}
}
.font(.caption2)
@@ -157,6 +159,7 @@ struct ThreadView: View {
return HStack(alignment: .bottom, spacing: 8) {
TextField(working ? "Message (queued until it's done)" : "Message \(bot?.name ?? "")", text: $draft, axis: .vertical)
.lineLimit(1...6)
+ .textFieldStyle(.plain)
.focused($composerFocused)
.padding(.horizontal, 14)
.padding(.vertical, 10)
@@ -230,7 +233,7 @@ struct ChatItem: Identifiable {
struct UserBubble: View {
let entry: Entry
let botWorking: Bool
- @Environment(AppModel.self) private var model
+ @Environment(BotStore.self) private var model
var body: some View {
VStack(alignment: .trailing, spacing: 4) {
@@ -242,7 +245,7 @@ struct UserBubble: View {
.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 }
+ Button("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }
}
status
}
@@ -292,7 +295,7 @@ struct AgentBubble: View {
.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("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }
Button("Show what it did", systemImage: "list.bullet.rectangle", action: openTrace)
}
Spacer(minLength: 24)
@@ -386,12 +389,13 @@ struct TypingDots: View {
private struct IntroCard: View {
let bot: Bot
+ @Environment(BotStore.self) private var model
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)")
+ Text("\(model.backendName(bot.backend)) in \(bot.cwd)")
.font(.footnote.monospaced())
.foregroundStyle(Palette.tertiary)
.multilineTextAlignment(.center)
diff --git a/Codync-iOS/Views/TraceView.swift b/CodyncKit/Sources/CodyncUI/TraceView.swift
similarity index 95%
rename from Codync-iOS/Views/TraceView.swift
rename to CodyncKit/Sources/CodyncUI/TraceView.swift
index 47de8d1e..2b72dfc1 100644
--- a/Codync-iOS/Views/TraceView.swift
+++ b/CodyncKit/Sources/CodyncUI/TraceView.swift
@@ -3,12 +3,14 @@ import SwiftUI
/// "Full conversation": everything the agent did — narration, thinking, tool
/// calls with output and diffs, plans — grouped by turn.
-struct TraceView: View {
+public struct TraceView: View {
let botId: String
- @Environment(AppModel.self) private var model
+
+ public init(botId: String) { self.botId = botId }
+ @Environment(BotStore.self) private var model
@Environment(\.dismiss) private var dismiss
- var body: some View {
+ public var body: some View {
let turns = Dictionary(grouping: model.thread(botId), by: \.turn)
.sorted { $0.key < $1.key }
List {
@@ -25,11 +27,11 @@ struct TraceView: View {
}
}
}
- .listStyle(.insetGrouped)
+ .groupedList()
.scrollContentBackground(.hidden)
.background(Palette.background)
.navigationTitle("Full conversation")
- .navigationBarTitleDisplayMode(.inline)
+ .inlineNavigationTitle()
.toolbar {
ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } }
}
diff --git a/CodyncKit/Sources/CodyncUI/UsageViews.swift b/CodyncKit/Sources/CodyncUI/UsageViews.swift
new file mode 100644
index 00000000..c1acc8f8
--- /dev/null
+++ b/CodyncKit/Sources/CodyncUI/UsageViews.swift
@@ -0,0 +1,85 @@
+import CodyncKit
+import SwiftUI
+
+public struct UsageCard: View {
+ let provider: UsageProvider
+
+ public init(provider: UsageProvider) { self.provider = provider }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack {
+ Text(provider.name).font(.subheadline.bold())
+ Spacer()
+ 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.resetDescription {
+ Text("· \(reset)").font(.caption2).foregroundStyle(Palette.tertiary)
+ }
+ }
+ UsageBar(percent: w.percent)
+ }
+ }
+ }
+ .padding(.vertical, 4)
+ }
+}
+
+public struct UsageBar: View {
+ let percent: Double
+
+ public init(percent: Double) { self.percent = percent }
+
+ public 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.
+public struct UsageStrip: View {
+ let usage: Usage
+
+ public init(usage: Usage) { self.usage = usage }
+
+ public 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))
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/CodyncWidgets/CodyncWidgets.swift b/CodyncWidgets/CodyncWidgets.swift
index 4ab2ecad..029769df 100644
--- a/CodyncWidgets/CodyncWidgets.swift
+++ b/CodyncWidgets/CodyncWidgets.swift
@@ -123,8 +123,8 @@ struct UsageWidgetView: View {
}
}
.frame(height: 5)
- if family == .systemMedium, let reset = item.window.resetDate {
- Text("resets \(reset, style: .relative)").font(.system(size: 9)).foregroundStyle(Palette.tertiary)
+ if family == .systemMedium, let reset = item.window.resetDescription {
+ Text(reset).font(.system(size: 9)).foregroundStyle(Palette.tertiary)
}
}
}
diff --git a/host/Cargo.lock b/host/Cargo.lock
index ff7c8804..394f01bd 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -160,6 +160,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -272,6 +281,7 @@ dependencies = [
"rusqlite",
"serde",
"serde_json",
+ "sha2",
"tokio",
"tokio-stream",
"tracing",
@@ -295,6 +305,12 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "const-oid"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+
[[package]]
name = "core-foundation"
version = "0.10.1"
@@ -320,6 +336,26 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "block-buffer",
+ "const-oid",
+ "crypto-common",
+]
+
[[package]]
name = "dirs"
version = "7.0.0"
@@ -616,6 +652,15 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+[[package]]
+name = "hybrid-array"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
+dependencies = [
+ "typenum",
+]
+
[[package]]
name = "hyper"
version = "1.11.1"
@@ -1534,6 +1579,17 @@ dependencies = [
"serde",
]
+[[package]]
+name = "sha2"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
[[package]]
name = "sharded-slab"
version = "0.1.7"
@@ -1891,6 +1947,12 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
[[package]]
name = "unicode-ident"
version = "1.0.26"
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 9b545fff..963b0e50 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -11,11 +11,12 @@ 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 }
+qrcode = { version = "0.14.1", default-features = false, features = ["svg"] }
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"] }
+sha2 = "0.11.0"
tokio = { version = "1.53.1", features = ["full"] }
tokio-stream = { version = "0.1.19", features = ["sync"] }
tracing = "0.1.44"
diff --git a/host/src/api.rs b/host/src/api.rs
index c3dfbf20..c1a3afea 100644
--- a/host/src/api.rs
+++ b/host/src/api.rs
@@ -175,6 +175,10 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
}
json!({})
}
+ "refreshBackends" => {
+ tokio::task::spawn_blocking(backends::hydrate_path).await?;
+ json!({"backends": backends::list()})
+ }
"usage" => {
if b["refresh"].as_bool().unwrap_or(false) {
usage::refresh(hub).await;
@@ -182,6 +186,16 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
hub.usage.lock().unwrap().clone()
}
"listDirs" => list_dirs(b["path"].as_str())?,
+ "pairing" => {
+ let urls = crate::service::addresses(hub.port);
+ let url = crate::service::pairing_url(&crate::service::host_name(), &hub.token, &urls);
+ let svg = qrcode::QrCode::new(url.as_bytes())?
+ .render::<qrcode::render::svg::Color>()
+ .quiet_zone(false)
+ .min_dimensions(200, 200)
+ .build();
+ json!({"pairingUrl": url, "urls": urls, "svg": svg})
+ }
_ => return Err(anyhow!("unknown method")),
})
}
diff --git a/host/src/backends.rs b/host/src/backends.rs
index e20b6eca..07704141 100644
--- a/host/src/backends.rs
+++ b/host/src/backends.rs
@@ -1,78 +1,288 @@
-//! Known coding-agent backends and the ACP command that drives each one.
+//! Which coding harnesses this machine has, and how to drive each over ACP.
+//!
+//! Detection works like Orca's preflight: hydrate PATH from the user's login
+//! shell (GUI apps and launchd get a bare PATH), add the usual install dirs
+//! (Homebrew, ~/.local/bin, nvm, bun, volta, asdf, mise, pnpm…), then look for
+//! each known CLI. Launching prefers the installed CLI's own ACP mode and falls
+//! back to the official ACP registry build (npx / uvx / downloaded binary).
+use crate::registry;
use serde_json::{Value, json};
+use std::collections::HashSet;
+use std::path::PathBuf;
+use std::sync::Mutex;
+use std::time::Duration;
-pub struct Backend {
+pub struct Harness {
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,
+ /// CLI names that mean "installed on this machine".
+ pub bins: &'static [&'static str],
+ /// The installed CLI's native ACP mode (`{bin}` = resolved binary path).
+ pub local: Option<&'static str>,
+ /// Entry in the ACP registry (adapter or pinned build).
+ pub registry: Option<&'static str>,
+ pub setup: &'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 const HARNESSES: &[Harness] = &[
+ Harness { id: "claude", name: "Claude Code", bins: &["claude"], local: None, registry: Some("claude-acp"), setup: "Install Claude Code and run `claude` once to sign in." },
+ Harness { id: "codex", name: "Codex", bins: &["codex"], local: None, registry: Some("codex-acp"), setup: "Install Codex CLI and run `codex login`." },
+ Harness { id: "cursor", name: "Cursor", bins: &["cursor-agent"], local: Some("{bin} acp"), registry: Some("cursor"), setup: "Install Cursor CLI (curl https://cursor.com/install -fsS | bash) and run `cursor-agent login`." },
+ Harness { id: "pi", name: "Pi", bins: &["pi"], local: None, registry: Some("pi-acp"), setup: "Install pi (npm install -g @mariozechner/pi-coding-agent) and sign in with `pi`." },
+ Harness { id: "opencode", name: "OpenCode", bins: &["opencode"], local: Some("{bin} acp"), registry: Some("opencode"), setup: "Install OpenCode (curl -fsSL https://opencode.ai/install | bash) and run `opencode auth login`." },
+ Harness { id: "grok", name: "Grok Build", bins: &["grok"], local: Some("{bin} agent stdio"), registry: Some("grok-build"), setup: "Install Grok Build (curl -fsSL https://x.ai/cli/install.sh | bash) and run `grok` once to sign in." },
+ Harness { id: "gemini", name: "Gemini CLI", bins: &["gemini"], local: Some("{bin} --acp"), registry: Some("gemini"), setup: "Install Gemini CLI (npm install -g @google/gemini-cli) and run `gemini` once to sign in." },
+ Harness { id: "copilot", name: "GitHub Copilot", bins: &["copilot"], local: Some("{bin} --acp --stdio"), registry: Some("github-copilot-cli"), setup: "Install Copilot CLI (npm install -g @github/copilot) and run `copilot` to sign in." },
+ Harness { id: "qwen", name: "Qwen Code", bins: &["qwen"], local: Some("{bin} --acp"), registry: Some("qwen-code"), setup: "Install Qwen Code (npm install -g @qwen-code/qwen-code) and sign in with `qwen`." },
+ Harness { id: "goose", name: "goose", bins: &["goose"], local: Some("{bin} acp"), registry: Some("goose"), setup: "Install goose and run `goose configure`." },
+ Harness { id: "kimi", name: "Kimi CLI", bins: &["kimi"], local: Some("{bin} acp"), registry: Some("kimi"), setup: "Install Kimi CLI and sign in with `kimi`." },
+ Harness { id: "droid", name: "Factory Droid", bins: &["droid"], local: Some("{bin} exec --output-format acp-daemon"), registry: Some("factory-droid"), setup: "Install Droid (curl -fsSL https://app.factory.ai/cli | sh) and sign in with `droid`." },
+ Harness { id: "amp", name: "Amp", bins: &["amp"], local: None, registry: Some("amp-acp"), setup: "Install Amp and sign in with `amp login`." },
+ Harness { id: "kilo", name: "Kilo", bins: &["kilo"], local: Some("{bin} acp"), registry: Some("kilo"), setup: "Install Kilo CLI (npm install -g @kilocode/cli) and sign in." },
+ Harness { id: "cline", name: "Cline", bins: &["cline"], local: Some("{bin} --acp"), registry: Some("cline"), setup: "Install Cline CLI (npm install -g cline) and sign in." },
+ Harness { id: "auggie", name: "Auggie", bins: &["auggie"], local: Some("{bin} --acp"), registry: Some("auggie"), setup: "Install Auggie (npm install -g @augmentcode/auggie) and run `auggie login`." },
+ Harness { id: "vibe", name: "Mistral Vibe", bins: &["vibe-acp", "vibe"], local: None, registry: Some("mistral-vibe"), setup: "Install Mistral Vibe and run `vibe` once to sign in." },
+ Harness { id: "kiro", name: "Kiro CLI", bins: &["kiro-cli"], local: Some("{bin} acp"), registry: None, setup: "Install Kiro CLI (curl -fsSL https://cli.kiro.dev/install | bash) and run `kiro-cli login`." },
+ Harness { id: "devin", name: "Devin", bins: &["devin"], local: Some("{bin} acp"), registry: Some("devin"), setup: "Install the Devin CLI and sign in." },
+ Harness { id: "qoder", name: "Qoder CLI", bins: &["qodercli"], local: Some("{bin} --acp"), registry: Some("qoder"), setup: "Install Qoder CLI and sign in." },
];
-pub fn command(id: &str) -> Option<&'static str> {
- BACKENDS.iter().find(|b| b.id == id).map(|b| b.command)
+pub fn harness(id: &str) -> Option<&'static Harness> {
+ HARNESSES.iter().find(|h| h.id == id)
+}
+
+// MARK: PATH hydration
+
+static SEARCH_PATH: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
+
+/// Login-shell PATH, via `$SHELL -ilc` with a timeout (nvm/conda can make shells slow).
+fn login_shell_path() -> Option<String> {
+ const MARK: &str = "__CODYNC_PATH__";
+ let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into());
+ let mut child = std::process::Command::new(shell)
+ .args(["-ilc", &format!("printf '%s%s%s' '{MARK}' \"$PATH\" '{MARK}'")])
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .ok()?;
+ let deadline = std::time::Instant::now() + Duration::from_secs(8);
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => break,
+ Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
+ _ => {
+ let _ = child.kill();
+ return None;
+ }
+ }
+ }
+ let mut out = String::new();
+ std::io::Read::read_to_string(&mut child.stdout.take()?, &mut out).ok()?;
+ let start = out.find(MARK)? + MARK.len();
+ let end = start + out[start..].find(MARK)?;
+ Some(out[start..end].to_owned())
+}
+
+fn well_known_dirs() -> Vec<PathBuf> {
+ let Some(home) = dirs::home_dir() else { return vec![] };
+ let mut dirs: Vec<PathBuf> = [
+ "/opt/homebrew/bin",
+ "/usr/local/bin",
+ "/home/linuxbrew/.linuxbrew/bin",
+ "/usr/bin",
+ "/bin",
+ ]
+ .iter()
+ .map(PathBuf::from)
+ .collect();
+ for rel in [
+ ".local/bin",
+ ".bun/bin",
+ ".cargo/bin",
+ ".volta/bin",
+ ".asdf/shims",
+ ".local/share/mise/shims",
+ ".fnm/aliases/default/bin",
+ ".local/share/pnpm",
+ "Library/pnpm",
+ ".npm-global/bin",
+ ".opencode/bin",
+ ".deno/bin",
+ "go/bin",
+ ] {
+ dirs.push(home.join(rel));
+ }
+ // Every nvm-installed node, newest first (global npm CLIs live next to node).
+ if let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) {
+ let mut versions: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path().join("bin")).collect();
+ versions.sort();
+ versions.reverse();
+ dirs.extend(versions);
+ }
+ dirs
+}
+
+/// Re-detects the search path and exports it as this process's PATH, so every
+/// agent we spawn (and the `npx`/`node` they need) resolves the same way.
+pub fn hydrate_path() {
+ let mut seen = HashSet::new();
+ let mut path: Vec<PathBuf> = vec![];
+ let current = std::env::var("PATH").unwrap_or_default();
+ let login = login_shell_path().unwrap_or_default();
+ for p in std::env::split_paths(&current).chain(std::env::split_paths(&login)).chain(well_known_dirs()) {
+ if p.as_os_str().is_empty() || !p.is_dir() {
+ continue;
+ }
+ if seen.insert(p.clone()) {
+ path.push(p);
+ }
+ }
+ if let Ok(joined) = std::env::join_paths(&path) {
+ // SAFETY: called at startup and from the single refresh command, before/between spawns.
+ unsafe { std::env::set_var("PATH", joined) };
+ }
+ *SEARCH_PATH.lock().unwrap() = path;
+}
+
+pub fn which(bin: &str) -> Option<PathBuf> {
+ let dirs = {
+ let cached = SEARCH_PATH.lock().unwrap();
+ if cached.is_empty() {
+ std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default()
+ } else {
+ cached.clone()
+ }
+ };
+ dirs.into_iter().map(|d| d.join(bin)).find(|p| is_executable(p))
+}
+
+fn is_executable(p: &std::path::Path) -> bool {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
+ }
+ #[cfg(not(unix))]
+ {
+ p.is_file()
+ }
}
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)
+ which(bin).is_some()
}
+// MARK: listing + launching
+
+/// Every harness the phone can pick, installed ones first.
pub fn list() -> Vec<Value> {
- BACKENDS
+ let registry = registry::agents();
+ let mut out: Vec<Value> = HARNESSES
.iter()
- .map(|b| {
- let needs_npx = b.command.starts_with("npx ");
- let available = on_path(b.requires) && (!needs_npx || on_path("npx"));
+ .map(|h| {
+ let path = h.bins.iter().find_map(|b| which(b));
+ let reg = h.registry.and_then(|id| registry.iter().find(|a| a["id"] == id));
+ let runnable = (path.is_some() && h.local.is_some()) || reg.is_some_and(|a| registry::launch_kind(a).is_some());
json!({
- "id": b.id,
- "name": b.name,
- "available": available,
- "command": b.command,
- "installHint": b.install_hint,
+ "id": h.id,
+ "name": h.name,
+ "installed": path.is_some(),
+ "available": path.is_some() && runnable,
+ "path": path.map(|p| p.to_string_lossy().into_owned()),
+ "description": reg.and_then(|a| a["description"].as_str()).unwrap_or_default(),
+ "installHint": h.setup,
+ "command": h.local.unwrap_or_default(),
+ "curated": true,
})
})
- .collect()
+ .collect();
+ // Registry agents we don't know by name: runnable, but you sign in yourself.
+ let known: HashSet<&str> = HARNESSES.iter().filter_map(|h| h.registry).collect();
+ for a in &registry {
+ let id = a["id"].as_str().unwrap_or_default();
+ if id.is_empty() || known.contains(id) || id == "github-copilot" {
+ continue;
+ }
+ out.push(json!({
+ "id": id,
+ "name": a["name"],
+ "installed": false,
+ "available": registry::launch_kind(a).is_some(),
+ "path": null,
+ "description": a["description"],
+ "installHint": format!("Codync installs it automatically. Sign in to {} on this computer first if it needs an account.", a["name"].as_str().unwrap_or(id)),
+ "command": "",
+ "curated": false,
+ }));
+ }
+ out.sort_by_key(|v| (!v["installed"].as_bool().unwrap_or(false), !v["curated"].as_bool().unwrap_or(false)));
+ out
+}
+
+pub fn is_known(id: &str) -> bool {
+ harness(id).is_some() || registry::agent(id).is_some()
+}
+
+/// Ways to start this backend, best first. Local CLIs can be too old to speak
+/// ACP, so the registry build is kept as a fallback.
+pub async fn launch_candidates(id: &str, progress: impl Fn(&str)) -> anyhow::Result<Vec<String>> {
+ let mut out = vec![];
+ let h = harness(id);
+ if let Some(h) = h
+ && let Some(template) = h.local
+ && let Some(path) = h.bins.iter().find_map(|b| which(b))
+ {
+ out.push(template.replace("{bin}", &shell_quote(&path.to_string_lossy())));
+ }
+ let reg_id = h.map_or(Some(id), |h| h.registry);
+ if let Some(agent) = reg_id.and_then(registry::agent) {
+ match registry::command(&agent, &progress).await {
+ Ok(cmd) => out.push(cmd),
+ Err(e) if out.is_empty() => return Err(e),
+ Err(e) => tracing::info!("registry launch for {id} unavailable: {e}"),
+ }
+ }
+ if out.is_empty() {
+ let hint = h.map(|h| h.setup).unwrap_or("Check that it's installed on this computer.");
+ anyhow::bail!("{} isn't set up on this computer. {hint}", h.map_or(id, |h| h.name));
+ }
+ Ok(out)
+}
+
+fn shell_quote(s: &str) -> String {
+ if s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)) {
+ s.to_owned()
+ } else {
+ format!("'{}'", s.replace('\'', "'\\''"))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn detects_executables_on_search_path() {
+ let dir = std::env::temp_dir().join(format!("codync-bin-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let bin = dir.join("fake-harness");
+ std::fs::write(&bin, "#!/bin/sh\n").unwrap();
+ *SEARCH_PATH.lock().unwrap() = vec![dir.clone()];
+ assert!(which("fake-harness").is_none(), "not executable yet");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ assert_eq!(which("fake-harness"), Some(bin));
+ SEARCH_PATH.lock().unwrap().clear();
+ }
+
+ #[test]
+ fn every_harness_is_unique() {
+ let ids: HashSet<_> = HARNESSES.iter().map(|h| h.id).collect();
+ assert_eq!(ids.len(), HARNESSES.len());
+ }
}
diff --git a/host/src/bot.rs b/host/src/bot.rs
index 4792d888..592bb473 100644
--- a/host/src/bot.rs
+++ b/host/src/bot.rs
@@ -188,7 +188,13 @@ impl Actor {
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");
+ let mut msg = format!("Couldn't start the agent: {e}");
+ if e.to_string().to_lowercase().contains("auth")
+ && let Some(h) = crate::backends::harness(&self.cfg.backend)
+ {
+ msg = format!("{} needs you to sign in on your computer first. {}", h.name, h.setup);
+ }
+ self.notice(&msg, "error");
self.turn = None;
self.hub.set_runtime(&self.id(), |r| {
r.status = "error".into();
@@ -219,6 +225,18 @@ impl Actor {
});
self.ensure_session().await?;
+ // Session-start chatter (banners, command lists) isn't part of the reply.
+ // Some adapters (pi-acp) send it on a timer right after session/new.
+ if self.session_fresh {
+ tokio::time::sleep(Duration::from_millis(400)).await;
+ }
+ if let Some(conn) = self.conn.as_mut() {
+ while let Ok(inc) = conn.rx.try_recv() {
+ if let Incoming::Request { id, .. } = inc {
+ let _ = conn.acp.respond_error(id, -32601, "not supported").await;
+ }
+ }
+ }
let conn = self.conn.as_ref().ok_or_else(|| anyhow!("agent not running"))?;
let mut prompt = text.to_owned();
if self.session_fresh {
@@ -245,29 +263,38 @@ impl Actor {
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(),
+ let candidates = match self.cfg.command.as_deref().map(str::trim) {
+ Some(c) if !c.is_empty() => vec![c.to_owned()],
+ _ => {
+ let hub = self.hub.clone();
+ let id = self.cfg.id.clone();
+ crate::backends::launch_candidates(&self.cfg.backend, move |msg: &str| {
+ let msg = msg.to_owned();
+ hub.set_runtime(&id, |r| r.activity = msg);
+ })
+ .await?
+ }
};
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 mut last_err = None;
+ for (i, command) in candidates.iter().enumerate() {
+ let fallback_left = i + 1 < candidates.len();
+ // A local CLI too old for ACP just hangs; don't make the user wait long before the fallback.
+ let budget = Duration::from_secs(if fallback_left { 20 } else { 180 });
+ match start_agent(command, &self.cfg.cwd, budget).await {
+ Ok(conn) => {
+ self.conn = Some(conn);
+ break;
+ }
+ Err(e) => {
+ tracing::info!("`{command}` failed to start: {e}");
+ last_err = Some(e);
+ }
+ }
+ }
+ if self.conn.is_none() {
+ return Err(last_err.unwrap_or_else(|| anyhow!("agent failed to start")));
+ }
}
let conn = self.conn.as_mut().unwrap();
if let Some(sid) = self.session_id.clone() {
@@ -471,6 +498,12 @@ impl Actor {
self.set_activity(&title);
}
}
+ "usage_update" => {
+ let info = &u["_meta"]["_claude/rateLimit"];
+ if info.is_object() {
+ crate::usage::ingest_claude_rate_limit(&self.hub, info);
+ }
+ }
"plan" => {
let data = json!({"entries": u["entries"].clone()});
match &self.plan_entry {
@@ -630,6 +663,36 @@ impl Actor {
}
}
+/// Spawns an ACP agent and completes the `initialize` handshake.
+async fn start_agent(command: &str, cwd: &str, budget: Duration) -> Result<Conn> {
+ let (acp, rx) = Acp::spawn(command, cwd)?;
+ let init = tokio::time::timeout(
+ budget,
+ 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;
+ let init = match init {
+ Ok(Ok(v)) => v,
+ Ok(Err(e)) => {
+ acp.kill().await;
+ return Err(e);
+ }
+ Err(_) => {
+ acp.kill().await;
+ return Err(anyhow!("the agent didn't answer the ACP handshake within {}s", budget.as_secs()));
+ }
+ };
+ let can_load = init["agentCapabilities"]["loadSession"].as_bool().unwrap_or(false);
+ Ok(Conn { acp, rx, can_load, loaded: HashSet::new() })
+}
+
async fn recv_incoming(conn: &mut Option<Conn>) -> Option<Incoming> {
match conn {
Some(c) => c.rx.recv().await,
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 9cdc03e0..1f52df25 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -22,6 +22,7 @@ pub struct Hub {
pub store: Store,
pub host_id: String,
pub token: String,
+ pub port: u16,
pub events: broadcast::Sender<Value>,
/// Held across "mutate store + broadcast" so events leave in rev order.
emit_lock: Mutex<()>,
@@ -35,12 +36,13 @@ pub struct Hub {
}
impl Hub {
- pub fn new(store: Store, host_id: String, token: String) -> Arc<Self> {
+ pub fn new(store: Store, host_id: String, token: String, port: u16) -> Arc<Self> {
let (events, _) = broadcast::channel(1024);
Arc::new(Self {
store,
host_id,
token,
+ port,
events,
emit_lock: Mutex::new(()),
bots: Default::default(),
@@ -238,7 +240,7 @@ fn validate(cfg: &BotConfig) -> Result<()> {
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() {
+ if cfg.command.as_deref().map(str::trim).unwrap_or_default().is_empty() && !crate::backends::is_known(&cfg.backend) {
return Err(anyhow!("unknown backend {}", cfg.backend));
}
Ok(())
diff --git a/host/src/main.rs b/host/src/main.rs
index aacdd1c9..f03554ae 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -4,6 +4,7 @@ mod backends;
mod bot;
mod hub;
mod push;
+mod registry;
mod service;
mod store;
mod usage;
@@ -51,10 +52,13 @@ enum Sub {
#[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.
+ /// Claude Code statusLine command: forwards usage limits to the host, then prints
+ /// the wrapped command's status line (`statusline -- <command>`) or a short default.
Statusline {
#[arg(long, default_value_t = service::DEFAULT_PORT)]
port: u16,
+ #[arg(last = true)]
+ wrapped: Vec<String>,
},
/// Rotate the pairing token (unpairs every phone).
ResetToken,
@@ -131,6 +135,11 @@ async fn main() -> Result<()> {
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}"),
}
+ match service::ensure_statusline(&home.join(".claude/settings.json")) {
+ Ok(true) => println!("Claude Code's status line now also reports usage limits to Codync (your own status line still shows)."),
+ Ok(false) => {}
+ Err(e) => eprintln!("Couldn't set Claude Code's status line: {e}"),
+ }
}
service::install(port)?;
println!("Codync host installed and started on port {port}. Run `codync-host pair` to connect your phone.");
@@ -138,6 +147,9 @@ async fn main() -> Result<()> {
}
Sub::Uninstall => {
service::uninstall()?;
+ if let Some(home) = dirs::home_dir() {
+ let _ = service::restore_statusline(&home.join(".claude/settings.json"));
+ }
println!("Codync host service removed. Data is kept in {}", service::data_dir().display());
Ok(())
}
@@ -151,8 +163,8 @@ async fn main() -> Result<()> {
println!("installed: {}\nrunning: {running}\nport: {port}\ndata: {}", service::installed(), service::data_dir().display());
Ok(())
}
- Sub::Statusline { port } => {
- statusline(port).await;
+ Sub::Statusline { port, wrapped } => {
+ statusline(port, wrapped.join(" ")).await;
Ok(())
}
Sub::ResetToken => {
@@ -172,8 +184,10 @@ async fn serve(bind: &str, port: u16) -> Result<()> {
.init();
let (store, host_id, token) = open_store()?;
write_token_file(&token)?;
- let hub = hub::Hub::new(store, host_id, token);
+ tokio::task::spawn_blocking(backends::hydrate_path).await?;
+ let hub = hub::Hub::new(store, host_id, token, port);
hub.start()?;
+ tokio::spawn(registry::refresh_loop());
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"));
@@ -182,7 +196,7 @@ async fn serve(bind: &str, port: u16) -> Result<()> {
}
/// Never blocks Claude Code: 1 s budget, all errors ignored.
-async fn statusline(port: u16) {
+async fn statusline(port: u16, wrapped: String) {
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();
@@ -195,6 +209,22 @@ async fn statusline(port: u16) {
.send()
.await;
}
+ if !wrapped.trim().is_empty() {
+ // The user's own status line gets the same JSON on stdin.
+ use std::io::Write;
+ if let Ok(mut child) = std::process::Command::new("/bin/sh")
+ .arg("-c")
+ .arg(&wrapped)
+ .stdin(std::process::Stdio::piped())
+ .spawn()
+ {
+ if let Some(mut stdin) = child.stdin.take() {
+ let _ = stdin.write_all(input.as_bytes());
+ }
+ let _ = child.wait();
+ }
+ return;
+ }
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")] {
diff --git a/host/src/registry.rs b/host/src/registry.rs
new file mode 100644
index 00000000..53972ae0
--- /dev/null
+++ b/host/src/registry.rs
@@ -0,0 +1,242 @@
+//! The official ACP agent registry (https://agentclientprotocol.com/registry):
+//! ~40 coding agents with a known-good way to launch each over ACP — an npx or
+//! uvx package, or a per-platform binary archive we download on first use.
+
+use anyhow::{Context, Result, anyhow, bail};
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::time::Duration;
+
+const URL: &str = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
+
+static CACHE: Mutex<Option<Value>> = Mutex::new(None);
+
+fn cache_file() -> PathBuf {
+ crate::service::data_dir().join("registry.json")
+}
+
+/// Registry agents (from memory, else the on-disk copy).
+pub fn agents() -> Vec<Value> {
+ let mut cache = CACHE.lock().unwrap();
+ if cache.is_none() {
+ *cache = std::fs::read_to_string(cache_file()).ok().and_then(|s| serde_json::from_str(&s).ok());
+ }
+ cache.as_ref().and_then(|v| v["agents"].as_array().cloned()).unwrap_or_default()
+}
+
+pub fn agent(id: &str) -> Option<Value> {
+ agents().into_iter().find(|a| a["id"] == id)
+}
+
+/// Refreshes the registry once a day (it changes hourly upstream; daily is plenty).
+pub async fn refresh_loop() {
+ loop {
+ match fetch().await {
+ Ok(v) => {
+ let _ = std::fs::write(cache_file(), v.to_string());
+ *CACHE.lock().unwrap() = Some(v);
+ }
+ Err(e) => tracing::info!("ACP registry refresh failed (using cache): {e}"),
+ }
+ tokio::time::sleep(Duration::from_secs(24 * 3600)).await;
+ }
+}
+
+async fn fetch() -> Result<Value> {
+ let v: Value = reqwest::Client::new()
+ .get(URL)
+ .timeout(Duration::from_secs(20))
+ .send()
+ .await?
+ .error_for_status()?
+ .json()
+ .await?;
+ if !v["agents"].is_array() {
+ bail!("unexpected registry format");
+ }
+ Ok(v)
+}
+
+pub fn platform() -> Option<&'static str> {
+ Some(match (std::env::consts::OS, std::env::consts::ARCH) {
+ ("macos", "aarch64") => "darwin-aarch64",
+ ("macos", "x86_64") => "darwin-x86_64",
+ ("linux", "aarch64") => "linux-aarch64",
+ ("linux", "x86_64") => "linux-x86_64",
+ _ => return None,
+ })
+}
+
+/// How this machine would launch the agent: `npx` / `uvx` / `download`, or None.
+pub fn launch_kind(agent: &Value) -> Option<&'static str> {
+ let d = &agent["distribution"];
+ let on_path = crate::backends::on_path;
+ if let Some(p) = platform()
+ && d["binary"][p].is_object()
+ {
+ return Some("download");
+ }
+ if d["npx"].is_object() && on_path("npx") {
+ return Some("npx");
+ }
+ if d["uvx"].is_object() && on_path("uvx") {
+ return Some("uvx");
+ }
+ None
+}
+
+fn shell_quote(s: &str) -> String {
+ if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=@:+,".contains(c)) {
+ s.to_owned()
+ } else {
+ format!("'{}'", s.replace('\'', "'\\''"))
+ }
+}
+
+fn args_of(v: &Value) -> String {
+ v["args"]
+ .as_array()
+ .map(|a| a.iter().filter_map(Value::as_str).map(shell_quote).collect::<Vec<_>>().join(" "))
+ .unwrap_or_default()
+}
+
+fn env_prefix(v: &Value) -> String {
+ v["env"]
+ .as_object()
+ .map(|m| {
+ m.iter()
+ .filter_map(|(k, v)| Some(format!("{k}={} ", shell_quote(v.as_str()?))))
+ .collect::<String>()
+ })
+ .unwrap_or_default()
+}
+
+/// Shell command that starts the agent over ACP stdio, downloading it first if needed.
+/// `progress` receives short status lines ("Downloading Cursor…").
+pub async fn command(agent: &Value, progress: impl Fn(&str)) -> Result<String> {
+ let name = agent["name"].as_str().unwrap_or("agent");
+ let d = &agent["distribution"];
+ match launch_kind(agent) {
+ Some("download") => {
+ let target = &d["binary"][platform().unwrap()];
+ let dir = install_binary(agent, target, &progress).await?;
+ let cmd = target["cmd"].as_str().ok_or_else(|| anyhow!("registry entry has no cmd"))?;
+ let exe = dir.join(cmd.trim_start_matches("./"));
+ Ok(format!("{}{} {}", env_prefix(target), shell_quote(&exe.to_string_lossy()), args_of(target)))
+ }
+ Some("npx") => Ok(format!(
+ "{}npx -y {} {}",
+ env_prefix(&d["npx"]),
+ shell_quote(d["npx"]["package"].as_str().unwrap_or_default()),
+ args_of(&d["npx"])
+ )),
+ Some("uvx") => Ok(format!(
+ "{}uvx {} {}",
+ env_prefix(&d["uvx"]),
+ shell_quote(d["uvx"]["package"].as_str().unwrap_or_default()),
+ args_of(&d["uvx"])
+ )),
+ _ => bail!("{name} has no build for this computer (needs {}).", if d["uvx"].is_object() { "uv" } else { "Node.js" }),
+ }
+}
+
+/// Downloads + extracts a binary distribution into ~/.codync/agents/<id>/<version>.
+async fn install_binary(agent: &Value, target: &Value, progress: &impl Fn(&str)) -> Result<PathBuf> {
+ let id = agent["id"].as_str().unwrap_or("agent");
+ let version = agent["version"].as_str().unwrap_or("latest");
+ let dir = crate::service::data_dir().join("agents").join(id).join(version);
+ if dir.join(".installed").exists() {
+ return Ok(dir);
+ }
+ let url = target["archive"].as_str().ok_or_else(|| anyhow!("registry entry has no archive"))?;
+ progress(&format!("Downloading {}…", agent["name"].as_str().unwrap_or(id)));
+ let bytes = reqwest::Client::new()
+ .get(url)
+ .timeout(Duration::from_secs(600))
+ .send()
+ .await?
+ .error_for_status()?
+ .bytes()
+ .await?;
+ if let Some(want) = target["sha256"].as_str() {
+ let got: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect();
+ if !got.eq_ignore_ascii_case(want) {
+ bail!("download checksum mismatch for {id}");
+ }
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir)?;
+ let file_name = url.rsplit('/').next().unwrap_or("download").split('?').next().unwrap_or("download");
+ let archive = dir.join(file_name);
+ std::fs::write(&archive, &bytes)?;
+ progress("Installing…");
+ extract(&archive, &dir, target["cmd"].as_str().unwrap_or_default())?;
+ std::fs::write(dir.join(".installed"), "")?;
+ Ok(dir)
+}
+
+fn extract(archive: &Path, dir: &Path, cmd: &str) -> Result<()> {
+ let name = archive.file_name().unwrap().to_string_lossy().to_lowercase();
+ let status = if name.ends_with(".zip") {
+ std::process::Command::new("unzip").arg("-q").arg("-o").arg(archive).arg("-d").arg(dir).status()
+ } else if [".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".tar"].iter().any(|e| name.ends_with(e)) {
+ std::process::Command::new("tar").arg("-xf").arg(archive).arg("-C").arg(dir).status()
+ } else {
+ // Raw binary: it *is* the command.
+ let exe = dir.join(cmd.trim_start_matches("./"));
+ if let Some(parent) = exe.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::rename(archive, &exe)?;
+ chmod_x(&exe)?;
+ return Ok(());
+ }
+ .context("running the extractor")?;
+ if !status.success() {
+ bail!("couldn't extract {}", archive.display());
+ }
+ let _ = std::fs::remove_file(archive);
+ let exe = dir.join(cmd.trim_start_matches("./"));
+ if exe.exists() {
+ chmod_x(&exe)?;
+ }
+ Ok(())
+}
+
+fn chmod_x(path: &Path) -> Result<()> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut p = std::fs::metadata(path)?.permissions();
+ p.set_mode(p.mode() | 0o755);
+ std::fs::set_permissions(path, p)?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[tokio::test]
+ async fn npx_command_is_quoted() {
+ let a = json!({"id": "x", "name": "X", "distribution": {"npx": {"package": "@s/[email protected]", "args": ["--acp", "a b"], "env": {"K": "v"}}}});
+ if crate::backends::on_path("npx") {
+ assert_eq!(command(&a, |_| {}).await.unwrap(), "K=v npx -y @s/[email protected] --acp 'a b'");
+ }
+ }
+
+ #[test]
+ fn raw_binary_extract_marks_executable() {
+ let dir = std::env::temp_dir().join(format!("codync-reg-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let archive = dir.join("tool-darwin");
+ std::fs::write(&archive, "#!/bin/sh\necho hi\n").unwrap();
+ extract(&archive, &dir, "./bin/tool").unwrap();
+ let out = std::process::Command::new(dir.join("bin/tool")).output().unwrap();
+ assert_eq!(String::from_utf8_lossy(&out.stdout), "hi\n");
+ }
+}
diff --git a/host/src/service.rs b/host/src/service.rs
index ef04a7a0..e0bc90c4 100644
--- a/host/src/service.rs
+++ b/host/src/service.rs
@@ -242,6 +242,54 @@ pub fn remove_legacy_hooks(settings: &std::path::Path) -> Result<usize> {
Ok(removed)
}
+const STATUSLINE_MARK: &str = " statusline --";
+
+/// Routes Claude Code's status line through `codync-host statusline` so usage
+/// limits reach the host locally. An existing status line keeps working: it is
+/// wrapped (`codync-host statusline -- <original>`) and restored on uninstall.
+pub fn ensure_statusline(settings: &std::path::Path) -> Result<bool> {
+ let text = std::fs::read_to_string(settings).unwrap_or_else(|_| "{}".into());
+ let mut v: serde_json::Value = serde_json::from_str(&text).context("parsing Claude settings")?;
+ let current = v["statusLine"]["command"].as_str().map(str::to_owned);
+ if current.as_deref().is_some_and(|c| c.contains(" statusline")) {
+ return Ok(false);
+ }
+ if v.get("statusLine").is_some() && current.is_none() {
+ return Ok(false); // not a command status line; leave it alone
+ }
+ let exe = std::env::current_exe()?.canonicalize()?;
+ let ours = format!("'{}' statusline", exe.to_string_lossy());
+ let command = match current {
+ Some(original) => format!("{ours} -- {original}"),
+ None => ours,
+ };
+ v["statusLine"] = serde_json::json!({"type": "command", "command": command});
+ if let Some(parent) = settings.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::write(settings, serde_json::to_string_pretty(&v)? + "\n")?;
+ Ok(true)
+}
+
+/// Undoes `ensure_statusline`.
+pub fn restore_statusline(settings: &std::path::Path) -> Result<()> {
+ let Ok(text) = std::fs::read_to_string(settings) else { return Ok(()) };
+ let mut v: serde_json::Value = serde_json::from_str(&text)?;
+ let Some(cmd) = v["statusLine"]["command"].as_str().map(str::to_owned) else { return Ok(()) };
+ // Ours always starts with the quoted host path followed by ` statusline`.
+ if !cmd.starts_with('\'') || !cmd.contains("' statusline") {
+ return Ok(());
+ }
+ match cmd.split_once(STATUSLINE_MARK) {
+ Some((_, original)) => v["statusLine"]["command"] = original.trim().into(),
+ None => {
+ v.as_object_mut().unwrap().remove("statusLine");
+ }
+ }
+ std::fs::write(settings, serde_json::to_string_pretty(&v)? + "\n")?;
+ Ok(())
+}
+
#[cfg(test)]
mod legacy_tests {
#[test]
@@ -261,4 +309,19 @@ mod legacy_tests {
assert_eq!(v["model"], "x");
assert!(dir.join("settings.json.codync-backup").exists());
}
+
+ #[test]
+ fn statusline_wraps_and_restores() {
+ let dir = std::env::temp_dir().join(format!("codync-sl-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let f = dir.join("settings.json");
+ std::fs::write(&f, r#"{"statusLine":{"type":"command","command":"sh ~/mine.sh"}}"#).unwrap();
+ assert!(super::ensure_statusline(&f).unwrap());
+ assert!(!super::ensure_statusline(&f).unwrap(), "idempotent");
+ let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&f).unwrap()).unwrap();
+ assert!(v["statusLine"]["command"].as_str().unwrap().ends_with("statusline -- sh ~/mine.sh"));
+ super::restore_statusline(&f).unwrap();
+ let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&f).unwrap()).unwrap();
+ assert_eq!(v["statusLine"]["command"], "sh ~/mine.sh");
+ }
}
diff --git a/host/src/usage.rs b/host/src/usage.rs
index 9a74f87d..afc49855 100644
--- a/host/src/usage.rs
+++ b/host/src/usage.rs
@@ -1,9 +1,9 @@
-//! Subscription usage limits, read on the host only (tokens never leave it).
+//! Subscription usage limits, read locally on the host — no extra login.
//!
-//! 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.
+//! Claude: asks the installed `claude` binary (`claude -p /usage`, a local
+//! command that costs nothing), plus the `rate_limits` Claude Code hands its
+//! status line and the Claude ACP adapter's rate-limit events. Codex: the
+//! newest `rate_limits` event in `~/.codex/sessions` rollout files.
use crate::hub::Hub;
use serde_json::{Value, json};
@@ -15,6 +15,10 @@ pub fn window(id: &str, label: &str, percent: f64, resets_at_ms: Option<i64>) ->
json!({"id": id, "label": label, "percent": percent, "resetsAt": resets_at_ms})
}
+fn window_text(id: &str, label: &str, percent: f64, resets_text: &str) -> Value {
+ json!({"id": id, "label": label, "percent": percent, "resetsAt": null, "resetsText": resets_text})
+}
+
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()})
}
@@ -28,6 +32,19 @@ fn merge(hub: &Hub, p: Value) {
hub.set_usage(usage);
}
+/// Replaces or adds windows for one provider, keeping the others it already had.
+fn merge_windows(hub: &Hub, id: &str, name: &str, source: &str, new: Vec<Value>) {
+ let existing = hub.usage.lock().unwrap()["providers"]
+ .as_array()
+ .and_then(|l| l.iter().find(|p| p["id"] == id))
+ .and_then(|p| p["windows"].as_array().cloned())
+ .unwrap_or_default();
+ let mut windows: Vec<Value> = existing.into_iter().filter(|w| !new.iter().any(|n| n["id"] == w["id"])).collect();
+ windows.extend(new);
+ windows.sort_by_key(|w| w["id"].as_str().unwrap_or_default().to_owned());
+ merge(hub, provider(id, name, windows, source));
+}
+
pub async fn poll(hub: Arc<Hub>) {
loop {
refresh(&hub).await;
@@ -35,29 +52,52 @@ pub async fn poll(hub: Arc<Hub>) {
}
}
-static CLAUDE_BACKOFF_UNTIL: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);
-
pub async fn refresh(hub: &Hub) {
- // Live statusline data beats polling an undocumented endpoint.
- let fresh_statusline = hub.usage.lock().unwrap()["providers"]
- .as_array()
- .into_iter()
- .flatten()
- .any(|p| p["id"] == "claude" && p["source"] == "statusline" && p["updatedAt"].as_i64().is_some_and(|t| crate::store::now_ms() - t < 600_000));
- let backing_off = CLAUDE_BACKOFF_UNTIL.lock().unwrap().is_some_and(|t| std::time::Instant::now() < t);
- if !fresh_statusline && !backing_off {
- match claude_oauth_usage().await {
- Ok(Some(p)) => merge(hub, p),
- Ok(None) => {}
- Err(e) => {
- tracing::debug!("claude usage: {e}");
- *CLAUDE_BACKOFF_UNTIL.lock().unwrap() = Some(std::time::Instant::now() + Duration::from_secs(3600));
- }
- }
- }
if let Some(p) = tokio::task::spawn_blocking(codex_usage).await.ok().flatten() {
merge(hub, p);
}
+ if let Some(windows) = claude_cli_usage().await {
+ merge_windows(hub, "claude", "Claude", "claude", windows);
+ }
+}
+
+/// `claude -p /usage`: Claude Code's own local usage report, no model call.
+async fn claude_cli_usage() -> Option<Vec<Value>> {
+ let bin = crate::backends::which("claude")?;
+ let out = tokio::time::timeout(
+ Duration::from_secs(60),
+ tokio::process::Command::new(bin)
+ .args(["-p", "/usage", "--output-format", "json", "--no-session-persistence"])
+ .current_dir(dirs::home_dir()?)
+ .stdin(std::process::Stdio::null())
+ .output(),
+ )
+ .await
+ .ok()?
+ .ok()?;
+ let v: Value = serde_json::from_slice(&out.stdout).ok()?;
+ let windows = parse_claude_usage(v["result"].as_str()?);
+ (!windows.is_empty()).then_some(windows)
+}
+
+/// Lines like `Current week (all models): 53% used · resets Sep 26 at 12pm (Asia/Taipei)`.
+pub fn parse_claude_usage(text: &str) -> Vec<Value> {
+ text.lines()
+ .filter_map(|line| {
+ let (name, rest) = line.trim().split_once(": ")?;
+ let pct: f64 = rest.split_once("% used")?.0.trim().parse().ok()?;
+ let resets = rest.split_once("resets ").map(|(_, r)| r.trim()).unwrap_or_default();
+ let (id, label) = match name {
+ "Current session" => ("five_hour".to_owned(), "5-hour".to_owned()),
+ "Current week (all models)" => ("seven_day".to_owned(), "Weekly".to_owned()),
+ n => {
+ let model = n.strip_prefix("Current week (")?.strip_suffix(')')?;
+ (format!("seven_day_{}", model.to_lowercase()), format!("Weekly · {model}"))
+ }
+ };
+ Some(window_text(&id, &label, pct, resets))
+ })
+ .collect()
}
/// `POST /ingest/statusline` body: Claude Code's statusline JSON.
@@ -70,106 +110,31 @@ pub fn ingest_statusline(hub: &Hub, body: &Value) {
}
}
if !windows.is_empty() {
- merge(hub, provider("claude", "Claude", windows, "statusline"));
+ merge_windows(hub, "claude", "Claude", "statusline", windows);
}
}
-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"])
- .stdin(std::process::Stdio::null())
- .output()
- .ok()?;
- if !out.status.success() {
- return None;
- }
- 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.
+/// Claude ACP adapter: `usage_update._meta["_claude/rateLimit"]` (the SDK's SDKRateLimitInfo).
+pub fn ingest_claude_rate_limit(hub: &Hub, info: &Value) {
+ if let Some(w) = claude_window(info) {
+ merge_windows(hub, "claude", "Claude", "agent", vec![w]);
}
- 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))
+fn claude_window(info: &Value) -> Option<Value> {
+ let kind = info["rateLimitType"].as_str()?;
+ let label = match kind {
+ "five_hour" => "5-hour",
+ "seven_day" => "Weekly",
+ "seven_day_opus" => "Weekly · Opus",
+ "seven_day_sonnet" => "Weekly · Sonnet",
+ _ => return None,
};
- 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)
+ let u = info["utilization"].as_f64()?;
+ // The SDK reports a 0–1 fraction (from the unified rate-limit headers).
+ let pct = if u <= 1.0 { u * 100.0 } else { u };
+ let resets = info["resetsAt"].as_i64().map(|t| if t > 100_000_000_000 { t } else { t * 1000 });
+ Some(window(kind, label, pct, resets))
}
fn newest_rollout(root: &Path) -> Option<PathBuf> {
@@ -232,15 +197,7 @@ 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);
+ fn parses_codex_rollout_limits() {
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}}),
@@ -249,6 +206,26 @@ mod tests {
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));
+ }
+
+ #[test]
+ fn parses_claude_usage_report() {
+ let w = parse_claude_usage(
+ "You are currently using your subscription\n\nCurrent session: 11% used · resets Sep 25 at 5am (Asia/Taipei)\nCurrent week (all models): 53% used · resets Sep 26 at 12pm (Asia/Taipei)\nCurrent week (Fable): 83% used · resets Sep 26 at 12pm (Asia/Taipei)\n\nLast 24h · 794 requests",
+ );
+ assert_eq!(w.len(), 3);
+ assert_eq!(w[0]["id"], "five_hour");
+ assert_eq!(w[0]["percent"], 11.0);
+ assert_eq!(w[0]["resetsText"], "Sep 25 at 5am (Asia/Taipei)");
+ assert_eq!(w[2]["label"], "Weekly · Fable");
+ }
+
+ #[test]
+ fn claude_rate_limit_fraction_becomes_percent() {
+ let w = claude_window(&json!({"rateLimitType": "five_hour", "utilization": 0.42, "resetsAt": 1_790_000_000}));
+ let w = w.unwrap();
+ assert_eq!(w["percent"], 42.0);
+ assert_eq!(w["resetsAt"], 1_790_000_000_000i64);
+ assert!(claude_window(&json!({"rateLimitType": "overage", "utilization": 0.1})).is_none());
}
}
diff --git a/project.yml b/project.yml
index a4664709..09065903 100644
--- a/project.yml
+++ b/project.yml
@@ -26,6 +26,9 @@ targets:
- Codync-macOS
dependencies:
- package: CodyncKit
+ product: CodyncKit
+ - package: CodyncKit
+ product: CodyncUI
settings:
base:
PRODUCT_NAME: Codync
@@ -65,6 +68,7 @@ targets:
else
cargo build --manifest-path "$SRCROOT/host/Cargo.toml" && BIN="$SRCROOT/host/target/debug/codync-host"
fi
+ [ -n "$BIN" ] || { echo "error: building codync-host failed"; exit 1; }
DEST="$TARGET_BUILD_DIR/$EXECUTABLE_FOLDER_PATH/codync-host"
cp "$BIN" "$DEST"
if [ -n "$EXPANDED_CODE_SIGN_IDENTITY" ] && [ "$CODE_SIGNING_ALLOWED" != "NO" ]; then
@@ -77,6 +81,9 @@ targets:
- Codync-iOS
dependencies:
- package: CodyncKit
+ product: CodyncKit
+ - package: CodyncKit
+ product: CodyncUI
- target: CodyncWidgets
embed: true
settings:
@@ -106,6 +113,7 @@ targets:
- CodyncWidgets
dependencies:
- package: CodyncKit
+ product: CodyncKit
- sdk: WidgetKit.framework
- sdk: SwiftUI.framework
settings: