Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
25 changes: 22 additions & 3 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -417,11 +417,13 @@ enum TerminalDirectoryOpenTarget: String, CaseIterable {
let homeDirectoryPath: String
let fileExistsAtPath: (String) -> Bool
let isExecutableFileAtPath: (String) -> Bool
let applicationPathForName: (String) -> String?

static let live = DetectionEnvironment(
homeDirectoryPath: FileManager.default.homeDirectoryForCurrentUser.path,
fileExistsAtPath: { FileManager.default.fileExists(atPath: $0) },
isExecutableFileAtPath: { FileManager.default.isExecutableFile(atPath: $0) }
isExecutableFileAtPath: { FileManager.default.isExecutableFile(atPath: $0) },
applicationPathForName: { NSWorkspace.shared.fullPath(forApplication: $0) }
)
}

Expand All @@ -433,8 +435,6 @@ enum TerminalDirectoryOpenTarget: String, CaseIterable {
Set(commandPaletteShortcutTargets.filter { $0.isAvailable(in: environment) })
}

static let cachedLiveAvailableTargets: Set<Self> = availableTargets(in: .live)

var commandPaletteCommandId: String {
"palette.terminalOpenDirectory.\(rawValue)"
}
Expand Down Expand Up @@ -524,6 +524,17 @@ enum TerminalDirectoryOpenTarget: String, CaseIterable {
for path in expandedCandidatePaths(in: environment) where environment.fileExistsAtPath(path) {
return path
}

// Fall back to LaunchServices so apps outside the standard bundle paths
// still appear in the command palette.
for applicationName in applicationSearchNames {
guard let resolvedPath = environment.applicationPathForName(applicationName),
environment.fileExistsAtPath(resolvedPath) else {
continue
}
return resolvedPath
}

return nil
}

Expand All @@ -543,6 +554,14 @@ enum TerminalDirectoryOpenTarget: String, CaseIterable {
return uniquePreservingOrder(expanded)
}

private var applicationSearchNames: [String] {
uniquePreservingOrder(
applicationBundlePathCandidates.map {
URL(fileURLWithPath: $0).deletingPathExtension().lastPathComponent
}
)
}

