Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,17 @@ enum FinderServicePathResolver {
return canonical
}

private static func normalizedComparisonURL(_ url: URL) -> URL {
url.standardizedFileURL.resolvingSymlinksInPath()
}

private static func isSameOrDescendant(_ url: URL, of rootURL: URL) -> Bool {
let urlPathComponents = normalizedComparisonURL(url).pathComponents
let rootPathComponents = normalizedComparisonURL(rootURL).pathComponents
guard urlPathComponents.count >= rootPathComponents.count else { return false }
return Array(urlPathComponents.prefix(rootPathComponents.count)) == rootPathComponents
}
Comment on lines +429 to +438

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 normalizedComparisonURL for excluded root recomputed per-input-URL

isSameOrDescendant(_:of:) is called inside an inner closure (excludedRootURLs.contains(where:)), so normalizedComparisonURL(rootURL) — which calls resolvingSymlinksInPath() (a synchronous filesystem stat chain) — is re-executed on the same excludedRootURL once for every URL in the input array.

For the typical launch-time use (excludedRootURLs = [Bundle.main.bundleURL], a handful of URLs), the overhead is negligible. But the current shape makes it easy for a future caller to pass a large pathURLs array and unknowingly amplify the I/O. Pre-computing the normalised roots before the loop would eliminate the redundancy at zero semantic cost.


