cmux/Sources/WorkspaceContentView.swift
Lawrence Chen 484b66c8ac
Fix terminal keys swallowed after opening browser (#45)
* Fix terminal keys (arrows, Ctrl+N/P) swallowed after opening browser

After a browser panel is shown, SwiftUI's internal focus system activates
and its _NSHostingView starts consuming arrow keys and other non-Command
key events via performKeyEquivalent, preventing them from reaching the
terminal's keyDown handler.

Fix: In the NSWindow performKeyEquivalent swizzle, when GhosttyNSView is
the first responder and the event has no Command modifier, route directly
to the terminal's performKeyEquivalent — bypassing SwiftUI's view hierarchy
walk entirely.

Also clear stale browserAddressBarFocusedPanelId when a terminal surface
has focus, preventing Cmd+N from being eaten by omnibar selection logic
after focus transitions away from a browser.

Adds DEBUG-only keyboard event ring buffer (KeyDebugLog) that dumps to
/tmp/cmux-key-debug.log for diagnosing future key routing issues.

* Fix split focus and Cmd+Shift+N swallowed after opening browser

Split focus: capture the source terminal's hostedView before bonsplit
mutates focusedPaneId, so focusPanel moves focus FROM the old pane
instead of from the new pane to itself. Also retry ensureFocus when the
new terminal's view has no window yet (matching the existing retry
pattern for isVisibleInUI).

Cmd+Shift+N: after WKWebView has been in the responder chain, SwiftUI's
internal focus system can intercept Command-key events in the content
view hierarchy (returning true) without firing the CommandGroup action
closure. Fix by dispatching Command-key events directly to NSApp.mainMenu
when the terminal is first responder, bypassing the broken SwiftUI path.
Also add Cmd+Shift+N to handleCustomShortcut so it's customizable and
doesn't depend on SwiftUI menu dispatch at all.

* Unified debug event log: merge key/mouse/focus into /tmp/cmux-debug.log

- Delete KeyDebugLog, MouseDebugLog, klog(), mlog() from AppDelegate
- Replace all klog/mlog calls with dlog() (provided by bonsplit)
- Remove debugLogCallback wiring from Workspace
- Add focus change logging: focus.panel, focus.firstResponder,
  split.created, focus.moveFocus
- Add import Bonsplit where needed for dlog access
- Fix stale drag state on cancelled tab drags (bonsplit submodule)

* Fix split focus stolen by re-entrant becomeFirstResponder during reparenting

During programmatic splits (Cmd+D / Cmd+Shift+D), SwiftUI reparents the old
terminal view, which fires becomeFirstResponder → onFocus → focusPanel for the
OLD panel, stealing focus from the newly created pane.

Add programmaticFocusTargetPanelId guard to suppress re-entrant focusPanel
calls for non-target panels during split creation.

Also document the unified debug event log in CLAUDE.md.

* Clear stale title/favicon when browser navigation fails

When a page fails to load (e.g. connection refused), the tab was still
showing the previous page's title and favicon. Now didFailProvisionalNavigation
resets pageTitle to the failed URL and clears faviconPNGData.

* Fix Cmd+N swallowed by browser omnibar and improve split focus suppression

- Only Ctrl+N/P trigger omnibar navigation, not Cmd+N/P (Cmd+N should
  always create new workspace regardless of address bar focus)
- Move split focus suppression from workspace-level guard to source:
  suppress becomeFirstResponder side-effects (onFocus + ghostty_surface_set_focus)
  directly on the old GhosttyNSView during reparenting, preventing both
  model-level and libghostty-level focus divergence
- Remove programmaticFocusTargetPanelId from Workspace.focusPanel

* Fix omnibar hang, WebView white flash, drag-over-browser, and idle CPU spin

- Omnibar: first click selects all without entering NSTextView tracking loop;
  subsequent clicks have 3s synthetic mouseUp safety net to prevent hang
- WebView: set underPageBackgroundColor to match window so new browsers don't
  flash white before content loads
- Drag/drop: register custom UTType (com.splittabbar.tabtransfer) in Info.plist
  so WKWebView doesn't intercept tab drags; override registerForDraggedTypes
  on CmuxWebView as belt-and-suspenders
- CPU: fix infinite makeFirstResponder loop in controlTextDidEndEditing by
  checking both the text field and its field editor (the actual first responder)
2026-02-17 03:21:08 -08:00

208 lines
7.5 KiB
Swift