private var applicationBundlePathCandidates: [String] {
switch self {
case .androidStudio:
Expand Down
3 changes: 1 addition & 2 deletions Sources/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4803,7 +4803,7 @@ struct ContentView: View {
snapshot.setBool(CommandPaletteContextKeys.panelHasUnread, hasUnread)

if panelIsTerminal {
let availableTargets = TerminalDirectoryOpenTarget.cachedLiveAvailableTargets
let availableTargets = TerminalDirectoryOpenTarget.availableTargets()
for target in TerminalDirectoryOpenTarget.commandPaletteShortcutTargets {
snapshot.setBool(
CommandPaletteContextKeys.terminalOpenTargetAvailable(target),
Expand Down Expand Up @@ -5372,7 +5372,6 @@ struct ContentView: View {
keywords: target.commandPaletteKeywords,
when: { context in
context.bool(CommandPaletteContextKeys.panelIsTerminal)
&& context.bool(CommandPaletteContextKeys.terminalOpenTargetAvailable(target))
}
)
)
Expand Down
40 changes: 36 additions & 4 deletions cmuxTests/CmuxWebViewKeyEquivalentTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7667,12 +7667,14 @@ final class FinderServicePathResolverTests: XCTestCase {
final class TerminalDirectoryOpenTargetAvailabilityTests: XCTestCase {
private func environment(
existingPaths: Set<String>,
homeDirectoryPath: String = "/Users/tester"
homeDirectoryPath: String = "/Users/tester",
applicationPathsByName: [String: String] = [:]
) -> TerminalDirectoryOpenTarget.DetectionEnvironment {
TerminalDirectoryOpenTarget.DetectionEnvironment(
homeDirectoryPath: homeDirectoryPath,
fileExistsAtPath: { existingPaths.contains($0) },
isExecutableFileAtPath: { existingPaths.contains($0) }
isExecutableFileAtPath: { existingPaths.contains($0) },
applicationPathForName: { applicationPathsByName[$0] }
)
}

Expand Down Expand Up @@ -7711,9 +7713,10 @@ final class TerminalDirectoryOpenTargetAvailabilityTests: XCTestCase {
XCTAssertFalse(availableTargets.contains(.vscode))
}

func testVSCodeRequiresCodeTunnelExecutable() {
func testVSCodeInlineRequiresCodeTunnelExecutable() {
let env = environment(existingPaths: ["/Applications/Visual Studio Code.app"])
XCTAssertFalse(TerminalDirectoryOpenTarget.vscode.isAvailable(in: env))
XCTAssertTrue(TerminalDirectoryOpenTarget.vscode.isAvailable(in: env))
XCTAssertFalse(TerminalDirectoryOpenTarget.vscodeInline.isAvailable(in: env))
}

func testITerm2DetectsLegacyBundleName() {
Expand All @@ -7726,6 +7729,35 @@ final class TerminalDirectoryOpenTargetAvailabilityTests: XCTestCase {
XCTAssertTrue(TerminalDirectoryOpenTarget.tower.isAvailable(in: env))
}

func testAvailableTargetsFallbackToApplicationLookupForVSCodeAliasOutsideApplications() {
let vscodePath = "/Volumes/Tools/Code.app"
let env = environment(
existingPaths: [
vscodePath,
"\(vscodePath)/Contents/Resources/app/bin/code-tunnel",
],
applicationPathsByName: [
"Code": vscodePath,
]
)

let availableTargets = TerminalDirectoryOpenTarget.availableTargets(in: env)
XCTAssertTrue(availableTargets.contains(.vscode))
XCTAssertTrue(availableTargets.contains(.vscodeInline))
}

func testTowerDetectedViaApplicationLookupOutsideApplications() {
let towerPath = "/Volumes/Setapp/Tower.app"
let env = environment(
existingPaths: [towerPath],
applicationPathsByName: [
"Tower": towerPath,
]
)

XCTAssertTrue(TerminalDirectoryOpenTarget.tower.isAvailable(in: env))
}

func testCommandPaletteShortcutsExcludeGenericIDEEntry() {
let targets = TerminalDirectoryOpenTarget.commandPaletteShortcutTargets
XCTAssertFalse(targets.contains(where: { $0.commandPaletteTitle == "Open Current Directory in IDE" }))
Expand Down
104 changes: 104 additions & 0 deletions cmuxUITests/SidebarHelpMenuUITests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ final class CommandPaletteAllSurfacesUITests: XCTestCase {
private var socketPath = ""
private let hiddenSurfaceToken = "cmux-command-palette-hidden-surface"
private let visibleSurfaceToken = "cmux-command-palette-visible-surface"
private let noMatchWorkspaceQuery = "cmux-command-palette-no-match"

override func setUp() {
super.setUp()
Expand Down Expand Up @@ -475,6 +476,69 @@ final class CommandPaletteAllSurfacesUITests: XCTestCase {
)
}

func testSwitcherEmptyStateDoesNotBlinkWhileRefiningNoMatchQuery() throws {
let app = XCUIApplication()
app.launchArguments += ["-AppleLanguages", "(en)", "-AppleLocale", "en_US"]
app.launchEnvironment["CMUX_UI_TEST_MODE"] = "1"
app.launchEnvironment["CMUX_SOCKET_PATH"] = socketPath
launchAndActivate(app)

XCTAssertTrue(
sidebarHelpPollUntil(timeout: 8.0) {
app.windows.count >= 1
},
"Expected the main window to be visible"
)
XCTAssertTrue(waitForSocketPong(timeout: 12.0), "Expected control socket at \(socketPath)")

let mainWindowId = try XCTUnwrap(
socketCommand("current_window")?.trimmingCharacters(in: .whitespacesAndNewlines)
)
try seedWorkspaceSwitcherCorpus(workspaceCount: 96)

Comment on lines +497 to +498

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

Assert that the seeded switcher corpus is actually searchable before the no-match check.

seedWorkspaceSwitcherCorpus only sends new_workspace/workspace.rename; it never waits for those titles to land in switcher results. If indexing lags, this test can pass against the default workspace set and stop exercising the large-corpus path it is supposed to cover.

Also applies to: 670-698

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmuxUITests/SidebarHelpMenuUITests.swift` around lines 497 - 498, After
calling seedWorkspaceSwitcherCorpus(workspaceCount: 96) ensure the seeded
entries are actually indexed by polling the switcher search until at least one
known seeded workspace title appears (or until the expected count is returned)
before proceeding to the no-match assertion; implement this by performing the
same switcher search used later (e.g., call the switcher search helper or
getSwitcherResults/searchInSwitcher) in a retry loop with a timeout (or use an
XCTest expectation/XCTWaiter) and assert the presence of a seeded workspace
title or expected result count; update the same pattern for the other
occurrences (lines ~670-698) so the test fails if indexing didn’t complete
rather than silently using the default workspace set.

let searchField = app.textFields["CommandPaletteSearchField"]
app.typeKey("p", modifierFlags: [.command])
XCTAssertTrue(searchField.waitForExistence(timeout: 5.0), "Expected command palette search field")
searchField.click()

try debugTypeText(String(repeating: "z", count: 8))

let emptyLabel = app.staticTexts["No workspaces match your search."].firstMatch
XCTAssertTrue(
sidebarHelpPollUntil(timeout: 5.0) {
guard emptyLabel.exists else { return false }
guard let snapshot = commandPaletteSnapshot(windowId: mainWindowId) else { return false }
return (snapshot["query"] as? String) == String(repeating: "z", count: 8)
&& self.commandPaletteResultRows(from: snapshot).isEmpty
},
"Expected the switcher to reach a visible no-results state before refining the query"
)

try debugTypeText("z")

let emptyLabelDisappearedWhileRefining = sidebarHelpPollUntil(timeout: 0.5, pollInterval: 0.01) {
!emptyLabel.exists
}
XCTAssertFalse(
emptyLabelDisappearedWhileRefining,
"Expected refining an already-empty switcher query to keep the empty-state label visible"
)

let refinedSnapshot = try XCTUnwrap(
waitForCommandPaletteSnapshot(
windowId: mainWindowId,
query: String(repeating: "z", count: 9),
timeout: 5.0
) { snapshot in
self.commandPaletteResultRows(from: snapshot).isEmpty
}
)
Comment on lines +519 to +535

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

The no-blink assertion stops well before the refined query is allowed to settle.

You only watch the empty-state label for 0.5s, but the refined snapshot is allowed 5s to arrive. On slower CI, the label can disappear after that 0.5s window and this still passes. Keep the visibility check running until the 9-character snapshot is observed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmuxUITests/SidebarHelpMenuUITests.swift` around lines 519 - 535, The test
currently uses sidebarHelpPollUntil(timeout: 0.5, ...) to assert the emptyLabel
remains visible but then waits up to 5s for waitForCommandPaletteSnapshot(...)
to return refinedSnapshot, allowing the label to disappear after 0.5s on slow
CI; change the logic so the no-blink check runs until the refined snapshot is
observed: remove the fixed 0.5s timeout and instead poll
sidebarHelpPollUntil(...) continuously while
waitForCommandPaletteSnapshot(windowId: mainWindowId, query: String(repeating:
"z", count: 9), ...) is pending (or combine into a single poll condition that
returns true only when the refined snapshot is seen and the emptyLabel still
exists). Update references: emptyLabel, sidebarHelpPollUntil,
waitForCommandPaletteSnapshot, refinedSnapshot, and commandPaletteResultRows so
the empty-state visibility is asserted for the full duration of the refined
snapshot wait.

XCTAssertTrue(
commandPaletteResultRows(from: refinedSnapshot).isEmpty,
"Expected the refined no-match query to stay empty. snapshot=\(refinedSnapshot)"
)
}
Comment on lines +479 to +540

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 | 🟠 Major

This regression test is scoped to shared command-palette refresh behavior, not the open-target fix.

It locks a “no blink while refining” guarantee onto shared switcher refresh infrastructure, so this PR now depends on a broader UX behavior that maintainers have explicitly asked to keep out of feature-scoped changes.

Based on learnings, "scheduleCommandPaletteResultsRefresh(forceSearchCorpusRefresh:) is shared command‑palette infrastructure across all submenus. Do not change its sync‑seeding behavior within feature‑scoped PRs; treat brief initial flashes as consistent with existing submenus. Any UX improvement ... should be implemented and tested globally in a dedicated follow‑up PR."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmuxUITests/SidebarHelpMenuUITests.swift` around lines 479 - 540, The test
testSwitcherEmptyStateDoesNotBlinkWhileRefiningNoMatchQuery asserts a global "no
blink while refining" UX guarantee that touches shared infrastructure
(scheduleCommandPaletteResultsRefresh(forceSearchCorpusRefresh:)); remove or
relax the specific visibility assertion that enforces emptyLabel never
disappearing (the sidebarHelpPollUntil/XCTAssertFalse block checking
emptyLabelDisappearedWhileRefining) so this PR only verifies the
open-target/scoped behavior: keep the setup, ensure the refined query still
yields no results (the waitForCommandPaletteSnapshot/assert that resultRows are
empty) but do not assert on the empty-state label visibility or modify
scheduleCommandPaletteResultsRefresh(forceSearchCorpusRefresh:)'s seeding
behavior.


private func launchAndActivate(_ app: XCUIApplication) {
app.launch()
XCTAssertTrue(
Expand Down Expand Up @@ -592,6 +656,46 @@ final class CommandPaletteAllSurfacesUITests: XCTestCase {
return UUID(uuidString: value) != nil ? value : nil
}

private func debugTypeText(_ text: String) throws {
let response = try XCTUnwrap(
socketJSON(
method: "debug.type",
params: ["text": text]
),
"Expected a response from debug.type"
)
XCTAssertEqual(response["ok"] as? Bool, true, "Expected debug.type to succeed. response=\(response)")
}

private func seedWorkspaceSwitcherCorpus(workspaceCount: Int) throws {
guard workspaceCount > 1 else { return }

for index in 1..<workspaceCount {
let workspaceId = try XCTUnwrap(
okUUID(from: socketCommand("new_workspace")),
"Expected new_workspace to return a workspace ID"
)
let title = "\(noMatchWorkspaceQuery)-\(index)-" + String(repeating: "workspace-", count: 8)
let response = try XCTUnwrap(
socketJSON(
method: "workspace.rename",
params: [
"workspace_id": workspaceId,
"title": title,
]
),
"Expected a response from workspace.rename"
)
XCTAssertEqual(
response["ok"] as? Bool,
true,
"Expected workspace.rename to succeed. response=\(response)"
)
}

XCTAssertEqual(socketCommand("select_workspace 0"), "OK")
}

private func socketCommand(_ command: String) -> String? {
ControlSocketClient(path: socketPath, responseTimeout: 2.0).sendLine(command)
}
Expand Down
Loading