Skip to content

Handle Cmd+O in handleCustomShortcut to prevent Documents folder open - #2034

Merged
lawrencecchen merged 4 commits into
manaflow-ai:mainfrom
anthhub:fix/cmd-o-opens-documents
Mar 25, 2026
Merged

lawrencecchen merged 4 commits into
manaflow-ai:mainfrom
anthhub:fix/cmd-o-opens-documents

Conversation

@anthhub

@anthhub anthhub commented Mar 24, 2026 •

Copy link
Copy Markdown

Summary

  • Cmd+O for "Open Folder" was only defined in the SwiftUI menu system
  • When the terminal is focused, SwiftUI's performKeyEquivalent can fail due to known focus bugs, causing AppKit's default NSDocumentController to handle the event and open the Documents folder
  • Fix: intercept Cmd+O in handleCustomShortcut (same pattern as Cmd+N, Cmd+W, etc.) to reliably show the Open Folder panel

Fixes #2010

Test plan

  • Press Cmd+O with terminal focused — should show "Open Folder" panel, not Documents
  • Press Cmd+O with browser panel focused — same behavior
  • Verify opening a folder works correctly after selection

🤖 Generated with Claude Code


Summary by cubic

Handle Cmd+O in handleCustomShortcut to always show the Open Folder panel, preventing NSDocumentController from opening the Documents folder when SwiftUI menu dispatch fails with terminal focus. Extracted showOpenFolderPanel() and use it from both the menu and shortcut; it seeds the panel with the current workspace’s directory via the shared main‑window resolver and opens the selection with openWorkspaceForExternalDirectory, ensuring it’s added to a workspace or a new window with that folder.

Written for commit 43d8469. Summary will update on new commits.

Summary by CodeRabbit

  • New Features

    • Cmd+O opens a folder-selection dialog to create or add workspaces from chosen directories.
    • Open-folder handling is centralized so the same dialog and workspace-opening flow is used app-wide.
  • Bug Fixes

    • Cmd+O now reliably consumes the shortcut to prevent unintended default system behavior.

Cmd+O for "Open Folder" was only handled in SwiftUI menu, which can
fail due to focus bugs when terminal is focused. This caused AppKit's
default NSDocumentController to open the Documents folder instead.
Now Cmd+O is intercepted in handleCustomShortcut like other shortcuts.

Fixes manaflow-ai#2010

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@vercel

vercel Bot commented Mar 24, 2026

Copy link
Copy Markdown

@anthhub is attempting to deploy a commit to the Manaflow Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds AppDelegate.showOpenFolderPanel() to present a directory-only NSOpenPanel and routes the Cmd+O / Open Folder command to it; selected directory is used to open or create a workspace in the preferred main window. cmuxApp now invokes AppDelegate for this action.

Changes

Cohort / File(s) Summary
AppDelegate — open-panel & shortcut
Sources/AppDelegate.swift
Added showOpenFolderPanel() which presents a directories-only NSOpenPanel (single selection, localized title/prompt). handleCustomShortcut(event:) now intercepts .openFolder (⌘O), consumes the event, and calls the new method; selected directory is passed to workspace-opening helpers (openWorkspaceForExternalDirectory / addWorkspaceInPreferredMainWindow / create main window fallback).
App entrypoint — command routing
Sources/cmuxApp.swift
Replaced the command's inline NSOpenPanel logic with a single call to AppDelegate.shared?.showOpenFolderPanel(), removing the local fallback workspace-creation path; command becomes a no-op if AppDelegate.shared is nil.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App as "cmuxApp / Menu"
    participant AppDelegate
    participant NSOpenPanel
    participant WorkspaceMgr as "WorkspaceManager"

    User->>App: Presses ⌘O (Open Folder)
    App->>AppDelegate: showOpenFolderPanel()
    AppDelegate->>NSOpenPanel: present directory-only picker
    NSOpenPanel-->>AppDelegate: selected URL / cancel
    alt URL selected
        AppDelegate->>WorkspaceMgr: openWorkspaceForExternalDirectory(path, debugSource)
        alt workspace opened
            WorkspaceMgr-->>AppDelegate: workspace (done)
        else workspace not opened
            AppDelegate->>WorkspaceMgr: addWorkspaceInPreferredMainWindow(workingDirectory)
            WorkspaceMgr-->>AppDelegate: created main window / workspace
        end
    else cancelled
        NSOpenPanel-->>AppDelegate: nil (no-op)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I hopped and nudged a key so bold,
