SPB Git

Repository Public

DataStores.swift 23.0 KB 578 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteCore/DataStores.swift10// Module           : ClaudeRemoteCore11// Repository       : https://git.spboucher.ai/claude-remote-apple12// Project Website  : https://claude.spboucher.ai13// Created          : 2026-11-2914// Last Modified    : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteAPI89import ClaudeRemoteModels90import Foundation91import Observation9293/// A text file open in an editor, with optimistic-concurrency state.94public struct OpenDocument: Hashable, Sendable, Identifiable {95    public var path: String96    /// Text as edited locally.97    public var content: String98    /// Hash of the version loaded from / last saved to the server.99    public var baseSha256: String?100    public var savedContent: String101    public var modifiedAt: Date?102    /// Set when a save hit a 409: hash now on disk (nil inside = the file was deleted).103    public var conflict: Conflict?104105    public struct Conflict: Hashable, Sendable {106        public var currentSha256: String?107    }108109    public var id: String { path }110    public var isDirty: Bool { content != savedContent }111    public var isNew: Bool { baseSha256 == nil }112}113114public enum SaveOutcome: Hashable, Sendable {115    case saved116    /// The file changed on the server since it was loaded. Offer: reload (`reloadDocument`),117    /// overwrite (`save(path:overwriteConflict: true)`), or keep editing.118    case conflict(currentSha256: String?)119}120121/// Files of ONE project: directory listings, open documents, fs operations, transfers, search, git.122@MainActor123@Observable124public final class FilesStore {125    public nonisolated let projectId: String126    /// Listings by directory path ("" = project root).127    public private(set) var listings: [String: [FileEntry]] = [:]128    public private(set) var loadingPaths: Set<String> = []129    public private(set) var errors: [String: APIError] = [:]130    public private(set) var documents: [String: OpenDocument] = [:]131    public private(set) var gitStatus: GitStatus?132    /// Running transfers by path.133    public private(set) var transfers: [String: TransferProgress] = [:]134    @ObservationIgnored private let client: APIClient135136    public init(client: APIClient, projectId: String) {137        self.client = client138        self.projectId = projectId139    }140141    public func entries(at path: String = "") -> [FileEntry]? { listings[path] }142143    @discardableResult144    public func list(_ path: String = "") async -> [FileEntry] {145        loadingPaths.insert(path)146        defer { loadingPaths.remove(path) }147        do {148            let entries = try await client.listFiles(projectId: projectId, path: path)149            listings[path] = entries150            errors[path] = nil151            return entries152        } catch {153            errors[path] = APIError.wrap(error)154            return listings[path] ?? []155        }156    }157158    /// Opens a text file (≤ 2 MiB). Throws `.binary` / `.payloadTooLarge` for others: offer a download.159    @discardableResult160    public func open(_ path: String) async throws -> OpenDocument {161        if let existing = documents[path], existing.isDirty { return existing }162        return try await reloadDocument(path)163    }164165    /// Discards local edits and loads the server version.166    @discardableResult167    public func reloadDocument(_ path: String) async throws -> OpenDocument {168        let file = try await client.readFile(projectId: projectId, path: path)169        let doc = OpenDocument(path: path, content: file.content, baseSha256: file.sha256, savedContent: file.content, modifiedAt: file.modifiedAt)170        documents[path] = doc171        return doc172    }173174    /// Starts a new, unsaved document.175    public func newDocument(_ path: String, content: String = "") {176        documents[path] = OpenDocument(path: path, content: content, baseSha256: nil, savedContent: "", modifiedAt: nil)177    }178179    public func edit(_ path: String, content: String) { documents[path]?.content = content }180    public func close(_ path: String) { documents[path] = nil }181182    /// Saves with `baseSha256`. A 409 is returned as `.conflict` (nothing is overwritten) unless183    /// `overwriteConflict` is true, in which case the hash reported by the conflict is used as base.184    public func save(_ path: String, overwriteConflict: Bool = false) async throws -> SaveOutcome {185        guard let doc = documents[path] else { throw APIError.client("not_open", "This file is not open.") }186        var base = doc.baseSha256187        var create = doc.isNew188        if overwriteConflict, let conflict = doc.conflict {189            base = conflict.currentSha256190            create = conflict.currentSha256 == nil191        }192        do {193            let saved = try await client.writeFile(projectId: projectId, WriteFile(path: path, content: doc.content, baseSha256: base, create: create ? true : nil))194            documents[path]?.baseSha256 = saved.sha256195            documents[path]?.savedContent = doc.content196            documents[path]?.modifiedAt = saved.modifiedAt197            documents[path]?.conflict = nil198            return .saved199        } catch let error as APIError where error.kind == .conflict {200            documents[path]?.conflict = .init(currentSha256: error.conflictSha256)201            return .conflict(currentSha256: error.conflictSha256)202        }203    }204205    public func makeDirectory(_ path: String) async throws {206        try await client.fsOp(projectId: projectId, .mkdir(path: path))207        await list(Self.parent(of: path))208    }209210    public func rename(from: String, to: String) async throws {211        try await client.fsOp(projectId: projectId, .rename(from: from, to: to))212        if var doc = documents.removeValue(forKey: from) {213            doc.path = to214            documents[to] = doc215        }216        await list(Self.parent(of: from))217        if Self.parent(of: to) != Self.parent(of: from) { await list(Self.parent(of: to)) }218    }219220    /// Destructive: gate with `AppSession.reauthenticate(reason:)`.221    public func delete(_ path: String) async throws {222        try await client.fsOp(projectId: projectId, .delete(path: path))223        documents[path] = nil224        listings[path] = nil225        await list(Self.parent(of: path))226    }227228    /// Uploads a local file into `directory`. Throws `.exists` unless `overwrite`.229    public func upload(_ fileURL: URL, toDirectory directory: String, overwrite: Bool = false) async throws {230        let path = directory.isEmpty ? fileURL.lastPathComponent : "\(directory)/\(fileURL.lastPathComponent)"231        transfers[path] = TransferProgress(completedBytes: 0, totalBytes: nil)232        defer { transfers[path] = nil }233        try await client.upload(projectId: projectId, path: path, from: fileURL, overwrite: overwrite) { [weak self] progress in234            Task { @MainActor in if self?.transfers[path] != nil { self?.transfers[path] = progress } }235        }236        await list(directory)237    }238239    public func download(_ path: String, to destination: URL) async throws {240        transfers[path] = TransferProgress(completedBytes: 0, totalBytes: nil)241        defer { transfers[path] = nil }242        try await client.download(projectId: projectId, path: path, to: destination) { [weak self] progress in243            Task { @MainActor in if self?.transfers[path] != nil { self?.transfers[path] = progress } }244        }245    }246247    public func search(_ query: String, mode: SearchMode = .name, in path: String = "", limit: Int = 100) async throws -> [SearchHit] {248        try await client.searchFiles(projectId: projectId, query: query, mode: mode, path: path, limit: limit)249    }250251    @discardableResult252    public func refreshGitStatus() async throws -> GitStatus {253        let status = try await client.gitStatus(projectId: projectId)254        gitStatus = status255        return status256    }257258    public func diff(path: String = "", staged: Bool = false) async throws -> GitDiff {259        try await client.gitDiff(projectId: projectId, path: path, staged: staged)260    }261262    public static func parent(of path: String) -> String {263        guard let slash = path.lastIndex(of: "/") else { return "" }264        return String(path[..<slash])265    }266}267268/// Cluster telemetry. The server has no cluster events, so this store refreshes on demand and —269/// only while a cluster view is visible — on a timer (`startAutoRefresh` / `stopAutoRefresh`).270@MainActor271@Observable272public final class ClusterStore {273    public private(set) var overview: ClusterOverview?274    public private(set) var apps: ClusterApps?275    public private(set) var incidents: [ClusterIncident] = []276    public private(set) var trend: ClusterTrend?277    public private(set) var models: [LocalModel] = []278    public private(set) var load: LoadState = .idle279    public private(set) var nodeDetails: [String: ClusterNodeDetail] = [:]280    public private(set) var modelTests: [String: LocalModelTest] = [:]281    public private(set) var testingModels: Set<String> = []282    @ObservationIgnored private let client: APIClient283    @ObservationIgnored private var auto: Task<Void, Never>?284285    public init(client: APIClient) { self.client = client }286287    public func node(id: String) -> ClusterNode? { overview?.nodes.first { $0.id == id } }288289    /// Overview + apps + incidents + trend + models, in parallel. Partial failures keep old data.290    public func refresh() async {291        if !load.hasLoaded { load = .loading }292        async let o = client.clusterOverview()293        async let a = client.clusterApps()294        async let i = client.clusterIncidents()295        async let t = client.clusterTrend()296        async let m = client.localModels()297        do {298            overview = try await o299            load = .loaded(at: Date())300        } catch {301            load = .failed(APIError.wrap(error))302        }303        if let v = try? await a { apps = v }304        if let v = try? await i { incidents = v }305        if let v = try? await t { trend = v }306        if let v = try? await m { models = v }307    }308309    @discardableResult310    public func loadNode(id: String) async throws -> ClusterNodeDetail {311        let detail = try await client.clusterNode(id: id)312        nodeDetails[id] = detail313        return detail314    }315316    public func metrics(node: String? = nil, minutes: Int = 60) async throws -> ClusterMetrics {317        try await client.clusterMetrics(node: node, minutes: minutes)318    }319320    /// Runs a real completion on the model (server side) and records the result.321    @discardableResult322    public func testModel(id: String) async throws -> LocalModelTest {323        testingModels.insert(id)324        defer { testingModels.remove(id) }325        let result = try await client.testLocalModel(id: id)326        modelTests[id] = result327        if let fresh = try? await client.localModels() { models = fresh }328        return result329    }330331    public func startAutoRefresh(every seconds: TimeInterval = 30) {332        guard auto == nil else { return }333        auto = Task { [weak self] in334            while !Task.isCancelled {335                await self?.refresh()336                try? await Task.sleep(for: .seconds(max(5, seconds)))337            }338        }339    }340341    public func stopAutoRefresh() {342        auto?.cancel()343        auto = nil344    }345346    public func reset() {347        stopAutoRefresh()348        overview = nil; apps = nil; incidents = []; trend = nil; models = []; nodeDetails = [:]; modelTests = [:]; load = .idle349    }350}351352@MainActor353@Observable354public final class SkillsMCPStore {355    public private(set) var skills: [SkillInfo] = []356    public private(set) var servers: [McpServerInfo] = []357    public private(set) var skillsLoad: LoadState = .idle358    public private(set) var serversLoad: LoadState = .idle359    /// True while live statuses are being checked (can take up to 45 s).360    public private(set) var checkingLiveStatus = false361    /// Project whose `.claude/` items are included (nil = user scope only).362    public var projectId: String?363    @ObservationIgnored private let client: APIClient364365    public init(client: APIClient) { self.client = client }366367    public func refreshSkills() async {368        if !skillsLoad.hasLoaded { skillsLoad = .loading }369        do {370            skills = try await client.skills(projectId: projectId)371            skillsLoad = .loaded(at: Date())372        } catch {373            skillsLoad = .failed(APIError.wrap(error))374        }375    }376377    public func setEnabled(_ skill: SkillInfo, _ enabled: Bool) async throws {378        let scope: SkillScope = skill.source == .project ? .project : .user379        try await client.skillOp(enabled ? .enable(name: skill.name, kind: skill.kind, scope: scope, projectId: scope == .project ? projectId : nil)380                                         : .disable(name: skill.name, kind: skill.kind, scope: scope, projectId: scope == .project ? projectId : nil))381        await refreshSkills()382    }383384    /// Destructive: gate with `AppSession.reauthenticate(reason:)`.385    public func remove(_ skill: SkillInfo) async throws {386        let scope: SkillScope = skill.source == .project ? .project : .user387        try await client.skillOp(.remove(name: skill.name, kind: skill.kind, scope: scope, projectId: scope == .project ? projectId : nil))388        await refreshSkills()389    }390391    public func install(fromProject projectId: String, path: String, replace: Bool = false) async throws {392        try await client.skillOp(.install(projectId: projectId, path: path, replace: replace))393        await refreshSkills()394    }395396    public func searchRegistry(_ query: String) async throws -> SkillRegistrySearch { try await client.searchSkillRegistry(query: query) }397398    /// Configuration first (immediate), then — when `live` — real statuses (slow).399    public func refreshServers(live: Bool = false, force: Bool = false) async {400        if !serversLoad.hasLoaded { serversLoad = .loading }401        do {402            if servers.isEmpty || !live { servers = try await client.mcpServers(projectId: projectId) }403            serversLoad = .loaded(at: Date())404            if live {405                checkingLiveStatus = true406                defer { checkingLiveStatus = false }407                servers = try await client.mcpServers(projectId: projectId, live: true, refresh: force)408                serversLoad = .loaded(at: Date())409            }410        } catch {411            serversLoad = .failed(APIError.wrap(error))412        }413    }414415    public func addServer(_ server: AddMcpServer) async throws {416        try await client.addMcpServer(server)417        await refreshServers()418    }419420    /// Destructive: gate with `AppSession.reauthenticate(reason:)`.421    public func removeServer(_ server: McpServerInfo) async throws {422        try await client.removeMcpServer(name: server.name, scope: server.scope, projectId: server.scope == .user ? nil : projectId)423        servers.removeAll { $0.id == server.id }424    }425426    @discardableResult427    public func testServer(_ server: McpServerInfo) async throws -> McpServerInfo {428        let result = try await client.testMcpServer(name: server.name, scope: server.scope, projectId: server.scope == .user ? nil : projectId)429        if let i = servers.firstIndex(where: { $0.id == server.id }) { servers[i] = result }430        return result431    }432433    public func reset() {434        skills = []; servers = []; skillsLoad = .idle; serversLoad = .idle435    }436}437438/// System status, audit trail and the account's devices.439@MainActor440@Observable441public final class SystemStore {442    public private(set) var status: SystemStatus?443    public private(set) var load: LoadState = .idle444    public private(set) var audit: [AuditEvent] = []445    public private(set) var auditHasMore = true446    public private(set) var devices: [Device] = []447    @ObservationIgnored private let client: APIClient448449    public init(client: APIClient) { self.client = client }450451    public func refresh() async {452        if !load.hasLoaded { load = .loading }453        do {454            status = try await client.systemStatus()455            load = .loaded(at: Date())456        } catch {457            load = .failed(APIError.wrap(error))458        }459    }460461    /// First page (`reset: true`) or the next one.462    public func loadAudit(reset: Bool = false, pageSize: Int = 100, action: String? = nil) async throws {463        let page = try await client.audit(limit: pageSize, before: reset ? nil : audit.last?.id, action: action)464        audit = reset ? page : audit + page465        auditHasMore = page.count == pageSize466    }467468    public func refreshDevices() async throws { devices = try await client.devices() }469470    /// Removes a passkey or revokes a session. Destructive: gate with `reauthenticate`. Revoking the471    /// current device ends this session (the app returns to sign-in through the usual path).472    public func revokeDevice(id: String) async throws {473        try await client.revokeDevice(id: id)474        devices.removeAll { $0.id == id }475    }476477    public func reset() {478        status = nil; load = .idle; audit = []; auditHasMore = true; devices = []479    }480}481482@MainActor483@Observable484public final class NotificationsStore {485    /// Newest first.486    public private(set) var notifications: [ServerNotification] = []487    public private(set) var load: LoadState = .idle488    public var unreadCount: Int { notifications.count(where: \.isUnread) }489    /// Called for each notification arriving live (use it to post a local notification).490    @ObservationIgnored public var onArrival: (@MainActor (ServerNotification) -> Void)?491    @ObservationIgnored private let client: APIClient492493    public init(client: APIClient) { self.client = client }494495    public func refresh(limit: Int = 50) async {496        if !load.hasLoaded { load = .loading }497        do {498            notifications = try await client.notifications(limit: limit)499            load = .loaded(at: Date())500        } catch {501            load = .failed(APIError.wrap(error))502        }503    }504505    public func markRead(ids: [String]) async throws {506        guard !ids.isEmpty else { return }507        try await client.markNotificationsRead(ids: ids)508        let now = Date()509        for i in notifications.indices where ids.contains(notifications[i].id) && notifications[i].readAt == nil {510            notifications[i].readAt = now511        }512    }513514    public func markAllRead() async throws {515        try await client.markAllNotificationsRead()516        let now = Date()517        for i in notifications.indices where notifications[i].readAt == nil { notifications[i].readAt = now }518    }519520    public func apply(_ event: ServerEvent) {521        guard case .notification(let n) = event else { return }522        let isNew = !notifications.contains { $0.id == n.id }523        notifications.upsert(n)524        notifications.sort { $0.createdAt > $1.createdAt }525        if isNew { onArrival?(n) }526    }527528    public func reset() {529        notifications = []530        load = .idle531    }532}533534/// User settings shared with the web application.535@MainActor536@Observable537public final class SettingsStore {538    /// Server values once loaded; defaults before.539    public private(set) var settings = UserSettings()540    public private(set) var load: LoadState = .idle541    public private(set) var isSaving = false542    @ObservationIgnored private let client: APIClient543544    public init(client: APIClient) { self.client = client }545546    public func refresh() async {547        if !load.hasLoaded { load = .loading }548        do {549            settings = try await client.settings()550            load = .loaded(at: Date())551        } catch {552            load = .failed(APIError.wrap(error))553        }554    }555556    /// Applies a change optimistically and saves the whole object; rolls back on failure.557    public func update(_ change: (inout UserSettings) -> Void) async throws {558        let previous = settings559        var next = settings560        change(&next)561        guard next != previous else { return }562        settings = next563        isSaving = true564        defer { isSaving = false }565        do {566            settings = try await client.saveSettings(next)567        } catch {568            settings = previous569            throw error570        }571    }572573    public func reset() {574        settings = UserSettings()575        load = .idle576    }577}578
Files main
Menu

Theme