SPB Git

Repository Public

WorkStores.swift 20.5 KB 514 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/WorkStores.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/// Terminal sessions, kept live by `session.updated` / `session.removed` events.94@MainActor95@Observable96public final class SessionsStore {97    /// Non-archived sessions: waiting first, then live, then by last activity.98    public private(set) var sessions: [TerminalSession] = []99    /// Archived sessions, loaded on demand by `refreshArchived()`.100    public private(set) var archived: [TerminalSession] = []101    public private(set) var load: LoadState = .idle102    @ObservationIgnored private let client: APIClient103104    public init(client: APIClient) { self.client = client }105106    public var live: [TerminalSession] { sessions.filter(\.state.isLive) }107    public var waiting: [TerminalSession] { sessions.filter { $0.state == .waitingForInput } }108    public var recoverable: [TerminalSession] { sessions.filter { $0.state == .recoverable } }109    public func session(id: String) -> TerminalSession? { sessions.first { $0.id == id } ?? archived.first { $0.id == id } }110    public func sessions(inProject projectId: String?) -> [TerminalSession] { sessions.filter { $0.projectId == projectId } }111112    public func refresh() async {113        if !load.hasLoaded { load = .loading }114        do {115            sessions = Self.sorted(try await client.sessions())116            load = .loaded(at: Date())117        } catch {118            load = .failed(APIError.wrap(error))119        }120    }121122    public func refreshArchived() async throws { archived = Self.sorted(try await client.sessions(archived: true)) }123124    /// Creates and starts a session (agent CLI or shell). Never called by reconnect logic.125    @discardableResult126    public func create(_ request: CreateSession) async throws -> TerminalSession {127        let session = try await client.createSession(request)128        merge(session)129        return session130    }131132    @discardableResult133    public func rename(id: String, title: String) async throws -> TerminalSession { merge(try await client.updateSession(id: id, UpdateSession(title: title))) }134    @discardableResult135    public func setPinned(id: String, _ pinned: Bool) async throws -> TerminalSession { merge(try await client.updateSession(id: id, UpdateSession(pinned: pinned))) }136    /// Only a session that is not live can be archived.137    @discardableResult138    public func setArchived(id: String, _ archived: Bool) async throws -> TerminalSession { merge(try await client.updateSession(id: id, UpdateSession(archived: archived))) }139    /// Stops the process. Destructive: gate with `AppSession.reauthenticate(reason:)`.140    @discardableResult141    public func terminate(id: String) async throws -> TerminalSession { merge(try await client.terminateSession(id: id)) }142    /// Re-syncs the state with the runtime (no new process).143    @discardableResult144    public func resync(id: String) async throws -> TerminalSession { merge(try await client.reconnectSession(id: id)) }145    /// Restarts a RECOVERABLE session: a NEW process, resuming the conversation when known.146    @discardableResult147    public func restart(id: String) async throws -> TerminalSession { merge(try await client.reconnectSession(id: id, restart: true)) }148    /// Last screen lines; only on explicit user request (never cached, never sent to widgets).149    public func snapshot(id: String) async throws -> String { try await client.sessionSnapshot(id: id).text }150    public func conversations(projectId: String) async throws -> [AgentConversation] { try await client.conversations(projectId: projectId) }151152    public func apply(_ event: ServerEvent) {153        switch event {154        case .sessionUpdated(let session): merge(session)155        case .sessionRemoved(let id):156            sessions.removeAll { $0.id == id }157            archived.removeAll { $0.id == id }158        default: break159        }160    }161162    @discardableResult163    private func merge(_ session: TerminalSession) -> TerminalSession {164        if session.archived {165            sessions.removeAll { $0.id == session.id }166            archived.upsert(session)167            archived = Self.sorted(archived)168        } else {169            archived.removeAll { $0.id == session.id }170            sessions.upsert(session)171            sessions = Self.sorted(sessions)172        }173        return session174    }175176    public func reset() {177        sessions = []178        archived = []179        load = .idle180    }181182    static func rank(_ s: TerminalSession) -> Int {183        if s.state == .waitingForInput { return 0 }184        if s.pinned { return 1 }185        if s.state.isLive { return 2 }186        if s.state == .recoverable { return 3 }187        return 4188    }189190    static func sorted(_ list: [TerminalSession]) -> [TerminalSession] {191        list.sorted { a, b in192            let (ra, rb) = (rank(a), rank(b))193            if ra != rb { return ra < rb }194            let (da, db) = (a.lastActivityAt ?? a.createdAt, b.lastActivityAt ?? b.createdAt)195            return da != db ? da > db : a.id < b.id196        }197    }198}199200/// Recent and favourite projects of this device (not secret: `UserDefaults`).201public struct ProjectShortcuts: @unchecked Sendable { // UserDefaults is thread-safe202    private let defaults: UserDefaults203    private let scope: String204    public static let maxRecents = 12205206    public init(defaults: UserDefaults = .standard, scope: String) {207        self.defaults = defaults208        self.scope = scope209    }210211    public var recents: [String] { defaults.stringArray(forKey: "cr.projects.recent.\(scope)") ?? [] }212    public var favourites: [String] { defaults.stringArray(forKey: "cr.projects.favourite.\(scope)") ?? [] }213214    public func noteOpened(_ id: String) {215        var list = recents.filter { $0 != id }216        list.insert(id, at: 0)217        defaults.set(Array(list.prefix(Self.maxRecents)), forKey: "cr.projects.recent.\(scope)")218    }219220    public func setFavourite(_ id: String, _ on: Bool) {221        var list = favourites.filter { $0 != id }222        if on { list.append(id) }223        defaults.set(list, forKey: "cr.projects.favourite.\(scope)")224    }225226    public func forget(_ id: String) {227        defaults.set(recents.filter { $0 != id }, forKey: "cr.projects.recent.\(scope)")228        defaults.set(favourites.filter { $0 != id }, forKey: "cr.projects.favourite.\(scope)")229    }230231    public func clear() {232        defaults.removeObject(forKey: "cr.projects.recent.\(scope)")233        defaults.removeObject(forKey: "cr.projects.favourite.\(scope)")234    }235}236237@MainActor238@Observable239public final class ProjectsStore {240    /// Pinned first, then by last activity.241    public private(set) var projects: [Project] = []242    public private(set) var roots: [WorkspaceRoot] = []243    public private(set) var load: LoadState = .idle244    /// Ids, most recent first (this device).245    public private(set) var recentIDs: [String] = []246    public private(set) var favouriteIDs: [String] = []247    @ObservationIgnored private let client: APIClient248    @ObservationIgnored private let shortcuts: ProjectShortcuts249250    public init(client: APIClient, shortcuts: ProjectShortcuts) {251        self.client = client252        self.shortcuts = shortcuts253        recentIDs = shortcuts.recents254        favouriteIDs = shortcuts.favourites255    }256257    public func project(id: String) -> Project? { projects.first { $0.id == id } }258    public var recents: [Project] { recentIDs.compactMap(project(id:)) }259    public var favourites: [Project] { favouriteIDs.compactMap(project(id:)) }260    public func isFavourite(_ id: String) -> Bool { favouriteIDs.contains(id) }261262    public func refresh() async {263        if !load.hasLoaded { load = .loading }264        do {265            async let list = client.projects()266            async let rootList = client.workspaceRoots()267            projects = Self.sorted(try await list)268            roots = (try? await rootList) ?? roots269            load = .loaded(at: Date())270        } catch {271            load = .failed(APIError.wrap(error))272        }273    }274275    /// Registers a project (new directory, existing directory, or `git clone`).276    @discardableResult277    public func create(_ request: CreateProject) async throws -> Project { merge(try await client.createProject(request)) }278    @discardableResult279    public func update(id: String, _ change: UpdateProject) async throws -> Project { merge(try await client.updateProject(id: id, change)) }280    @discardableResult281    public func setPinned(id: String, _ pinned: Bool) async throws -> Project { try await update(id: id, UpdateProject(pinned: pinned)) }282    /// Unregisters the project; its files stay on the server.283    public func remove(id: String) async throws {284        try await client.deleteProject(id: id)285        projects.removeAll { $0.id == id }286        shortcuts.forget(id)287        recentIDs = shortcuts.recents288        favouriteIDs = shortcuts.favourites289    }290291    public func noteOpened(_ id: String) {292        shortcuts.noteOpened(id)293        recentIDs = shortcuts.recents294    }295296    public func setFavourite(_ id: String, _ on: Bool) {297        shortcuts.setFavourite(id, on)298        favouriteIDs = shortcuts.favourites299    }300301    /// A session changed: the project's `activeSessions` / `lastActivityAt` are stale. Coalesced refetch.302    public func apply(_ event: ServerEvent) {303        guard case .sessionUpdated(let s) = event, let pid = s.projectId, project(id: pid) != nil else { return }304        scheduleRefresh()305    }306307    @ObservationIgnored private var pendingRefresh: Task<Void, Never>?308    private func scheduleRefresh() {309        guard pendingRefresh == nil else { return }310        pendingRefresh = Task { [weak self] in311            try? await Task.sleep(for: .seconds(2))312            guard let self, !Task.isCancelled else { return }313            self.pendingRefresh = nil314            await self.refresh()315        }316    }317318    @discardableResult319    private func merge(_ project: Project) -> Project {320        projects.upsert(project)321        projects = Self.sorted(projects)322        return project323    }324325    public func reset() {326        pendingRefresh?.cancel()327        pendingRefresh = nil328        projects = []329        roots = []330        load = .idle331    }332333    static func sorted(_ list: [Project]) -> [Project] {334        list.sorted { a, b in335            if a.pinned != b.pinned { return a.pinned }336            let (da, db) = (a.lastActivityAt ?? a.createdAt, b.lastActivityAt ?? b.createdAt)337            return da != db ? da > db : a.name.localizedCaseInsensitiveCompare(b.name) == .orderedAscending338        }339    }340}341342/// Tasks, kept live by `task.updated` events.343@MainActor344@Observable345public final class TasksStore {346    /// Newest first.347    public private(set) var tasks: [AgentTask] = []348    public private(set) var load: LoadState = .idle349    @ObservationIgnored private let client: APIClient350    @ObservationIgnored private let sleeper: any Sleeper351352    public init(client: APIClient, sleeper: any Sleeper = SystemSleeper()) {353        self.client = client354        self.sleeper = sleeper355    }356357    public var active: [AgentTask] { tasks.filter(\.state.isActive) }358    public func task(id: String) -> AgentTask? { tasks.first { $0.id == id } }359360    public func refresh(limit: Int = 100) async {361        if !load.hasLoaded { load = .loading }362        do {363            tasks = try await client.tasks(limit: limit).sorted { $0.createdAt > $1.createdAt }364            load = .loaded(at: Date())365        } catch {366            load = .failed(APIError.wrap(error))367        }368    }369370    @discardableResult371    public func create(_ request: CreateTask) async throws -> AgentTask { merge(try await client.createTask(request)) }372    @discardableResult373    public func cancel(id: String) async throws -> AgentTask { merge(try await client.cancelTask(id: id)) }374    /// Returns the NEW task created by the retry.375    @discardableResult376    public func retry(id: String) async throws -> AgentTask { merge(try await client.retryTask(id: id)) }377    @discardableResult378    public func reload(id: String) async throws -> AgentTask { merge(try await client.task(id: id)) }379    public func downloadArtifact(taskId: String, artifactId: String, to destination: URL,380                                 progress: (@Sendable (TransferProgress) -> Void)? = nil) async throws {381        try await client.downloadArtifact(taskId: taskId, artifactId: artifactId, to: destination, progress: progress)382    }383384    /// A live follower of one task's log. Call `start()` when its view appears, `stop()` when it goes.385    public func logFollower(taskId: String, maxBytes: Int = 2 * 1024 * 1024) -> TaskLogFollower {386        TaskLogFollower(client: client, taskId: taskId, maxBytes: maxBytes, sleeper: sleeper)387    }388389    public func apply(_ event: ServerEvent) {390        if case .taskUpdated(let task) = event { merge(task) }391    }392393    @discardableResult394    private func merge(_ task: AgentTask) -> AgentTask {395        tasks.upsert(task)396        tasks.sort { $0.createdAt > $1.createdAt }397        return task398    }399400    public func reset() {401        tasks = []402        load = .idle403    }404}405406/// Follows a task log over WS `/tasks/:id/log/stream?offset=`, resuming from the last byte407/// received after a disconnection. Keeps at most `maxBytes` (the head is dropped, `truncatedBytes`408/// says how much); older parts can be paged with `APIClient.taskLog(id:offset:limit:)`.409@MainActor410@Observable411public final class TaskLogFollower {412    public enum Phase: Hashable, Sendable {413        case idle, connecting, streaming414        case reconnecting(attempt: Int)415        /// The server closed the stream: the task ended and the log is complete.416        case finished417        case failed(APIError)418    }419420    public private(set) var phase: Phase = .idle421    /// Bytes currently kept (tail of the log).422    public private(set) var data = Data()423    /// Next byte to request = total bytes received so far.424    public private(set) var offset: Int64 = 0425    /// Bytes dropped from the head to respect `maxBytes`.426    public private(set) var truncatedBytes: Int64 = 0427    public var text: String { String(decoding: data, as: UTF8.self) }428    public nonisolated let taskId: String429430    @ObservationIgnored private let client: APIClient431    @ObservationIgnored private let maxBytes: Int432    @ObservationIgnored private let sleeper: any Sleeper433    @ObservationIgnored private let policy: ReconnectPolicy434    @ObservationIgnored private var task: Task<Void, Never>?435    @ObservationIgnored private var socket: (any WebSocketConnection)?436437    init(client: APIClient, taskId: String, maxBytes: Int, sleeper: any Sleeper, policy: ReconnectPolicy = .standard) {438        self.client = client439        self.taskId = taskId440        self.maxBytes = max(4096, maxBytes)441        self.sleeper = sleeper442        self.policy = policy443    }444445    /// Starts following from `offset` (0 the first time). Idempotent while running.446    public func start() {447        guard task == nil, phase != .finished else { return }448        phase = .connecting449        task = Task { [weak self] in await self?.run() }450    }451452    public func stop() {453        task?.cancel()454        task = nil455        socket?.close(code: 1000, reason: nil)456        socket = nil457        if phase != .finished { phase = .idle }458    }459460    private func run() async {461        var attempt = 0462        while !Task.isCancelled {463            do {464                let socket = try await client.openTaskLogStream(taskId: taskId, offset: offset)465                if Task.isCancelled { socket.close(code: 1000, reason: nil); return }466                self.socket = socket467                phase = .streaming468                attempt = 0469                while true {470                    if case .data(let chunk) = try await socket.receive() { append(chunk) }471                }472            } catch let closed as WebSocketClosed {473                if Task.isCancelled { return }474                socket = nil475                // 1000 / 1005 = the server drained the log of a finished task.476                if closed.code == 1000 || closed.code == 1005 {477                    phase = .finished478                    task = nil479                    return480                }481                if closed.code == WSCloseCode.unauthorized.rawValue || closed.code == WSCloseCode.notFound.rawValue {482                    phase = .failed(APIError.from(status: closed.code - 4000, data: Data()))483                    task = nil484                    return485                }486            } catch is CancellationError {487                return488            } catch {489                if Task.isCancelled { return }490                let api = APIError.wrap(error)491                if !api.isTransient {492                    phase = .failed(api)493                    task = nil494                    return495                }496            }497            let delay = policy.delay(attempt: attempt)498            attempt += 1499            phase = .reconnecting(attempt: attempt)500            guard (try? await sleeper.sleep(seconds: delay)) != nil else { return }501        }502    }503504    private func append(_ chunk: Data) {505        offset += Int64(chunk.count)506        data.append(chunk)507        if data.count > maxBytes {508            let drop = data.count - maxBytes509            data.removeFirst(drop)510            truncatedBytes += Int64(drop)511        }512    }513}514
Files main
Menu

Theme