import SwiftUI
import Foundation
import Bonsplit
/// View that renders a Workspace's content using BonsplitView
struct WorkspaceContentView: View {
@ObservedObject var workspace: Workspace
let isTabActive: Bool
@State private var config = GhosttyConfig.load()
@EnvironmentObject var notificationStore: TerminalNotificationStore
var body: some View {
let appearance = PanelAppearance.fromConfig(config)
let isSplit = workspace.bonsplitController.allPaneIds.count > 1 ||
workspace.panels.count > 1
BonsplitView(controller: workspace.bonsplitController) { tab, paneId in
// Content for each tab in bonsplit
let _ = Self.debugPanelLookup(tab: tab, workspace: workspace)
if let panel = workspace.panel(for: tab.id) {
let isFocused = isTabActive && workspace.focusedPanelId == panel.id
let isSelectedInPane = workspace.bonsplitController.selectedTab(inPane: paneId)?.id == tab.id
let isVisibleInUI = isTabActive && isSelectedInPane
PanelContentView(
panel: panel,
isFocused: isFocused,
isSelectedInPane: isSelectedInPane,
isVisibleInUI: isVisibleInUI,
isSplit: isSplit,
appearance: appearance,
notificationStore: notificationStore,
onFocus: {
// Keep bonsplit focus in sync with the AppKit first responder for the
// active workspace. This prevents divergence between the blue focused-tab
// indicator and where keyboard input/flash-focus actually lands.
guard isTabActive else { return }
guard workspace.panels[panel.id] != nil else { return }
workspace.focusPanel(panel.id)
},
onRequestPanelFocus: {
guard isTabActive else { return }
guard workspace.panels[panel.id] != nil else { return }
workspace.focusPanel(panel.id)
},
onTriggerFlash: { workspace.triggerDebugFlash(panelId: panel.id) }
)
.onTapGesture {
workspace.bonsplitController.focusPane(paneId)
}
} else {
// Fallback for tabs without panels (shouldn't happen normally)
EmptyPanelView(workspace: workspace, paneId: paneId)
}
} emptyPane: { paneId in
// Empty pane content
EmptyPanelView(workspace: workspace, paneId: paneId)
.onTapGesture {
workspace.bonsplitController.focusPane(paneId)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear {
syncBonsplitNotificationBadges()
}
.onChange(of: notificationStore.notifications) { _, _ in
syncBonsplitNotificationBadges()
}
.onReceive(NotificationCenter.default.publisher(for: .ghosttyConfigDidReload)) { _ in
config = GhosttyConfig.load()
}
}
private func syncBonsplitNotificationBadges() {
let unreadPanelIds: Set<UUID> = Set(
notificationStore.notifications
.filter { $0.tabId == workspace.id && !$0.isRead }
.compactMap { $0.surfaceId }
)
for paneId in workspace.bonsplitController.allPaneIds {
for tab in workspace.bonsplitController.tabs(inPane: paneId) {
let panelId = workspace.panelIdFromSurfaceId(tab.id)
let shouldShow = panelId.map { unreadPanelIds.contains($0) } ?? false
if tab.showsNotificationBadge != shouldShow {
workspace.bonsplitController.updateTab(tab.id, showsNotificationBadge: shouldShow)
}
}
}
}
}
extension WorkspaceContentView {
#if DEBUG
static func debugPanelLookup(tab: Bonsplit.Tab, workspace: Workspace) {
let found = workspace.panel(for: tab.id) != nil
if !found {
let ts = ISO8601DateFormatter().string(from: Date())
let line = "[\(ts)] PANEL NOT FOUND for tabId=\(tab.id) ws=\(workspace.id) panelCount=\(workspace.panels.count)\n"
let logPath = "/tmp/cmux-panel-debug.log"
if let handle = FileHandle(forWritingAtPath: logPath) {
handle.seekToEndOfFile()
handle.write(line.data(using: .utf8)!)
handle.closeFile()
} else {
FileManager.default.createFile(atPath: logPath, contents: line.data(using: .utf8))
}
}
}
#else
static func debugPanelLookup(tab: Bonsplit.Tab, workspace: Workspace) {
_ = tab
_ = workspace
}
#endif
}
/// View shown for empty panes
struct EmptyPanelView: View {
@ObservedObject var workspace: Workspace
let paneId: PaneID
private struct ShortcutHint: View {
let text: String
var body: some View {
Text(text)
.font(.system(size: 11, weight: .semibold, design: .rounded))
.foregroundStyle(.white.opacity(0.9))
.padding(.horizontal, 8)
.padding(.vertical, 3)
.background(.white.opacity(0.18), in: Capsule())
}
}
private func focusPane() {
workspace.bonsplitController.focusPane(paneId)
}
private func createTerminal() {
#if DEBUG
dlog("emptyPane.newTerminal pane=\(paneId.id.uuidString.prefix(5))")
#endif
focusPane()
_ = workspace.newTerminalSurface(inPane: paneId)
}
private func createBrowser() {
#if DEBUG
dlog("emptyPane.newBrowser pane=\(paneId.id.uuidString.prefix(5))")
#endif
focusPane()
_ = workspace.newBrowserSurface(inPane: paneId)
}
var body: some View {
VStack(spacing: 16) {
Image(systemName: "terminal.fill")
.font(.system(size: 48))
.foregroundStyle(.tertiary)
Text("Empty Panel")
.font(.headline)
.foregroundStyle(.secondary)
HStack(spacing: 12) {
Button {
createTerminal()
} label: {
HStack(spacing: 10) {
Label("Terminal", systemImage: "terminal.fill")
ShortcutHint(text: "⌘T")
}
}
.buttonStyle(.borderedProminent)
.keyboardShortcut("t", modifiers: [.command])
Button {
createBrowser()
} label: {
HStack(spacing: 10) {
Label("Browser", systemImage: "globe")
ShortcutHint(text: "⌘⇧L")
}
}
.buttonStyle(.borderedProminent)
.keyboardShortcut("l", modifiers: [.command, .shift])
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(nsColor: .windowBackgroundColor))
#if DEBUG
.onAppear {
DebugUIEventCounters.emptyPanelAppearCount += 1
}
#endif
}
}
#if DEBUG
@MainActor
enum DebugUIEventCounters {
static var emptyPanelAppearCount: Int = 0
static func resetEmptyPanelAppearCount() {
emptyPanelAppearCount = 0
}
}
#endif