Cmd+O now finds the place I hold.
From pane or root the picker starts,
A workspace springs from chosen parts.
Hooray—🥕📁

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: intercepting Cmd+O in handleCustomShortcut to prevent the Documents folder from opening, which is the primary objective.
Description check ✅ Passed The description covers the summary of changes and context. However, the testing section shows unchecked boxes without actual test results, and no demo video is provided.
Linked Issues check ✅ Passed The PR fully addresses issue #2010 by intercepting Cmd+O in handleCustomShortcut, preventing NSDocumentController from opening Documents folder, and seeding the panel with current workspace directory.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the Cmd+O behavior: extracting showOpenFolderPanel() and integrating it into both shortcut and menu paths. No unrelated modifications were introduced.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@greptile-apps

greptile-apps Bot commented Mar 24, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR intercepts Cmd+O in handleCustomShortcut so that AppKit's default NSDocumentController can no longer steal the event and open the Documents folder when SwiftUI's performKeyEquivalent dispatch fails due to focus bugs (typically when the terminal surface is focused).

Key changes:

  • A new showOpenFolderPanel() helper on AppDelegate encapsulates the NSOpenPanel setup and the addWorkspaceInPreferredMainWindow / openNewMainWindow routing logic.
  • handleCustomShortcut now matches .openFolder (Cmd+O) and calls showOpenFolderPanel(), exactly mirroring how Cmd+N, Cmd+W, and other shortcuts are handled.
  • The fix is surgical and follows the established pattern in the codebase.

Minor observation: The doc comment on showOpenFolderPanel() describes the function as "Extracted so it can be called from both the SwiftUI menu and handleCustomShortcut", but cmuxApp.swift was not updated — the SwiftUI menu still has its own identical inline implementation. The extraction is incomplete, leaving two divergent code paths for the same action.

Confidence Score: 5/5

  • Safe to merge — the fix is correct, targeted, and follows the established shortcut-interception pattern in the codebase.
  • The change is a minimal, well-understood pattern (identical to how Cmd+N and Cmd+W are handled). The new showOpenFolderPanel() faithfully replicates the existing SwiftUI menu behavior. The only remaining item is a non-blocking P2 docstring/duplication note that does not affect runtime correctness.
  • No files require special attention.

Important Files Changed

Filename Overview
Sources/AppDelegate.swift Adds showOpenFolderPanel() helper and intercepts Cmd+O in handleCustomShortcut; fix is correct and mirrors the existing Cmd+N/Cmd+W pattern. Minor: the SwiftUI menu in cmuxApp.swift retains its own inline copy of the same logic, making the doc comment ("Extracted so it can be called from both the SwiftUI menu and handleCustomShortcut") inaccurate.

Sequence Diagram

sequenceDiagram
    participant User
    participant EventMonitor
    participant handleCustomShortcut
    participant showOpenFolderPanel
    participant NSOpenPanel
    participant addWorkspaceInPreferredMainWindow
    participant openNewMainWindow

    User->>EventMonitor: Press Cmd+O (terminal focused)
    EventMonitor->>handleCustomShortcut: event
    handleCustomShortcut->>handleCustomShortcut: matchShortcut(.openFolder)?
    handleCustomShortcut->>showOpenFolderPanel: call (returns true, swallows event)
    Note over handleCustomShortcut: NSDocumentController never sees the event
    showOpenFolderPanel->>NSOpenPanel: runModal()
    NSOpenPanel-->>showOpenFolderPanel: .OK + url
    showOpenFolderPanel->>addWorkspaceInPreferredMainWindow: workingDirectory: url.path
    alt workspace added successfully
        addWorkspaceInPreferredMainWindow-->>showOpenFolderPanel: UUID (non-nil)
    else no main window available
        addWorkspaceInPreferredMainWindow-->>showOpenFolderPanel: nil
        showOpenFolderPanel->>openNewMainWindow: nil
    end
