import Foundation /// Subscribes to grid command events from the daemon and dispatches them to WorkspaceRegistry. /// Modeled after DaemonAttachSession — actor isolation serializes writes. actor DaemonGridSubscription { let projectRoot: String /// The registry's key for this project (its root locally, `machine:…` remotely). let projectId: String private let client: DaemonClient private weak var registry: WorkspaceRegistry? private var connection: (any DaemonByteStream)? private var stopped = false init(projectRoot: String, projectId: String? = nil, registry: WorkspaceRegistry, client: DaemonClient = DaemonEndpoint.local.makeClient()) { self.projectRoot = projectRoot self.projectId = projectId ?? projectRoot self.registry = registry self.client = client } /// Start the subscription loop with reconnection. func start() async { guard !stopped else { return } var backoff: UInt64 = 500_000_000 // 0.5s let maxBackoff: UInt64 = 5_000_000_000 // 5s var retries = 0 let maxRetries = 20 while !stopped { do { try await runSubscriptionLoop() break // Normal exit } catch is CancellationError { break } catch { #if os(iOS) // A suspended app loses its SSH streams: reconnect when it returns to the foreground, // without spending retries while it is in the background. if await AppActivity.shared.isInBackground { await AppActivity.shared.untilForeground() retries = 0 backoff = 500_000_000 continue } #endif // A remote machine that is down: only its supervisor reconnects. Resubscribe // once it is back, without spending retries (MACH-014). if let machineId = client.machineId, MachineConnectivity.shared.shouldWait(forMachine: machineId) { guard await waitForMachine(machineId) else { break } retries = 0 backoff = 500_000_000 continue } retries += 1 guard !stopped, retries <= maxRetries else { break } do { try await Task.sleep(nanoseconds: backoff) } catch { break } backoff = min(backoff * 2, maxBackoff) } } } /// Send a grid command through the subscription connection. func sendCommand(_ command: GridCommandPayload) async { guard let conn = connection else { return } try? await DaemonClient.write( .gridCommand(projectRoot: projectRoot, command: command), to: conn ) } /// Stop the subscription. func stop() { stopped = true connection?.close() connection = nil } // MARK: - Private /// Wait until the machine reports connected, then a random 0–1 s so its streams do not /// all resubscribe at once (MACH-014). False when stopped or cancelled meanwhile. private func waitForMachine(_ machineId: UUID) async -> Bool { while !stopped, !MachineConnectivity.shared.isConnected(machineId) { do { try await Task.sleep(for: MachineConnectivity.pollInterval) } catch { return false } } guard !stopped else { return false } do { try await Task.sleep(for: MachineConnectivity.resumeDelay()) } catch { return false } return !stopped } private func runSubscriptionLoop() async throws { let reg = self.registry let (conn, reader) = try await client.connect() self.connection?.close() self.connection = conn // Send subscribe request try await DaemonClient.write(.subscribeGrid(projectRoot: projectRoot), to: conn) // Read GridSubscribed confirmation let firstLine = try await reader.readLine() let firstResponse = DaemonClient.parse(firstLine) guard case .gridSubscribed = firstResponse else { if case .error(_, let msg) = firstResponse { throw DaemonGridError.subscribeFailed(msg) } throw DaemonGridError.unexpectedResponse } // Stream loop — receive GridEvent messages while !stopped { let line = try await reader.readLine() let response = DaemonClient.parse(line) switch response { case .gridEvent(_, let command): let root = self.projectId await MainActor.run { reg?.handleRemoteCommand(command, from: root) } case .error(_, let message): throw DaemonGridError.subscribeFailed(message) default: break } } } } enum DaemonGridError: Error, LocalizedError { case subscribeFailed(String) case unexpectedResponse var errorDescription: String? { switch self { case .subscribeFailed(let msg): "Grid subscribe failed: \(msg)" case .unexpectedResponse: "Unexpected response during grid subscribe" } } }