diff --git a/DockhandAPI/Sources/DockhandAPI/ClientFactory.swift b/DockhandAPI/Sources/DockhandAPI/ClientFactory.swift index 6902d89..7cca746 100644 --- a/DockhandAPI/Sources/DockhandAPI/ClientFactory.swift +++ b/DockhandAPI/Sources/DockhandAPI/ClientFactory.swift @@ -27,11 +27,12 @@ public enum DockhandAPIClientFactory { public static func makeClient( baseURL: URL, token: String?, - customHeaders: [DockhandCustomHeader] = [] + customHeaders: [DockhandCustomHeader] = [], + session: URLSession? = nil ) -> Client { let normalizedToken = token?.trimmingCharacters(in: .whitespacesAndNewlines) let transport = URLSessionTransport( - configuration: URLSessionTransport.Configuration(session: DockhandHTTPSession.api) + configuration: URLSessionTransport.Configuration(session: session ?? DockhandHTTPSession.api) ) let trimmedPath = baseURL.path.hasSuffix("/") ? String(baseURL.path.dropLast()) : baseURL.path diff --git a/DockhandMobile.xcodeproj/project.pbxproj b/DockhandMobile.xcodeproj/project.pbxproj index af25710..407710d 100644 --- a/DockhandMobile.xcodeproj/project.pbxproj +++ b/DockhandMobile.xcodeproj/project.pbxproj @@ -514,7 +514,7 @@ "ASSETCATALOG_COMPILER_APPICON_NAME" = "dockhand_glass"; "ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS" = NO; "CODE_SIGN_IDENTITY" = "iPhone Developer"; - "CURRENT_PROJECT_VERSION" = 17; + "CURRENT_PROJECT_VERSION" = 18; "DEVELOPMENT_TEAM" = 8DA225EN79; "GENERATE_INFOPLIST_FILE" = NO; "INFOPLIST_FILE" = "DockhandMobile/Info.plist"; @@ -523,7 +523,7 @@ "@executable_path/Frameworks", ); "LOCALIZED_STRING_SWIFTUI_SUPPORT" = YES; - "MARKETING_VERSION" = "1.6.0"; + "MARKETING_VERSION" = "1.7.0"; "PRODUCT_BUNDLE_IDENTIFIER" = "garanda.dockhand.mobile"; SDKROOT = iphoneos; "SWIFT_EMIT_LOC_STRINGS" = YES; @@ -538,7 +538,7 @@ "ASSETCATALOG_COMPILER_APPICON_NAME" = "dockhand_glass"; "ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS" = NO; "CODE_SIGN_IDENTITY" = "iPhone Developer"; - "CURRENT_PROJECT_VERSION" = 17; + "CURRENT_PROJECT_VERSION" = 18; "DEVELOPMENT_TEAM" = 8DA225EN79; "GENERATE_INFOPLIST_FILE" = NO; "INFOPLIST_FILE" = "DockhandMobile/Info.plist"; @@ -547,7 +547,7 @@ "@executable_path/Frameworks", ); "LOCALIZED_STRING_SWIFTUI_SUPPORT" = YES; - "MARKETING_VERSION" = "1.6.0"; + "MARKETING_VERSION" = "1.7.0"; "PRODUCT_BUNDLE_IDENTIFIER" = "garanda.dockhand.mobile"; SDKROOT = iphoneos; "SWIFT_EMIT_LOC_STRINGS" = YES; diff --git a/DockhandMobile/App/AppModel.swift b/DockhandMobile/App/AppModel.swift index 329683f..fe968fc 100644 --- a/DockhandMobile/App/AppModel.swift +++ b/DockhandMobile/App/AppModel.swift @@ -42,6 +42,7 @@ final class AppModel { var environments: [Components.Schemas.Environment] = [] var selectedEnvironmentID: Int? var isLoadingEnvironments = false + private var environmentsLoadToken = UUID() var environmentError: String? var lastHealthStatus: String? private(set) var dashboardRefreshRevision = 0 @@ -105,6 +106,12 @@ final class AppModel { "\(selectedProfileID ?? "none"):\(selectedEnvironmentID ?? -1)" } + /// A remembered environment ID alone is not enough: list tasks must restart + /// when the new server's environment actually becomes available. + var connectionLoadID: String { + "\(connectionScopeID):\(selectedEnvironment?.id ?? -1)" + } + var connectionScope: DockhandConnectionScope { DockhandConnectionScope(profileID: selectedProfileID, environmentID: selectedEnvironmentID) } @@ -196,7 +203,10 @@ final class AppModel { } func refreshEnvironments(forceEnvironmentReset: Bool = false) async { + let loadToken = UUID() + environmentsLoadToken = loadToken guard selectedProfile != nil else { + isLoadingEnvironments = false environmentError = nil environments = [] lastHealthStatus = nil @@ -205,6 +215,7 @@ final class AppModel { guard let baseURL = normalizedBaseURL, let profileID = selectedProfile?.id else { + isLoadingEnvironments = false environmentError = String(localized: "Invalid Dockhand URL") environments = [] lastHealthStatus = nil @@ -215,7 +226,7 @@ final class AppModel { environmentError = nil defer { - isLoadingEnvironments = false + if loadToken == environmentsLoadToken { isLoadingEnvironments = false } } do { @@ -235,6 +246,7 @@ final class AppModel { throw DockhandConnectionStageError(stage: .environments, underlying: error) } } + guard loadToken == environmentsLoadToken, selectedProfile?.id == profileID, !Task.isCancelled else { return } lastHealthStatus = loaded.0 let loadedEnvironments = loaded.1 environments = loadedEnvironments.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } @@ -254,7 +266,7 @@ final class AppModel { PreferencesStore.setSelectedEnvironmentID(selectedEnvironmentID, for: profileID) } catch { - guard !error.isDockhandCancellation else { return } + guard loadToken == environmentsLoadToken, selectedProfile?.id == profileID, !error.isDockhandCancellation else { return } // Keep the last known environments so screens recover on their own // once the server is reachable again. environmentError = error.dockhandUserFacingMessage diff --git a/DockhandMobile/Features/Containers/ContainersView.swift b/DockhandMobile/Features/Containers/ContainersView.swift index f0acd9d..73357df 100644 --- a/DockhandMobile/Features/Containers/ContainersView.swift +++ b/DockhandMobile/Features/Containers/ContainersView.swift @@ -6,6 +6,8 @@ import SwiftUI @Observable final class ContainersStore { var containers: [Components.Schemas.Container] = [] + private var listLoadToken = UUID() + private var loadedListScopeID: String? var isLoading = false var error: String? var actionMessage: String? @@ -13,30 +15,38 @@ final class ContainersStore { var pendingUpdates: [String: PendingContainerUpdate] = [:] var updatingContainerID: String? - func load(appModel: AppModel) async { + func load(appModel: AppModel, service: DockhandService? = nil) async { + let scope = appModel.connectionLoadID + let token = UUID() + listLoadToken = token + isLoading = false + if loadedListScopeID != scope { + containers = [] + pendingUpdates = [:] + loadedListScopeID = scope + } + error = nil guard let baseURL = appModel.normalizedBaseURL, let environmentID = appModel.selectedEnvironment?.id else { containers = [] + pendingUpdates = [:] return } isLoading = true - error = nil - defer { isLoading = false } - + defer { if listLoadToken == token { isLoading = false } } do { - let service = appModel.service(baseURL: baseURL) - // Update badges are optional; a failed pending-updates request must not hide the list. + let service = service ?? appModel.service(baseURL: baseURL) async let loadedUpdates = try? service.fetchPendingContainerUpdates(environmentID: environmentID) - containers = try await service.fetchContainers(environmentID: environmentID) - .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } - let updates = PendingContainerUpdate.actionable( - await loadedUpdates ?? [], - liveContainerIDs: Set(containers.map(\.id)) - ) + let loaded = try await service.fetchContainers(environmentID: environmentID) + guard listLoadToken == token, scope == appModel.connectionLoadID, !Task.isCancelled else { return } + containers = loaded.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } + // Optional update badges must not delay the main list. + let updates = PendingContainerUpdate.actionable(await loadedUpdates ?? [], liveContainerIDs: Set(loaded.map(\.id))) + guard listLoadToken == token, scope == appModel.connectionLoadID, !Task.isCancelled else { return } pendingUpdates = Dictionary(updates.map { ($0.containerID, $0) }, uniquingKeysWith: { first, _ in first }) } catch { - guard !error.isDockhandCancellation else { return } + guard listLoadToken == token, scope == appModel.connectionLoadID, !error.isDockhandCancellation else { return } self.error = error.dockhandUserFacingMessage } } @@ -169,7 +179,11 @@ struct ContainersView: View { } Section("Containers") { - if filteredContainers.isEmpty { + if appModel.isLoadingEnvironments && appModel.selectedEnvironment == nil { + ProgressView("Loading environments…") + } else if store.isLoading && store.containers.isEmpty { + ProgressView("Loading…") + } else if filteredContainers.isEmpty { Text( !searchText.trimmed.isEmpty ? String(format: String(localized: "No results for “%@”"), locale: Locale.current, searchText.trimmed) @@ -230,12 +244,7 @@ struct ContainersView: View { } } } - .overlay { - if store.isLoading && store.containers.isEmpty { - ProgressView() - } - } - .task(id: "\(appModel.connectionScopeID):\(appModel.dashboardRefreshRevision)") { + .task(id: "\(appModel.connectionLoadID):\(appModel.dashboardRefreshRevision)") { await store.load(appModel: appModel) } .onChange(of: filterRequestRevision, initial: true) { diff --git a/DockhandMobile/Features/Dashboard/DashboardView.swift b/DockhandMobile/Features/Dashboard/DashboardView.swift index d0f69a1..9fac284 100644 --- a/DockhandMobile/Features/Dashboard/DashboardView.swift +++ b/DockhandMobile/Features/Dashboard/DashboardView.swift @@ -92,10 +92,21 @@ final class DashboardStore { @MainActor @Observable -private final class DashboardResourceDetailStore { +final class DashboardResourceDetailStore { var pendingUpdates: [PendingContainerUpdate] = [] var serverVersion: String? private var updatesLoadToken = UUID() + private var updateCheckToken = UUID() + private var loadedUpdatesScopeID: String? + private var checkedUpdatesScopeID: String? + private var lastCheckUpdatesFound: Int? + + var hasCheckedCurrentEnvironment: Bool { + checkedUpdatesScopeID != nil && checkedUpdatesScopeID == loadedUpdatesScopeID + } + var lastCheckFoundNoUpdates: Bool { + hasCheckedCurrentEnvironment && lastCheckUpdatesFound == 0 + } var volumes: [VolumeSnapshot] = [] var networks: [NetworkSnapshot] = [] var activity = ContainerActivitySnapshot(events: [], total: 0) @@ -103,12 +114,25 @@ private final class DashboardResourceDetailStore { var isLoading = false var isCheckingUpdates = false var isUpdatingContainers = false + var updatingContainerIDs: Set = [] + var completedUpdateIDs: Set = [] + var containerUpdateMessage = "" + var containerUpdateOutput: [String] = [] var updateCheckProgress: Double? var operationMessage: String? var error: String? func loadUpdates(appModel: AppModel) async { let scope = appModel.connectionScopeID + if scope != loadedUpdatesScopeID { + loadedUpdatesScopeID = scope + checkedUpdatesScopeID = nil + lastCheckUpdatesFound = nil + updateCheckToken = UUID() + isCheckingUpdates = false + updateCheckProgress = nil + operationMessage = nil + } let token = UUID() updatesLoadToken = token serverVersion = nil @@ -151,57 +175,94 @@ private final class DashboardResourceDetailStore { } func checkForUpdates(appModel: AppModel) async { - guard let service = service(for: appModel), + guard !isCheckingUpdates, !isUpdatingContainers, + let service = service(for: appModel), let environmentID = appModel.selectedEnvironment?.id else { return } + let scope = appModel.connectionScopeID + let token = UUID() + updateCheckToken = token isCheckingUpdates = true updateCheckProgress = nil operationMessage = nil error = nil - defer { isCheckingUpdates = false } + defer { if token == updateCheckToken { isCheckingUpdates = false } } do { let operation = try await service.startContainerUpdateCheck(environmentID: environmentID) + guard scope == appModel.connectionScopeID, token == updateCheckToken, !Task.isCancelled else { return } let result: ContainerUpdateCheckResult switch operation { case .job(let jobID): - result = try await watchUpdateCheckJob(jobID, service: service) + result = try await watchUpdateCheckJob(jobID, service: service, appModel: appModel, scope: scope, token: token) case .completed(let completedResult): updateCheckProgress = 1 result = completedResult } + guard scope == appModel.connectionScopeID, token == updateCheckToken, !Task.isCancelled else { return } + checkedUpdatesScopeID = scope + lastCheckUpdatesFound = result.updatesFound + appModel.requestDashboardRefresh() + await loadUpdates(appModel: appModel) + guard scope == appModel.connectionScopeID, token == updateCheckToken, !Task.isCancelled else { return } operationMessage = String( format: String(localized: "%1$d updates found after checking %2$d containers"), locale: .current, result.updatesFound, result.total ) - appModel.requestDashboardRefresh() - await loadUpdates(appModel: appModel) } catch { - guard !error.isDockhandCancellation else { return } + guard scope == appModel.connectionScopeID, token == updateCheckToken, !error.isDockhandCancellation else { return } self.error = error.dockhandUserFacingMessage } } func updateContainers(_ updates: [PendingContainerUpdate], appModel: AppModel) async { - guard !updates.isEmpty, + guard !updates.isEmpty, !isUpdatingContainers, !isCheckingUpdates, let service = service(for: appModel), let environmentID = appModel.selectedEnvironment?.id else { return } + let scope = appModel.connectionScope isUpdatingContainers = true + updatingContainerIDs = Set(updates.map(\.containerID)) + completedUpdateIDs = [] + containerUpdateMessage = String(localized: "Updating containers…") + containerUpdateOutput = [] operationMessage = nil error = nil - defer { isUpdatingContainers = false } + defer { + isUpdatingContainers = false + updatingContainerIDs = [] + } do { - let response = try await service.updateContainers( + let response = try await service.updateContainersWithProgress( ids: updates.map(\.containerID), environmentID: environmentID - ) + ) { event in + try Task.checkCancellation() + try await MainActor.run { + guard appModel.isCurrentScope(scope) else { throw CancellationError() } + if event.type == "heartbeat" { return } + if event.isTerminalContainerStep, let id = event.containerId { + self.completedUpdateIDs.insert(id) + } + if event.type != "pull_log" && event.type != "scan_log" && event.type != "complete" { + self.containerUpdateMessage = event.displayMessage + } + let line = event.message ?? event.error ?? [event.pullStatus, event.pullProgress].compactMap { $0 }.joined(separator: " ") + if !line.isEmpty, self.containerUpdateOutput.last != line { + self.containerUpdateOutput.append(line) + if self.containerUpdateOutput.count > 200 { self.containerUpdateOutput.removeFirst() } + } + } + } + guard appModel.isCurrentScope(scope), !Task.isCancelled else { return } + containerUpdateMessage = String(localized: "Refreshing container updates…") // loadUpdates clears messages, so refresh the list before reporting the outcome. appModel.requestDashboardRefresh() await loadUpdates(appModel: appModel) + guard appModel.isCurrentScope(scope), !Task.isCancelled else { return } if response.summary.success > 0 { operationMessage = String( format: String(localized: "%d containers updated"), @@ -219,20 +280,25 @@ private final class DashboardResourceDetailStore { ) } } catch { - guard !error.isDockhandCancellation else { return } + guard appModel.isCurrentScope(scope), !error.isDockhandCancellation else { return } self.error = error.dockhandUserFacingMessage } } private func watchUpdateCheckJob( _ jobID: String, - service: DockhandService + service: DockhandService, + appModel: AppModel, + scope: String, + token: UUID ) async throws -> ContainerUpdateCheckResult { var cursor = 0 while true { try Task.checkCancellation() + guard scope == appModel.connectionScopeID, token == updateCheckToken else { throw CancellationError() } let snapshot = try await service.fetchContainerUpdateCheckJob(id: jobID) + guard scope == appModel.connectionScopeID, token == updateCheckToken, !Task.isCancelled else { throw CancellationError() } if cursor < snapshot.lines.count { for line in snapshot.lines[cursor...] { @@ -878,6 +944,32 @@ private struct DashboardUpdatesDetailView: View { .listRowBackground(Color.clear) } + if store.isUpdatingContainers { + Section { + VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 12) { + ProgressView() + Text(store.containerUpdateMessage) + .font(.headline) + .accessibilityAddTraits(.updatesFrequently) + } + if !store.updatingContainerIDs.isEmpty { + ProgressView(value: Double(store.completedUpdateIDs.count), total: Double(store.updatingContainerIDs.count)) + Text(String(format: String(localized: "%1$lld of %2$lld containers processed"), + Int64(store.completedUpdateIDs.count), Int64(store.updatingContainerIDs.count))) + .font(.caption).foregroundStyle(.secondary) + } + if !store.containerUpdateOutput.isEmpty { + Text(store.containerUpdateOutput.suffix(8).joined(separator: "\n")) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) + .textSelection(.enabled) + } + } + .padding(.vertical, 8) + } + } + if let error = store.error { Section { Text(error) @@ -901,7 +993,9 @@ private struct DashboardUpdatesDetailView: View { .disabled(store.isCheckingUpdates || store.isUpdatingContainers) if store.isCheckingUpdates { - ProgressView(value: store.updateCheckProgress) + ProgressView(value: store.updateCheckProgress) { + Text("Checking for updates…") + } } if !store.pendingUpdates.isEmpty { @@ -916,17 +1010,24 @@ private struct DashboardUpdatesDetailView: View { Section("Pending updates") { if store.isLoading && store.pendingUpdates.isEmpty { - HStack { - Spacer() - ProgressView() - Spacer() - } + ProgressView("Loading pending updates…") + } else if store.isCheckingUpdates && store.pendingUpdates.isEmpty { + Text("Waiting for the update check to finish…") + .foregroundStyle(.secondary) } else if store.pendingUpdates.isEmpty && store.error == nil { - ContentUnavailableView( - "No pending updates", - systemImage: "checkmark.circle", - description: Text("All checked containers are up to date.") - ) + if store.lastCheckFoundNoUpdates { + ContentUnavailableView( + "No updates found", + systemImage: "checkmark.circle", + description: Text("No updates were found in the last check for this environment.") + ) + } else { + ContentUnavailableView( + "No recorded updates", + systemImage: "tray", + description: Text("Run Check for updates to look for newer images. Loading this list does not check for new updates.") + ) + } } else { ForEach(store.pendingUpdates, id: \.containerID) { update in HStack(alignment: .center, spacing: 12) { @@ -956,8 +1057,11 @@ private struct DashboardUpdatesDetailView: View { Button { updatesToConfirm = [update] } label: { - Image(systemName: "arrow.up.circle") - .font(.title3) + if store.updatingContainerIDs.contains(update.containerID) { + ProgressView() + } else { + Image(systemName: "arrow.up.circle").font(.title3) + } } .buttonStyle(.borderless) .disabled(store.isCheckingUpdates || store.isUpdatingContainers) @@ -969,6 +1073,19 @@ private struct DashboardUpdatesDetailView: View { } } .listStyle(.insetGrouped) + .safeAreaInset(edge: .bottom) { + if store.isUpdatingContainers { + HStack(spacing: 12) { + ProgressView() + Text(store.containerUpdateMessage).font(.subheadline.weight(.medium)) + Spacer(minLength: 0) + } + .padding(18) + .glassEffect(.regular, in: .rect(cornerRadius: 20)) + .padding(.horizontal, 20) + .padding(.vertical, 8) + } + } .navigationTitle("Available Updates") .navigationBarTitleDisplayMode(.inline) .task(id: ServerDetailsStore.loadID(appModel: appModel)) { diff --git a/DockhandMobile/Features/Images/ImagesStore.swift b/DockhandMobile/Features/Images/ImagesStore.swift index ceb218d..fcbe1b1 100644 --- a/DockhandMobile/Features/Images/ImagesStore.swift +++ b/DockhandMobile/Features/Images/ImagesStore.swift @@ -33,6 +33,8 @@ struct ImagePullLayer: Identifiable, Equatable { @Observable final class ImagesStore { var images: [Components.Schemas.ImageSummary] = [] + private var listLoadToken = UUID() + private var loadedListScopeID: String? var isLoading = false var error: String? var actionMessage: String? @@ -65,7 +67,16 @@ final class ImagesStore { !pullLayers.isEmpty && pullLayers.allSatisfy(\.isAlreadyPresent) } - func load(appModel: AppModel) async { + func load(appModel: AppModel, service: DockhandService? = nil) async { + let scope = appModel.connectionLoadID + let token = UUID() + listLoadToken = token + isLoading = false + if loadedListScopeID != scope { + images = [] + loadedListScopeID = scope + } + error = nil guard let baseURL = appModel.normalizedBaseURL, let environmentID = appModel.selectedEnvironment?.id else { images = [] @@ -73,15 +84,14 @@ final class ImagesStore { } isLoading = true - error = nil - defer { isLoading = false } - + defer { if listLoadToken == token { isLoading = false } } do { - let service = appModel.service(baseURL: baseURL) - images = try await service.fetchImages(environmentID: environmentID) - .sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending } + let service = service ?? appModel.service(baseURL: baseURL) + let loaded = try await service.fetchImages(environmentID: environmentID) + guard listLoadToken == token, scope == appModel.connectionLoadID, !Task.isCancelled else { return } + images = loaded.sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending } } catch { - guard !error.isDockhandCancellation else { return } + guard listLoadToken == token, scope == appModel.connectionLoadID, !error.isDockhandCancellation else { return } self.error = error.dockhandUserFacingMessage } } diff --git a/DockhandMobile/Features/Images/ImagesView.swift b/DockhandMobile/Features/Images/ImagesView.swift index 8db99d7..9dbe829 100644 --- a/DockhandMobile/Features/Images/ImagesView.swift +++ b/DockhandMobile/Features/Images/ImagesView.swift @@ -53,7 +53,11 @@ struct ImagesView: View { } Section("Images") { - if filteredImages.isEmpty { + if appModel.isLoadingEnvironments && appModel.selectedEnvironment == nil { + ProgressView("Loading environments…") + } else if store.isLoading && store.images.isEmpty { + ProgressView("Loading…") + } else if filteredImages.isEmpty { Text( !searchText.trimmed.isEmpty ? String(format: String(localized: "No results for “%@”"), locale: Locale.current, searchText.trimmed) @@ -140,12 +144,7 @@ struct ImagesView: View { .sheet(isPresented: $pullSheetPresented) { PullImageSheet(appModel: appModel, scope: appModel.connectionScope, store: store, actionScope: .list) } - .overlay { - if store.isLoading && store.images.isEmpty { - ProgressView() - } - } - .task(id: "\(appModel.connectionScopeID):\(appModel.dashboardRefreshRevision)") { + .task(id: "\(appModel.connectionLoadID):\(appModel.dashboardRefreshRevision)") { await store.load(appModel: appModel) } .refreshable { diff --git a/DockhandMobile/Features/Settings/SettingsView.swift b/DockhandMobile/Features/Settings/SettingsView.swift index a4b9d22..b3fe270 100644 --- a/DockhandMobile/Features/Settings/SettingsView.swift +++ b/DockhandMobile/Features/Settings/SettingsView.swift @@ -13,7 +13,7 @@ final class ServerDetailsStore { private var loadToken = UUID() static func loadID(appModel: AppModel) -> String { - "\(appModel.connectionScopeID):\(appModel.selectedEnvironment?.id ?? -1)" + appModel.connectionLoadID } func load(appModel: AppModel) async { diff --git a/DockhandMobile/Features/Stacks/StackEditorSupport.swift b/DockhandMobile/Features/Stacks/StackEditorSupport.swift index 750fafd..b89fcfd 100644 --- a/DockhandMobile/Features/Stacks/StackEditorSupport.swift +++ b/DockhandMobile/Features/Stacks/StackEditorSupport.swift @@ -4,6 +4,22 @@ import UIKit import Yams enum StackEditorValidator { + static func validateNewStack(name: String, compose: String, env: String, existingNames: [String]) throws { + guard name.range(of: #"^[a-z0-9][a-z0-9_-]*$"#, options: .regularExpression) != nil else { + throw DockhandServiceError.message(String(localized: "Use lowercase letters, numbers, hyphens or underscores. Start with a letter or number.")) + } + guard !existingNames.contains(where: { $0.caseInsensitiveCompare(name) == .orderedSame }) else { + throw DockhandServiceError.message(String(localized: "A stack with this name already exists in this environment.")) + } + try validateCompose(compose) + guard let root = try Yams.load(yaml: compose) as? [String: Any], + let services = root["services"] as? [String: Any], !services.isEmpty, + services.values.allSatisfy({ $0 is [String: Any] }) else { + throw DockhandServiceError.message(String(localized: "Compose must contain a non-empty services mapping.")) + } + try validateEnv(env) + } + static func validateCompose(_ text: String) throws { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { diff --git a/DockhandMobile/Features/Stacks/StacksStore.swift b/DockhandMobile/Features/Stacks/StacksStore.swift index ee4680b..006b528 100644 --- a/DockhandMobile/Features/Stacks/StacksStore.swift +++ b/DockhandMobile/Features/Stacks/StacksStore.swift @@ -14,6 +14,8 @@ enum StackRedeployStatus: Equatable { @Observable final class StacksStore { var stacks: [Components.Schemas.StackSummary] = [] + private var listLoadToken = UUID() + private var loadedListScopeID: String? var isLoading = false var error: String? var actionMessage: String? @@ -25,28 +27,32 @@ final class StacksStore { var redeployOutput: [String] = [] var redeployError: String? - func load(appModel: AppModel) async { + func load(appModel: AppModel, service: DockhandService? = nil) async { + let scope = appModel.connectionLoadID + let token = UUID() + listLoadToken = token + isLoading = false + if loadedListScopeID != scope { + stacks = [] + loadedListScopeID = scope + } + error = nil guard let baseURL = appModel.normalizedBaseURL, let environmentID = appModel.selectedEnvironment?.id else { stacks = [] return } - // Keep the current list while refreshing so an open stack editor is not torn down. isLoading = true - error = nil - defer { isLoading = false } - + defer { if listLoadToken == token { isLoading = false } } do { - let service = appModel.service(baseURL: baseURL) - stacks = try await service.fetchStacks(environmentID: environmentID) - .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } + let service = service ?? appModel.service(baseURL: baseURL) + let loaded = try await service.fetchStacks(environmentID: environmentID) + guard listLoadToken == token, scope == appModel.connectionLoadID, !Task.isCancelled else { return } + stacks = loaded.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } } catch { - guard !error.isDockhandCancellation else { return } - self.error = DockhandConnectionStageError( - stage: .selectedEnvironment, - underlying: error - ).dockhandUserFacingMessage + guard listLoadToken == token, scope == appModel.connectionLoadID, !error.isDockhandCancellation else { return } + self.error = DockhandConnectionStageError(stage: .selectedEnvironment, underlying: error).dockhandUserFacingMessage } } @@ -156,6 +162,36 @@ final class StacksStore { } } + func deployCreatedStack(name: String, service: DockhandService, environmentID: Int, + appModel: AppModel, scope: DockhandConnectionScope, + options: StackDeployOptions) async throws { + try Task.checkCancellation() + guard appModel.isCurrentScope(scope), scope.environmentID == environmentID, !hasPendingAction else { throw CancellationError() } + activeStackActionID = "create:" + name + resetRedeployProgress() + redeployStatus = .deploying + defer { activeStackActionID = nil } + do { + let start = try await service.startStackRedeploy(stackName: name, environmentID: environmentID, options: options) + let result: StackRedeployResult + switch start { + case .completed(let completed): result = completed + case .job(let id): result = try await watchStackRedeployJob(id, service: service, appModel: appModel, scope: scope) + } + try Task.checkCancellation() + guard appModel.isCurrentScope(scope) else { throw CancellationError() } + guard result.success == true, result.error == nil else { + throw DockhandServiceError.message(result.error ?? String(localized: "Stack redeploy failed")) + } + applyRedeployResult(result) + redeployStatus = .complete + } catch { + redeployStatus = error.isDockhandCancellation ? .cancelled : .failed + redeployError = error.dockhandUserFacingMessage + throw error + } + } + func resetRedeployProgress() { redeployStatus = .idle redeploySteps = [] diff --git a/DockhandMobile/Features/Stacks/StacksView.swift b/DockhandMobile/Features/Stacks/StacksView.swift index dc3a689..d728edc 100644 --- a/DockhandMobile/Features/Stacks/StacksView.swift +++ b/DockhandMobile/Features/Stacks/StacksView.swift @@ -8,6 +8,7 @@ struct StacksView: View { @State private var sort = StackListSort.name @State private var stateFilter = DockhandStateFilter.all @State private var searchText = "" + @State private var creationTarget: StackCreationTarget? private var filteredStacks: [Components.Schemas.StackSummary] { let filtered = store.stacks.filter { @@ -52,7 +53,11 @@ struct StacksView: View { } Section("Stacks") { - if store.error == nil && filteredStacks.isEmpty { + if appModel.isLoadingEnvironments && appModel.selectedEnvironment == nil { + ProgressView("Loading environments…") + } else if store.isLoading && store.stacks.isEmpty { + ProgressView("Loading…") + } else if store.error == nil && filteredStacks.isEmpty { Text( !searchText.trimmed.isEmpty ? String(format: String(localized: "No results for “%@”"), locale: Locale.current, searchText.trimmed) @@ -73,7 +78,23 @@ struct StacksView: View { .listStyle(.insetGrouped) .navigationTitle("Stacks") .searchable(text: $searchText, prompt: Text("Search stacks")) + .sheet(item: $creationTarget) { target in + StackCreationView(appModel: appModel, stacksStore: store, scope: target.scope) { name in + searchText = "" + stateFilter = .all + selection = name + } + } .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button { + creationTarget = StackCreationTarget(scope: appModel.connectionScope) + } label: { + Label("Create stack", systemImage: "plus") + } + .disabled(appModel.normalizedBaseURL == nil || appModel.connectionScope.environmentID == nil || store.hasPendingAction) + } + ToolbarItem(placement: .topBarTrailing) { Menu { Section("Sort") { @@ -106,12 +127,7 @@ struct StacksView: View { } } } - .overlay { - if store.isLoading && store.stacks.isEmpty { - ProgressView() - } - } - .task(id: "\(appModel.connectionScopeID):\(appModel.dashboardRefreshRevision)") { + .task(id: "\(appModel.connectionLoadID):\(appModel.dashboardRefreshRevision)") { await store.load(appModel: appModel) } .refreshable { @@ -1045,3 +1061,341 @@ private enum EditorPane: String, CaseIterable, Identifiable { var id: String { rawValue } var title: String { self == .compose ? String(localized: "Compose") : ".env" } } + +/// The presentation and its captured destination must change as one state value. +private struct StackCreationTarget: Identifiable { + let id = UUID() + let scope: DockhandConnectionScope +} + +private struct StackCreationView: View { + let appModel: AppModel + let stacksStore: StacksStore + let scope: DockhandConnectionScope + let onCreated: (String) -> Void + @Environment(\.dismiss) private var dismiss + @State private var name = "" + @State private var compose = "services:\n app:\n image: nginx:alpine\n" + @State private var envContent = "" + @State private var editorFocused = false + @State private var activePane = EditorPane.compose + @State private var showsDeploymentOptions = false + @State private var options = StackDeployOptions() + @State private var isWorking = false + @State private var isCreated = false + @State private var message: String? + @State private var attempt = 0 + @State private var shouldStart = false + @State private var creationPhase = String(localized: "Checking stack…") + + private var isCurrentScope: Bool { appModel.isCurrentScope(scope) } + + private var canSubmit: Bool { + !isWorking && isCurrentScope && !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + var body: some View { + NavigationStack { + ScrollView { + GlassEffectContainer(spacing: 18) { + VStack(alignment: .leading, spacing: 18) { + destinationCard + if !isCurrentScope { + statusCard(String(localized: "The server or environment changed. Close this form and try again."), + symbol: "exclamationmark.triangle", color: .orange) + } + if let message { + statusCard(message, symbol: "exclamationmark.circle", color: .red) + } + if isCreated && !isWorking { + statusCard(String(localized: "The stack has been created. You can close this form or retry starting it."), + symbol: "checkmark.circle", color: .green) + } + if isWorking { + progressCard + } else { + nameCard + editorCard + deploymentCard + if attempt > 0 && !stacksStore.redeployOutput.isEmpty { + progressCard + } + } + } + } + .padding(20) + } + .id(isWorking) + .scrollDismissesKeyboard(.interactively) + .background(Color(.systemGroupedBackground)) + .navigationTitle("Create stack") + .navigationBarTitleDisplayMode(.inline) + .safeAreaInset(edge: .bottom) { + if !isWorking { creationActions } + } + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button(isCreated ? String(localized: "Done") : String(localized: "Cancel")) { dismiss() } + .disabled(isWorking) + } + } + } + .presentationDetents([.large]) + .presentationDragIndicator(.visible) + .presentationSizing(.form) + .interactiveDismissDisabled(isWorking) + .onChange(of: activePane) { editorFocused = false } + .task(id: attempt) { + guard attempt > 0 else { return } + await submit() + } + } + + private var destinationCard: some View { + HStack(spacing: 14) { + Image(systemName: "square.3.layers.3d") + .font(.title2) + .foregroundStyle(.tint) + .frame(width: 44, height: 44) + .background(Color.accentColor.opacity(0.1), in: .rect(cornerRadius: 14)) + VStack(alignment: .leading, spacing: 5) { + Text(appModel.serverProfiles.first(where: { $0.id == scope.profileID })?.name ?? "") + .font(.headline) + Label(appModel.environment(for: scope)?.name ?? "", systemImage: "server.rack") + .font(.subheadline) + .foregroundStyle(.secondary) + } + Spacer(minLength: 0) + } + .padding(18) + .frame(maxWidth: .infinity, alignment: .leading) + .glassEffect(.regular.tint(.white.opacity(0.02)), in: .rect(cornerRadius: 24)) + } + + private var nameCard: some View { + VStack(alignment: .leading, spacing: 12) { + Label("Stack name", systemImage: "tag") + .font(.headline) + TextField("Stack name", text: $name) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .padding(14) + .background(Color(.secondarySystemGroupedBackground), in: .rect(cornerRadius: 14)) + Text("Use lowercase letters, numbers, hyphens or underscores. Start with a letter or number.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .padding(20) + .glassEffect(.regular.tint(.white.opacity(0.02)), in: .rect(cornerRadius: 24)) + .disabled(isWorking || isCreated || !isCurrentScope) + } + + private var editorCard: some View { + VStack(alignment: .leading, spacing: 12) { + Picker("Pane", selection: $activePane) { + ForEach(EditorPane.allCases) { pane in + Text(pane.title).tag(pane) + } + } + .pickerStyle(.segmented) + Label(activePane == .compose ? String(localized: "Compose file") : String(localized: "Environment file"), + systemImage: activePane == .compose ? "doc.text" : "slider.horizontal.3") + .font(.subheadline.weight(.medium)) + .foregroundStyle(.secondary) + SyntaxHighlightingTextEditor(text: activePane == .compose ? $compose : $envContent, + isFocused: $editorFocused, kind: activePane == .compose ? .yaml : .env) + .frame(height: 320) + .background(Color(.secondarySystemGroupedBackground), in: .rect(cornerRadius: 16)) + .clipShape(.rect(cornerRadius: 16)) + .accessibilityLabel(activePane == .compose ? String(localized: "Compose file") : String(localized: "Environment file")) + if activePane == .env { + Text("Optional. Add environment variables used by your Compose file.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + .padding(20) + .glassEffect(.regular.tint(.white.opacity(0.02)), in: .rect(cornerRadius: 24)) + .disabled(isWorking || isCreated || !isCurrentScope) + } + + private var deploymentCard: some View { + DisclosureGroup(isExpanded: $showsDeploymentOptions) { + VStack(spacing: 14) { + Toggle("Pull images", isOn: $options.pull) + Divider() + Toggle("Build images", isOn: $options.build) + Divider() + Toggle("Force recreate", isOn: $options.forceRecreate) + } + .padding(.top, 16) + } label: { + VStack(alignment: .leading, spacing: 6) { + Label("Deployment options", systemImage: "slider.horizontal.3") + .font(.headline) + Text("Only used when starting the stack. Creating without starting ignores these options.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .foregroundStyle(.primary) + } + .padding(20) + .glassEffect(.regular.tint(.white.opacity(0.02)), in: .rect(cornerRadius: 24)) + .disabled(isWorking || !isCurrentScope) + } + + private var progressCard: some View { + VStack(alignment: .leading, spacing: 20) { + HStack(spacing: 16) { + if isWorking { + ProgressView().controlSize(.large) + } else { + Image(systemName: "terminal").font(.title2) + } + VStack(alignment: .leading, spacing: 6) { + Text(name.trimmingCharacters(in: .whitespacesAndNewlines)) + .font(.title2.weight(.semibold)) + Text(creationPhase) + .font(.subheadline) + .foregroundStyle(.secondary) + .accessibilityAddTraits(.updatesFrequently) + } + } + if isCreated { + Label("Stack files saved", systemImage: "checkmark.circle.fill") + .font(.subheadline) + .foregroundStyle(.green) + } + if isWorking && stacksStore.redeployStatus == .deploying, + let status = stacksStore.redeploySteps.last { + Text(status) + .font(.subheadline) + .foregroundStyle(.secondary) + } + if !stacksStore.redeployOutput.isEmpty { + Label("Deployment output", systemImage: "terminal") + .font(.headline) + ScrollViewReader { reader in + ScrollView { + Text(stacksStore.redeployOutput.joined(separator: "\n")) + .font(.caption.monospaced()) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + Color.clear.frame(height: 1).id("output-end") + } + .frame(height: 260) + .padding(14) + .background(Color(.secondarySystemGroupedBackground), in: .rect(cornerRadius: 16)) + .onChange(of: stacksStore.redeployOutput.count, initial: true) { + reader.scrollTo("output-end", anchor: .bottom) + } + } + } + } + .padding(20) + .frame(maxWidth: .infinity, alignment: .leading) + .glassEffect(.regular.tint(.white.opacity(0.02)), in: .rect(cornerRadius: 24)) + } + + private func statusCard(_ text: String, symbol: String, color: Color) -> some View { + Label(text, systemImage: symbol) + .font(.footnote) + .foregroundStyle(color) + .textSelection(.enabled) + .padding(16) + .frame(maxWidth: .infinity, alignment: .leading) + .glassEffect(.regular.tint(color.opacity(0.08)), in: .rect(cornerRadius: 18)) + } + + private var creationActions: some View { + GlassEffectContainer(spacing: 12) { + ViewThatFits(in: .horizontal) { + HStack(spacing: 12) { actionButtons } + VStack(spacing: 12) { actionButtons } + } + } + .font(.subheadline.weight(.semibold)) + .controlSize(.large) + .disabled(!canSubmit) + .padding(.horizontal, 20) + .padding(.vertical, 12) + .background(.bar) + } + + @ViewBuilder + private var actionButtons: some View { + if !isCreated { + Button { begin(start: false) } label: { + Label("Create only", systemImage: "square.and.arrow.down") + .lineLimit(1) + .fixedSize(horizontal: true, vertical: false) + .frame(maxWidth: .infinity, minHeight: 24) + } + .buttonStyle(.glass) + } + Button { begin(start: true) } label: { + Label(isCreated ? String(localized: "Retry start") : String(localized: "Create and start"), systemImage: "play.fill") + .lineLimit(1) + .fixedSize(horizontal: true, vertical: false) + .frame(maxWidth: .infinity, minHeight: 24) + } + .buttonStyle(.glassProminent) + } + + private func begin(start: Bool) { + guard !isWorking else { return } + shouldStart = start + creationPhase = isCreated ? String(localized: "Deploying stack…") : String(localized: "Checking stack…") + isWorking = true + stacksStore.resetRedeployProgress() + message = nil + editorFocused = false + attempt += 1 + } + + @MainActor + private func submit() async { + defer { isWorking = false } + guard isCurrentScope, let environmentID = scope.environmentID, + let baseURL = appModel.normalizedBaseURL else { return } + let service = appModel.service(baseURL: baseURL) + let stackName = name.trimmingCharacters(in: .whitespacesAndNewlines) + do { + if !isCreated { + try StackEditorValidator.validateNewStack(name: stackName, compose: compose, env: envContent, + existingNames: []) + // The create endpoint can replace an existing stack: always check a fresh listing. + let currentStacks = try await service.fetchStacks(environmentID: environmentID) + try StackEditorValidator.validateNewStack(name: stackName, compose: compose, env: envContent, + existingNames: currentStacks.map(\.name)) + try Task.checkCancellation() + guard isCurrentScope else { throw CancellationError() } + creationPhase = String(localized: "Creating stack…") + try await service.createStack(name: stackName, compose: compose, envContent: envContent, environmentID: environmentID) + isCreated = true + } + if shouldStart { + creationPhase = String(localized: "Deploying stack…") + try await stacksStore.deployCreatedStack(name: stackName, service: service, environmentID: environmentID, + appModel: appModel, scope: scope, options: options) + } + try Task.checkCancellation() + guard isCurrentScope else { throw CancellationError() } + creationPhase = String(localized: "Refreshing stack list…") + appModel.requestDashboardRefresh() + await stacksStore.load(appModel: appModel) + guard isCurrentScope else { throw CancellationError() } + onCreated(stackName) + dismiss() + } catch { + creationPhase = String(localized: "Operation stopped") + if !error.isDockhandCancellation { message = error.dockhandUserFacingMessage } + if isCreated && isCurrentScope { + appModel.requestDashboardRefresh() + await stacksStore.load(appModel: appModel) + } + } + } +} diff --git a/DockhandMobile/Localizable.xcstrings b/DockhandMobile/Localizable.xcstrings index e710914..ed33d3c 100644 --- a/DockhandMobile/Localizable.xcstrings +++ b/DockhandMobile/Localizable.xcstrings @@ -1,6 +1,426 @@ { "sourceLanguage" : "en", "strings" : { + "Loading environments…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Cargando entornos…" + } + } + } + }, + "Checking for updates…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Buscando actualizaciones…" + } + } + } + }, + "Loading pending updates…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Cargando actualizaciones pendientes…" + } + } + } + }, + "Waiting for the update check to finish…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Esperando a que termine la comprobación…" + } + } + } + }, + "No updates found": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "No se encontraron actualizaciones" + } + } + } + }, + "No updates were found in the last check for this environment.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "No se encontraron actualizaciones en la última comprobación de este entorno." + } + } + } + }, + "No recorded updates": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "No hay actualizaciones registradas" + } + } + } + }, + "Run Check for updates to look for newer images. Loading this list does not check for new updates.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Pulsa Buscar actualizaciones para buscar imágenes nuevas. Cargar esta lista no comprueba si hay nuevas actualizaciones." + } + } + } + }, + "Pulling image…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Descargando imagen…" + } + } + } + }, + "Scanning image…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Analizando imagen…" + } + } + } + }, + "Stopping container…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Deteniendo contenedor…" + } + } + } + }, + "Removing old container…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Eliminando contenedor anterior…" + } + } + } + }, + "Recreating container…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Recreando contenedor…" + } + } + } + }, + "Starting container…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Arrancando contenedor…" + } + } + } + }, + "Container updated": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Contenedor actualizado" + } + } + } + }, + "Updating containers…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Actualizando contenedores…" + } + } + } + }, + "Pulling images and recreating containers…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Descargando imágenes y recreando contenedores…" + } + } + } + }, + "Container update progress could not be confirmed. Refresh before trying again.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo confirmar el resultado de la actualización. Actualiza la lista antes de reintentarlo." + } + } + } + }, + "Refreshing container updates…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Actualizando lista de contenedores…" + } + } + } + }, + "%1$lld of %2$lld containers processed": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "%1$lld de %2$lld contenedores procesados" + } + } + } + }, + "Checking stack…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Comprobando stack…" + } + } + } + }, + "Deploying stack…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Desplegando stack…" + } + } + } + }, + "Stack files saved": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Archivos del stack guardados" + } + } + } + }, + "Deployment output": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Salida del despliegue" + } + } + } + }, + "Refreshing stack list…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Actualizando lista de stacks…" + } + } + } + }, + "Operation stopped": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Operación detenida" + } + } + } + }, + "Create only": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Solo crear" + } + } + } + }, + "Optional. Add environment variables used by your Compose file.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Opcional. Añade las variables de entorno que utiliza tu archivo Compose." + } + } + } + }, + "Only used when starting the stack. Creating without starting ignores these options.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Solo se aplican al arrancar el stack. Al crear sin arrancar, estas opciones no se utilizan." + } + } + } + }, + "Create stack": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Crear stack" + } + } + } + }, + "Stack name": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Nombre del stack" + } + } + } + }, + "Create and start": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Crear y arrancar" + } + } + } + }, + "Retry start": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Reintentar arranque" + } + } + } + }, + "Deployment options": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Opciones de despliegue" + } + } + } + }, + "Creating stack…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Creando stack…" + } + } + } + }, + "Starting stack…": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Arrancando stack…" + } + } + } + }, + "Failed to create stack": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo crear el stack" + } + } + } + }, + "The server or environment changed. Close this form and try again.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "El servidor o el entorno ha cambiado. Cierra este formulario y vuelve a intentarlo." + } + } + } + }, + "The stack has been created. You can close this form or retry starting it.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "El stack ya está creado. Puedes cerrar este formulario o reintentar el arranque." + } + } + } + }, + "Use lowercase letters, numbers, hyphens or underscores. Start with a letter or number.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Usa minúsculas, números, guiones o guiones bajos. Empieza por una letra o un número." + } + } + } + }, + "A stack with this name already exists in this environment.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Ya existe un stack con este nombre en este entorno." + } + } + } + }, + "Compose must contain a non-empty services mapping.": { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Compose debe contener un mapa de servicios no vacío." + } + } + } + }, "Show server picker in header" : { "localizations" : { "es" : { diff --git a/DockhandMobile/Services/DockhandService.swift b/DockhandMobile/Services/DockhandService.swift index 42c59b2..3616ca8 100644 --- a/DockhandMobile/Services/DockhandService.swift +++ b/DockhandMobile/Services/DockhandService.swift @@ -362,6 +362,58 @@ struct ContainerUpdateCheckJobSnapshot: Decodable, Sendable, Hashable { var result: ContainerUpdateCheckResult? } +struct ContainerBatchUpdateProgress: Decodable, Sendable { + var type: String + var containerId: String? + var containerName: String? + var step: String? + var message: String? + var error: String? + var pullStatus: String? + var pullProgress: String? + var summary: Summary? + + struct Summary: Decodable, Sendable { + var total: Int + var success: Int + var failed: Int + var blocked: Int? + var skipped: Int? + } + + var isTerminalContainerStep: Bool { + ["done", "failed", "blocked", "skipped"].contains(step ?? "") + } + + var displayMessage: String { + let stage: String + switch step { + case "pulling": stage = String(localized: "Pulling image…") + case "scanning": stage = String(localized: "Scanning image…") + case "stopping": stage = String(localized: "Stopping container…") + case "removing": stage = String(localized: "Removing old container…") + case "creating": stage = String(localized: "Recreating container…") + case "starting": stage = String(localized: "Starting container…") + case "done": stage = String(localized: "Container updated") + default: return message ?? error ?? String(localized: "Updating containers…") + } + return containerName.map { "\($0): \(stage)" } ?? stage + } +} + +private struct ContainerBatchUpdateJobSnapshot: Decodable { + struct Line: Decodable { var data: ContainerBatchUpdateProgress } + // failJob produces {success: false, error: ...} without a progress-event type. + struct Result: Decodable { + var type: String? + var error: String? + var summary: ContainerBatchUpdateProgress.Summary? + } + var status: String + var lines: [Line] + var result: Result? +} + struct ContainerBatchUpdateResult: Decodable, Sendable, Hashable { var containerID: String var containerName: String @@ -517,19 +569,22 @@ struct DockhandService { let token: String let customHeaders: [DockhandCustomHeader] private let session: URLSession + private let apiSession: URLSession? - init(baseURL: URL, token: String, customHeaders: [DockhandCustomHeader] = [], session: URLSession = DockhandHTTPSession.shared) { + init(baseURL: URL, token: String, customHeaders: [DockhandCustomHeader] = [], session: URLSession? = nil) { self.baseURL = baseURL self.token = DockhandToken.normalized(token) self.customHeaders = DockhandCustomHeaderValidator.sanitized(customHeaders) - self.session = session + self.session = session ?? DockhandHTTPSession.shared + self.apiSession = session } private var client: Client { DockhandAPIClientFactory.makeClient( baseURL: baseURL, token: token.isEmpty ? nil : token, - customHeaders: customHeaders + customHeaders: customHeaders, + session: apiSession ) } @@ -735,6 +790,71 @@ struct DockhandService { return try JSONDecoder().decode(ContainerBatchUpdateResponse.self, from: data) } + /// Only fall back on an unsupported route. Never repeat a mutation after an ambiguous failure. + func updateContainersWithProgress( + ids: [String], environmentID: Int, + onProgress: @escaping @Sendable (ContainerBatchUpdateProgress) async throws -> Void + ) async throws -> ContainerBatchUpdateResponse { + guard !ids.isEmpty else { throw DockhandServiceError.invalidResponse } + guard var components = URLComponents(url: baseURL.appending(path: "/api/containers/batch-update-stream"), + resolvingAgainstBaseURL: false) else { + throw DockhandServiceError.invalidResponse + } + components.queryItems = [URLQueryItem(name: "env", value: "\(environmentID)")] + guard let url = components.url else { throw DockhandServiceError.invalidResponse } + var request = URLRequest(url: url) + request.httpMethod = "POST" + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.setValue("application/json", forHTTPHeaderField: "Accept") + request.httpBody = try JSONSerialization.data(withJSONObject: ["containerIds": ids]) + authorize(&request) + try Task.checkCancellation() + let (data, response) = try await send(request) + if let http = response as? HTTPURLResponse, [404, 405].contains(http.statusCode) { + try Task.checkCancellation() + // Let the caller recheck the active destination before the fallback mutation. + try await onProgress(.init(type: "start", message: String(localized: "Pulling images and recreating containers…"))) + return try await updateContainers(ids: ids, environmentID: environmentID) + } + try Self.validateResponse(response, data: data) + let start = try JSONDecoder().decode(ImagePullJobStartPayload.self, from: data) + guard let jobID = start.jobId, !jobID.isEmpty else { throw DockhandServiceError.invalidResponse } + var cursor = 0 + var results: [String: ContainerBatchUpdateResult] = [:] + while true { + try Task.checkCancellation() + try await onProgress(.init(type: "heartbeat")) + var poll = URLRequest(url: baseURL.appending(path: "/api/jobs").appending(path: jobID)) + poll.setValue("application/json", forHTTPHeaderField: "Accept") + authorize(&poll) + let (jobData, jobResponse) = try await send(poll) + try Self.validateResponse(jobResponse, data: jobData) + let snapshot = try JSONDecoder().decode(ContainerBatchUpdateJobSnapshot.self, from: jobData) + for line in snapshot.lines.dropFirst(cursor) { + let event = line.data + if event.isTerminalContainerStep, let id = event.containerId, ids.contains(id) { + results[id] = .init(containerID: id, containerName: event.containerName ?? id, + success: event.step == "done", error: event.error ?? event.message) + } + try await onProgress(event) + } + cursor = snapshot.lines.count + if snapshot.status != "running" { + guard snapshot.status != "error", let result = snapshot.result, + result.type == "complete", let summary = result.summary, + summary.total == ids.count, results.count == ids.count, + summary.success == results.values.filter(\.success).count else { + throw DockhandServiceError.message(snapshot.result?.error ?? String(localized: "Container update progress could not be confirmed. Refresh before trying again.")) + } + let failed = summary.failed + (summary.blocked ?? 0) + (summary.skipped ?? 0) + guard summary.success + failed == summary.total else { throw DockhandServiceError.invalidResponse } + return .init(success: failed == 0, results: ids.compactMap { results[$0] }, + summary: .init(total: summary.total, success: summary.success, failed: failed)) + } + try await Task.sleep(for: .milliseconds(500)) + } + } + func fetchVolumes(environmentID: Int) async throws -> [VolumeSnapshot] { let response = try await performJSONArrayRequest( path: "/api/volumes", @@ -1364,6 +1484,19 @@ struct DockhandService { } } + /// Save first so a deployment failure never requires creating the stack again. + func createStack(name: String, compose: String, envContent: String, environmentID: Int) async throws { + let response = try await performJSONRequest( + path: "/api/stacks", + method: "POST", + environmentID: environmentID, + body: ["name": name, "compose": compose, "rawEnvContent": envContent, "start": false] + ) + guard response["success"] as? Bool == true else { + throw DockhandServiceError.message((response["error"] as? String) ?? String(localized: "Failed to create stack")) + } + } + func stackAction(_ action: StackAction, stackName: String, environmentID: Int) async throws { let encodedName = stackName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? stackName let response = try await performJSONRequest( @@ -1426,6 +1559,8 @@ struct DockhandService { var request = URLRequest(url: url) request.httpMethod = "POST" + // Ask for a job ID so progress can be polled while Compose is running. + request.setValue("text/event-stream", forHTTPHeaderField: "Accept") request.setValue("application/json", forHTTPHeaderField: "Content-Type") authorize(&request) request.httpBody = try JSONSerialization.data(withJSONObject: [ diff --git a/DockhandMobile/Shared/EnvironmentHeaderBar.swift b/DockhandMobile/Shared/EnvironmentHeaderBar.swift index 5dd4f87..09a305a 100644 --- a/DockhandMobile/Shared/EnvironmentHeaderBar.swift +++ b/DockhandMobile/Shared/EnvironmentHeaderBar.swift @@ -12,6 +12,16 @@ struct EnvironmentHeaderBar: View { let appModel: AppModel @Environment(\.showsEnvironmentHeader) private var showsEnvironmentHeader @AppStorage(serverPickerKey) private var showsServerPicker = false + @State private var headerWidth: CGFloat = 0 + @ScaledMetric(relativeTo: .body) private var minimumInlineWidth: CGFloat = 300 + + private var showsInlinePickers: Bool { headerWidth >= minimumInlineWidth } + + private var pickerLayout: AnyLayout { + showsInlinePickers + ? AnyLayout(HStackLayout(alignment: .center, spacing: 10)) + : AnyLayout(VStackLayout(alignment: .leading, spacing: 10)) + } var body: some View { if showsEnvironmentHeader { @@ -21,23 +31,22 @@ struct EnvironmentHeaderBar: View { private var header: some View { VStack(alignment: .leading, spacing: 10) { - // Side by side when it fits; stack the picker below on narrow widths (iPhone Duo folded). - ViewThatFits(in: .horizontal) { - HStack(alignment: .center, spacing: 10) { - serverInfo - // Pin the picker to the trailing edge on wide layouts (iPhone Duo unfolded, iPad). - Spacer(minLength: 0) + // AnyLayout rearranges the same menus without duplicating or replacing them. + // Choose by available width, so changing server names does not change layout. + pickerLayout { + serverInfo + .frame(maxWidth: .infinity, alignment: .leading) + HStack(spacing: 10) { environmentMenu loadingIndicator } - - VStack(alignment: .leading, spacing: 10) { - serverInfo - HStack(spacing: 10) { - environmentMenu - loadingIndicator - } - } + .frame(maxWidth: showsInlinePickers ? min(248, headerWidth / 2) : .infinity, alignment: .leading) + } + .frame(maxWidth: .infinity, alignment: .leading) + .onGeometryChange(for: CGFloat.self) { geometry in + geometry.size.width + } action: { width in + headerWidth = width } if let environment = appModel.selectedEnvironment { @@ -139,7 +148,7 @@ struct EnvironmentHeaderBar: View { } label: { HStack(spacing: 8) { Image(systemName: "globe.europe.africa.fill") - Text(appModel.selectedEnvironmentName) + Text(appModel.isLoadingEnvironments && appModel.environments.isEmpty ? String(localized: "Loading environments…") : appModel.selectedEnvironmentName) .font(.subheadline.weight(.semibold)) .lineLimit(1) Spacer(minLength: 8) @@ -156,13 +165,13 @@ struct EnvironmentHeaderBar: View { .disabled(appModel.environments.isEmpty) } - @ViewBuilder private var loadingIndicator: some View { - if appModel.isLoadingEnvironments { - ProgressView() - .controlSize(.small) - .frame(width: 28, height: 28) + Group { + if appModel.isLoadingEnvironments { + ProgressView().controlSize(.small) + } } + .frame(width: 28, height: 28) } private var lastHealthStatus: String? { diff --git a/DockhandMobileTests/DockhandMobileTests.swift b/DockhandMobileTests/DockhandMobileTests.swift index 425d8cd..e3e05ac 100644 --- a/DockhandMobileTests/DockhandMobileTests.swift +++ b/DockhandMobileTests/DockhandMobileTests.swift @@ -4,6 +4,196 @@ import SwiftUI import DockhandAPI final class DockhandMobileTests: XCTestCase { + @MainActor + func testEnvironmentSwitchClearsPreviousUpdateCheckPresentation() async { + let model = AppModel() + model.serverProfiles = [] // No connection: this test must not contact a real server. + model.selectedProfileID = "update-status-test" + model.selectedEnvironmentID = 1 + let store = DashboardResourceDetailStore() + await store.loadUpdates(appModel: model) + XCTAssertFalse(store.hasCheckedCurrentEnvironment) + + store.isCheckingUpdates = true + store.updateCheckProgress = 0.5 + store.operationMessage = "Result from the previous environment" + await store.loadUpdates(appModel: model) + XCTAssertTrue(store.isCheckingUpdates, "Reloading the same environment must not cancel its active check") + + model.selectedEnvironmentID = 2 + await store.loadUpdates(appModel: model) + XCTAssertFalse(store.isCheckingUpdates) + XCTAssertNil(store.updateCheckProgress) + XCTAssertNil(store.operationMessage) + XCTAssertFalse(store.hasCheckedCurrentEnvironment, "Loading saved pending updates is not an update check") + } + + @MainActor + func testListLoadIdentityChangesWhenRememberedEnvironmentArrives() async { + let model = AppModel() + model.serverProfiles = [.init(id: "work", name: "Work", baseURL: "https://work.test")] + model.selectedProfileID = "work" + model.selectedEnvironmentID = 1 + model.environments = [] + let identityBefore = model.connectionLoadID + let scopeBefore = model.connectionScopeID + let containers = ContainersStore() + let stacks = StacksStore() + let images = ImagesStore() + await containers.load(appModel: model) + await stacks.load(appModel: model) + await images.load(appModel: model) + XCTAssertTrue(containers.containers.isEmpty) + XCTAssertTrue(stacks.stacks.isEmpty) + XCTAssertTrue(images.images.isEmpty) + + model.environments = [makeEnvironment(publicIP: nil)] + XCTAssertEqual(model.connectionScopeID, scopeBefore, "The remembered selection itself did not change") + XCTAssertNotEqual(model.connectionLoadID, identityBefore, "List tasks must restart once the environment is available") + XCTAssertEqual(ServerDetailsStore.loadID(appModel: model), model.connectionLoadID) + } + + @MainActor + func testLateListResponsesCannotOverwriteNewServerData() async throws { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [ServerSwitchURLProtocol.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let model = AppModel() + model.serverProfiles = [.init(id: "home", name: "Home", baseURL: "https://home.test"), + .init(id: "work", name: "Work", baseURL: "https://work.test")] + model.selectedProfileID = "home" + model.selectedEnvironmentID = 1 + model.environments = [makeEnvironment(publicIP: nil)] + let oldService = DockhandService(baseURL: URL(string: "https://home.test")!, token: "", session: session) + let newService = DockhandService(baseURL: URL(string: "https://work.test")!, token: "", session: session) + let containers = ContainersStore() + let stacks = StacksStore() + let images = ImagesStore() + let oldContainers = Task { await containers.load(appModel: model, service: oldService) } + let oldStacks = Task { await stacks.load(appModel: model, service: oldService) } + let oldImages = Task { await images.load(appModel: model, service: oldService) } + try await Task.sleep(for: .milliseconds(50)) + model.selectedProfileID = "work" + await containers.load(appModel: model, service: newService) + await stacks.load(appModel: model, service: newService) + await images.load(appModel: model, service: newService) + XCTAssertEqual(stacks.stacks.first?.name, "work") + await oldContainers.value + await oldStacks.value + await oldImages.value + XCTAssertTrue(containers.containers.isEmpty) + XCTAssertEqual(stacks.stacks.first?.name, "work") + XCTAssertTrue(images.images.isEmpty) + XCTAssertNil(containers.error) + XCTAssertNil(stacks.error) + XCTAssertNil(images.error) + } + + func testCreateStackSendsSavedComposeEnvAndAuthenticationToSelectedEnvironment() async throws { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [StackCreationURLProtocol.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let service = DockhandService(baseURL: URL(string: "https://dockhand.test/prefix")!, token: "test-token", + customHeaders: [.init(name: "X-Proxy-Token", value: "proxy-token")], session: session) + try await service.createStack(name: "new-stack", compose: "services:\n app:\n image: nginx\n", + envContent: "# comment\nPORT=8080\n", environmentID: 7) + } + + func testCreateStackRejectsPermissionAndUnconfirmedResponses() async { + for host in ["forbidden.test", "unconfirmed.test", "failure.test"] { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [StackCreationURLProtocol.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let service = DockhandService(baseURL: URL(string: "https://" + host)!, token: "", session: session) + do { + try await service.createStack(name: "new-stack", compose: "services: {}", envContent: "", environmentID: 7) + XCTFail("Expected creation failure for \(host)") + } catch { + if host == "forbidden.test" { + guard case DockhandServiceError.message(let message) = error else { return XCTFail("Expected API error") } + XCTAssertEqual(message, "Permission denied") + } + } + } + } + + func testNewStackValidationRejectsDuplicateNamesPathsAndNonComposeYAML() throws { + let compose = "services:\n app:\n image: nginx\n" + XCTAssertNoThrow(try StackEditorValidator.validateNewStack(name: "new-stack_1", compose: compose, env: "PORT=8080", existingNames: [])) + for name in ["", "../stack", "UPPER", "-stack", "stack/name", "has space"] { + XCTAssertThrowsError(try StackEditorValidator.validateNewStack(name: name, compose: compose, env: "", existingNames: [])) + } + XCTAssertThrowsError(try StackEditorValidator.validateNewStack(name: "existing", compose: compose, env: "", existingNames: ["existing"])) + for yaml in ["", "hello", "[]", "services: {}", "services: []", "services: {app: nginx}", "services: ["] { + XCTAssertThrowsError(try StackEditorValidator.validateNewStack(name: "new", compose: yaml, env: "", existingNames: [])) + } + XCTAssertThrowsError(try StackEditorValidator.validateNewStack(name: "new", compose: compose, env: "INVALID LINE", existingNames: [])) + } + + @MainActor + func testCreatedStackDeploymentTracksCompletionAndRejectsChangedScope() async throws { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [GitDeploymentURLProtocol.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let service = DockhandService(baseURL: URL(string: "https://dockhand.test")!, token: "test", session: session) + let model = AppModel() + model.selectedProfileID = "creation-test" + model.selectedEnvironmentID = 2 + let scope = model.connectionScope + let store = StacksStore() + let options = StackDeployOptions(pull: true, build: true, forceRecreate: true) + try await store.deployCreatedStack(name: "local-stack", service: service, environmentID: 2, + appModel: model, scope: scope, options: options) + XCTAssertEqual(store.redeployStatus, .complete) + XCTAssertEqual(store.redeployOutput, ["Compose redeployed"]) + XCTAssertFalse(store.hasPendingAction) + for changedScope in [DockhandConnectionScope(profileID: "other", environmentID: 2), + DockhandConnectionScope(profileID: "creation-test", environmentID: 3)] { + do { + try await store.deployCreatedStack(name: "local-stack", service: service, environmentID: 2, + appModel: model, scope: changedScope, options: options) + XCTFail("A different scope must never start deployment") + } catch { + XCTAssertTrue(error is CancellationError) + } + } + XCTAssertFalse(store.hasPendingAction) + } + + @MainActor + func testCreatedStackJobPreservesProgressAndReportsFailure() async throws { + for fails in [false, true] { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [GitDeploymentURLProtocol.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let host = fails ? "creation-failure.test" : "creation-progress.test" + let service = DockhandService(baseURL: URL(string: "https://" + host)!, token: "test", session: session) + let model = AppModel() + model.selectedProfileID = "creation-progress" + model.selectedEnvironmentID = 2 + let store = StacksStore() + do { + try await store.deployCreatedStack(name: "local-stack", service: service, environmentID: 2, + appModel: model, scope: model.connectionScope, + options: .init(pull: true, build: true, forceRecreate: true)) + XCTAssertFalse(fails, "A failed deployment must not be reported as successful") + XCTAssertEqual(store.redeployStatus, .complete) + } catch { + XCTAssertTrue(fails) + XCTAssertEqual(store.redeployStatus, .failed) + XCTAssertEqual(store.redeployError, "Image pull failed") + } + XCTAssertEqual(store.redeploySteps, ["Pulling images"]) + XCTAssertTrue(store.redeployOutput.contains("app Pulling")) + XCTAssertFalse(store.hasPendingAction) + } + } + func testComposeRedeployKeepsEndpointEnvironmentAndAllOptions() async throws { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [GitDeploymentURLProtocol.self] @@ -1078,7 +1268,18 @@ private final class GitDeploymentURLProtocol: URLProtocol, @unchecked Sendable { client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse)) return } - payload = #"{"success":true,"output":"Compose redeployed"}"# + if request.url?.host?.hasPrefix("creation-") == true { + XCTAssertEqual(request.value(forHTTPHeaderField: "Accept"), "text/event-stream") + payload = #"{"jobId":"creation-job"}"# + } else { + payload = #"{"success":true,"output":"Compose redeployed"}"# + } + case ("GET", "/api/jobs/creation-job"): + if request.url?.host == "creation-failure.test" { + payload = #"{"status":"error","lines":[{"event":"progress","data":{"status":"Pulling images","line":"app Pulling"}}],"result":{"success":false,"error":"Image pull failed"}}"# + } else { + payload = #"{"status":"done","lines":[{"event":"progress","data":{"status":"Pulling images","line":"app Pulling"}}],"result":{"success":true,"output":"app Pulling\napp Created\napp Started"}}"# + } case ("POST", "/api/git/stacks/20/deploy"): payload = #"{"jobId":"git-job"}"# case ("GET", "/api/jobs/git-job"): @@ -1110,3 +1311,222 @@ final class ListSearchTests: XCTestCase { XCTAssertFalse("redis".isSearchMatch(in: ["postgres", "nginx"])) } } + + +private final class StackCreationURLProtocol: URLProtocol, @unchecked Sendable { + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + let host = request.url!.host! + var body = request.httpBody ?? Data() + if body.isEmpty, let stream = request.httpBodyStream { + stream.open() + defer { stream.close() } + var buffer = [UInt8](repeating: 0, count: 1024) + while stream.hasBytesAvailable { + let count = stream.read(&buffer, maxLength: buffer.count) + guard count > 0 else { break } + body.append(contentsOf: buffer.prefix(count)) + } + } + if host == "dockhand.test" { + let json = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] + XCTAssertEqual(request.httpMethod, "POST") + XCTAssertEqual(request.url?.path, "/prefix/api/stacks") + XCTAssertEqual(URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems, + [URLQueryItem(name: "env", value: "7")]) + XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer test-token") + XCTAssertEqual(request.value(forHTTPHeaderField: "X-Proxy-Token"), "proxy-token") + XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json") + XCTAssertEqual(json?["name"] as? String, "new-stack") + XCTAssertEqual(json?["compose"] as? String, "services:\n app:\n image: nginx\n") + XCTAssertEqual(json?["rawEnvContent"] as? String, "# comment\nPORT=8080\n") + XCTAssertEqual(json?["start"] as? Bool, false) + } + let payload: String + switch host { + case "forbidden.test": payload = #"{"error":"Permission denied"}"# + case "unconfirmed.test": payload = "{}" + case "failure.test": payload = #"{"success":false,"error":"Cannot create stack"}"# + default: payload = #"{"success":true,"started":false}"# + } + client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: host == "forbidden.test" ? 403 : 200, + httpVersion: nil, headerFields: ["Content-Type": "application/json"])!, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Data(payload.utf8)) + client?.urlProtocolDidFinishLoading(self) + } + override func stopLoading() {} +} + + +private actor BatchProgressRecorder { + var events: [ContainerBatchUpdateProgress] = [] + func append(_ event: ContainerBatchUpdateProgress) { events.append(event) } +} + +final class ContainerBatchProgressTests: XCTestCase { + func testJobReportsActualStagesAndPartialFailuresWithProfileHeaders() async throws { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [BatchProgressURLProtocol.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let service = DockhandService(baseURL: URL(string: "https://progress.test/prefix")!, token: "token", + customHeaders: [.init(name: "X-Proxy-Key", value: "proxy")], session: session) + let recorder = BatchProgressRecorder() + let result = try await service.updateContainersWithProgress(ids: ["web", "db"], environmentID: 7) { + await recorder.append($0) + } + XCTAssertFalse(result.success) + XCTAssertEqual(result.summary.success, 1) + XCTAssertEqual(result.summary.failed, 1) + XCTAssertEqual(result.failureDetails, "database: pull failed") + let events = await recorder.events + XCTAssertEqual(events.compactMap(\.step), ["pulling", "creating", "done", "failed"]) + XCTAssertEqual(events.first(where: { $0.step == "pulling" })?.containerName, "website") + } + + func testUnsupportedEndpointFallsBackWithoutInventingPerContainerProgress() async throws { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [BatchProgressURLProtocol.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let service = DockhandService(baseURL: URL(string: "https://legacy.test/prefix")!, token: "token", + customHeaders: [.init(name: "X-Proxy-Key", value: "proxy")], session: session) + let recorder = BatchProgressRecorder() + let result = try await service.updateContainersWithProgress(ids: ["web", "db"], environmentID: 7) { + await recorder.append($0) + } + XCTAssertTrue(result.success) + let events = await recorder.events + XCTAssertEqual(events.count, 1) + XCTAssertEqual(events.first?.type, "start") + XCTAssertNil(events.first?.step) + } + + func testPermissionPollingAndIncompleteResultErrorsNeverRepeatMutation() async { + for host in ["forbidden.test", "poll-failure.test", "incomplete.test", "job-error.test"] { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [BatchProgressURLProtocol.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let service = DockhandService(baseURL: URL(string: "https://" + host + "/prefix")!, token: "token", + customHeaders: [.init(name: "X-Proxy-Key", value: "proxy")], session: session) + do { + _ = try await service.updateContainersWithProgress(ids: ["web", "db"], environmentID: 7) { _ in } + XCTFail("An unconfirmed operation must not be reported as successful") + } catch { + if host == "job-error.test" { + guard case DockhandServiceError.message(let message) = error else { + return XCTFail("Job failures must preserve the server error") + } + XCTAssertEqual(message, "Scanner unavailable") + } + } + } + } + + func testScopeCancellationCanStopFallbackBeforeItsMutation() async { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [BatchProgressURLProtocol.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + let service = DockhandService(baseURL: URL(string: "https://cancelled.test/prefix")!, token: "token", + customHeaders: [.init(name: "X-Proxy-Key", value: "proxy")], session: session) + do { + _ = try await service.updateContainersWithProgress(ids: ["web", "db"], environmentID: 7) { _ in + throw CancellationError() + } + XCTFail("A changed scope must stop the fallback request") + } catch { XCTAssertTrue(error is CancellationError) } + } +} + +private final class BatchProgressURLProtocol: URLProtocol, @unchecked Sendable { + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer token") + XCTAssertEqual(request.value(forHTTPHeaderField: "X-Proxy-Key"), "proxy") + let host = request.url!.host! + let path = request.url!.path + var status = 200 + let payload: String + if request.httpMethod == "POST" { + XCTAssertEqual(URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems, + [URLQueryItem(name: "env", value: "7")]) + var body = request.httpBody ?? Data() + if body.isEmpty, let stream = request.httpBodyStream { + stream.open() + defer { stream.close() } + var buffer = [UInt8](repeating: 0, count: 1024) + while stream.hasBytesAvailable { + let n = stream.read(&buffer, maxLength: buffer.count) + guard n > 0 else { break } + body.append(contentsOf: buffer.prefix(n)) + } + } + let json = (try? JSONSerialization.jsonObject(with: body)) as? [String: [String]] + XCTAssertEqual(json?["containerIds"], ["web", "db"]) + } + switch path { + case "/prefix/api/containers/batch-update-stream": + if ["legacy.test", "cancelled.test"].contains(host) { + status = 404 + payload = #"{"error":"Not found"}"# + } else if host == "forbidden.test" { + status = 403 + payload = #"{"error":"Permission denied"}"# + } else { payload = #"{"jobId":"batch-job"}"# } + case "/prefix/api/containers/batch-update": + XCTAssertEqual(host, "legacy.test", "Never repeat an update after polling fails or scope cancellation") + payload = #"{"success":true,"results":[{"containerId":"web","containerName":"website","success":true},{"containerId":"db","containerName":"database","success":true}],"summary":{"total":2,"success":2,"failed":0}}"# + case "/prefix/api/jobs/batch-job": + if host == "poll-failure.test" { + status = 500; payload = #"{"error":"Job unavailable"}"# + } else if host == "job-error.test" { + payload = #"{"status":"error","lines":[],"result":{"success":false,"error":"Scanner unavailable"}}"# + } else if host == "incomplete.test" { + payload = #"{"status":"done","lines":[],"result":{"type":"complete","summary":{"total":2,"success":2,"failed":0}}}"# + } else { + payload = #"{"status":"done","lines":[{"data":{"type":"progress","containerId":"web","containerName":"website","step":"pulling"}},{"data":{"type":"progress","containerId":"web","step":"creating"}},{"data":{"type":"progress","containerId":"web","containerName":"website","step":"done"}},{"data":{"type":"progress","containerId":"db","containerName":"database","step":"failed","error":"pull failed"}}],"result":{"type":"complete","summary":{"total":2,"success":1,"failed":1,"blocked":0,"skipped":0}}}"# + } + default: + XCTFail("Unexpected route: \(path)") + status = 500; payload = "{}" + } + client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: status, + httpVersion: nil, headerFields: ["Content-Type": "application/json"])!, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Data(payload.utf8)) + client?.urlProtocolDidFinishLoading(self) + } + override func stopLoading() {} +} + + +private final class ServerSwitchURLProtocol: URLProtocol, @unchecked Sendable { + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + let old = request.url?.host == "home.test" + DispatchQueue.global().asyncAfter(deadline: .now() + (old ? 0.2 : 0)) { [self] in + let status: Int + let payload: String + switch request.url!.path { + case "/api/stacks": + status = 200 + let name = old ? "home" : "work" + payload = "[{\"name\":\"\(name)\",\"containers\":[],\"containerDetails\":[],\"status\":\"running\"}]" + case "/api/containers", "/api/images": + status = old ? 500 : 200 + payload = old ? #"{"error":"Old server response must be ignored"}"# : "[]" + default: + status = 200; payload = "[]" + } + client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: status, + httpVersion: nil, headerFields: ["Content-Type": "application/json"])!, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Data(payload.utf8)) + client?.urlProtocolDidFinishLoading(self) + } + } + override func stopLoading() {} +} diff --git a/README.md b/README.md index ccc7c56..934d3c7 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ Pushing a `v*` tag that points to `main` creates the GitHub Release automaticall - Start, stop, restart and pause/unpause containers where the current state allows it. - View container logs, including live streaming logs when available. - List stacks, filter and sort them by state. +- Create Compose stacks with optional `.env` content, save without starting, or create and deploy with pull/build/recreate options. - Open a stack detail view with its related containers and run container actions from there. - Edit stack compose content and `.env` files. - Validate compose YAML and `.env` format before saving. diff --git a/docs/container-update-progress.md b/docs/container-update-progress.md new file mode 100644 index 0000000..1ddd029 --- /dev/null +++ b/docs/container-update-progress.md @@ -0,0 +1,21 @@ +# Container update progress + +The Available Updates screen shows a persistent progress indicator as soon as an update starts. It displays the current container/stage, real completed-container counts and recent server output; the bottom status remains visible when updating from farther down a long list. Selected rows also show activity indicators. + +## API and compatibility + +The dashboard submits `POST /api/containers/batch-update-stream?env=ID` with the selected `containerIds`, then polls `GET /api/jobs/{jobId}`. Both requests preserve profile bearer and custom proxy headers. Stages and pull logs come from the server, including scanning when the server has scanners configured. Completed counts advance only for terminal per-container events. + +Only an HTTP 404/405 from the initial streaming-route request falls back to the existing synchronous batch endpoint. On older servers, an indeterminate activity indicator remains visible with explanatory text. Permissions, timeouts, job-polling errors and malformed results never trigger a second update request. The active connection scope is checked during polling and before fallback, refresh and result presentation. + +The final response must contain a terminal complete result and one terminal event for every selected container. Failed, blocked and skipped containers are reported as unsuccessful, alongside successful updates. An incomplete or lost job is reported as unconfirmed; the UI advises refreshing before another attempt. + +Official endpoint reviewed: [Dockhand v1.0.50 batch-update-stream route](https://github.com/Finsys/dockhand/blob/v1.0.50/src/routes/api/containers/batch-update-stream/%2Bserver.ts). + +## Validation + +Four mocked HTTP tests cover actual stages and partial failures, legacy fallback, authentication and environment/base-path routing, authorization/polling/incomplete-result failures, fatal job errors without a progress-event type, and cancellation before fallback. The full app test suite passed on iOS 26.5: 92 tests, 3 optional integration tests skipped, 0 failures. No live containers were updated by these tests. + +## Loading saved updates versus checking images + +Changing the environment or refreshing the list only fetches pending updates already recorded by Dockhand. The screen labels this as loading pending updates and, if empty, invites an explicit **Check for updates** rather than claiming all containers are up to date. A completed explicit check with zero results enables the separate “No updates found in the last check” state. Environment changes clear that state and invalidate old check results/progress so they cannot appear under a different destination. diff --git a/docs/create-stacks.md b/docs/create-stacks.md new file mode 100644 index 0000000..2f6e243 --- /dev/null +++ b/docs/create-stacks.md @@ -0,0 +1,24 @@ +# Create Compose stacks + +The Stacks toolbar opens a creation form scoped to the selected server and environment. The form accepts a Compose project name, Compose YAML and optional raw `.env` content. It reuses syntax highlighting and existing YAML/environment validation, and requires a non-empty services mapping. + +## Request flow + +1. Validate the draft and fetch a fresh `GET /api/stacks?env=ID` listing to reject a name already in use. A listing or permission failure stops creation. Dockhand's create endpoint can overwrite existing files, so the cached list alone is insufficient. There is still a server-side race if another client creates the same name between listing and submission; the API provides no atomic create-only precondition. +2. Recheck cancellation and the captured server/environment before `POST /api/stacks?env=ID`, with `name`, `compose`, `rawEnvContent` and explicit `start: false`. The existing authenticated JSON request helper sends bearer and custom proxy headers. A response must explicitly contain `success: true`. +3. **Create** saves without starting. **Create and start** first saves, then calls the existing Compose deployment endpoint with pull/build/force-recreate options and polls a returned job ID. Separate creation and deployment require the corresponding create/start permissions. +4. While creating, replace the form and its action buttons with a visible progress screen. Show validation, file creation, deployment and list-refresh phases; request the job channel explicitly with `Accept: text/event-stream` and render real server status/output with automatic log scrolling. The saved-stack/retry message is only shown after an interrupted or failed operation, never while deployment is running. Once creation succeeds, the draft is locked. If deployment fails, the form explains that the stack already exists and offers **Retry start**, which only repeats deployment. It also refreshes the list to expose the saved stack. +5. Refresh the stack list and dashboard, clear list filters, select the new stack and close the form on success. A changed connection scope stops subsequent operations and prevents selecting a stack in another environment. Closing the view cancels monitoring; cancellation does not undo server-side changes. + +The manual service request follows the existing deployment API glue; generated OpenAPI files are unchanged. No credentials, preferences or iCloud behavior are modified. + +## Compatibility and validation + +The save-only create contract and name validation were inspected in the official Dockhand `v1.0.50` sources and the current main create route: + +- [Create route](https://github.com/Finsys/dockhand/blob/v1.0.50/src/routes/api/stacks/%2Bserver.ts) +- [Stack persistence](https://github.com/Finsys/dockhand/blob/v1.0.50/src/lib/server/stacks.ts) + +Automated tests cover request routing (including base path), environment, authentication, exact Compose and `.env` preservation, explicit save-only behavior, permission errors, unconfirmed success, duplicate/invalid names and invalid documents. Manual validation on the user’s iPhone confirmed real stack creation and startup. The user also reviewed the sheet presentation, styling and progress changes. + +Local verification: the simulator app/test bundle and physical-device builds compile successfully with Xcode 27.2. On November 2, 2026, CoreSimulator was revalidated at 1174.21 and the full app test suite passed on iOS 26.5 with normal simulator signing: **87 tests, 3 integration tests skipped, 0 failures**. Simulator runtime UI remains unverified; physical-device functional and visual validation was performed by the user. diff --git a/docs/server-switch-loading.md b/docs/server-switch-loading.md new file mode 100644 index 0000000..1d3375b --- /dev/null +++ b/docs/server-switch-loading.md @@ -0,0 +1,13 @@ +# Reload resource lists when a server becomes ready + +When switching servers, the app restores the remembered environment ID before fetching that server's environments. Previously the list task ran while the resolved environment was nil, cleared its data and never ran again if the remembered ID was still valid after connection. Pull to refresh was needed to populate Containers, Stacks or Images. + +Resource task identities now include the resolved environment as well as the selected profile/environment IDs. Environment arrival changes that identity even if the remembered selection stays the same, triggering an automatic load. Server-details and pending-update screens use the same identity helper. + +Each resource load has a token and checks its captured destination before publishing data or errors. A destination change clears old rows, while same-destination refreshes retain them. Containers are published as soon as their main request completes, without waiting for optional update badges. Environment discovery also rejects obsolete responses after another server selection. + +The header keeps a single instance of each picker using `AnyLayout`: the environment stays to the right of the server when width permits, and moves below on narrow layouts or larger text sizes. Layout selection depends on measured available width rather than changing server labels; space for the connection indicator is reserved. Menus are no longer duplicated across alternative `ViewThatFits` layouts during dismissal. Lists show loading while environments/resources are being fetched rather than prematurely claiming no data. + +Regression tests cover arrival of a remembered environment without a raw scope-ID change, and delayed old-server list results/errors after the new server loads. Explicit test URLSession injection is honored by both manual requests and the generated client; default production sessions are unchanged. + +Validation: 94 app tests, 3 optional integration tests skipped, 0 failures on iOS 26.5. diff --git a/metadata/version/1.7.0/en-US.json b/metadata/version/1.7.0/en-US.json new file mode 100644 index 0000000..0af5441 --- /dev/null +++ b/metadata/version/1.7.0/en-US.json @@ -0,0 +1,8 @@ +{ + "description": "Dockhand Mobile is a native iPhone and iPad client for managing your self-hosted Dockhand servers on the go.\n\nConnect to one or more Dockhand instances, switch between environments from the main header and run the daily container operations you need without opening a laptop.\n\nFEATURES\n• Multiple servers, each isolated with its own URL, API token and selected environment\n• Optional per-server custom HTTP headers for reverse proxies such as Cloudflare Access or Pangolin\n• Environment dashboard: container health, CPU, memory, images, volumes, networks, stacks and events\n• Containers: filter, sort, start, stop, restart, pause and unpause\n• Logs, including live streaming when available\n• Stacks: view related containers, edit compose and .env files with validation, redeploy with pull, build and force recreate options\n• Images: inspect details, tags, labels and usage; pull, tag, delete and prune unused images\n• Backups: run backups, review history and destinations\n• Container update visibility\n\nREQUIREMENTS\nYou need access to your own Dockhand server and an API token. The app does not include any server or hosting service.\n\nDockhand Mobile is an independent, open-source community client. It is not affiliated with, endorsed by or maintained by the official Dockhand project. Docker is a trademark of Docker, Inc.", + "keywords": "container,self-hosted,homelab,devops,stack,compose,server,logs,sysadmin,images,monitor,prune,deploy", + "marketingUrl": "https://github.com/garanda21/dockhand_ios", + "promotionalText": "Manage containers, stacks, images and logs on your self-hosted Dockhand servers from your iPhone.", + "supportUrl": "https://github.com/garanda21/dockhand_ios/issues", + "whatsNew": "What's New\n• Create Compose stacks with an optional .env file. Save them for later or start them right away.\n• Follow deployment and container update progress with live status and server output.\n• Retry a failed deployment without creating the stack again.\n\nFixes\n• Container, stack and image lists now refresh automatically when you switch servers or environments.\n• The server selector stays visible while switching servers.\n• Update messages now distinguish recorded pending updates from a fresh image check." +} diff --git a/metadata/version/1.7.0/es-ES.json b/metadata/version/1.7.0/es-ES.json new file mode 100644 index 0000000..ef50157 --- /dev/null +++ b/metadata/version/1.7.0/es-ES.json @@ -0,0 +1,8 @@ +{ + "description": "Dockhand Mobile es un cliente nativo para iPhone, iPad y Mac con el que gestionar tus servidores Dockhand autoalojados desde cualquier lugar.\n\nConéctate a una o varias instancias de Dockhand, cambia de entorno desde la cabecera y realiza las operaciones diarias con tus contenedores sin abrir el portátil.\n\nFUNCIONES\n• Varios servidores, cada uno aislado con su propia URL, token de API y entorno seleccionado\n• Cabeceras HTTP personalizadas opcionales por servidor para proxies inversos como Cloudflare Access o Pangolin\n• Panel del entorno: salud de los contenedores, CPU, memoria, imágenes, volúmenes, redes, stacks y eventos\n• Contenedores: filtra, ordena, inicia, detén, reinicia, pausa y reanuda\n• Logs, con transmisión en directo cuando está disponible\n• Stacks: consulta sus contenedores, edita los archivos compose y .env con validación y redespliega con opciones de pull, build y recreación forzada\n• Imágenes: consulta detalles, etiquetas y uso; descarga, etiqueta, elimina y limpia las imágenes sin usar\n• Copias de seguridad: lánzalas y revisa el historial y los destinos\n• Aviso de actualizaciones de contenedores\n• En iPad y Mac, barra lateral con secciones, lista y detalle a la vez\n\nREQUISITOS\nNecesitas acceso a tu propio servidor Dockhand y un token de API. La app no incluye ningún servidor ni servicio de alojamiento.\n\nDockhand Mobile es un cliente comunitario independiente y de código abierto. No está afiliado, respaldado ni mantenido por el proyecto oficial de Dockhand. Docker es una marca registrada de Docker, Inc.", + "keywords": "contenedores,autoalojado,homelab,docker,stack,compose,logs,imágenes,monitorizar,desplegar,devops", + "marketingUrl": "https://github.com/garanda21/dockhand_ios", + "promotionalText": "Gestiona contenedores, stacks, imágenes y logs de tus servidores Dockhand autoalojados desde tu iPhone, iPad o Mac.", + "supportUrl": "https://github.com/garanda21/dockhand_ios/issues", + "whatsNew": "Novedades\n• Crea stacks Compose con un archivo .env opcional. Guárdalos para más tarde o arráncalos al momento.\n• Sigue el progreso de los despliegues y las actualizaciones de contenedores con el estado y la salida del servidor en tiempo real.\n• Reintenta un despliegue fallido sin volver a crear el stack.\n\nCorrecciones\n• Al cambiar de servidor o entorno, las listas de contenedores, stacks e imágenes se actualizan automáticamente.\n• El selector de servidor permanece visible durante el cambio.\n• Los mensajes de actualizaciones distinguen las pendientes registradas de una nueva comprobación de imágenes." +} diff --git a/project.yml b/project.yml index dfe23da..d104165 100644 --- a/project.yml +++ b/project.yml @@ -31,10 +31,10 @@ targets: PRODUCT_BUNDLE_IDENTIFIER: pro.dockhand.mobile SWIFT_VERSION: 6.0 TARGETED_DEVICE_FAMILY: "1,2" - CURRENT_PROJECT_VERSION: 2 + CURRENT_PROJECT_VERSION: 18 GENERATE_INFOPLIST_FILE: NO INFOPLIST_FILE: DockhandMobile/Info.plist - MARKETING_VERSION: 1.0 + MARKETING_VERSION: 1.7.0 SWIFT_EMIT_LOC_STRINGS: YES LOCALIZED_STRING_SWIFTUI_SUPPORT: YES ASSETCATALOG_COMPILER_APPICON_NAME: dockhand_glass