Loading

Reviews (1): Last reviewed commit: "Handle Cmd+O in handleCustomShortcut to ..." | Re-trigger Greptile

Comment thread Sources/AppDelegate.swift
Comment on lines +5366 to +5383
/// Shows the "Open Folder" panel and creates a workspace for the selected directory.
/// Extracted so it can be called from both the SwiftUI menu and `handleCustomShortcut`.
func showOpenFolderPanel() {
let panel = NSOpenPanel()
panel.canChooseFiles = false
panel.canChooseDirectories = true
panel.allowsMultipleSelection = false
panel.title = String(localized: "menu.file.openFolder.panelTitle", defaultValue: "Open Folder")
panel.prompt = String(localized: "menu.file.openFolder.panelPrompt", defaultValue: "Open")
if panel.runModal() == .OK, let url = panel.url {
if addWorkspaceInPreferredMainWindow(
workingDirectory: url.path,
debugSource: "shortcut.openFolder"
) == nil {
openNewMainWindow(nil)
}
}
}

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 Docstring overstates extraction scope; SwiftUI menu still has its own inline copy

The doc comment says "Extracted so it can be called from both the SwiftUI menu and handleCustomShortcut", but cmuxApp.swift (lines 589–608) was not updated to call showOpenFolderPanel(). The inline panel setup there is byte-for-byte identical to this new function, so the extraction is only half-done and the docstring is currently inaccurate.

This means there are now two divergent code paths for the same action:

  • AppDelegate.showOpenFolderPanel() → called from handleCustomShortcut (this PR)
  • Inline NSOpenPanel block in cmuxApp.swift → still called from the SwiftUI menu

A future change to panel titles, localization keys, or the addWorkspaceInPreferredMainWindow fallback would need to be applied in both places. Consider either:

  1. Updating cmuxApp.swift to call AppDelegate.shared?.showOpenFolderPanel() so there is one canonical implementation, or
  2. Updating the docstring to reflect that this function is only for the handleCustomShortcut path, e.g. "Shows the 'Open Folder' panel when the shortcut is triggered via handleCustomShortcut."

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.