private static func resolvedDirectoryURL(from url: URL) -> URL {
let standardized = url.standardizedFileURL
if standardized.hasDirectoryPath {
Expand All @@ -438,12 +449,18 @@ enum FinderServicePathResolver {
return standardized.deletingLastPathComponent()
}

static func orderedUniqueDirectories(from pathURLs: [URL]) -> [String] {
static func orderedUniqueDirectories(
from pathURLs: [URL],
excludingDescendantsOf excludedRootURLs: [URL] = []
) -> [String] {
var seen: Set<String> = []
var directories: [String] = []

for url in pathURLs {
let directoryURL = resolvedDirectoryURL(from: url)
guard !excludedRootURLs.contains(where: { isSameOrDescendant(directoryURL, of: $0) }) else {
continue
}
let path = canonicalDirectoryPath(directoryURL.path(percentEncoded: false))
guard !path.isEmpty else { continue }
if seen.insert(path).inserted {
Expand Down Expand Up @@ -5687,8 +5704,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
target: ServiceOpenTarget,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
prepareForExplicitOpenIntentAtStartup()

let pathURLs = servicePathURLs(from: pasteboard)
guard !pathURLs.isEmpty else {
error.pointee = Self.serviceErrorNoPath
Expand All @@ -5701,6 +5716,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
return
}

prepareForExplicitOpenIntentAtStartup()
for directory in directories {
switch target {
case .window:
Expand Down Expand Up @@ -5755,7 +5771,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
}

private func externalOpenDirectories(from urls: [URL]) -> [String] {
FinderServicePathResolver.orderedUniqueDirectories(from: urls.filter { $0.isFileURL })
// LaunchServices can surface the running app bundle on relaunch; ignore self paths so
// they do not get treated as explicit folder opens and suppress session restore.
FinderServicePathResolver.orderedUniqueDirectories(
from: urls.filter { $0.isFileURL },
excludingDescendantsOf: [Bundle.main.bundleURL]
)
}

private func openWorkspaceForExternalDirectory(
Expand Down
103 changes: 103 additions & 0 deletions cmuxTests/OmnibarAndToolsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ import UserNotifications
#endif

final class FinderServicePathResolverTests: XCTestCase {
private func withTemporaryDirectory<T>(_ body: (URL) throws -> T) throws -> T {
let root = FileManager.default.temporaryDirectory.appendingPathComponent(
"cmux-finder-service-tests-\(UUID().uuidString)",
isDirectory: true
)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
return try body(root)
}

func testOrderedUniqueDirectoriesUsesParentForFilesAndDedupes() {
let input: [URL] = [
URL(fileURLWithPath: "/tmp/cmux-services/project", isDirectory: true),
Expand Down Expand Up @@ -49,6 +59,99 @@ final class FinderServicePathResolverTests: XCTestCase {
]
)
}

func testOrderedUniqueDirectoriesSkipsBundleAndEmbeddedPathsWhenExcludingBundleRoot() {
let bundleURL = URL(fileURLWithPath: "/Applications/Tools/../cmux.app", isDirectory: true)
let input: [URL] = [
bundleURL,
URL(fileURLWithPath: "/Applications/cmux.app/Contents/MacOS/cmux", isDirectory: false),
URL(fileURLWithPath: "/Applications/cmux.app/Contents/Resources/bin/cmux", isDirectory: false),
URL(fileURLWithPath: "/Users/tester/Projects/cmux", isDirectory: true),
URL(fileURLWithPath: "/Users/tester/Projects/cmux/README.md", isDirectory: false),
]

let directories = FinderServicePathResolver.orderedUniqueDirectories(
from: input,
excludingDescendantsOf: [bundleURL]
)

XCTAssertEqual(
directories,
[
"/Users/tester/Projects/cmux",
]
)
}

func testOrderedUniqueDirectoriesExclusionDoesNotFilterSiblingPaths() {
let bundleURL = URL(fileURLWithPath: "/Applications/cmux.app", isDirectory: true)
let input: [URL] = [
URL(fileURLWithPath: "/Applications/cmux.app backup/project", isDirectory: true),
URL(fileURLWithPath: "/Applications/cmux.app.beta/project/file.txt", isDirectory: false),
]

let directories = FinderServicePathResolver.orderedUniqueDirectories(
from: input,
excludingDescendantsOf: [bundleURL]
)

XCTAssertEqual(
directories,
[
"/Applications/cmux.app backup/project",
"/Applications/cmux.app.beta/project",
]
)
}

func testOrderedUniqueDirectoriesPreservesSymlinkAliasPaths() throws {
try withTemporaryDirectory { root in
let actualDirectory = root.appendingPathComponent("actual/project", isDirectory: true)
let aliasDirectory = root.appendingPathComponent("alias-project", isDirectory: true)
let actualFile = actualDirectory.appendingPathComponent("README.md", isDirectory: false)
let aliasFile = aliasDirectory.appendingPathComponent("README.md", isDirectory: false)

try FileManager.default.createDirectory(at: actualDirectory, withIntermediateDirectories: true)
FileManager.default.createFile(atPath: actualFile.path, contents: Data())
try FileManager.default.createSymbolicLink(at: aliasDirectory, withDestinationURL: actualDirectory)

let directories = FinderServicePathResolver.orderedUniqueDirectories(
from: [aliasDirectory, aliasFile]
)

XCTAssertEqual(directories, [aliasDirectory.standardizedFileURL.path])
XCTAssertNotEqual(directories, [actualDirectory.standardizedFileURL.path])
}
}

func testOrderedUniqueDirectoriesResolvesSymlinksOnlyForExcludedRootComparison() throws {
try withTemporaryDirectory { root in
let applicationsDirectory = root.appendingPathComponent("Applications", isDirectory: true)
let actualBundle = applicationsDirectory.appendingPathComponent("cmux.app", isDirectory: true)
let actualBinary = actualBundle.appendingPathComponent("Contents/MacOS/cmux", isDirectory: false)
let aliasApplications = root.appendingPathComponent("Launcher", isDirectory: true)
let aliasWorkspace = aliasApplications.appendingPathComponent("workspace", isDirectory: true)

try FileManager.default.createDirectory(at: actualBinary.deletingLastPathComponent(), withIntermediateDirectories: true)
FileManager.default.createFile(atPath: actualBinary.path, contents: Data())
try FileManager.default.createDirectory(
at: applicationsDirectory.appendingPathComponent("workspace", isDirectory: true),
withIntermediateDirectories: true
)
try FileManager.default.createSymbolicLink(at: aliasApplications, withDestinationURL: applicationsDirectory)

let directories = FinderServicePathResolver.orderedUniqueDirectories(
from: [
aliasApplications.appendingPathComponent("cmux.app", isDirectory: true),
aliasApplications.appendingPathComponent("cmux.app/Contents/MacOS/cmux", isDirectory: false),
aliasWorkspace,
],
excludingDescendantsOf: [actualBundle]
)

XCTAssertEqual(directories, [aliasWorkspace.standardizedFileURL.path])
}
}
}


Expand Down
33 changes: 33 additions & 0 deletions cmuxTests/WindowAndDragTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,39 @@ final class AppDelegateWindowContextRoutingTests: XCTestCase {
XCTAssertNotNil(createdWorkspace)
XCTAssertEqual(createdWorkspace?.currentDirectory, droppedDirectory.path)
}

func testApplicationOpenURLsIgnoresBundleSelfPaths() {
_ = NSApplication.shared
let app = AppDelegate()

let windowId = UUID()
let window = makeMainWindow(id: windowId)
defer { window.orderOut(nil) }

let manager = TabManager()
app.registerMainWindow(
window,
windowId: windowId,
tabManager: manager,
sidebarState: SidebarState(),
sidebarSelectionState: SidebarSelectionState()
)

window.makeKeyAndOrderFront(nil)
_ = app.synchronizeActiveMainWindowContext(preferredWindow: window)

let existingWorkspaceIds = Set(manager.tabs.map(\.id))
let embeddedExecutableURL = Bundle.main.bundleURL
.appendingPathComponent("Contents/MacOS/cmux", isDirectory: false)

app.application(
NSApplication.shared,
open: [embeddedExecutableURL]
)

let createdWorkspace = manager.tabs.first { !existingWorkspaceIds.contains($0.id) }
XCTAssertNil(createdWorkspace)
}
Comment on lines +233 to +264

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Stabilize onboarding preconditions so this regression can’t pass for the wrong reason.

If first-run onboarding suppresses application(_:open:) routing, this test can pass even when bundle-self filtering regresses. Mirror the welcome-key setup used in the dropped-folder test to isolate the intended behavior.

Suggested patch
     func testApplicationOpenURLsIgnoresBundleSelfPaths() {
         _ = NSApplication.shared
         let app = AppDelegate()
@@
         window.makeKeyAndOrderFront(nil)
         _ = app.synchronizeActiveMainWindowContext(preferredWindow: window)

+        let defaults = UserDefaults.standard
+        let previousWelcomeShown = defaults.object(forKey: WelcomeSettings.shownKey)
+        defaults.set(true, forKey: WelcomeSettings.shownKey)
+        defer {
+            if let previousWelcomeShown {
+                defaults.set(previousWelcomeShown, forKey: WelcomeSettings.shownKey)
+            } else {
+                defaults.removeObject(forKey: WelcomeSettings.shownKey)
+            }
+        }
+
         let existingWorkspaceIds = Set(manager.tabs.map(\.id))
         let embeddedExecutableURL = Bundle.main.bundleURL
             .appendingPathComponent("Contents/MacOS/cmux", isDirectory: false)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmuxTests/WindowAndDragTests.swift` around lines 233 - 264, The test
testApplicationOpenURLsIgnoresBundleSelfPaths can falsely pass if first-run
onboarding suppresses application(_:open:), so before creating AppDelegate add
the same onboarding/welcome-key setup used in the dropped-folder test to mark
onboarding as completed (i.e., set the same UserDefaults key the dropped-folder
test sets), placing that UserDefaults write before instantiating app =
AppDelegate() so application(_:open:) is exercised normally and the bundle-self
filtering logic in application(_:open:) is actually tested.

Comment on lines +233 to +264

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Missing welcome-screen suppression guard

The existing testApplicationOpenURLsCreatesWorkspaceForDroppedDirectory test (lines 184–231 just above) explicitly suppresses the welcome-tab by writing to UserDefaults.standard before calling app.application(_:open:), then restores it in a defer. That guard was presumably added because, in a fresh CI environment where the welcome screen has never been shown, some AppDelegate init path can add an extra tab after the existingWorkspaceIds snapshot.

This new test skips that guard. Since the snapshot is captured before the call under test, any welcome-generated tab that appears after the snapshot would cause a false XCTAssertNil failure. Adding the same UserDefaults setup-and-restore block (before the existingWorkspaceIds snapshot) would make this test consistent with the established pattern and eliminate that potential flake.

}


Expand Down
Loading