fix(ios): harden native task creation

This commit is contained in:
Theo Browne committed 2026-08-09 20:52:51 -07:00
1 parent 509fe681c3
commit fe48a626d1
5 files changed
+620 -50

No files matched your search

+263 -30
View File
@@ -328,12 +328,34 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
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
do {
return try await client.cloneRepository(
remoteURL: remoteURL,
destinationPath: destinationPath
)
} catch let error as RPCError {
switch error {
case .connectionUnavailable, .disconnected:
// The clone RPC is not receipt-bearing, so a lost reply is
// ambiguous. Confirm the requested destination became a Git
// repository with a primary remote before moving on to the
// independently retryable project-registration step.
if let refs = try? await client.listVCSRefs(
cwd: destinationPath,
refresh: true,
limit: 1
), refs.isRepo, refs.hasPrimaryRemote {
return SourceControlCloneResult(
cwd: destinationPath,
remoteUrl: remoteURL,
repository: nil
)
}
throw error
case .remote, .protocolViolation:
throw error
}
}
}
private func createProject(client: T3Client, path: String) async throws {
@@ -341,15 +363,71 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
guard !trimmed.isEmpty else {
throw NativeFeatureClientError.invalidProjectPath
}
let title = URL(fileURLWithPath: trimmed).lastPathComponent
_ = try await client.createProject(
title: title.isEmpty ? "Project" : title,
workspaceRoot: trimmed,
defaultModel: client.environment.id == activeEnvironment?.id
? defaultModelSelection()
: nil
)
try await refresh(client: client)
let title = ProjectCreationPath.lastPathComponent(trimmed)
let projectID = UUID().uuidString
do {
_ = try await client.createProject(
projectID: projectID,
title: title.isEmpty ? "Project" : title,
workspaceRoot: trimmed,
defaultModel: client.environment.id == activeEnvironment?.id
? fallbackModelSelection(
environmentID: client.environment.id,
projectID: nil,
shell: shellsByEnvironmentID[client.environment.id]
)
: nil
)
} catch {
// The dispatch reply may be lost after the server persisted the
// project. A fresh shell turns that ambiguous failure into success
// and also makes retrying clone registration idempotent.
guard await recoverCreatedProject(
client: client,
projectID: projectID,
path: trimmed
) else {
throw error
}
return
}
do {
try await refresh(client: client)
} catch {
guard await recoverCreatedProject(
client: client,
projectID: projectID,
path: trimmed
) else {
throw error
}
}
}
private func recoverCreatedProject(
client: T3Client,
projectID: String,
path: String
) async -> Bool {
let environment = client.environment
let generation = environmentGeneration
guard let shell = try? await client.shellSnapshot(),
isKnownClient(client, environmentID: environment.id, generation: generation),
shell.projects.contains(where: {
$0.id == projectID
|| ProjectCreationPath.normalizedForComparison($0.workspaceRoot)
== ProjectCreationPath.normalizedForComparison(path)
}) else {
return false
}
shellsByEnvironmentID[environment.id] = shell
if activeEnvironment?.id == environment.id {
latestShell = shell
}
rebuildEntityIndexes((try? await runtime.environments()) ?? [environment])
await emitSnapshot(shell, environment: environment)
return true
}
func listWorkspaceBranches(
@@ -358,13 +436,26 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
) async throws -> [FeatureWorkspaceBranch] {
let route = try projectRoute(for: projectID)
let project = try project(for: route)
let result = try await route.client.listVCSRefs(
cwd: project.workspaceRoot,
refresh: refresh,
limit: 100
)
guard result.isRepo else { return [] }
return result.refs.map { ref in
var refs: [VCSRef] = []
var cursor: Int?
var seenCursors = Set<Int>()
repeat {
let result = try await route.client.listVCSRefs(
cwd: project.workspaceRoot,
cursor: cursor,
refresh: refresh && cursor == nil,
limit: 100
)
guard result.isRepo else { return [] }
refs.append(contentsOf: result.refs)
guard let nextCursor = result.nextCursor,
seenCursors.insert(nextCursor).inserted else {
break
}
cursor = nextCursor
} while true
return refs.map { ref in
FeatureWorkspaceBranch(
name: ref.name,
isRemote: ref.isRemote ?? false,
@@ -388,6 +479,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
let model = modelSelection(
selection,
projectID: route.wireID,
environmentID: environment.id,
shell: shellsByEnvironmentID[environment.id]
)
let resolvedTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -480,6 +572,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
let model = modelSelection(
selection,
projectID: route.wireID,
environmentID: environment.id,
shell: shellsByEnvironmentID[environment.id]
)
let title = Self.title(from: prompt, hasAttachments: !attachments.isEmpty)
@@ -545,7 +638,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
// but before its reply reaches us. Bootstrap expansion creates the
// thread before dispatching the stable final turn, so recover an
// interrupted empty thread by sending only that original turn.
guard try await recoverBootstrap(
let recovered = try await recoverBootstrap(
client: client,
pending: pending,
projectID: route.wireID,
@@ -554,7 +647,13 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
runtimeMode: runtime,
interactionMode: interaction,
attachments: uploads
) else {
)
guard recovered else {
await resetFailedBootstrapIfConfirmed(
client: client,
pending: pending,
projectCwd: routedProject.workspaceRoot
)
throw error
}
}
@@ -654,6 +753,41 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
return true
}
/// A failed bootstrap can leave its generated worktree behind after the
/// server rolls back the thread. Only reset the retry identity after a
/// fresh shell confirms the thread is absent; ambiguous network failures
/// keep the stable IDs so the normal recovery path remains idempotent.
private func resetFailedBootstrapIfConfirmed(
client: T3Client,
pending: PendingBootstrapSubmission,
projectCwd: String
) async {
guard let shell = try? await client.shellSnapshot(),
!shell.threads.contains(where: { $0.id == pending.threadID }) else {
return
}
if let branch = pending.worktreeBranchName,
let refs = try? await client.listVCSRefs(
cwd: projectCwd,
query: branch,
refresh: true,
limit: 100
),
let path = refs.refs.first(where: {
$0.name == branch && $0.isRemote != true
})?.worktreePath {
// Never force-remove: setup scripts may have left useful changes.
// A clean orphan is safe to reclaim; a dirty one remains visible
// through normal worktree management.
try? await client.removeWorktree(cwd: projectCwd, path: path)
}
if pendingBootstrapSubmission?.identity == pending.identity {
pendingBootstrapSubmission = nil
}
}
func renameThread(id: String, title: String) async throws {
let route = try threadRoute(for: id)
_ = try await route.client.rename(threadID: route.wireID, title: title)
@@ -1973,6 +2107,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
private func loadEnvironmentShells(
_ environments: [Environment]
) async -> [EnvironmentShellLoad] {
let activeEnvironmentID = activeEnvironment?.id
let environmentsWithCachedConfig = Set(serverConfigsByEnvironmentID.keys)
let runtime = runtime
var clients: [(environment: Environment, client: T3Client)] = []
clients.reserveCapacity(environments.count)
for environment in environments {
@@ -1984,9 +2121,36 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
return await withTaskGroup(of: EnvironmentShellLoad.self) { group in
for pair in clients {
group.addTask {
async let shell: OrchestrationShellSnapshot? = try? await pair.client.shellSnapshot()
async let config: ServerConfigSnapshot? = try? await pair.client.serverConfig()
return await EnvironmentShellLoad(
let shell = try? await pair.client.shellSnapshot()
guard shell != nil else {
return EnvironmentShellLoad(
environment: pair.environment,
client: pair.client,
shell: nil,
config: nil
)
}
let isActive = pair.environment.id == activeEnvironmentID
let shouldFetchConfig = isActive
|| !environmentsWithCachedConfig.contains(pair.environment.id)
var config: ServerConfigSnapshot?
if shouldFetchConfig {
if isActive {
config = try? await pair.client.serverConfig()
} else {
// A passive catalogue is a bounded one-shot RPC on
// an uncached client. Never disconnect the shared
// client because the environment may become active
// while this aggregate load is in flight.
let probe = await runtime.ephemeralClient(
for: pair.environment
)
config = try? await probe.serverConfig()
await probe.disconnect()
}
}
return EnvironmentShellLoad(
environment: pair.environment,
client: pair.client,
shell: shell,
@@ -3230,6 +3394,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
private func modelSelection(
_ selection: FeatureSelection?,
projectID: String,
environmentID: String,
shell: OrchestrationShellSnapshot?
) -> ModelSelection {
if let selection {
@@ -3240,16 +3405,84 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr
.defaultModelSelection {
return projectDefault
}
return defaultModelSelection()
return fallbackModelSelection(
environmentID: environmentID,
projectID: projectID,
shell: shell
)
}
private func defaultModelSelection() -> ModelSelection {
if let selection = loadSettings().defaultSelection {
/// Automatic selection is resolved against the target environment. This
/// matters when a passive machine exposes a different provider catalogue
/// than the currently active one.
private func fallbackModelSelection(
environmentID: String,
projectID: String?,
shell: OrchestrationShellSnapshot?
) -> ModelSelection {
let config = serverConfigsByEnvironmentID[environmentID]
let appSelection = loadSettings().defaultSelection
if let selection = appSelection, let config {
if configSupports(selection, config: config) {
return coreModelSelection(selection)
}
}
if let configuredDefault = defaultModelSelection(in: config) {
return configuredDefault
}
if let projectID,
let recentProjectSelection = shell?.threads
.first(where: { $0.projectId == projectID })?
.modelSelection {
return recentProjectSelection
}
if let knownSelection = shell?.projects.compactMap(\.defaultModelSelection).first
?? shell?.threads.first?.modelSelection {
return knownSelection
}
if let selection = appSelection {
return coreModelSelection(selection)
}
return ModelSelection(instanceId: "codex", model: "gpt-5.6-sol")
}
private func configSupports(
_ selection: FeatureSelection,
config: ServerConfigSnapshot
) -> Bool {
config.providers.contains { provider in
provider.instanceId == selection.providerID
&& providerCanRun(provider)
&& provider.models.contains { $0.slug == selection.modelID }
}
}
private func defaultModelSelection(
in config: ServerConfigSnapshot?
) -> ModelSelection? {
guard let providers = config?.providers else { return nil }
for provider in providers where providerCanRun(provider) {
if let model = provider.models.first(where: { $0.isDefault == true }) {
return ModelSelection(instanceId: provider.instanceId, model: model.slug)
}
}
for provider in providers where providerCanRun(provider) {
if let model = provider.models.first {
return ModelSelection(instanceId: provider.instanceId, model: model.slug)
}
}
return nil
}
private func providerCanRun(_ provider: ServerProviderSnapshot) -> Bool {
provider.enabled
&& provider.installed
&& provider.status != "disabled"
&& provider.status != "error"
&& provider.auth.status != "unauthenticated"
&& provider.availability != "unavailable"
}
private func coreModelSelection(_ selection: FeatureSelection) -> ModelSelection {
let options = selection.options.map { option in
ModelSelection.OptionSelection(
+12
View File
@@ -1005,6 +1005,18 @@ public actor EnvironmentRuntime {
clients[environment.id] = client
return client
}
/// Creates an uncached client for bounded one-shot WebSocket RPCs. Passive
/// environment probes must not stop or mutate the shared client if that
/// environment becomes active while the probe is in flight.
public func ephemeralClient(for environment: Environment) -> T3Client {
T3Client(
environment: environment,
credentialStore: credentialStore,
httpTransport: httpTransport,
webSocketConnector: webSocketConnector
)
}
}
public enum RPCMethod: String, Sendable {
@@ -1,6 +1,13 @@
import SwiftUI
public struct AddProjectView: View {
private struct PendingCloneRegistration: Equatable {
let environmentID: String
let remoteURL: String
let destinationPath: String
let clonedPath: String
}
private enum ProjectMode: String, CaseIterable, Identifiable {
case folder
case repository
@@ -27,18 +34,22 @@ public struct AddProjectView: View {
@State private var destinationPath = "~/"
@State private var resolvedRepository: SourceControlRepositoryInfo?
@State private var didEditDestination = false
@State private var pendingCloneRegistration: PendingCloneRegistration?
@State private var browsePath = "~/"
@State private var browseResult: FilesystemBrowseResult?
@State private var isBrowsing = false
@State private var browseError: String?
@State private var browseRequestID: UUID?
@State private var discovery: SourceControlDiscoveryResult?
@State private var isDiscovering = false
@State private var discoveryError: String?
@State private var discoveryRequestID: UUID?
@State private var isSubmitting = false
@State private var errorMessage: String?
@State private var cloneRequestID: UUID?
@FocusState private var focusedField: Field?
public init(model: FeatureRootModel) {
@@ -98,11 +109,15 @@ public struct AddProjectView: View {
}
.onChange(of: source) {
resolvedRepository = nil
pendingCloneRegistration = nil
cloneRequestID = nil
updateSuggestedDestination()
errorMessage = nil
}
.onChange(of: repositoryInput) {
resolvedRepository = nil
pendingCloneRegistration = nil
cloneRequestID = nil
updateSuggestedDestination()
errorMessage = nil
}
@@ -236,7 +251,12 @@ public struct AddProjectView: View {
text: $localPath,
field: .localPath,
browseAction: {
Task { await loadDirectory(localPath, updateSelection: false) }
Task {
await loadDirectory(
ProjectCreationPath.directoryBrowsePath(localPath),
updateSelection: false
)
}
}
)
primaryAction(label: "Add project", icon: "plus") {
@@ -414,9 +434,7 @@ public struct AddProjectView: View {
.foregroundStyle(T3Colors.warning)
.padding(.vertical, 8)
}
if let parentPath = browseResult?.parentPath,
ProjectCreationPath.normalizedForComparison(parentPath)
!= ProjectCreationPath.normalizedForComparison(browsePath) {
if let parentPath = ProjectCreationPath.parentBrowsePath(of: browsePath) {
folderRow(name: "..", icon: "arrow.turn.left.up") {
await loadDirectory(parentPath, updateSelection: true)
}
@@ -425,7 +443,10 @@ public struct AddProjectView: View {
ForEach(entries, id: \.fullPath) { entry in
Divider().overlay(T3Colors.separator)
folderRow(name: entry.name, icon: "folder") {
await loadDirectory(entry.fullPath, updateSelection: true)
await loadDirectory(
ProjectCreationPath.directoryBrowsePath(entry.fullPath),
updateSelection: true
)
}
}
} else if !isBrowsing, browseError == nil {
@@ -464,6 +485,7 @@ public struct AddProjectView: View {
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.disabled(isBrowsing)
}
private func sectionTitle(_ title: String) -> some View {
@@ -543,6 +565,8 @@ public struct AddProjectView: View {
set: { value in
didEditDestination = true
destinationPath = value
pendingCloneRegistration = nil
cloneRequestID = nil
}
)
}
@@ -568,10 +592,14 @@ public struct AddProjectView: View {
browsePath = "~/"
browseResult = nil
browseError = nil
browseRequestID = nil
discovery = nil
discoveryError = nil
discoveryRequestID = nil
source = .url
resolvedRepository = nil
pendingCloneRegistration = nil
cloneRequestID = nil
didEditDestination = false
localPath = "~/"
destinationPath = repositoryInput.isEmpty
@@ -586,16 +614,31 @@ public struct AddProjectView: View {
discoveryError = "Git URL cloning is available. Provider discovery is unavailable."
return
}
let requestID = UUID()
discoveryRequestID = requestID
isDiscovering = true
defer { isDiscovering = false }
defer {
if discoveryRequestID == requestID {
isDiscovering = false
}
}
do {
discovery = try await projectClient.discoverProjectSources(
let result = try await projectClient.discoverProjectSources(
environmentID: environmentID
)
guard discoveryRequestID == requestID,
selectedEnvironmentID == environmentID else {
return
}
discovery = result
discoveryError = nil
} catch is CancellationError {
return
} catch {
guard discoveryRequestID == requestID,
selectedEnvironmentID == environmentID else {
return
}
discovery = nil
discoveryError = "Provider discovery unavailable. Git URL still works."
}
@@ -609,26 +652,37 @@ public struct AddProjectView: View {
}
let requestedPath = path.trimmingCharacters(in: .whitespacesAndNewlines)
guard !requestedPath.isEmpty else { return }
let requestID = UUID()
browseRequestID = requestID
isBrowsing = true
browseError = nil
defer { isBrowsing = false }
defer {
if browseRequestID == requestID {
isBrowsing = false
}
}
do {
let result = try await projectClient.browseProjectFolders(
environmentID: environmentID,
partialPath: requestedPath
)
guard selectedEnvironmentID == environmentID else { return }
browsePath = requestedPath
guard browseRequestID == requestID,
selectedEnvironmentID == environmentID else {
return
}
let selectedDirectory = result.parentPath
browsePath = ProjectCreationPath.directoryBrowsePath(selectedDirectory)
browseResult = result
if updateSelection {
switch mode {
case .folder:
localPath = requestedPath
localPath = selectedDirectory
case .repository:
if !didEditDestination {
pendingCloneRegistration = nil
destinationPath = ProjectCreationPath.appending(
repositoryName,
to: requestedPath
to: selectedDirectory
)
}
}
@@ -636,6 +690,10 @@ public struct AddProjectView: View {
} catch is CancellationError {
return
} catch {
guard browseRequestID == requestID,
selectedEnvironmentID == environmentID else {
return
}
browseError = "Couldn’t browse that folder. Direct path entry still works."
}
}
@@ -649,6 +707,14 @@ public struct AddProjectView: View {
errorMessage = error.localizedDescription
return
}
if let serverPath = browseResult?.parentPath,
!ProjectCreationPath.isCompatibleWithServerPath(
validated,
serverPath: serverPath
) {
errorMessage = "Use a path that matches \(environment.name)’s filesystem."
return
}
if let existing = existingProject(environmentID: environment.id, path: validated) {
errorMessage = "\(existing.name) already uses this folder."
return
@@ -691,16 +757,29 @@ public struct AddProjectView: View {
isSubmitting = true
defer { isSubmitting = false }
do {
resolvedRepository = try await projectClient.lookupProjectRepository(
let result = try await projectClient.lookupProjectRepository(
environmentID: environment.id,
provider: provider,
repository: repository
)
guard selectedEnvironmentID == environment.id,
source.provider == provider,
repositoryInput.trimmingCharacters(in: .whitespacesAndNewlines)
== repository else {
return
}
resolvedRepository = result
updateSuggestedDestination()
focusedField = .destination
} catch is CancellationError {
return
} catch {
guard selectedEnvironmentID == environment.id,
source.provider == provider,
repositoryInput.trimmingCharacters(in: .whitespacesAndNewlines)
== repository else {
return
}
errorMessage = projectErrorMessage(error)
}
}
@@ -719,6 +798,14 @@ public struct AddProjectView: View {
errorMessage = error.localizedDescription
return
}
if let serverPath = browseResult?.parentPath,
!ProjectCreationPath.isCompatibleWithServerPath(
validatedDestination,
serverPath: serverPath
) {
errorMessage = "Use a path that matches \(environment.name)’s filesystem."
return
}
if let existing = existingProject(
environmentID: environment.id,
path: validatedDestination
@@ -732,22 +819,100 @@ public struct AddProjectView: View {
}
errorMessage = nil
let requestID = UUID()
cloneRequestID = requestID
isSubmitting = true
defer { isSubmitting = false }
defer {
isSubmitting = false
if cloneRequestID == requestID {
cloneRequestID = nil
}
}
do {
_ = try await projectClient.cloneProjectRepository(
let clonedPath: String
if let pending = pendingCloneRegistration,
pending.environmentID == environment.id,
pending.remoteURL == remoteURL,
pending.destinationPath == validatedDestination {
clonedPath = pending.clonedPath
} else {
let result = try await projectClient.cloneProjectRepository(
environmentID: environment.id,
remoteURL: remoteURL,
destinationPath: validatedDestination
)
guard cloneRequestIsCurrent(
requestID,
environmentID: environment.id,
remoteURL: remoteURL,
destinationPath: validatedDestination
) else {
return
}
clonedPath = result.cwd
pendingCloneRegistration = PendingCloneRegistration(
environmentID: environment.id,
remoteURL: remoteURL,
destinationPath: validatedDestination,
clonedPath: result.cwd
)
}
guard cloneRequestIsCurrent(
requestID,
environmentID: environment.id,
remoteURL: remoteURL,
destinationPath: validatedDestination
) else {
return
}
try await projectClient.addProject(
environmentID: environment.id,
path: clonedPath
)
guard cloneRequestIsCurrent(
requestID,
environmentID: environment.id,
remoteURL: remoteURL,
destinationPath: validatedDestination
) else {
return
}
pendingCloneRegistration = nil
dismiss()
} catch is CancellationError {
return
} catch {
errorMessage = projectErrorMessage(error)
guard cloneRequestIsCurrent(
requestID,
environmentID: environment.id,
remoteURL: remoteURL,
destinationPath: validatedDestination
) else {
return
}
if pendingCloneRegistration != nil {
errorMessage = "Repository cloned. Try again to finish adding the project."
} else {
errorMessage = projectErrorMessage(error)
}
}
}
private func cloneRequestIsCurrent(
_ requestID: UUID,
environmentID: String,
remoteURL: String,
destinationPath: String
) -> Bool {
let currentRemoteURL = resolvedRepository?.sshUrl
?? repositoryInput.trimmingCharacters(in: .whitespacesAndNewlines)
return cloneRequestID == requestID
&& selectedEnvironmentID == environmentID
&& currentRemoteURL == remoteURL
&& self.destinationPath.trimmingCharacters(in: .whitespacesAndNewlines)
== destinationPath
}
private func updateSuggestedDestination() {
guard !didEditDestination, !repositoryInput.isEmpty else { return }
destinationPath = ProjectCreationPath.appending(repositoryName, to: browsePath)
@@ -155,14 +155,91 @@ enum ProjectCreationPath {
return base + separator + component
}
/// `filesystem.browse` interprets a path without a trailing separator as
/// a prefix search. Directory navigation always sends an explicit folder.
static func directoryBrowsePath(_ value: String) -> String {
let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
guard !path.isEmpty,
!path.hasSuffix("/"),
!path.hasSuffix("\\") else {
return path
}
if isWindowsAbsolutePath(path) {
return path.replacingOccurrences(of: "/", with: "\\") + "\\"
}
return path + "/"
}
static func parentBrowsePath(of value: String) -> String? {
let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
guard !path.isEmpty else { return nil }
if isWindowsAbsolutePath(path) {
let normalized = path.replacingOccurrences(of: "/", with: "\\")
if normalized.hasPrefix("\\\\") {
let components = normalized.dropFirst(2).split(separator: "\\")
guard components.count > 2 else { return nil }
return "\\\\"
+ components.dropLast().joined(separator: "\\")
+ "\\"
}
var trimmed = normalized
while trimmed.count > 3, trimmed.hasSuffix("\\") {
trimmed.removeLast()
}
guard trimmed.count > 3,
let separator = trimmed.lastIndex(of: "\\") else {
return nil
}
let parent = String(trimmed[...separator])
return parent.count == 3 ? parent : directoryBrowsePath(parent)
}
var trimmed = path
while trimmed.count > 1, trimmed.hasSuffix("/") {
trimmed.removeLast()
}
guard trimmed != "/", trimmed != "~",
let separator = trimmed.lastIndex(of: "/") else {
return nil
}
let parent = String(trimmed[...separator])
guard parent != "~/" || trimmed != "~" else { return nil }
return directoryBrowsePath(parent)
}
static func lastPathComponent(_ value: String) -> String {
let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
let normalized = isWindowsAbsolutePath(path)
? path.replacingOccurrences(of: "\\", with: "/")
: path
return normalized
.split(separator: "/", omittingEmptySubsequences: true)
.last
.map(String.init) ?? path
}
static func isCompatibleWithServerPath(_ value: String, serverPath: String) -> Bool {
let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
let reference = serverPath.trimmingCharacters(in: .whitespacesAndNewlines)
guard !path.hasPrefix("~"),
isAbsoluteOrHomeRelative(reference) else {
return true
}
return isWindowsAbsolutePath(path) == isWindowsAbsolutePath(reference)
}
static func normalizedForComparison(_ value: String) -> String {
var normalized = value
.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: "\\", with: "/")
let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
let isWindows = isWindowsAbsolutePath(path)
var normalized = isWindows
? path.replacingOccurrences(of: "\\", with: "/")
: path
while normalized.count > 1, normalized.hasSuffix("/") {
normalized.removeLast()
}
return normalized.lowercased()
return isWindows ? normalized.lowercased() : normalized
}
private static func isAbsoluteOrHomeRelative(_ path: String) -> Bool {
@@ -172,6 +249,11 @@ enum ProjectCreationPath {
if path.hasPrefix("/") || path.hasPrefix("\\\\") {
return true
}
return isWindowsAbsolutePath(path)
}
private static func isWindowsAbsolutePath(_ path: String) -> Bool {
if path.hasPrefix("\\\\") || path.hasPrefix("//") { return true }
let scalars = Array(path.unicodeScalars.prefix(3))
return scalars.count == 3
&& CharacterSet.letters.contains(scalars[0])
@@ -40,6 +40,84 @@ struct ProjectCreationModelsTests {
ProjectCreationPath.normalizedForComparison(#"C:\Work\T3Code\"#)
== "c:/work/t3code"
)
#expect(ProjectCreationPath.normalizedForComparison("/srv/App") == "/srv/App")
#expect(ProjectCreationPath.normalizedForComparison(#"/srv/a\b"#) == #"/srv/a\b"#)
}
@Test
func folderBrowseQueriesNavigateDirectoriesInsteadOfPrefixSearching() {
#expect(ProjectCreationPath.directoryBrowsePath("~/work") == "~/work/")
#expect(ProjectCreationPath.directoryBrowsePath("/srv/t3code/") == "/srv/t3code/")
#expect(
ProjectCreationPath.directoryBrowsePath(#"C:\work\t3code"#)
== #"C:\work\t3code\"#
)
#expect(ProjectCreationPath.parentBrowsePath(of: "~/work/t3code/") == "~/work/")
#expect(ProjectCreationPath.parentBrowsePath(of: "~/") == nil)
#expect(ProjectCreationPath.parentBrowsePath(of: "/srv/t3code/") == "/srv/")
#expect(ProjectCreationPath.parentBrowsePath(of: "/") == nil)
#expect(
ProjectCreationPath.parentBrowsePath(of: #"C:\work\t3code\"#)
== #"C:\work\"#
)
#expect(ProjectCreationPath.parentBrowsePath(of: #"C:\"#) == nil)
#expect(
ProjectCreationPath.parentBrowsePath(of: #"\\server\share\folder\"#)
== #"\\server\share\"#
)
#expect(ProjectCreationPath.parentBrowsePath(of: #"\\server\share\"#) == nil)
#expect(
ProjectCreationPath.directoryBrowsePath("//server/share/folder")
== #"\\server\share\folder\"#
)
}
@Test
func projectTitlesHandleServerPathStyles() {
#expect(ProjectCreationPath.lastPathComponent("/srv/t3code/") == "t3code")
#expect(ProjectCreationPath.lastPathComponent(#"C:\work\t3code\"#) == "t3code")
#expect(ProjectCreationPath.lastPathComponent(#"\\server\share\t3code"#) == "t3code")
}
@Test
func explicitPathsMatchTheConnectedServerFilesystemStyle() {
#expect(
ProjectCreationPath.isCompatibleWithServerPath(
"/srv/t3code",
serverPath: "/srv"
)
)
#expect(
!ProjectCreationPath.isCompatibleWithServerPath(
#"C:\work\t3code"#,
serverPath: "/srv"
)
)
#expect(
ProjectCreationPath.isCompatibleWithServerPath(
#"C:\work\t3code"#,
serverPath: #"C:\work"#
)
)
#expect(
ProjectCreationPath.isCompatibleWithServerPath(
"//server/share/t3code",
serverPath: #"C:\work"#
)
)
#expect(
!ProjectCreationPath.isCompatibleWithServerPath(
"/srv/t3code",
serverPath: #"C:\work"#
)
)
#expect(
ProjectCreationPath.isCompatibleWithServerPath(
"~/work/t3code",
serverPath: #"C:\Users\theo"#
)
)
}
@Test