SPB Git

Repository Public

Summary.swift 8.6 KB 217 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/Summary.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/// What widgets and the menu bar read: counters only — never titles, paths or terminal content.94public struct CachedSummary: Codable, Hashable, Sendable {95    public var agent: AgentID96    public var productName: String97    /// False after sign-out: widgets show "Sign in" instead of stale numbers.98    public var signedIn: Bool99    public var summary: NativeSummary?100    public var savedAt: Date101102    public init(agent: AgentID, productName: String, signedIn: Bool, summary: NativeSummary?, savedAt: Date = Date()) {103        self.agent = agent104        self.productName = productName105        self.signedIn = signedIn106        self.summary = summary107        self.savedAt = savedAt108    }109110    /// Older than this, numbers should be shown as stale.111    public func isStale(after seconds: TimeInterval = 15 * 60, now: Date = Date()) -> Bool {112        now.timeIntervalSince(savedAt) > seconds113    }114}115116/// A small JSON file in the App Group container, written by the app and read by its widget117/// extension. Widgets never hold a credential and never talk to the server.118///119///     // app:    SharedSummaryCache(appGroup: "group.ai.spboucher.clauderemote", agent: .claude)120///     // widget: SharedSummaryCache(appGroup: …, agent: .claude)?.read()121public struct SharedSummaryCache: Sendable {122    public let fileURL: URL123124    /// - Returns: nil when the App Group is not available to this process (missing entitlement).125    public init?(appGroup: String, agent: AgentID) {126        guard let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else { return nil }127        self.init(directory: container.appending(path: "Library/Caches", directoryHint: .isDirectory), agent: agent)128    }129130    /// Explicit directory (tests, non-sandboxed tools).131    public init(directory: URL, agent: AgentID) {132        fileURL = directory.appending(path: "cr-summary-\(agent.rawValue).json")133    }134135    public func read() -> CachedSummary? {136        guard let data = try? Data(contentsOf: fileURL) else { return nil }137        return try? CRJSON.decode(CachedSummary.self, from: data)138    }139140    public func write(_ value: CachedSummary) throws {141        try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)142        var options: Data.WritingOptions = [.atomic]143        #if os(iOS)144        options.insert(.completeFileProtectionUntilFirstUserAuthentication)145        #endif146        try CRJSON.encode(value).write(to: fileURL, options: options)147    }148149    public func clear() {150        try? FileManager.default.removeItem(at: fileURL)151    }152}153154/// `GET /native/summary`, refreshed when the app becomes active and — coalesced — whenever a155/// server event changes a counter. No timer.156@MainActor157@Observable158public final class SummaryStore {159    public private(set) var summary: NativeSummary?160    public private(set) var load: LoadState = .idle161    /// Called after each successful refresh (e.g. `WidgetCenter.shared.reloadAllTimelines()`).162    @ObservationIgnored public var onChange: (@MainActor (NativeSummary) -> Void)?163    @ObservationIgnored private let client: APIClient164    @ObservationIgnored private let profile: AgentProfile165    @ObservationIgnored private let cache: SharedSummaryCache?166    @ObservationIgnored private let coalesce: TimeInterval167    @ObservationIgnored private var pending: Task<Void, Never>?168169    public init(client: APIClient, profile: AgentProfile, cache: SharedSummaryCache?, coalesce: TimeInterval = 1.5) {170        self.client = client171        self.profile = profile172        self.cache = cache173        self.coalesce = coalesce174        summary = cache?.read().flatMap { $0.signedIn ? $0.summary : nil }175    }176177    public func refresh() async {178        if !load.hasLoaded { load = .loading }179        do {180            let fresh = try await client.summary()181            summary = fresh182            load = .loaded(at: Date())183            try? cache?.write(CachedSummary(agent: profile.id, productName: fresh.productName, signedIn: true, summary: fresh))184            onChange?(fresh)185        } catch {186            load = .failed(APIError.wrap(error))187        }188    }189190    public func apply(_ event: ServerEvent) {191        switch event {192        case .sessionUpdated, .sessionRemoved, .taskUpdated, .notification: scheduleRefresh()193        default: break194        }195    }196197    private func scheduleRefresh() {198        guard pending == nil else { return }199        let delay = coalesce200        pending = Task { [weak self] in201            try? await Task.sleep(for: .milliseconds(Int(delay * 1000)))202            guard let self, !Task.isCancelled else { return }203            self.pending = nil204            await self.refresh()205        }206    }207208    /// Sign-out: forget the numbers and tell widgets.209    public func reset() {210        pending?.cancel()211        pending = nil212        summary = nil213        load = .idle214        try? cache?.write(CachedSummary(agent: profile.id, productName: profile.productName, signedIn: false, summary: nil))215    }216}217
Files main
Menu

Theme