Fixed in 43d8469. The docstring is now accurate (cmuxApp.swift already delegates to showOpenFolderPanel() since 553d35c), and the method now uses openWorkspaceForExternalDirectory for consistent behavior.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Sources/AppDelegate.swift`:
- Around line 5368-5375: In showOpenFolderPanel, NSOpenPanel is never seeded
with a starting directory so Cmd+O opens in AppKit’s default; before running
panel.runModal() set panel.directoryURL to the currently focused pane/workspace
directory (e.g. get the URL from your focused pane or workspace controller —
e.g. focusedPane.directoryURL or
WorkspaceController.shared.activeWorkingDirectory) so the open panel starts in
the active working directory; keep the fallback to nil if no active directory is
available.
- Around line 5375-5381: When
addWorkspaceInPreferredMainWindow(workingDirectory: url.path, debugSource:
"shortcut.openFolder") returns nil you currently call openNewMainWindow(nil)
which discards the selected url.path; instead preserve and open the chosen
folder by either calling openWorkspaceForExternalDirectory(url.path) or invoking
openNewMainWindow with initialWorkingDirectory: url.path (i.e. replace the
fallback openNewMainWindow(nil) with a call that passes url.path so the selected
folder is opened).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9f6ab779-25d1-4107-9d63-a705b6e18e4f

📥 Commits

Reviewing files that changed from the base of the PR and between 22c50a4 and 2d4ffcb.

📒 Files selected for processing (1)
  • Sources/AppDelegate.swift

Comment thread Sources/AppDelegate.swift
Comment thread Sources/AppDelegate.swift Outdated

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

1 issue found across 1 file

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="Sources/AppDelegate.swift">

<violation number="1" location="Sources/AppDelegate.swift:5380">
P2: Open Folder fallback drops the selected directory by opening a blank window when workspace routing returns nil.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread Sources/AppDelegate.swift Outdated
Address review feedback:
1. Pass selected directory URL to fallback window creation so the
   user's folder choice is not silently discarded
2. Replace inline NSOpenPanel code in cmuxApp.swift menu action
   with a call to AppDelegate.showOpenFolderPanel() to avoid
   future divergence between the two code paths

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
Sources/AppDelegate.swift (1)

5369-5375: ⚠️ Potential issue | 🟠 Major

Seed the Open Folder panel with the active directory before showing it.

Line 5375 runs panel.runModal() without setting panel.directoryURL, so Cmd+O can still start from AppKit’s default/last-used location instead of the focused workspace/pane directory.

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

In `@Sources/AppDelegate.swift` around lines 5369 - 5375, Set panel.directoryURL
to the currently focused workspace/pane directory before calling
panel.runModal(); specifically, before the line that checks panel.runModal() ==
.OK, compute the active directory from the focused workspace or pane (e.g., the
focused workspace/pane’s directory property or the frontmost editor’s file URL’s
parent) and assign it to panel.directoryURL so the NSOpenPanel opens seeded to
the active directory rather than AppKit’s default. Use the existing identifiers
panel, panel.directoryURL and panel.runModal() to locate where to add this
assignment.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@Sources/AppDelegate.swift`:
- Around line 5369-5375: Set panel.directoryURL to the currently focused
workspace/pane directory before calling panel.runModal(); specifically, before
the line that checks panel.runModal() == .OK, compute the active directory from
the focused workspace or pane (e.g., the focused workspace/pane’s directory
property or the frontmost editor’s file URL’s parent) and assign it to
panel.directoryURL so the NSOpenPanel opens seeded to the active directory
rather than AppKit’s default. Use the existing identifiers panel,
panel.directoryURL and panel.runModal() to locate where to add this assignment.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3d2c6747-fa3a-44a7-9c4d-6617d953110c

📥 Commits

Reviewing files that changed from the base of the PR and between 2d4ffcb and 553d35c.

📒 Files selected for processing (2)
  • Sources/AppDelegate.swift
  • Sources/cmuxApp.swift

Address review feedback: set panel.directoryURL to the focused
terminal's working directory so Open Folder starts in a contextually
relevant location instead of AppKit's default.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Sources/AppDelegate.swift`:
- Around line 5375-5385: The current File → Open Folder flow uses
NSApp.keyWindow directly for panel.directoryURL and then calls
addWorkspaceInPreferredMainWindow(...) which can leave shouldBringToFront false;
change it to reuse the shared main-window resolver and open path logic by: use
contextForMainWindow(...) (the same resolver used elsewhere) to set
panel.directoryURL instead of directly accessing NSApp.keyWindow, and after the
user selects a URL call openWorkspaceForExternalDirectory(workingDirectory:
url.path, debugSource: "shortcut.openFolder") (or the existing helper that
ensures shouldBringToFront is handled the same as other open paths) instead of
addWorkspaceInPreferredMainWindow(...); this keeps behavior consistent with
add/open flows (references: contextForMainWindow, panel.directoryURL,
addWorkspaceInPreferredMainWindow, openWorkspaceForExternalDirectory,
shouldBringToFront).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1598db84-c559-4e7e-8853-a6115c6c23f9

📥 Commits

Reviewing files that changed from the base of the PR and between 553d35c and d3538d4.

📒 Files selected for processing (1)
  • Sources/AppDelegate.swift

Comment thread Sources/AppDelegate.swift Outdated
… in showOpenFolderPanel

