diff --git a/apps/swift-ios/App/NativeFeatureClient.swift b/apps/swift-ios/App/NativeFeatureClient.swift index 20f82c448d..f4814fbd96 100644 --- a/apps/swift-ios/App/NativeFeatureClient.swift +++ b/apps/swift-ios/App/NativeFeatureClient.swift @@ -13,7 +13,7 @@ extension FeatureInputAnswer { /// Composes the transport-focused Core layer with the UI-focused Features layer. @MainActor -final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { +final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeatureProjectCreationClient { private let runtime: EnvironmentRuntime private let settingsStore: UserDefaults private let stream: AsyncStream @@ -282,7 +282,59 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { } func addProject(path: String) async throws { - let client = try requireClient() + guard let environmentID = activeEnvironment?.id else { + throw NativeFeatureClientError.notConnected + } + try await addProject(environmentID: environmentID, path: path) + } + + func addProject(environmentID: String, path: String) async throws { + let client = try await projectCreationClient(environmentID: environmentID) + try await createProject(client: client, path: path) + } + + func browseProjectFolders( + environmentID: String, + partialPath: String + ) async throws -> FilesystemBrowseResult { + let client = try await projectCreationClient(environmentID: environmentID) + return try await client.browseFilesystem(partialPath: partialPath) + } + + func discoverProjectSources( + environmentID: String + ) async throws -> SourceControlDiscoveryResult { + let client = try await projectCreationClient(environmentID: environmentID) + return try await client.discoverSourceControl() + } + + func lookupProjectRepository( + environmentID: String, + provider: SourceControlProviderKind, + repository: String + ) async throws -> SourceControlRepositoryInfo { + let client = try await projectCreationClient(environmentID: environmentID) + return try await client.lookupRepository( + provider: provider, + repository: repository + ) + } + + func cloneProjectRepository( + environmentID: String, + remoteURL: String, + destinationPath: String + ) async throws -> SourceControlCloneResult { + let client = try await projectCreationClient(environmentID: environmentID) + let result = try await client.cloneRepository( + remoteURL: remoteURL, + destinationPath: destinationPath + ) + try await createProject(client: client, path: result.cwd) + return result + } + + private func createProject(client: T3Client, path: String) async throws { let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { throw NativeFeatureClientError.invalidProjectPath @@ -291,7 +343,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { _ = try await client.createProject( title: title.isEmpty ? "Project" : title, workspaceRoot: trimmed, - defaultModel: defaultModelSelection() + defaultModel: client.environment.id == activeEnvironment?.id + ? defaultModelSelection() + : nil ) try await refresh(client: client) } @@ -1047,6 +1101,20 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { return client } + private func projectCreationClient(environmentID: String) async throws -> T3Client { + if let client = environmentClients[environmentID] { + return client + } + guard let environment = try await runtime.environments().first(where: { + $0.id == environmentID + }) else { + throw NativeFeatureClientError.environmentNotFound + } + let client = await runtime.client(for: environment) + environmentClients[environmentID] = client + return client + } + private func projectRoute(for projectID: String) throws -> NativeProjectRoute { guard let environmentID = projectEnvironmentIDs[projectID], let wireID = projectWireIDs[projectID], @@ -3893,6 +3961,7 @@ private struct PendingTurnSubmission { private enum NativeFeatureClientError: LocalizedError { case notConnected + case environmentNotFound case projectNotFound case threadNotFound case workspaceNotFound @@ -3907,6 +3976,7 @@ private enum NativeFeatureClientError: LocalizedError { var errorDescription: String? { switch self { case .notConnected: "Connect to a T3 environment first." + case .environmentNotFound: "That T3 environment is no longer available." case .projectNotFound: "The selected project is no longer available." case .threadNotFound: "The selected thread is no longer available." case .workspaceNotFound: "The thread workspace is no longer available." diff --git a/apps/swift-ios/Core/T3Client.swift b/apps/swift-ios/Core/T3Client.swift index bf72ee5e4e..6154839b29 100644 --- a/apps/swift-ios/Core/T3Client.swift +++ b/apps/swift-ios/Core/T3Client.swift @@ -628,6 +628,14 @@ public actor T3Client { ) } + public func discoverSourceControl() async throws -> SourceControlDiscoveryResult { + try await rpc.request( + RPCMethod.serverDiscoverSourceControl.rawValue, + payload: .object([:]), + as: SourceControlDiscoveryResult.self + ) + } + public func cloneRepository( provider: SourceControlProviderKind? = nil, repository: String? = nil, @@ -1011,6 +1019,7 @@ public enum RPCMethod: String, Sendable { case filesystemBrowse = "filesystem.browse" case assetsCreateURL = "assets.createUrl" case subscribeServerConfig + case serverDiscoverSourceControl = "server.discoverSourceControl" case subscribeVCSStatus = "subscribeVcsStatus" case vcsPull = "vcs.pull" case vcsRefreshStatus = "vcs.refreshStatus" diff --git a/apps/swift-ios/Core/WorkspaceModels.swift b/apps/swift-ios/Core/WorkspaceModels.swift index 11f86ad69c..dcaab19870 100644 --- a/apps/swift-ios/Core/WorkspaceModels.swift +++ b/apps/swift-ios/Core/WorkspaceModels.swift @@ -76,6 +76,214 @@ public struct SourceControlPublishResult: Codable, Equatable, Sendable { public let status: String } +public enum SourceControlDiscoveryStatus: String, Codable, Sendable { + case available + case missing +} + +public enum SourceControlProviderAuthStatus: String, Codable, Sendable { + case authenticated + case unauthenticated + case unknown +} + +public struct SourceControlProviderAuth: Decodable, Equatable, Sendable { + public let status: SourceControlProviderAuthStatus + public let account: String? + public let host: String? + public let detail: String? + + private enum CodingKeys: String, CodingKey { + case status + case account + case host + case detail + } + + public init( + status: SourceControlProviderAuthStatus, + account: String? = nil, + host: String? = nil, + detail: String? = nil + ) { + self.status = status + self.account = account + self.host = host + self.detail = detail + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + status = try container.decode(SourceControlProviderAuthStatus.self, forKey: .status) + account = try container.decodeEffectOptionalString(forKey: .account) + host = try container.decodeEffectOptionalString(forKey: .host) + detail = try container.decodeEffectOptionalString(forKey: .detail) + } +} + +public struct SourceControlVCSDiscoveryItem: Decodable, Equatable, Sendable { + public let kind: String + public let label: String + public let executable: String? + public let implemented: Bool + public let status: SourceControlDiscoveryStatus + public let version: String? + public let installHint: String + public let detail: String? + + private enum CodingKeys: String, CodingKey { + case kind + case label + case executable + case implemented + case status + case version + case installHint + case detail + } + + public init( + kind: String, + label: String, + executable: String? = nil, + implemented: Bool, + status: SourceControlDiscoveryStatus, + version: String? = nil, + installHint: String, + detail: String? = nil + ) { + self.kind = kind + self.label = label + self.executable = executable + self.implemented = implemented + self.status = status + self.version = version + self.installHint = installHint + self.detail = detail + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + kind = try container.decode(String.self, forKey: .kind) + label = try container.decode(String.self, forKey: .label) + executable = try container.decodeIfPresent(String.self, forKey: .executable) + implemented = try container.decode(Bool.self, forKey: .implemented) + status = try container.decode(SourceControlDiscoveryStatus.self, forKey: .status) + version = try container.decodeEffectOptionalString(forKey: .version) + installHint = try container.decode(String.self, forKey: .installHint) + detail = try container.decodeEffectOptionalString(forKey: .detail) + } +} + +public struct SourceControlProviderDiscoveryItem: Decodable, Equatable, Sendable { + public let kind: SourceControlProviderKind + public let label: String + public let executable: String? + public let status: SourceControlDiscoveryStatus + public let version: String? + public let installHint: String + public let detail: String? + public let auth: SourceControlProviderAuth + + private enum CodingKeys: String, CodingKey { + case kind + case label + case executable + case status + case version + case installHint + case detail + case auth + } + + public init( + kind: SourceControlProviderKind, + label: String, + executable: String? = nil, + status: SourceControlDiscoveryStatus, + version: String? = nil, + installHint: String, + detail: String? = nil, + auth: SourceControlProviderAuth + ) { + self.kind = kind + self.label = label + self.executable = executable + self.status = status + self.version = version + self.installHint = installHint + self.detail = detail + self.auth = auth + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + kind = try container.decode(SourceControlProviderKind.self, forKey: .kind) + label = try container.decode(String.self, forKey: .label) + executable = try container.decodeIfPresent(String.self, forKey: .executable) + status = try container.decode(SourceControlDiscoveryStatus.self, forKey: .status) + version = try container.decodeEffectOptionalString(forKey: .version) + installHint = try container.decode(String.self, forKey: .installHint) + detail = try container.decodeEffectOptionalString(forKey: .detail) + auth = try container.decode(SourceControlProviderAuth.self, forKey: .auth) + } +} + +public struct SourceControlDiscoveryResult: Decodable, Equatable, Sendable { + public let versionControlSystems: [SourceControlVCSDiscoveryItem] + public let sourceControlProviders: [SourceControlProviderDiscoveryItem] + + public init( + versionControlSystems: [SourceControlVCSDiscoveryItem], + sourceControlProviders: [SourceControlProviderDiscoveryItem] + ) { + self.versionControlSystems = versionControlSystems + self.sourceControlProviders = sourceControlProviders + } +} + +private struct EffectOptionalString: Decodable { + let value: String? + + private enum CodingKeys: String, CodingKey { + case _tag + case value + } + + init(from decoder: any Decoder) throws { + let singleValue = try decoder.singleValueContainer() + if singleValue.decodeNil() { + value = nil + return + } + if let direct = try? singleValue.decode(String.self) { + value = direct + return + } + + let container = try decoder.container(keyedBy: CodingKeys.self) + switch try container.decode(String.self, forKey: ._tag) { + case "Some": + value = try container.decode(String.self, forKey: .value) + case "None": + value = nil + case let tag: + throw DecodingError.dataCorruptedError( + forKey: ._tag, + in: container, + debugDescription: "Unknown Effect Option tag \(tag)" + ) + } + } +} + +private extension KeyedDecodingContainer { + func decodeEffectOptionalString(forKey key: Key) throws -> String? { + guard contains(key), try !decodeNil(forKey: key) else { return nil } + return try decode(EffectOptionalString.self, forKey: key).value + } +} + public struct VCSWorkingTreeFile: Codable, Equatable, Sendable { public let path: String public let insertions: Int diff --git a/apps/swift-ios/Features/Workspace/ProjectAndArchiveViews.swift b/apps/swift-ios/Features/Workspace/ProjectAndArchiveViews.swift index 43e89c9480..b031c74073 100644 --- a/apps/swift-ios/Features/Workspace/ProjectAndArchiveViews.swift +++ b/apps/swift-ios/Features/Workspace/ProjectAndArchiveViews.swift @@ -1,10 +1,45 @@ import SwiftUI public struct AddProjectView: View { + private enum ProjectMode: String, CaseIterable, Identifiable { + case folder + case repository + + var id: String { rawValue } + var label: String { self == .folder ? "Folder" : "Clone" } + var icon: String { self == .folder ? "folder" : "arrow.down.circle" } + } + + private enum Field: Hashable { + case localPath + case repository + case destination + } + @SwiftUI.Environment(\.dismiss) private var dismiss @Bindable var model: FeatureRootModel - @State private var path = "" - @State private var isAdding = false + + @State private var selectedEnvironmentID: String? + @State private var mode = ProjectMode.folder + @State private var localPath = "~/" + @State private var source = ProjectRemoteSource.url + @State private var repositoryInput = "" + @State private var destinationPath = "~/" + @State private var resolvedRepository: SourceControlRepositoryInfo? + @State private var didEditDestination = false + + @State private var browsePath = "~/" + @State private var browseResult: FilesystemBrowseResult? + @State private var isBrowsing = false + @State private var browseError: String? + + @State private var discovery: SourceControlDiscoveryResult? + @State private var isDiscovering = false + @State private var discoveryError: String? + + @State private var isSubmitting = false + @State private var errorMessage: String? + @FocusState private var focusedField: Field? public init(model: FeatureRootModel) { self.model = model @@ -12,44 +47,745 @@ public struct AddProjectView: View { public var body: some View { NavigationStack { - Form { - Section { - TextField("/path/to/project", text: $path) - .textInputAutocapitalization(.never) - .autocorrectionDisabled() - } header: { - Text("Workspace path") - } footer: { - Text("The path is resolved by the connected T3 environment.") + Group { + if let environment = selectedEnvironment { + ScrollView { + LazyVStack(alignment: .leading, spacing: 22) { + if environments.count > 1 { + environmentPicker(environment) + } + modePicker + if let errorMessage { + errorBanner(errorMessage) + } + switch mode { + case .folder: + localProjectForm(environment) + case .repository: + repositoryProjectForm(environment) + } + if showsFolderBrowser { + folderBrowser(environment) + } + } + .padding(.horizontal, 18) + .padding(.top, 14) + .padding(.bottom, 32) + } + .scrollDismissesKeyboard(.interactively) + } else { + ContentUnavailableView( + "Environment unavailable", + systemImage: "server.rack", + description: Text("Reconnect a T3 environment before adding a project.") + ) } } - .scrollContentBackground(.hidden) - .background(Color.black) - .navigationTitle("Add Project") + .background(T3Colors.background) + .navigationTitle("Add project") .navigationBarTitleDisplayMode(.inline) + .t3NavigationChrome() .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } - ToolbarItem(placement: .confirmationAction) { - Button(isAdding ? "Adding…" : "Add") { add() } - .disabled(trimmedPath.isEmpty || isAdding) + } + } + .preferredColorScheme(.dark) + .onAppear(perform: selectEnvironmentIfNeeded) + .onChange(of: model.snapshot.environments) { + selectEnvironmentIfNeeded() + } + .onChange(of: source) { + resolvedRepository = nil + updateSuggestedDestination() + errorMessage = nil + } + .onChange(of: repositoryInput) { + resolvedRepository = nil + updateSuggestedDestination() + errorMessage = nil + } + .task(id: selectedEnvironmentID) { + guard selectedEnvironmentID != nil else { return } + resetEnvironmentState() + await loadDirectory(browsePath, updateSelection: false) + await loadDiscovery() + } + } + + private var projectClient: (any FeatureProjectCreationClient)? { + model.client as? any FeatureProjectCreationClient + } + + private var environments: [FeatureEnvironment] { + model.snapshot.environments.sorted { lhs, rhs in + if lhs.isActive != rhs.isActive { return lhs.isActive } + return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == .orderedAscending + } + } + + private var selectedEnvironment: FeatureEnvironment? { + environments.first { $0.id == selectedEnvironmentID && canCreateProject(in: $0) } + } + + private var sourceOptions: [ProjectRemoteSourceOption] { + ProjectRemoteSourceOptions.options(discovery: discovery) + } + + private var selectedSourceOption: ProjectRemoteSourceOption? { + sourceOptions.first { $0.source == source } + } + + private var needsRepositoryLookup: Bool { + source.provider != nil && resolvedRepository == nil + } + + private var showsFolderBrowser: Bool { + mode == .folder || !needsRepositoryLookup + } + + private var repositoryName: String { + ProjectCreationPath.repositoryName( + from: resolvedRepository?.nameWithOwner ?? repositoryInput + ) + } + + private var modePicker: some View { + HStack(spacing: 24) { + ForEach(ProjectMode.allCases) { candidate in + Button { + focusedField = nil + errorMessage = nil + mode = candidate + } label: { + VStack(spacing: 9) { + Label(candidate.label, systemImage: candidate.icon) + .font(T3Typography.control) + .foregroundStyle( + mode == candidate ? T3Colors.textPrimary : T3Colors.textTertiary + ) + Rectangle() + .fill(mode == candidate ? T3Colors.textPrimary : Color.clear) + .frame(height: 2) + } + .frame(maxWidth: .infinity) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + .accessibilityElement(children: .contain) + } + + private func environmentPicker(_ environment: FeatureEnvironment) -> some View { + VStack(alignment: .leading, spacing: 8) { + sectionTitle("Environment") + Menu { + ForEach(environments) { option in + Button { + selectedEnvironmentID = option.id + } label: { + if option.id == environment.id { + Label(option.name, systemImage: "checkmark") + } else { + Text(option.name) + } + } + .disabled(!canCreateProject(in: option)) + } + } label: { + HStack(spacing: 10) { + Image(systemName: "server.rack") + VStack(alignment: .leading, spacing: 2) { + Text(environment.name) + .font(T3Typography.control) + .foregroundStyle(T3Colors.textPrimary) + Text(environment.endpoint) + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.textTertiary) + .lineLimit(1) + } + Spacer(minLength: 12) + Image(systemName: "chevron.up.chevron.down") + .font(.caption.weight(.semibold)) + .foregroundStyle(T3Colors.textTertiary) + } + .padding(.horizontal, 13) + .frame(minHeight: 52) + .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 12)) + .overlay { + RoundedRectangle(cornerRadius: 12).stroke(T3Colors.border, lineWidth: 1) + } + } + .buttonStyle(.plain) + } + } + + private func localProjectForm(_ environment: FeatureEnvironment) -> some View { + VStack(alignment: .leading, spacing: 10) { + HStack(alignment: .firstTextBaseline) { + sectionTitle("Workspace path") + Spacer() + Text("on \(environment.name)") + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.textTertiary) + } + pathField( + placeholder: "~/projects/my-app", + text: $localPath, + field: .localPath, + browseAction: { + Task { await loadDirectory(localPath, updateSelection: false) } + } + ) + primaryAction(label: "Add project", icon: "plus") { + await addLocalProject(environment) + } + } + } + + private func repositoryProjectForm(_ environment: FeatureEnvironment) -> some View { + VStack(alignment: .leading, spacing: 16) { + VStack(alignment: .leading, spacing: 8) { + HStack { + sectionTitle("Repository source") + if isDiscovering { + ProgressView().controlSize(.small) + } + } + sourcePicker + if let discoveryError { + Label(discoveryError, systemImage: "info.circle") + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.textTertiary) + } + } + + VStack(alignment: .leading, spacing: 8) { + sectionTitle(source == .url ? "Remote URL" : "Repository") + TextField(source.prompt, text: $repositoryInput) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .keyboardType(source == .url ? .URL : .default) + .submitLabel(needsRepositoryLookup ? .next : .done) + .focused($focusedField, equals: .repository) + .onSubmit { + Task { + if needsRepositoryLookup { + await resolveRepository(environment) + } else { + focusedField = .destination + } + } + } + .t3ProjectInput() + } + + if let resolvedRepository { + repositorySummary(resolvedRepository) + } + + if needsRepositoryLookup { + primaryAction(label: "Find repository", icon: "magnifyingglass") { + await resolveRepository(environment) + } + } else { + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .firstTextBaseline) { + sectionTitle("Clone destination") + Spacer() + Text("on \(environment.name)") + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.textTertiary) + } + pathField( + placeholder: "~/projects/\(repositoryName)", + text: destinationBinding, + field: .destination, + browseAction: nil + ) + } + primaryAction(label: "Clone and add", icon: "arrow.down.circle") { + await cloneProject(environment) } } } } - private var trimmedPath: String { - path.trimmingCharacters(in: .whitespacesAndNewlines) + private var sourcePicker: some View { + Menu { + ForEach(sourceOptions) { option in + Button { + source = option.source + } label: { + if option.source == source { + Label(option.source.label, systemImage: "checkmark") + } else if let detail = option.detail { + Text("\(option.source.label) · \(detail)") + } else { + Text(option.source.label) + } + } + .disabled(!option.isReady) + } + } label: { + HStack(spacing: 10) { + Image(systemName: sourceIcon(source)) + .frame(width: 22) + VStack(alignment: .leading, spacing: 2) { + Text(source.label) + .font(T3Typography.control) + .foregroundStyle(T3Colors.textPrimary) + if let detail = selectedSourceOption?.detail { + Text(detail) + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.textTertiary) + .lineLimit(1) + } + } + Spacer(minLength: 12) + Image(systemName: "chevron.up.chevron.down") + .font(.caption.weight(.semibold)) + .foregroundStyle(T3Colors.textTertiary) + } + .padding(.horizontal, 13) + .frame(minHeight: 52) + .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 12)) + .overlay { + RoundedRectangle(cornerRadius: 12).stroke(T3Colors.border, lineWidth: 1) + } + } + .buttonStyle(.plain) } - private func add() { - isAdding = true - Task { - if await model.addProject(path: trimmedPath) { - dismiss() + private func repositorySummary(_ repository: SourceControlRepositoryInfo) -> some View { + HStack(alignment: .top, spacing: 11) { + Image(systemName: sourceIcon(source)) + .font(.body.weight(.semibold)) + .foregroundStyle(T3Colors.textSecondary) + .frame(width: 24) + VStack(alignment: .leading, spacing: 3) { + Text(repository.nameWithOwner) + .font(T3Typography.control) + .foregroundStyle(T3Colors.textPrimary) + Text(repository.sshUrl) + .font(T3Typography.supporting.monospaced()) + .foregroundStyle(T3Colors.textTertiary) + .lineLimit(2) + } + Spacer(minLength: 0) + Image(systemName: "checkmark.circle.fill") + .foregroundStyle(T3Colors.success) + } + .padding(.vertical, 4) + } + + private func folderBrowser(_ environment: FeatureEnvironment) -> some View { + VStack(alignment: .leading, spacing: 8) { + HStack { + sectionTitle("Folders on \(environment.name)") + Spacer() + if isBrowsing { + ProgressView().controlSize(.small) + } else { + Button { + Task { await loadDirectory(browsePath, updateSelection: false) } + } label: { + Image(systemName: "arrow.clockwise") + .frame(width: 32, height: 32) + } + .buttonStyle(.plain) + .foregroundStyle(T3Colors.textSecondary) + .accessibilityLabel("Refresh folders") + } + } + + Text(browsePath) + .font(T3Typography.supporting.monospaced()) + .foregroundStyle(T3Colors.textTertiary) + .lineLimit(1) + .truncationMode(.middle) + + Divider().overlay(T3Colors.separator) + if let browseError { + Text(browseError) + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.warning) + .padding(.vertical, 8) + } + if let parentPath = browseResult?.parentPath, + ProjectCreationPath.normalizedForComparison(parentPath) + != ProjectCreationPath.normalizedForComparison(browsePath) { + folderRow(name: "..", icon: "arrow.turn.left.up") { + await loadDirectory(parentPath, updateSelection: true) + } + } + if let entries = browseResult?.entries, !entries.isEmpty { + ForEach(entries, id: \.fullPath) { entry in + Divider().overlay(T3Colors.separator) + folderRow(name: entry.name, icon: "folder") { + await loadDirectory(entry.fullPath, updateSelection: true) + } + } + } else if !isBrowsing, browseError == nil { + Text("No folders here") + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.textTertiary) + .frame(maxWidth: .infinity, minHeight: 54, alignment: .center) } - isAdding = false } } + + private func folderRow( + name: String, + icon: String, + action: @escaping @MainActor () async -> Void + ) -> some View { + Button { + focusedField = nil + Task { await action() } + } label: { + HStack(spacing: 11) { + Image(systemName: icon) + .font(.body.weight(.medium)) + .foregroundStyle(T3Colors.textSecondary) + .frame(width: 24) + Text(name) + .font(.body.weight(.medium)) + .foregroundStyle(T3Colors.textPrimary) + .lineLimit(1) + Spacer(minLength: 12) + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(T3Colors.textTertiary) + } + .frame(minHeight: T3Metrics.minimumTapTarget) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + private func sectionTitle(_ title: String) -> some View { + Text(title) + .font(T3Typography.supportingStrong) + .foregroundStyle(T3Colors.textSecondary) + } + + private func pathField( + placeholder: String, + text: Binding, + field: Field, + browseAction: (() -> Void)? + ) -> some View { + HStack(spacing: 4) { + TextField(placeholder, text: text) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .submitLabel(.done) + .focused($focusedField, equals: field) + if let browseAction { + Button(action: browseAction) { + Image(systemName: "folder") + .frame(width: 36, height: 36) + } + .buttonStyle(.plain) + .foregroundStyle(T3Colors.textSecondary) + .accessibilityLabel("Browse entered path") + } + } + .t3ProjectInput() + } + + private func primaryAction( + label: String, + icon: String, + action: @escaping @MainActor () async -> Void + ) -> some View { + Button { + focusedField = nil + Task { await action() } + } label: { + HStack(spacing: 8) { + if isSubmitting { + ProgressView() + .tint(.black) + } else { + Image(systemName: icon) + } + Text(isSubmitting ? "Working…" : label) + } + .font(.body.weight(.semibold)) + .foregroundStyle(.black) + .frame(maxWidth: .infinity, minHeight: 48) + .background(Color.white, in: RoundedRectangle(cornerRadius: 12)) + } + .buttonStyle(.plain) + .disabled(isSubmitting) + .opacity(isSubmitting ? 0.66 : 1) + } + + private func errorBanner(_ message: String) -> some View { + HStack(alignment: .top, spacing: 9) { + Image(systemName: "exclamationmark.triangle.fill") + Text(message) + .font(T3Typography.supporting) + .frame(maxWidth: .infinity, alignment: .leading) + } + .foregroundStyle(T3Colors.danger) + .padding(12) + .background(T3Colors.danger.opacity(0.08), in: RoundedRectangle(cornerRadius: 10)) + } + + private var destinationBinding: Binding { + Binding( + get: { destinationPath }, + set: { value in + didEditDestination = true + destinationPath = value + } + ) + } + + private func canCreateProject(in environment: FeatureEnvironment) -> Bool { + let state = environment.isActive + ? model.snapshot.connection.state + : environment.connectionState + return state != .disconnected + } + + private func selectEnvironmentIfNeeded() { + if let selectedEnvironmentID, + environments.contains(where: { + $0.id == selectedEnvironmentID && canCreateProject(in: $0) + }) { + return + } + selectedEnvironmentID = environments.first(where: canCreateProject)?.id + } + + private func resetEnvironmentState() { + browsePath = "~/" + browseResult = nil + browseError = nil + discovery = nil + discoveryError = nil + source = .url + resolvedRepository = nil + didEditDestination = false + localPath = "~/" + destinationPath = repositoryInput.isEmpty + ? "~/" + : ProjectCreationPath.appending(repositoryName, to: "~/") + errorMessage = nil + } + + private func loadDiscovery() async { + guard let environmentID = selectedEnvironmentID, + let projectClient else { + discoveryError = "Git URL cloning is available. Provider discovery is unavailable." + return + } + isDiscovering = true + defer { isDiscovering = false } + do { + discovery = try await projectClient.discoverProjectSources( + environmentID: environmentID + ) + discoveryError = nil + } catch is CancellationError { + return + } catch { + discovery = nil + discoveryError = "Provider discovery unavailable. Git URL still works." + } + } + + private func loadDirectory(_ path: String, updateSelection: Bool) async { + guard let environmentID = selectedEnvironmentID, + let projectClient else { + browseError = "Folder browsing is unavailable. You can still enter a path directly." + return + } + let requestedPath = path.trimmingCharacters(in: .whitespacesAndNewlines) + guard !requestedPath.isEmpty else { return } + isBrowsing = true + browseError = nil + defer { isBrowsing = false } + do { + let result = try await projectClient.browseProjectFolders( + environmentID: environmentID, + partialPath: requestedPath + ) + guard selectedEnvironmentID == environmentID else { return } + browsePath = requestedPath + browseResult = result + if updateSelection { + switch mode { + case .folder: + localPath = requestedPath + case .repository: + if !didEditDestination { + destinationPath = ProjectCreationPath.appending( + repositoryName, + to: requestedPath + ) + } + } + } + } catch is CancellationError { + return + } catch { + browseError = "Couldn’t browse that folder. Direct path entry still works." + } + } + + private func addLocalProject(_ environment: FeatureEnvironment) async { + errorMessage = nil + let validated: String + switch ProjectCreationPath.validated(localPath) { + case let .success(path): validated = path + case let .failure(error): + errorMessage = error.localizedDescription + return + } + if let existing = existingProject(environmentID: environment.id, path: validated) { + errorMessage = "\(existing.name) already uses this folder." + return + } + + isSubmitting = true + defer { isSubmitting = false } + do { + if let projectClient { + try await projectClient.addProject( + environmentID: environment.id, + path: validated + ) + dismiss() + } else if environment.isActive, await model.addProject(path: validated) { + dismiss() + } else { + errorMessage = model.errorMessage ?? "The project could not be added." + } + } catch is CancellationError { + return + } catch { + errorMessage = projectErrorMessage(error) + } + } + + private func resolveRepository(_ environment: FeatureEnvironment) async { + guard let provider = source.provider else { return } + let repository = repositoryInput.trimmingCharacters(in: .whitespacesAndNewlines) + guard !repository.isEmpty else { + errorMessage = "Enter a repository name." + return + } + guard let projectClient else { + errorMessage = "Repository lookup is unavailable on this connection." + return + } + + errorMessage = nil + isSubmitting = true + defer { isSubmitting = false } + do { + resolvedRepository = try await projectClient.lookupProjectRepository( + environmentID: environment.id, + provider: provider, + repository: repository + ) + updateSuggestedDestination() + focusedField = .destination + } catch is CancellationError { + return + } catch { + errorMessage = projectErrorMessage(error) + } + } + + private func cloneProject(_ environment: FeatureEnvironment) async { + let remoteURL = resolvedRepository?.sshUrl + ?? repositoryInput.trimmingCharacters(in: .whitespacesAndNewlines) + guard !remoteURL.isEmpty else { + errorMessage = "Enter a Git remote URL." + return + } + let validatedDestination: String + switch ProjectCreationPath.validated(destinationPath) { + case let .success(path): validatedDestination = path + case let .failure(error): + errorMessage = error.localizedDescription + return + } + if let existing = existingProject( + environmentID: environment.id, + path: validatedDestination + ) { + errorMessage = "\(existing.name) already uses this destination." + return + } + guard let projectClient else { + errorMessage = "Repository cloning is unavailable on this connection." + return + } + + errorMessage = nil + isSubmitting = true + defer { isSubmitting = false } + do { + _ = try await projectClient.cloneProjectRepository( + environmentID: environment.id, + remoteURL: remoteURL, + destinationPath: validatedDestination + ) + dismiss() + } catch is CancellationError { + return + } catch { + errorMessage = projectErrorMessage(error) + } + } + + private func updateSuggestedDestination() { + guard !didEditDestination, !repositoryInput.isEmpty else { return } + destinationPath = ProjectCreationPath.appending(repositoryName, to: browsePath) + } + + private func existingProject(environmentID: String, path: String) -> FeatureProject? { + let normalized = ProjectCreationPath.normalizedForComparison(path) + return model.snapshot.projects.first { + $0.environmentID == environmentID + && ProjectCreationPath.normalizedForComparison($0.path) == normalized + } + } + + private func sourceIcon(_ source: ProjectRemoteSource) -> String { + switch source { + case .url: "link" + case .github: "chevron.left.forwardslash.chevron.right" + case .gitlab: "shippingbox" + case .bitbucket: "shippingbox.fill" + case .azureDevOps: "point.3.connected.trianglepath.dotted" + } + } + + private func projectErrorMessage(_ error: Error) -> String { + let message = error.localizedDescription.trimmingCharacters(in: .whitespacesAndNewlines) + return message.isEmpty ? "The server could not complete that request." : message + } +} + +private extension View { + func t3ProjectInput() -> some View { + font(.body) + .foregroundStyle(T3Colors.textPrimary) + .padding(.horizontal, 13) + .frame(minHeight: 48) + .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 12)) + .overlay { + RoundedRectangle(cornerRadius: 12).stroke(T3Colors.border, lineWidth: 1) + } + } } diff --git a/apps/swift-ios/Features/Workspace/ProjectCreationModels.swift b/apps/swift-ios/Features/Workspace/ProjectCreationModels.swift new file mode 100644 index 0000000000..8643325a6d --- /dev/null +++ b/apps/swift-ios/Features/Workspace/ProjectCreationModels.swift @@ -0,0 +1,187 @@ +import Foundation + +@MainActor +protocol FeatureProjectCreationClient: AnyObject { + func addProject(environmentID: String, path: String) async throws + func browseProjectFolders( + environmentID: String, + partialPath: String + ) async throws -> FilesystemBrowseResult + func discoverProjectSources(environmentID: String) async throws -> SourceControlDiscoveryResult + func lookupProjectRepository( + environmentID: String, + provider: SourceControlProviderKind, + repository: String + ) async throws -> SourceControlRepositoryInfo + func cloneProjectRepository( + environmentID: String, + remoteURL: String, + destinationPath: String + ) async throws -> SourceControlCloneResult +} + +enum ProjectRemoteSource: String, CaseIterable, Hashable, Identifiable { + case url + case github + case gitlab + case bitbucket + case azureDevOps = "azure-devops" + + var id: String { rawValue } + + var provider: SourceControlProviderKind? { + switch self { + case .url: nil + case .github: .github + case .gitlab: .gitlab + case .bitbucket: .bitbucket + case .azureDevOps: .azureDevOps + } + } + + var label: String { + switch self { + case .url: "Git URL" + case .github: "GitHub" + case .gitlab: "GitLab" + case .bitbucket: "Bitbucket" + case .azureDevOps: "Azure DevOps" + } + } + + var prompt: String { + switch self { + case .url: "https://github.com/org/repository.git" + case .github, .gitlab, .bitbucket: "owner/repository" + case .azureDevOps: "organization/project/repository" + } + } +} + +struct ProjectRemoteSourceOption: Equatable, Identifiable { + let source: ProjectRemoteSource + let isReady: Bool + let detail: String? + + var id: String { source.id } +} + +enum ProjectRemoteSourceOptions { + static func options( + discovery: SourceControlDiscoveryResult? + ) -> [ProjectRemoteSourceOption] { + let providerByKind = Dictionary( + uniqueKeysWithValues: (discovery?.sourceControlProviders ?? []).map { + ($0.kind.rawValue, $0) + } + ) + + return ProjectRemoteSource.allCases.map { source in + guard let providerKind = source.provider else { + return ProjectRemoteSourceOption(source: source, isReady: true, detail: nil) + } + guard let provider = providerByKind[providerKind.rawValue] else { + return ProjectRemoteSourceOption( + source: source, + isReady: false, + detail: "Provider status unavailable" + ) + } + guard provider.status == .available else { + return ProjectRemoteSourceOption( + source: source, + isReady: false, + detail: provider.detail ?? provider.installHint + ) + } + guard provider.auth.status != .unauthenticated else { + return ProjectRemoteSourceOption( + source: source, + isReady: false, + detail: provider.auth.detail ?? "Authentication required" + ) + } + let account = provider.auth.account.map { "Signed in as \($0)" } + return ProjectRemoteSourceOption( + source: source, + isReady: true, + detail: account ?? provider.version + ) + } + } +} + +enum ProjectCreationPath { + static func validated(_ rawValue: String) -> Result { + let path = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) + guard !path.isEmpty else { + return .failure(.init(message: "Enter a project path.")) + } + guard isAbsoluteOrHomeRelative(path) else { + return .failure( + .init(message: "Use an absolute path, or start with ~/.") + ) + } + return .success(path) + } + + static func repositoryName(from value: String) -> String { + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return "repository" } + let withoutQuery = trimmed.split(separator: "?", maxSplits: 1).first.map(String.init) + ?? trimmed + let withoutFragment = withoutQuery.split(separator: "#", maxSplits: 1).first.map(String.init) + ?? withoutQuery + let normalized = withoutFragment + .replacingOccurrences(of: "\\", with: "/") + .replacingOccurrences(of: ":", with: "/") + .trimmingCharacters(in: CharacterSet(charactersIn: "/")) + let component = normalized.split(separator: "/").last.map(String.init) ?? "repository" + let withoutGit = component.lowercased().hasSuffix(".git") + ? String(component.dropLast(4)) + : component + let sanitized = withoutGit.trimmingCharacters(in: .whitespacesAndNewlines) + return sanitized.isEmpty ? "repository" : sanitized + } + + static func appending(_ component: String, to basePath: String) -> String { + let base = basePath.trimmingCharacters(in: .whitespacesAndNewlines) + guard !base.isEmpty else { return component } + guard !component.isEmpty else { return base } + let separator = base.contains("\\") && !base.contains("/") ? "\\" : "/" + if base.hasSuffix("/") || base.hasSuffix("\\") { + return base + component + } + return base + separator + component + } + + static func normalizedForComparison(_ value: String) -> String { + var normalized = value + .trimmingCharacters(in: .whitespacesAndNewlines) + .replacingOccurrences(of: "\\", with: "/") + while normalized.count > 1, normalized.hasSuffix("/") { + normalized.removeLast() + } + return normalized.lowercased() + } + + private static func isAbsoluteOrHomeRelative(_ path: String) -> Bool { + if path == "~" || path.hasPrefix("~/") || path.hasPrefix("~\\") { + return true + } + if path.hasPrefix("/") || path.hasPrefix("\\\\") { + return true + } + let scalars = Array(path.unicodeScalars.prefix(3)) + return scalars.count == 3 + && CharacterSet.letters.contains(scalars[0]) + && scalars[1] == ":" + && (scalars[2] == "\\" || scalars[2] == "/") + } +} + +struct ProjectCreationValidationError: LocalizedError, Equatable { + let message: String + + var errorDescription: String? { message } +} diff --git a/apps/swift-ios/Tests/CoreTests/SourceControlDiscoveryTests.swift b/apps/swift-ios/Tests/CoreTests/SourceControlDiscoveryTests.swift new file mode 100644 index 0000000000..b4d71dccc5 --- /dev/null +++ b/apps/swift-ios/Tests/CoreTests/SourceControlDiscoveryTests.swift @@ -0,0 +1,91 @@ +import Foundation +import Testing +@testable import T3Code + +@Suite("Source control discovery contracts") +struct SourceControlDiscoveryTests { + @Test + func decodesEffectOptionsFromTheServerContract() throws { + let data = Data( + #""" + { + "versionControlSystems": [ + { + "kind": "git", + "label": "Git", + "executable": "git", + "implemented": true, + "status": "available", + "version": {"_id":"Option","_tag":"Some","value":"git 2.50"}, + "installHint": "Install Git", + "detail": {"_id":"Option","_tag":"None"} + } + ], + "sourceControlProviders": [ + { + "kind": "github", + "label": "GitHub", + "executable": "gh", + "status": "available", + "version": {"_id":"Option","_tag":"Some","value":"2.76"}, + "installHint": "Install gh", + "detail": {"_id":"Option","_tag":"None"}, + "auth": { + "status": "authenticated", + "account": {"_id":"Option","_tag":"Some","value":"octocat"}, + "host": {"_id":"Option","_tag":"Some","value":"github.com"}, + "detail": {"_id":"Option","_tag":"None"} + } + } + ] + } + """#.utf8 + ) + + let result = try JSONDecoder.t3.decode(SourceControlDiscoveryResult.self, from: data) + + #expect(result.versionControlSystems.first?.version == "git 2.50") + #expect(result.versionControlSystems.first?.detail == nil) + #expect(result.sourceControlProviders.first?.kind == .github) + #expect(result.sourceControlProviders.first?.auth.account == "octocat") + #expect(result.sourceControlProviders.first?.auth.host == "github.com") + #expect(result.sourceControlProviders.first?.auth.detail == nil) + #expect(RPCMethod.serverDiscoverSourceControl.rawValue == "server.discoverSourceControl") + } + + @Test + func toleratesMissingAndPlainOptionalStrings() throws { + let data = Data( + #""" + { + "versionControlSystems": [], + "sourceControlProviders": [ + { + "kind": "gitlab", + "label": "GitLab", + "status": "missing", + "version": null, + "installHint": "Install glab", + "detail": "Not installed", + "auth": { + "status": "unknown", + "account": null, + "host": null, + "detail": "Not installed" + } + } + ] + } + """#.utf8 + ) + + let result = try JSONDecoder.t3.decode(SourceControlDiscoveryResult.self, from: data) + let provider = try #require(result.sourceControlProviders.first) + + #expect(provider.status == .missing) + #expect(provider.version == nil) + #expect(provider.detail == "Not installed") + #expect(provider.auth.account == nil) + #expect(provider.auth.detail == "Not installed") + } +} diff --git a/apps/swift-ios/Tests/FeatureTests/ProjectCreationModelsTests.swift b/apps/swift-ios/Tests/FeatureTests/ProjectCreationModelsTests.swift new file mode 100644 index 0000000000..69f64edb43 --- /dev/null +++ b/apps/swift-ios/Tests/FeatureTests/ProjectCreationModelsTests.swift @@ -0,0 +1,91 @@ +import Foundation +import Testing +@testable import T3Code + +@Suite("Native project creation") +struct ProjectCreationModelsTests { + @Test + func repositoryNamesCoverHttpsSshAndProviderPaths() { + #expect( + ProjectCreationPath.repositoryName( + from: "https://github.com/pingdotgg/t3code.git" + ) == "t3code" + ) + #expect( + ProjectCreationPath.repositoryName( + from: "git@github.com:pingdotgg/t3code.git" + ) == "t3code" + ) + #expect(ProjectCreationPath.repositoryName(from: "pingdotgg/t3code") == "t3code") + #expect(ProjectCreationPath.repositoryName(from: "") == "repository") + } + + @Test + func pathsRequireServerAbsoluteOrHomeRelativeInput() throws { + #expect(try ProjectCreationPath.validated(" ~/work/t3code ").get() == "~/work/t3code") + #expect(try ProjectCreationPath.validated("/srv/t3code").get() == "/srv/t3code") + #expect(try ProjectCreationPath.validated(#"C:\work\t3code"#).get() == #"C:\work\t3code"#) + #expect(ProjectCreationPath.validated("relative/project").isFailure) + #expect(ProjectCreationPath.validated(" ").isFailure) + } + + @Test + func destinationSuggestionsRespectUnixAndWindowsSeparators() { + #expect(ProjectCreationPath.appending("t3code", to: "~/work") == "~/work/t3code") + #expect(ProjectCreationPath.appending("t3code", to: "~/work/") == "~/work/t3code") + #expect( + ProjectCreationPath.appending("t3code", to: #"C:\work"#) == #"C:\work\t3code"# + ) + #expect( + ProjectCreationPath.normalizedForComparison(#"C:\Work\T3Code\"#) + == "c:/work/t3code" + ) + } + + @Test + func discoveryKeepsGitUrlReadyAndGatesProviderAuthentication() { + let discovery = SourceControlDiscoveryResult( + versionControlSystems: [], + sourceControlProviders: [ + SourceControlProviderDiscoveryItem( + kind: .github, + label: "GitHub", + status: .available, + version: "2.76", + installHint: "Install gh", + auth: SourceControlProviderAuth( + status: .authenticated, + account: "octocat" + ) + ), + SourceControlProviderDiscoveryItem( + kind: .gitlab, + label: "GitLab", + status: .available, + installHint: "Install glab", + auth: SourceControlProviderAuth( + status: .unauthenticated, + detail: "Run glab auth login" + ) + ), + ] + ) + + let options = ProjectRemoteSourceOptions.options(discovery: discovery) + let bySource = Dictionary(uniqueKeysWithValues: options.map { ($0.source, $0) }) + + #expect(bySource[.url]?.isReady == true) + #expect(bySource[.github]?.isReady == true) + #expect(bySource[.github]?.detail == "Signed in as octocat") + #expect(bySource[.gitlab]?.isReady == false) + #expect(bySource[.gitlab]?.detail == "Run glab auth login") + #expect(bySource[.bitbucket]?.isReady == false) + } +} + +private extension Result { + var isFailure: Bool { + if case .failure = self { return true } + return false + } +}