Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
Snapshot of in-progress account and sign-in work
leepokai9a978d6e5828
diff --git a/.github/workflows/release-macos.yml b/.github/workflows/release-macos.ymlindex 2d1a6075..be9b3d5e 100644--- a/.github/workflows/release-macos.yml+++ b/.github/workflows/release-macos.yml@@ -46,6 +46,10 @@ jobs:security list-keychain -d user -s "$KEYCHAIN_FILE"+ - name: Metal toolchain+ # SwiftTerm (setup terminals) ships a Metal shader.+ run: xcodebuild -downloadComponent MetalToolchain+- name: Buildrun: |xcodebuild build \diff --git a/Codync.xcodeproj/project.pbxproj b/Codync.xcodeproj/project.pbxprojindex 5df13042..4bdc1bdb 100644--- a/Codync.xcodeproj/project.pbxproj+++ b/Codync.xcodeproj/project.pbxproj@@ -12,6 +12,7 @@24DF3CB466CC877FCB8BAED6 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 80868F96B9905FF52DCDFAE2 /* CodyncKit */; };25667EBFCCC64B96FDCE95A9 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 59F5D19A417A7A50596902FA /* CodyncKit */; };25FCB36A2661833502357807 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0A657FB98BBE0D73807B263 /* Session.swift */; };+ 28DE92C4209739829F6AD1A1 /* AccountSwitcherView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFE4E0839DCD380109300DF1 /* AccountSwitcherView.swift */; };2CC074683AE086D6C77CC1E8 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B274A0195CB3B2409EA4C194 /* WidgetKit.framework */; };2D724C1001CF872BAFCAE7EA /* IconButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3831394C093AF3A4E504BC5 /* IconButton.swift */; };2F0A1C29DBBD1D700C10BE46 /* CodyncApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = F45CCA6BBDCF412897AEC105 /* CodyncApp.swift */; };@@ -20,10 +21,11 @@48DAAA1384E5B8D0BA27C895 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1E47C60032C326157E0386B8 /* SwiftUI.framework */; };498C81B8C82557C85F912238 /* HostLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75CAC64DDC41D4A222A12DDE /* HostLink.swift */; };513F59BF65DED5379AB950A1 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = D2C705F063CD20F5B3036BD4 /* Assets.xcassets */; };- 52CF04B855C6AAEC47B75B8F /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = 06C9F37C6502131CAF0F145E /* CodyncUI */; };+ 52CF04B855C6AAEC47B75B8F /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1285DDFA0390A76ECDAAD6C0 /* CodyncKit */; };5F9AE9B8E7FF66F194162BDC /* ScreenHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB932B6C1849B8DF7CF7C2E3 /* ScreenHelper.swift */; };6A15821964A5EE5AEBB0C420 /* ClerkConfig.plist in Resources */ = {isa = PBXBuildFile; fileRef = 19D41F16A62FEF37BE0AD1FC /* ClerkConfig.plist */; };826FEDA23997E436D632E579 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB70DD8757C90695CDA211 /* PrivacyInfo.xcprivacy */; };+ 8AC8D90C21B92480E2809758 /* AccountSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B8EAB09016D328195FE2AD /* AccountSession.swift */; };8CD641A45F144BF41D703D2A /* CodyncMacApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2969919CCC8BC89F277C43A6 /* CodyncMacApp.swift */; };AA601649E43A5AF73DCF5B5E /* WebRTC in Frameworks */ = {isa = PBXBuildFile; productRef = 2D9748E611692583AFC5A152 /* WebRTC */; };ACCB28F3DB9C89108B7911E3 /* Input.swift in Sources */ = {isa = PBXBuildFile; fileRef = 842DA106CA15E3810C3C9461 /* Input.swift */; };@@ -32,18 +34,20 @@B75DD137E6F645F797B60B09 /* PairingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 739EC95223CC8F8717C33736 /* PairingView.swift */; };B8B86B2B7F8D9EE8639A9E09 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = BEE30A9D5C73E5A151F34180 /* CodyncUI */; };C937F66F810AA238B73E8363 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 4EDD440CC0624F03363AC1BA /* PrivacyInfo.xcprivacy */; };+ CA1174F732B066EAFA3D963C /* ClerkConfig.plist in Resources */ = {isa = PBXBuildFile; fileRef = D81BA172C8FED5521B00D5CF /* ClerkConfig.plist */; };CC9F6FB8055C38D5D625F738 /* BotListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5E57711E223A292872322C5 /* BotListView.swift */; };- D1374E0F041B7FEA4DFB33E7 /* AccountSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1D2C6A291E95D607E9EB1E7 /* AccountSession.swift */; };D4AB92074A9C0D9C72B4080A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E8B808BC2A9AA0ECD666A454 /* Assets.xcassets */; };DEF7478AB86DB605F52905F5 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE4AE9A34F61B3D28E0C2550 /* SettingsView.swift */; };E430F9317B690366F62164DB /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1B79D48C1D6F90D53751B3F /* RootView.swift */; };- EBB0417A5FB2CE6D514D21BE /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1285DDFA0390A76ECDAAD6C0 /* CodyncKit */; };+ EBB0417A5FB2CE6D514D21BE /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = D9AB2F442A5F243653EAE936 /* ClerkKit */; };EC14C7513A8D2999D97D5ABA /* Screen.app in Embed Dependencies */ = {isa = PBXBuildFile; fileRef = 741B706007BA1B91CB853699 /* Screen.app */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };ED143C01BF7AD4953101D160 /* UsageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47BCE8E2AFA6CA829DBC489A /* UsageView.swift */; };F0A26FABD15480810021C86A /* HostController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93A9881C76B67297BE26D8FD /* HostController.swift */; };+ F171F16563D1FF6308697173 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = 06C9F37C6502131CAF0F145E /* CodyncUI */; };F191B13B972C72CB4253B449 /* CodyncWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00F135A0B168269BD6C2A199 /* CodyncWidgets.swift */; };F842AE1C5ED96AF9A7F5D16C /* Widgets.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 6D734BEE7CD3F84677B0218B /* Widgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };F93D9960F7C20B2E629C1736 /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = 7D524C19E9D41C0CF635A619 /* ClerkKit */; };+ FF6CF0FBF496B5B50F09E063 /* AccountSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B8EAB09016D328195FE2AD /* AccountSession.swift */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */@@ -124,15 +128,17 @@991A0FD3EAAD4B446F3BF14E /* macOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = macOS.app; sourceTree = BUILT_PRODUCTS_DIR; };9A59E3A7670EAF57F2F4C9B9 /* ChatWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatWindow.swift; sourceTree = "<group>"; };AB932B6C1849B8DF7CF7C2E3 /* ScreenHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScreenHelper.swift; sourceTree = "<group>"; };+ AFE4E0839DCD380109300DF1 /* AccountSwitcherView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSwitcherView.swift; sourceTree = "<group>"; };B274A0195CB3B2409EA4C194 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };C5E57711E223A292872322C5 /* BotListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotListView.swift; sourceTree = "<group>"; };CE4D28E8291EEB43E17B11FA /* Capture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Capture.swift; sourceTree = "<group>"; };D0A657FB98BBE0D73807B263 /* Session.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Session.swift; sourceTree = "<group>"; };- D1D2C6A291E95D607E9EB1E7 /* AccountSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSession.swift; sourceTree = "<group>"; };D2C705F063CD20F5B3036BD4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };D3831394C093AF3A4E504BC5 /* IconButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IconButton.swift; sourceTree = "<group>"; };+ D81BA172C8FED5521B00D5CF /* ClerkConfig.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = ClerkConfig.plist; sourceTree = "<group>"; };DE4AE9A34F61B3D28E0C2550 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };E1B79D48C1D6F90D53751B3F /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };+ E4B8EAB09016D328195FE2AD /* AccountSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSession.swift; sourceTree = "<group>"; };E8B808BC2A9AA0ECD666A454 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };F0B6AECA1FDDD3064F3D4447 /* iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = iOS.entitlements; sourceTree = "<group>"; };F45CCA6BBDCF412897AEC105 /* CodyncApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncApp.swift; sourceTree = "<group>"; };@@ -171,8 +177,9 @@isa = PBXFrameworksBuildPhase;buildActionMask = 2147483647;files = (- EBB0417A5FB2CE6D514D21BE /* CodyncKit in Frameworks */,- 52CF04B855C6AAEC47B75B8F /* CodyncUI in Frameworks */,+ EBB0417A5FB2CE6D514D21BE /* ClerkKit in Frameworks */,+ 52CF04B855C6AAEC47B75B8F /* CodyncKit in Frameworks */,+ F171F16563D1FF6308697173 /* CodyncUI in Frameworks */,);runOnlyForDeploymentPostprocessing = 0;};@@ -182,6 +189,7 @@1E45A5D617A608D762EC7EC5 /* Views */ = {isa = PBXGroup;children = (+ AFE4E0839DCD380109300DF1 /* AccountSwitcherView.swift */,C5E57711E223A292872322C5 /* BotListView.swift */,739EC95223CC8F8717C33736 /* PairingView.swift */,E1B79D48C1D6F90D53751B3F /* RootView.swift */,@@ -206,6 +214,7 @@B297A6ACE16EAA751102BC05 /* ios */,C0244F098744E616AB7FA840 /* macos */,E6BF4F999DB656FB8CB90885 /* screen */,+ 450E7ADDBD0DD2889F3BF989 /* shared */,);path = apps;sourceTree = "<group>";@@ -230,6 +239,14 @@name = Products;sourceTree = "<group>";};+ 450E7ADDBD0DD2889F3BF989 /* shared */ = {+ isa = PBXGroup;+ children = (+ E4B8EAB09016D328195FE2AD /* AccountSession.swift */,+ );+ path = shared;+ sourceTree = "<group>";+ };5893B7E84BB07F9649417F2D /* App */ = {isa = PBXGroup;children = (@@ -288,7 +305,6 @@BDFF077DDD37FEC8B83F2AED /* App */ = {isa = PBXGroup;children = (- D1D2C6A291E95D607E9EB1E7 /* AccountSession.swift */,2969919CCC8BC89F277C43A6 /* CodyncMacApp.swift */,93A9881C76B67297BE26D8FD /* HostController.swift */,);@@ -320,6 +336,7 @@isa = PBXGroup;children = (D2C705F063CD20F5B3036BD4 /* Assets.xcassets */,+ D81BA172C8FED5521B00D5CF /* ClerkConfig.plist */,232B2C00B9575BFF7068BB62 /* Info.plist */,F0B6AECA1FDDD3064F3D4447 /* iOS.entitlements */,4EDD440CC0624F03363AC1BA /* PrivacyInfo.xcprivacy */,@@ -414,6 +431,7 @@);name = iOS;packageProductDependencies = (+ D9AB2F442A5F243653EAE936 /* ClerkKit */,1285DDFA0390A76ECDAAD6C0 /* CodyncKit */,06C9F37C6502131CAF0F145E /* CodyncUI */,);@@ -510,6 +528,7 @@buildActionMask = 2147483647;files = (513F59BF65DED5379AB950A1 /* Assets.xcassets in Resources */,+ CA1174F732B066EAFA3D963C /* ClerkConfig.plist in Resources */,C937F66F810AA238B73E8363 /* PrivacyInfo.xcprivacy in Resources */,);runOnlyForDeploymentPostprocessing = 0;@@ -574,6 +593,8 @@isa = PBXSourcesBuildPhase;buildActionMask = 2147483647;files = (+ FF6CF0FBF496B5B50F09E063 /* AccountSession.swift in Sources */,+ 28DE92C4209739829F6AD1A1 /* AccountSwitcherView.swift in Sources */,CC9F6FB8055C38D5D625F738 /* BotListView.swift in Sources */,2F0A1C29DBBD1D700C10BE46 /* CodyncApp.swift in Sources */,B75DD137E6F645F797B60B09 /* PairingView.swift in Sources */,@@ -588,7 +609,7 @@isa = PBXSourcesBuildPhase;buildActionMask = 2147483647;files = (- D1374E0F041B7FEA4DFB33E7 /* AccountSession.swift in Sources */,+ 8AC8D90C21B92480E2809758 /* AccountSession.swift in Sources */,03774684DC8344D81AFED53B /* ChatWindow.swift in Sources */,8CD641A45F144BF41D703D2A /* CodyncMacApp.swift in Sources */,F0A26FABD15480810021C86A /* HostController.swift in Sources */,@@ -1040,6 +1061,11 @@isa = XCSwiftPackageProductDependency;productName = CodyncUI;};+ D9AB2F442A5F243653EAE936 /* ClerkKit */ = {+ isa = XCSwiftPackageProductDependency;+ package = 2C830647014432C6F20C557C /* XCRemoteSwiftPackageReference "clerk-ios" */;+ productName = ClerkKit;+ };/* End XCSwiftPackageProductDependency section */};rootObject = 5B6351DD20AF4506794D6460 /* Project object */;diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swiftindex 2d9eab2f..673b5c5b 100644--- a/apps/ios/App/CodyncApp.swift+++ b/apps/ios/App/CodyncApp.swift@@ -1,25 +1,39 @@import CodyncKitimport CodyncUIimport SwiftUI+import Observationimport UserNotificationsimport WidgetKit@mainstruct CodyncApp: App {@UIApplicationDelegateAdaptor(AppDelegate.self) private var delegate- @State private var model = AppStore.shared+ @State private var app = AppStore.shared+ private var model: BotStore { app.model }@Environment(\.scenePhase) private var scenePhase@State private var tab = AppTab.botsvar body: some Scene {WindowGroup {RootView(tab: $tab)+ .id(app.contextID).environment(model)+ .environment(app.account).tint(Palette.accent)+ .sheet(isPresented: Bindable(app.account).showSwitcher) {+ NavigationStack { AccountSwitcherView().environment(app.account).environment(model) }+ }+ .onChange(of: app.account.userID, initial: true) { _, userID in+ app.switchAccount(to: userID)+ tab = .bots+ }.onOpenURL { url in- if let p = Pairing(url: url) {+ if url.scheme == "com.pokai.Codync.ios" {+ Task { await app.account.handle(url) }+ } else if let p = Pairing(url: url) {model.pair(p)} else if url.host() == "bot" {+ guard model.storage.acceptsBotURL(url) else { return }model.selection = url.lastPathComponent} else if url.host() == "plugins" {model.selection = nil@@ -55,23 +69,57 @@ struct CodyncApp: App {}}-/// The phone's store, wired to push registration, Live Activities and widgets.+/// A new host mirror for each account prevents in-flight work from being+/// applied to another user's screen or storage. Cloud ownership is separate.@MainActor-enum AppStore {- static let shared: BotStore = {- let store = BotStore(pairing: SharedStore.pairing, clientKind: "ios", persistsPairing: true)+@Observable+final class AppStore {+ static let shared = AppStore()+ let account = AccountSession()+ private(set) var model: BotStore+ private(set) var contextID: String++ private init() {+ let storage = SharedStore.Context(accountID: account.userID)+ SharedStore.activeAccountID = account.userID+ contextID = storage.id+ model = Self.makeStore(storage)+ }++ func switchAccount(to userID: String?) {+ let storage = SharedStore.Context(accountID: userID)+ guard storage.id != contextID else { return }+ model.retire()+ PushRegistrar.shared.deactivate()+ LiveActivities.shared.endAll()+ SharedStore.activeAccountID = userID+ storage.bots = []+ storage.usage = nil+ contextID = storage.id+ model = Self.makeStore(storage)+ BotsWidgetFeed.reset()+ WidgetCenter.shared.reloadAllTimelines()+ model.setActive(true)+ }++ private static func makeStore(_ storage: SharedStore.Context) -> BotStore {+ let store = BotStore(pairing: storage.pairing, clientKind: "ios", persistsPairing: true, storage: storage)store.onPaired = { PushRegistrar.shared.syncDevice(with: $0) }- store.onBotUpdated = {- LiveActivities.shared.update(bot: $0)+ store.onBotUpdated = { [weak store] bot in+ guard let store else { return }+ LiveActivities.shared.update(bot: bot)BotsWidgetFeed.update(store.roster)}- store.onSent = { LiveActivities.shared.start(for: $0, model: store) }+ store.onSent = { [weak store] bot in+ guard let store else { return }+ LiveActivities.shared.start(for: bot, model: store)+ }store.onUsageChanged = { usage in- SharedStore.usage = usage+ storage.usage = usageWidgetCenter.shared.reloadAllTimelines()}return store- }()+ }}final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {@@ -92,7 +140,13 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCentnonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {let botId = response.notification.request.content.userInfo["botId"] as? Stringif let botId {- await MainActor.run { AppStore.shared.selection = botId }+ await MainActor.run {+ // Legacy push payloads have no account/computer identity. Never+ // route one into a signed-in account using only a naked bot ID.+ let app = AppStore.shared+ guard app.account.userID == nil, app.model.bots[botId] != nil else { return }+ app.model.selection = botId+ }}}@@ -108,6 +162,8 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCentenum BotsWidgetFeed {private static var shown = ""+ static func reset() { shown = "" }+static func update(_ roster: [Bot]) {SharedStore.bots = rosterlet signature = roster.map { "\($0.id):\($0.status):\($0.unread)" }.joined(separator: ",")diff --git a/apps/ios/App/Push.swift b/apps/ios/App/Push.swiftindex 94b2ca15..74bcbdcc 100644--- a/apps/ios/App/Push.swift+++ b/apps/ios/App/Push.swift@@ -35,6 +35,13 @@ final class PushRegistrar {private var deviceToken: Data?private weak var model: BotStore?+ private var registrationTask: Task<Void, Never>?++ func deactivate() {+ registrationTask?.cancel()+ registrationTask = nil+ model = nil+ }func requestAuthorization() async -> Bool {let granted = (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])) ?? false@@ -57,10 +64,15 @@ final class PushRegistrar {}return}- Task {+ registrationTask?.cancel()+ let pairing = model.storage.orderedPairing+ registrationTask = Task { [weak model] indo {let ticket = try await relayTicket(token: token, kind: "alert")- guard let pairing = SharedStore.orderedPairing, let client = await HostClient.resolve(pairing) else { return }+ try Task.checkCancellation()+ guard let model, self.model === model, let pairing,+ let client = await HostClient.resolve(pairing) else { return }+ try Task.checkCancellation()try await client.registerDevice(ticket: ticket, relay: SharedStore.relayURL, name: UIDevice.current.name)log.info("device registered with host")} catch {@@ -75,24 +87,47 @@ final class PushRegistrar {final class LiveActivities {static let shared = LiveActivities()+ private var requests: [UUID: Task<Void, Never>] = [:]++ func endAll() {+ requests.values.forEach { $0.cancel() }+ requests.removeAll()+ let ids = Set(Activity<BotActivityAttributes>.activities.map(\.id))+ Task.detached {+ for activity in Activity<BotActivityAttributes>.activities where ids.contains(activity.id) {+ await activity.end(nil, dismissalPolicy: .immediate)+ }+ }+ }+private nonisolated static func find(_ botId: String) -> Activity<BotActivityAttributes>? {Activity<BotActivityAttributes>.activities.first { $0.attributes.botId == botId }}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) }+ let attributes = BotActivityAttributes(bot: bot, link: model.storage.botURL(bot.id))+ let id = UUID()+ requests[id] = Task.detached { [weak self] in+ await Self.request(attributes: attributes, client: client)+ await self?.finishedRequest(id)+ }}+ private func finishedRequest(_ id: UUID) { requests[id] = nil }+private nonisolated static func request(attributes: BotActivityAttributes, client: HostClient) async {let state = BotActivityAttributes.ContentState(status: "working", activity: "Starting…", startedAt: .now)do {+ try Task.checkCancellation()let activity = try Activity.request(attributes: attributes, content: .init(state: state, staleDate: nil), pushType: .token)for await token in activity.pushTokenUpdates {+ guard !Task.isCancelled else { break }guard let ticket = try? await relayTicket(token: token, kind: "liveactivity") else { continue }+ guard !Task.isCancelled else { break }try? await client.registerActivity(botId: attributes.botId, ticket: ticket)}+ if Task.isCancelled { await activity.end(nil, dismissalPolicy: .immediate) }} catch {log.info("live activity not started: \(error.localizedDescription)")}diff --git a/apps/ios/Resources/ClerkConfig.plist b/apps/ios/Resources/ClerkConfig.plistnew file mode 100644index 00000000..400a55f7--- /dev/null+++ b/apps/ios/Resources/ClerkConfig.plist@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>publishableKey</key>+ <string>pk_test_c3VubnktbW9sbHVzay04NjUxLmNsZXJrLmFjY291bnRzLmRldiQ</string>+</dict>+</plist>diff --git a/apps/ios/Resources/Info.plist b/apps/ios/Resources/Info.plistindex f3549cc4..7beeeadb 100644--- a/apps/ios/Resources/Info.plist+++ b/apps/ios/Resources/Info.plist@@ -10,6 +10,7 @@<key>CFBundleURLSchemes</key><array><string>codync</string>+ <string>com.pokai.Codync.ios</string></array></dict></array>diff --git a/apps/ios/Views/AccountSwitcherView.swift b/apps/ios/Views/AccountSwitcherView.swiftnew file mode 100644index 00000000..a91ff452--- /dev/null+++ b/apps/ios/Views/AccountSwitcherView.swift@@ -0,0 +1,129 @@+import CodyncKit+import CodyncUI+import SwiftUI++struct AccountSwitcherButton: View {+ @Environment(AccountSession.self) private var account++ var body: some View {+ Button { account.showSwitcher = true } label: {+ HStack(spacing: 4) {+ AccountAvatar(url: account.avatarURL, size: 30)+ Image(systemName: "chevron.down")+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(Palette.secondary)+ }+ }+ .accessibilityLabel("Switch account")+ .accessibilityValue(account.email ?? "Local pairing")+ }+}++struct AccountSwitcherView: View {+ @Environment(AccountSession.self) private var account+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ Form {+ Section("Accounts") {+ if account.accounts.isEmpty {+ Label("Local pairing", systemImage: "person.crop.circle")+ .foregroundStyle(Palette.secondary)+ }+ ForEach(account.accounts) { item in+ Button {+ Task { await account.switchAccount(item) }+ } label: {+ HStack(spacing: 12) {+ AccountAvatar(url: item.avatarURL, size: 34)+ Text(item.email)+ .lineLimit(1)+ .foregroundStyle(Palette.text)+ Spacer(minLength: 8)+ if item.id == account.userID {+ Image(systemName: "checkmark")+ .foregroundStyle(Palette.text)+ .accessibilityLabel("Current account")+ }+ }+ }+ .disabled(account.isBusy)+ }+ if !account.isSignedIn || account.supportsMultipleAccounts {+ Button {+ Task { await account.signIn() }+ } label: {+ Label(account.isSignedIn ? "Add Google account" : "Continue with Google", systemImage: "person.crop.circle.badge.plus")+ }+ .disabled(account.isBusy || !account.isConfigured)+ }+ }++ Section {+ NavigationLink {+ SettingsView()+ } label: {+ Label("Computers & settings", systemImage: "desktopcomputer")+ }+ } footer: {+ Text("Computer connections are saved separately for each account on this iPhone. Pair a computer to see its bots.")+ }++ if account.isSignedIn {+ Section {+ Button("Sign out of this account", role: .destructive) {+ Task { await account.signOut() }+ }+ .disabled(account.isBusy)+ } footer: {+ if !account.supportsMultipleAccounts {+ Text("Sign out to use a different Google account.")+ }+ }+ }++ if !account.isConfigured {+ Section {+ Text("Account sign-in isn't configured in this build. Local pairing is available.")+ .foregroundStyle(Palette.secondary)+ }+ }+ if let message = account.errorMessage {+ Section {+ Text(message).foregroundStyle(Palette.danger)+ }+ }+ }+ .scrollContentBackground(.hidden)+ .background(Palette.background)+ .navigationTitle("Accounts")+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Close", systemImage: "xmark") { dismiss() }+ .labelStyle(.iconOnly)+ }+ if account.isBusy {+ ToolbarItem(placement: .topBarTrailing) { ProgressView() }+ }+ }+ }+}++private struct AccountAvatar: View {+ let url: URL?+ let size: CGFloat++ var body: some View {+ AsyncImage(url: url) { image in+ image.resizable().scaledToFill()+ } placeholder: {+ Image(systemName: "person.crop.circle.fill")+ .resizable()+ .foregroundStyle(Palette.secondary)+ }+ .frame(width: size, height: size)+ .clipShape(Circle())+ .accessibilityHidden(true)+ }+}diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swiftindex a7d625eb..172ed29e 100644--- a/apps/ios/Views/BotListView.swift+++ b/apps/ios/Views/BotListView.swift@@ -59,10 +59,7 @@ struct BotListView: View {.navigationBarTitleDisplayMode(.inline).toolbar {ToolbarItem(placement: .topBarLeading) {- Button { model.showProfile = true } label: {- ComputerBadge(model.pairing, size: 36)- }- .accessibilityLabel("Profile and computers")+ AccountSwitcherButton()}// Grok-style bare top bar: no visible title, just the two buttons.ToolbarItem(placement: .principal) { Color.clear.frame(width: 1, height: 1) }diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swiftindex e4ea871b..102bcf51 100644--- a/apps/ios/Views/PairingView.swift+++ b/apps/ios/Views/PairingView.swift@@ -74,7 +74,7 @@ struct PairingView: View {}}- Text("Your phone talks straight to your computer over Tailscale or local Wi-Fi. Codync has no account and no cloud copy of your code or chats.")+ Text("Pair this computer with the account currently selected on this iPhone. Your phone connects over Tailscale or local Wi-Fi; your code and chats stay on the computer.").font(.footnote).foregroundStyle(Palette.tertiary)}diff --git a/apps/ios/Views/RootView.swift b/apps/ios/Views/RootView.swiftindex 80f1ea9a..84574716 100644--- a/apps/ios/Views/RootView.swift+++ b/apps/ios/Views/RootView.swift@@ -16,7 +16,12 @@ struct RootView: View {var body: some View {Group {if model.pairing == nil {- PairingView()+ NavigationStack {+ PairingView()+ .toolbar {+ ToolbarItem(placement: .topBarLeading) { AccountSwitcherButton() }+ }+ }} else {TabView(selection: $tab) {Tab("Bots", systemImage: "bubble.left.and.bubble.right.fill", value: .bots) {diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swiftindex 530228ed..0d276052 100644--- a/apps/ios/Views/SettingsView.swift+++ b/apps/ios/Views/SettingsView.swift@@ -3,8 +3,7 @@ import CodyncUIimport SwiftUIimport UserNotifications-/// The profile sheet behind the top-left button: which computer you're talking-/// to (and switching between them), notifications, hidden bots.+/// Computer connections and settings for the currently selected account.struct SettingsView: View {@Environment(BotStore.self) private var model@Environment(\.dismiss) private var dismiss@@ -45,8 +44,10 @@ struct SettingsView: View {Label("Add a computer", systemImage: "plus").foregroundStyle(Palette.text)}+ } header: {+ Text("Computers on this iPhone")} footer: {- Text("Each computer has its own bots. Tap one to switch.")+ Text("Each bot runs on its own computer. Tap a computer to view its bots.")}Section {@@ -88,6 +89,7 @@ struct SettingsView: View {}.scrollContentBackground(.hidden).background(Palette.background)+ .navigationTitle("Computers & settings").navigationBarTitleDisplayMode(.inline).toolbar {ToolbarItem(placement: .cancellationAction) {diff --git a/apps/ios/Widgets/CodyncWidgets.swift b/apps/ios/Widgets/CodyncWidgets.swiftindex 17c8736b..adc867ea 100644--- a/apps/ios/Widgets/CodyncWidgets.swift+++ b/apps/ios/Widgets/CodyncWidgets.swift@@ -20,6 +20,7 @@ struct BotsEntry: TimelineEntry {let date: Datelet bots: [Bot]let paired: Bool+ var links: [String: URL] = [:]}struct BotsTimeline: TimelineProvider {@@ -32,7 +33,9 @@ struct BotsTimeline: TimelineProvider {/// The app writes the roster and reloads this widget when a bot's state changes.func getTimeline(in context: Context, completion: @escaping (Timeline<BotsEntry>) -> Void) {- let entry = BotsEntry(date: .now, bots: SharedStore.bots, paired: SharedStore.pairing != nil)+ let storage = SharedStore.activeContext+ let entry = BotsEntry(date: .now, bots: storage.bots, paired: storage.pairing != nil,+ links: Dictionary(storage.bots.map { ($0.id, storage.botURL($0.id)) }, uniquingKeysWith: { a, _ in a }))completion(Timeline(entries: [entry], policy: .never))}}@@ -96,7 +99,7 @@ struct BotsWidgetView: View {summary.frame(width: 104, alignment: .leading)VStack(alignment: .leading, spacing: 10) {ForEach(ordered.prefix(3)) { bot in- Link(destination: URL(string: "codync://bot/\(bot.id)")!) { BotLine(bot: bot, detail: line(bot)) }+ Link(destination: entry.links[bot.id] ?? URL(string: "codync://computers")!) { BotLine(bot: bot, detail: line(bot)) }}Spacer(minLength: 0)}@@ -112,7 +115,7 @@ struct BotsWidgetView: View {summary}.frame(maxWidth: .infinity, alignment: .leading)- .widgetURL(ordered.first.map { URL(string: "codync://bot/\($0.id)")! })+ .widgetURL(ordered.first.flatMap { entry.links[$0.id] })}}}@@ -490,7 +493,7 @@ struct BotLiveActivity: Widget {ActivityConfiguration(for: BotActivityAttributes.self) { context inLockScreenView(context: context).activityBackgroundTint(Palette.background)- .widgetURL(URL(string: "codync://bot/\(context.attributes.botId)"))+ .widgetURL(context.attributes.link ?? URL(string: "codync://computers"))} dynamicIsland: { context inlet s = context.statereturn DynamicIsland {@@ -523,7 +526,7 @@ struct BotLiveActivity: Widget {} minimal: {CharacterAvatar(shape: context.attributes.avatarShape, color: context.attributes.avatarColor, size: 20)}- .widgetURL(URL(string: "codync://bot/\(context.attributes.botId)"))+ .widgetURL(context.attributes.link ?? URL(string: "codync://computers"))}}}diff --git a/apps/macos/App/CodyncMacApp.swift b/apps/macos/App/CodyncMacApp.swiftindex 7a52a263..e4aa5866 100644--- a/apps/macos/App/CodyncMacApp.swift+++ b/apps/macos/App/CodyncMacApp.swift@@ -106,7 +106,7 @@ struct MenuView: View {if host.needsAttention {("A bot needs you", Palette.warning)} else if host.working > 0 {- ("\(host.working) bot\(host.working == 1 ? "" : "s") working", Palette.switchOn)+ ("\(host.working) bot\(host.working == 1 ? "" : "s") working", Palette.accent)} else {("Connected", nil)}@@ -248,15 +248,15 @@ private struct RemoteScreenSection: View {HStack(spacing: 10) {Image(systemName: "display").font(.system(size: 13, weight: .semibold))- .foregroundStyle(screen.enabled ? .white : Palette.text)+ .foregroundStyle(screen.enabled ? Palette.onAccent : Palette.text).frame(width: 30, height: 30)- .background(screen.enabled ? Palette.switchOn : Palette.bubbleUser, in: Circle())+ .background(screen.enabled ? Palette.accentFill : Palette.bubbleUser, in: Circle()).accessibilityHidden(true)VStack(alignment: .leading, spacing: 1) {Text("Remote screen").font(.callout.weight(.medium)).foregroundStyle(Palette.text)Text(subtitle(screen)).font(.caption)- .foregroundStyle(screen.enabled && screen.viewers > 0 ? Palette.switchOn : Palette.secondary)+ .foregroundStyle(screen.enabled && screen.viewers > 0 ? Palette.text : Palette.secondary).lineLimit(2).fixedSize(horizontal: false, vertical: true)}@@ -265,6 +265,8 @@ private struct RemoteScreenSection: View {.labelsHidden().toggleStyle(.switch).controlSize(.mini)+ // Grey, not blue: a white track would hide the white knob.+ .tint(Palette.secondary)}if screen.enabled {if host.screenAgentNeedsApproval {diff --git a/apps/macos/Views/ChatWindow.swift b/apps/macos/Views/ChatWindow.swiftindex 2a23144e..376c49ac 100644--- a/apps/macos/Views/ChatWindow.swift+++ b/apps/macos/Views/ChatWindow.swift@@ -31,6 +31,9 @@ private struct ChatSplitView: View {@Environment(AccountSession.self) private var account@State private var editing: EditorRequest?@State private var confirmDelete: Bot?+ @State private var contextBot: Bot?+ @State private var contextPoint = CGPoint.zero+ @State private var newSessionBot: Bot?@State private var composing = false@State private var previousSelection: String?@State private var hoveredBot: String?@@ -89,7 +92,19 @@ private struct ChatSplitView: View {.accessibilityAddTraits(model.selection == bot.id ? .isSelected : []).help(bot.name).onHover { hoveredBot = $0 ? bot.id : nil }- .contextMenu { botMenu(bot) }+ .overlay {+ GeometryReader { geometry in+ SecondaryClickCapture { point in+ let frame = geometry.frame(in: .named("chat-window"))+ contextPoint = CGPoint(x: frame.minX + point.x, y: frame.minY + point.y)+ contextBot = bot+ }+ }+ }+ .accessibilityAction(named: "Conversation actions") {+ contextPoint = CGPoint(x: compact ? 64 : sidebarWidth - 24, y: 100)+ contextBot = bot+ }}}.padding(.horizontal, 12)@@ -186,8 +201,8 @@ private struct ChatSplitView: View {// Animate mode changes from every entry point, while ordinary resizing tracks the pointer..animation(Motion.reduced(Motion.layout, reduceMotion), value: compact).coordinateSpace(name: "chat-window")- .allowsHitTesting(!showAccount)- .accessibilityHidden(showAccount)+ .allowsHitTesting(!showAccount && contextBot == nil)+ .accessibilityHidden(showAccount || contextBot != nil).overlay(alignment: .bottomLeading) {if showAccount {ZStack(alignment: .bottomLeading) {@@ -220,13 +235,29 @@ private struct ChatSplitView: View {},onSearch: { dismissAccountMenu(); compact = false; searchFocused = true })- .frame(width: min(288, windowSize.width - 32))+ .frame(width: min(260, windowSize.width - 32)).padding(.leading, 16).padding(.bottom, compact ? 68 : 64).transition(.scale(scale: 0.97, anchor: .bottomLeading).combined(with: .opacity))}}}+ .overlay(alignment: .topLeading) {+ if let bot = contextBot {+ ZStack(alignment: .topLeading) {+ Color.black.opacity(0.001)+ .contentShape(Rectangle())+ .onTapGesture { contextBot = nil }+ .accessibilityLabel("Dismiss conversation menu")+ .accessibilityAddTraits(.isButton)+ DesktopActionMenu(items: botActions(bot), onDismiss: { contextBot = nil })+ .frame(width: 260)+ .offset(x: min(max(8, contextPoint.x), windowSize.width - 268),+ y: min(max(8, contextPoint.y), max(8, windowSize.height - 344)))+ .transition(.opacity)+ }+ }+ }.animation(Motion.reduced(Motion.fade, reduceMotion), value: showAccount).ignoresSafeArea(.container, edges: .top).sheet(item: $editing) { request in@@ -271,6 +302,16 @@ private struct ChatSplitView: View {sidebarWidth = min(sidebarWidth, max(260, $0.width - 420))}.hiddenWindowTitle()+ .confirmationDialog("Start a new session?", isPresented: Binding(+ get: { newSessionBot != nil },+ set: { if !$0 { newSessionBot = nil } }+ ), titleVisibility: .visible) {+ if let bot = newSessionBot {+ Button("New session") { model.newSession(bot.id); newSessionBot = nil }+ }+ } message: {+ Text("The conversation stays here, but the agent starts with a fresh context.")+ }.deleteBotConfirmation($confirmDelete).storeErrorAlert(model).animation(Motion.reduced(Motion.fade, reduceMotion), value: model.selection)@@ -360,7 +401,7 @@ extension ChatSplitView {}.font(.system(size: 13)).padding(.horizontal, 9)- .frame(height: 32)+ .frame(height: 28).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 8)).overlay(RoundedRectangle(cornerRadius: 8).stroke(Palette.border, lineWidth: 0.5)).padding(.horizontal, 12)@@ -377,7 +418,7 @@ extension ChatSplitView {AsyncImage(url: url) { image in image.resizable().scaledToFill() } placeholder: { profilePlaceholder }} else { profilePlaceholder }}- .frame(width: 32, height: 32)+ .frame(width: 28, height: 28).background(Palette.bubbleUser, in: Circle()).clipShape(Circle()).overlay(Circle().strokeBorder(Palette.text.opacity(0.08), lineWidth: 0.5))@@ -407,7 +448,7 @@ extension ChatSplitView {Spacer(minLength: 0)}.padding(.horizontal, 8)- .frame(height: 42)+ .frame(height: 36).background(hoveredFooter == "marketplace" ? Palette.bubbleAgent : .clear,in: RoundedRectangle(cornerRadius: 10)).contentShape(Rectangle())@@ -426,7 +467,7 @@ extension ChatSplitView {}.padding(.horizontal, 8)- .frame(height: 44)+ .frame(height: 38).background(hoveredFooter == "account" || showAccount ? Palette.bubbleAgent : .clear,in: RoundedRectangle(cornerRadius: 10)).contentShape(Rectangle())@@ -498,13 +539,21 @@ extension ChatSplitView {.padding(.bottom, 10)}- @ViewBuilder fileprivate func botMenu(_ bot: Bot) -> some View {- 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 }+ private func botActions(_ bot: Bot) -> [DesktopActionMenu.Item] {+ [+ .init(title: bot.pinned ? "Unpin" : "Pin", icon: "pin", action: { model.setPinned(bot, !bot.pinned) }),+ .init(title: "Mark as Read", icon: "bell.badge", action: { model.markRead(bot.id) }),+ .init(title: "Edit Profile…", icon: "square.and.pencil", divider: true,+ action: { editing = EditorRequest(BotDraft(bot)) }),+ .init(title: "Copy conversation ID", icon: "square.on.square", divider: true, action: {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(bot.id, forType: .string)+ }),+ .init(title: "New session", icon: "arrow.counterclockwise", action: { newSessionBot = bot }),+ .init(title: "Hide from sidebar", icon: "eye.slash", divider: true,+ action: { model.setHidden(bot, true) }),+ .init(title: "Delete", icon: "trash", destructive: true, action: { confirmDelete = bot })+ ]}}@@ -600,7 +649,7 @@ private struct SidebarAccountPanel: View {if let errorMessage, page == "main" {Text(errorMessage).font(.system(size: 12)).foregroundStyle(Palette.warning).fixedSize(horizontal: false, vertical: true)- .padding(.horizontal, 12).padding(.vertical, 8)+ .padding(.horizontal, 10).padding(.vertical, 8)}}}@@ -615,20 +664,20 @@ private struct SidebarAccountPanel: View {}private var accountIdentity: some View {- HStack(spacing: 10) {- Image(systemName: "person.crop.circle").font(.system(size: 18))+ HStack(spacing: 8) {+ Image(systemName: "person.crop.circle").font(.system(size: 15))Text(email ?? name).font(.system(size: 12)).lineLimit(1)Spacer()if !signedIn { Text("Not signed in").font(.system(size: 11)) }}.foregroundStyle(Palette.secondary)- .padding(.horizontal, 12)- .frame(height: 38)+ .padding(.horizontal, 10)+ .frame(height: 30)}private var divider: some View {Rectangle().fill(Palette.text.opacity(0.13)).frame(height: 0.5)- .padding(.horizontal, 10).padding(.vertical, 7)+ .padding(.horizontal, 10).padding(.vertical, 5)}private func navigate(_ destination: String) {@@ -659,21 +708,22 @@ private struct AccountPanelRow: View {let detail: String?let chevron: Boollet keyboardFocused: Bool+ var destructive = falselet action: () -> Void@State private var hovered = falsevar body: some View {Button(action: action) {- HStack(spacing: 10) {- Image(systemName: icon).font(.system(size: 16, weight: .regular)).frame(width: 20)- Text(title).font(.system(size: 14)).lineLimit(1)+ HStack(spacing: 8) {+ Image(systemName: icon).font(.system(size: 14, weight: .regular)).frame(width: 20)+ Text(title).font(.system(size: 12)).lineLimit(1)Spacer(minLength: 8)if let detail { Text(detail).font(.system(size: 13)).foregroundStyle(Palette.secondary) }if chevron { Image(systemName: "chevron.right").font(.system(size: 11)).foregroundStyle(Palette.secondary) }}- .foregroundStyle(Palette.text)- .padding(.horizontal, 12)- .frame(height: 40)+ .foregroundStyle(destructive ? Palette.danger : Palette.text)+ .padding(.horizontal, 10)+ .frame(height: 30).background(hovered || keyboardFocused ? Palette.text.opacity(0.08) : .clear,in: RoundedRectangle(cornerRadius: 10)).contentShape(Rectangle())@@ -683,3 +733,87 @@ private struct AccountPanelRow: View {.onHover { hovered = $0 }}}++/// A SwiftUI action surface shared by pointer and accessibility entry points.+private struct DesktopActionMenu: View {+ struct Item {+ let title: String+ let icon: String+ var divider = false+ var destructive = false+ let action: () -> Void+ }++ let items: [Item]+ let onDismiss: () -> Void+ @State private var highlighted = 0+ @FocusState private var focused: Bool++ var body: some View {+ VStack(spacing: 2) {+ ForEach(items.indices, id: \.self) { index in+ let item = items[index]+ if item.divider {+ Rectangle().fill(Palette.text.opacity(0.13)).frame(height: 0.5)+ .padding(.horizontal, 10).padding(.vertical, 5)+ }+ AccountPanelRow(title: item.title, icon: item.icon, detail: nil,+ chevron: false, keyboardFocused: highlighted == index,+ destructive: item.destructive) { activate(index) }+ .onHover { if $0 { highlighted = index } }+ }+ }+ .padding(7)+ .background(Color(light: 0xFAFAFA, dark: 0x1B1B1B), in: RoundedRectangle(cornerRadius: 14))+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Palette.text.opacity(0.15), lineWidth: 0.5))+ .shadow(color: .black.opacity(0.25), radius: 20, x: 0, y: 8)+ .accessibilityElement(children: .contain)+ .accessibilityLabel("Conversation actions")+ .focusable()+ .focused($focused)+ .focusEffectDisabled()+ .onKeyPress(.escape) { onDismiss(); return .handled }+ .onKeyPress(.downArrow) { move(1); return .handled }+ .onKeyPress(.upArrow) { move(-1); return .handled }+ .onKeyPress(.tab, phases: .down) { press in move(press.modifiers.contains(.shift) ? -1 : 1); return .handled }+ .onKeyPress(.return) { activate(highlighted); return .handled }+ .onKeyPress(.space) { activate(highlighted); return .handled }+ .task { await Task.yield(); focused = true }+ }++ private func move(_ delta: Int) { highlighted = (highlighted + delta + items.count) % items.count }++ private func activate(_ index: Int) {+ guard items.indices.contains(index) else { return }+ onDismiss()+ items[index].action()+ }+}++/// Intercepts only secondary clicks; primary clicks, scrolling and dragging pass through.+private struct SecondaryClickCapture: NSViewRepresentable {+ let onClick: (CGPoint) -> Void++ func makeNSView(context: Context) -> CaptureView { CaptureView(onClick: onClick) }+ func updateNSView(_ view: CaptureView, context: Context) { view.onClick = onClick }++ final class CaptureView: NSView {+ var onClick: (CGPoint) -> Void+ override var isFlipped: Bool { true }++ init(onClick: @escaping (CGPoint) -> Void) {+ self.onClick = onClick+ super.init(frame: .zero)+ }+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }++ override func hitTest(_ point: NSPoint) -> NSView? {+ guard let event = NSApp.currentEvent,+ event.type == .rightMouseDown || (event.type == .leftMouseDown && event.modifierFlags.contains(.control))+ else { return nil }+ return super.hitTest(point)+ }+ override func rightMouseDown(with event: NSEvent) { onClick(convert(event.locationInWindow, from: nil)) }+ override func mouseDown(with event: NSEvent) { onClick(convert(event.locationInWindow, from: nil)) }+ }+}diff --git a/apps/macos/App/AccountSession.swift b/apps/shared/AccountSession.swiftsimilarity index 59%rename from apps/macos/App/AccountSession.swiftrename to apps/shared/AccountSession.swiftindex 8b185aea..b589153c 100644--- a/apps/macos/App/AccountSession.swift+++ b/apps/shared/AccountSession.swift@@ -12,8 +12,30 @@ final class AccountSession {private(set) var isBusy = falsevar errorMessage: String?+ var showSwitcher = false++ struct Account: Identifiable {+ let id: String+ let sessionID: String+ let email: String+ let avatarURL: URL?+ }++ var userID: String? { clerk?.session?.status == .active ? clerk?.user?.id : nil }+ var accounts: [Account] {+ var seen = Set<String>()+ return (clerk?.auth.sessions ?? []).compactMap { session in+ guard session.status == .active, session.expireAt > .now,+ let user = session.user, seen.insert(user.id).inserted else { return nil }+ return Account(id: user.id, sessionID: session.id,+ email: user.primaryEmailAddress?.emailAddress ?? "Codync account",+ avatarURL: URL(string: user.imageUrl).flatMap { $0.scheme == "https" ? $0 : nil })+ }+ }+ var supportsMultipleAccounts: Bool { clerk?.environment?.authConfig.singleSessionMode == false }+var isConfigured: Bool { clerk != nil }- var isSignedIn: Bool { clerk?.user != nil }+ var isSignedIn: Bool { userID != nil }var email: String? { clerk?.user?.primaryEmailAddress?.emailAddress }var avatarURL: URL? {guard let image = clerk?.user?.imageUrl, let url = URL(string: image), url.scheme == "https" else { return nil }@@ -30,16 +52,17 @@ final class AccountSession {clerk = nilreturn}+ let scheme = Bundle.main.bundleIdentifier ?? "com.pokai.Codync"clerk = Clerk.configure(publishableKey: key, options: .init(telemetryEnabled: false,- redirectConfig: .init(redirectUrl: "com.pokai.Codync://callback", callbackUrlScheme: "com.pokai.Codync")+ redirectConfig: .init(redirectUrl: "\(scheme)://callback", callbackUrlScheme: scheme)))}func signIn() async {guard !isBusy else { return }guard let clerk else {- errorMessage = "Sign-in setup isn't finished yet. You can continue using Codync on this Mac."+ errorMessage = "Sign-in setup isn't finished yet. You can continue using local pairing."return}isBusy = true@@ -47,7 +70,7 @@ final class AccountSession {defer { isBusy = false }do {// Start Google directly; Clerk transfers new users into sign-up.- let result = try await clerk.auth.signInWithOAuth(provider: .google)+ let result = try await clerk.auth.signInWithOAuth(provider: .google, prefersEphemeralWebBrowserSession: isSignedIn)switch result {case .signIn(let signIn):if signIn.status != .complete {@@ -68,17 +91,35 @@ final class AccountSession {}func signOut() async {- guard !isBusy, let clerk else { return }+ guard !isBusy, let clerk, let sessionID = clerk.session?.id else { return }isBusy = trueerrorMessage = nildefer { isBusy = false }do {- try await clerk.auth.signOut()+ try await clerk.auth.signOut(sessionId: sessionID)} catch {errorMessage = "Couldn't sign out. Check your connection and try again."}}+ func switchAccount(_ account: Account) async {+ guard !isBusy, let clerk, account.id != userID else { return }+ isBusy = true+ errorMessage = nil+ defer { isBusy = false }+ do {+ try await clerk.auth.setActive(sessionId: account.sessionID)+ } catch {+ errorMessage = "Couldn't switch accounts. Check your connection or sign in again."+ }+ }++ func handle(_ url: URL) async {+ guard let clerk else { return }+ do { try await clerk.handle(url) }+ catch { errorMessage = "Couldn't finish signing in. Please try again." }+ }+private struct Configuration: Decodable {let publishableKey: String}diff --git a/docs/bot-computer-ssh-plan.md b/docs/bot-computer-ssh-plan.mdnew file mode 100644index 00000000..3cb38adf--- /dev/null+++ b/docs/bot-computer-ssh-plan.md@@ -0,0 +1,186 @@+# Bot、computer、帳號切換與 SSH 遠端執行計畫++日期:2026-09-25+狀態:規劃;補充 [Cloudflare 帳號與裝置管理計畫](cloudflare-account-device-plan.md)。++## 1. 產品目標++使用者可以在同一個 Codync 介面與多個 bots 聊天,每個 bot 固定使用一台 computer。這台 computer 可以是正在操作的 Mac,也可以是透過網路/SSH 連上的遠端電腦。++例如:++| Bot | Computer | 實際執行位置 | Mac 的連線方式 |+|---|---|---|---|+| Personal reviewer | My MacBook | 本機專案與 agent | 本機連線 |+| Backend maintainer | Dev Linux | 遠端 repo 與 agent | SSH tunnel |+| Build assistant | Mac mini | Mac mini 的工具與工作目錄 | 直連或後續雲端中繼 |++每個 bot 只有一個 computer。預設允許多個 bots 共用同一台 computer;這是多對一歸屬,不是要求每個 bot 獨占一台實體機器。++切換顯示帳號不會移動 bot 的工作位置,也不會把原有 session 搬到另一台電腦。++## 2. 明確區分三種帳號++| 名稱 | 範例 | 管理什麼 |+|---|---|---|+| Codync account | 個人/工作用 Google 或其他 Clerk 登入 | 電腦歸屬、裝置授權、資料隔離 |+| Connection identity | `alice@dev-server`、`deploy@build-machine` | 使用哪個 OS 使用者連到遠端執行環境 |+| Agent identity | Claude Code/Codex 自己的訂閱登入 | 該 agent 的憑證、用量與供應商權限 |++已確認:手機左上角切換不同 Google/Clerk 的 **Codync account**,每個帳號各自管理電腦與 bots。SSH connection identity 僅在 computer 連線設定中選擇,agent identity 留在該 computer 的 agent 登入流程。++同一台實體機器上的兩個 OS 使用者可能各自執行 host、各自有資料庫和權限。computer 應標識一個已驗證的 host 執行環境,而不是僅用 IP、主機名稱或硬體名稱作唯一鍵;不同 OS 使用者的環境不得任意合併。++## 3. 手機與桌面的資訊架構++### 手機++- 左上角:目前帳號 avatar/名稱與展開入口,顯示目前帳號、新增帳號、切換與登出。+- 主清單:目前帳號可存取的 bots;每列顯示 computer 名稱與該 computer 的連線狀態。+- 新增 bot:先選 computer,再取得該 computer 的 agents、模型、專案目錄、connectors 與 skills。+- Bot 設定:顯示固定的 computer;有既存聊天後,換 computer 視為建立新 bot/明確遷移,不直接更改 ID 讓原聊天指向另一台機器。+- Computer 管理:移入帳號內的「Computers」頁,負責新增、連線方式、授權與移除。+- 遠端畫面:放在 bot 或 computer 的操作中;跨 computer 清單沒有唯一的全域 Screen 按鈕。+- 離線:單台電腦離線只影響其 bots,不能把全帳號清單顯示成全部離線。+- 未登入:顯示「Local」或「本機配對」,不能將 computer 名稱誤作已登入的帳號名稱。++### 桌面++- 同一帳號下可以列出本機與遠端 bots,不把 `HostController.store` 視為所有 bot 唯一來源。+- 本機 host 安裝/重啟仍由 `HostController` 管理;遠端連線由獨立 computer connection controller 管理。+- 選到 SSH computer 時,agent 安裝、folder picker、用量、terminal 與設定都必須對應遠端。+- 在操作前清楚顯示 remote computer 和 OS user;不因 SSH 掉線自動把工作轉到本機。++## 4. 資料模型與路由++### 模型++- `AccountContext`:目前可用的 Codync 登入 session、active account ID、該帳號的電腦目錄。+- `Computer`:穩定 ID、owner、驗證過的 host identity、公用顯示資訊與能力。+- `ComputerConnection`:transport 類型(local/direct/ssh/relay)、connection identity、狀態、秘密參照;可有多種路徑通往同一個已驗證 host。+- `BotReference`:`accountId + computerId + botId`,用於 client 路由、導覽、cache 和通知。+- 每台 host 保有自己的 bots/threads 與 `rev`。既有 bot JSON 可在 client 從所屬 store 加上 computer context,不必第一步就破壞 wire format。+- 本機模式的 account namespace 為明確的 local context,不把未歸屬 host 偷偷轉成當前登入者所有。++### Store 與請求++目前 `BotStore` 只有一個 client、pairing、bots dictionary 與同步游標。要呈現跨電腦清單,建議新增 account-scoped 聚合 store,內含 `[ComputerID: BotStore]`,保留既有每 host 的 BotStore 責任。++- 聚合清單的每個 bot 都攜帶 `BotReference`,不能只拿裸 `botId` 查全域 dictionary。+- 進入聊天時把正確的 computer store 注入 `ThreadView`;send、stop、permission、history、screen、marketplace 全部沿同一條路由。+- 新 bot 的 draft 必須在選定 computer 後才填入預設值;建立命令送到該 computer。+- Push、widget、Live Activity、deep link 的新版 payload 加入穩定 computer ID;舊 payload 只有能唯一解析才導覽,否則請使用者選擇。+- 避免以 pairing token 作 UI identity;憑證輪替不應產生新的 computer。+- 不同 computer 的 bot ID、rev、session ID 即使相同,也不能混用。+- 背景/非可見電腦採有限連線與快取策略;不預設每支手機永遠開啟所有 SSE。++### 帳號切換的隔離++關閉舊帳號 streams、取消 in-flight mutations 的 UI 回傳、清除 selection/screen/terminal/pending approval,切換所有 cache namespace 和 widget snapshot。非同步回覆攜帶 account generation;切換後到達的舊回覆不得寫入新帳號狀態。++先核對目前 Clerk SDK 是否支援所需的多 session 行為。若不支援同時保留多個登入,實作「登出後切換/重新驗證」並明確呈現,不能做看似可切換但只更換畫面的假帳號清單。email 相同也不得自行合併 Clerk 使用者。++## 5. SSH 技術方案++### 首選:遠端 host + OpenSSH tunnel++遠端電腦安裝 codync-host,agent 與 repo 都在遠端;Mac 透過系統 OpenSSH 的 local forwarding 存取遠端 loopback API。SSH tunnel 本身不取代 codync-host 的授權。++```text+Mac Codync+ → 本機 loopback 上的臨時 tunnel port+ → OpenSSH 加密連線+ → 遠端 loopback 的 codync-host+ → 遠端 agent、repo、SQLite+```++不把遠端 host API 暴露到公網。採這條路可重用既有 HTTP/SSE、folder picker、agent discovery、session 持久化與 permission 流程。++第一版 SSH 範圍:++1. 使用者選擇已有 SSH config alias,或填入 hostname、port、OS username 與本機 key reference。+2. 使用系統 OpenSSH/ssh-agent,不把 SSH 私鑰上傳到 D1 或傳到手機;不自動開啟 agent forwarding。+3. 首次連線以可信管道確認 host key fingerprint;改變時阻擋並提示,不能 `StrictHostKeyChecking=no` 靜默通過。+4. tunnel 只 bind loopback,採無遠端 shell的 forwarding 模式,偵測 port 衝突、建隧道失敗、keepalive 與 reconnect。+5. 驗證遠端 host identity、protocol capabilities 與 grant 後才顯示可操作。+6. UI 分辨 SSH 驗證失敗、host 未安裝、agent 未安裝、remote cwd 不存在與 agent 尚未登入。+7. 遠端安裝/更新是獨立明確動作;不因按「測試連線」就執行安裝腳本。+8. 輸入以 structured argv 傳給 OpenSSH;限制可輸入的連線欄位,不將未驗證的 user/host/path 拼接 shell。++MVP 支援既有 key/agent 驗證與 macOS 客戶端;password、互動式 MFA、ProxyJump、複雜 ssh config 與 Linux desktop 的支援逐項驗證後宣告,不能推定全部可用。++### 為何不只把 command 改成 `ssh ... agent`++目前 ACP process 透過本機 shell 啟動,`cwd`、環境變數、MCP 設定、agent discovery 與 screen tools 都有本機假設。單純把 agent command 換成 SSH,可能讓 agent 在遠端執行,但 folder picker、工具和控制畫面仍指向本機。++因此不把這種做法當成完整的 remote computer 功能。若之後要支援「遠端不安裝 host」,需另做 ACP transport、遠端檔案/terminal callbacks、進程終止與工具轉送設計。++### 手機如何操作 SSH computer++桌面 SSH tunnel 成功不代表手機可用 Mac 的 `127.0.0.1` tunnel port。明確支援三條路徑:++| 路徑 | 條件 | 推出順序 |+|---|---|---|+| 手機直連遠端 host | 遠端 host 已配對且有 Tailscale/受保護路徑 | 先沿用現有能力 |+| 遠端 host 主動連 Cloudflare relay | 主計畫 P3 的出站中繼完成 | 推薦的後續體驗 |+| 手機經 Mac gateway,再 SSH 到遠端 | Mac 在線且明確啟用 gateway,具備逐 target 授權 | 另立功能,不含在 SSH tunnel MVP |++不將 desktop tunnel port 複製到手機配對資料。若只有 Mac 能連 SSH,手機顯示該 bot 目前需要桌面連線支援,不能把它假裝成可直接使用。++遠端 screen 依該 computer 的 OS/helper 能力決定;Linux headless computer 不顯示 Mac 的畫面控制按鈕。++## 6. 整合順序與是否現在一起做++**結論:帳號/computer/bot 的關係與 UI 導覽應一起納入現在的架構;完整 SSH 執行不是單一小改動,安排獨立的提前試行階段。**++### A. 現在納入++- 左上角使用已確認的 Codync 登入帳號語意。+- 定義一 bot 一 computer、複合路由 identity、account-scoped cache。+- 帳號切換器與 computer 管理入口分離。+- Bot 新增/設定與清單顯示 computer context。+- 帳號 SDK 整合不能假裝已完成雲端 ownership;未實作能力要如實顯示。++### B. 多 computer 路由++- 新增 account 聚合 store,重用每 computer 的 BotStore。+- 改寫 navigation、push、widget、screen 與 marketplace 路由。+- 測試同帳號兩台電腦、相同 bot ID、其中一台離線與帳號切換競態。++### C. SSH 桌面試行,可早於雲端中繼++- 先以測試用遠端 host 完成 tunnel、host key 驗證、連線生命週期與身份驗證。+- 確认 folder picker/agent 安裝/chat/stop/permission 都在遠端。+- 只有在 B 的路由和授權驗收通過後才整合到正式 bot 建立流程。+- 無可用 SSH 測試環境時可以做本機 mock/loopback 整合測試,但不能宣告真實跨機器流程驗收完成。++### D. 手機遠端體驗++優先讓遠端 host 直接接 Cloudflare 中繼。Mac gateway 與手機原生 SSH client 都增加另一套生命週期與金鑰管理,等到有確實需求再做。++## 7. 新增驗收條件++- 同帳號的本機 bot 與 SSH bot 可以並列,send/stop 不會送錯 computer。+- 兩台 computer 同名或具有相同 bot ID,仍能正確區分。+- 切換帳號後,不殘留上一個帳號的聊天、權限卡、用量、terminal 或 widget。+- 遠端 agent、專案目錄、MCP、skills、用量都來自遠端 host。+- SSH 斷線不會在本機重跑命令;連回後依遠端狀態恢復,不重複建立 task。+- Remote host key 變更、授權失效、OS user 變更時阻擋並重新驗證。+- 移除 connection profile 不刪除遠端 repo/SQLite;撤權與刪除 bot 是各自明確的操作。+- 停止一個 bot 不終止其他 bot 共用的 SSH tunnel;只有沒有使用者/引用時才釋放連線。+- 手機不使用桌面的 loopback 位址;不支援的 screen/terminal 能力正確隱藏或提示。+- SSH profile/device credentials 不進 D1、log 或一般 UserDefaults;只保存必要的非秘密描述與安全儲存參照。++## 8. 目前評估依據++對照 `apps/ios/Views/BotListView.swift`、`SettingsView.swift`、`kit/Sources/CodyncUI/Store/BotStore.swift`、`HostClient.swift`、`host/src/acp.rs` 與 `apps/macos/App/HostController.swift`:目前是一個 active computer 對應一個 store/client 的設計,尚無跨 computer 的 account store 或 SSH 連線管理。因此此功能不能只換手機左上角圖示或加 `computerId` 就算完成。++SSH 與 Clerk 具體 API/平台相容性應在實作階段依當時官方文件和已安裝版本核對;本文件未宣告任何 SSH 或多帳號功能已經可用。++## 9. 本次已落地與仍在規劃的範圍++已落地:iOS 左上角帳號入口、Clerk Google 登入/新增帳號/session 切換、每個帳號獨立的手機配對清單與聊天 cache、切換時退出舊 store 和結束 Live Activities。「Computers & settings」移到帳號選單內。單 session 的 Clerk instance 會顯示登出後換帳號,而不是假的多帳號切換。++這是手機端的登入與本機資料分區,尚未建立 Cloudflare ownership、雲端裝置目錄或逐裝置撤權。每個帳號仍需手動配對 computer;同一份有效配對憑證若被再次提供給另一帳號,現有 host 仍可能接受。舊 APNs ticket 也尚未具備帳號級撤權,相關安全邊界必須依主計畫 P2 完成後才能宣稱具備後端帳號隔離。++跨 computer bot 彙整、新 bot 選 computer、SSH transport、手機 SSH gateway 與雲端中繼仍屬後續工作。現在清單顯示目前所選 computer 的 bots,每個 bot 的執行位置仍由其 host 固定。diff --git a/docs/clerk-macos.md b/docs/clerk-macos.mdindex 5d98881e..db7ffe06 100644--- a/docs/clerk-macos.md+++ b/docs/clerk-macos.md@@ -24,7 +24,7 @@ and publishable key. Never put a Clerk secret key in the Mac bundle or this file## Flow-`AccountSession` configures Clerk once. Continue with Google calls `clerk.auth.signInWithOAuth(provider: .google)`+`apps/shared/AccountSession.swift` configures Clerk once per app. Continue with Google calls `clerk.auth.signInWithOAuth(provider: .google)`directly, without the Clerk Account Portal intermediary. Google authorizationuses the SDK's system browser authentication session. Clerk handles new-usertransfer, callback validation, session restoration and Keychain storage.@@ -53,3 +53,30 @@ consent; compilation alone does not verify those steps.References:- https://clerk.com/docs/ios/getting-started/quickstart- https://github.com/clerk/clerk-ios++## iOS account switching++The iOS app now uses the same ClerkKit dependency and shared AccountSession.+Its top-left button opens Accounts; Computers & settings is a separate destination+inside that sheet. The iOS native application must be registered in the same Clerk+instance with bundle ID `com.pokai.Codync.ios` and its own callback+`com.pokai.Codync.ios://callback`. The iOS public configuration is in+`apps/ios/Resources/ClerkConfig.plist`. The repository configuration does not prove+that the corresponding Clerk Dashboard registration has been completed.++To retain several accounts at once, enable multi-session support in the Clerk+instance. The UI reads `authConfig.singleSessionMode`: with multi-session enabled,+it lists active SDK sessions and switches with `auth.setActive(sessionId:)`; with+single-session enabled, it asks the user to sign out before using another account.+Signing out passes the current session ID, rather than signing out all accounts.++Pairings and caches are partitioned by the Clerk user ID on this iPhone. Local+pairings keep their original storage namespace and are not automatically claimed+by a newly signed-in user. Each BotStore captures a fixed storage context, and is+retired when changing accounts. This is client-side separation, not server-side+ownership enforcement. Cloudflare device discovery, per-device grants, account-aware+push revocation and Keychain migration remain work in the architecture plan.++Verify with two real Google accounts: add both, switch, cancel OAuth, restart,+check each account's pairings, sign out just one, and verify the other remains.+A simulator build verifies compilation, not the Dashboard settings or OAuth flow.diff --git a/docs/cloudflare-account-device-plan.md b/docs/cloudflare-account-device-plan.mdnew file mode 100644index 00000000..a320fed1--- /dev/null+++ b/docs/cloudflare-account-device-plan.md@@ -0,0 +1,423 @@+# Codync 帳號、裝置管理與 Cloudflare 架構計畫++日期:2026-09-25+狀態:規劃文件;尚未實作或部署。文中的時間、容量與保留期限是建議產品設定,不是服務商限制。++## 1. 目標與核心決策++讓使用者在 Mac 和 iPhone 登入同一個 Codync 帳號後,能找到自己的電腦、完成首次授權、管理已授權裝置,並在之後擴充訂閱與免 Tailscale 的遠端連線。++採用以下分工:++- **Clerk**:使用者身分、Google 等登入方式與登入 session。+- **Cloudflare Workers + D1**:帳號與電腦的歸屬、裝置授權、撤權、必要的管理資料。+- **電腦上的 codync-host + SQLite**:bots、threads、entries、專案設定、agent 執行與實際操作權限。+- **既有 Cloudflare 推播 relay**:APNs 通知與 Live Activities,逐步補上帳號與裝置授權。+- **後續 Durable Objects + WebSocket**:協調及中繼手機與 host 的連線。++第一版先完成帳號與裝置管理,直連仍使用 Tailscale/受保護的本機網路連線。聊天、程式碼與本機 SQLite 不會整份複製到 D1。++保留不登入的本機模式。登入是使用雲端管理功能的必要條件,不是本機 agent 執行的必要條件。++### 1.1 Bot、computer、帳號與連線方式(新增需求)++每個 bot 固定屬於一台 computer;該 computer 是 agent、專案目錄、session 與聊天資料實際所在的位置。Mac App 是操作介面,不代表 bot 必須在目前這台 Mac 執行。++- 一個 bot 只能對應一台 computer;預設允許同一台 computer 執行多個 bots,不強加「一台只能有一個 bot」的限制。+- computer 可以是本機 Mac、另一台已配對的電腦,或經 SSH 連到的遠端 Mac/Linux。+- SSH 是連線方式;它不取代 computer 的穩定身分,也不是 agent 類型。+- Codync 帳號管理 computer 與 bot 的可見範圍;SSH 的 `user@machine` 是執行/連線身分;Claude/Codex 帳號則是 agent 自身的登入,三者不得混用同一個 account 欄位。+- 手機左上角目標改成「帳號切換」,不再以切換目前 computer 作為整個 bot 清單的主入口。已確認此處指不同 Google/Clerk 的 Codync 登入帳號,各自管理電腦與 bots。+- computer 選擇放在新增 bot 流程與 bot 設定;bot 清單、聊天標頭顯示所屬 computer,讓使用者知道命令會在哪裡執行。++目標階層為 `Account → Computers → Bots`,帳號下的 bot 清單可跨 computer 彙整。使用者可以同時保有本機 bot 與遠端 bot,不需要每次先切換全域 host。++具體的多 computer 路由與 SSH 計畫見 [Bot 與遠端 computer 計畫](bot-computer-ssh-plan.md)。++## 2. 已確認的專案現況++| 現況 | 程式位置 | 對計畫的影響 |+|---|---|---|+| Mac 已使用 ClerkKit,支援 Google 登入 | `apps/shared/AccountSession.swift`、`docs/clerk-macos.md` | 延伸現有登入,不另建帳號系統 |+| iOS 尚未接 Clerk,以掃碼配對進入主畫面 | `apps/ios/App/CodyncApp.swift`、`apps/ios/Views/RootView.swift`、`PairingView.swift` | 新增可略過的登入入口與雲端電腦清單 |+| host SQLite 位於 `~/.codync/codync.db` | `host/src/main.rs`、`host/src/store.rs` | 保留本機資料與既有 `rev` 同步機制 |+| host 使用共用 pairing token,旋轉會使所有舊裝置失效 | `host/src/main.rs`、`host/src/api.rs` | 必須新增逐裝置授權,才能精準撤權 |+| 手機配對資料序列化到 App Group UserDefaults | `kit/Sources/CodyncKit/Client/SharedStore.swift` | 秘密搬到 Keychain,UserDefaults 僅留顯示資料與參照 |+| 命令走 HTTP API,事件走 SSE | `host/src/api.rs`、`kit/Sources/CodyncKit/Client/HostClient.swift` | 第一版沿用;後續用 transport 抽象接中繼 |+| 已有 Cloudflare Worker 轉送 APNs,使用加密 ticket | `relay/src/index.ts`、`relay/wrangler.toml` | 保留相容性;它目前不是裝置目錄或聊天中繼 |+| Remote screen 使用獨立 helper 與 WebRTC | `apps/screen/`、`kit/Sources/CodyncUI/Screen/` | 影像傳輸與聊天中繼分開 |++目前「Mac 登入成功」不等於「手機已獲准連 host」。現有配對 token 也不會因 Clerk 登出而自動失效。++## 3. 本機 SQLite 與雲端 D1 的資料邊界++SQLite 是資料庫引擎;本機 SQLite 存在使用者電腦,D1 的資料存在 Cloudflare。兩者不會自動互相同步,也不是彼此的完整備份。++| 資料 | 權威來源 | 雲端是否保存 |+|---|---|---|+| 使用者登入身分、登入方式 | Clerk | Clerk 保存;D1 只保留關聯 ID 與必要狀態 |+| 電腦歸屬、裝置授權與撤權版本 | D1 | 是 |+| 電腦顯示名稱、版本、最後回報時間 | D1 中的 host 回報 | 是;線上狀態只是估計 |+| bots、threads、聊天、工具輸出與 agent session | host SQLite | 第一版不保存 |+| 專案檔案、路徑、agent API keys、MCP 憑證 | 使用者電腦 | 不保存 |+| 連線候選位址 | host | 第一版由配對/本機探索取得;不建立含私人 IP 的全域目錄 |+| 裝置私鑰、存取憑證 | 各裝置的安全儲存 | 私鑰不上傳;雲端可存公鑰或憑證雜湊 |+| APNs token/ticket | 手機與推播服務 | 維持必要的加密處理;不寫入一般 log |+| 訂閱權益 | 後續付款供應商事件與後端計算結果 | 商業化階段才新增 |++雲端目錄的價值:新手機即使還沒連到 Mac,也能知道帳號擁有哪些電腦,並啟動授權流程。電腦離線時仍能顯示清單,但無法讀取最新 bots、聊天或執行新指令。++既有推播內容可能經 Cloudflare 與 Apple 處理;未來聊天中繼也會處理傳輸內容。「不持久化聊天」不等於「內容從不經過雲端」,也不等於端對端加密。++## 4. 服務配置與範圍++| 服務 | 用途 | 導入階段 |+|---|---|---|+| Clerk | 原生登入、session、身分驗證 | 第一版 |+| Workers,新增 `codync-api` | 帳號 API、claim、授權、撤權、webhook | 第一版 |+| D1 | 管理資料與事件去重 | 第一版 |+| 現有 `codync-relay` Worker | APNs 與 Live Activities | 延用並升級 |+| Durable Objects | 每台 host 的連線協調、WebSocket 中繼、即時撤權通知 | 第二階段 |+| R2 | 使用者明確選擇的附件/備份 | 有實際需求再導入 |+| Queues | 推播與 webhook 的背景處理、重試 | 量體或可靠性需要時導入 |+| Workers KV | 非關鍵設定快取 | 非必要;不作為授權與撤權權威來源 |+| TURN 服務 | WebRTC 無法直連時的媒體轉送 | 遠端畫面階段另行評估 |++先新增 `cloud/` 放帳號與裝置 API,保留 `relay/` 的部署與 API,避免一開始就改壞既有推播。Workers 是雲端後端的執行位置,不需要另租常駐 VM。++Cloudflare Tunnel 不列為第一版終端使用者的安裝依賴。帳號驗證、host 授權與跨網路傳輸是不同問題,不能靠加一個 Tunnel 就視為全部完成。++## 5. 架構++```mermaid+flowchart TD+ IOS[iPhone App] --> CLERK[Clerk 登入]+ MAC[Mac App] --> CLERK+ IOS --> API[Workers:Codync API]+ MAC --> API+ API --> D1[(D1:電腦歸屬與裝置授權)]+ HOST[codync-host] -->|機器身分、授權更新| API+ MAC -->|本機連線| HOST+ IOS -->|第一版:Tailscale/安全直連| HOST+ HOST --> DB[(本機 SQLite)]+ HOST --> AGENT[Agent CLI 與專案檔案]+ HOST --> PUSH[既有 APNs relay]+ PUSH --> APNS[Apple APNs]+ APNS --> IOS+ IOS -. 第二階段 .-> DO[Durable Object:連線中繼]+ HOST -. 主動建立出站連線 .-> DO+```++雲端不執行 agent,不遠端修改使用者專案。所有命令最終仍由 host 驗證與執行;不能因為流量經中繼就繞過 host 的權限檢查。++## 6. 使用者流程++### 6.1 Mac 首次綁定++1. 使用者透過現有 Clerk 流程登入。+2. App 顯示「將這台電腦加入我的帳號」,明確展示目標帳號。+3. App 向雲端取得有效期建議 5 分鐘的一次性 claim challenge。+4. App 透過已驗證的本機連線,請 host 產生/使用機器金鑰簽署 challenge。+5. 雲端驗證 Clerk session、challenge、host 持有金鑰的證明與 claim 狀態,原子化建立 ownership。+6. host 保存 cloud host ID、owner ID、機器憑證與授權版本;開始低頻回報狀態。++claim 必須綁定使用者、host 公鑰、nonce 與到期時間;只傳 `hostId`、email 或任意公鑰不能取得既有電腦的所有權。同一個已 claim 的 host 不能被另一個帳號覆蓋。++第一次信任建立依靠本機 App/host 連線與使用者確認,不從未驗證的網路 `/health` 回應直接信任 host 身分。Linux 後續提供一次性瀏覽器 claim code 的等效流程,不儲存使用者 Clerk refresh credential 到 daemon。++### 6.2 iPhone 登入與連接++1. iPhone 使用與 Mac 相同環境的 Clerk instance 登入;使用 iOS 自己的 bundle ID 與 callback 設定。+2. `GET /v1/hosts` 取得自己的電腦清單,顯示離線/最後回報時間。+3. 使用者選擇電腦,新手機提出裝置授權申請。+4. Mac 顯示手機名稱、帳號與申請時間,由使用者確認。+5. 手機獲得綁定該 host 的短效 grant,並完成安全直連設定。+6. 手機向 host 取得 bots 與歷史訊息。++第一版新手機仍可能需要一次掃碼來交換連線資訊與驗證 host。登入取得裝置清單,不代表已解決 NAT、IP 探索或 Tailscale 安裝。UI 必須分別顯示「已綁定帳號」「已授權」「可連線」。++### 6.3 裝置管理與帳號切換++- 「我的電腦」:列出、改顯示名稱、查看最後連線、解除雲端綁定。+- 「已授權裝置」:查看每支手機的授權狀態、撤銷單一裝置。+- 新裝置申請有效期建議 10 分鐘,過期要重申請,不能留成無限期待批准。+- 手機登出/換帳號:關閉帳號連線,刪除該帳號 grant 與本機快取,清除相關 widget snapshot;不得顯示上一個帳號的 bots。+- 手機登出盡力撤銷該裝置在雲端的 session/grant;若離線登出,先清本機資料,剩餘權限受 lease 到期限制。+- Mac App 登出只結束互動式登入;daemon 的雲端綁定持續存在,UI 要提示如何另行解除綁定。+- 解除 host 綁定撤銷全部帳號型 grant 與機器憑證,不刪本機專案、bots 或聊天。+- 帳號刪除要同步處理 host ownership、裝置、推播訂閱、雲端 metadata 與後续商業資料保留要求。++## 7. 驗證、授權與撤權模型++### 7.1 三種身分分開++| 身分 | 驗證方式 | 可做的事 |+|---|---|---|+| 使用者 App | Clerk session token | 存取自己的管理資源、提出授權 |+| host daemon | 專用機器金鑰/機器憑證 | 回報自身狀態、取得自身待辦授權、確認請求 |+| 已授權手機到 host | 短效 host grant + 裝置持有金鑰證明 | 執行 grant 允許的 host 操作 |++Worker 驗證 Clerk token 的簽章、issuer、到期與適用的 audience/authorized-party 設定,從已驗證的 `sub` 取得 user ID。依實際 Clerk token 格式核對 claims,不能假設所有 token 都含同一組欄位。++每次查詢、更新都帶 owner 範圍並檢查帳號/host/grant 是否仍有效。不信任 client body 裡的 owner ID;知道另一個 host ID 不構成權限。JWT 驗證使用維護中的函式庫,快取 JWKS 並支援 key rotation。++### 7.2 新的 host grant++建議包含:`grantId`、`hostId`、`deviceId`、`userId`、`scopes`、`authVersion`、`iat`、`exp`、裝置公鑰指紋。雲端以獨立 signing key 簽署;host 信任已配置的 issuer 與 key set。++- scopes 至少區分讀取、送訊息、bot 設定、permission 回覆與 screen control。+- 裝置金鑰證明須使用標準簽章機制、一次性 challenge/防重播狀態;不自創加密協定。+- cloud host ID 由雲端分配;原本本機 host ID 留作關聯。複製資料庫造成相同 local ID 時,不能自動視為同一台可信電腦。+- host 擁有的機器憑證不能批准另一台 host 的請求;新裝置批准必須對應實際本機確認事件。+- Remote screen 的 OS 權限與 `setScreenEnabled` 本機限制繼續由 host/helper 執行,grant 不能越過它們。++### 7.3 明確的撤權時效++第一版採短 lease,建議 grant 最長 15 分鐘。host 有網路時每 30 秒檢查授權版本,目標在 60 秒內中止被撤權連線;第二階段改為中繼即時通知並保留輪詢/到期後備機制。++雲端不可達時,不允許無限延長帳號型遠端存取。lease 到期後停止該裝置的讀寫與 screen control,即使 SSE/WebSocket 已建立也要檢查到期並關閉。host 上原有本機任務可繼續執行。++撤權不等於撤回已下載資料,也不保證取消已開始的 agent 工作。產品先定義為阻止後續存取;使用者如需停止工作,應另送 stop。screen control 連線撤權後要立即交還本機控制。++本機獨立配對是另一種權限來源。若仍存在舊共用 token,雲端撤權無法使它失效;遷移前不能宣稱「已撤銷此手機的所有存取」。++### 7.4 秘密與傳輸++- Clerk publishable key 可存在 App;Clerk secret、APNs key、雲端簽章私鑰只放 Worker secrets。+- iOS/macOS 的裝置私鑰與 grant 放 Keychain;widget 使用必要的 Keychain access group,不將 token 放 App Group UserDefaults。+- host 私鑰使用 OS 安全儲存或受限制權限的檔案;Linux 至少使用專屬使用者與 `0600`。+- 第一版優先 Tailscale 的加密連線;一般 LAN 需有已驗證的 TLS/配對信任機制才啟用新帳號型遠端權限,不能直接把長效 token 暴露在普通 HTTP。+- 不在 URL query、一般 log、分析事件或 crash report 中記錄憑證。現有 query token 相容入口需列入退場範圍。+- 若未來需要中繼無法讀取內容,另做端對端加密設計與審查,不能把 TLS 描述成端對端加密。++## 8. D1 資料模型++以下為 migration 設計依據;實作時提供真正 SQL、索引、約束與遷移測試。++| Table | 主要欄位 | 約束/索引 |+|---|---|---|+| `accounts` | `clerk_user_id`, `status`, `created_at`, `deleted_at` | Clerk ID 為主鍵;不以 email 作關聯 |+| `hosts` | `id`, `owner_user_id`, `local_host_id`, `name`, `platform`, `version`, `status`, `last_seen_at`, `auth_version` | owner/status 索引;ownership 變更必須經受控流程 |+| `host_keys` | `id`, `host_id`, `public_key`, `fingerprint`, `created_at`, `revoked_at` | fingerprint 唯一;支援輪替 |+| `devices` | `id`, `owner_user_id`, `name`, `platform`, `public_key`, `revoked_at` | owner 索引;installation ID 不充當秘密 |+| `host_grants` | `id`, `host_id`, `device_id`, `scopes`, `status`, `approved_at`, `revoked_at`, `version` | host/device 唯一;驗證雙方 owner 一致 |+| `claim_challenges` | `id`, `user_id`, `nonce_hash`, `expires_at`, `consumed_at` | 一次性消耗;到期清理 |+| `access_requests` | `id`, `host_id`, `device_id`, `status`, `expires_at`, `decided_at` | host/status 索引;條件更新避免雙重批准 |+| `processed_events` | `provider`, `event_id`, `processed_at` | provider/event 唯一,供 webhook 去重 |+| `audit_events` | `id`, `actor_id`, `action`, `target_id`, `result`, `created_at` | owner/time 索引;不含聊天、token、私人路徑 |++推播升級時新增 `push_subscriptions`,關聯 device、host grant、ticket 版本與失效時間。訂閱功能開發時才新增 `entitlements` 與付款事件資料,不把付款狀態與 Google 登入混在一起。++所有時間統一 UTC。ID 不重用。重要變更用 D1 支援的原子操作/batch 與唯一約束,實作前核對交易語意;不得使用「先查不存在,再無條件新增」處理 claim。++D1 中授權寫入後的讀取必須提供所需一致性;若啟用 read replicas/Sessions,明確設計 read-after-write。撤權不能被一般快取或 replica 的舊值覆蓋。++## 9. API 契約草案++API 使用 `/v1`,錯誤固定為 `{ error: { code, message }, requestId }`。列表分頁,所有 mutation 定義重試與冪等語意。跨帳號資源回覆不洩漏其存在;細節只記安全稽核。++| Endpoint | 呼叫身分 | 行為 |+|---|---|---|+| `GET /v1/me` | Clerk | 取得/初始化最小帳號資料 |+| `POST /v1/devices` | Clerk + 裝置持有金鑰證明 | 註冊目前 installation |+| `GET /v1/devices` | Clerk | 列出自己的裝置 |+| `DELETE /v1/devices/:id` | Clerk | 撤銷該裝置全部帳號型 grant |+| `POST /v1/host-claims` | Clerk | 建立一次性 claim challenge |+| `POST /v1/host-claims/:id/complete` | Clerk + host 簽章 | 原子化認領 host |+| `GET /v1/hosts` | Clerk | 列出自己的電腦 |+| `PATCH /v1/hosts/:id` | Clerk owner | 修改雲端顯示名稱 |+| `DELETE /v1/hosts/:id` | Clerk owner | 解除綁定、撤銷 key/grant、增加授權版本 |+| `POST /v1/hosts/:id/access-requests` | Clerk + 裝置證明 | 申請首次連線授權 |+| `GET /v1/access-requests/:id` | 申請者或對應 host | 查申請結果 |+| `POST /v1/host/access-requests/:id/decision` | 對應 host | 傳回本機批准/拒絕 |+| `GET /v1/hosts/:id/grants` | Clerk owner | 列出已授權裝置 |+| `DELETE /v1/hosts/:id/grants/:grantId` | Clerk owner | 撤銷單一 grant |+| `POST /v1/hosts/:id/connection-grants` | Clerk + 裝置證明 | 核對有效批准後發短效 grant |+| `POST /v1/host/heartbeat` | host | 更新自身版本、最後回報時間 |+| `GET /v1/host/authorization-state` | host | 取得自身授權版本、撤權與待批准申請 |+| `POST /v1/webhooks/clerk` | 驗證 webhook 簽章 | 帳號刪除/停用,去重與同步撤權 |++機器請求包含 timestamp、nonce、method/path/body 的簽章或等效標準機器驗證,防止 heartbeat/approval 重播。heartbeat 不能更新 owner。++## 10. 既有使用者與資料遷移++1. 新版本先讀舊 `Pairing` 與電腦清單,不要求重建 bots 或清除 SQLite。+2. 把 pairing 秘密移到 Keychain;寫入並讀回成功後才刪除 UserDefaults 中的秘密。保留可重入的 migration version。+3. 舊掃碼配對標為「本機配對」;登入不會自動把全部舊 host 宣告為該帳號所有。+4. 使用者在實際電腦上完成 claim,再逐支手機升級到獨立 grant。+5. 新授權驗證成功後,明確提示舊共用 token 仍有效;提供在電腦上「停用舊配對」的收尾操作。+6. 保留本機 helpers 所需的驗證,但將其限制到本機用途;不繼續讓該憑證兼任所有手機的遠端管理權限。+7. 同一台電腦在雲端與舊配對清單中出現時,經驗證的 host 身分對應後合併顯示,不用名稱或 IP 去重。+8. 版本協商包含 auth/protocol capabilities;不相容時提示升級,不在失敗時靜默降級為共用 token。++## 11. 推播與離線行為++現有 APNs ticket 具備加密,但持有 ticket 即能向 relay 要求推播;目前 payload 沒有明確到期與帳號/host grant 歸屬。升級時新增版本、到期、授權關聯、撤銷查核與限流。++- host 只能通知自身有效 grant 對應的手機;不能自行提交任意帳號裝置。+- 登出、撤權與 APNs `Unregistered` 都要清理或停用 subscription。+- 推播是提醒,不是授權憑證;點擊後重新驗證,再從 host 取得內容。+- 保留舊 ticket 過渡期,明確設定停止接受日期/版本門檻,避免永久留下繞過撤權的入口。+- 預設通知採最少內容;是否顯示訊息摘要提供使用者設定。++| 情境 | 預期行為 |+|---|---|+| 電腦離線/睡眠 | 顯示最後回報;不假裝已送達命令,也不把 heartbeat 當連線保證 |+| 雲端暫時故障 | 本機 agent 繼續;既有帳號型直連僅在有效 lease 內使用 |+| Clerk 暫時不可用 | 已驗證且未過期的 session 可依快取公鑰驗證;需要刷新時顯示可重試狀態 |+| 手機切換網路 | 重新驗證連線,沿用 host `rev` 補事件;送訊息用既有 nonce 去重 |+| 撤權時有正在執行的工作 | 阻止後續存取;工作是否停止由獨立 stop/本機控制決定 |++第一版不在雲端替離線 host 排隊執行命令。手機保留未送出內容時,要清楚標示,恢復後依冪等鍵送出;permission 回覆等時效性操作不得盲目重播。++## 12. 第二階段:免 Tailscale 的遠端連線++目標是 host 主動建立出站連線,手機不需知道私人 IP 或設定路由器。++1. 每台 host 對應一個 Durable Object,host 與手機分別完成身分與 grant 驗證。+2. 定義版本化 envelope:`requestId`、`hostId`、`deviceId`、`method`、`payload`、`deadline`、protocol version。+3. Worker/DO 做路由與連線管理,host 再驗證操作權限;不提供任意 URL 代理或任意 TCP 轉送。+4. 保留 `clientNonce`、`rev` 與去重;斷線後從 host 補齊事件,不靠 DO 保存完整聊天。+5. 設定每帳號/host 的連線數、訊息大小、in-flight requests、backpressure、逾時與頻寬預算。+6. Durable Object 重啟/休眠不能遺失必要的認證上下文;重連需重新驗證,未完成 mutation 回報結果未知並透過 ID 查詢。+7. 先支援聊天/狀態,再加入 terminal streaming;screen signaling 與影像傳輸分別驗收。++WebRTC 優先直連,必要時使用 TURN;憑證需短效且受裝置授權約束。Cloudflare 是否承接 TURN、其容量和費用,在該階段核對官方文件後決定。++只做傳輸層 TLS 的中繼可接觸明文。若選擇端對端加密,需要另外定義首次信任、換機、key rotation、撤權與復原,不在本計畫第一版順帶承諾。++## 13. 儲存庫實作位置++| 位置 | 預計修改 |+|---|---|+| `cloud/`(新增) | Workers API、D1 migrations、驗證/授權模組、API 測試、Wrangler 設定 |+| `relay/` | ticket 升級、subscription 驗證、限流與相容遷移 |+| `apps/shared/AccountSession.swift`(已提取共用) | 從 Mac 提取兩端共用 Clerk wrapper,以 target sources 引入 |+| `apps/ios/App/`、`apps/macos/App/` | App lifecycle、登入、登出清理、各平台 callback |+| `apps/ios/Views/`、`apps/macos/Views/` | 登入入口、我的電腦、授權申請與撤權 |+| `kit/Sources/CodyncKit/Client/` | `CloudClient`、Keychain 儲存、配對遷移;不引入 Clerk 到 widget-safe core |+| `kit/Sources/CodyncUI/Store/` | 本機/雲端電腦清單合併、帳號切換、grant 更新 |+| `host/src/` | host identity、cloud client、逐裝置 auth、撤權與版本協商 |+| `project.yml` | iOS Clerk 依賴、shared sources、config 與 Keychain entitlement 配置 |+| `docs/clerk-macos.md`、README、PairingView 文案 | 更新帳號、資料處理與本機模式說明 |++實作應保持帳號 SDK 與 widget-safe 資料模型分離,避免 widget 因共享套件被迫初始化 Clerk。不要把雲端管理 API 全塞進現有 `HostClient`。++## 14. 分階段交付與完成條件++### P0:確認邊界與協定++- 確認本機模式保留、第一版仍可能掃碼/使用 Tailscale、首次手機需要 Mac 確認。+- 完成 claim、grant、傳輸安全、撤權 lease 與 host identity 的協定細節。+- 核對 Clerk 原生 iOS 配置、Cloudflare D1 一致性與 migration 能力。+- 核對 iOS 上架所需的登入選項、帳號刪除流程;若需 Apple 登入則列入 P1。+- 決定 staging/production 環境、API domain、秘密輪替與資料保存政策。++完成條件:沒有「雲端已撤權但有效連線可無限使用」或「知道 host ID 就能認領」的空白設計。++### P1:兩端帳號與唯讀裝置目錄++- 新增 `cloud/`、D1 migrations、JWT 驗證、`me`、host claim/list 與最小 audit。+- iOS 加入 Clerk;共用 AccountSession;登入可略過。+- Mac 明確 claim,host 以機器身分 heartbeat;iPhone 顯示我的電腦。+- 已列出但未授權的電腦顯示後續設定提示,不能點一下就繞過配對。++完成條件:同帳號兩端清單一致;不同帳號完全隔離;既有掃碼配對與本機資料仍可用。++### P2:逐裝置授權、撤權與遷移(第一版正式目標)++- 完成 devices、access requests、grants、host 認證與 scopes。+- 完成安全直連、Keychain migration、登出/帳號切換清理。+- 實作在線撤權與離線 lease 到期;存量連線也要停止。+- APNs ticket/subscription 升級,補上單一裝置撤權與舊 token 退場。+- 完成帳號刪除 webhook、冪等重試與所有失敗提示。++完成條件:撤銷手機 A 後,A 在約定時限內失去存取,手機 B 正常;雲端失聯時 A 也不能超過 lease 繼續使用。++### P3:免 Tailscale 中繼++- 加入 Durable Objects、host 出站連線、transport 抽象與版本化訊息。+- 驗證斷線重連、去重、事件補齊、限流與中繼重啟。+- 先推出聊天,再逐項驗收 terminal、screen signaling 與 TURN。++完成條件:手機行動網路連家中 NAT 後的 host,不需要開 port;權限與撤權行為與直連一致。++### 可提前導入:多 computer bot 路由與 SSH 試行++- P1/P2 的資料模型一併納入每 bot 的 computer 關聯、帳號作用域與複合路由 ID,避免日後重做 cache、deep link 與通知格式。+- 先實作帳號內多 computer 的 bot 彙整與路由;每台 computer 保有自己的 `BotStore`/同步游標,不把多個 host 的 `rev` 混成一個。+- SSH 試行使用 macOS 系統 OpenSSH,連到遠端已安裝的 codync-host,透過 loopback tunnel 重用既有 API;不先實作任意 SSH command 當完整 bot backend。+- SSH 試行不依賴雲端中繼,可以在 P2 後、P3 前交付;但必須先完成 host 身分驗證、獨立授權、連線生命週期及正確路由。+- 手機直接連 SSH host、手機經 Mac gateway 存取,以及免安裝 remote host 是不同工作項;不因桌面 tunnel 成功就宣稱三者均完成。++完成條件與延後原因詳見 [SSH 計畫的整合門檻](bot-computer-ssh-plan.md#6-整合順序與是否現在一起做)。++### P4:商業與可選同步++- 依實際需求接訂閱/權益、驗證付款 webhook、提供基本使用者支援後台。+- 評估 R2 備份/附件與 Queues;用戶選擇上傳後才建立對應資料生命週期。+- 平台管理員可管理帳號狀態與權益,但不因此獲得讀取本機專案/聊天的權限。++此階段另立付款與資料同步計畫,不把登入系統當作已完成訂閱後端。++## 15. 驗證矩陣++| 類別 | 必測案例 |+|---|---|+| 身分 | 過期/錯 issuer/偽造 JWT、取消登入、session 恢復、key rotation |+| 租戶隔離 | 帳號 A 猜到 B 的 host/device/request/grant ID 仍無法讀寫;列表不洩漏 |+| Claim | 過期、重播、兩帳號競爭、複製 local host ID、重複提交、host key 不匹配 |+| 授權 | 首次批准/拒絕/逾期、scope 不足、裝置持有證明錯誤、grant 跨 host 使用 |+| 撤權 | SSE/WebSocket 存量連線、雲端失聯 lease 到期、screen control、舊 token 仍在 |+| 遷移 | 舊手機升級、寫 Keychain 失敗、重複跑 migration、多台電腦、帳號切換、widget |+| 推播 | 已登出/撤權不再通知、ticket 過期、APNs token 更新與 `Unregistered` |+| 網路 | LAN、Tailscale、行動網路、Mac 睡眠、host 重啟、雲端 outage、網路切換 |+| 冪等 | 重複 claim/approve/webhook/send、API response 丟失後重試不重複執行 |+| 刪帳號 | 重複/亂序 webhook、禁止重新發 grant、撤權、metadata 清理與最小 tombstone |+| 本機能力 | 未登入仍可本機執行;雲端故障不破壞本機 SQLite/現有工作 |++Worker 執行 typecheck 與具 D1 binding 的整合測試;Rust 執行 auth/遷移測試;Swift 執行登入狀態、Keychain 與帳號切換測試。最後使用兩個測試帳號、兩台手機/模擬器與實際 Mac 驗證,不以編譯成功代替 OAuth/跨裝置驗收。++## 16. 部署、監控、成本與回滾++- local、staging、production 使用不同 Clerk instance/D1/Worker secrets;release 不含測試 key 或 staging API URL。+- 部署順序:相容的雲端 API → 新 host → 新手機 → 關閉舊配對/ticket 路徑。每步設定最低協定版本與遙測指標。+- D1 schema 使用先擴充再移除;migration 前做可還原備份並演練還原。回滾不能把已撤銷 grant 恢復為有效。+- 初期採帳號 allowlist 與功能旗標。關閉雲端功能時保留本機工作能力,但不得靜默恢復舊的不安全遠端權限。+- 監控 API 錯誤率/延遲、claim 成功率、撤權延遲、heartbeat、連線數、推播失敗、D1 讀寫量;log 做秘密過濾。+- audit events 建議保留 30 天;過期 challenge/request 定期清理。刪帳號後的最低限度 tombstone、備份保留與清除期限在正式隱私政策中定義。+- 第一版 heartbeat 建議 60 秒一次、降低 D1 寫入頻率至約 5 分鐘一次;authorization polling 30 秒一次。100 台常在線 host 的 30 秒輪詢約為每日 288,000 次,需納入預算。+- 明確區分 Workers requests、D1 rows read/written、DO 活躍時間/訊息、log、推播及未來 TURN 頻寬;不預設免費額度一定夠。+- 若輪詢成本過高,提早導入 DO 連線通知屬里程碑調整;不要為省成本把撤權查核改成無期限快取。+- 設定每帳號裝置數/申請頻率/claim 次數與預算告警;具體商業上限待量測後確定。++## 17. 尚待確認的產品選項++本計畫已選可實作的預設,不因這些選項未定而阻止 P0/P1 準備。++| 選項 | 預設建議 | 何時必須定案 |+|---|---|---|+| 是否強制登入 | 本機模式可略過;雲端管理需要登入 | P1 UI |+| 新手機能否自動授權 | 需要 Mac 確認 | P2 |+| 雲端失聯可用多久 | 帳號型 grant 最長 15 分鐘;本機使用不受影響 | P2 |+| 重新登入是否恢復舊批准 | 同一 installation 金鑰可重新驗證;已撤銷裝置需重新批准 | P2 |+| 是否雲端保存聊天 | 第一版不保存 | 若進 P4 同步 |+| 中繼是否端對端加密 | 未承諾;單獨設計 | P3 前 |+| 付款方式/方案 | 尚未選定 | P4 前 |+| 團隊共享/多 owner | 第一版不做;每台 host 一個 owner | 後續獨立需求 |++## 18. 參考資料與核對狀態++本文件的現況已對照儲存庫。撰寫時網頁工具回傳驗證錯誤,先前直接存取官方網站也受到限制,因此不把最新價格、配額或上架規則寫成已驗證事實。以下官方入口供各里程碑實作前核對:++- [Clerk iOS Quickstart](https://clerk.com/docs/ios/getting-started/quickstart)+- [Clerk Session Tokens](https://clerk.com/docs/guides/sessions/session-tokens)+- [Clerk JWT Verification](https://clerk.com/docs/guides/sessions/manual-jwt-verification)+- [Cloudflare Workers](https://developers.cloudflare.com/workers/)+- [Cloudflare D1](https://developers.cloudflare.com/d1/)+- [Durable Objects WebSockets](https://developers.cloudflare.com/durable-objects/best-practices/websockets/)+- [Cloudflare R2](https://developers.cloudflare.com/r2/)+- [Cloudflare Queues](https://developers.cloudflare.com/queues/)+- [Apple App Review Guidelines](https://developer.apple.com/app-store/review/guidelines/)++本地參考:[專案結構](structure.md)、[目前 macOS Clerk 設定](clerk-macos.md)、[既有推播 relay](../relay/README.md)。diff --git a/host/Cargo.lock b/host/Cargo.lockindex 4e46f00a..a35edf6f 100644--- a/host/Cargo.lock+++ b/host/Cargo.lock@@ -307,12 +307,14 @@ version = "2.1.0"dependencies = ["anyhow","axum",+ "base64","clap","crossterm","dirs","futures","gethostname","if-addrs",+ "pty-process","qrcode","ratatui","reqwest",@@ -1447,6 +1449,16 @@ dependencies = ["unicode-ident",]+[[package]]+name = "pty-process"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "71cec9e2670207c5ebb9e477763c74436af3b9091dd550b9fb3c1bec7f3ea266"+dependencies = [+ "rustix",+ "tokio",+]+[[package]]name = "qrcode"version = "0.14.1"diff --git a/host/Cargo.toml b/host/Cargo.tomlindex c14f716e..38e99fb4 100644--- a/host/Cargo.toml+++ b/host/Cargo.toml@@ -11,12 +11,14 @@ repository = "https://github.com/leepokai/Codync"[dependencies]anyhow = "1.0.104"axum = "0.8.9"+base64 = "0.23.1"clap = { version = "4.6.7", features = ["derive", "env"] }crossterm = { version = "0.29", features = ["event-stream"] }dirs = "7.0.0"futures = "0.3.34"gethostname = "1.1.0"if-addrs = "0.15.0"+pty-process = { version = "0.5.3", features = ["async"] }qrcode = { version = "0.14.1", default-features = false, features = ["svg"] }ratatui = { version = "0.30", default-features = false, features = ["crossterm"] }reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "stream"] }diff --git a/host/src/acp.rs b/host/src/acp.rsindex da3a1279..a1a1a830 100644--- a/host/src/acp.rs+++ b/host/src/acp.rs@@ -25,6 +25,24 @@ pub enum Incoming {/// In-flight requests by JSON-RPC id. A std mutex: it's never held across an `.await`.type Pending = Arc<std::sync::Mutex<HashMap<i64, oneshot::Sender<Result<Value, Value>>>>>;+/// A JSON-RPC error answer (downcast from `request`'s error to read the code).+#[derive(Debug)]+pub struct RpcError {+ pub code: i64,+ pub message: String,+}++/// ACP's "authentication required".+pub const AUTH_REQUIRED: i64 = -32000;++impl std::fmt::Display for RpcError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.message)+ }+}++impl std::error::Error for RpcError {}+pub struct Acp {stdin: tokio::sync::Mutex<ChildStdin>,next_id: AtomicI64,@@ -34,10 +52,16 @@ pub struct Acp {impl Acp {/// Spawns `command` through `sh -c` so user-provided commands (npx, env vars) just work.- pub fn spawn(command: &str, cwd: &str) -> Result<(Arc<Self>, mpsc::UnboundedReceiver<Incoming>)> {+ /// `env` stays out of the command line (it can hold API keys).+ pub fn spawn(+ command: &str,+ cwd: &str,+ env: &[(String, String)],+ ) -> Result<(Arc<Self>, mpsc::UnboundedReceiver<Incoming>)> {let mut child = Command::new("/bin/sh").arg("-c").arg(format!("exec {command}"))+ .envs(env.iter().map(|(k, v)| (k, v))).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped())@@ -136,10 +160,11 @@ impl Acp {Ok(Ok(v)) => Ok(v),Ok(Err(e)) => {let msg = e["message"].as_str().map_or_else(|| e.to_string(), str::to_owned);- match e["data"]["details"].as_str().or(e["data"].as_str()) {- Some(d) => bail!("{msg} ({d})"),- None => bail!("{msg}"),- }+ let message = match e["data"]["details"].as_str().or(e["data"].as_str()) {+ Some(d) => format!("{msg} ({d})"),+ None => msg,+ };+ Err(RpcError { code: e["code"].as_i64().unwrap_or_default(), message }.into())}Err(_) => bail!("{method}: connection closed"),}@@ -214,7 +239,7 @@ mod tests {async fn request_response_roundtrip() {// A fake agent: answers `initialize`, then sends a notification and exits.let script = r#"read l; id=$(echo "$l" | sed 's/.*"id":\([0-9]*\).*/\1/'); echo "{\"jsonrpc\":\"2.0\",\"id\":$id,\"result\":{\"ok\":true}}"; echo '{"jsonrpc":"2.0","method":"session/update","params":{"x":1}}'"#;- let (acp, mut rx) = Acp::spawn(&format!("sh -c '{}'", script.replace('\'', "'\\''")), "/tmp").unwrap();+ let (acp, mut rx) = Acp::spawn(&format!("sh -c '{}'", script.replace('\'', "'\\''")), "/tmp", &[]).unwrap();let res = acp.request("initialize", json!({})).await.unwrap();assert_eq!(res["ok"], true);match rx.recv().await.unwrap() {diff --git a/host/src/api.rs b/host/src/api.rsindex f21a028f..3a25aa4f 100644--- a/host/src/api.rs+++ b/host/src/api.rs@@ -31,6 +31,7 @@ pub fn router(hub: Arc<Hub>) -> Router {.route("/health", get(health)).route("/events", get(events)).route("/api/{method}", post(command))+ .route("/term/{id}", get(term_stream)).route("/ingest/statusline", post(statusline)).with_state(hub)}@@ -211,6 +212,7 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {}"refreshBackends" => {tokio::task::spawn_blocking(backends::hydrate_path).await?;+ backends::refresh_sign_in().await;json!({"backends": backends::list()})}"usage" => {@@ -269,6 +271,33 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {market::remove_skill(&hub.store, str_arg(&b, "id")?)?;json!({})}+ "agentSetup" => {+ let step: crate::term::Step =+ serde_json::from_value(b["step"].clone()).context("`step` is install or login")?;+ let (cols, rows) = term_size(&b);+ json!({"term": hub.terms.start(str_arg(&b, "backend")?, step, b["method"].as_str(), cols, rows)?})+ }+ "agentAuth" => crate::auth::check(&hub.store, str_arg(&b, "backend")?).await?,+ "agentAuthenticate" => {+ crate::auth::authenticate(&hub.store, str_arg(&b, "backend")?, str_arg(&b, "method")?).await?+ }+ "setAgentEnv" => {+ let vars = b["vars"].as_object().ok_or_else(|| anyhow!("`vars` is required"))?;+ crate::auth::set_env(&hub.store, str_arg(&b, "backend")?, vars).await?+ }+ "termInput" => {+ hub.terms.write(str_arg(&b, "term")?, str_arg(&b, "data")?)?;+ json!({})+ }+ "termResize" => {+ let (cols, rows) = term_size(&b);+ hub.terms.resize(str_arg(&b, "term")?, cols, rows)?;+ json!({})+ }+ "termClose" => {+ hub.terms.close(str_arg(&b, "term")?);+ json!({})+ }"screenStatus" => hub.screen.state(),"screenOffer" => {let display = b["display"].as_u64().and_then(|d| u32::try_from(d).ok());@@ -323,6 +352,40 @@ fn list_dirs(path: Option<std::path::PathBuf>) -> Result<Value> {}))}+fn term_size(b: &Value) -> (u16, u16) {+ let dim = |k: &str, default: u16| b[k].as_u64().and_then(|v| u16::try_from(v).ok()).unwrap_or(default);+ (dim("cols", 80), dim("rows", 24))+}++#[derive(Deserialize)]+struct TokenQuery {+ token: Option<String>,+}++/// A setup terminal's output: everything so far, then live, ending after `exit`.+async fn term_stream(+ State(hub): State<Arc<Hub>>,+ Path(id): Path<String>,+ headers: HeaderMap,+ Query(q): Query<TokenQuery>,+) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, ApiError> {+ if !authorized(&hub, &headers, q.token.as_deref()) {+ return Err(ApiError(StatusCode::UNAUTHORIZED, "invalid token".into()));+ }+ let term = hub.terms.get(&id).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "that terminal is gone".into()))?;+ let (head, rx) = term.attach();+ let done = head.iter().any(|v| v["type"] == "exit");+ let live = BroadcastStream::new(rx).filter_map(|msg| async move { msg.ok() }).scan(done, |done, v| {+ let out = (!*done).then(|| {+ *done = v["type"] == "exit";+ v+ });+ async move { out }+ });+ let events = stream::iter(head).chain(live).map(|v| Ok(Event::default().data(v.to_string())));+ Ok(Sse::new(events).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))))+}+#[derive(Deserialize)]struct EventsQuery {since: Option<i64>,diff --git a/host/src/auth.rs b/host/src/auth.rsnew file mode 100644index 00000000..3f2747d9--- /dev/null+++ b/host/src/auth.rs@@ -0,0 +1,336 @@+//! Signing agents in the ACP way, so every agent that speaks ACP can be set up+//! from Codync, not just the ones we know by name.+//!+//! A check starts the agent, reads the `authMethods` it advertises and tries+//! `session/new`: `-32000` means it needs signing in. Methods come in three kinds:+//! - terminal: a command (the agent's `_meta.terminal-auth`, or its own binary+//! with `args`), run in a setup terminal (`term`);+//! - agent: the agent signs itself in on `authenticate` (usually a browser on+//! this computer);+//! - env var: keys the user types, kept in the store and handed to the agent's+//! environment on every launch.++use crate::LockExt;+use crate::acp::{AUTH_REQUIRED, Acp, Incoming, RpcError};+use crate::backends;+use crate::registry::Cmd;+use crate::store::Store;+use anyhow::{Context, Result, anyhow, bail};+use serde::Serialize;+use serde_json::{Map, Value, json};+use std::collections::BTreeMap;+use std::path::PathBuf;+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tokio::sync::mpsc;++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase", tag = "kind")]+pub enum MethodKind {+ /// Shell command for a setup terminal. Never sent to clients.+ Terminal {+ #[serde(skip)]+ command: String,+ },+ Agent,+ EnvVar {+ vars: Vec<EnvVar>,+ link: Option<String>,+ },+}++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct EnvVar {+ pub name: String,+ pub label: String,+ pub secret: bool,+ pub optional: bool,+}++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Method {+ pub id: String,+ pub name: String,+ pub description: Option<String>,+ #[serde(flatten)]+ pub kind: MethodKind,+}++/// What the last check found for one backend.+#[derive(Clone, Debug, Default, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Status {+ pub signed_in: Option<bool>,+ /// The agent's own words when it wants signing in (can hold a pairing code).+ pub detail: Option<String>,+ pub methods: Vec<Method>,+}++static CHECKED: Mutex<BTreeMap<String, Status>> = Mutex::new(BTreeMap::new());++/// Where probe sessions live, away from the user's projects.+fn probe_dir() -> PathBuf {+ crate::service::data_dir().join("probe")+}++fn env_slot(backend: &str) -> String {+ format!("agent-env:{backend}")+}++/// Keys saved for `backend`, as environment for its process.+pub fn env(store: &Store, backend: &str) -> Vec<(String, String)> {+ store+ .kv_get(&env_slot(backend))+ .and_then(|s| serde_json::from_str::<BTreeMap<String, String>>(&s).ok())+ .map(|m| m.into_iter().collect())+ .unwrap_or_default()+}++/// Names of the saved keys (values never leave the host).+fn saved_env(store: &Store, backend: &str) -> Vec<String> {+ env(store, backend).into_iter().map(|(k, _)| k).collect()+}++/// Runs a check and returns `{signedIn, detail, methods, savedEnv}`.+pub async fn check(store: &Store, backend: &str) -> Result<Value> {+ let status = probe(store, backend).await?;+ backends::set_signed_in(backend, status.signed_in);+ CHECKED.locked().insert(backend.to_owned(), status.clone());+ let mut v = serde_json::to_value(&status)?;+ v["savedEnv"] = json!(saved_env(store, backend));+ Ok(v)+}++async fn probe(store: &Store, backend: &str) -> Result<Status> {+ let (acp, _inbox, init, cmd) = start(store, backend).await?;+ let methods = methods(backend, &init, &cmd);+ let dir = probe_dir();+ tokio::fs::create_dir_all(&dir).await?;+ let res = tokio::time::timeout(+ Duration::from_secs(60),+ acp.request("session/new", json!({"cwd": dir, "mcpServers": []})),+ )+ .await;+ acp.kill().await;+ let (signed_in, detail) = match res {+ Ok(Ok(_)) => (Some(true), None),+ Ok(Err(e)) => match e.downcast_ref::<RpcError>() {+ Some(r) if r.code == AUTH_REQUIRED => (Some(false), Some(r.message.clone())),+ _ => (None, Some(format!("{e:#}"))),+ },+ Err(_) => (None, None),+ };+ Ok(Status { signed_in, detail, methods })+}++/// Starts `backend` and completes `initialize`, trying each way to launch it.+/// The agent's inbox must stay open: the reader stops when nobody listens.+type Started = (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>, Value, Cmd);++async fn start(store: &Store, backend: &str) -> Result<Started> {+ let candidates = backends::launch_candidates(backend, |_| {}).await?;+ let env = env(store, backend);+ let dir = probe_dir();+ tokio::fs::create_dir_all(&dir).await?;+ let mut last = None;+ let count = candidates.len();+ for (i, cmd) in candidates.into_iter().enumerate() {+ // A first `npx` run downloads the package: give the last candidate time.+ let budget = Duration::from_secs(if i + 1 < count { 20 } else { 180 });+ let (acp, rx) = match Acp::spawn(&cmd.acp(), &dir.to_string_lossy(), &env) {+ Ok(v) => v,+ Err(e) => {+ last = Some(e);+ continue;+ }+ };+ let init = acp.request(+ "initialize",+ json!({+ "protocolVersion": 1,+ "clientCapabilities": {+ "fs": {"readTextFile": false, "writeTextFile": false},+ "terminal": false,+ // Ask for terminal sign-in methods (spec field and the older `_meta` flag).+ "auth": {"terminal": true},+ "_meta": {"terminal-auth": true},+ },+ "clientInfo": {"name": "codync", "title": "Codync", "version": env!("CARGO_PKG_VERSION")},+ }),+ );+ match tokio::time::timeout(budget, init).await {+ Ok(Ok(init)) => return Ok((acp, rx, init, cmd)),+ Ok(Err(e)) => last = Some(e),+ Err(_) => last = Some(anyhow!("the agent didn't start within {}s", budget.as_secs())),+ }+ acp.kill().await;+ }+ Err(last.unwrap_or_else(|| anyhow!("couldn't start the agent")))+}++fn text(v: &Value) -> Option<String> {+ v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)+}++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 joined_args(v: &Value) -> String {+ v.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.as_object()+ .map(|m| {+ m.iter()+ .filter(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))+ .filter_map(|(k, v)| Some(format!("{k}={} ", shell_quote(v.as_str()?))))+ .collect::<String>()+ })+ .unwrap_or_default()+}++/// The agent's advertised sign-in methods, in Codync's terms.+fn methods(backend: &str, init: &Value, cmd: &Cmd) -> Vec<Method> {+ let empty = Map::new();+ init["authMethods"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|m| {+ let id = text(&m["id"])?;+ let name = text(&m["name"]).unwrap_or_else(|| id.clone());+ let meta = m["_meta"].as_object().unwrap_or(&empty);+ let kind = if m["type"] == "env_var" {+ let vars = m["vars"]+ .as_array()?+ .iter()+ .filter_map(|v| {+ let name = text(&v["name"])?;+ name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_').then(|| EnvVar {+ label: text(&v["label"]).unwrap_or_else(|| name.clone()),+ secret: v["secret"].as_bool().unwrap_or(true),+ optional: v["optional"].as_bool().unwrap_or(false),+ name,+ })+ })+ .collect::<Vec<_>>();+ if vars.is_empty() {+ return None;+ }+ MethodKind::EnvVar { vars, link: text(&m["link"]) }+ } else if let Some(t) = meta.get("terminal-auth").filter(|t| t["command"].is_string()) {+ let program = t["command"].as_str().unwrap_or_default();+ // An adapter pointing at another harness's CLI is a copy-paste slip (Kilo → `opencode`).+ if backends::belongs_to_other(backend, program) {+ return None;+ }+ let command = format!("{}{} {}", env_prefix(&t["env"]), shell_quote(program), joined_args(&t["args"]));+ MethodKind::Terminal { command }+ } else if m["type"] == "terminal" || meta.get("type").is_some_and(|t| t == "terminal") {+ let args = if m["args"].is_array() { &m["args"] } else { meta.get("args").unwrap_or(&Value::Null) };+ let env = if m["env"].is_object() { &m["env"] } else { meta.get("env").unwrap_or(&Value::Null) };+ MethodKind::Terminal { command: format!("{}{} {}", env_prefix(env), cmd.program, joined_args(args)) }+ } else if meta.contains_key("api-key") || meta.contains_key("gateway") {+ // Keys the agent itself asks for through a UI we don't have.+ return None;+ } else {+ MethodKind::Agent+ };+ Some(Method { id, name, description: text(&m["description"]), kind })+ })+ .collect()+}++/// The terminal command for a method found by the last check.+pub fn terminal_command(backend: &str, method: &str) -> Option<String> {+ CHECKED.locked().get(backend)?.methods.iter().find(|m| m.id == method).and_then(|m| match &m.kind {+ MethodKind::Terminal { command } => Some(command.clone()),+ _ => None,+ })+}++/// Lets the agent sign itself in (it usually opens a browser on this computer).+pub async fn authenticate(store: &Store, backend: &str, method: &str) -> Result<Value> {+ let (acp, _inbox, _, _) = start(store, backend).await?;+ let res =+ tokio::time::timeout(Duration::from_secs(10 * 60), acp.request("authenticate", json!({"methodId": method})))+ .await;+ acp.kill().await;+ match res {+ Ok(r) => {+ r.context("signing in")?;+ }+ Err(_) => bail!("Sign-in didn't finish within 10 minutes."),+ }+ check(store, backend).await+}++/// Saves the keys for an env-var method (empty values remove them), then re-checks.+pub async fn set_env(store: &Store, backend: &str, vars: &Map<String, Value>) -> Result<Value> {+ let mut saved: BTreeMap<String, String> = env(store, backend).into_iter().collect();+ for (k, v) in vars {+ if !k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') || k.is_empty() {+ bail!("`{k}` isn't an environment variable name");+ }+ match v.as_str().map(str::trim).filter(|s| !s.is_empty()) {+ Some(v) => saved.insert(k.clone(), v.to_owned()),+ None => saved.remove(k),+ };+ }+ store.kv_set(&env_slot(backend), &serde_json::to_string(&saved)?)?;+ check(store, backend).await+}++#[cfg(test)]+mod tests {+ use super::*;++ fn cmd() -> Cmd {+ Cmd { program: "npx -y pkg@1".into(), args: "--acp".into() }+ }++ #[test]+ fn reads_every_kind_of_method() {+ let init = json!({"authMethods": [+ {"id": "a", "name": "Terminal meta", "_meta": {"terminal-auth": {"command": "/bin/tool", "args": ["login", "--x y"]}}},+ {"id": "b", "name": "Terminal args", "type": "terminal", "args": ["--terminal-login"]},+ {"id": "c", "name": "Key", "type": "env_var", "link": "https://k", "vars": [{"name": "Z_KEY", "label": "Key"}, {"name": "bad name"}]},+ {"id": "d", "name": "Browser"},+ {"id": "e", "name": "Api key", "_meta": {"api-key": {"provider": "openai"}}},+ {"id": "f", "name": "Qwen style", "_meta": {"type": "terminal", "args": ["--auth-type=openai"]}},+ ]});+ let m = methods("x", &init, &cmd());+ let kinds: Vec<_> = m.iter().map(|m| (m.id.as_str(), &m.kind)).collect();+ assert!(matches!(kinds[0], ("a", MethodKind::Terminal { command }) if command == "/bin/tool login '--x y'"));+ assert!(+ matches!(kinds[1], ("b", MethodKind::Terminal { command }) if command == "npx -y pkg@1 --terminal-login")+ );+ assert!(+ matches!(kinds[2], ("c", MethodKind::EnvVar { vars, .. }) if vars.len() == 1 && vars[0].name == "Z_KEY")+ );+ assert!(matches!(kinds[3], ("d", MethodKind::Agent)));+ assert!(+ matches!(kinds[4], ("f", MethodKind::Terminal { command }) if command == "npx -y pkg@1 --auth-type=openai")+ );+ assert_eq!(m.len(), 5);+ // Commands stay on the host.+ assert!(serde_json::to_value(&m[0]).unwrap().get("command").is_none());+ }++ #[test]+ fn skips_terminal_commands_of_another_harness() {+ let init = json!({"authMethods": [{"id": "k", "name": "Kilo", "_meta": {"terminal-auth": {"command": "opencode", "args": ["auth", "login"]}}}]});+ assert!(methods("kilo", &init, &cmd()).is_empty());+ assert_eq!(methods("opencode", &init, &cmd()).len(), 1);+ }+}diff --git a/host/src/backends.rs b/host/src/backends.rsindex c037de0e..9b810fb9 100644--- a/host/src/backends.rs+++ b/host/src/backends.rs@@ -23,7 +23,53 @@ pub struct Harness {pub local: Option<&'static str>,/// Entry in the ACP registry (adapter or pinned build).pub registry: Option<&'static str>,+ /// What to tell someone setting it up by hand.pub setup: &'static str,+ /// How Codync installs the CLI for you (in a setup terminal).+ pub install: Option<Install>,+ /// Shell command that signs in, run in a setup terminal.+ pub login: &'static str,+ /// How to tell whether it's signed in without starting it.+ pub signed_in: Option<SignInCheck>,+}++#[derive(Clone, Copy)]+pub enum Install {+ /// A vendor install script (`curl … | bash`).+ Script(&'static str),+ /// A global npm package.+ Npm(&'static str),+}++impl Install {+ pub fn command(self) -> String {+ match self {+ Self::Script(s) => s.to_owned(),+ Self::Npm(pkg) => format!(+ "command -v npm >/dev/null || {{ echo 'This needs Node.js first: https://nodejs.org'; exit 1; }}; npm install -g {pkg}"+ ),+ }+ }+}++/// `<bin> <args>`, judged by exit code and stdout.+#[derive(Clone, Copy)]+pub struct SignInCheck {+ pub args: &'static str,+ pub ok: fn(bool, &str) -> bool,+}++fn exit_ok(success: bool, _: &str) -> bool {+ success+}++fn claude_signed_in(_: bool, out: &str) -> bool {+ serde_json::from_str::<Value>(out).is_ok_and(|v| v["loggedIn"] == true)+}++fn says_logged_in(_: bool, out: &str) -> bool {+ let out = out.to_lowercase();+ out.contains("logged in") && !out.contains("not logged in")}pub const HARNESSES: &[Harness] = &[@@ -34,6 +80,9 @@ pub const HARNESSES: &[Harness] = &[local: None,registry: Some("claude-acp"),setup: "Install Claude Code and run `claude` once to sign in.",+ install: Some(Install::Script("curl -fsSL https://claude.ai/install.sh | bash")),+ login: "claude auth login",+ signed_in: Some(SignInCheck { args: "auth status", ok: claude_signed_in }),},Harness {id: "codex",@@ -42,6 +91,9 @@ pub const HARNESSES: &[Harness] = &[local: None,registry: Some("codex-acp"),setup: "Install Codex CLI and run `codex login`.",+ install: Some(Install::Npm("@openai/codex")),+ login: "codex login --device-auth",+ signed_in: Some(SignInCheck { args: "login status", ok: exit_ok }),},Harness {id: "cursor",@@ -50,6 +102,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} acp"),registry: Some("cursor"),setup: "Install Cursor CLI (curl https://cursor.com/install -fsS | bash) and run `cursor-agent login`.",+ install: Some(Install::Script("curl https://cursor.com/install -fsS | bash")),+ login: "cursor-agent login",+ signed_in: Some(SignInCheck { args: "status", ok: says_logged_in }),},Harness {id: "pi",@@ -58,6 +113,9 @@ pub const HARNESSES: &[Harness] = &[local: None,registry: Some("pi-acp"),setup: "Install pi (npm install -g @mariozechner/pi-coding-agent) and sign in with `pi`.",+ install: Some(Install::Npm("@mariozechner/pi-coding-agent")),+ login: "pi",+ signed_in: None,},Harness {id: "opencode",@@ -66,6 +124,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} acp"),registry: Some("opencode"),setup: "Install OpenCode (curl -fsSL https://opencode.ai/install | bash) and run `opencode auth login`.",+ install: Some(Install::Script("curl -fsSL https://opencode.ai/install | bash")),+ login: "opencode auth login",+ signed_in: None,},Harness {id: "grok",@@ -74,6 +135,9 @@ pub const HARNESSES: &[Harness] = &[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.",+ install: Some(Install::Script("curl -fsSL https://x.ai/cli/install.sh | bash")),+ login: "grok",+ signed_in: None,},Harness {id: "gemini",@@ -82,6 +146,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} --acp"),registry: Some("gemini"),setup: "Install Gemini CLI (npm install -g @google/gemini-cli) and run `gemini` once to sign in.",+ install: Some(Install::Npm("@google/gemini-cli")),+ login: "gemini",+ signed_in: None,},Harness {id: "copilot",@@ -90,6 +157,9 @@ pub const HARNESSES: &[Harness] = &[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.",+ install: Some(Install::Npm("@github/copilot")),+ login: "copilot",+ signed_in: None,},Harness {id: "qwen",@@ -98,6 +168,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} --acp"),registry: Some("qwen-code"),setup: "Install Qwen Code (npm install -g @qwen-code/qwen-code) and sign in with `qwen`.",+ install: Some(Install::Npm("@qwen-code/qwen-code")),+ login: "qwen",+ signed_in: None,},Harness {id: "goose",@@ -106,6 +179,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} acp"),registry: Some("goose"),setup: "Install goose and run `goose configure`.",+ install: None,+ login: "goose configure",+ signed_in: None,},Harness {id: "kimi",@@ -114,6 +190,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} acp"),registry: Some("kimi"),setup: "Install Kimi CLI and sign in with `kimi`.",+ install: None,+ login: "kimi",+ signed_in: None,},Harness {id: "droid",@@ -122,6 +201,9 @@ pub const HARNESSES: &[Harness] = &[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`.",+ install: Some(Install::Script("curl -fsSL https://app.factory.ai/cli | sh")),+ login: "droid",+ signed_in: None,},Harness {id: "amp",@@ -130,6 +212,9 @@ pub const HARNESSES: &[Harness] = &[local: None,registry: Some("amp-acp"),setup: "Install Amp and sign in with `amp login`.",+ install: None,+ login: "amp login",+ signed_in: None,},Harness {id: "kilo",@@ -138,6 +223,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} acp"),registry: Some("kilo"),setup: "Install Kilo CLI (npm install -g @kilocode/cli) and sign in.",+ install: Some(Install::Npm("@kilocode/cli")),+ login: "kilo",+ signed_in: None,},Harness {id: "cline",@@ -146,6 +234,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} --acp"),registry: Some("cline"),setup: "Install Cline CLI (npm install -g cline) and sign in.",+ install: Some(Install::Npm("cline")),+ login: "cline",+ signed_in: None,},Harness {id: "auggie",@@ -154,6 +245,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} --acp"),registry: Some("auggie"),setup: "Install Auggie (npm install -g @augmentcode/auggie) and run `auggie login`.",+ install: Some(Install::Npm("@augmentcode/auggie")),+ login: "auggie login",+ signed_in: None,},Harness {id: "vibe",@@ -162,6 +256,9 @@ pub const HARNESSES: &[Harness] = &[local: None,registry: Some("mistral-vibe"),setup: "Install Mistral Vibe and run `vibe` once to sign in.",+ install: None,+ login: "vibe",+ signed_in: None,},Harness {id: "kiro",@@ -170,6 +267,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} acp"),registry: None,setup: "Install Kiro CLI (curl -fsSL https://cli.kiro.dev/install | bash) and run `kiro-cli login`.",+ install: Some(Install::Script("curl -fsSL https://cli.kiro.dev/install | bash")),+ login: "kiro-cli login",+ signed_in: None,},Harness {id: "devin",@@ -178,6 +278,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} acp"),registry: Some("devin"),setup: "Install the Devin CLI and sign in.",+ install: None,+ login: "devin",+ signed_in: None,},Harness {id: "qoder",@@ -186,6 +289,9 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} --acp"),registry: Some("qoder"),setup: "Install Qoder CLI and sign in.",+ install: None,+ login: "qodercli",+ signed_in: None,},];@@ -338,6 +444,8 @@ pub fn list() -> Vec<Value> {"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,+ "signedIn": signed_in(h.id),+ "canInstall": h.install.is_some(),"command": h.local.unwrap_or_default(),"registry": h.registry,"curated": true,@@ -359,6 +467,7 @@ pub fn list() -> Vec<Value> {"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)),+ "signedIn": signed_in(id),"command": "","registry": id,"curated": false,@@ -368,20 +477,77 @@ pub fn list() -> Vec<Value> {out}+// MARK: sign-in++/// Last sign-in check per harness id; missing = can't tell.+static SIGNED_IN: Mutex<Vec<(String, bool)>> = Mutex::new(Vec::new());++pub fn signed_in(id: &str) -> Option<bool> {+ SIGNED_IN.locked().iter().find(|(h, _)| h == id).map(|(_, ok)| *ok)+}++/// Records what a check found (`None`: can't tell).+pub fn set_signed_in(id: &str, state: Option<bool>) {+ let mut map = SIGNED_IN.locked();+ map.retain(|(h, _)| h != id);+ if let Some(ok) = state {+ map.push((id.to_owned(), ok));+ }+}++/// Re-checks every installed harness that can report its sign-in state.+pub async fn refresh_sign_in() {+ let checks = HARNESSES.iter().filter_map(|h| {+ let check = h.signed_in?;+ let bin = h.bins.iter().find_map(|b| which(b))?;+ Some(async move {+ let run = tokio::process::Command::new(bin)+ .args(check.args.split_whitespace())+ .stdin(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .kill_on_drop(true)+ .output();+ let ok = match tokio::time::timeout(Duration::from_secs(15), run).await {+ Ok(Ok(out)) => Some((check.ok)(out.status.success(), &String::from_utf8_lossy(&out.stdout))),+ Ok(Err(e)) => {+ tracing::info!(backend = h.id, error = %e, "sign-in check failed");+ None+ }+ Err(_) => None,+ };+ (h.id, ok)+ })+ });+ let results = futures::future::join_all(checks).await;+ for (id, ok) in results {+ set_signed_in(id, ok);+ }+}++/// `program` is some other harness's CLI (not `backend`'s own).+pub fn belongs_to_other(backend: &str, program: &str) -> bool {+ let name = Path::new(program).file_name().and_then(|n| n.to_str()).unwrap_or(program);+ let own = |h: &Harness| h.id == backend || h.registry == Some(backend);+ HARNESSES.iter().any(|h| !own(h) && h.bins.contains(&name))+ && !HARNESSES.iter().any(|h| own(h) && h.bins.contains(&name))+}+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>> {+pub async fn launch_candidates(id: &str, progress: impl Fn(&str)) -> anyhow::Result<Vec<registry::Cmd>> {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 program = shell_quote(&path.to_string_lossy());+ let args = template.strip_prefix("{bin}").unwrap_or(template).trim().to_owned();+ out.push(registry::Cmd { program, args });}let reg_id = h.map_or(Some(id), |h| h.registry);if let Some(agent) = reg_id.and_then(registry::agent) {diff --git a/host/src/bot.rs b/host/src/bot.rsindex 3727d26f..54d547f3 100644--- a/host/src/bot.rs+++ b/host/src/bot.rs@@ -214,7 +214,7 @@ impl Actor {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);+ msg = format!("{0} needs you to sign in. Open {0} in Marketplace to sign in.", h.name);}self.notice(&msg, NoticeStyle::Error);self.turn = None;@@ -330,15 +330,20 @@ impl Actor {hub.set_runtime(&id, |r| r.activity = msg);}).await?+ .iter()+ .map(crate::registry::Cmd::acp)+ .collect()}};self.hub.set_runtime(&self.id(), |r| r.activity = "Starting agent…".into());+ // Keys saved from an "environment variable" sign-in.+ let env = crate::auth::env(&self.hub.store, &self.cfg.backend);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 {+ match start_agent(command, &self.cfg.cwd, &env, budget).await {Ok(conn) => {self.conn = Some(conn);break;@@ -737,8 +742,8 @@ 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)?;+async fn start_agent(command: &str, cwd: &str, env: &[(String, String)], budget: Duration) -> Result<Conn> {+ let (acp, rx) = Acp::spawn(command, cwd, env)?;let init = tokio::time::timeout(budget,acp.request(diff --git a/host/src/hub.rs b/host/src/hub.rsindex 75289417..2db002db 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -49,6 +49,8 @@ pub struct Hub {/// botId -> Live Activity push tickets.pub activities: Mutex<HashMap<String, Vec<String>>>,pub screen: Arc<Screen>,+ /// Setup terminals (installs, sign-ins).+ pub terms: Arc<crate::term::Terms>,}impl Hub {@@ -69,6 +71,7 @@ impl Hub {keep_awake: Mutex::default(),activities: Mutex::default(),screen,+ terms: Arc::default(),})}diff --git a/host/src/main.rs b/host/src/main.rsindex 3ebae065..a87ef63c 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -2,6 +2,7 @@mod acp;mod api;+mod auth;mod backends;mod bot;mod hub;@@ -12,6 +13,7 @@ mod registry;mod screen;mod service;mod store;+mod term;mod tui;mod usage;@@ -270,6 +272,7 @@ async fn serve(bind: &str, port: u16) -> Result<()> {let hub = hub::Hub::new(store, host_id, token, port);hub.start()?;tokio::spawn(registry::refresh_loop());+ tokio::spawn(backends::refresh_sign_in());tokio::spawn(usage::poll(hub.clone()));tokio::spawn(screen::serve_helpers(hub.screen.clone()));#[cfg(target_os = "linux")]diff --git a/host/src/registry.rs b/host/src/registry.rsindex c0cb45d0..2f377dcb 100644--- a/host/src/registry.rs+++ b/host/src/registry.rs@@ -141,9 +141,23 @@ fn contained(rel: &str) -> Option<&Path> {p.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)).then_some(p)}-/// Shell command that starts the agent over ACP stdio, downloading it first if needed.+/// How to run a registry agent: `program` alone (what ACP `terminal` sign-in+/// methods add their own args to) and `args` for its ACP mode.+pub struct Cmd {+ pub program: String,+ pub args: String,+}++impl Cmd {+ /// The shell command that starts it over ACP stdio.+ pub fn acp(&self) -> String {+ format!("{} {}", self.program, self.args)+ }+}++/// Downloads the agent first if needed./// `progress` receives short status lines ("Downloading Cursor…").-pub async fn command(agent: &Value, progress: impl Fn(&str)) -> Result<String> {+pub async fn command(agent: &Value, progress: impl Fn(&str)) -> Result<Cmd> {let name = agent["name"].as_str().unwrap_or("agent");let d = &agent["distribution"];match launch_kind(agent) {@@ -153,20 +167,27 @@ pub async fn command(agent: &Value, progress: impl Fn(&str)) -> Result<String> {let cmd =target["cmd"].as_str().and_then(contained).ok_or_else(|| anyhow!("registry entry has a bad cmd"))?;let dir = install_binary(agent, target, cmd, &progress).await?;- Ok(format!("{}{} {}", env_prefix(target), shell_quote(&dir.join(cmd).to_string_lossy()), args_of(target)))+ Ok(Cmd {+ program: format!("{}{}", env_prefix(target), shell_quote(&dir.join(cmd).to_string_lossy())),+ args: args_of(target),+ })}- Some(Launch::Npx) => Ok(format!(- "{}npx -y {} {}",- env_prefix(&d["npx"]),- shell_quote(d["npx"]["package"].as_str().unwrap_or_default()),- args_of(&d["npx"])- )),- Some(Launch::Uvx) => Ok(format!(- "{}uvx {} {}",- env_prefix(&d["uvx"]),- shell_quote(d["uvx"]["package"].as_str().unwrap_or_default()),- args_of(&d["uvx"])- )),+ Some(Launch::Npx) => Ok(Cmd {+ program: format!(+ "{}npx -y {}",+ env_prefix(&d["npx"]),+ shell_quote(d["npx"]["package"].as_str().unwrap_or_default())+ ),+ args: args_of(&d["npx"]),+ }),+ Some(Launch::Uvx) => Ok(Cmd {+ program: format!(+ "{}uvx {}",+ env_prefix(&d["uvx"]),+ shell_quote(d["uvx"]["package"].as_str().unwrap_or_default())+ ),+ args: args_of(&d["uvx"]),+ }),None => bail!("{name} has no build for this computer (needs {})",if d["uvx"].is_object() { "uv" } else { "Node.js" }@@ -292,7 +313,7 @@ mod tests {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", "BAD;rm": "x"}}}});if crate::backends::on_path("npx") {- assert_eq!(command(&a, |_| {}).await.unwrap(), "K=v npx -y @s/[email protected] --acp 'a b'");+ assert_eq!(command(&a, |_| {}).await.unwrap().acp(), "K=v npx -y @s/[email protected] --acp 'a b'");}}diff --git a/host/src/term.rs b/host/src/term.rsnew file mode 100644index 00000000..379bfed0--- /dev/null+++ b/host/src/term.rs@@ -0,0 +1,242 @@+//! Setup terminals: installing an agent's CLI or signing in to it runs in a+//! real PTY on this computer, streamed to the client that started it. The+//! host picks the command (from `backends::HARNESSES`); clients only type.++use crate::LockExt;+use crate::backends;+use anyhow::{Result, anyhow, bail};+use base64::Engine as _;+use base64::engine::general_purpose::STANDARD as B64;+use serde::Deserialize;+use serde_json::{Value, json};+use std::collections::HashMap;+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::sync::{broadcast, mpsc};++/// Output kept for a client that (re)attaches mid-run.+const SCROLLBACK: usize = 256 * 1024;+/// A finished terminal stays readable this long.+const LINGER: Duration = Duration::from_secs(10 * 60);++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum Step {+ Install,+ Login,+}++enum Input {+ Data(Vec<u8>),+ Resize(u16, u16),+ Kill,+}++struct Output {+ scrollback: Vec<u8>,+ exit: Option<i32>,+}++pub struct Term {+ key: (String, Step),+ input: mpsc::UnboundedSender<Input>,+ output: Mutex<Output>,+ /// `{"type":"output","data":<base64>}` and `{"type":"exit","code":n}`.+ events: broadcast::Sender<Value>,+}++impl Term {+ /// The scrollback so far plus a live feed, taken atomically so nothing is lost or doubled.+ pub fn attach(&self) -> (Vec<Value>, broadcast::Receiver<Value>) {+ let out = self.output.locked();+ let rx = self.events.subscribe();+ let mut head = vec![];+ if !out.scrollback.is_empty() {+ head.push(json!({"type": "output", "data": B64.encode(&out.scrollback)}));+ }+ if let Some(code) = out.exit {+ head.push(json!({"type": "exit", "code": code}));+ }+ (head, rx)+ }++ fn push(&self, bytes: &[u8]) {+ let mut out = self.output.locked();+ out.scrollback.extend_from_slice(bytes);+ if out.scrollback.len() > SCROLLBACK {+ let cut = out.scrollback.len() - SCROLLBACK;+ out.scrollback.drain(..cut);+ }+ let _ = self.events.send(json!({"type": "output", "data": B64.encode(bytes)}));+ }++ fn finish(&self, code: i32) {+ self.output.locked().exit = Some(code);+ let _ = self.events.send(json!({"type": "exit", "code": code}));+ }+}++#[derive(Default)]+pub struct Terms(Mutex<HashMap<String, Arc<Term>>>);++impl Terms {+ pub fn get(&self, id: &str) -> Option<Arc<Term>> {+ self.0.locked().get(id).cloned()+ }++ /// Starts `step` for `backend` (a sign-in `method` the agent advertised, or+ /// Codync's own command for it), or returns the one already running.+ pub fn start(+ self: &Arc<Self>,+ backend: &str,+ step: Step,+ method: Option<&str>,+ cols: u16,+ rows: u16,+ ) -> Result<String> {+ let h = backends::harness(backend);+ let name = h.map_or(backend, |h| h.name);+ let command = match step {+ Step::Install => {+ let h = h.ok_or_else(|| anyhow!("Codync downloads {name} by itself"))?;+ h.install.ok_or_else(|| anyhow!("{}", h.setup))?.command()+ }+ // Some CLIs (codex) delete the current credentials the moment a new sign-in starts.+ Step::Login if backends::signed_in(backend) == Some(true) => bail!("{name} is already signed in"),+ Step::Login => match method {+ Some(m) => crate::auth::terminal_command(backend, m)+ .ok_or_else(|| anyhow!("That sign-in option is gone; check {name} again"))?,+ None => h.ok_or_else(|| anyhow!("Pick a sign-in option for {name}"))?.login.to_owned(),+ },+ };+ self.spawn((backend.to_owned(), step), &command, cols, rows)+ }++ fn spawn(self: &Arc<Self>, key: (String, Step), command: &str, cols: u16, rows: u16) -> Result<String> {+ let mut map = self.0.locked();+ if let Some((id, _)) = map.iter().find(|(_, t)| t.key == key && t.output.locked().exit.is_none()) {+ return Ok(id.clone());+ }+ let (pty, pts) = pty_process::open()?;+ pty.resize(pty_process::Size::new(rows.max(4), cols.max(20)))?;+ let child = pty_process::Command::new("/bin/sh")+ .arg("-c")+ .arg(command)+ .env("TERM", "xterm-256color")+ .env("COLORTERM", "truecolor")+ .current_dir(dirs::home_dir().unwrap_or_else(|| "/".into()))+ .kill_on_drop(true)+ .spawn(pts)?;+ let (tx, rx) = mpsc::unbounded_channel();+ let term = Arc::new(Term {+ key,+ input: tx,+ output: Mutex::new(Output { scrollback: vec![], exit: None }),+ events: broadcast::channel(256).0,+ });+ term.push(format!("\x1b[2m$ {command}\x1b[0m\r\n").as_bytes());+ let id = uuid::Uuid::new_v4().to_string();+ map.insert(id.clone(), term.clone());+ tracing::info!(backend = term.key.0, step = ?term.key.1, term = %id, "setup terminal started");+ tokio::spawn(run(self.clone(), id.clone(), term, pty, child, rx));+ Ok(id)+ }++ pub fn write(&self, id: &str, data: &str) -> Result<()> {+ let bytes = B64.decode(data)?;+ self.send(id, Input::Data(bytes))+ }++ pub fn resize(&self, id: &str, cols: u16, rows: u16) -> Result<()> {+ self.send(id, Input::Resize(cols, rows))+ }++ pub fn close(&self, id: &str) {+ if let Some(t) = self.0.locked().remove(id) {+ let _ = t.input.send(Input::Kill);+ }+ }++ fn send(&self, id: &str, input: Input) -> Result<()> {+ let t = self.get(id).ok_or_else(|| anyhow!("that terminal is gone"))?;+ // Input after exit has nowhere to go; not an error for the typist.+ let _ = t.input.send(input);+ Ok(())+ }+}++async fn run(+ terms: Arc<Terms>,+ id: String,+ term: Arc<Term>,+ pty: pty_process::Pty,+ mut child: tokio::process::Child,+ mut rx: mpsc::UnboundedReceiver<Input>,+) {+ let (mut reader, mut writer) = pty.into_split();+ let pump = {+ let term = term.clone();+ tokio::spawn(async move {+ let mut buf = vec![0u8; 16 * 1024];+ // EOF or EIO once the child and its children are gone.+ while let Ok(n @ 1..) = reader.read(&mut buf).await {+ term.push(&buf[..n]);+ }+ })+ };+ let status = loop {+ tokio::select! {+ status = child.wait() => break status,+ input = rx.recv() => match input {+ Some(Input::Data(bytes)) => {+ if let Err(error) = writer.write_all(&bytes).await {+ tracing::info!(%error, "setup terminal write failed");+ }+ }+ Some(Input::Resize(cols, rows)) => {+ let _ = writer.resize(pty_process::Size::new(rows.max(4), cols.max(20)));+ }+ Some(Input::Kill) | None => {+ let _ = child.start_kill();+ }+ },+ }+ };+ // Let the last output drain; a background grandchild can hold the PTY open forever.+ let _ = tokio::time::timeout(Duration::from_secs(1), pump).await;+ let code = status.ok().and_then(|s| s.code()).unwrap_or(-1);+ tracing::info!(term = %id, code, "setup terminal finished");+ term.finish(code);+ tokio::time::sleep(LINGER).await;+ terms.0.locked().remove(&id);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn runs_in_a_pty_and_takes_input() {+ let terms = Arc::new(Terms::default());+ let id =+ terms.spawn(("test".into(), Step::Login), "[ -t 0 ] && echo tty; read x; echo got-$x", 80, 24).unwrap();+ let term = terms.get(&id).unwrap();+ let (_, mut rx) = term.attach();+ terms.write(&id, &B64.encode("hi\n")).unwrap();+ let code = tokio::time::timeout(Duration::from_secs(10), async {+ loop {+ let v = rx.recv().await.unwrap();+ if v["type"] == "exit" {+ return v["code"].as_i64().unwrap();+ }+ }+ })+ .await+ .unwrap();+ assert_eq!(code, 0);+ let (head, _) = term.attach();+ let text = String::from_utf8(B64.decode(head[0]["data"].as_str().unwrap()).unwrap()).unwrap();+ assert!(text.contains("tty") && text.contains("got-hi"), "{text}");+ }+}diff --git a/kit/Package.swift b/kit/Package.swiftindex 5fada50b..0c9802dc 100644--- a/kit/Package.swift+++ b/kit/Package.swift@@ -11,12 +11,19 @@ let package = Package(dependencies: [// libwebrtc for the remote screen viewer (hardware H.264 over WebRTC)..package(url: "https://github.com/stasel/WebRTC.git", exact: "153.0.0"),+ // Terminal emulator for agent install and sign-in. 1.19+ adds a build-tool+ // plugin every Xcode build would have to trust.+ .package(url: "https://github.com/migueldeicaza/SwiftTerm.git", exact: "1.18.0"),],targets: [.target(name: "CodyncKit"),.target(name: "CodyncUI",- dependencies: ["CodyncKit", .product(name: "WebRTC", package: "WebRTC", condition: .when(platforms: [.iOS]))],+ dependencies: [+ "CodyncKit",+ .product(name: "WebRTC", package: "WebRTC", condition: .when(platforms: [.iOS])),+ .product(name: "SwiftTerm", package: "SwiftTerm"),+ ],resources: [.process("Resources")]),.testTarget(name: "CodyncKitTests", dependencies: ["CodyncKit"], resources: [.copy("Fixtures")]),diff --git a/kit/Sources/CodyncKit/Client/HostClient.swift b/kit/Sources/CodyncKit/Client/HostClient.swiftindex 311e881a..86e97f12 100644--- a/kit/Sources/CodyncKit/Client/HostClient.swift+++ b/kit/Sources/CodyncKit/Client/HostClient.swift@@ -57,6 +57,12 @@ public enum HostEvent: Sendable {case undecodable(type: String)}+/// A setup terminal's output stream.+public enum TermEvent: Sendable {+ case output(Data)+ case exit(Int)+}+public struct Empty: Codable, Sendable {public init() {}}@@ -119,9 +125,26 @@ public struct HostClient: Sendable {public func events(since: Int64, client: String) -> AsyncThrowingStream<HostEvent, Error> {var comps = URLComponents(url: baseURL.appending(path: "events"), resolvingAgainstBaseURL: false)!comps.queryItems = [.init(name: "since", value: String(since)), .init(name: "client", value: client)]+ return sse(comps.url!, parse: Self.parseEvent)+ }++ /// A setup terminal's output: everything so far, then live, finishing after `.exit`.+ public func termOutput(_ term: String) -> AsyncThrowingStream<TermEvent, Error> {+ sse(baseURL.appending(path: "term/\(term)")) { data in+ struct Raw: Decodable { var type: String; var data: String?; var code: Int? }+ guard let raw = try? Self.decoder.decode(Raw.self, from: data) else { return nil }+ switch raw.type {+ case "output": return raw.data.flatMap { Data(base64Encoded: $0) }.map(TermEvent.output)+ case "exit": return .exit(raw.code ?? -1)+ default: return nil+ }+ }+ }++ private func sse<T: Sendable>(_ url: URL, parse: @escaping @Sendable (Data) -> T?) -> AsyncThrowingStream<T, Error> {// Idle timeout, not a total one: the host pings every 15 s, so silence this long means it's// gone (shut down, asleep, off the network) even if the socket never closed.- var req = URLRequest(url: comps.url!, timeoutInterval: 45)+ var req = URLRequest(url: url, timeoutInterval: 45)req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")req.setValue("text/event-stream", forHTTPHeaderField: "Accept")let session = self.session@@ -135,7 +158,7 @@ public struct HostClient: Sendable {for try await line in bytes.lines {guard line.hasPrefix("data:") else { continue }let payload = Data(line.dropFirst(5).utf8)- if let event = Self.parseEvent(payload) {+ if let event = parse(payload) {continuation.yield(event)}}@@ -286,6 +309,37 @@ public extension HostClient {}}+// MARK: - Agent setup++public extension HostClient {+ func refreshBackends() async throws -> [Backend] {+ struct Res: Decodable { var backends: [Backend] }+ let res: Res = try await call("refreshBackends", timeout: 60)+ return res.backends+ }++ /// Starts (or rejoins) installing or signing in to `backend` in a terminal on the computer.+ func agentSetup(backend: String, step: SetupStep, cols: Int, rows: Int) async throws -> String {+ struct Body: Encodable { var backend: String; var step: SetupStep; var cols: Int; var rows: Int }+ struct Res: Decodable { var term: String }+ let res: Res = try await call("agentSetup", Body(backend: backend, step: step, cols: cols, rows: rows))+ return res.term+ }++ func termInput(_ term: String, _ bytes: Data) async throws {+ let _: Empty = try await call("termInput", ["term": term, "data": bytes.base64EncodedString()])+ }++ func termResize(_ term: String, cols: Int, rows: Int) async throws {+ struct Body: Encodable { var term: String; var cols: Int; var rows: Int }+ let _: Empty = try await call("termResize", Body(term: term, cols: cols, rows: rows))+ }++ func termClose(_ term: String) async throws {+ let _: Empty = try await call("termClose", ["term": term])+ }+}+public struct ScreenAnswer: Codable, Sendable {public var session: Stringpublic var sdp: Stringdiff --git a/kit/Sources/CodyncKit/Client/SharedStore.swift b/kit/Sources/CodyncKit/Client/SharedStore.swiftindex 01fa2e5e..8f8e9456 100644--- a/kit/Sources/CodyncKit/Client/SharedStore.swift+++ b/kit/Sources/CodyncKit/Client/SharedStore.swift@@ -1,4 +1,5 @@import Foundation+import CryptoKit/// Values shared between the iOS app and its widgets through the App Group.public enum SharedStore {@@ -8,44 +9,104 @@ public enum SharedStore {private static var defaults: UserDefaults { UserDefaults(suiteName: appGroup) ?? .standard }- public static var pairing: Pairing? {- get { defaults.data(forKey: "pairing").flatMap { try? JSONDecoder().decode(Pairing.self, from: $0) } }- set { defaults.set(newValue.flatMap { try? JSONEncoder().encode($0) }, forKey: "pairing") }+ /// Widgets read only the account selected by the app. Stores capture a fixed+ /// context so late responses from a previous account cannot write into it.+ public static var activeAccountID: String? {+ get { defaults.string(forKey: "activeAccountID") }+ set { defaults.set(newValue, forKey: "activeAccountID") }}- /// Every computer this phone has paired with, most recently used first.- /// `pairing` is the active one.- public static var computers: [Pairing] {- get {- let saved = defaults.data(forKey: "computers").flatMap { try? JSONDecoder().decode([Pairing].self, from: $0) } ?? []- return saved.isEmpty ? pairing.map { [$0] } ?? [] : saved+ public static var activeContext: Context { Context(accountID: activeAccountID) }++ public struct Context {+ public let accountID: String?+ private let defaults: UserDefaults+ public var id: String { accountID.map { Self.digest($0) } ?? "local" }++ public init(accountID: String?, defaults: UserDefaults = UserDefaults(suiteName: SharedStore.appGroup) ?? .standard) {+ self.accountID = accountID+ self.defaults = defaults+ }++ private func key(_ name: String) -> String { accountID == nil ? name : "account.\(id).\(name)" }+ public static func digest(_ value: String) -> String {+ SHA256.hash(data: Data(value.utf8)).map { String(format: "%02x", $0) }.joined()+ }+ private func read<T: Decodable>(_ type: T.Type, _ name: String) -> T? {+ defaults.data(forKey: key(name)).flatMap { try? JSONDecoder().decode(type, from: $0) }+ }+ private func write<T: Encodable>(_ value: T?, _ name: String) {+ defaults.set(value.flatMap { try? JSONEncoder().encode($0) }, forKey: key(name))+ }+ public var pairing: Pairing? {+ get { read(Pairing.self, "pairing") }+ nonmutating set { write(newValue, "pairing") }+ }+ public var computers: [Pairing] {+ get { read([Pairing].self, "computers") ?? pairing.map { [$0] } ?? [] }+ nonmutating set { write(newValue, "computers") }+ }+ public var preferredURL: String? {+ get { defaults.string(forKey: key("preferredURL")) }+ nonmutating set { defaults.set(newValue, forKey: key("preferredURL")) }+ }+ public var usage: Usage? {+ get { read(Usage.self, "usage") }+ nonmutating set { write(newValue, "usage") }+ }+ public var bots: [Bot] {+ get { read([Bot].self, "bots") ?? [] }+ nonmutating set { write(newValue, "bots") }+ }+ /// Deep links carry the storage scope captured when a widget/activity+ /// was created, so an old surface cannot open another account's bot.+ public func botURL(_ botID: String) -> URL {+ var url = URLComponents()+ url.scheme = "codync"+ url.host = "bot"+ url.path = "/" + botID+ url.queryItems = [+ URLQueryItem(name: "scope", value: id),+ URLQueryItem(name: "computer", value: Self.digest(pairing?.token ?? "unpaired"))+ ]+ return url.url!+ }+ public func acceptsBotURL(_ url: URL) -> Bool {+ guard url.scheme == "codync", url.host == "bot" else { return false }+ let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []+ guard let scope = items.first(where: { $0.name == "scope" })?.value else {+ return accountID == nil+ }+ return scope == id && items.first(where: { $0.name == "computer" })?.value == Self.digest(pairing?.token ?? "unpaired")+ }+ public var orderedPairing: Pairing? {+ guard var p = pairing else { return nil }+ if let preferredURL, let i = p.urls.firstIndex(of: preferredURL) {+ p.urls.insert(p.urls.remove(at: i), at: 0)+ }+ return p}- set { defaults.set(try? JSONEncoder().encode(newValue), forKey: "computers") }}- /// Last address that answered, tried first next time.+ public static var pairing: Pairing? {+ get { activeContext.pairing }+ set { activeContext.pairing = newValue }+ }+ public static var computers: [Pairing] {+ get { activeContext.computers }+ set { activeContext.computers = newValue }+ }public static var preferredURL: String? {- get { defaults.string(forKey: "preferredURL") }- set { defaults.set(newValue, forKey: "preferredURL") }+ get { activeContext.preferredURL }+ set { activeContext.preferredURL = newValue }}-public static var usage: Usage? {- get { defaults.data(forKey: "usage").flatMap { try? JSONDecoder().decode(Usage.self, from: $0) } }- set { defaults.set(newValue.flatMap { try? JSONEncoder().encode($0) }, forKey: "usage") }+ get { activeContext.usage }+ set { activeContext.usage = newValue }}-- /// Roster snapshot for the Bots widget, written by the app as bots change.public static var bots: [Bot] {- get { defaults.data(forKey: "bots").flatMap { try? JSONDecoder().decode([Bot].self, from: $0) } ?? [] }- set { defaults.set(try? JSONEncoder().encode(newValue), forKey: "bots") }- }-- /// Pairing with the last working address moved to the front.- public static var orderedPairing: Pairing? {- guard var p = pairing else { return nil }- if let preferred = preferredURL, let i = p.urls.firstIndex(of: preferred) {- p.urls.insert(p.urls.remove(at: i), at: 0)- }- return p+ get { activeContext.bots }+ set { activeContext.bots = newValue }}+ public static var orderedPairing: Pairing? { activeContext.orderedPairing }}diff --git a/kit/Sources/CodyncKit/Design/UsageBar.swift b/kit/Sources/CodyncKit/Design/UsageBar.swiftindex a632279d..76e33af8 100644--- a/kit/Sources/CodyncKit/Design/UsageBar.swift+++ b/kit/Sources/CodyncKit/Design/UsageBar.swift@@ -36,14 +36,8 @@ public struct UsageBar: View {}public extension UsageProvider {- /// Each provider's own color, used by the Usage tab and the provider widget.- var tint: Color {- switch id {- case "claude": Color(hex: 0xD97757)- case "codex": Color(hex: 0x3D8BF2)- default: Palette.accent- }- }+ /// Claude keeps its orange; everyone else is ink, like the rest of the app.+ var tint: Color { id == "claude" ? Color(hex: 0xD97757) : Palette.accent }/// ACP registry id of the provider's agent, for its logo (`AgentIcon`)./// Claude and Codex run through ACP adapters (`claude-acp`, `codex-acp`); others by their own id.diff --git a/kit/Sources/CodyncKit/Models/BotActivity.swift b/kit/Sources/CodyncKit/Models/BotActivity.swiftindex aff7592a..c7a3e634 100644--- a/kit/Sources/CodyncKit/Models/BotActivity.swift+++ b/kit/Sources/CodyncKit/Models/BotActivity.swift@@ -18,12 +18,14 @@ public struct BotActivityAttributes: ActivityAttributes {}}+ public var link: URL?public var botId: Stringpublic var name: Stringpublic var avatarShape: Stringpublic var avatarColor: String- public init(bot: Bot) {+ public init(bot: Bot, link: URL? = nil) {+ self.link = linkbotId = bot.idname = bot.nameavatarShape = bot.avatarShapediff --git a/kit/Sources/CodyncKit/Models/Models.swift b/kit/Sources/CodyncKit/Models/Models.swiftindex 0b25f69f..c41d2240 100644--- a/kit/Sources/CodyncKit/Models/Models.swift+++ b/kit/Sources/CodyncKit/Models/Models.swift@@ -204,6 +204,16 @@ public struct Backend: Codable, Hashable, Sendable, Identifiable {public var registry: String?public var description: String?public var installed: Bool?+ /// Known to Codync by name: it can install and sign in to it.+ public var curated: Bool?+ /// Missing when the host can't tell.+ public var signedIn: Bool?+ public var canInstall: Bool?+}++/// What a setup terminal on the computer runs.+public enum SetupStep: String, Codable, Sendable {+ case install, login}public struct Hello: Codable, Sendable {diff --git a/kit/Sources/CodyncUI/Bots/BotEditorView.swift b/kit/Sources/CodyncUI/Bots/BotEditorView.swiftindex a17b1245..3219c6c1 100644--- a/kit/Sources/CodyncUI/Bots/BotEditorView.swift+++ b/kit/Sources/CodyncUI/Bots/BotEditorView.swift@@ -103,12 +103,12 @@ struct BotSettingsForm: View {var body: some View {ScrollView {- VStack(alignment: .leading, spacing: 18) {- VStack(spacing: 16) {+ VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 12, mobile: 18)) {+ VStack(spacing: InterfaceMetrics.value(mac: 12, mobile: 16)) {#if os(macOS)Button { pickingAvatar.toggle() } label: {- CharacterAvatar(shape: draft.avatarShape, color: draft.avatarColor, size: 80)- .padding(18)+ CharacterAvatar(shape: draft.avatarShape, color: draft.avatarColor, size: 56)+ .padding(12).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 20))}.buttonStyle(.plain)@@ -116,7 +116,7 @@ struct BotSettingsForm: View {.help("Edit Bot avatar").popover(isPresented: $pickingAvatar) {AvatarPicker(shape: $draft.avatarShape, color: $draft.avatarColor)- .padding(20)+ .padding(14).frame(width: 300)}#else@@ -141,7 +141,12 @@ struct BotSettingsForm: View {}// Grok-style option card: no dividers, values in outlined pills.- VStack(alignment: .leading, spacing: 20) {+ VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 12, mobile: 20)) {+ OptionRow("Computer") {+ Text(model.hostName)+ .lineLimit(1)+ .foregroundStyle(Palette.secondary)+ }OptionRow("Agent") {PillMenu(title: model.backendName(draft.backend), selection: $draft.backend,options: (model.hello?.backends ?? []).map { ($0.id, $0.available ? $0.name : "\($0.name) (not installed)") } + [("custom", "Custom command")])@@ -161,7 +166,7 @@ struct BotSettingsForm: View {.plainTextInput().multilineTextAlignment(.trailing).textFieldStyle(.plain)- .frame(width: 130)+ .frame(width: InterfaceMetrics.value(mac: 100, mobile: 130)).pill()}OptionRow("Project folder") {@@ -182,7 +187,7 @@ struct BotSettingsForm: View {Toggle(isOn: Binding(get: { draft.notify ?? true }, set: { draft.notify = $0 })) {VStack(alignment: .leading, spacing: 3) {Text("Notifications").foregroundStyle(Palette.text)- Text("Get notified when this bot finishes or needs you").font(.subheadline).foregroundStyle(Palette.secondary)+ Text("Get notified when this bot finishes or needs you").font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary)}}.toggleStyle(.switch)@@ -194,15 +199,15 @@ struct BotSettingsForm: View {Text(model.screen?.enabled == true? "Let this bot see the screen and use the mouse and keyboard. You can watch and take over from your phone.": "Let this bot see the screen and use the mouse and keyboard. Turn on Remote screen in Codync's menu on the computer first.")- .font(.subheadline).foregroundStyle(Palette.secondary)+ .font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary)}}.toggleStyle(.switch).tint(Palette.switchOn)}}- .padding(.horizontal, 18)- .padding(.vertical, 20)+ .padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 18))+ .padding(.vertical, InterfaceMetrics.value(mac: 14, mobile: 20)).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))PluginToggles(@@ -228,8 +233,12 @@ struct BotSettingsForm: View {Text(error).font(.footnote).foregroundStyle(Palette.danger)}}- .padding(20)+ .padding(InterfaceMetrics.value(mac: 14, mobile: 20))}+ .font(InterfaceMetrics.body)+ #if os(macOS)+ .controlSize(.small)+ #endif.scrollDismissesKeyboard(.interactively).background(Palette.background).task { await model.refreshPlugins() }@@ -263,7 +272,7 @@ private struct Field<Content: View>: View {var body: some View {VStack(alignment: .leading, spacing: 6) {- Text(label).font(.subheadline).foregroundStyle(Palette.secondary).padding(.leading, 4)+ Text(label).font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary).padding(.leading, 4)content}}@@ -296,10 +305,10 @@ private struct PluginToggles: View {var body: some View {VStack(alignment: .leading, spacing: 6) {- Text(title).font(.subheadline).foregroundStyle(Palette.secondary).padding(.leading, 4)- VStack(alignment: .leading, spacing: 16) {+ Text(title).font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary).padding(.leading, 4)+ VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 12, mobile: 16)) {if items.isEmpty {- Text(empty).font(.subheadline).foregroundStyle(Palette.secondary)+ Text(empty).font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary)}ForEach(items, id: \.id) { item inToggle(isOn: Binding(@@ -320,7 +329,7 @@ private struct PluginToggles: View {.tint(Palette.switchOn)}}- .padding(18)+ .padding(InterfaceMetrics.value(mac: 12, mobile: 18)).frame(maxWidth: .infinity, alignment: .leading).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))}@@ -357,8 +366,8 @@ private struct PillMenu: View {extension View {/// The outlined value pill used in the options card.func pill() -> some View {- padding(.horizontal, 12)- .padding(.vertical, 7)+ padding(.horizontal, InterfaceMetrics.value(mac: 9, mobile: 12))+ .padding(.vertical, InterfaceMetrics.value(mac: 5, mobile: 7)).background(Palette.background, in: RoundedRectangle(cornerRadius: 10, style: .continuous)).overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).stroke(Palette.border))}@@ -366,8 +375,8 @@ extension View {/// A bordered, rounded input box.func fieldBox() -> some View {textFieldStyle(.plain)- .padding(.horizontal, 14)- .padding(.vertical, 11)+ .padding(.horizontal, InterfaceMetrics.value(mac: 10, mobile: 14))+ .padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 11)).background(Palette.background, in: RoundedRectangle(cornerRadius: 12, style: .continuous)).overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).stroke(Palette.border))}diff --git a/kit/Sources/CodyncUI/Bots/BotRow.swift b/kit/Sources/CodyncUI/Bots/BotRow.swiftindex f956ef73..b0e8f3d5 100644--- a/kit/Sources/CodyncUI/Bots/BotRow.swift+++ b/kit/Sources/CodyncUI/Bots/BotRow.swift@@ -13,8 +13,8 @@ public struct BotRow: View {// A Mac sidebar row is denser than a phone row (Grok Bot's desktop sidebar).#if os(macOS)- private let avatar: CGFloat = 36- private let rowPadding: CGFloat = 8+ private let avatar: CGFloat = 30+ private let rowPadding: CGFloat = 6private let lineSpacing: CGFloat = 1#elseprivate let avatar: CGFloat = 46@@ -23,7 +23,7 @@ public struct BotRow: View {#endifpublic var body: some View {- HStack(spacing: compact ? 0 : 12) {+ HStack(spacing: compact ? 0 : InterfaceMetrics.value(mac: 8, mobile: 12)) {AvatarWithStatus(bot: bot, size: avatar)VStack(alignment: .leading, spacing: lineSpacing) {HStack(alignment: .firstTextBaseline) {@@ -31,7 +31,7 @@ public struct BotRow: View {Image(systemName: "pin.fill").font(.caption2).foregroundStyle(Palette.tertiary)}Text(bot.name)- .font(.body.weight(.semibold))+ .font(InterfaceMetrics.body.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(1)if model.screen?.agentBot == bot.id {@@ -43,7 +43,7 @@ public struct BotRow: View {Spacer(minLength: 8)#if os(iOS)Text(RelativeTime.day(Date(milliseconds: bot.lastAt)))- .font(.subheadline)+ .font(InterfaceMetrics.secondary).foregroundStyle(bot.unread > 0 ? Palette.text : Palette.tertiary)#endif}@@ -75,7 +75,7 @@ public struct BotRow: View {@ViewBuilder private var preview: some View {if bot.needsInput {Label(bot.activity.isEmpty ? "Needs your approval" : bot.activity, systemImage: "hand.raised.fill")- .font(.subheadline)+ .font(InterfaceMetrics.secondary).foregroundStyle(Palette.warning).lineLimit(1)} else if bot.isWorking {@@ -84,16 +84,16 @@ public struct BotRow: View {Text(bot.activity.isEmpty ? "Working…" : bot.activity).lineLimit(1)}- .font(.subheadline)+ .font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary)} else if bot.status == "error" {Text(bot.lastMessage ?? "Something went wrong")- .font(.subheadline)+ .font(InterfaceMetrics.secondary).foregroundStyle(Palette.danger).lineLimit(1)} else {Text(bot.lastMessage ?? "\(model.backendName(bot.backend)) · \(bot.folderName)")- .font(.subheadline)+ .font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary).lineLimit(1)}diff --git a/kit/Sources/CodyncUI/Bots/BotTemplateView.swift b/kit/Sources/CodyncUI/Bots/BotTemplateView.swiftnew file mode 100644index 00000000..dd08aaee--- /dev/null+++ b/kit/Sources/CodyncUI/Bots/BotTemplateView.swift@@ -0,0 +1,70 @@+import CodyncKit+import SwiftUI++/// A portable settings snapshot, with no conversation identity or runtime state.+struct BotTemplateView: View {+ @Environment(\.dismiss) private var dismiss+ @State private var copied = false+ private let template: BotDraft+ private let encoded: String?++ init(draft: BotDraft) {+ var template = draft+ template.id = nil+ template.pinned = nil+ template.hidden = nil+ self.template = template+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]+ encoded = (try? encoder.encode(template)).flatMap { String(data: $0, encoding: .utf8) }+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 20) {+ HStack {+ VStack(alignment: .leading, spacing: 5) {+ Text("Create template").font(.title2.weight(.semibold))+ Text(template.name).font(.subheadline).foregroundStyle(Palette.secondary)+ }+ Spacer()+ Button("Close", systemImage: "xmark") { dismiss() }+ .labelStyle(.iconOnly)+ .buttonStyle(.plain)+ .keyboardShortcut(.cancelAction)+ }+ Text("Copy this bot’s settings to reuse as a template. Conversation history and conversation ID are excluded.")+ .font(.callout)+ .foregroundStyle(Palette.secondary)+ ScrollView {+ Text(encoded ?? "Unable to create this template.")+ .font(.system(size: 12, design: .monospaced))+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(16)+ }+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))+ .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(Palette.border))+ HStack {+ Text("Includes the working folder and agent configuration.")+ .font(.caption).foregroundStyle(Palette.secondary)+ Spacer()+ Button {+ Pasteboard.copy(encoded)+ copied = true+ } label: {+ Label(copied ? "Copied" : "Copy template", systemImage: copied ? "checkmark" : "square.on.square")+ .font(.system(size: 13, weight: .semibold))+ .padding(.horizontal, 14).padding(.vertical, 9)+ .foregroundStyle(Palette.onAccent)+ .background(Palette.accentFill, in: RoundedRectangle(cornerRadius: 9))+ }+ .buttonStyle(.plain)+ .disabled(encoded == nil)+ .keyboardShortcut(.defaultAction)+ }+ }+ .padding(24)+ .frame(width: 560, height: 540)+ .background(Palette.background)+ }+}diff --git a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swiftindex ed9f58a4..6f63815b 100644--- a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift+++ b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift@@ -20,7 +20,7 @@ public struct MarketplaceView: View {@State private var busySkill: String?@State private var addingConnector = false@State private var writingSkill = false- @State private var newBot: EditorRequest?+ @State private var agent: Backend?@State private var showInstalled = false/// Shown as a sheet: a close button in the header instead of the navigation bar.let close: (() -> Void)?@@ -30,7 +30,7 @@ public struct MarketplaceView: View {private var query: String { search.trimmingCharacters(in: .whitespaces) }private var agents: [Backend] {- let all = (model.hello?.backends ?? []).filter { $0.available || $0.installed == true }+ let all = (model.hello?.backends ?? []).filter { $0.available || $0.installed == true || $0.curated == true }let hits = query.isEmpty ? all : all.filter { $0.name.localizedCaseInsensitiveContains(query) }return Array(hits.prefix(query.isEmpty ? 8 : 12))}@@ -154,6 +154,8 @@ public struct MarketplaceView: View {.task {await model.refreshPlugins()}+ // Picks up CLIs installed or signed in outside Codync.+ .task { await model.refreshBackends() }.task { await loadConnectors() }.task {do { skills = try await model.marketSkills() } catch { self.error = error.localizedDescription }@@ -177,10 +179,10 @@ public struct MarketplaceView: View {.frame(minWidth: 480, minHeight: 480)#endif}- .sheet(item: $newBot) { request in- NavigationStack { BotEditorView(draft: request.draft) }+ .sheet(item: $agent) { b in+ NavigationStack { AgentSheet(initial: b) }#if os(macOS)- .frame(minWidth: 520, minHeight: 640)+ .frame(minWidth: 640, minHeight: 460)#endif}}@@ -235,11 +237,7 @@ public struct MarketplaceView: View {}private func agentCard(_ b: Backend) -> some View {- AgentCard(backend: b) {- var d = BotDraft(name: b.name)- d.backend = b.id- newBot = EditorRequest(d)- }+ AgentCard(backend: b) { agent = b }}private func loadConnectors() async {@@ -388,6 +386,14 @@ private struct AgentCard: View {let action: () -> Void@State private var hovering = false+ private var status: String {+ switch (backend.installed == true, backend.signedIn) {+ case (true, false?): "Not signed in"+ case (true, _): "Installed"+ case (false, _): backend.curated == true ? "Not installed" : "Sets up on first use"+ }+ }+var body: some View {Button(action: action) {VStack(spacing: 12) {@@ -396,7 +402,7 @@ private struct AgentCard: View {.background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))VStack(spacing: 2) {Text(backend.name).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(1)- Text(backend.installed == true ? "Installed" : "Sets up on first use")+ Text(status).font(.caption).foregroundStyle(Palette.secondary).lineLimit(1)@@ -411,7 +417,126 @@ private struct AgentCard: View {}.buttonStyle(PressScale()).onHover { h in withAnimation(Motion.hover) { hovering = h } }- .help("New bot with \(backend.name)")+ .help(backend.name)+ }+}++/// Getting an agent ready on the computer: install it, then sign in. Both run+/// in a terminal on that computer. Bots are made from New chat, not here.+private struct AgentSheet: View {+ let initial: Backend+ @Environment(BotStore.self) private var model+ @Environment(\.dismiss) private var dismiss+ @State private var running: SetupStep?++ /// Live: an install or sign-in updates the host's list.+ private var backend: Backend { model.hello?.backends.first { $0.id == initial.id } ?? initial }+ private var installed: Bool { backend.installed == true }++ var body: some View {+ Form {+ Section {+ HStack(spacing: 14) {+ AgentIcon(registry: backend.registry, size: 30)+ .frame(width: 52, height: 52)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 14, style: .continuous))+ VStack(alignment: .leading, spacing: 2) {+ Text(backend.name).font(.title3.weight(.semibold))+ if let d = backend.description, !d.isEmpty {+ Text(d).font(.subheadline).foregroundStyle(Palette.secondary).lineLimit(3)+ }+ }+ }+ .padding(.vertical, 4)+ }+ if backend.curated == true {+ Section {+ SetupStepRow(+ number: 1,+ title: "Install",+ detail: installed+ ? "Installed on \(model.hostName)."+ : backend.canInstall == true ? "Runs the official installer on \(model.hostName)." : backend.installHint,+ done: installed,+ action: installed || backend.canInstall != true ? nil : ("Install", { running = .install })+ )+ SetupStepRow(+ number: 2,+ title: "Sign in",+ detail: signInDetail,+ done: backend.signedIn == true,+ // Some CLIs drop the current sign-in as soon as a new one starts.+ action: installed && backend.signedIn != true ? ("Sign in", { running = .login }) : nil+ )+ } footer: {+ Text("Each step runs in a terminal on \(model.hostName). Sign-in links open on this device.")+ }+ } else {+ Section {+ Text("Codync downloads \(backend.name) the first time a bot uses it. If it needs an account, the bot tells you how to sign in.")+ .foregroundStyle(Palette.secondary)+ }+ }+ }+ .formStyle(.grouped)+ .navigationTitle(backend.name)+ .inlineNavigationTitle()+ .navigationDestination(item: $running) { step in SetupTerminalView(backend: backend, step: step) }+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Close", systemImage: "xmark") { dismiss() }.labelStyle(.iconOnly)+ }+ }+ }++ private var signInDetail: String {+ guard installed else { return "After it's installed." }+ switch backend.signedIn {+ case true?: return "Signed in."+ case false?: return "Not signed in yet."+ case nil: return "Skip this if you've already signed in on \(model.hostName)."+ }+ }+}++private struct SetupStepRow: View {+ let number: Int+ let title: String+ let detail: String+ let done: Bool+ let action: (label: String, run: () -> Void)?++ var body: some View {+ HStack(spacing: 12) {+ ZStack {+ Circle().fill(done ? Palette.accentFill : Palette.bubbleAgent)+ if done {+ Image(systemName: "checkmark").font(.caption.weight(.bold)).foregroundStyle(Palette.onAccent)+ } else {+ Text("\(number)").font(.caption.weight(.semibold)).foregroundStyle(Palette.secondary)+ }+ }+ .frame(width: 26, height: 26)+ .accessibilityHidden(true)+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.body.weight(.medium)).foregroundStyle(Palette.text)+ Text(detail).font(.subheadline).foregroundStyle(Palette.secondary).textSelection(.enabled)+ }+ Spacer(minLength: 8)+ if let action {+ Button(action.label, action: action.run)+ .buttonStyle(.plain)+ .font(.subheadline.weight(.semibold))+ .foregroundStyle(Palette.text)+ .padding(.horizontal, 14)+ .padding(.vertical, 7)+ .background(Palette.bubbleAgent, in: Capsule())+ .fixedSize()+ }+ }+ .padding(.vertical, 4)+ .accessibilityElement(children: .combine)+ .accessibilityValue(done ? "Done" : "")}}diff --git a/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift b/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swiftnew file mode 100644index 00000000..b339229d--- /dev/null+++ b/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift@@ -0,0 +1,240 @@+import CodyncKit+import SwiftTerm+import SwiftUI+#if canImport(UIKit)+import UIKit+#else+import AppKit+#endif++/// Installing or signing in to an agent, live: the command runs in a terminal+/// on the computer and this screen is that terminal (links open here).+struct SetupTerminalView: View {+ let backend: Backend+ let step: SetupStep+ @Environment(BotStore.self) private var model+ @Environment(\.dismiss) private var dismiss+ @Environment(\.openURL) private var openURL+ @State private var session = TermSession()++ var body: some View {+ VStack(spacing: 0) {+ TerminalSurface(session: session) { openURL($0) }+ .padding(.horizontal, 10)+ .padding(.top, 6)+ footer+ }+ .background(Palette.background)+ .navigationTitle(step == .install ? "Install \(backend.name)" : "Sign in to \(backend.name)")+ .inlineNavigationTitle()+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Close", systemImage: "xmark") { dismiss() }.labelStyle(.iconOnly)+ }+ }+ .task {+ guard let client = model.client else { return }+ await session.run(client, backend: backend.id, step: step)+ await model.refreshBackends()+ }+ .onDisappear { session.close() }+ }++ private var footer: some View {+ HStack(spacing: 8) {+ if let error = session.error {+ Text(error).foregroundStyle(Palette.danger)+ } else if let code = session.exitCode {+ Image(systemName: code == 0 ? "checkmark.circle.fill" : "exclamationmark.circle.fill")+ .foregroundStyle(code == 0 ? Palette.added : Palette.warning)+ Text(code == 0 ? "Finished." : "Ended with an error (\(code)).")+ .foregroundStyle(Palette.secondary)+ } else {+ ThinkingOrb(size: 14, color: Palette.secondary)+ Text("Running on \(model.hostName). Links open on this device.")+ .foregroundStyle(Palette.secondary)+ }+ Spacer(minLength: 0)+ if session.exitCode != nil {+ Button("Done") { dismiss() }.buttonStyle(.borderedProminent)+ }+ }+ .font(.footnote)+ .lineLimit(2)+ .padding(.horizontal, 16)+ .padding(.vertical, 10)+ }+}++/// One setup terminal on the host: keystrokes go up in order, output comes down.+@MainActor @Observable+final class TermSession {+ private(set) var exitCode: Int?+ private(set) var error: String?+ @ObservationIgnored weak var view: TerminalView?+ @ObservationIgnored private var client: HostClient?+ @ObservationIgnored private var term: String?+ @ObservationIgnored private var size = (cols: 80, rows: 24)+ @ObservationIgnored private var sentSize = (cols: 0, rows: 0)+ @ObservationIgnored private let keys: AsyncStream<Data>.Continuation+ @ObservationIgnored private let keyStream: AsyncStream<Data>+ @ObservationIgnored private var typing: Task<Void, Never>?++ init() {+ (keyStream, keys) = AsyncStream.makeStream()+ }++ func run(_ client: HostClient, backend: String, step: SetupStep) async {+ self.client = client+ let term: String+ do {+ term = try await client.agentSetup(backend: backend, step: step, cols: size.cols, rows: size.rows)+ } catch {+ self.error = error.localizedDescription+ return+ }+ self.term = term+ sentSize = size+ syncSize()+ let keyStream = keyStream+ // One sender, so keystrokes can't overtake each other.+ typing = Task {+ for await bytes in keyStream {+ try? await client.termInput(term, bytes)+ }+ }+ // Reattach after a dropped connection; the host replays the whole scrollback.+ var attempt = 0+ while exitCode == nil, !Task.isCancelled {+ do {+ view?.getTerminal().resetToInitialState()+ for try await event in client.termOutput(term) {+ attempt = 0+ switch event {+ case .output(let data): view?.feed(byteArray: ArraySlice(data))+ case .exit(let code): exitCode = code+ }+ }+ } catch HostError.http(404, let message) {+ error = message+ return+ } catch {+ attempt += 1+ if attempt > 5 {+ self.error = error.localizedDescription+ return+ }+ }+ if exitCode == nil { try? await Task.sleep(for: .seconds(1)) }+ }+ }++ func type(_ bytes: ArraySlice<UInt8>) {+ guard exitCode == nil else { return }+ keys.yield(Data(bytes))+ }++ func resized(cols: Int, rows: Int) {+ size = (cols, rows)+ syncSize()+ }++ private func syncSize() {+ guard let client, let term, size != sentSize else { return }+ sentSize = size+ let size = size+ Task { try? await client.termResize(term, cols: size.cols, rows: size.rows) }+ }++ /// Leaving the screen ends whatever is still running.+ func close() {+ keys.finish()+ typing?.cancel()+ guard exitCode == nil, let client, let term else { return }+ Task { try? await client.termClose(term) }+ }+}++// MARK: - SwiftTerm bridge++private final class TerminalBridge: NSObject, @preconcurrency TerminalViewDelegate {+ let session: TermSession+ let open: (URL) -> Void++ init(session: TermSession, open: @escaping (URL) -> Void) {+ self.session = session+ self.open = open+ }++ @MainActor func make() -> TerminalView {+ let view = TerminalView(frame: CGRect(x: 0, y: 0, width: 400, height: 300))+ view.terminalDelegate = self+ #if canImport(UIKit)+ view.font = .monospacedSystemFont(ofSize: 12, weight: .regular)+ view.nativeBackgroundColor = UIColor(Palette.background)+ view.nativeForegroundColor = UIColor(Palette.text)+ view.keyboardDismissMode = .interactive+ #else+ view.font = .monospacedSystemFont(ofSize: 12, weight: .regular)+ view.nativeBackgroundColor = NSColor(Palette.background)+ view.nativeForegroundColor = NSColor(Palette.text)+ #endif+ session.view = view+ return view+ }++ @MainActor func focus(_ view: TerminalView) {+ #if canImport(UIKit)+ _ = view.becomeFirstResponder()+ #else+ view.window?.makeFirstResponder(view)+ #endif+ }++ @MainActor func send(source: TerminalView, data: ArraySlice<UInt8>) { session.type(data) }+ @MainActor func sizeChanged(source: TerminalView, newCols: Int, newRows: Int) {+ session.resized(cols: newCols, rows: newRows)+ }+ @MainActor func requestOpenLink(source: TerminalView, link: String, params: [String: String]) {+ if let url = URL(string: link), url.scheme?.hasPrefix("http") == true { open(url) }+ }+ func setTerminalTitle(source: TerminalView, title: String) {}+ func hostCurrentDirectoryUpdate(source: TerminalView, directory: String?) {}+ func scrolled(source: TerminalView, position: Double) {}+ func rangeChanged(source: TerminalView, startY: Int, endY: Int) {}+ func clipboardCopy(source: TerminalView, content: Data) {+ Pasteboard.copy(String(data: content, encoding: .utf8))+ }+}++#if canImport(UIKit)+private struct TerminalSurface: UIViewRepresentable {+ let session: TermSession+ let open: (URL) -> Void++ func makeCoordinator() -> TerminalBridge { TerminalBridge(session: session, open: open) }++ func makeUIView(context: Context) -> TerminalView {+ let view = context.coordinator.make()+ Task { @MainActor in context.coordinator.focus(view) }+ return view+ }++ func updateUIView(_ view: TerminalView, context: Context) {}+}+#else+private struct TerminalSurface: NSViewRepresentable {+ let session: TermSession+ let open: (URL) -> Void++ func makeCoordinator() -> TerminalBridge { TerminalBridge(session: session, open: open) }++ func makeNSView(context: Context) -> TerminalView {+ let view = context.coordinator.make()+ Task { @MainActor in context.coordinator.focus(view) }+ return view+ }++ func updateNSView(_ view: TerminalView, context: Context) {}+}+#endifdiff --git a/kit/Sources/CodyncUI/Platform.swift b/kit/Sources/CodyncUI/Platform.swiftindex 05265914..76cfab1d 100644--- a/kit/Sources/CodyncUI/Platform.swift+++ b/kit/Sources/CodyncUI/Platform.swift@@ -81,3 +81,30 @@ extension View {#endif}}++/// Compact desktop metrics while preserving the phone's touch layout and Dynamic Type.+enum InterfaceMetrics {+ static func value(mac: CGFloat, mobile: CGFloat) -> CGFloat {+ #if os(macOS)+ mac+ #else+ mobile+ #endif+ }++ static var body: Font {+ #if os(macOS)+ .system(size: 12)+ #else+ .body+ #endif+ }++ static var secondary: Font {+ #if os(macOS)+ .system(size: 11)+ #else+ .subheadline+ #endif+ }+}diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swiftindex c4822e3b..31fa4b95 100644--- a/kit/Sources/CodyncUI/Store/BotStore.swift+++ b/kit/Sources/CodyncUI/Store/BotStore.swift@@ -32,7 +32,7 @@ public final class BotStore {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()+ public private(set) var usage: Usage/// The computer's remote screen (`nil`: the host predates it).public private(set) var screen: ScreenState?/// Installed on the computer, for the Plugins screen and bot settings.@@ -60,6 +60,8 @@ public final class BotStore {private let clientKind: String/// Whether pairing lives in the shared App Group (iPhone) or is supplied each launch (Mac).private let persistsPairing: Bool+ public let storage: SharedStore.Context+ private var retired = falseprivate var rev: Int64 = 0private var hostId: String?@@ -68,11 +70,14 @@ public final class BotStore {private var saveTask: Task<Void, Never>?private var rewound = false- public init(pairing: Pairing?, clientKind: String, persistsPairing: Bool) {+ public init(pairing: Pairing?, clientKind: String, persistsPairing: Bool, storage: SharedStore.Context? = nil) {+ let storage = storage ?? (persistsPairing ? SharedStore.activeContext : SharedStore.Context(accountID: nil))+ self.storage = storage+ usage = storage.usage ?? Usage()self.pairing = pairingself.clientKind = clientKindself.persistsPairing = persistsPairing- computers = persistsPairing ? SharedStore.computers : pairing.map { [$0] } ?? []+ computers = persistsPairing ? storage.computers : pairing.map { [$0] } ?? []loadCache()connection = pairing == nil ? .unpaired : .connecting}@@ -81,7 +86,7 @@ public final class BotStore {private var orderedPairing: Pairing? {guard persistsPairing else { return pairing }- return SharedStore.orderedPairing ?? pairing+ return storage.orderedPairing ?? pairing}public var isOffline: Bool {@@ -110,15 +115,16 @@ public final class BotStore {// MARK: pairingpublic func pair(_ p: Pairing) {+ guard !retired else { return }let changedHost = pairing?.token != p.tokenpairing = pif persistsPairing {- SharedStore.pairing = p- SharedStore.preferredURL = nil+ storage.pairing = p+ storage.preferredURL = nil}// Re-pairing the same computer (new token after a reset) replaces its old entry.computers = [p] + computers.filter { $0.token != p.token && $0.name != p.name }- if persistsPairing { SharedStore.computers = computers }+ if persistsPairing { storage.computers = computers }if changedHost { resetMirror() }connection = .connectingrestartStream()@@ -128,7 +134,7 @@ public final class BotStore {/// Forgets a computer; forgetting the active one switches to the next, if any.public func forget(_ p: Pairing) {computers.removeAll { $0.token == p.token }- if persistsPairing { SharedStore.computers = computers }+ if persistsPairing { storage.computers = computers }guard p.token == pairing?.token else { return }if let next = computers.first { pair(next) } else { unpair() }}@@ -141,8 +147,8 @@ public final class BotStore {computers = computers.map { var c = $0; if c.token == token { change(&c) }; return c }if pairing?.token == token { change(&pairing!) }guard persistsPairing else { return }- SharedStore.computers = computers- if SharedStore.pairing?.token == token, var p = SharedStore.pairing { change(&p); SharedStore.pairing = p }+ storage.computers = computers+ if storage.pairing?.token == token, var p = storage.pairing { change(&p); storage.pairing = p }}public func unpair() {@@ -150,7 +156,7 @@ public final class BotStore {pairing = nilclient = nilhello = nil- if persistsPairing { SharedStore.pairing = nil }+ if persistsPairing { storage.pairing = nil }resetMirror()connection = .unpaired}@@ -167,7 +173,25 @@ public final class BotStore {// MARK: lifecycle+ /// Permanently detach a store when the client changes accounts. Existing+ /// async callbacks retain this old store and its fixed storage namespace.+ public func retire() {+ setActive(false)+ retired = true+ saveTask?.cancel()+ onPaired = nil+ onBotUpdated = nil+ onUsageChanged = nil+ onSent = nil+ client = nil+ selection = nil+ screenRequest = nil+ showProfile = false+ showPlugins = false+ }+public func setActive(_ active: Bool) {+ guard !retired else { return }isActive = activeif active {restartStream()@@ -181,7 +205,7 @@ public final class BotStore {public func restartStream() {streamTask?.cancel()- guard pairing != nil, isActive else { return }+ guard pairing != nil, isActive, !retired else { return }if connection != .online { connection = .connecting }streamTask = Task { [weak self] in await self?.runStream() }}@@ -191,16 +215,19 @@ public final class BotStore {while !Task.isCancelled {guard let pairing = orderedPairing else { return }guard let client = await HostClient.resolve(pairing) else {+ guard !Task.isCancelled, !retired else { return }connection = .offline(HostError.unreachable.localizedDescription)try? await Task.sleep(for: .seconds(backoff))backoff = min(backoff * 2, 20)continue}+ guard !Task.isCancelled, !retired else { return }self.client = client- if persistsPairing { SharedStore.preferredURL = client.baseURL.absoluteString }+ if persistsPairing { storage.preferredURL = client.baseURL.absoluteString }do {if hello == nil || hello?.hostId != hostId {let h = try await client.hello()+ guard !Task.isCancelled, !retired else { return }hello = hif let device = h.device, self.pairing?.device != device, let token = self.pairing?.token {updateComputer(token) { $0.device = device }@@ -217,6 +244,7 @@ public final class BotStore {}}for try await event in client.events(since: rev, client: clientKind) {+ guard !Task.isCancelled, !retired else { return }connection = .onlinebackoff = 1apply(event)@@ -310,7 +338,7 @@ public final class BotStore {// MARK: actionsprivate func require() throws -> HostClient {- guard let client, connection == .online else { throw HostError.unreachable }+ guard !retired, let client, connection == .online else { throw HostError.unreachable }return client}@@ -451,6 +479,12 @@ public final class BotStore {await refreshPlugins()}+ /// Re-detects agents on the computer (after an install or sign-in).+ public func refreshBackends() async {+ guard let client, let backends = try? await client.refreshBackends() else { return }+ hello?.backends = backends+ }+public func listDirs(_ path: String?) async throws -> DirListing {try await require().listDirs(path)}@@ -492,13 +526,14 @@ public final class BotStore {private static let appBuild = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"private var cacheStamp: String?- private static var cacheURL: URL {- URL.cachesDirectory.appending(path: "codync-mirror-\(Bundle.main.bundleIdentifier ?? "app").json")+ private var cacheURL: URL {+ let computer = SharedStore.Context.digest(pairing?.token ?? "unpaired")+ return URL.cachesDirectory.appending(path: "codync-mirror-\(Bundle.main.bundleIdentifier ?? "app")-\(storage.id)-\(computer).json")}private func loadCache() {guard pairing != nil,- let data = try? Data(contentsOf: Self.cacheURL),+ let data = try? Data(contentsOf: cacheURL),let cache = try? JSONDecoder().decode(Cache.self, from: data),cache.stamp?.hasPrefix(Self.appBuild + "/") == true else { return }cacheStamp = cache.stamp@@ -509,6 +544,7 @@ public final class BotStore {}private func scheduleSave() {+ guard !retired else { return }saveTask?.cancel()saveTask = Task {try? await Task.sleep(for: .seconds(2))@@ -517,11 +553,12 @@ public final class BotStore {}public func saveCache() {+ guard !retired else { return }// Keep the newest 200 entries per bot; older ones page in from the host.let kept = entries.values.flatMap { $0.filter { !$0.id.hasPrefix("local-") }.suffix(200) }let cache = Cache(stamp: "\(Self.appBuild)/\(hello?.version ?? "")", hostId: hostId, rev: rev, bots: Array(bots.values), entries: kept)if let data = try? JSONEncoder().encode(cache) {- try? data.write(to: Self.cacheURL, options: .atomic)+ try? data.write(to: cacheURL, options: .atomic)}}}diff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swiftindex 2bb5d4ea..9dfd3b25 100644--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -11,11 +11,11 @@ struct UserBubble: View {var body: some View {VStack(alignment: .trailing, spacing: 4) {Text(entry.data.text ?? "")- .font(.body)+ .font(InterfaceMetrics.body).foregroundStyle(Palette.text).textSelection(.enabled)- .padding(.horizontal, 16)- .padding(.vertical, 10)+ .padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16))+ .padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 10)).background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 22, style: .continuous)).contextMenu {Button("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }@@ -58,8 +58,8 @@ struct AgentBubble: View {var body: some View {VStack(alignment: .leading, spacing: 4) {MarkdownText(entry.data.text ?? "")- .padding(.horizontal, 16)- .padding(.vertical, 10)+ .padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16))+ .padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 10)).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22, style: .continuous)).contextMenu {Button("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }@@ -140,7 +140,7 @@ struct WorkingIndicator: View {}Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Palette.tertiary)}- .padding(.horizontal, 16)+ .padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16)).padding(.vertical, 12).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22, style: .continuous))}diff --git a/kit/Sources/CodyncUI/Thread/MarkdownText.swift b/kit/Sources/CodyncUI/Thread/MarkdownText.swiftindex 62e4e0e4..8b1afd62 100644--- a/kit/Sources/CodyncUI/Thread/MarkdownText.swift+++ b/kit/Sources/CodyncUI/Thread/MarkdownText.swift@@ -30,7 +30,7 @@ public struct MarkdownText: View {@ViewBuilder private func view(for block: Block) -> some View {switch block {case let .paragraph(t):- Text(Self.inline(t)).font(.body).foregroundStyle(Palette.text)+ Text(Self.inline(t)).font(InterfaceMetrics.body).foregroundStyle(Palette.text)case let .heading(t, level):Text(Self.inline(t)).font(level == 1 ? .title3.bold() : level == 2 ? .headline : .subheadline.bold())@@ -40,10 +40,10 @@ public struct MarkdownText: View {Text(marker).foregroundStyle(Palette.secondary).monospacedDigit()Text(Self.inline(t)).foregroundStyle(Palette.text)}- .font(.body)+ .font(InterfaceMetrics.body)case let .quote(t):Text(Self.inline(t))- .font(.body)+ .font(InterfaceMetrics.body).foregroundStyle(Palette.secondary).padding(.leading, 10).overlay(alignment: .leading) { Rectangle().fill(Palette.border).frame(width: 3) }diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swiftindex e2be90e0..ecfe7b17 100644--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -12,6 +12,7 @@ public struct ThreadView: View {@State private var draft = ""@State private var showTrace = false@State private var editing: EditorRequest?+ @State private var templateRequest: EditorRequest?@State private var confirmNewSession = false@State private var confirmDelete: Bot?/// Desktop: the bot's settings as an inspector beside the chat.@@ -30,7 +31,7 @@ public struct ThreadView: View {conversation.frame(maxWidth: .infinity)if showSettings && geometry.size.width >= 680 {Rectangle().fill(Palette.border).frame(width: 1)- detailsPanel.frame(width: 320)+ detailsPanel.frame(width: 292)}}.onGeometryChange(for: CGFloat.self) {@@ -128,7 +129,11 @@ public struct ThreadView: View {HStack {headerSpacer(minLength: 8)- menu+ if let bot {+ TemplateButton {+ templateRequest = EditorRequest(BotDraft(bot))+ }+ }if !showSettings || availableWidth < 680 {Button("Conversation details", systemImage: "chevron.right.2") { toggleDetails() }.labelStyle(.iconOnly)@@ -158,6 +163,9 @@ public struct ThreadView: View {.presentationDetents([.medium, .large]).presentationDragIndicator(.visible)}+ .sheet(item: $templateRequest) { request in+ BotTemplateView(draft: request.draft)+ }.sheet(item: $editing) { request inNavigationStack { BotEditorView(draft: request.draft) }}@@ -344,11 +352,7 @@ public struct ThreadView: View {Divider()Button("Delete bot", systemImage: "trash", role: .destructive) { confirmDelete = bot }} label: {- #if os(macOS)- Image(systemName: "square.and.arrow.up")- #elseImage(systemName: "ellipsis.circle")- #endif}}@@ -367,9 +371,10 @@ public struct ThreadView: View {return HStack(alignment: .bottom, spacing: 8) {TextField(working ? "Queue a message for \(bot?.name ?? "it")" : "Message \(bot?.name ?? "")", text: $draft, axis: .vertical).lineLimit(1...8)+ .font(InterfaceMetrics.body).textFieldStyle(.plain).focused($composerFocused)- .padding(.vertical, 10)+ .padding(.vertical, InterfaceMetrics.value(mac: 7, mobile: 10)).sendOnReturn(submit)if working && draft.isEmpty {Button {@@ -377,7 +382,7 @@ public struct ThreadView: View {} label: {Image(systemName: "stop.fill").font(.system(size: 12, weight: .bold))- .frame(width: 34, height: 34)+ .frame(width: InterfaceMetrics.value(mac: 28, mobile: 34), height: InterfaceMetrics.value(mac: 28, mobile: 34)).background(Palette.accentFill, in: Circle()).foregroundStyle(Palette.onAccent)}@@ -388,7 +393,7 @@ public struct ThreadView: View {Button(action: submit) {Image(systemName: "arrow.up").font(.system(size: 14, weight: .bold))- .frame(width: 34, height: 34)+ .frame(width: InterfaceMetrics.value(mac: 28, mobile: 34), height: InterfaceMetrics.value(mac: 28, mobile: 34)).background(canSend ? Palette.accentFill : Palette.accentDim, in: Circle()).foregroundStyle(canSend ? Palette.onAccent : Palette.tertiary)}@@ -398,9 +403,9 @@ public struct ThreadView: View {.help("Send")}}- .padding(.leading, 18)+ .padding(.leading, InterfaceMetrics.value(mac: 14, mobile: 18)).padding(.trailing, 6)- .padding(.vertical, 6)+ .padding(.vertical, InterfaceMetrics.value(mac: 4, mobile: 6)).composerSurface(in: RoundedRectangle(cornerRadius: 24, style: .continuous)).padding(.horizontal, 16).padding(.top, 6)@@ -471,3 +476,25 @@ private struct IntroCard: View {.padding(.horizontal, 24)}}++/// The share glyph creates a settings template; conversation actions live in the sidebar.+private struct TemplateButton: View {+ let action: () -> Void+ @State private var hovered = false++ var body: some View {+ Button(action: action) {+ Image(systemName: "square.and.arrow.up")+ .font(.system(size: 15))+ .foregroundStyle(hovered ? Palette.text : Palette.secondary)+ .frame(width: 30, height: 30)+ .background(hovered ? Palette.text.opacity(0.08) : .clear,+ in: RoundedRectangle(cornerRadius: 8))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .onHover { hovered = $0 }+ .accessibilityLabel("Create template")+ .help("Create template")+ }+}diff --git a/kit/Tests/CodyncKitTests/AccountStorageTests.swift b/kit/Tests/CodyncKitTests/AccountStorageTests.swiftnew file mode 100644index 00000000..ba31b045--- /dev/null+++ b/kit/Tests/CodyncKitTests/AccountStorageTests.swift@@ -0,0 +1,53 @@+import Foundation+import Testing+@testable import CodyncKit++@Test func accountPairingsStayIsolatedIncludingLateWrites() throws {+ let suite = "CodyncAccountTests.\(UUID().uuidString)"+ let defaults = try #require(UserDefaults(suiteName: suite))+ defer { defaults.removePersistentDomain(forName: suite) }+ let alice = SharedStore.Context(accountID: "user_alice", defaults: defaults)+ let bob = SharedStore.Context(accountID: "user_bob", defaults: defaults)+ let a = Pairing(name: "Same name", token: "alice-token", urls: ["https://alice.invalid"])+ let b = Pairing(name: "Same name", token: "bob-token", urls: ["https://bob.invalid"])+ alice.pairing = a+ alice.computers = [a]+ bob.pairing = b+ bob.computers = [b]++ // A retained store finishes work after the UI has selected Bob.+ alice.preferredURL = a.urls.first+ alice.usage = Usage()+ #expect(bob.pairing == b)+ #expect(bob.computers == [b])+ #expect(bob.preferredURL == nil)+ #expect(bob.usage == nil)+ #expect(alice.orderedPairing == a)+ #expect(alice.id != bob.id)+ #expect(SharedStore.Context(accountID: "user_alice", defaults: defaults).pairing == a)++ let oldWidget = alice.botURL("shared-bot-id")+ #expect(alice.acceptsBotURL(oldWidget))+ #expect(!bob.acceptsBotURL(oldWidget))+ #expect(!bob.acceptsBotURL(URL(string: "codync://bot/shared-bot-id")!))+ alice.pairing = b+ #expect(!alice.acceptsBotURL(oldWidget))+}++@Test func signingInDoesNotClaimLegacyLocalPairings() throws {+ let suite = "CodyncAccountTests.\(UUID().uuidString)"+ let defaults = try #require(UserDefaults(suiteName: suite))+ defer { defaults.removePersistentDomain(forName: suite) }+ let old = Pairing(name: "Legacy Mac", token: "local-token", urls: ["http://127.0.0.1:19222"])+ defaults.set(try JSONEncoder().encode(old), forKey: "pairing")+ let local = SharedStore.Context(accountID: nil, defaults: defaults)+ let signedIn = SharedStore.Context(accountID: "user_new", defaults: defaults)++ #expect(local.pairing == old)+ #expect(local.computers == [old])+ #expect(signedIn.pairing == nil)+ #expect(signedIn.computers.isEmpty)+ signedIn.pairing = old+ signedIn.pairing = nil+ #expect(local.pairing == old)+}diff --git a/project.yml b/project.ymlindex e02f8434..38c2545c 100644--- a/project.yml+++ b/project.yml@@ -30,6 +30,7 @@ targets:type: applicationplatform: macOSsources:+ - path: apps/shared- path: apps/macosexcludes:- LaunchAgents@@ -121,10 +122,13 @@ targets:type: applicationplatform: iOSsources:+ - path: apps/shared- path: apps/iosexcludes:- Widgetsdependencies:+ - package: Clerk+ product: ClerkKit- package: CodyncKitproduct: CodyncKit- package: CodyncKit