Address review feedback: use preferredMainWindowContextForWorkspaceCreation
for directory seeding (works when auxiliary windows are key) and
openWorkspaceForExternalDirectory for workspace creation (ensures
shouldBringToFront and consistent fallback behavior).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Sources/AppDelegate.swift`:
- Around line 5382-5386: The code currently marks folder picks as explicit
startup opens too early; only mark them after the user actually confirmed a URL.
Move the call to prepareForExplicitOpenIntentAtStartup() so it runs after you
verify panel.url (i.e., inside the if where panel.runModal() == .OK and let url
= panel.url) and before calling
openWorkspaceForExternalDirectory(workingDirectory:debugSource:); this ensures
openWorkspaceForExternalDirectory can still fall back to
createMainWindow(initialWorkingDirectory:) and that registerMainWindow will not
overwrite the confirmed explicit open with the saved session.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0394c31a-48a3-45fb-b420-bfd6f5a91412

📥 Commits

Reviewing files that changed from the base of the PR and between d3538d4 and 43d8469.

📒 Files selected for processing (1)
  • Sources/AppDelegate.swift

Comment thread Sources/AppDelegate.swift
Comment on lines +5382 to +5386
if panel.runModal() == .OK, let url = panel.url {
openWorkspaceForExternalDirectory(
workingDirectory: url.path,
debugSource: "shortcut.openFolder"
)

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

Mark confirmed folder picks as explicit startup opens.

If this runs before the initial session-restore attempt and there is no main window yet, openWorkspaceForExternalDirectory(...) can fall back to createMainWindow(initialWorkingDirectory:), and registerMainWindow(...) will still restore the saved session over the selected folder. Call prepareForExplicitOpenIntentAtStartup() only after panel.url is confirmed.

💡 Suggested fix
         if panel.runModal() == .OK, let url = panel.url {
+            prepareForExplicitOpenIntentAtStartup()
             openWorkspaceForExternalDirectory(
                 workingDirectory: url.path,
                 debugSource: "shortcut.openFolder"
             )
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Sources/AppDelegate.swift` around lines 5382 - 5386, The code currently marks
folder picks as explicit startup opens too early; only mark them after the user
actually confirmed a URL. Move the call to
prepareForExplicitOpenIntentAtStartup() so it runs after you verify panel.url
(i.e., inside the if where panel.runModal() == .OK and let url = panel.url) and
before calling openWorkspaceForExternalDirectory(workingDirectory:debugSource:);
this ensures openWorkspaceForExternalDirectory can still fall back to
createMainWindow(initialWorkingDirectory:) and that registerMainWindow will not
overwrite the confirmed explicit open with the saved session.

@lawrencecchen
lawrencecchen merged commit 5b82041 into manaflow-ai:main Mar 25, 2026
12 of 13 checks passed
@lawrencecchen

Copy link
Copy Markdown
Contributor

Thank you for the contribution!

bn-l pushed a commit to bn-l/cmux that referenced this pull request Apr 3, 2026
…manaflow-ai#2034)

* Handle Cmd+O in handleCustomShortcut to prevent Documents folder open

Cmd+O for "Open Folder" was only handled in SwiftUI menu, which can
fail due to focus bugs when terminal is focused. This caused AppKit's
default NSDocumentController to open the Documents folder instead.
Now Cmd+O is intercepted in handleCustomShortcut like other shortcuts.

Fixes manaflow-ai#2010

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fix fallback directory loss and deduplicate Open Folder logic

Address review feedback:
1. Pass selected directory URL to fallback window creation so the
   user's folder choice is not silently discarded
2. Replace inline NSOpenPanel code in cmuxApp.swift menu action
   with a call to AppDelegate.showOpenFolderPanel() to avoid
   future divergence between the two code paths

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Set NSOpenPanel directoryURL to current terminal working directory

Address review feedback: set panel.directoryURL to the focused
terminal's working directory so Open Folder starts in a contextually
relevant location instead of AppKit's default.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Use shared main-window resolver and openWorkspaceForExternalDirectory in showOpenFolderPanel

Address review feedback: use preferredMainWindowContextForWorkspaceCreation
for directory seeding (works when auxiliary windows are key) and
openWorkspaceForExternalDirectory for workspace creation (ensures
shouldBringToFront and consistent fallback behavior).

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Lawrence Chen <lawrencecchen@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

⌘O opens macOS Documents folder instead of intended action

2 participants